Files
Library/tests/standalone/Storage/Storage.cpp
T

918 lines
32 KiB
C++

#include <Void/Async/Executor.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Core/Uuid.hpp>
#include <Void/Storage/Storage.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Time/Clock.hpp>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <limits>
#include <map>
#include <random>
#include <stop_token>
#include <string>
#include <thread>
#include <unistd.h>
#include <vector>
namespace
{
using namespace Void::Storage;
struct TempStorageDir {
std::filesystem::path path;
TempStorageDir()
{
static std::atomic<std::uint64_t> seq{0};
const auto id = seq.fetch_add(1, std::memory_order_relaxed);
path = std::filesystem::temp_directory_path() /
("void-storage-test-" + std::to_string(::getpid()) + "-" + std::to_string(id));
std::error_code ec;
std::filesystem::remove_all(path, ec);
std::filesystem::create_directories(path, ec);
}
~TempStorageDir()
{
std::error_code ec;
std::filesystem::remove_all(path, ec);
}
};
void write_raw_bytes(const std::filesystem::path& p, ByteView data)
{
auto port = make_posix_file_port();
(void)port->unlink_file(p);
auto f = port->open_file(p, FileOpenMode::CreateNew);
Void::Testing::require(f.has_value());
Void::Testing::require((*f)->append_all(data).has_value());
Void::Testing::require((*f)->sync().has_value());
}
Void::Coro::Task<void> run_async_stop_before_append(
AsyncStorageAdapter& adapter,
std::expected<CommitReceipt, WriteFailure>* out,
bool* done)
{
std::stop_source ss;
ss.request_stop();
Batch b;
b.put("k_cancelled", "never_written");
Void::Async::OperationOptions op;
op.stop = ss.get_token();
*out = co_await adapter.write_async(std::move(b), Durability::Sync, op);
*done = true;
}
Void::Coro::Task<void> run_async_write_tracked(
AsyncStorageAdapter& adapter,
std::string key,
std::string val,
std::stop_token st,
std::expected<CommitReceipt, WriteFailure>* out,
std::atomic<int>* deliveries,
bool* done)
{
Batch b;
b.put(key, val);
Void::Async::OperationOptions op;
op.stop = st;
*out = co_await adapter.write_async(std::move(b), Durability::Sync, op);
deliveries->fetch_add(1, std::memory_order_acq_rel);
*done = true;
}
Void::Testing::Test storage_crc32c_golden_and_v1_format_codecs()
{
// Golden CRC32C check (Cyphal / Castagnoli)
Void::Testing::expect_eq(crc32c(std::string_view{"123456789"}), 0xE3069283u);
Void::Testing::expect_eq(crc32c(std::string_view{""}), 0u);
// Incremental chunked update must match single-pass CRC32C
std::uint32_t st = crc32c_init();
st = crc32c_update(st, std::string_view{"1234"});
st = crc32c_update(st, std::string_view{"56789"});
Void::Testing::expect_eq(crc32c_finalize(st), 0xE3069283u);
// Limits validation rejects zero fields
Limits bad_lim;
bad_lim.max_key_bytes = 0;
Void::Testing::expect(!validate_limits(bad_lim).has_value());
// WAL segment header encode/decode + corruption & unknown major/flags rejection
auto uuid = Void::Uuid::try_v4();
Void::Testing::require(uuid.has_value());
WalSegmentHeader wsh;
wsh.database_uuid = *uuid;
wsh.segment_id = 7;
wsh.previous_segment_id = 6;
wsh.first_candidate_sequence = 42;
auto raw_seg = encode_wal_segment_header(wsh);
Void::Testing::require(raw_seg.has_value());
Void::Testing::expect_eq(raw_seg->size(), static_cast<std::size_t>(kWalSegmentHeaderSize));
auto dec_seg = decode_wal_segment_header(*raw_seg);
Void::Testing::require(dec_seg.has_value());
Void::Testing::expect_eq(dec_seg->segment_id, static_cast<std::uint64_t>(7));
// Flip a byte in segment header -> corrupt
auto flipped_seg = *raw_seg;
flipped_seg[20] ^= std::byte{0x01};
auto bad_seg = decode_wal_segment_header(flipped_seg);
Void::Testing::expect(!bad_seg.has_value());
Void::Testing::expect(bad_seg.error().kind() == Void::Result::ErrorKind::corrupt);
// WAL record header checks header CRC BEFORE trusting huge payload_length!
auto mp = encode_wal_mutation_payload(false, to_byte_view("k"), to_byte_view("v"));
Void::Testing::require(mp.has_value());
auto frame = encode_wal_record_frame(WalRecordType::Put, 5, 1, *mp);
Void::Testing::require(frame.has_value());
auto rh = decode_wal_record_header(
std::span<const std::byte>{frame->data(), kWalRecordHeaderSize}, 65536);
Void::Testing::require(rh.has_value());
Void::Testing::require(verify_wal_record_frame(*rh, *frame).has_value());
// Flip header payload_len without updating header CRC -> rejected before allocation
auto huge_len_hdr = *frame;
huge_len_hdr[28] = std::byte{0xFF};
huge_len_hdr[29] = std::byte{0xFF};
huge_len_hdr[30] = std::byte{0xFF};
huge_len_hdr[31] = std::byte{0x7F};
auto bad_rh = decode_wal_record_header(
std::span<const std::byte>{huge_len_hdr.data(), kWalRecordHeaderSize}, 1024);
Void::Testing::expect(!bad_rh.has_value());
// Erase payload with non-zero value fails decode
auto bad_erase = encode_wal_mutation_payload(true, to_byte_view("k"), to_byte_view("nonempty"));
Void::Testing::expect(!bad_erase.has_value());
}
Void::Testing::Test storage_model_atomic_batches_preconditions_snapshots_and_scans()
{
TempStorageDir dir;
OpenOptions opts;
opts.directory = dir.path;
opts.limits.max_snapshots = 8;
opts.limits.max_cursors = 8;
auto eng_r = Engine::open(opts);
Void::Testing::require(eng_r.has_value());
auto& eng = *eng_r;
// Reference model: key -> (value, version_seq)
struct RefVal {
OwnedBytes val;
Sequence seq;
};
std::map<OwnedBytes, RefVal, ByteLess> ref;
// Test empty key and empty value distinct from absence, plus binary 0x00/0xFF keys.
const OwnedBytes k_empty{};
const OwnedBytes k_nul{std::byte{0x00}, std::byte{0x41}, std::byte{0x00}};
const OwnedBytes k_ff{std::byte{0xFF}, std::byte{0xFF}};
{
Batch b;
b.require_absent(k_empty)
.put(k_empty, OwnedBytes{})
.put(k_nul, to_byte_view("zero"))
.put(k_ff, to_byte_view("ffval"));
auto r = eng.write(std::move(b), Durability::Sync);
Void::Testing::require(r.has_value());
ref[k_empty] = RefVal{{}, r->sequence};
ref[k_nul] = RefVal{to_owned_bytes("zero"), r->sequence};
ref[k_ff] = RefVal{to_owned_bytes("ffval"), r->sequence};
}
// Duplicate key & duplicate precondition rejected cleanly as NotCommitted
{
Batch dup_mut;
dup_mut.put("a", "1").put("a", "2");
auto r = eng.write(std::move(dup_mut), Durability::Sync);
Void::Testing::expect(!r.has_value());
Void::Testing::expect(r.error().outcome == Outcome::NotCommitted);
Batch dup_cond;
dup_cond.require_absent("a").require_value("a", "1").put("b", "2");
auto r2 = eng.write(std::move(dup_cond), Durability::Sync);
Void::Testing::expect(!r2.has_value());
Void::Testing::expect(r2.error().outcome == Outcome::NotCommitted);
}
// Delete + reinsert ABA version check: old sequence must fail after delete!
Sequence seq_a1 = 0;
{
Batch b;
b.put("aba", "v1");
auto r = eng.write(std::move(b), Durability::Sync);
Void::Testing::require(r.has_value());
seq_a1 = r->sequence;
}
{
Batch b;
b.require_version("aba", seq_a1).erase("aba");
Void::Testing::require(eng.write(std::move(b), Durability::Sync).has_value());
}
{
// Obsolete version check after delete MUST fail!
Batch b;
b.require_version("aba", seq_a1).put("aba", "should_fail");
auto r = eng.write(std::move(b), Durability::Sync);
Void::Testing::expect(!r.has_value());
Void::Testing::expect(r.error().outcome == Outcome::NotCommitted);
Void::Testing::expect(r.error().cause.code == StorageErrorCode::conflict);
}
// Take Snapshot before randomized model mutations!
auto early_snap = eng.snapshot();
Void::Testing::require(early_snap.has_value());
{
auto g = eng.get(*early_snap, k_empty);
Void::Testing::require(g.has_value());
Void::Testing::expect(g->bytes.empty());
}
// Deterministic RNG model check comparing EVERY snapshot against ordered std::map!
std::mt19937 rng{20261126u};
{
auto s0 = eng.snapshot();
Void::Testing::require(s0.has_value());
auto cur0 = eng.scan(std::move(*s0), ScanBounds::all());
Void::Testing::require(cur0.has_value());
for (;;) {
auto pg = cur0->next_page();
Void::Testing::require(pg.has_value());
for (const auto& e : pg->entries) {
ref[e.key] = RefVal{e.value, e.version};
}
if (!pg->has_more) break;
}
}
for (int step = 0; step < 60; ++step) {
const auto kb = to_owned_bytes("m/" + std::to_string(rng() % 7));
Batch b;
const bool do_erase = (rng() % 3) == 0;
const std::string val_str = "val_" + std::to_string(step);
if ((rng() % 4) == 0) {
if (auto it = ref.find(kb); it != ref.end()) {
b.require_value(kb, it->second.val);
} else {
b.require_absent(kb);
}
}
if (do_erase) {
b.erase(kb);
} else {
b.put(ByteView{kb}, to_byte_view(val_str));
}
auto wr = eng.write(std::move(b), (step % 2 == 0) ? Durability::Sync : Durability::Buffered);
Void::Testing::require(wr.has_value());
if (do_erase) {
ref.erase(kb);
} else {
ref[kb] = RefVal{to_owned_bytes(val_str), wr->sequence};
}
auto s = eng.snapshot();
Void::Testing::require(s.has_value());
auto cur = eng.scan(std::move(*s), ScanBounds::all());
Void::Testing::require(cur.has_value());
std::map<OwnedBytes, RefVal, ByteLess> got;
for (;;) {
auto pg = cur->next_page();
Void::Testing::require(pg.has_value());
for (const auto& e : pg->entries) {
got[e.key] = RefVal{e.value, e.version};
}
if (!pg->has_more) break;
}
Void::Testing::expect_eq(got.size(), ref.size());
for (const auto& [k, rv] : ref) {
Void::Testing::require(got.contains(k));
Void::Testing::expect(got[k].val == rv.val);
Void::Testing::expect_eq(got[k].seq, rv.seq);
}
}
// Prefix scan including 0xFF prefix and close()-while-snapshot-live -> Busy!
{
auto cur = eng.scan(std::move(*early_snap), ScanBounds::prefix(k_ff));
Void::Testing::require(cur.has_value());
auto busy = eng.close();
Void::Testing::expect(!busy.has_value());
Void::Testing::expect(busy.error().code().value ==
static_cast<std::int32_t>(StorageErrorCode::busy));
auto pg = cur->next_page();
Void::Testing::require(pg.has_value());
Void::Testing::expect_eq(pg->entries.size(), static_cast<std::size_t>(1));
Void::Testing::expect(pg->entries[0].key == k_ff);
cur->close();
}
// PageTooSmall reported when entry exceeds ScanBounds::page_bytes
{
Batch big_b;
const std::string big_v(2048, 'B');
big_b.put("big_key", big_v);
Void::Testing::require(eng.write(std::move(big_b), Durability::Sync).has_value());
auto s = eng.snapshot();
Void::Testing::require(s.has_value());
ScanBounds sb = ScanBounds::prefix("big_key");
sb.page_bytes = 512;
auto cur = eng.scan(std::move(*s), sb);
Void::Testing::require(cur.has_value());
auto pg = cur->next_page();
Void::Testing::expect(!pg.has_value());
Void::Testing::expect(pg.error().code().value ==
static_cast<std::int32_t>(StorageErrorCode::page_too_small));
}
// Sequence counter exhaustion returns sequence_exhausted without wrapping
{
TempStorageDir max_dir;
OpenOptions mopts;
mopts.directory = max_dir.path;
mopts.initial_sequence = std::numeric_limits<Sequence>::max();
auto meng = Engine::open(mopts);
Void::Testing::require(meng.has_value());
Batch b;
b.put("x", "1");
auto wr = meng->write(std::move(b), Durability::Sync);
Void::Testing::expect(!wr.has_value());
Void::Testing::expect(wr.error().outcome == Outcome::NotCommitted);
Void::Testing::expect(wr.error().cause.code == StorageErrorCode::sequence_exhausted);
}
Void::Testing::require(eng.close().has_value());
}
Void::Testing::Test storage_wal_recovery_byte_truncation_corruption_and_rotation()
{
// 1. Orphan manifest without CURRENT -> incomplete_init (never adopts orphan!)
{
TempStorageDir dir;
auto uuid = Void::Uuid::try_v4();
Void::Testing::require(uuid.has_value());
ManifestData m;
m.database_uuid = *uuid;
m.generation = 5;
m.wal_segments = {1};
auto enc = encode_manifest(m, 65536);
Void::Testing::require(enc.has_value());
write_raw_bytes(dir.path / make_manifest_filename(5), *enc);
OpenOptions opts;
opts.directory = dir.path;
auto r = Engine::open(opts);
Void::Testing::expect(!r.has_value());
Void::Testing::expect(r.error().code().value ==
static_cast<std::int32_t>(StorageErrorCode::incomplete_init));
}
// 2. Truncate EVERY byte offset across a multi-batch WAL & test reopen recovery!
TempStorageDir base_dir;
OpenOptions base_opts;
base_opts.directory = base_dir.path;
base_opts.limits.max_batch_encoded_bytes = 4096;
base_opts.limits.wal_segment_target_bytes = 4096; // force small target for rotation later
std::vector<Sequence> expected_seqs;
{
auto eng = Engine::open(base_opts);
Void::Testing::require(eng.has_value());
for (int i = 1; i <= 2; ++i) {
Batch b;
b.put(std::string(1, static_cast<char>('a' + i - 1)), std::to_string(i));
auto wr = eng->write(std::move(b), Durability::Sync);
Void::Testing::require(wr.has_value());
expected_seqs.push_back(wr->sequence);
}
Void::Testing::require(eng->close().has_value());
}
const auto orig_wal_path = base_dir.path / make_wal_filename(1);
OwnedBytes orig_wal_bytes;
{
auto port = make_posix_file_port();
auto sz = port->file_size(orig_wal_path);
Void::Testing::require(sz.has_value());
orig_wal_bytes.resize(*sz);
auto f = port->open_file(orig_wal_path, FileOpenMode::ReadOnly);
Void::Testing::require(f.has_value());
Void::Testing::require((*f)->pread_exact(0, orig_wal_bytes).has_value());
}
// Sweep EVERY truncation length from kWalSegmentHeaderSize up to orig_wal_bytes.size()
for (std::size_t cut = kWalSegmentHeaderSize; cut <= orig_wal_bytes.size(); ++cut) {
TempStorageDir copy_dir;
std::filesystem::copy(
base_dir.path, copy_dir.path,
std::filesystem::copy_options::recursive |
std::filesystem::copy_options::overwrite_existing);
(void)std::filesystem::remove(copy_dir.path / "LOCK");
{
auto port = make_posix_file_port();
auto wf = port->open_file(
copy_dir.path / make_wal_filename(1), FileOpenMode::ReadWriteExisting);
Void::Testing::require(wf.has_value());
Void::Testing::require((*wf)->truncate(cut).has_value());
Void::Testing::require((*wf)->sync().has_value());
}
OpenOptions ropts;
ropts.directory = copy_dir.path;
ropts.limits = base_opts.limits;
auto eng = Engine::open(ropts);
Void::Testing::require(eng.has_value());
const auto st1 = eng->stats();
Void::Testing::expect(st1.committed_sequence <= 3);
Void::Testing::require(eng->close().has_value());
// Idempotent second recovery!
auto eng2 = Engine::open(ropts);
Void::Testing::require(eng2.has_value());
Void::Testing::expect_eq(eng2->stats().committed_sequence, st1.committed_sequence);
Void::Testing::expect_eq(eng2->stats().recovery_truncated_bytes, static_cast<std::uint64_t>(0));
Void::Testing::require(eng2->close().has_value());
}
// 3. Complete record with single-bit corruption (including final byte!) MUST fail closed (Corrupt)
{
TempStorageDir bad_dir;
std::filesystem::copy(base_dir.path, bad_dir.path,
std::filesystem::copy_options::recursive |
std::filesystem::copy_options::overwrite_existing);
(void)std::filesystem::remove(bad_dir.path / "LOCK");
{
auto port = make_posix_file_port();
auto wf = port->open_file(
bad_dir.path / make_wal_filename(1), FileOpenMode::ReadWriteExisting);
Void::Testing::require(wf.has_value());
auto b = orig_wal_bytes;
b[b.size() - 12] ^= std::byte{0x04}; // flip inside final complete COMMIT trailer/payload
Void::Testing::require((*wf)->pwrite_all(0, b).has_value());
Void::Testing::require((*wf)->sync().has_value());
}
OpenOptions ropts = base_opts;
ropts.directory = bad_dir.path;
auto r = Engine::open(ropts);
Void::Testing::expect(!r.has_value());
Void::Testing::expect(r.error().kind() == Void::Result::ErrorKind::corrupt);
}
// 4. WAL segment rotation across multiple small batches preserves full recovery
{
TempStorageDir rot_dir;
OpenOptions ropts;
ropts.directory = rot_dir.path;
ropts.limits.max_batch_encoded_bytes = 256;
ropts.limits.wal_segment_target_bytes = 384; // rotate every ~2 batches!
auto eng = Engine::open(ropts);
Void::Testing::require(eng.has_value());
for (int i = 0; i < 10; ++i) {
Batch b;
b.put("r/" + std::to_string(i), std::string(48, static_cast<char>('A' + i)));
Void::Testing::require(eng->write(std::move(b), Durability::Sync).has_value());
}
Void::Testing::require(eng->close().has_value());
auto reopened = Engine::open(ropts);
Void::Testing::require(reopened.has_value());
Void::Testing::expect_eq(reopened->stats().committed_sequence, static_cast<Sequence>(10));
auto s = reopened->snapshot();
Void::Testing::require(s.has_value());
Void::Testing::expect_eq(
reopened->get(*s, "r/9")->as_string_view(),
std::string_view{std::string(48, 'J')});
s->reset();
Void::Testing::require(reopened->close().has_value());
}
}
Void::Testing::Test storage_fault_injected_crashes_sync_unknown_checkpoint_and_compaction()
{
// 1. Initial CURRENT creation failure -> directory fails incomplete_init on reopen
{
TempStorageDir dir;
auto fp = std::make_shared<FaultInjectingFilePort>();
fp->add_rule(FaultRule{
.op = FaultOp::Rename,
.path_contains = "CURRENT",
.hit_index = 1,
.error_code = StorageErrorCode::io_error});
OpenOptions opts;
opts.directory = dir.path;
opts.file_port = fp;
Void::Testing::expect(!Engine::open(opts).has_value());
OpenOptions clean_opts;
clean_opts.directory = dir.path;
auto reopen = Engine::open(clean_opts);
Void::Testing::expect(!reopen.has_value());
Void::Testing::expect(reopen.error().code().value ==
static_cast<std::int32_t>(StorageErrorCode::incomplete_init));
}
// 2. Sync failure AFTER append -> Outcome::Unknown + RecoveryRequired,
// existing snapshots keep reading last published state, reopen recovers persisted batch!
{
TempStorageDir dir;
auto fp = std::make_shared<FaultInjectingFilePort>();
OpenOptions opts;
opts.directory = dir.path;
opts.file_port = fp;
auto eng = Engine::open(opts);
Void::Testing::require(eng.has_value());
{
Batch b1;
b1.put("k", "v1");
Void::Testing::require(eng->write(std::move(b1), Durability::Sync).has_value());
}
auto pre_snap = eng->snapshot();
Void::Testing::require(pre_snap.has_value());
// Inject fsync failure on next WAL sync!
fp->add_rule(FaultRule{
.op = FaultOp::SyncFile,
.path_contains = "WAL-",
.hit_index = 1,
.error_code = StorageErrorCode::io_error});
{
Batch b2;
b2.put("k", "v2");
auto wr = eng->write(std::move(b2), Durability::Sync);
Void::Testing::expect(!wr.has_value());
Void::Testing::expect(wr.error().outcome == Outcome::Unknown);
}
Void::Testing::expect(eng->state() == EngineState::RecoveryRequired);
// Existing snapshot still sees pre-failure published v1!
Void::Testing::expect_eq(eng->get(*pre_snap, "k")->as_string_view(), std::string_view{"v1"});
// Further writes rejected cleanly
{
Batch b3;
b3.put("k", "v3");
auto wr3 = eng->write(std::move(b3), Durability::Sync);
Void::Testing::expect(!wr3.has_value());
Void::Testing::expect(wr3.error().outcome == Outcome::NotCommitted);
}
pre_snap->reset();
(void)eng->close();
// Clean reopen recovers v2 because COMMIT was appended before fsync error!
OpenOptions clean_opts;
clean_opts.directory = dir.path;
auto eng2 = Engine::open(clean_opts);
Void::Testing::require(eng2.has_value());
auto s2 = eng2->snapshot();
Void::Testing::require(s2.has_value());
Void::Testing::expect_eq(eng2->get(*s2, "k")->as_string_view(), std::string_view{"v2"});
s2->reset();
Void::Testing::require(eng2->close().has_value());
}
// 3. Checkpoint failure before CURRENT rename leaves previous generation intact,
// and slow Snapshot pins keep obsolete compacted tables alive until released!
{
TempStorageDir dir;
auto fp = std::make_shared<FaultInjectingFilePort>();
OpenOptions opts;
opts.directory = dir.path;
opts.file_port = fp;
auto eng = Engine::open(opts);
Void::Testing::require(eng.has_value());
// Create key k across 2 checkpoints so we have 2 immutable tables + a pinned snapshot!
{
Batch b;
b.put("alpha", "gen1");
b.put("beta", "keep");
Void::Testing::require(eng->write(std::move(b), Durability::Sync).has_value());
}
Void::Testing::require(eng->checkpoint().has_value());
auto snap_v1 = eng->snapshot();
Void::Testing::require(snap_v1.has_value());
{
Batch b;
b.put("alpha", "gen2");
b.erase("beta");
Void::Testing::require(eng->write(std::move(b), Durability::Sync).has_value());
}
Void::Testing::require(eng->checkpoint().has_value());
// Inject checkpoint rename failure on CURRENT -> old generation remains authoritative on reopen!
{
Batch b;
b.put("alpha", "gen3_in_wal");
Void::Testing::require(eng->write(std::move(b), Durability::Sync).has_value());
}
fp->add_rule(FaultRule{
.op = FaultOp::Rename,
.path_contains = "CURRENT",
.hit_index = 1,
.error_code = StorageErrorCode::io_error});
Void::Testing::expect(!eng->checkpoint().has_value());
Void::Testing::expect(eng->state() == EngineState::RecoveryRequired);
snap_v1->reset();
(void)eng->close();
// Clean reopen still recovers gen3 cleanly!
OpenOptions clean_opts;
clean_opts.directory = dir.path;
auto eng2 = Engine::open(clean_opts);
Void::Testing::require(eng2.has_value());
auto s_latest = eng2->snapshot();
Void::Testing::require(s_latest.has_value());
Void::Testing::expect_eq(eng2->get(*s_latest, "alpha")->as_string_view(),
std::string_view{"gen3_in_wal"});
Void::Testing::require(eng2->checkpoint().has_value());
// Now pin s_latest and trigger compaction across multiple tables!
Void::Testing::require(eng2->stats().active_table_count >= 2);
Void::Testing::require(eng2->compact().has_value());
Void::Testing::expect(eng2->stats().obsolete_pinned_bytes > 0);
Void::Testing::expect_eq(eng2->get(*s_latest, "alpha")->as_string_view(),
std::string_view{"gen3_in_wal"});
// Dropping s_latest releases the pin and lets obsolete files be reclaimed!
s_latest->reset();
Void::Testing::expect_eq(eng2->stats().obsolete_pinned_bytes, static_cast<std::uint64_t>(0));
Void::Testing::require(eng2->close().has_value());
}
}
Void::Coro::Task<void> drive_stop_before_append_test(
AsyncStorageAdapter& adapter,
std::expected<CommitReceipt, WriteFailure>* out,
bool* done)
{
co_await run_async_stop_before_append(adapter, out, done);
}
Void::Coro::Task<void> drive_tracked_write_test(
AsyncStorageAdapter& adapter,
std::string key,
std::string val,
std::stop_token st,
std::expected<CommitReceipt, WriteFailure>* out,
std::atomic<int>* deliveries,
bool* done)
{
co_await run_async_write_tracked(
adapter, std::move(key), std::move(val), st, out, deliveries, done);
}
Void::Testing::Test storage_tools_verify_backup_restore_salvage_and_async_stop_races()
{
TempStorageDir dir;
TempStorageDir backup_dir;
TempStorageDir restore_dir;
TempStorageDir salvage_dir;
// 1. Live export_backup, offline verify_directory, block-level corruption detection, restore & salvage
{
OpenOptions opts;
opts.directory = dir.path;
auto eng = Engine::open(opts);
Void::Testing::require(eng.has_value());
{
Batch b;
b.put("t1", std::string(1024, 'X'));
b.put("t2", std::string(1024, 'Y'));
Void::Testing::require(eng->write(std::move(b), Durability::Sync).has_value());
}
Void::Testing::require(eng->checkpoint().has_value());
{
Batch b;
b.put("w1", "after_ckpt");
Void::Testing::require(eng->write(std::move(b), Durability::Sync).has_value());
}
// Backup while engine remains open
Void::Testing::require(eng->export_backup(backup_dir.path).has_value());
Void::Testing::require(eng->close().has_value());
// Offline verify_directory passes on backup
auto vr = verify_directory(backup_dir.path);
Void::Testing::require(vr.has_value());
Void::Testing::expect(vr->tables_verified >= 1);
Void::Testing::expect(vr->blocks_verified >= 1);
// Restore backup into restore_dir and verify data
Void::Testing::require(restore_backup(backup_dir.path, restore_dir.path).has_value());
OpenOptions r_opts;
r_opts.directory = restore_dir.path;
auto reng = Engine::open(r_opts);
Void::Testing::require(reng.has_value());
auto rs = reng->snapshot();
Void::Testing::require(rs.has_value());
Void::Testing::expect_eq(reng->get(*rs, "w1")->as_string_view(), std::string_view{"after_ckpt"});
Void::Testing::expect_eq(reng->get(*rs, "t1")->bytes.size(), static_cast<std::size_t>(1024));
rs->reset();
Void::Testing::require(reng->close().has_value());
// Corrupt a single bit inside table data block in dir -> verify_directory fails!
for (const auto& entry : std::filesystem::directory_iterator(dir.path)) {
const auto name = entry.path().filename().string();
if (name.starts_with("TABLE-") && name.ends_with(".vtbl")) {
auto port = make_posix_file_port();
auto tf = port->open_file(entry.path(), FileOpenMode::ReadWriteExisting);
Void::Testing::require(tf.has_value());
std::byte b{};
Void::Testing::require((*tf)->pread_exact(kTableHeaderSize + 12, std::span{&b, 1}).has_value());
b ^= std::byte{0x01};
Void::Testing::require((*tf)->pwrite_all(kTableHeaderSize + 12, ByteView{&b, 1}).has_value());
Void::Testing::require((*tf)->sync().has_value());
break;
}
}
auto bad_vr = verify_directory(dir.path);
Void::Testing::expect(!bad_vr.has_value());
Void::Testing::expect(bad_vr.error().kind() == Void::Result::ErrorKind::corrupt);
// Same-directory salvage refused
auto same_sal = salvage_directory(dir.path, dir.path);
Void::Testing::expect(!same_sal.has_value());
// Salvage backup (or WAL) to separate salvage_dir succeeds!
auto sal = salvage_directory(backup_dir.path, salvage_dir.path);
Void::Testing::require(sal.has_value());
Void::Testing::expect(sal->keys_recovered >= 3);
}
// 2. AsyncStorageAdapter C-03 stop-race conformance
{
TempStorageDir adir;
auto fp = std::make_shared<FaultInjectingFilePort>();
OpenOptions opts;
opts.directory = adir.path;
opts.file_port = fp;
auto eng = Engine::open(opts);
Void::Testing::require(eng.has_value());
Void::Async::ManualExecutor exec;
AsyncStorageAdapter adapter{*eng, AsyncAdapterOptions{}, &exec};
// Case A: stop before append -> Outcome::NotCommitted
{
std::expected<CommitReceipt, WriteFailure> out = CommitReceipt{};
bool done = false;
auto t = drive_stop_before_append_test(adapter, &out, &done);
t.handle().resume();
Void::Testing::expect(done);
Void::Testing::expect(!out.has_value());
Void::Testing::expect(out.error().outcome == Outcome::NotCommitted);
}
// Case B: stop requested WHILE WAL sync is pending, then sync SUCCEEDS ->
// must still publish index and deliver CommitReceipt once (no stolen cancel!)
{
std::atomic<bool> in_sync{false};
std::atomic<bool> release_sync{false};
fp->set_pause_before_sync([&]() {
in_sync.store(true, std::memory_order_release);
while (!release_sync.load(std::memory_order_acquire)) {
std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
});
std::stop_source ss;
std::expected<CommitReceipt, WriteFailure> out =
std::unexpected{WriteFailure{{}, Outcome::Unknown}};
std::atomic<int> deliveries{0};
bool done = false;
auto t = drive_tracked_write_test(
adapter, "race_ok", "persisted", ss.get_token(), &out, &deliveries, &done);
t.handle().resume();
while (!in_sync.load(std::memory_order_acquire)) {
std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
// Stop while sync is pending: nothing delivered yet!
ss.request_stop();
exec.drain();
Void::Testing::expect(!done);
Void::Testing::expect_eq(deliveries.load(), 0);
// Let sync succeed -> CommitReceipt delivered exactly once & visible!
release_sync.store(true, std::memory_order_release);
while (!done) {
if (exec.drain() == 0) std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
fp->set_pause_before_sync({});
Void::Testing::expect_eq(deliveries.load(), 1);
Void::Testing::require(out.has_value());
auto snap = eng->snapshot();
Void::Testing::require(snap.has_value());
Void::Testing::expect_eq(eng->get(*snap, "race_ok")->as_string_view(),
std::string_view{"persisted"});
}
// Case C: sync FAILS after append while stop requested -> Outcome::Unknown + RecoveryRequired, single delivery
{
std::atomic<bool> in_sync{false};
std::atomic<bool> release_sync{false};
fp->set_pause_before_sync([&]() {
in_sync.store(true, std::memory_order_release);
while (!release_sync.load(std::memory_order_acquire)) {
std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
});
fp->add_rule(FaultRule{
.op = FaultOp::SyncFile,
.path_contains = "WAL-",
.hit_index = 1,
.error_code = StorageErrorCode::io_error});
std::stop_source live_ss;
std::expected<CommitReceipt, WriteFailure> out = CommitReceipt{};
std::atomic<int> deliveries{0};
bool done = false;
auto t = drive_tracked_write_test(
adapter, "race_fail", "uncertain", live_ss.get_token(), &out, &deliveries, &done);
t.handle().resume();
while (!in_sync.load(std::memory_order_acquire)) {
std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
live_ss.request_stop();
release_sync.store(true, std::memory_order_release);
while (!done) {
if (exec.drain() == 0) std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
fp->set_pause_before_sync({});
Void::Testing::expect_eq(deliveries.load(), 1);
Void::Testing::expect(!out.has_value());
Void::Testing::expect(out.error().outcome == Outcome::Unknown);
Void::Testing::expect(eng->state() == EngineState::RecoveryRequired);
}
adapter.close_and_join();
}
}
} // namespace
Void::Testing::Test storage_file_port_space_link_noreplace_and_no_follow()
{
TempStorageDir dir;
auto port = make_posix_file_port();
Void::Testing::require(port != nullptr);
const auto exists = [&](const std::filesystem::path& path) {
auto result = port->exists(path);
return result.has_value() && *result;
};
auto available = port->available_space(dir.path);
Void::Testing::require(available.has_value());
Void::Testing::expect(*available > 0);
const std::vector<std::byte> payload{std::byte{'a'}, std::byte{'b'}};
const auto src = dir.path / "src.bin";
{
auto file = port->open_file(src, FileOpenMode::CreateNew);
Void::Testing::require(file.has_value());
Void::Testing::require(
(*file)->pwrite_all(0, std::span<const std::byte>{payload})
.has_value());
Void::Testing::require((*file)->sync().has_value());
Void::Testing::require((*file)->close().has_value());
}
// Exclusive create refuses an existing file.
Void::Testing::expect(
!port->open_file(src, FileOpenMode::CreateNew).has_value());
const auto link = dir.path / "link.bin";
Void::Testing::require(port->hard_link(src, link).has_value());
Void::Testing::expect(exists(link));
Void::Testing::require(port->unlink_file(src).has_value());
Void::Testing::expect(exists(link));
// No-replace rename refuses an existing destination.
const auto moved = dir.path / "moved.bin";
{
auto dest = port->open_file(moved, FileOpenMode::CreateNew);
Void::Testing::require(dest.has_value());
Void::Testing::require((*dest)->close().has_value());
}
Void::Testing::expect(!port->rename_noreplace(link, moved).has_value());
Void::Testing::require(port->unlink_file(moved).has_value());
Void::Testing::require(port->rename_noreplace(link, moved).has_value());
Void::Testing::expect(!exists(link));
Void::Testing::expect(exists(moved));
// O_NOFOLLOW: opening through a symlink is rejected.
const auto target = dir.path / "target.bin";
{
auto file = port->open_file(target, FileOpenMode::CreateNew);
Void::Testing::require(file.has_value());
Void::Testing::require((*file)->close().has_value());
}
const auto symlink_path = dir.path / "symlink";
Void::Testing::require(::symlink(target.c_str(), symlink_path.c_str()) == 0);
Void::Testing::expect(
!port->open_file(symlink_path, FileOpenMode::ReadOnly).has_value());
}