diff --git a/include/Void/Storage/AsyncAdapter.hpp b/include/Void/Storage/AsyncAdapter.hpp new file mode 100644 index 0000000..068d358 --- /dev/null +++ b/include/Void/Storage/AsyncAdapter.hpp @@ -0,0 +1,72 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace Void::Storage +{ + struct AsyncAdapterOptions { + std::size_t max_pending_batches{64}; + std::size_t max_pending_bytes{64ULL * 1024ULL * 1024ULL}; + const Void::Time::MonotonicClock* clock{nullptr}; + }; + + struct AsyncAdapterStats { + std::size_t queued_writes{0}; + std::size_t pending_bytes{0}; + std::uint64_t completed_writes{0}; + std::uint64_t rejected_writes{0}; + std::uint64_t unknown_outcomes{0}; + std::uint64_t cancelled_before_append{0}; + }; + + /// Bounded blocking async adapter over Storage::Engine following C-03 + /// domain-result classification (never steals a persisted commit outcome with + /// a synthetic timeout/cancel once WAL append begins; single delivery only). + class AsyncStorageAdapter + { + public: + explicit AsyncStorageAdapter( + Engine& engine, + AsyncAdapterOptions options = {}, + Void::Async::Executor* completion_executor = nullptr); + ~AsyncStorageAdapter(); + + AsyncStorageAdapter(const AsyncStorageAdapter&) = delete; + AsyncStorageAdapter& operator=(const AsyncStorageAdapter&) = delete; + AsyncStorageAdapter(AsyncStorageAdapter&&) = delete; + AsyncStorageAdapter& operator=(AsyncStorageAdapter&&) = delete; + + [[nodiscard]] Void::Coro::Task> + write_async( + Batch batch, + Durability durability, + Void::Async::OperationOptions op = {}); + + [[nodiscard]] Void::Coro::Task> + get_async( + ByteView key, + Void::Async::OperationOptions op = {}); + + [[nodiscard]] Void::Coro::Task> + checkpoint_async(Void::Async::OperationOptions op = {}); + + [[nodiscard]] AsyncAdapterStats stats() const noexcept; + void close_and_join(); + + private: + struct Impl; + std::shared_ptr m_impl{}; + }; + +} // namespace Void::Storage diff --git a/include/Void/Storage/Batch.hpp b/include/Void/Storage/Batch.hpp new file mode 100644 index 0000000..7ff312f --- /dev/null +++ b/include/Void/Storage/Batch.hpp @@ -0,0 +1,93 @@ +#pragma once + +#include + +#include +#include +#include +#include + +namespace Void::Storage +{ + enum class MutationKind : std::uint8_t { + Put = 1, + Erase = 2 + }; + + enum class PreconditionKind : std::uint8_t { + Absent = 1, + VersionEquals = 2, + ValueEquals = 3 + }; + + struct Mutation { + MutationKind kind{MutationKind::Put}; + OwnedBytes key{}; + OwnedBytes value{}; + }; + + struct Precondition { + PreconditionKind kind{PreconditionKind::Absent}; + OwnedBytes key{}; + Sequence expected_version{0}; + OwnedBytes expected_value{}; + }; + + /// Atomic conditional write batch owning all key and value bytes. + /// Rejects duplicate mutation keys and duplicate preconditions per key. + class Batch + { + public: + Batch() = default; + + Batch& put(ByteView key, ByteView value); + Batch& put(std::string_view key, std::string_view value) + { + return put(to_byte_view(key), to_byte_view(value)); + } + + Batch& erase(ByteView key); + Batch& erase(std::string_view key) + { + return erase(to_byte_view(key)); + } + + Batch& require_absent(ByteView key); + Batch& require_absent(std::string_view key) + { + return require_absent(to_byte_view(key)); + } + + Batch& require_version(ByteView key, Sequence expected_version); + Batch& require_version(std::string_view key, Sequence expected_version) + { + return require_version(to_byte_view(key), expected_version); + } + + Batch& require_value(ByteView key, ByteView expected_value); + Batch& require_value(std::string_view key, std::string_view expected_value) + { + return require_value(to_byte_view(key), to_byte_view(expected_value)); + } + + [[nodiscard]] const std::vector& mutations() const noexcept + { + return m_mutations; + } + [[nodiscard]] const std::vector& preconditions() const noexcept + { + return m_preconditions; + } + [[nodiscard]] bool empty() const noexcept + { + return m_mutations.empty() && m_preconditions.empty(); + } + + [[nodiscard]] Result validate(const Limits& limits) const; + + private: + std::vector m_mutations{}; + std::vector m_preconditions{}; + }; + +} // namespace Void::Storage diff --git a/include/Void/Storage/Crc32c.hpp b/include/Void/Storage/Crc32c.hpp new file mode 100644 index 0000000..7b6d6ca --- /dev/null +++ b/include/Void/Storage/Crc32c.hpp @@ -0,0 +1,83 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace Void::Storage +{ + namespace detail + { + [[nodiscard]] constexpr std::array + make_crc32c_table() noexcept + { + // Reflected Castagnoli polynomial (normal 0x1EDC6F41, reflected 0x82F63B78). + constexpr std::uint32_t kPoly = 0x82F63B78u; + std::array table{}; + for (std::uint32_t i = 0; i < 256; ++i) { + std::uint32_t c = i; + for (int k = 0; k < 8; ++k) { + c = (c & 1u) ? (kPoly ^ (c >> 1)) : (c >> 1); + } + table[i] = c; + } + return table; + } + + inline constexpr auto kCrc32cTable = make_crc32c_table(); + } // namespace detail + + inline constexpr std::uint32_t kCrc32cInitial = 0xFFFFFFFFu; + + [[nodiscard]] constexpr std::uint32_t crc32c_init() noexcept + { + return kCrc32cInitial; + } + + [[nodiscard]] constexpr std::uint32_t crc32c_update( + std::uint32_t state, + std::span data) noexcept + { + for (const auto b : data) { + const auto idx = + (state ^ static_cast(std::to_integer(b))) & + 0xFFu; + state = detail::kCrc32cTable[idx] ^ (state >> 8); + } + return state; + } + + [[nodiscard]] constexpr std::uint32_t crc32c_update( + std::uint32_t state, + std::string_view text) noexcept + { + for (const unsigned char c : text) { + state = detail::kCrc32cTable[(state ^ c) & 0xFFu] ^ (state >> 8); + } + return state; + } + + [[nodiscard]] constexpr std::uint32_t crc32c_finalize(std::uint32_t state) noexcept + { + return state ^ 0xFFFFFFFFu; + } + + [[nodiscard]] constexpr std::uint32_t crc32c( + std::span data) noexcept + { + return crc32c_finalize(crc32c_update(crc32c_init(), data)); + } + + [[nodiscard]] constexpr std::uint32_t crc32c(std::string_view text) noexcept + { + return crc32c_finalize(crc32c_update(crc32c_init(), text)); + } + + static_assert(crc32c(std::string_view{"123456789"}) == 0xE3069283u, + "CRC32C golden vector mismatch"); + static_assert(crc32c(std::string_view{""}) == 0u, + "CRC32C empty vector mismatch"); + +} // namespace Void::Storage diff --git a/include/Void/Storage/Engine.hpp b/include/Void/Storage/Engine.hpp new file mode 100644 index 0000000..981b227 --- /dev/null +++ b/include/Void/Storage/Engine.hpp @@ -0,0 +1,147 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include + +namespace Void::Storage +{ + namespace detail + { + class EngineControl; + struct SourceView; + } // namespace detail + + class Engine; + class Cursor; + + /// Move-only reader pin of a committed sequence and immutable source set. + class Snapshot + { + public: + Snapshot() noexcept = default; + ~Snapshot(); + Snapshot(Snapshot&&) noexcept; + Snapshot& operator=(Snapshot&&) noexcept; + Snapshot(const Snapshot&) = delete; + Snapshot& operator=(const Snapshot&) = delete; + + [[nodiscard]] Sequence sequence() const noexcept { return m_sequence; } + [[nodiscard]] bool valid() const noexcept { return static_cast(m_control); } + void reset() noexcept; + + private: + friend class Engine; + friend class Cursor; + friend class detail::EngineControl; + + Snapshot(std::shared_ptr control, + std::shared_ptr view, + Sequence seq, + std::uint64_t pin_id) noexcept; + + std::shared_ptr m_control{}; + std::shared_ptr m_view{}; + Sequence m_sequence{0}; + std::uint64_t m_pin_id{0}; + }; + + /// Move-only ordered byte-lexicographic iterator retaining its Snapshot. + class Cursor + { + public: + Cursor() noexcept = default; + ~Cursor(); + Cursor(Cursor&&) noexcept; + Cursor& operator=(Cursor&&) noexcept; + Cursor(const Cursor&) = delete; + Cursor& operator=(const Cursor&) = delete; + + [[nodiscard]] Result next_page(); + [[nodiscard]] bool valid() const noexcept { return !m_closed && m_snapshot.valid(); } + void close() noexcept; + + private: + friend class Engine; + + Cursor(Snapshot snap, + ScanBounds bounds, + std::size_t page_bytes, + std::size_t page_rows, + std::uint64_t cursor_id) noexcept; + + Snapshot m_snapshot{}; + ScanBounds m_bounds{}; + std::size_t m_page_bytes{0}; + std::size_t m_page_rows{0}; + std::uint64_t m_cursor_id{0}; + std::optional m_resume_after{}; + bool m_finished{false}; + bool m_closed{false}; + }; + + class Engine + { + public: + Engine() noexcept = default; + ~Engine(); + Engine(Engine&&) noexcept; + Engine& operator=(Engine&&) noexcept; + Engine(const Engine&) = delete; + Engine& operator=(const Engine&) = delete; + + [[nodiscard]] static Result open(OpenOptions options); + + [[nodiscard]] Result snapshot(); + + [[nodiscard]] std::expected write( + Batch batch, + Durability durability); + + [[nodiscard]] std::expected write(Batch batch) + { + return write(std::move(batch), default_durability()); + } + + [[nodiscard]] Result get( + const Snapshot& snap, + ByteView key) const; + + [[nodiscard]] Result get( + const Snapshot& snap, + std::string_view key) const + { + return get(snap, to_byte_view(key)); + } + + [[nodiscard]] Result scan( + Snapshot snap, + ScanBounds bounds = ScanBounds::all()) const; + + [[nodiscard]] Result checkpoint(); + [[nodiscard]] Result compact(); + [[nodiscard]] Result sync(); + [[nodiscard]] Result close(); + + /// Copy consistent manifest, tables, and necessary WAL prefix into + /// `destination` while keeping this engine open and pinning sources. + [[nodiscard]] Result export_backup( + const std::filesystem::path& destination); + + [[nodiscard]] EngineState state() const noexcept; + [[nodiscard]] EngineStats stats() const noexcept; + [[nodiscard]] Durability default_durability() const noexcept; + [[nodiscard]] const Limits& limits() const noexcept; + + private: + friend class AsyncStorageAdapter; + explicit Engine(std::shared_ptr control) noexcept; + + std::shared_ptr m_control{}; + }; + +} // namespace Void::Storage diff --git a/include/Void/Storage/FilePort.hpp b/include/Void/Storage/FilePort.hpp new file mode 100644 index 0000000..f454798 --- /dev/null +++ b/include/Void/Storage/FilePort.hpp @@ -0,0 +1,145 @@ +#pragma once + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Storage +{ + enum class FileOpenMode : std::uint8_t { + ReadOnly = 0, + ReadWriteExisting = 1, + CreateNew = 2, + CreateOrOpen = 3 + }; + + class FileHandle + { + public: + virtual ~FileHandle() = default; + + [[nodiscard]] virtual Result pread( + std::uint64_t offset, std::span out) = 0; + [[nodiscard]] virtual Result pread_exact( + std::uint64_t offset, std::span out) = 0; + [[nodiscard]] virtual Result pwrite_all( + std::uint64_t offset, ByteView data) = 0; + [[nodiscard]] virtual Result append_all(ByteView data) = 0; + [[nodiscard]] virtual Result sync() = 0; + [[nodiscard]] virtual Result truncate(std::uint64_t new_size) = 0; + [[nodiscard]] virtual Result size() const = 0; + [[nodiscard]] virtual Result close() = 0; + }; + + class DirLockHandle + { + public: + virtual ~DirLockHandle() = default; + }; + + class FilePort + { + public: + virtual ~FilePort() = default; + + [[nodiscard]] virtual Result ensure_dir( + const std::filesystem::path& dir) = 0; + [[nodiscard]] virtual Result exists( + const std::filesystem::path& p) = 0; + [[nodiscard]] virtual Result file_size( + const std::filesystem::path& p) = 0; + [[nodiscard]] virtual Result> list_dir( + const std::filesystem::path& dir) = 0; + [[nodiscard]] virtual Result> + lock_directory(const std::filesystem::path& dir) = 0; + [[nodiscard]] virtual Result> open_file( + const std::filesystem::path& p, FileOpenMode mode) = 0; + [[nodiscard]] virtual Result rename_atomic( + const std::filesystem::path& from, + const std::filesystem::path& to) = 0; + [[nodiscard]] virtual Result unlink_file( + const std::filesystem::path& p) = 0; + [[nodiscard]] virtual Result sync_dir( + const std::filesystem::path& dir) = 0; + [[nodiscard]] virtual Result probe_durability_capabilities( + const std::filesystem::path& dir) = 0; + }; + + [[nodiscard]] std::shared_ptr make_posix_file_port(); + + enum class FaultOp : std::uint8_t { + LockDir = 0, + ProbeDurability = 1, + OpenFile = 2, + AppendWrite = 3, + PWrite = 4, + SyncFile = 5, + SyncDir = 6, + Rename = 7, + Unlink = 8, + Truncate = 9 + }; + + struct FaultRule { + FaultOp op{FaultOp::SyncFile}; + std::string path_contains{}; + /// 1-based hit index among matching operations (0 = fail every match). + std::uint64_t hit_index{1}; + StorageErrorCode error_code{StorageErrorCode::io_error}; + /// For write ops: write at most this many bytes before failing (SIZE_MAX = skip write). + std::optional partial_write_bytes{}; + bool consumed{false}; + std::uint64_t match_count{0}; + }; + + /// Deterministic filesystem fault-injection proxy wrapping a FilePort + /// (default: PosixFilePort) for crash, partial-write, and sync-failure tests. + class FaultInjectingFilePort final : public FilePort + { + public: + explicit FaultInjectingFilePort( + std::shared_ptr delegate = make_posix_file_port()); + + void add_rule(FaultRule rule); + void clear_rules(); + void set_pause_before_sync(std::function hook); + [[nodiscard]] std::uint64_t op_count(FaultOp op) const noexcept; + + [[nodiscard]] Result ensure_dir(const std::filesystem::path& dir) override; + [[nodiscard]] Result exists(const std::filesystem::path& p) override; + [[nodiscard]] Result file_size(const std::filesystem::path& p) override; + [[nodiscard]] Result> list_dir(const std::filesystem::path& dir) override; + [[nodiscard]] Result> lock_directory(const std::filesystem::path& dir) override; + [[nodiscard]] Result> open_file(const std::filesystem::path& p, FileOpenMode mode) override; + [[nodiscard]] Result rename_atomic(const std::filesystem::path& from, const std::filesystem::path& to) override; + [[nodiscard]] Result unlink_file(const std::filesystem::path& p) override; + [[nodiscard]] Result sync_dir(const std::filesystem::path& dir) override; + [[nodiscard]] Result probe_durability_capabilities(const std::filesystem::path& dir) override; + + private: + friend class FaultFileHandle; + + struct MatchedFault { + StorageErrorCode error_code{StorageErrorCode::none}; + std::optional partial_write_bytes{}; + bool triggered{false}; + }; + + [[nodiscard]] MatchedFault check_fault(FaultOp op, const std::string& path); + void maybe_run_sync_hook(); + + std::shared_ptr delegate_; + mutable std::mutex mu_; + std::vector rules_{}; + std::function pause_before_sync_{}; + std::uint64_t op_counts_[10]{}; + }; + +} // namespace Void::Storage diff --git a/include/Void/Storage/Format.hpp b/include/Void/Storage/Format.hpp new file mode 100644 index 0000000..22f5cdd --- /dev/null +++ b/include/Void/Storage/Format.hpp @@ -0,0 +1,216 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include + +namespace Void::Storage +{ + inline constexpr std::array kWalSegmentMagic{'V', 'O', 'I', 'D', 'W', 'A', 'L', '1'}; + inline constexpr std::uint16_t kWalFormatMajor = 1; + inline constexpr std::uint16_t kWalFormatMinor = 0; + inline constexpr std::uint32_t kWalSegmentHeaderSize = 64; + + inline constexpr std::uint32_t kWalRecordMagic = 0x56575231u; // "1RWV" little-endian + inline constexpr std::uint16_t kWalRecordVersion = 1; + inline constexpr std::uint32_t kWalRecordHeaderSize = 36; + inline constexpr std::uint32_t kWalRecordTrailerSize = 8; + + enum class WalRecordType : std::uint16_t { + Begin = 1, + Put = 2, + Erase = 3, + Commit = 4 + }; + + struct WalSegmentHeader { + std::uint16_t major{kWalFormatMajor}; + std::uint16_t minor{kWalFormatMinor}; + std::uint32_t header_size{kWalSegmentHeaderSize}; + Void::Uuid::Uuid database_uuid{}; + std::uint64_t segment_id{0}; + std::uint64_t previous_segment_id{0}; + Sequence first_candidate_sequence{0}; + std::uint32_t flags{0}; + }; + + struct WalRecordHeader { + std::uint32_t total_length{0}; + WalRecordType type{WalRecordType::Begin}; + std::uint16_t record_version{kWalRecordVersion}; + std::uint32_t flags{0}; + Sequence batch_sequence{0}; + std::uint32_t ordinal{0}; + std::uint32_t payload_length{0}; + }; + + struct WalBeginPayload { + std::uint32_t op_count{0}; + std::uint64_t total_op_bytes{0}; + }; + + struct WalMutationPayload { + OwnedBytes key{}; + OwnedBytes value{}; + }; + + struct WalCommitPayload { + std::uint32_t op_count{0}; + std::uint64_t total_op_bytes{0}; + std::uint32_t aggregate_crc32c{0}; + }; + + [[nodiscard]] Result encode_wal_segment_header(const WalSegmentHeader& hdr); + [[nodiscard]] Result decode_wal_segment_header(ByteView bytes); + + [[nodiscard]] Result encode_wal_record_frame( + WalRecordType type, + Sequence batch_sequence, + std::uint32_t ordinal, + ByteView payload); + + /// Decode and verify ONLY the 36-byte record header before reading/allocating payload. + [[nodiscard]] Result decode_wal_record_header( + ByteView header_bytes, + std::size_t max_payload_bytes); + + /// Verify full record CRC32C and trailing repeated length after reading payload+trailer. + [[nodiscard]] Result verify_wal_record_frame( + const WalRecordHeader& hdr, + ByteView full_record_bytes); + + [[nodiscard]] Result encode_wal_begin_payload(const WalBeginPayload& p); + [[nodiscard]] Result decode_wal_begin_payload(ByteView bytes); + + [[nodiscard]] Result encode_wal_mutation_payload( + bool is_erase, ByteView key, ByteView value); + [[nodiscard]] Result decode_wal_mutation_payload( + bool is_erase, + ByteView bytes, + std::size_t max_key_bytes, + std::size_t max_value_bytes); + + [[nodiscard]] Result encode_wal_commit_payload(const WalCommitPayload& p); + [[nodiscard]] Result decode_wal_commit_payload(ByteView bytes); + + // ── V1 Immutable Sorted Table (`VOIDTBL1`) ─────────────────────────────── + + inline constexpr std::array kTableMagic{'V', 'O', 'I', 'D', 'T', 'B', 'L', '1'}; + inline constexpr std::array kTableFooterMagic{'V', 'O', 'I', 'D', 'T', 'B', 'F', '1'}; + inline constexpr std::uint32_t kTableHeaderSize = 76; + inline constexpr std::uint32_t kTableFooterSize = 48; + + struct TableEntryRecord { + OwnedBytes key{}; + Sequence sequence{0}; + bool erased{false}; + OwnedBytes value{}; + }; + + struct TableHeader { + std::uint16_t major{1}; + std::uint16_t minor{0}; + std::uint32_t header_size{kTableHeaderSize}; + Void::Uuid::Uuid database_uuid{}; + std::uint64_t table_id{0}; + std::uint32_t level{0}; + std::uint32_t flags{0}; + std::uint64_t entry_count{0}; + Sequence min_sequence{0}; + Sequence max_sequence{0}; + }; + + struct TableBlockIndexEntry { + OwnedBytes first_key{}; + OwnedBytes last_key{}; + std::uint64_t offset{0}; + std::uint32_t byte_length{0}; + }; + + struct TableFooter { + std::uint64_t index_offset{0}; + std::uint64_t index_size{0}; + std::uint64_t data_end_offset{0}; + std::uint32_t file_crc32c{0}; + }; + + struct TableMeta { + std::uint64_t table_id{0}; + std::uint32_t level{0}; + std::uint64_t file_size{0}; + std::uint64_t entry_count{0}; + Sequence min_sequence{0}; + Sequence max_sequence{0}; + OwnedBytes min_key{}; + OwnedBytes max_key{}; + std::uint32_t file_crc32c{0}; + }; + + [[nodiscard]] Result encode_table_header(const TableHeader& hdr); + [[nodiscard]] Result decode_table_header(ByteView bytes); + [[nodiscard]] Result encode_table_block( + std::span entries, + std::size_t max_bytes); + [[nodiscard]] Result> decode_table_block( + ByteView bytes, + std::size_t max_key_bytes, + std::size_t max_value_bytes); + [[nodiscard]] Result encode_table_index( + std::span index, + std::size_t max_bytes); + [[nodiscard]] Result> decode_table_index( + ByteView bytes, + std::size_t max_key_bytes); + [[nodiscard]] Result encode_table_footer(const TableFooter& footer); + [[nodiscard]] Result decode_table_footer(ByteView bytes); + + // ── V1 Manifest (`VOIDMNF1`) & CURRENT (`VOIDCUR1`) ────────────────────── + + inline constexpr std::array kManifestMagic{'V', 'O', 'I', 'D', 'M', 'N', 'F', '1'}; + inline constexpr std::array kCurrentMagic{'V', 'O', 'I', 'D', 'C', 'U', 'R', '1'}; + inline constexpr std::string_view kComparatorIdV1 = "void.byte.lex.v1"; + + struct ManifestData { + std::uint16_t major{1}; + std::uint16_t minor{0}; + std::uint32_t flags{0}; + Void::Uuid::Uuid database_uuid{}; + std::uint64_t generation{0}; + Sequence checkpoint_sequence{0}; + Sequence next_sequence_hint{1}; + std::uint64_t next_file_id{1}; + std::string comparator{kComparatorIdV1}; + std::vector tables{}; + std::vector wal_segments{}; + }; + + struct CurrentPointer { + std::uint16_t major{1}; + std::uint16_t minor{0}; + Void::Uuid::Uuid database_uuid{}; + std::uint64_t generation{0}; + std::string manifest_filename{}; + }; + + [[nodiscard]] Result encode_manifest( + const ManifestData& m, + std::size_t max_manifest_bytes); + [[nodiscard]] Result decode_manifest( + ByteView bytes, + std::size_t max_manifest_bytes, + std::size_t max_tables, + std::size_t max_key_bytes); + + [[nodiscard]] Result encode_current(const CurrentPointer& cur); + [[nodiscard]] Result decode_current(ByteView bytes); + + [[nodiscard]] std::string make_wal_filename(std::uint64_t segment_id); + [[nodiscard]] std::string make_table_filename(std::uint64_t table_id); + [[nodiscard]] std::string make_manifest_filename(std::uint64_t generation); + +} // namespace Void::Storage diff --git a/include/Void/Storage/Storage.hpp b/include/Void/Storage/Storage.hpp new file mode 100644 index 0000000..504348c --- /dev/null +++ b/include/Void/Storage/Storage.hpp @@ -0,0 +1,10 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include diff --git a/include/Void/Storage/Tools.hpp b/include/Void/Storage/Tools.hpp new file mode 100644 index 0000000..4c05bd2 --- /dev/null +++ b/include/Void/Storage/Tools.hpp @@ -0,0 +1,54 @@ +#pragma once + +#include +#include + +#include +#include +#include + +namespace Void::Storage +{ + struct VerifyReport { + std::uint64_t manifest_generation{0}; + Sequence checkpoint_sequence{0}; + std::uint64_t tables_verified{0}; + std::uint64_t blocks_verified{0}; + std::uint64_t wal_segments_verified{0}; + std::uint64_t wal_batches_verified{0}; + }; + + struct SalvageReport { + Sequence highest_recovered_sequence{0}; + std::uint64_t recovered_batches{0}; + std::uint64_t keys_recovered{0}; + std::uint64_t tombstones_preserved{0}; + std::uint64_t truncated_or_skipped_bytes{0}; + }; + + /// Read-only full structural & block-level verification of an offline or + /// quiesced Storage directory (CURRENT, MANIFEST, every block of every table, + /// and every manifest-listed WAL segment). + [[nodiscard]] Result verify_directory( + const std::filesystem::path& directory, + const Limits& limits = {}, + std::shared_ptr port = nullptr); + + /// Restore a verified backup directory into `destination` without mutating + /// `backup_dir`. + [[nodiscard]] Result restore_backup( + const std::filesystem::path& backup_dir, + const std::filesystem::path& destination, + const Limits& limits = {}, + std::shared_ptr port = nullptr); + + /// Offline salvage: extracts the valid prefix of committed data and valid + /// tables/WAL records from `source_dir` into a fresh `destination_dir`. + /// Refuses same-directory salvage. + [[nodiscard]] Result salvage_directory( + const std::filesystem::path& source_dir, + const std::filesystem::path& destination_dir, + const Limits& limits = {}, + std::shared_ptr port = nullptr); + +} // namespace Void::Storage diff --git a/include/Void/Storage/Types.hpp b/include/Void/Storage/Types.hpp new file mode 100644 index 0000000..454fa3c --- /dev/null +++ b/include/Void/Storage/Types.hpp @@ -0,0 +1,381 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Storage +{ + using Void::Result::Error; + template using Result = Void::Result::Result; + + using Sequence = std::uint64_t; + using ByteView = std::span; + using OwnedBytes = std::vector; + + class FilePort; + + enum class Durability : std::uint8_t { + Sync = 0, + Buffered = 1 + }; + + enum class Outcome : std::uint8_t { + NotCommitted = 0, + Committed = 1, + Unknown = 2 + }; + + enum class EngineState : std::uint8_t { + Open = 0, + RecoveryRequired = 1, + Closed = 2 + }; + + enum class StorageErrorCode : std::int32_t { + none = 0, + invalid_argument = 1, + not_found = 2, + conflict = 3, + interrupted = 4, + timeout = 5, + overloaded = 6, + unsupported_capability = 7, + io_error = 8, + corrupt = 9, + incomplete_init = 10, + sequence_exhausted = 11, + recovery_required = 12, + busy = 13, + closed = 14, + page_too_small = 15, + quota_exceeded = 16 + }; + + [[nodiscard]] inline Error make_storage_error( + StorageErrorCode code, + std::string message, + std::error_code sys_err = {}) + { + using Void::Result::ErrorCode; + using Void::Result::ErrorKind; + + ErrorKind kind = ErrorKind::internal; + switch (code) { + case StorageErrorCode::none: + kind = ErrorKind::internal; + break; + case StorageErrorCode::invalid_argument: + case StorageErrorCode::page_too_small: + kind = ErrorKind::invalid_argument; + break; + case StorageErrorCode::not_found: + kind = ErrorKind::not_found; + break; + case StorageErrorCode::conflict: + case StorageErrorCode::recovery_required: + case StorageErrorCode::busy: + case StorageErrorCode::incomplete_init: + kind = ErrorKind::conflict; + break; + case StorageErrorCode::interrupted: + case StorageErrorCode::closed: + kind = ErrorKind::cancelled; + break; + case StorageErrorCode::timeout: + kind = ErrorKind::timeout; + break; + case StorageErrorCode::overloaded: + kind = ErrorKind::overloaded; + break; + case StorageErrorCode::unsupported_capability: + kind = ErrorKind::unsupported; + break; + case StorageErrorCode::io_error: + kind = ErrorKind::io; + break; + case StorageErrorCode::corrupt: + kind = ErrorKind::corrupt; + break; + case StorageErrorCode::sequence_exhausted: + case StorageErrorCode::quota_exceeded: + kind = ErrorKind::exhausted; + break; + } + + return Error{ + kind, + std::move(message), + ErrorCode{Void::Result::kStorageErrorDomain, + static_cast(code)}, + sys_err}; + } + + struct StorageError { + StorageErrorCode code{StorageErrorCode::none}; + Error error{}; + }; + + struct CommitReceipt { + Sequence sequence{0}; + Durability durability{Durability::Sync}; + }; + + struct WriteFailure { + StorageError cause{}; + Outcome outcome{Outcome::NotCommitted}; + }; + + struct OwnedValue { + OwnedBytes bytes{}; + Sequence version{0}; + + [[nodiscard]] std::string_view as_string_view() const noexcept + { + return bytes.empty() + ? std::string_view{} + : std::string_view{ + reinterpret_cast(bytes.data()), + bytes.size()}; + } + + [[nodiscard]] bool operator==(const OwnedValue&) const = default; + }; + + [[nodiscard]] inline OwnedBytes to_owned_bytes(std::string_view s) + { + OwnedBytes out(s.size()); + for (std::size_t i = 0; i < s.size(); ++i) { + out[i] = static_cast(static_cast(s[i])); + } + return out; + } + + [[nodiscard]] inline ByteView to_byte_view(std::string_view s) noexcept + { + return std::as_bytes(std::span{s.data(), s.size()}); + } + + [[nodiscard]] inline std::string_view to_string_view(ByteView b) noexcept + { + return b.empty() + ? std::string_view{} + : std::string_view{ + reinterpret_cast(b.data()), + b.size()}; + } + + /// Locale-independent unsigned-byte lexicographic comparison. + [[nodiscard]] inline int byte_compare(ByteView a, ByteView b) noexcept + { + const std::size_t n = std::min(a.size(), b.size()); + for (std::size_t i = 0; i < n; ++i) { + const auto xa = std::to_integer(a[i]); + const auto yb = std::to_integer(b[i]); + if (xa < yb) return -1; + if (xa > yb) return 1; + } + if (a.size() < b.size()) return -1; + if (a.size() > b.size()) return 1; + return 0; + } + + struct ByteLess { + using is_transparent = void; + + [[nodiscard]] bool operator()(ByteView a, ByteView b) const noexcept + { + return byte_compare(a, b) < 0; + } + [[nodiscard]] bool operator()(const OwnedBytes& a, const OwnedBytes& b) const noexcept + { + return byte_compare(a, b) < 0; + } + [[nodiscard]] bool operator()(const OwnedBytes& a, ByteView b) const noexcept + { + return byte_compare(a, b) < 0; + } + [[nodiscard]] bool operator()(ByteView a, const OwnedBytes& b) const noexcept + { + return byte_compare(a, b) < 0; + } + }; + + struct ScanBounds { + std::optional begin{}; + std::optional end{}; + std::size_t page_bytes{0}; + std::size_t page_rows{0}; + + [[nodiscard]] static ScanBounds all() { return {}; } + + [[nodiscard]] static ScanBounds range(ByteView b, ByteView e) + { + ScanBounds sb; + sb.begin.emplace(b.begin(), b.end()); + sb.end.emplace(e.begin(), e.end()); + return sb; + } + + [[nodiscard]] static ScanBounds range(std::string_view b, std::string_view e) + { + return range(to_byte_view(b), to_byte_view(e)); + } + + [[nodiscard]] static ScanBounds prefix(ByteView p) + { + ScanBounds sb; + sb.begin.emplace(p.begin(), p.end()); + OwnedBytes upper(p.begin(), p.end()); + while (!upper.empty()) { + const auto b = std::to_integer(upper.back()); + if (b < 0xFFu) { + upper.back() = static_cast(b + 1u); + sb.end = std::move(upper); + return sb; + } + upper.pop_back(); + } + // All-0xFF prefix has no finite upper bound. + return sb; + } + + [[nodiscard]] static ScanBounds prefix(std::string_view p) + { + return prefix(to_byte_view(p)); + } + }; + + struct ScanEntry { + OwnedBytes key{}; + OwnedBytes value{}; + Sequence version{0}; + }; + + struct ScanPage { + std::vector entries{}; + bool has_more{false}; + }; + + struct Limits { + std::size_t max_key_bytes{4096}; + std::size_t max_value_bytes{4ULL * 1024ULL * 1024ULL}; + std::size_t max_batch_encoded_bytes{16ULL * 1024ULL * 1024ULL}; + std::size_t max_batch_mutations{1024}; + std::size_t max_batch_conditions{1024}; + + std::size_t max_pending_batches{64}; + std::size_t max_pending_bytes{64ULL * 1024ULL * 1024ULL}; + + std::size_t active_memtable_target_bytes{64ULL * 1024ULL * 1024ULL}; + std::size_t max_total_memtable_bytes{256ULL * 1024ULL * 1024ULL}; + + std::size_t max_snapshots{128}; + std::size_t max_cursors{128}; + std::size_t default_scan_page_bytes{1024ULL * 1024ULL}; + std::size_t max_scan_page_bytes{8ULL * 1024ULL * 1024ULL}; + std::size_t default_scan_page_rows{1024}; + + std::size_t max_obsolete_pinned_bytes{1024ULL * 1024ULL * 1024ULL}; + std::size_t block_cache_bytes{32ULL * 1024ULL * 1024ULL}; + std::size_t compaction_workspace_bytes{16ULL * 1024ULL * 1024ULL}; + + std::uint64_t wal_segment_target_bytes{64ULL * 1024ULL * 1024ULL}; + std::uint64_t max_wal_total_bytes{4ULL * 1024ULL * 1024ULL * 1024ULL}; + std::size_t max_active_runs{32}; + std::size_t table_block_target_bytes{32768}; + std::size_t max_manifest_bytes{64ULL * 1024ULL * 1024ULL}; + std::size_t max_manifest_tables{65536}; + std::size_t max_compaction_merge_runs{4}; + std::uint64_t compaction_output_target_bytes{64ULL * 1024ULL * 1024ULL}; + std::size_t compaction_work_slice_bytes{8ULL * 1024ULL * 1024ULL}; + }; + + [[nodiscard]] inline Result validate_limits(const Limits& l) + { + if (l.max_key_bytes == 0 || + l.max_value_bytes == 0 || + l.max_batch_encoded_bytes == 0 || + l.max_batch_mutations == 0 || + l.max_batch_conditions == 0 || + l.max_pending_batches == 0 || + l.max_pending_bytes == 0 || + l.active_memtable_target_bytes == 0 || + l.max_total_memtable_bytes == 0 || + l.max_snapshots == 0 || + l.max_cursors == 0 || + l.default_scan_page_bytes == 0 || + l.max_scan_page_bytes == 0 || + l.default_scan_page_rows == 0 || + l.max_obsolete_pinned_bytes == 0 || + l.block_cache_bytes == 0 || + l.compaction_workspace_bytes == 0 || + l.wal_segment_target_bytes == 0 || + l.max_wal_total_bytes == 0 || + l.max_active_runs == 0 || + l.table_block_target_bytes == 0 || + l.max_manifest_bytes == 0 || + l.max_manifest_tables == 0 || + l.max_compaction_merge_runs == 0 || + l.compaction_output_target_bytes == 0 || + l.compaction_work_slice_bytes == 0) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::invalid_argument, + "Storage::Limits: all limits must be positive finite values")); + } + if (l.default_scan_page_bytes > l.max_scan_page_bytes || + l.active_memtable_target_bytes > l.max_total_memtable_bytes || + l.wal_segment_target_bytes > l.max_wal_total_bytes || + l.max_batch_encoded_bytes > l.wal_segment_target_bytes) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::invalid_argument, + "Storage::Limits: inconsistent bound ordering (max batch must fit in one WAL segment)")); + } + return {}; + } + + struct OpenOptions { + std::filesystem::path directory{}; + Durability default_durability{Durability::Sync}; + Limits limits{}; + std::pmr::memory_resource* memory_resource{nullptr}; + std::shared_ptr file_port{}; + const Void::Time::MonotonicClock* monotonic_clock{nullptr}; + std::function metric_hook{}; + /// Optional explicit sequence seed used only when opening a brand-new + /// database (e.g. sequence-exhaustion tests). + Sequence initial_sequence{0}; + }; + + struct EngineStats { + EngineState state{EngineState::Closed}; + Sequence committed_sequence{0}; + Sequence checkpoint_sequence{0}; + Sequence oldest_snapshot_sequence{0}; + std::uint64_t live_snapshots{0}; + std::uint64_t live_cursors{0}; + std::uint64_t active_memtable_bytes{0}; + std::uint64_t total_memtable_bytes{0}; + std::uint64_t wal_total_bytes{0}; + std::uint64_t active_table_count{0}; + std::uint64_t obsolete_pinned_bytes{0}; + std::uint64_t total_table_bytes{0}; + std::uint64_t recovery_truncated_bytes{0}; + bool durable_sync_verified{false}; + }; + +} // namespace Void::Storage diff --git a/src/Storage/AsyncAdapter.cpp b/src/Storage/AsyncAdapter.cpp new file mode 100644 index 0000000..462881f --- /dev/null +++ b/src/Storage/AsyncAdapter.cpp @@ -0,0 +1,272 @@ +#include + +#include +#include +#include +#include +#include +#include + +namespace Void::Storage +{ + struct AsyncStorageAdapter::Impl { + struct WriteJob { + std::shared_ptr>> state{}; + Batch batch{}; + Durability durability{Durability::Sync}; + std::size_t bytes{0}; + }; + + Impl(Engine& eng, AsyncAdapterOptions opts, Void::Async::Executor* exec) + : engine(eng), + options(std::move(opts)), + clock(options.clock ? options.clock : &Void::Time::SystemMonotonicClock::instance()), + completion_executor(exec) + { + worker = std::thread([this]() { run_loop(); }); + } + + ~Impl() + { + close_and_join(); + } + + void run_loop() + { + for (;;) { + WriteJob job; + { + std::unique_lock lk{mu}; + cv.wait(lk, [this]() { return !queue.empty() || closing; }); + if (queue.empty() && closing) { + return; + } + job = std::move(queue.front()); + queue.pop_front(); + pending_bytes -= job.bytes; + } + + auto& st = job.state; + // Check stop / deadline BEFORE emitting WAL bytes. + if (st->stop_requested()) { + cancelled_before_append.fetch_add(1, std::memory_order_relaxed); + std::expected wf = std::unexpected{WriteFailure{ + StorageError{StorageErrorCode::interrupted, + make_storage_error(StorageErrorCode::interrupted, + "AsyncStorageAdapter: stopped before append")}, + Outcome::NotCommitted}}; + if (auto t = st->try_commit_value(std::move(wf)); t) { + t->dispatch(); + } + st->release_backend_ref_and_dispatch(); + continue; + } + if (st->is_deadline_expired(*clock)) { + cancelled_before_append.fetch_add(1, std::memory_order_relaxed); + std::expected wf = std::unexpected{WriteFailure{ + StorageError{StorageErrorCode::timeout, + make_storage_error(StorageErrorCode::timeout, + "AsyncStorageAdapter: deadline expired before append")}, + Outcome::NotCommitted}}; + if (auto t = st->try_commit_value(std::move(wf)); t) { + t->dispatch(); + } + st->release_backend_ref_and_dispatch(); + continue; + } + + // Perform write: once append starts, external stop/deadline NEVER revokes + // a committed receipt or skips visibility publication! + auto wr = engine.write(std::move(job.batch), job.durability); + if (wr.has_value()) { + completed_writes.fetch_add(1, std::memory_order_relaxed); + } else if (wr.error().outcome == Outcome::Unknown) { + unknown_outcomes.fetch_add(1, std::memory_order_relaxed); + } else { + rejected_writes.fetch_add(1, std::memory_order_relaxed); + } + + if (auto t = st->try_commit_value(std::move(wr)); t) { + t->dispatch(); + } + st->release_backend_ref_and_dispatch(); + } + } + + void close_and_join() + { + { + std::lock_guard lk{mu}; + if (closed) return; + closing = true; + } + cv.notify_all(); + if (worker.joinable()) { + worker.join(); + } + std::lock_guard lk{mu}; + closed = true; + } + + Engine& engine; + AsyncAdapterOptions options; + const Void::Time::MonotonicClock* clock; + Void::Async::Executor* completion_executor{nullptr}; + + mutable std::mutex mu{}; + std::condition_variable cv{}; + std::deque queue{}; + std::size_t pending_bytes{0}; + bool closing{false}; + bool closed{false}; + std::thread worker{}; + + std::atomic completed_writes{0}; + std::atomic rejected_writes{0}; + std::atomic unknown_outcomes{0}; + std::atomic cancelled_before_append{0}; + }; + + AsyncStorageAdapter::AsyncStorageAdapter( + Engine& engine, + AsyncAdapterOptions options, + Void::Async::Executor* completion_executor) + : m_impl(std::make_shared(engine, std::move(options), completion_executor)) + { + } + + AsyncStorageAdapter::~AsyncStorageAdapter() + { + close_and_join(); + } + + Void::Coro::Task> + AsyncStorageAdapter::write_async( + Batch batch, + Durability durability, + Void::Async::OperationOptions op) + { + if (op.stop.stop_requested()) { + m_impl->cancelled_before_append.fetch_add(1, std::memory_order_relaxed); + co_return std::unexpected{WriteFailure{ + StorageError{StorageErrorCode::interrupted, + make_storage_error(StorageErrorCode::interrupted, + "AsyncStorageAdapter: stopped before admission")}, + Outcome::NotCommitted}}; + } + if (op.deadline.has_value() && m_impl->clock->now() >= *op.deadline) { + m_impl->cancelled_before_append.fetch_add(1, std::memory_order_relaxed); + co_return std::unexpected{WriteFailure{ + StorageError{StorageErrorCode::timeout, + make_storage_error(StorageErrorCode::timeout, + "AsyncStorageAdapter: deadline expired before admission")}, + Outcome::NotCommitted}}; + } + + if (auto vb = batch.validate(m_impl->engine.limits()); !vb) { + m_impl->rejected_writes.fetch_add(1, std::memory_order_relaxed); + const auto code = static_cast(vb.error().code().value); + co_return std::unexpected{WriteFailure{ + StorageError{code, std::move(vb).error()}, Outcome::NotCommitted}}; + } + + std::size_t batch_bytes = 0; + for (const auto& m : batch.mutations()) { + batch_bytes += m.key.size() + m.value.size(); + } + + auto state = Void::Async::OperationState< + std::expected>::create( + op, m_impl->completion_executor, Void::Async::StopBehavior::notify_only); + + { + std::lock_guard lk{m_impl->mu}; + if (m_impl->closing || m_impl->closed) { + m_impl->rejected_writes.fetch_add(1, std::memory_order_relaxed); + co_return std::unexpected{WriteFailure{ + StorageError{StorageErrorCode::closed, + make_storage_error(StorageErrorCode::closed, + "AsyncStorageAdapter: closing")}, + Outcome::NotCommitted}}; + } + if (m_impl->queue.size() >= m_impl->options.max_pending_batches || + batch_bytes > m_impl->options.max_pending_bytes || + m_impl->pending_bytes > m_impl->options.max_pending_bytes - batch_bytes) { + m_impl->rejected_writes.fetch_add(1, std::memory_order_relaxed); + co_return std::unexpected{WriteFailure{ + StorageError{StorageErrorCode::overloaded, + make_storage_error(StorageErrorCode::overloaded, + "AsyncStorageAdapter: pending queue overloaded")}, + Outcome::NotCommitted}}; + } + m_impl->pending_bytes += batch_bytes; + state->acquire_backend_ref(); + m_impl->queue.push_back(Impl::WriteJob{ + state, std::move(batch), durability, batch_bytes}); + } + + m_impl->cv.notify_one(); + auto awaited = co_await state->awaitable(m_impl->completion_executor); + if (!awaited) { + co_return std::unexpected{WriteFailure{ + StorageError{StorageErrorCode::io_error, std::move(awaited).error()}, + Outcome::Unknown}}; + } + co_return std::move(*awaited); + } + + Void::Coro::Task> + AsyncStorageAdapter::get_async( + ByteView key, + Void::Async::OperationOptions op) + { + if (op.stop.stop_requested()) { + co_return Void::Result::fail(make_storage_error( + StorageErrorCode::interrupted, "AsyncStorageAdapter::get_async cancelled")); + } + if (op.deadline.has_value() && m_impl->clock->now() >= *op.deadline) { + co_return Void::Result::fail(make_storage_error( + StorageErrorCode::timeout, "AsyncStorageAdapter::get_async timed out")); + } + auto snap = m_impl->engine.snapshot(); + if (!snap) co_return Void::Result::fail(std::move(snap).error()); + co_return m_impl->engine.get(*snap, key); + } + + Void::Coro::Task> + AsyncStorageAdapter::checkpoint_async(Void::Async::OperationOptions op) + { + if (op.stop.stop_requested()) { + co_return Void::Result::fail(make_storage_error( + StorageErrorCode::interrupted, "AsyncStorageAdapter::checkpoint_async cancelled")); + } + if (op.deadline.has_value() && m_impl->clock->now() >= *op.deadline) { + co_return Void::Result::fail(make_storage_error( + StorageErrorCode::timeout, "AsyncStorageAdapter::checkpoint_async timed out")); + } + co_return m_impl->engine.checkpoint(); + } + + AsyncAdapterStats AsyncStorageAdapter::stats() const noexcept + { + AsyncAdapterStats st; + if (!m_impl) return st; + std::lock_guard lk{m_impl->mu}; + st.queued_writes = m_impl->queue.size(); + st.pending_bytes = m_impl->pending_bytes; + st.completed_writes = m_impl->completed_writes.load(std::memory_order_relaxed); + st.rejected_writes = m_impl->rejected_writes.load(std::memory_order_relaxed); + st.unknown_outcomes = m_impl->unknown_outcomes.load(std::memory_order_relaxed); + st.cancelled_before_append = + m_impl->cancelled_before_append.load(std::memory_order_relaxed); + return st; + } + + void AsyncStorageAdapter::close_and_join() + { + if (m_impl) { + m_impl->close_and_join(); + } + } + +} // namespace Void::Storage diff --git a/src/Storage/Batch.cpp b/src/Storage/Batch.cpp new file mode 100644 index 0000000..a01c270 --- /dev/null +++ b/src/Storage/Batch.cpp @@ -0,0 +1,122 @@ +#include + +#include + +namespace Void::Storage +{ + Batch& Batch::put(ByteView key, ByteView value) + { + Mutation m; + m.kind = MutationKind::Put; + m.key.assign(key.begin(), key.end()); + m.value.assign(value.begin(), value.end()); + m_mutations.push_back(std::move(m)); + return *this; + } + + Batch& Batch::erase(ByteView key) + { + Mutation m; + m.kind = MutationKind::Erase; + m.key.assign(key.begin(), key.end()); + m_mutations.push_back(std::move(m)); + return *this; + } + + Batch& Batch::require_absent(ByteView key) + { + Precondition p; + p.kind = PreconditionKind::Absent; + p.key.assign(key.begin(), key.end()); + m_preconditions.push_back(std::move(p)); + return *this; + } + + Batch& Batch::require_version(ByteView key, Sequence expected_version) + { + Precondition p; + p.kind = PreconditionKind::VersionEquals; + p.key.assign(key.begin(), key.end()); + p.expected_version = expected_version; + m_preconditions.push_back(std::move(p)); + return *this; + } + + Batch& Batch::require_value(ByteView key, ByteView expected_value) + { + Precondition p; + p.kind = PreconditionKind::ValueEquals; + p.key.assign(key.begin(), key.end()); + p.expected_value.assign(expected_value.begin(), expected_value.end()); + m_preconditions.push_back(std::move(p)); + return *this; + } + + Result Batch::validate(const Limits& limits) const + { + if (m_mutations.size() > limits.max_batch_mutations) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::invalid_argument, + "Storage::Batch: mutation count exceeds max_batch_mutations")); + } + if (m_preconditions.size() > limits.max_batch_conditions) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::invalid_argument, + "Storage::Batch: precondition count exceeds max_batch_conditions")); + } + + std::set seen_mut_keys; + std::size_t total_op_bytes = 0; + for (const auto& m : m_mutations) { + if (m.key.size() > limits.max_key_bytes) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::invalid_argument, + "Storage::Batch: mutation key exceeds max_key_bytes")); + } + if (m.value.size() > limits.max_value_bytes) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::invalid_argument, + "Storage::Batch: mutation value exceeds max_value_bytes")); + } + if (m.kind == MutationKind::Erase && !m.value.empty()) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::invalid_argument, + "Storage::Batch: erase mutation must have empty value")); + } + if (!seen_mut_keys.insert(ByteView{m.key}).second) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::invalid_argument, + "Storage::Batch: duplicate mutation key in batch")); + } + const std::size_t pair_bytes = m.key.size() + m.value.size(); + if (total_op_bytes > limits.max_batch_encoded_bytes - pair_bytes) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::quota_exceeded, + "Storage::Batch: mutation payload exceeds max_batch_encoded_bytes")); + } + total_op_bytes += pair_bytes; + } + + std::set seen_cond_keys; + for (const auto& p : m_preconditions) { + if (p.key.size() > limits.max_key_bytes) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::invalid_argument, + "Storage::Batch: precondition key exceeds max_key_bytes")); + } + if (p.expected_value.size() > limits.max_value_bytes) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::invalid_argument, + "Storage::Batch: precondition expected_value exceeds max_value_bytes")); + } + if (!seen_cond_keys.insert(ByteView{p.key}).second) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::invalid_argument, + "Storage::Batch: duplicate precondition for same key")); + } + } + + return {}; + } + +} // namespace Void::Storage diff --git a/src/Storage/Engine.cpp b/src/Storage/Engine.cpp new file mode 100644 index 0000000..2216f14 --- /dev/null +++ b/src/Storage/Engine.cpp @@ -0,0 +1,1923 @@ +#include +#include +#include +#include +#include +#include "TableInternal.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Storage +{ + namespace detail + { + struct VersionNode { + Sequence seq{0}; + bool erased{false}; + OwnedBytes value{}; + std::shared_ptr next{}; + }; + + using MemMap = std::map, ByteLess>; + + struct MemTable { + MemMap map{}; + std::uint64_t approx_bytes{0}; + Sequence min_seq{0}; + Sequence max_seq{0}; + }; + + struct SourceView { + std::uint64_t generation{0}; + Sequence checkpoint_seq{0}; + std::shared_ptr active_at_capture{}; + std::vector> frozen{}; + std::vector> tables{}; + }; + + struct SnapshotPinInfo { + std::uint64_t generation{0}; + Sequence seq{0}; + }; + + struct ObsoleteFile { + std::filesystem::path path{}; + std::uint64_t byte_size{0}; + std::uint64_t superseded_at_generation{0}; + }; + + class EngineControl : public std::enable_shared_from_this + { + public: + OpenOptions options{}; + std::shared_ptr port{}; + std::unique_ptr dir_lock{}; + Void::Uuid::Uuid db_uuid{}; + + mutable std::mutex maint_mu{}; + mutable std::mutex writer_mu{}; + mutable std::shared_mutex vis_mu{}; + mutable std::mutex pin_mu{}; + + EngineState state{EngineState::Open}; + bool durable_sync_verified{true}; + + Sequence committed_seq{0}; + Sequence durable_seq{0}; + Sequence checkpoint_seq{0}; + std::uint64_t generation{0}; + std::uint64_t next_file_id{1}; + + std::uint64_t active_wal_seg_id{1}; + std::uint64_t active_wal_bytes{kWalSegmentHeaderSize}; + std::unique_ptr active_wal{}; + std::vector wal_segments{}; + std::map wal_segment_sizes{}; + + std::shared_ptr active_memtable{}; + std::vector> frozen_memtables{}; + std::vector> active_tables{}; + + std::map live_pins{}; + std::uint64_t next_pin_id{1}; + std::atomic live_cursors{0}; + std::uint64_t next_cursor_id{1}; + + std::vector obsolete_files{}; + std::uint64_t obsolete_pinned_bytes{0}; + std::uint64_t recovery_truncated_bytes{0}; + + ~EngineControl() + { + if (active_wal) { + (void)active_wal->close(); + active_wal.reset(); + } + active_tables.clear(); + dir_lock.reset(); + state = EngineState::Closed; + } + + void release_pin(std::uint64_t pin_id) noexcept + { + { + std::lock_guard lk{pin_mu}; + live_pins.erase(pin_id); + } + // Opportunistically sweep retireable files if maintenance lock is free + // and engine is healthy/open. + if (std::unique_lock m_lk{maint_mu, std::try_to_lock}; m_lk.owns_lock()) { + if (state == EngineState::Open) { + reclaim_obsolete_locked(); + } + } + } + + [[nodiscard]] std::uint64_t compute_min_pinned_gen_locked() const noexcept + { + std::uint64_t min_gen = std::numeric_limits::max(); + for (const auto& [_, pin] : live_pins) { + min_gen = std::min(min_gen, pin.generation); + } + return min_gen; + } + + [[nodiscard]] Sequence compute_oldest_pinned_seq_locked() const noexcept + { + Sequence oldest = std::numeric_limits::max(); + for (const auto& [_, pin] : live_pins) { + oldest = std::min(oldest, pin.seq); + } + return oldest; + } + + void reclaim_obsolete_locked() noexcept + { + std::uint64_t min_gen = 0; + { + std::lock_guard lk{pin_mu}; + min_gen = compute_min_pinned_gen_locked(); + } + bool removed_any = false; + std::vector kept; + std::uint64_t kept_bytes = 0; + for (auto& obs : obsolete_files) { + if (obs.superseded_at_generation <= min_gen) { + if (port && port->unlink_file(obs.path).has_value()) { + removed_any = true; + } else { + // Keep if unlink failed so caller/retry sees retained byte count + kept_bytes += obs.byte_size; + kept.push_back(std::move(obs)); + } + } else { + kept_bytes += obs.byte_size; + kept.push_back(std::move(obs)); + } + } + obsolete_files = std::move(kept); + obsolete_pinned_bytes = kept_bytes; + if (removed_any && port) { + (void)port->sync_dir(options.directory); + } + } + + [[nodiscard]] std::uint64_t total_wal_bytes_locked() const noexcept + { + std::uint64_t sum = 0; + for (const auto& [_, sz] : wal_segment_sizes) { + sum += sz; + } + return sum; + } + + [[nodiscard]] std::uint64_t total_table_bytes_locked() const noexcept + { + std::uint64_t sum = 0; + for (const auto& t : active_tables) { + sum += t->meta().file_size; + } + return sum; + } + + [[nodiscard]] Result publish_manifest_and_current_locked( + const ManifestData& manifest) + { + const auto man_name = make_manifest_filename(manifest.generation); + const auto man_tmp = options.directory / (man_name + ".tmp"); + const auto man_final = options.directory / man_name; + const auto cur_tmp = options.directory / "CURRENT.tmp"; + const auto cur_final = options.directory / "CURRENT"; + + auto man_bytes = encode_manifest(manifest, options.limits.max_manifest_bytes); + if (!man_bytes) return Void::Result::fail(std::move(man_bytes).error()); + + (void)port->unlink_file(man_tmp); + { + auto mf = port->open_file(man_tmp, FileOpenMode::CreateNew); + if (!mf) return Void::Result::fail(std::move(mf).error()); + if (auto w = (*mf)->append_all(*man_bytes); !w) { + (void)port->unlink_file(man_tmp); + return Void::Result::fail(std::move(w).error()); + } + if (auto s = (*mf)->sync(); !s) { + (void)port->unlink_file(man_tmp); + return s; + } + if (auto c = (*mf)->close(); !c) { + (void)port->unlink_file(man_tmp); + return c; + } + } + if (auto r = port->rename_atomic(man_tmp, man_final); !r) { + (void)port->unlink_file(man_tmp); + return r; + } + if (auto s = port->sync_dir(options.directory); !s) { + return s; + } + + CurrentPointer cur; + cur.database_uuid = db_uuid; + cur.generation = manifest.generation; + cur.manifest_filename = man_name; + auto cur_bytes = encode_current(cur); + if (!cur_bytes) return Void::Result::fail(std::move(cur_bytes).error()); + + (void)port->unlink_file(cur_tmp); + { + auto cf = port->open_file(cur_tmp, FileOpenMode::CreateNew); + if (!cf) return Void::Result::fail(std::move(cf).error()); + if (auto w = (*cf)->append_all(*cur_bytes); !w) { + (void)port->unlink_file(cur_tmp); + return Void::Result::fail(std::move(w).error()); + } + if (auto s = (*cf)->sync(); !s) { + (void)port->unlink_file(cur_tmp); + return s; + } + if (auto c = (*cf)->close(); !c) { + (void)port->unlink_file(cur_tmp); + return c; + } + } + if (auto r = port->rename_atomic(cur_tmp, cur_final); !r) { + (void)port->unlink_file(cur_tmp); + return r; + } + if (auto s = port->sync_dir(options.directory); !s) { + return s; + } + return {}; + } + + [[nodiscard]] Result> lookup_latest_in_source( + const SourceView& view, + Sequence snap_seq, + ByteView key, + bool lock_vis_for_active) const + { + std::optional best; + auto consider = [&](TableEntryRecord cand) { + if (cand.sequence <= snap_seq && + (!best.has_value() || cand.sequence > best->sequence)) { + best = std::move(cand); + } + }; + + auto scan_mem = [&](const MemTable& mt) { + auto it = mt.map.find(key); + if (it == mt.map.end()) return; + for (auto node = it->second; node != nullptr; node = node->next) { + if (node->seq <= snap_seq) { + consider(TableEntryRecord{ + OwnedBytes{key.begin(), key.end()}, + node->seq, + node->erased, + node->value}); + break; + } + } + }; + + if (view.active_at_capture) { + if (lock_vis_for_active) { + std::shared_lock v_lk{vis_mu}; + scan_mem(*view.active_at_capture); + } else { + scan_mem(*view.active_at_capture); + } + } + for (const auto& f : view.frozen) { + if (f) scan_mem(*f); + } + for (const auto& t : view.tables) { + if (!t) continue; + auto r = t->lookup(key, snap_seq); + if (!r) return Void::Result::fail(std::move(r).error()); + if (r->has_value()) { + consider(std::move(**r)); + } + } + return best; + } + }; + + [[nodiscard]] std::optional next_byte_key(ByteView k) + { + OwnedBytes next(k.begin(), k.end()); + next.push_back(std::byte{0}); + return next; + } + } // namespace detail + + // ── Snapshot ───────────────────────────────────────────────────────────── + + Snapshot::Snapshot( + std::shared_ptr control, + std::shared_ptr view, + Sequence seq, + std::uint64_t pin_id) noexcept + : m_control(std::move(control)), + m_view(std::move(view)), + m_sequence(seq), + m_pin_id(pin_id) + { + } + + Snapshot::~Snapshot() + { + reset(); + } + + Snapshot::Snapshot(Snapshot&& o) noexcept + : m_control(std::move(o.m_control)), + m_view(std::move(o.m_view)), + m_sequence(std::exchange(o.m_sequence, 0)), + m_pin_id(std::exchange(o.m_pin_id, 0)) + { + } + + Snapshot& Snapshot::operator=(Snapshot&& o) noexcept + { + if (this != &o) { + reset(); + m_control = std::move(o.m_control); + m_view = std::move(o.m_view); + m_sequence = std::exchange(o.m_sequence, 0); + m_pin_id = std::exchange(o.m_pin_id, 0); + } + return *this; + } + + void Snapshot::reset() noexcept + { + if (m_control) { + m_view.reset(); + auto ctrl = std::move(m_control); + const auto pin = std::exchange(m_pin_id, 0); + m_sequence = 0; + ctrl->release_pin(pin); + } + } + + // ── Cursor ─────────────────────────────────────────────────────────────── + + Cursor::Cursor( + Snapshot snap, + ScanBounds bounds, + std::size_t page_bytes, + std::size_t page_rows, + std::uint64_t cursor_id) noexcept + : m_snapshot(std::move(snap)), + m_bounds(std::move(bounds)), + m_page_bytes(page_bytes), + m_page_rows(page_rows), + m_cursor_id(cursor_id) + { + } + + Cursor::~Cursor() + { + close(); + } + + Cursor::Cursor(Cursor&& o) noexcept + : m_snapshot(std::move(o.m_snapshot)), + m_bounds(std::move(o.m_bounds)), + m_page_bytes(o.m_page_bytes), + m_page_rows(o.m_page_rows), + m_cursor_id(std::exchange(o.m_cursor_id, 0)), + m_resume_after(std::move(o.m_resume_after)), + m_finished(o.m_finished), + m_closed(std::exchange(o.m_closed, true)) + { + } + + Cursor& Cursor::operator=(Cursor&& o) noexcept + { + if (this != &o) { + close(); + m_snapshot = std::move(o.m_snapshot); + m_bounds = std::move(o.m_bounds); + m_page_bytes = o.m_page_bytes; + m_page_rows = o.m_page_rows; + m_cursor_id = std::exchange(o.m_cursor_id, 0); + m_resume_after = std::move(o.m_resume_after); + m_finished = o.m_finished; + m_closed = std::exchange(o.m_closed, true); + } + return *this; + } + + void Cursor::close() noexcept + { + if (!m_closed) { + m_closed = true; + if (m_snapshot.m_control) { + m_snapshot.m_control->live_cursors.fetch_sub(1, std::memory_order_acq_rel); + } + m_snapshot.reset(); + } + } + + Result Cursor::next_page() + { + if (m_closed || !m_snapshot.valid()) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::closed, "Storage::Cursor is closed")); + } + auto& ctrl = *m_snapshot.m_control; + if (ctrl.state == EngineState::Closed) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::closed, "Storage::Engine is closed")); + } + if (m_finished) { + return ScanPage{}; + } + + const auto& view = *m_snapshot.m_view; + const Sequence snap_seq = m_snapshot.sequence(); + + std::optional start_key; + if (m_resume_after.has_value()) { + start_key = detail::next_byte_key(*m_resume_after); + } else if (m_bounds.begin.has_value()) { + start_key = m_bounds.begin; + } + if (m_bounds.end.has_value() && start_key.has_value() && + byte_compare(*start_key, *m_bounds.end) >= 0) { + m_finished = true; + return ScanPage{}; + } + + // Stream source iterators positioned >= start_key. + struct MemCursor { + const detail::MemTable* mt{nullptr}; + detail::MemMap::const_iterator it; + detail::MemMap::const_iterator end; + std::optional current{}; + + void advance_to_next(Sequence seq) + { + current.reset(); + while (it != end) { + const auto& k = it->first; + std::shared_ptr best_node; + for (auto node = it->second; node != nullptr; node = node->next) { + if (node->seq <= seq) { + best_node = node; + break; + } + } + ++it; + if (best_node) { + current = TableEntryRecord{k, best_node->seq, best_node->erased, best_node->value}; + return; + } + } + } + }; + + struct TableCursor { + const detail::TableReader* tr{nullptr}; + std::size_t block_idx{0}; + std::vector block_entries{}; + std::size_t entry_idx{0}; + std::optional current{}; + + [[nodiscard]] Result init( + const detail::TableReader* reader, + const std::optional& start, + Sequence seq) + { + tr = reader; + const auto& idx = tr->index(); + if (idx.empty()) return {}; + if (start.has_value()) { + auto it = std::lower_bound( + idx.begin(), idx.end(), ByteView{*start}, + [](const TableBlockIndexEntry& blk, ByteView k) { + return byte_compare(blk.last_key, k) < 0; + }); + block_idx = static_cast(it - idx.begin()); + } else { + block_idx = 0; + } + return advance_to_key(start, seq); + } + + [[nodiscard]] Result advance_to_key( + const std::optional& min_key, + Sequence seq) + { + current.reset(); + const auto& idx = tr->index(); + OwnedBytes active_key; + bool have_key = false; + std::optional best_for_key; + + auto step_entry = [&](const TableEntryRecord& rec) -> bool { + if (min_key.has_value() && byte_compare(rec.key, *min_key) < 0) { + return false; + } + if (have_key && byte_compare(rec.key, active_key) != 0) { + if (best_for_key.has_value()) { + // Keep rec unconsumed for the next call! + return true; + } + active_key.clear(); + have_key = false; + } + if (!have_key) { + active_key = rec.key; + have_key = true; + } + if (rec.sequence <= seq && + (!best_for_key.has_value() || rec.sequence > best_for_key->sequence)) { + best_for_key = rec; + } + return false; + }; + + for (;;) { + while (entry_idx < block_entries.size()) { + if (step_entry(block_entries[entry_idx])) { + current = std::move(best_for_key); + return {}; + } + ++entry_idx; + } + if (block_idx >= idx.size()) { + if (best_for_key.has_value()) { + current = std::move(best_for_key); + } + return {}; + } + auto blk = tr->read_block(block_idx++); + if (!blk) return Void::Result::fail(std::move(blk).error()); + block_entries = std::move(*blk); + entry_idx = 0; + } + } + + [[nodiscard]] Result advance(Sequence seq) + { + return advance_to_key(std::nullopt, seq); + } + }; + + // Shared lock on vis_mu keeps active_at_capture->map safe against concurrent + // writer insertions while reading this page. + std::shared_lock v_lk{ctrl.vis_mu}; + + std::vector mem_cursors; + auto add_mem = [&](const detail::MemTable* mt) { + if (!mt) return; + MemCursor mc; + mc.mt = mt; + mc.it = start_key.has_value() ? mt->map.lower_bound(ByteView{*start_key}) : mt->map.begin(); + mc.end = mt->map.end(); + mc.advance_to_next(snap_seq); + if (mc.current.has_value()) { + mem_cursors.push_back(std::move(mc)); + } + }; + add_mem(view.active_at_capture.get()); + for (const auto& fm : view.frozen) { + add_mem(fm.get()); + } + + std::vector tbl_cursors(view.tables.size()); + for (std::size_t i = 0; i < view.tables.size(); ++i) { + if (auto r = tbl_cursors[i].init(view.tables[i].get(), start_key, snap_seq); !r) { + return Void::Result::fail(std::move(r).error()); + } + } + + ScanPage page; + std::size_t used_bytes = 0; + + for (;;) { + std::optional min_key; + auto consider_key = [&](ByteView k) { + if (!min_key.has_value() || byte_compare(k, *min_key) < 0) { + min_key = k; + } + }; + for (const auto& mc : mem_cursors) { + if (mc.current.has_value()) consider_key(mc.current->key); + } + for (const auto& tc : tbl_cursors) { + if (tc.current.has_value()) consider_key(tc.current->key); + } + + if (!min_key.has_value()) { + m_finished = true; + break; + } + if (m_bounds.end.has_value() && byte_compare(*min_key, *m_bounds.end) >= 0) { + m_finished = true; + break; + } + + OwnedBytes key_copy(min_key->begin(), min_key->end()); + std::optional winner; + auto pick_winner = [&](const TableEntryRecord& cand) { + if (!winner.has_value() || cand.sequence > winner->sequence) { + winner = cand; + } + }; + for (const auto& mc : mem_cursors) { + if (mc.current.has_value() && byte_compare(mc.current->key, key_copy) == 0) { + pick_winner(*mc.current); + } + } + for (const auto& tc : tbl_cursors) { + if (tc.current.has_value() && byte_compare(tc.current->key, key_copy) == 0) { + pick_winner(*tc.current); + } + } + + const bool visible = winner.has_value() && !winner->erased; + if (visible) { + const std::size_t rec_bytes = key_copy.size() + winner->value.size(); + if (rec_bytes > m_page_bytes) { + if (page.entries.empty()) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::page_too_small, + std::format("Storage::Cursor entry size {} exceeds page_bytes {}", + rec_bytes, m_page_bytes))); + } + page.has_more = true; + break; + } + if (page.entries.size() >= m_page_rows || + (!page.entries.empty() && used_bytes + rec_bytes > m_page_bytes)) { + page.has_more = true; + break; + } + page.entries.push_back(ScanEntry{key_copy, winner->value, winner->sequence}); + used_bytes += rec_bytes; + m_resume_after = key_copy; + } else { + m_resume_after = key_copy; + } + + // Consume key_copy from every cursor positioned at it. + for (auto& mc : mem_cursors) { + if (mc.current.has_value() && byte_compare(mc.current->key, key_copy) == 0) { + mc.advance_to_next(snap_seq); + } + } + for (auto& tc : tbl_cursors) { + if (tc.current.has_value() && byte_compare(tc.current->key, key_copy) == 0) { + if (auto r = tc.advance(snap_seq); !r) { + return Void::Result::fail(std::move(r).error()); + } + } + } + } + + return page; + } + + // ── Engine ─────────────────────────────────────────────────────────────── + + Engine::Engine(std::shared_ptr control) noexcept + : m_control(std::move(control)) + { + } + + Engine::~Engine() + { + if (m_control) { + // Best-effort clean release if not explicitly closed; destructors cannot + // report flush errors, though active handles are closed cleanly. + m_control.reset(); + } + } + + Engine::Engine(Engine&&) noexcept = default; + Engine& Engine::operator=(Engine&&) noexcept = default; + + Result Engine::open(OpenOptions options) + { + if (options.directory.empty()) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::invalid_argument, "Storage::Engine::open: empty directory")); + } + if (auto vl = validate_limits(options.limits); !vl) { + return Void::Result::fail(std::move(vl).error()); + } + + auto port = options.file_port ? options.file_port : make_posix_file_port(); + if (auto ed = port->ensure_dir(options.directory); !ed) { + return Void::Result::fail(std::move(ed).error()); + } + auto lock = port->lock_directory(options.directory); + if (!lock) return Void::Result::fail(std::move(lock).error()); + + if (auto probe = port->probe_durability_capabilities(options.directory); !probe) { + return Void::Result::fail(std::move(probe).error()); + } + + auto cur_exists = port->exists(options.directory / "CURRENT"); + if (!cur_exists) return Void::Result::fail(std::move(cur_exists).error()); + + auto ctrl = std::make_shared(); + ctrl->options = std::move(options); + ctrl->port = std::move(port); + ctrl->dir_lock = std::move(*lock); + ctrl->active_memtable = std::make_shared(); + + if (!*cur_exists) { + // Check for orphan storage artifacts — never adopt an uncommitted highest manifest! + auto files = ctrl->port->list_dir(ctrl->options.directory); + if (!files) return Void::Result::fail(std::move(files).error()); + for (const auto& name : *files) { + if (name.starts_with("MANIFEST-") || + name.starts_with("WAL-") || + name.starts_with("TABLE-")) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::incomplete_init, + "Storage::Engine::open: directory contains storage artifacts without valid CURRENT; refusing orphan manifest adoption")); + } + } + + auto uuid_r = Void::Uuid::try_v4(); + if (!uuid_r) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::io_error, "Storage::Engine::open: UUID entropy unavailable")); + } + ctrl->db_uuid = *uuid_r; + ctrl->committed_seq = ctrl->options.initial_sequence; + ctrl->durable_seq = ctrl->options.initial_sequence; + ctrl->checkpoint_seq = ctrl->options.initial_sequence; + ctrl->generation = 1; + ctrl->active_wal_seg_id = 1; + ctrl->next_file_id = 2; + + // 1. Write & sync WAL segment 1 + WalSegmentHeader wsh; + wsh.database_uuid = ctrl->db_uuid; + wsh.segment_id = 1; + wsh.previous_segment_id = 0; + wsh.first_candidate_sequence = + ctrl->committed_seq < std::numeric_limits::max() + ? ctrl->committed_seq + 1 + : std::numeric_limits::max(); + auto wsh_bytes = encode_wal_segment_header(wsh); + if (!wsh_bytes) return Void::Result::fail(std::move(wsh_bytes).error()); + + const auto wal_path = ctrl->options.directory / make_wal_filename(1); + auto wf = ctrl->port->open_file(wal_path, FileOpenMode::CreateNew); + if (!wf) return Void::Result::fail(std::move(wf).error()); + if (auto w = (*wf)->append_all(*wsh_bytes); !w) return Void::Result::fail(std::move(w).error()); + if (auto s = (*wf)->sync(); !s) return Void::Result::fail(std::move(s).error()); + + ctrl->active_wal = std::move(*wf); + ctrl->active_wal_bytes = wsh_bytes->size(); + ctrl->wal_segments = {1}; + ctrl->wal_segment_sizes[1] = wsh_bytes->size(); + + // 2. Write & sync MANIFEST + CURRENT.tmp -> CURRENT + dir sync + ManifestData man; + man.database_uuid = ctrl->db_uuid; + man.generation = 1; + man.checkpoint_sequence = ctrl->checkpoint_seq; + man.next_sequence_hint = wsh.first_candidate_sequence; + man.next_file_id = 2; + man.wal_segments = {1}; + if (auto pub = ctrl->publish_manifest_and_current_locked(man); !pub) { + return Void::Result::fail(std::move(pub).error()); + } + ctrl->state = EngineState::Open; + return Engine{std::move(ctrl)}; + } + + // Existing database: validate CURRENT -> MANIFEST -> Tables -> WAL segments + const auto cur_path = ctrl->options.directory / "CURRENT"; + auto cur_sz = ctrl->port->file_size(cur_path); + if (!cur_sz) return Void::Result::fail(std::move(cur_sz).error()); + if (*cur_sz > 512) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::corrupt, "Storage CURRENT file exceeds maximum size")); + } + OwnedBytes cur_bytes(*cur_sz); + { + auto cf = ctrl->port->open_file(cur_path, FileOpenMode::ReadOnly); + if (!cf) return Void::Result::fail(std::move(cf).error()); + if (auto r = (*cf)->pread_exact(0, cur_bytes); !r) return Void::Result::fail(std::move(r).error()); + } + auto cur_ptr = decode_current(cur_bytes); + if (!cur_ptr) return Void::Result::fail(std::move(cur_ptr).error()); + + const auto man_path = ctrl->options.directory / cur_ptr->manifest_filename; + auto man_sz = ctrl->port->file_size(man_path); + if (!man_sz) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::corrupt, + std::format("Storage manifest '{}' referenced by CURRENT is missing or invalid", + cur_ptr->manifest_filename))); + } + if (*man_sz > ctrl->options.limits.max_manifest_bytes) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::corrupt, "Storage manifest exceeds max_manifest_bytes")); + } + OwnedBytes man_bytes(*man_sz); + { + auto mf = ctrl->port->open_file(man_path, FileOpenMode::ReadOnly); + if (!mf) return Void::Result::fail(std::move(mf).error()); + if (auto r = (*mf)->pread_exact(0, man_bytes); !r) return Void::Result::fail(std::move(r).error()); + } + auto man = decode_manifest( + man_bytes, + ctrl->options.limits.max_manifest_bytes, + ctrl->options.limits.max_manifest_tables, + ctrl->options.limits.max_key_bytes); + if (!man) return Void::Result::fail(std::move(man).error()); + + if (man->database_uuid != cur_ptr->database_uuid || + man->generation != cur_ptr->generation || + man->wal_segments.empty()) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::corrupt, "Storage MANIFEST metadata mismatches CURRENT")); + } + + ctrl->db_uuid = man->database_uuid; + ctrl->generation = man->generation; + ctrl->checkpoint_seq = man->checkpoint_sequence; + ctrl->committed_seq = man->checkpoint_sequence; + ctrl->durable_seq = man->checkpoint_sequence; + ctrl->next_file_id = man->next_file_id; + ctrl->wal_segments = man->wal_segments; + + // Ensure next_file_id skips any orphan WAL/TABLE file IDs left behind by a + // previously interrupted checkpoint/compaction before CURRENT updated. + if (auto dir_files = ctrl->port->list_dir(ctrl->options.directory); dir_files) { + auto parse_hex_id = [](std::string_view fname, std::string_view prefix, std::string_view suffix) -> std::optional { + if (!fname.starts_with(prefix) || !fname.ends_with(suffix)) return std::nullopt; + const auto hex = fname.substr(prefix.size(), fname.size() - prefix.size() - suffix.size()); + if (hex.empty() || hex.size() > 16) return std::nullopt; + std::uint64_t val = 0; + for (const char c : hex) { + val <<= 4; + if (c >= '0' && c <= '9') val |= static_cast(c - '0'); + else if (c >= 'A' && c <= 'F') val |= static_cast(c - 'A' + 10); + else if (c >= 'a' && c <= 'f') val |= static_cast(c - 'a' + 10); + else return std::nullopt; + } + return val; + }; + for (const auto& fn : *dir_files) { + if (auto wid = parse_hex_id(fn, "WAL-", ".vwal"); wid && *wid >= ctrl->next_file_id) { + ctrl->next_file_id = *wid + 1; + } + if (auto tid = parse_hex_id(fn, "TABLE-", ".vtbl"); tid && *tid >= ctrl->next_file_id) { + ctrl->next_file_id = *tid + 1; + } + } + } + + // Open immutable tables referenced by manifest. + ctrl->active_tables.reserve(man->tables.size()); + for (const auto& tm : man->tables) { + auto tr = detail::TableReader::open( + ctrl->port, + ctrl->options.directory / make_table_filename(tm.table_id), + ctrl->db_uuid, + tm, + ctrl->options.limits); + if (!tr) return Void::Result::fail(std::move(tr).error()); + ctrl->active_tables.push_back(std::move(*tr)); + } + + // Verify and replay WAL segments in manifest order. + Sequence prev_batch_seq = 0; + for (std::size_t i = 0; i < man->wal_segments.size(); ++i) { + const std::uint64_t seg_id = man->wal_segments[i]; + if (i > 0 && seg_id <= man->wal_segments[i - 1]) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::corrupt, "Manifest WAL segments not strictly increasing")); + } + const auto seg_path = ctrl->options.directory / make_wal_filename(seg_id); + const bool is_final = (i + 1 == man->wal_segments.size()); + std::optional exp_prev = + (i > 0) ? std::optional{man->wal_segments[i - 1]} + : (seg_id == 1 ? std::optional{0} : std::nullopt); + auto scan = detail::scan_wal_segment( + *ctrl->port, + seg_path, + ctrl->db_uuid, + seg_id, + exp_prev, + is_final, + ctrl->options.limits, + true); + if (!scan) return Void::Result::fail(std::move(scan).error()); + + std::uint64_t effective_seg_sz = scan->file_size; + if (scan->truncate_offset.has_value()) { + const std::uint64_t trunc_at = *scan->truncate_offset; + auto wf = ctrl->port->open_file(seg_path, FileOpenMode::ReadWriteExisting); + if (!wf) return Void::Result::fail(std::move(wf).error()); + if (auto tr = (*wf)->truncate(trunc_at); !tr) return Void::Result::fail(std::move(tr).error()); + if (auto sy = (*wf)->sync(); !sy) return Void::Result::fail(std::move(sy).error()); + if (auto cl = (*wf)->close(); !cl) return Void::Result::fail(std::move(cl).error()); + ctrl->recovery_truncated_bytes += (scan->file_size - trunc_at); + effective_seg_sz = trunc_at; + } + ctrl->wal_segment_sizes[seg_id] = effective_seg_sz; + + for (const auto& batch : scan->batches) { + if (prev_batch_seq != 0 && batch.sequence != prev_batch_seq + 1) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::corrupt, + std::format("WAL batch sequence gap: expected {}, got {}", + prev_batch_seq + 1, batch.sequence))); + } + prev_batch_seq = batch.sequence; + if (batch.sequence <= ctrl->checkpoint_seq) { + continue; + } + if (batch.sequence != ctrl->committed_seq + 1) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::corrupt, + std::format("WAL redo sequence gap above checkpoint: expected {}, got {}", + ctrl->committed_seq + 1, batch.sequence))); + } + for (const auto& rec : batch.entries) { + auto node = std::make_shared(); + node->seq = rec.sequence; + node->erased = rec.erased; + node->value = rec.value; + auto it = ctrl->active_memtable->map.find(ByteView{rec.key}); + if (it == ctrl->active_memtable->map.end()) { + ctrl->active_memtable->map.emplace(rec.key, std::move(node)); + } else { + node->next = it->second; + it->second = std::move(node); + } + ctrl->active_memtable->approx_bytes += 64 + rec.key.size() + rec.value.size(); + } + ctrl->committed_seq = batch.sequence; + ctrl->durable_seq = batch.sequence; + } + } + + // Open final WAL segment for appending. + ctrl->active_wal_seg_id = man->wal_segments.back(); + const auto active_wal_path = + ctrl->options.directory / make_wal_filename(ctrl->active_wal_seg_id); + auto awf = ctrl->port->open_file(active_wal_path, FileOpenMode::ReadWriteExisting); + if (!awf) return Void::Result::fail(std::move(awf).error()); + ctrl->active_wal = std::move(*awf); + ctrl->active_wal_bytes = ctrl->wal_segment_sizes[ctrl->active_wal_seg_id]; + ctrl->state = EngineState::Open; + return Engine{std::move(ctrl)}; + } + + Result Engine::snapshot() + { + if (!m_control || m_control->state == EngineState::Closed) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::closed, "Storage::Engine::snapshot on closed engine")); + } + + std::shared_lock v_lk{m_control->vis_mu}; + std::lock_guard p_lk{m_control->pin_mu}; + if (m_control->live_pins.size() >= m_control->options.limits.max_snapshots) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::overloaded, + "Storage::Engine::snapshot exceeded max_snapshots")); + } + + auto view = std::make_shared(); + view->generation = m_control->generation; + view->checkpoint_seq = m_control->checkpoint_seq; + view->active_at_capture = m_control->active_memtable; + view->frozen = m_control->frozen_memtables; + view->tables = m_control->active_tables; + + const Sequence seq = m_control->committed_seq; + const std::uint64_t pin_id = m_control->next_pin_id++; + m_control->live_pins.emplace( + pin_id, detail::SnapshotPinInfo{view->generation, seq}); + + return Snapshot{m_control, std::move(view), seq, pin_id}; + } + + Result Engine::get(const Snapshot& snap, ByteView key) const + { + if (!snap.valid() || !m_control || snap.m_control.get() != m_control.get()) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::invalid_argument, + "Storage::Engine::get: invalid or foreign snapshot")); + } + if (m_control->state == EngineState::Closed) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::closed, "Storage::Engine::get on closed engine")); + } + if (key.size() > m_control->options.limits.max_key_bytes) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::invalid_argument, "Storage::Engine::get: key exceeds max_key_bytes")); + } + + auto res = m_control->lookup_latest_in_source( + *snap.m_view, snap.sequence(), key, true); + if (!res) return Void::Result::fail(std::move(res).error()); + if (!res->has_value() || (*res)->erased) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::not_found, "Storage::Engine::get: key not found")); + } + return OwnedValue{(*res)->value, (*res)->sequence}; + } + + Result Engine::scan(Snapshot snap, ScanBounds bounds) const + { + if (!snap.valid() || !m_control || snap.m_control.get() != m_control.get()) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::invalid_argument, + "Storage::Engine::scan: invalid or foreign snapshot")); + } + if (m_control->state == EngineState::Closed) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::closed, "Storage::Engine::scan on closed engine")); + } + const auto& lim = m_control->options.limits; + const std::size_t p_bytes = + bounds.page_bytes == 0 ? lim.default_scan_page_bytes : bounds.page_bytes; + const std::size_t p_rows = + bounds.page_rows == 0 ? lim.default_scan_page_rows : bounds.page_rows; + if (p_bytes > lim.max_scan_page_bytes) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::invalid_argument, + "Storage::Engine::scan: page_bytes exceeds max_scan_page_bytes")); + } + if (bounds.begin.has_value() && bounds.begin->size() > lim.max_key_bytes) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::invalid_argument, "Storage::Engine::scan: begin key exceeds max_key_bytes")); + } + if (bounds.end.has_value() && bounds.end->size() > lim.max_key_bytes) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::invalid_argument, "Storage::Engine::scan: end key exceeds max_key_bytes")); + } + + std::uint64_t prev = m_control->live_cursors.load(std::memory_order_acquire); + for (;;) { + if (prev >= lim.max_cursors) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::overloaded, "Storage::Engine::scan: max_cursors exceeded")); + } + if (m_control->live_cursors.compare_exchange_weak( + prev, prev + 1, std::memory_order_acq_rel, std::memory_order_acquire)) { + break; + } + } + + const auto cid = m_control->next_cursor_id++; + return Cursor{std::move(snap), std::move(bounds), p_bytes, p_rows, cid}; + } + + std::expected Engine::write( + Batch batch, + Durability durability) + { + auto fail_nc = [](StorageErrorCode code, std::string msg) { + return std::unexpected{WriteFailure{ + StorageError{code, make_storage_error(code, std::move(msg))}, + Outcome::NotCommitted}}; + }; + + if (!m_control || m_control->state == EngineState::Closed) { + return fail_nc(StorageErrorCode::closed, "Storage::Engine::write on closed engine"); + } + if (m_control->state == EngineState::RecoveryRequired) { + return fail_nc(StorageErrorCode::recovery_required, + "Storage::Engine::write halted: RecoveryRequired"); + } + + const auto& lim = m_control->options.limits; + if (auto vb = batch.validate(lim); !vb) { + const auto code = static_cast(vb.error().code().value); + return std::unexpected{WriteFailure{ + StorageError{code, std::move(vb).error()}, Outcome::NotCommitted}}; + } + + std::lock_guard w_lk{m_control->writer_mu}; + if (m_control->state != EngineState::Open) { + const auto code = (m_control->state == EngineState::RecoveryRequired) + ? StorageErrorCode::recovery_required + : StorageErrorCode::closed; + return fail_nc(code, "Storage::Engine::write unavailable in current state"); + } + if (m_control->committed_seq == std::numeric_limits::max()) { + return fail_nc(StorageErrorCode::sequence_exhausted, + "Storage::Engine::write: 64-bit sequence counter exhausted"); + } + if (m_control->obsolete_pinned_bytes >= lim.max_obsolete_pinned_bytes) { + return fail_nc(StorageErrorCode::overloaded, + "Storage::Engine::write paused: obsolete pinned bytes exceed limit"); + } + if (m_control->active_tables.size() > lim.max_active_runs) { + return fail_nc(StorageErrorCode::overloaded, + "Storage::Engine::write paused: active runs exceed max_active_runs"); + } + + // Evaluate all preconditions against latest committed state BEFORE allocating/logging. + { + detail::SourceView latest_view; + { + std::shared_lock v_lk{m_control->vis_mu}; + latest_view.active_at_capture = m_control->active_memtable; + latest_view.frozen = m_control->frozen_memtables; + latest_view.tables = m_control->active_tables; + } + for (const auto& cond : batch.preconditions()) { + auto cur = m_control->lookup_latest_in_source( + latest_view, m_control->committed_seq, cond.key, false); + if (!cur) { + const auto code = static_cast(cur.error().code().value); + return std::unexpected{WriteFailure{ + StorageError{code, std::move(cur).error()}, Outcome::NotCommitted}}; + } + const bool exists_live = cur->has_value() && !(*cur)->erased; + bool matched = false; + switch (cond.kind) { + case PreconditionKind::Absent: + matched = !exists_live; + break; + case PreconditionKind::VersionEquals: + matched = exists_live && (*cur)->sequence == cond.expected_version; + break; + case PreconditionKind::ValueEquals: + matched = exists_live && (*cur)->value == cond.expected_value; + break; + } + if (!matched) { + return fail_nc(StorageErrorCode::conflict, + "Storage::Engine::write: batch precondition failed"); + } + } + } + + const Sequence next_seq = m_control->committed_seq + 1; + + // Pre-encode complete WAL batch BEFORE touching disk. + std::uint64_t total_op_bytes = 0; + for (const auto& m : batch.mutations()) { + total_op_bytes += m.key.size() + m.value.size(); + } + + Void::Binary::ByteBuffer wal_buf{ + lim.max_batch_encoded_bytes, m_control->options.memory_resource}; + std::uint32_t agg_crc = crc32c_init(); + + auto bp = encode_wal_begin_payload(WalBeginPayload{ + static_cast(batch.mutations().size()), total_op_bytes}); + if (!bp) return fail_nc(StorageErrorCode::invalid_argument, bp.error().message()); + auto begin_frame = encode_wal_record_frame(WalRecordType::Begin, next_seq, 0, *bp); + if (!begin_frame) return fail_nc(StorageErrorCode::invalid_argument, begin_frame.error().message()); + agg_crc = crc32c_update(agg_crc, *begin_frame); + if (auto a = wal_buf.append(*begin_frame); !a) { + return fail_nc(StorageErrorCode::quota_exceeded, "Batch encoded size exceeds max_batch_encoded_bytes"); + } + + std::uint32_t ord = 1; + for (const auto& m : batch.mutations()) { + const bool is_erase = (m.kind == MutationKind::Erase); + auto mp = encode_wal_mutation_payload(is_erase, m.key, m.value); + if (!mp) return fail_nc(StorageErrorCode::invalid_argument, mp.error().message()); + auto m_frame = encode_wal_record_frame( + is_erase ? WalRecordType::Erase : WalRecordType::Put, next_seq, ord++, *mp); + if (!m_frame) return fail_nc(StorageErrorCode::invalid_argument, m_frame.error().message()); + agg_crc = crc32c_update(agg_crc, *m_frame); + if (auto a = wal_buf.append(*m_frame); !a) { + return fail_nc(StorageErrorCode::quota_exceeded, "Batch encoded size exceeds max_batch_encoded_bytes"); + } + } + + auto cp = encode_wal_commit_payload(WalCommitPayload{ + static_cast(batch.mutations().size()), + total_op_bytes, + crc32c_finalize(agg_crc)}); + if (!cp) return fail_nc(StorageErrorCode::invalid_argument, cp.error().message()); + auto commit_frame = encode_wal_record_frame(WalRecordType::Commit, next_seq, ord, *cp); + if (!commit_frame) return fail_nc(StorageErrorCode::invalid_argument, commit_frame.error().message()); + if (auto a = wal_buf.append(*commit_frame); !a) { + return fail_nc(StorageErrorCode::quota_exceeded, "Batch encoded size exceeds max_batch_encoded_bytes"); + } + + const auto wal_bytes = wal_buf.view(); + const auto total_wal = m_control->total_wal_bytes_locked(); + if (total_wal + wal_bytes.size() > lim.max_wal_total_bytes) { + return fail_nc(StorageErrorCode::quota_exceeded, + "Storage::Engine::write: max_wal_total_bytes exceeded"); + } + + // Pre-allocate EVERY VersionNode AND std::map node handle BEFORE emitting WAL bytes + // so visibility publication below performs ZERO heap allocations! + struct PreparedUpdate { + std::shared_ptr node{}; + detail::MemMap::node_type map_node{}; + detail::MemMap::iterator existing_it{}; + bool is_new_key{false}; + std::uint64_t added_bytes{0}; + }; + std::vector prepared; + try { + prepared.reserve(batch.mutations().size()); + detail::MemMap scratch_alloc_map; + std::shared_lock v_lk{m_control->vis_mu}; + auto& cur_map = m_control->active_memtable->map; + for (const auto& m : batch.mutations()) { + PreparedUpdate pu; + pu.node = std::make_shared(); + pu.node->seq = next_seq; + pu.node->erased = (m.kind == MutationKind::Erase); + pu.node->value = m.value; + pu.added_bytes = 64 + m.key.size() + m.value.size(); + + auto it = cur_map.find(ByteView{m.key}); + if (it == cur_map.end()) { + pu.is_new_key = true; + auto [tmp_it, _] = scratch_alloc_map.emplace(m.key, nullptr); + pu.map_node = scratch_alloc_map.extract(tmp_it); + } else { + pu.is_new_key = false; + pu.existing_it = it; + } + prepared.push_back(std::move(pu)); + } + } catch (const std::bad_alloc&) { + return fail_nc(StorageErrorCode::quota_exceeded, + "Storage::Engine::write: memory allocation failed before WAL"); + } + + // Rotate WAL segment first if appending would exceed wal_segment_target_bytes + // (only when current segment already contains batches). + if (m_control->active_wal_bytes > kWalSegmentHeaderSize && + m_control->active_wal_bytes + wal_bytes.size() > lim.wal_segment_target_bytes) { + if (auto s = m_control->active_wal->sync(); !s) { + m_control->state = EngineState::RecoveryRequired; + const auto code = static_cast(s.error().code().value); + return std::unexpected{WriteFailure{ + StorageError{code, std::move(s).error()}, Outcome::Unknown}}; + } + + const std::uint64_t new_seg_id = m_control->next_file_id++; + const std::uint64_t new_gen = m_control->generation + 1; + WalSegmentHeader wsh; + wsh.database_uuid = m_control->db_uuid; + wsh.segment_id = new_seg_id; + wsh.previous_segment_id = m_control->active_wal_seg_id; + wsh.first_candidate_sequence = next_seq; + auto wsh_bytes = encode_wal_segment_header(wsh); + if (!wsh_bytes) { + return fail_nc(StorageErrorCode::invalid_argument, wsh_bytes.error().message()); + } + const auto new_wal_path = + m_control->options.directory / make_wal_filename(new_seg_id); + auto nwf = m_control->port->open_file(new_wal_path, FileOpenMode::CreateNew); + if (!nwf) { + return fail_nc(static_cast(nwf.error().code().value), + nwf.error().message()); + } + if (auto w = (*nwf)->append_all(*wsh_bytes); !w) { + (void)m_control->port->unlink_file(new_wal_path); + return fail_nc(StorageErrorCode::io_error, w.error().message()); + } + if (auto s = (*nwf)->sync(); !s) { + (void)m_control->port->unlink_file(new_wal_path); + return fail_nc(StorageErrorCode::io_error, s.error().message()); + } + + // Publish new segment in manifest + CURRENT BEFORE writing any batch to it! + ManifestData man; + man.database_uuid = m_control->db_uuid; + man.generation = new_gen; + man.checkpoint_sequence = m_control->checkpoint_seq; + man.next_sequence_hint = next_seq; + man.next_file_id = m_control->next_file_id; + man.wal_segments = m_control->wal_segments; + man.wal_segments.push_back(new_seg_id); + for (const auto& t : m_control->active_tables) { + man.tables.push_back(t->meta()); + } + if (auto pub = m_control->publish_manifest_and_current_locked(man); !pub) { + // If publish fails on CURRENT rename or sync_dir, fail safe (NotCommitted since + // batch hasn't been written to WAL yet, though maintenance may leave orphan WAL). + const auto code = static_cast(pub.error().code().value); + if (code == StorageErrorCode::io_error) { + m_control->state = EngineState::RecoveryRequired; + return std::unexpected{WriteFailure{ + StorageError{code, std::move(pub).error()}, Outcome::Unknown}}; + } + return std::unexpected{WriteFailure{ + StorageError{code, std::move(pub).error()}, Outcome::NotCommitted}}; + } + + (void)m_control->active_wal->close(); + m_control->active_wal = std::move(*nwf); + m_control->active_wal_seg_id = new_seg_id; + m_control->active_wal_bytes = wsh_bytes->size(); + m_control->wal_segments.push_back(new_seg_id); + m_control->wal_segment_sizes[new_seg_id] = wsh_bytes->size(); + m_control->generation = new_gen; + } + + // Emit WAL bytes. Any failure from this point onward produces Outcome::Unknown + // and enters RecoveryRequired! + auto app_r = m_control->active_wal->append_all(wal_bytes); + if (!app_r) { + m_control->state = EngineState::RecoveryRequired; + const auto code = static_cast(app_r.error().code().value); + return std::unexpected{WriteFailure{ + StorageError{code, std::move(app_r).error()}, Outcome::Unknown}}; + } + m_control->active_wal_bytes += wal_bytes.size(); + m_control->wal_segment_sizes[m_control->active_wal_seg_id] = m_control->active_wal_bytes; + + if (durability == Durability::Sync) { + if (auto sy = m_control->active_wal->sync(); !sy) { + m_control->state = EngineState::RecoveryRequired; + const auto code = static_cast(sy.error().code().value); + return std::unexpected{WriteFailure{ + StorageError{code, std::move(sy).error()}, Outcome::Unknown}}; + } + } + + // Infallible index publication under visibility lock (ZERO allocations!). + { + std::unique_lock v_lk{m_control->vis_mu}; + auto& mt = *m_control->active_memtable; + for (auto& pu : prepared) { + if (pu.is_new_key) { + pu.map_node.mapped() = std::move(pu.node); + mt.map.insert(std::move(pu.map_node)); + } else { + pu.node->next = pu.existing_it->second; + pu.existing_it->second = std::move(pu.node); + } + mt.approx_bytes += pu.added_bytes; + } + if (mt.min_seq == 0) mt.min_seq = next_seq; + mt.max_seq = next_seq; + m_control->committed_seq = next_seq; + if (durability == Durability::Sync) { + m_control->durable_seq = next_seq; + } + } + + return CommitReceipt{next_seq, durability}; + } + + Result Engine::sync() + { + if (!m_control || m_control->state == EngineState::Closed) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::closed, "Storage::Engine::sync on closed engine")); + } + if (m_control->state == EngineState::RecoveryRequired) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::recovery_required, "Storage::Engine::sync: RecoveryRequired")); + } + std::lock_guard w_lk{m_control->writer_mu}; + if (!m_control->active_wal) return {}; + if (auto sy = m_control->active_wal->sync(); !sy) { + m_control->state = EngineState::RecoveryRequired; + return sy; + } + m_control->durable_seq = m_control->committed_seq; + return {}; + } + + Result Engine::checkpoint() + { + if (!m_control || m_control->state == EngineState::Closed) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::closed, "Storage::Engine::checkpoint on closed engine")); + } + if (m_control->state == EngineState::RecoveryRequired) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::recovery_required, "Storage::Engine::checkpoint: RecoveryRequired")); + } + + std::lock_guard m_lk{m_control->maint_mu}; + std::lock_guard w_lk{m_control->writer_mu}; + if (m_control->state != EngineState::Open) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::recovery_required, "Storage::Engine::checkpoint unavailable")); + } + + // Sync active WAL first so buffered batches are durable before checkpointing. + if (m_control->active_wal) { + if (auto sy = m_control->active_wal->sync(); !sy) { + m_control->state = EngineState::RecoveryRequired; + return sy; + } + m_control->durable_seq = m_control->committed_seq; + } + + // Freeze active_memtable under visibility lock. + std::shared_ptr freezing; + Sequence snap_ckpt_seq = m_control->committed_seq; + { + std::unique_lock v_lk{m_control->vis_mu}; + if (m_control->active_memtable->map.empty() && m_control->frozen_memtables.empty()) { + return {}; + } + freezing = std::move(m_control->active_memtable); + m_control->active_memtable = std::make_shared(); + m_control->frozen_memtables.push_back(freezing); + } + + // Collect sorted entries across all frozen memtables. + std::vector entries; + for (const auto& fm : m_control->frozen_memtables) { + for (const auto& [k, head] : fm->map) { + for (auto node = head; node != nullptr; node = node->next) { + entries.push_back(TableEntryRecord{k, node->seq, node->erased, node->value}); + } + } + } + std::sort(entries.begin(), entries.end(), [](const TableEntryRecord& a, const TableEntryRecord& b) { + const int kc = byte_compare(a.key, b.key); + if (kc != 0) return kc < 0; + return a.sequence > b.sequence; + }); + + const std::uint64_t new_table_id = m_control->next_file_id++; + const std::uint64_t new_wal_seg_id = m_control->next_file_id++; + const std::uint64_t new_gen = m_control->generation + 1; + + std::shared_ptr new_table; + if (!entries.empty()) { + const auto tmp_tbl = + m_control->options.directory / (make_table_filename(new_table_id) + ".tmp"); + const auto final_tbl = + m_control->options.directory / make_table_filename(new_table_id); + auto tm = detail::write_sorted_table( + *m_control->port, tmp_tbl, final_tbl, + m_control->db_uuid, new_table_id, 0, entries, m_control->options.limits); + if (!tm) { + return Void::Result::fail(std::move(tm).error()); + } + auto tr = detail::TableReader::open( + m_control->port, final_tbl, m_control->db_uuid, *tm, m_control->options.limits); + if (!tr) return Void::Result::fail(std::move(tr).error()); + new_table = std::move(*tr); + } + + // Create new WAL segment before publishing new manifest. + WalSegmentHeader wsh; + wsh.database_uuid = m_control->db_uuid; + wsh.segment_id = new_wal_seg_id; + wsh.previous_segment_id = m_control->active_wal_seg_id; + wsh.first_candidate_sequence = + snap_ckpt_seq < std::numeric_limits::max() + ? snap_ckpt_seq + 1 + : std::numeric_limits::max(); + auto wsh_bytes = encode_wal_segment_header(wsh); + if (!wsh_bytes) return Void::Result::fail(std::move(wsh_bytes).error()); + const auto new_wal_path = m_control->options.directory / make_wal_filename(new_wal_seg_id); + auto nwf = m_control->port->open_file(new_wal_path, FileOpenMode::CreateNew); + if (!nwf) return Void::Result::fail(std::move(nwf).error()); + if (auto w = (*nwf)->append_all(*wsh_bytes); !w) { + (void)m_control->port->unlink_file(new_wal_path); + return Void::Result::fail(std::move(w).error()); + } + if (auto sy = (*nwf)->sync(); !sy) { + (void)m_control->port->unlink_file(new_wal_path); + return sy; + } + if (auto sd = m_control->port->sync_dir(m_control->options.directory); !sd) { + return sd; + } + + ManifestData man; + man.database_uuid = m_control->db_uuid; + man.generation = new_gen; + man.checkpoint_sequence = snap_ckpt_seq; + man.next_sequence_hint = wsh.first_candidate_sequence; + man.next_file_id = m_control->next_file_id; + for (const auto& t : m_control->active_tables) { + man.tables.push_back(t->meta()); + } + if (new_table) { + man.tables.push_back(new_table->meta()); + } + man.wal_segments = {new_wal_seg_id}; + + if (auto pub = m_control->publish_manifest_and_current_locked(man); !pub) { + // If CURRENT rename/sync failed at boundary, old generation remains authoritative + // OR state becomes RecoveryRequired if rename status unknown. + m_control->state = EngineState::RecoveryRequired; + return pub; + } + + // Publish new in-memory source set! + std::vector old_wal_segs; + { + std::unique_lock v_lk{m_control->vis_mu}; + if (new_table) { + m_control->active_tables.push_back(std::move(new_table)); + } + m_control->frozen_memtables.clear(); + m_control->checkpoint_seq = snap_ckpt_seq; + m_control->generation = new_gen; + old_wal_segs = std::move(m_control->wal_segments); + m_control->wal_segments = {new_wal_seg_id}; + } + + if (m_control->active_wal) { + (void)m_control->active_wal->close(); + } + m_control->active_wal = std::move(*nwf); + m_control->active_wal_seg_id = new_wal_seg_id; + m_control->active_wal_bytes = wsh_bytes->size(); + + for (const auto seg_id : old_wal_segs) { + const auto sz = m_control->wal_segment_sizes[seg_id]; + m_control->wal_segment_sizes.erase(seg_id); + m_control->obsolete_files.push_back(detail::ObsoleteFile{ + m_control->options.directory / make_wal_filename(seg_id), + sz, + new_gen}); + m_control->obsolete_pinned_bytes += sz; + } + m_control->wal_segment_sizes[new_wal_seg_id] = wsh_bytes->size(); + + m_control->reclaim_obsolete_locked(); + return {}; + } + + Result Engine::compact() + { + if (!m_control || m_control->state == EngineState::Closed) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::closed, "Storage::Engine::compact on closed engine")); + } + if (m_control->state == EngineState::RecoveryRequired) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::recovery_required, "Storage::Engine::compact: RecoveryRequired")); + } + + std::lock_guard m_lk{m_control->maint_mu}; + std::vector> inputs; + std::vector> remaining_tables; + { + std::shared_lock v_lk{m_control->vis_mu}; + if (m_control->active_tables.size() < 2) { + return {}; + } + const std::size_t n = std::min( + m_control->options.limits.max_compaction_merge_runs, + m_control->active_tables.size()); + inputs.assign( + m_control->active_tables.begin(), + m_control->active_tables.begin() + static_cast(n)); + remaining_tables.assign( + m_control->active_tables.begin() + static_cast(n), + m_control->active_tables.end()); + } + + const bool includes_oldest_runs = remaining_tables.empty(); + Sequence oldest_pin_seq = std::numeric_limits::max(); + { + std::lock_guard p_lk{m_control->pin_mu}; + oldest_pin_seq = m_control->compute_oldest_pinned_seq_locked(); + } + + // Read all entries from inputs (bounded <= 4 tables). + std::vector all; + for (const auto& t : inputs) { + for (std::size_t bi = 0; bi < t->index().size(); ++bi) { + auto blk = t->read_block(bi); + if (!blk) return Void::Result::fail(std::move(blk).error()); + all.insert(all.end(), + std::make_move_iterator(blk->begin()), + std::make_move_iterator(blk->end())); + } + } + + std::sort(all.begin(), all.end(), [](const TableEntryRecord& a, const TableEntryRecord& b) { + const int kc = byte_compare(a.key, b.key); + if (kc != 0) return kc < 0; + return a.sequence > b.sequence; + }); + + // Version GC per key: keep all versions > oldest_pin_seq plus newest <= oldest_pin_seq; + // discard tombstones only when every older overlapping run is included and no live snapshot needs it. + std::vector merged; + merged.reserve(all.size()); + std::size_t i = 0; + while (i < all.size()) { + const ByteView cur_key = all[i].key; + std::size_t j = i; + while (j < all.size() && byte_compare(all[j].key, cur_key) == 0) { + ++j; + } + bool kept_below_pin = false; + for (std::size_t k = i; k < j; ++k) { + const auto& rec = all[k]; + if (rec.sequence > oldest_pin_seq) { + merged.push_back(rec); + } else if (!kept_below_pin) { + kept_below_pin = true; + // Can discard bottom-most tombstone only if NO remaining uncompacted table can hold an older version of this key. + bool maybe_older_exists = !includes_oldest_runs; + if (rec.erased && !maybe_older_exists) { + continue; + } + if (rec.erased) { + // Also check key ranges of remaining tables for tighter bound! + maybe_older_exists = false; + for (const auto& rem_t : remaining_tables) { + if (byte_compare(cur_key, rem_t->meta().min_key) >= 0 && + byte_compare(cur_key, rem_t->meta().max_key) <= 0 && + rem_t->meta().min_sequence < rec.sequence) { + maybe_older_exists = true; + break; + } + } + if (!maybe_older_exists) { + continue; + } + } + merged.push_back(rec); + } + } + i = j; + } + + std::uint64_t new_gen = 0; + std::shared_ptr out_table; + std::uint64_t out_table_id = 0; + { + std::lock_guard w_lk{m_control->writer_mu}; + out_table_id = m_control->next_file_id++; + } + if (!merged.empty()) { + const auto tmp_path = + m_control->options.directory / (make_table_filename(out_table_id) + ".tmp"); + const auto final_path = + m_control->options.directory / make_table_filename(out_table_id); + auto tm = detail::write_sorted_table( + *m_control->port, tmp_path, final_path, + m_control->db_uuid, out_table_id, 1, merged, m_control->options.limits); + if (!tm) return Void::Result::fail(std::move(tm).error()); + auto tr = detail::TableReader::open( + m_control->port, final_path, m_control->db_uuid, *tm, m_control->options.limits); + if (!tr) return Void::Result::fail(std::move(tr).error()); + out_table = std::move(*tr); + } + + { + std::lock_guard w_lk{m_control->writer_mu}; + new_gen = m_control->generation + 1; + ManifestData man; + man.database_uuid = m_control->db_uuid; + man.generation = new_gen; + man.checkpoint_sequence = m_control->checkpoint_seq; + man.next_sequence_hint = m_control->committed_seq + 1; + man.next_file_id = m_control->next_file_id; + man.wal_segments = m_control->wal_segments; + if (out_table) { + man.tables.push_back(out_table->meta()); + } + for (const auto& t : remaining_tables) { + man.tables.push_back(t->meta()); + } + if (auto pub = m_control->publish_manifest_and_current_locked(man); !pub) { + m_control->state = EngineState::RecoveryRequired; + return pub; + } + + { + std::unique_lock v_lk{m_control->vis_mu}; + std::vector> next_tables; + if (out_table) next_tables.push_back(std::move(out_table)); + next_tables.insert(next_tables.end(), remaining_tables.begin(), remaining_tables.end()); + m_control->active_tables = std::move(next_tables); + m_control->generation = new_gen; + } + } + + for (const auto& in_t : inputs) { + const auto sz = in_t->meta().file_size; + m_control->obsolete_files.push_back(detail::ObsoleteFile{ + in_t->path(), sz, new_gen}); + m_control->obsolete_pinned_bytes += sz; + } + inputs.clear(); // Drop local references before reclaiming if no live snapshot pins them! + m_control->reclaim_obsolete_locked(); + return {}; + } + + Result Engine::export_backup(const std::filesystem::path& destination) + { + if (!m_control || m_control->state == EngineState::Closed) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::closed, "Storage::Engine::export_backup on closed engine")); + } + if (destination.empty()) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::invalid_argument, "Storage::Engine::export_backup: empty destination")); + } + + // Pin current generation while copying so referenced tables/WAL are never deleted mid-copy! + auto snap = snapshot(); + if (!snap) return Void::Result::fail(std::move(snap).error()); + + std::lock_guard m_lk{m_control->maint_mu}; + std::error_code ec; + if (std::filesystem::exists(destination, ec) && + std::filesystem::equivalent(m_control->options.directory, destination, ec)) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::invalid_argument, + "Storage::Engine::export_backup: destination cannot be source directory")); + } + if (auto ed = m_control->port->ensure_dir(destination); !ed) return ed; + + // Read authoritative CURRENT and MANIFEST under maintenance lock. + const auto copy_file_synced = [&](const std::string& filename) -> Result { + const auto src = m_control->options.directory / filename; + const auto dst = destination / filename; + const auto dst_tmp = destination / (filename + ".tmp"); + auto sz = m_control->port->file_size(src); + if (!sz) return Void::Result::fail(std::move(sz).error()); + auto sf = m_control->port->open_file(src, FileOpenMode::ReadOnly); + if (!sf) return Void::Result::fail(std::move(sf).error()); + OwnedBytes buf(*sz); + if (*sz > 0) { + if (auto r = (*sf)->pread_exact(0, buf); !r) return r; + } + (void)m_control->port->unlink_file(dst_tmp); + auto df = m_control->port->open_file(dst_tmp, FileOpenMode::CreateNew); + if (!df) return Void::Result::fail(std::move(df).error()); + if (!buf.empty()) { + if (auto w = (*df)->append_all(buf); !w) return Void::Result::fail(std::move(w).error()); + } + if (auto sy = (*df)->sync(); !sy) return sy; + if (auto cl = (*df)->close(); !cl) return cl; + if (auto rn = m_control->port->rename_atomic(dst_tmp, dst); !rn) return rn; + return {}; + }; + + // Sync active WAL first so copied WAL captures up to committed durable prefix cleanly. + { + std::lock_guard w_lk{m_control->writer_mu}; + if (m_control->active_wal) { + if (auto sy = m_control->active_wal->sync(); !sy) return sy; + } + } + + auto cur_sz = m_control->port->file_size(m_control->options.directory / "CURRENT"); + if (!cur_sz) return Void::Result::fail(std::move(cur_sz).error()); + OwnedBytes cur_bytes(*cur_sz); + { + auto cf = m_control->port->open_file( + m_control->options.directory / "CURRENT", FileOpenMode::ReadOnly); + if (!cf) return Void::Result::fail(std::move(cf).error()); + if (auto r = (*cf)->pread_exact(0, cur_bytes); !r) return r; + } + auto cur = decode_current(cur_bytes); + if (!cur) return Void::Result::fail(std::move(cur).error()); + + auto man_sz = m_control->port->file_size( + m_control->options.directory / cur->manifest_filename); + if (!man_sz) return Void::Result::fail(std::move(man_sz).error()); + OwnedBytes man_bytes(*man_sz); + { + auto mf = m_control->port->open_file( + m_control->options.directory / cur->manifest_filename, FileOpenMode::ReadOnly); + if (!mf) return Void::Result::fail(std::move(mf).error()); + if (auto r = (*mf)->pread_exact(0, man_bytes); !r) return r; + } + auto man = decode_manifest( + man_bytes, + m_control->options.limits.max_manifest_bytes, + m_control->options.limits.max_manifest_tables, + m_control->options.limits.max_key_bytes); + if (!man) return Void::Result::fail(std::move(man).error()); + + for (const auto& t : man->tables) { + if (auto r = copy_file_synced(make_table_filename(t.table_id)); !r) return r; + } + for (const auto seg_id : man->wal_segments) { + if (auto r = copy_file_synced(make_wal_filename(seg_id)); !r) return r; + } + if (auto r = copy_file_synced(cur->manifest_filename); !r) return r; + if (auto r = copy_file_synced("CURRENT"); !r) return r; + return m_control->port->sync_dir(destination); + } + + Result Engine::close() + { + if (!m_control || m_control->state == EngineState::Closed) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::closed, "Storage::Engine already closed")); + } + + std::lock_guard m_lk{m_control->maint_mu}; + std::lock_guard w_lk{m_control->writer_mu}; + + if (m_control->live_cursors.load(std::memory_order_acquire) > 0) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::busy, + "Storage::Engine::close refused: live cursors still active")); + } + { + std::lock_guard p_lk{m_control->pin_mu}; + if (!m_control->live_pins.empty()) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::busy, + "Storage::Engine::close refused: live snapshots still active")); + } + } + + Result sync_res; + if (m_control->state == EngineState::Open && m_control->active_wal) { + sync_res = m_control->active_wal->sync(); + if (sync_res) { + m_control->durable_seq = m_control->committed_seq; + m_control->reclaim_obsolete_locked(); + } + } + if (m_control->active_wal) { + (void)m_control->active_wal->close(); + m_control->active_wal.reset(); + } + m_control->active_tables.clear(); + m_control->dir_lock.reset(); + m_control->state = EngineState::Closed; + return sync_res; + } + + EngineState Engine::state() const noexcept + { + return m_control ? m_control->state : EngineState::Closed; + } + + EngineStats Engine::stats() const noexcept + { + EngineStats st; + if (!m_control) return st; + st.state = m_control->state; + st.durable_sync_verified = m_control->durable_sync_verified; + st.recovery_truncated_bytes = m_control->recovery_truncated_bytes; + st.live_cursors = m_control->live_cursors.load(std::memory_order_acquire); + { + std::shared_lock v_lk{m_control->vis_mu}; + st.committed_sequence = m_control->committed_seq; + st.checkpoint_sequence = m_control->checkpoint_seq; + st.active_memtable_bytes = + m_control->active_memtable ? m_control->active_memtable->approx_bytes : 0; + st.total_memtable_bytes = st.active_memtable_bytes; + for (const auto& fm : m_control->frozen_memtables) { + st.total_memtable_bytes += fm->approx_bytes; + } + st.active_table_count = m_control->active_tables.size(); + st.total_table_bytes = m_control->total_table_bytes_locked(); + } + { + std::lock_guard p_lk{m_control->pin_mu}; + st.live_snapshots = m_control->live_pins.size(); + if (!m_control->live_pins.empty()) { + st.oldest_snapshot_sequence = m_control->compute_oldest_pinned_seq_locked(); + } + } + if (std::unique_lock m_lk{m_control->maint_mu, std::try_to_lock}; m_lk.owns_lock()) { + st.obsolete_pinned_bytes = m_control->obsolete_pinned_bytes; + } + if (std::unique_lock w_lk{m_control->writer_mu, std::try_to_lock}; w_lk.owns_lock()) { + st.wal_total_bytes = m_control->total_wal_bytes_locked(); + } + return st; + } + + Durability Engine::default_durability() const noexcept + { + return m_control ? m_control->options.default_durability : Durability::Sync; + } + + const Limits& Engine::limits() const noexcept + { + static const Limits kDefaultLimits{}; + return m_control ? m_control->options.limits : kDefaultLimits; + } + +} // namespace Void::Storage diff --git a/src/Storage/FilePort.cpp b/src/Storage/FilePort.cpp new file mode 100644 index 0000000..82e21d6 --- /dev/null +++ b/src/Storage/FilePort.cpp @@ -0,0 +1,681 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Storage +{ + namespace + { + [[nodiscard]] StorageErrorCode map_errno(int err) noexcept + { + switch (err) { + case ENOENT: + return StorageErrorCode::not_found; + case EAGAIN: +#if EWOULDBLOCK != EAGAIN + case EWOULDBLOCK: +#endif + case EBUSY: + return StorageErrorCode::busy; + case EEXIST: + return StorageErrorCode::conflict; + case ENOSYS: + case EOPNOTSUPP: +#if ENOTSUP != EOPNOTSUPP + case ENOTSUP: +#endif + return StorageErrorCode::unsupported_capability; + case ENOSPC: + case EDQUOT: + return StorageErrorCode::quota_exceeded; + case EINVAL: + return StorageErrorCode::invalid_argument; + default: + return StorageErrorCode::io_error; + } + } + + [[nodiscard]] Error errno_error(std::string_view op, const std::filesystem::path& p, int err) + { + return make_storage_error( + map_errno(err), + std::format("Storage: {} '{}' failed: {}", op, p.string(), std::strerror(err)), + std::error_code{err, std::generic_category()}); + } + + class PosixDirLock final : public DirLockHandle + { + public: + explicit PosixDirLock(int fd) noexcept : m_fd(fd) {} + ~PosixDirLock() override + { + if (m_fd >= 0) { + ::flock(m_fd, LOCK_UN); + ::close(m_fd); + m_fd = -1; + } + } + + private: + int m_fd{-1}; + }; + + class PosixFileHandle final : public FileHandle + { + public: + PosixFileHandle(int fd, std::filesystem::path path, std::uint64_t initial_size) noexcept + : m_fd(fd), m_path(std::move(path)), m_append_pos(initial_size) + { + } + + ~PosixFileHandle() override + { + if (m_fd >= 0) { + ::close(m_fd); + m_fd = -1; + } + } + + Result pread(std::uint64_t offset, std::span out) override + { + if (m_fd < 0) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::closed, "Storage: pread on closed handle")); + } + std::size_t total = 0; + while (total < out.size()) { + const ssize_t n = ::pread( + m_fd, + out.data() + total, + out.size() - total, + static_cast(offset + total)); + if (n > 0) { + total += static_cast(n); + } else if (n == 0) { + break; + } else if (errno == EINTR) { + continue; + } else { + return Void::Result::fail(errno_error("pread", m_path, errno)); + } + } + return total; + } + + Result pread_exact(std::uint64_t offset, std::span out) override + { + auto r = pread(offset, out); + if (!r) return Void::Result::fail(std::move(r).error()); + if (*r != out.size()) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::corrupt, + std::format("Storage: short pread on '{}' at offset {} (wanted {}, got {})", + m_path.string(), offset, out.size(), *r))); + } + return {}; + } + + Result pwrite_all(std::uint64_t offset, ByteView data) override + { + if (m_fd < 0) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::closed, "Storage: pwrite_all on closed handle")); + } + std::size_t total = 0; + while (total < data.size()) { + const ssize_t n = ::pwrite( + m_fd, + data.data() + total, + data.size() - total, + static_cast(offset + total)); + if (n > 0) { + total += static_cast(n); + } else if (n < 0 && errno == EINTR) { + continue; + } else { + const int err = (n < 0) ? errno : EIO; + return Void::Result::fail(errno_error("pwrite", m_path, err)); + } + } + return {}; + } + + Result append_all(ByteView data) override + { + std::lock_guard lk{m_mu}; + if (m_fd < 0) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::closed, "Storage: append_all on closed handle")); + } + const std::uint64_t start = m_append_pos; + auto w = pwrite_all(start, data); + if (!w) { + // Refresh actual size from fstat so partial failures keep accurate EOF. + struct stat st {}; + if (::fstat(m_fd, &st) == 0 && st.st_size >= 0) { + m_append_pos = static_cast(st.st_size); + } + return Void::Result::fail(std::move(w).error()); + } + m_append_pos = start + data.size(); + return start; + } + + Result sync() override + { + if (m_fd < 0) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::closed, "Storage: sync on closed handle")); + } + for (;;) { + if (::fsync(m_fd) == 0) { + return {}; + } + if (errno == EINTR) { + continue; + } + return Void::Result::fail(errno_error("fsync", m_path, errno)); + } + } + + Result truncate(std::uint64_t new_size) override + { + std::lock_guard lk{m_mu}; + if (m_fd < 0) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::closed, "Storage: truncate on closed handle")); + } + for (;;) { + if (::ftruncate(m_fd, static_cast(new_size)) == 0) { + m_append_pos = new_size; + return {}; + } + if (errno == EINTR) { + continue; + } + return Void::Result::fail(errno_error("ftruncate", m_path, errno)); + } + } + + Result size() const override + { + if (m_fd < 0) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::closed, "Storage: size on closed handle")); + } + struct stat st {}; + if (::fstat(m_fd, &st) != 0) { + return Void::Result::fail(errno_error("fstat", m_path, errno)); + } + return st.st_size >= 0 ? static_cast(st.st_size) : 0ULL; + } + + Result close() override + { + std::lock_guard lk{m_mu}; + if (m_fd < 0) { + return {}; + } + const int rc = ::close(m_fd); + m_fd = -1; + if (rc != 0) { + return Void::Result::fail(errno_error("close", m_path, errno)); + } + return {}; + } + + private: + mutable std::mutex m_mu{}; + int m_fd{-1}; + std::filesystem::path m_path{}; + std::uint64_t m_append_pos{0}; + }; + + class PosixFilePort final : public FilePort + { + public: + Result ensure_dir(const std::filesystem::path& dir) override + { + std::error_code ec; + std::filesystem::create_directories(dir, ec); + if (ec) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::io_error, + std::format("Storage: create_directories '{}' failed: {}", + dir.string(), ec.message()), + ec)); + } + return {}; + } + + Result exists(const std::filesystem::path& p) override + { + std::error_code ec; + const bool ex = std::filesystem::exists(p, ec); + if (ec) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::io_error, + std::format("Storage: exists '{}' failed: {}", p.string(), ec.message()), + ec)); + } + return ex; + } + + Result file_size(const std::filesystem::path& p) override + { + struct stat st {}; + if (::lstat(p.c_str(), &st) != 0) { + return Void::Result::fail(errno_error("lstat", p, errno)); + } + if (!S_ISREG(st.st_mode)) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::corrupt, + std::format("Storage: '{}' is not a regular file", p.string()))); + } + return st.st_size >= 0 ? static_cast(st.st_size) : 0ULL; + } + + Result> list_dir(const std::filesystem::path& dir) override + { + std::error_code ec; + std::vector out; + for (const auto& entry : std::filesystem::directory_iterator(dir, ec)) { + if (ec) break; + out.push_back(entry.path().filename().string()); + } + if (ec) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::io_error, + std::format("Storage: list_dir '{}' failed: {}", dir.string(), ec.message()), + ec)); + } + std::sort(out.begin(), out.end()); + return out; + } + + Result> lock_directory( + const std::filesystem::path& dir) override + { + const auto lock_path = dir / "LOCK"; + const int fd = ::open( + lock_path.c_str(), + O_CREAT | O_RDWR | O_NOFOLLOW | O_CLOEXEC, + 0600); + if (fd < 0) { + return Void::Result::fail(errno_error("open lock", lock_path, errno)); + } + if (::flock(fd, LOCK_EX | LOCK_NB) != 0) { + const int err = errno; + ::close(fd); + return Void::Result::fail(errno_error("flock", lock_path, err)); + } + return std::unique_ptr{new PosixDirLock{fd}}; + } + + Result> open_file( + const std::filesystem::path& p, + FileOpenMode mode) override + { + int flags = O_NOFOLLOW | O_CLOEXEC; + switch (mode) { + case FileOpenMode::ReadOnly: + flags |= O_RDONLY; + break; + case FileOpenMode::ReadWriteExisting: + flags |= O_RDWR; + break; + case FileOpenMode::CreateNew: + flags |= O_RDWR | O_CREAT | O_EXCL; + break; + case FileOpenMode::CreateOrOpen: + flags |= O_RDWR | O_CREAT; + break; + } + const int fd = ::open(p.c_str(), flags, 0600); + if (fd < 0) { + return Void::Result::fail(errno_error("open", p, errno)); + } + struct stat st {}; + if (::fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) { + const int err = S_ISREG(st.st_mode) ? errno : EINVAL; + ::close(fd); + return Void::Result::fail(errno_error("fstat", p, err)); + } + const std::uint64_t sz = + st.st_size >= 0 ? static_cast(st.st_size) : 0ULL; + return std::unique_ptr{new PosixFileHandle{fd, p, sz}}; + } + + Result rename_atomic( + const std::filesystem::path& from, + const std::filesystem::path& to) override + { + if (::rename(from.c_str(), to.c_str()) != 0) { + return Void::Result::fail(errno_error("rename", to, errno)); + } + return {}; + } + + Result unlink_file(const std::filesystem::path& p) override + { + if (::unlink(p.c_str()) != 0) { + return Void::Result::fail(errno_error("unlink", p, errno)); + } + return {}; + } + + Result sync_dir(const std::filesystem::path& dir) override + { + const int fd = ::open(dir.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (fd < 0) { + return Void::Result::fail(errno_error("open dir", dir, errno)); + } + int rc = 0; + int saved_errno = 0; + for (;;) { + rc = ::fsync(fd); + if (rc == 0) break; + if (errno == EINTR) continue; + saved_errno = errno; + break; + } + ::close(fd); + if (rc != 0) { + return Void::Result::fail(errno_error("fsync dir", dir, saved_errno)); + } + return {}; + } + + Result probe_durability_capabilities( + const std::filesystem::path& dir) override + { + const auto p_tmp = dir / std::format(".void-probe-{}.tmp", ::getpid()); + const auto p_dst = dir / std::format(".void-probe-{}.dst", ::getpid()); + (void)::unlink(p_tmp.c_str()); + (void)::unlink(p_dst.c_str()); + + auto f = open_file(p_tmp, FileOpenMode::CreateOrOpen); + if (!f) return Void::Result::fail(std::move(f).error()); + const std::byte one{0x5Au}; + if (auto w = (*f)->append_all(ByteView{&one, 1}); !w) { + (void)::unlink(p_tmp.c_str()); + return Void::Result::fail(std::move(w).error()); + } + if (auto s = (*f)->sync(); !s) { + (void)::unlink(p_tmp.c_str()); + return s; + } + (void)(*f)->close(); + if (auto r = rename_atomic(p_tmp, p_dst); !r) { + (void)::unlink(p_tmp.c_str()); + (void)::unlink(p_dst.c_str()); + return r; + } + auto sd = sync_dir(dir); + (void)::unlink(p_dst.c_str()); + if (!sd) return sd; + return sync_dir(dir); + } + }; + } // namespace + + std::shared_ptr make_posix_file_port() + { + return std::make_shared(); + } + + class FaultFileHandle final : public FileHandle + { + public: + FaultFileHandle( + FaultInjectingFilePort* owner, + std::unique_ptr inner, + std::string path) noexcept + : m_owner(owner), m_inner(std::move(inner)), m_path(std::move(path)) + { + } + + Result pread(std::uint64_t offset, std::span out) override + { + return m_inner->pread(offset, out); + } + + Result pread_exact(std::uint64_t offset, std::span out) override + { + return m_inner->pread_exact(offset, out); + } + + Result pwrite_all(std::uint64_t offset, ByteView data) override + { + const auto mf = m_owner->check_fault(FaultOp::PWrite, m_path); + if (mf.triggered) { + if (mf.partial_write_bytes.has_value() && *mf.partial_write_bytes > 0) { + const std::size_t n = std::min(*mf.partial_write_bytes, data.size()); + (void)m_inner->pwrite_all(offset, data.subspan(0, n)); + } + return Void::Result::fail(make_storage_error( + mf.error_code, + std::format("Storage: injected pwrite fault on '{}'", m_path))); + } + return m_inner->pwrite_all(offset, data); + } + + Result append_all(ByteView data) override + { + const auto mf = m_owner->check_fault(FaultOp::AppendWrite, m_path); + if (mf.triggered) { + if (mf.partial_write_bytes.has_value() && *mf.partial_write_bytes > 0) { + const std::size_t n = std::min(*mf.partial_write_bytes, data.size()); + (void)m_inner->append_all(data.subspan(0, n)); + } + return Void::Result::fail(make_storage_error( + mf.error_code, + std::format("Storage: injected append fault on '{}'", m_path))); + } + return m_inner->append_all(data); + } + + Result sync() override + { + m_owner->maybe_run_sync_hook(); + const auto mf = m_owner->check_fault(FaultOp::SyncFile, m_path); + if (mf.triggered) { + return Void::Result::fail(make_storage_error( + mf.error_code, + std::format("Storage: injected fsync fault on '{}'", m_path))); + } + return m_inner->sync(); + } + + Result truncate(std::uint64_t new_size) override + { + const auto mf = m_owner->check_fault(FaultOp::Truncate, m_path); + if (mf.triggered) { + return Void::Result::fail(make_storage_error( + mf.error_code, + std::format("Storage: injected truncate fault on '{}'", m_path))); + } + return m_inner->truncate(new_size); + } + + Result size() const override + { + return m_inner->size(); + } + + Result close() override + { + return m_inner->close(); + } + + private: + FaultInjectingFilePort* m_owner; + std::unique_ptr m_inner; + std::string m_path; + }; + + FaultInjectingFilePort::FaultInjectingFilePort(std::shared_ptr delegate) + : delegate_(delegate ? std::move(delegate) : make_posix_file_port()) + { + } + + void FaultInjectingFilePort::add_rule(FaultRule rule) + { + std::lock_guard lk{mu_}; + rules_.push_back(std::move(rule)); + } + + void FaultInjectingFilePort::clear_rules() + { + std::lock_guard lk{mu_}; + rules_.clear(); + } + + void FaultInjectingFilePort::set_pause_before_sync(std::function hook) + { + std::lock_guard lk{mu_}; + pause_before_sync_ = std::move(hook); + } + + std::uint64_t FaultInjectingFilePort::op_count(FaultOp op) const noexcept + { + std::lock_guard lk{mu_}; + return op_counts_[static_cast(op)]; + } + + FaultInjectingFilePort::MatchedFault FaultInjectingFilePort::check_fault( + FaultOp op, + const std::string& path) + { + std::lock_guard lk{mu_}; + ++op_counts_[static_cast(op)]; + for (auto& r : rules_) { + if (r.consumed || r.op != op) continue; + if (!r.path_contains.empty() && path.find(r.path_contains) == std::string::npos) { + continue; + } + ++r.match_count; + if (r.hit_index == 0 || r.match_count == r.hit_index) { + if (r.hit_index != 0) { + r.consumed = true; + } + return MatchedFault{r.error_code, r.partial_write_bytes, true}; + } + } + return {}; + } + + void FaultInjectingFilePort::maybe_run_sync_hook() + { + std::function cb; + { + std::lock_guard lk{mu_}; + cb = pause_before_sync_; + } + if (cb) { + cb(); + } + } + + Result FaultInjectingFilePort::ensure_dir(const std::filesystem::path& dir) + { + return delegate_->ensure_dir(dir); + } + + Result FaultInjectingFilePort::exists(const std::filesystem::path& p) + { + return delegate_->exists(p); + } + + Result FaultInjectingFilePort::file_size(const std::filesystem::path& p) + { + return delegate_->file_size(p); + } + + Result> FaultInjectingFilePort::list_dir(const std::filesystem::path& dir) + { + return delegate_->list_dir(dir); + } + + Result> FaultInjectingFilePort::lock_directory( + const std::filesystem::path& dir) + { + const auto mf = check_fault(FaultOp::LockDir, dir.string()); + if (mf.triggered) { + return Void::Result::fail(make_storage_error( + mf.error_code, "Storage: injected directory lock fault")); + } + return delegate_->lock_directory(dir); + } + + Result> FaultInjectingFilePort::open_file( + const std::filesystem::path& p, + FileOpenMode mode) + { + const auto mf = check_fault(FaultOp::OpenFile, p.string()); + if (mf.triggered) { + return Void::Result::fail(make_storage_error( + mf.error_code, + std::format("Storage: injected open_file fault on '{}'", p.string()))); + } + auto h = delegate_->open_file(p, mode); + if (!h) return Void::Result::fail(std::move(h).error()); + return std::unique_ptr{ + new FaultFileHandle{this, std::move(*h), p.string()}}; + } + + Result FaultInjectingFilePort::rename_atomic( + const std::filesystem::path& from, + const std::filesystem::path& to) + { + const auto mf = check_fault(FaultOp::Rename, to.string()); + if (mf.triggered) { + return Void::Result::fail(make_storage_error( + mf.error_code, + std::format("Storage: injected rename fault to '{}'", to.string()))); + } + return delegate_->rename_atomic(from, to); + } + + Result FaultInjectingFilePort::unlink_file(const std::filesystem::path& p) + { + const auto mf = check_fault(FaultOp::Unlink, p.string()); + if (mf.triggered) { + return Void::Result::fail(make_storage_error( + mf.error_code, + std::format("Storage: injected unlink fault on '{}'", p.string()))); + } + return delegate_->unlink_file(p); + } + + Result FaultInjectingFilePort::sync_dir(const std::filesystem::path& dir) + { + const auto mf = check_fault(FaultOp::SyncDir, dir.string()); + if (mf.triggered) { + return Void::Result::fail(make_storage_error( + mf.error_code, + std::format("Storage: injected sync_dir fault on '{}'", dir.string()))); + } + return delegate_->sync_dir(dir); + } + + Result FaultInjectingFilePort::probe_durability_capabilities( + const std::filesystem::path& dir) + { + const auto mf = check_fault(FaultOp::ProbeDurability, dir.string()); + if (mf.triggered) { + return Void::Result::fail(make_storage_error( + mf.error_code, "Storage: injected probe durability fault")); + } + return delegate_->probe_durability_capabilities(dir); + } + +} // namespace Void::Storage diff --git a/src/Storage/Format.cpp b/src/Storage/Format.cpp new file mode 100644 index 0000000..62c3537 --- /dev/null +++ b/src/Storage/Format.cpp @@ -0,0 +1,1432 @@ +#include +#include +#include +#include +#include +#include "TableInternal.hpp" + +#include +#include +#include +#include + +namespace Void::Storage +{ + namespace + { + [[nodiscard]] Error format_corrupt(std::string msg) + { + return make_storage_error(StorageErrorCode::corrupt, std::move(msg)); + } + + [[nodiscard]] Error format_invalid(std::string msg) + { + return make_storage_error(StorageErrorCode::invalid_argument, std::move(msg)); + } + + [[nodiscard]] Error format_unsupported(std::string msg) + { + return make_storage_error(StorageErrorCode::unsupported_capability, std::move(msg)); + } + + [[nodiscard]] Result write_magic( + Void::Binary::ByteBuffer& buf, + std::span magic) + { + return buf.append(std::as_bytes(std::span{magic.data(), 8})); + } + + [[nodiscard]] bool check_magic(ByteView bytes, std::span expected) noexcept + { + if (bytes.size() < 8) return false; + return std::memcmp(bytes.data(), expected.data(), 8) == 0; + } + } // namespace + + std::string make_wal_filename(std::uint64_t segment_id) + { + return std::format("WAL-{:016X}.vwal", segment_id); + } + + std::string make_table_filename(std::uint64_t table_id) + { + return std::format("TABLE-{:016X}.vtbl", table_id); + } + + std::string make_manifest_filename(std::uint64_t generation) + { + return std::format("MANIFEST-{:016X}.vmnf", generation); + } + + Result encode_wal_segment_header(const WalSegmentHeader& hdr) + { + Void::Binary::ByteBuffer buf(kWalSegmentHeaderSize); + if (auto r = write_magic(buf, kWalSegmentMagic); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(hdr.major); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(hdr.minor); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(kWalSegmentHeaderSize); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.append(std::as_bytes(std::span{hdr.database_uuid.bytes})); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(hdr.segment_id); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(hdr.previous_segment_id); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(hdr.first_candidate_sequence); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(hdr.flags); !r) return Void::Result::fail(std::move(r).error()); + const std::uint32_t crc = crc32c(buf.view()); + if (auto r = buf.writeLittle(crc); !r) return Void::Result::fail(std::move(r).error()); + return OwnedBytes{buf.view().begin(), buf.view().end()}; + } + + Result decode_wal_segment_header(ByteView bytes) + { + if (bytes.size() < kWalSegmentHeaderSize) { + return Void::Result::fail(format_corrupt("WAL segment header shorter than 64 bytes")); + } + if (!check_magic(bytes, kWalSegmentMagic)) { + return Void::Result::fail(format_corrupt("WAL segment header magic mismatch")); + } + const std::uint32_t computed_crc = crc32c(bytes.subspan(0, kWalSegmentHeaderSize - 4)); + Void::Binary::Reader rd{bytes.subspan(8, kWalSegmentHeaderSize - 8)}; + auto major = rd.readLittle(); + auto minor = rd.readLittle(); + auto hdr_sz = rd.readLittle(); + auto uuid_bytes = rd.readBytes(16); + auto seg_id = rd.readLittle(); + auto prev_id = rd.readLittle(); + auto first_seq = rd.readLittle(); + auto flags = rd.readLittle(); + auto stored_crc = rd.readLittle(); + if (!major || !minor || !hdr_sz || !uuid_bytes || !seg_id || + !prev_id || !first_seq || !flags || !stored_crc) { + return Void::Result::fail(format_corrupt("Truncated WAL segment header")); + } + if (*stored_crc != computed_crc) { + return Void::Result::fail(format_corrupt("WAL segment header CRC32C mismatch")); + } + if (*major != kWalFormatMajor) { + return Void::Result::fail(format_unsupported( + std::format("Unsupported WAL major version {}", *major))); + } + if (*flags != 0) { + return Void::Result::fail(format_unsupported( + std::format("Unsupported WAL segment flags 0x{:08x}", *flags))); + } + if (*hdr_sz != kWalSegmentHeaderSize) { + return Void::Result::fail(format_corrupt("Unexpected V1 WAL segment header size")); + } + WalSegmentHeader out; + out.major = *major; + out.minor = *minor; + out.header_size = *hdr_sz; + for (std::size_t i = 0; i < 16; ++i) { + out.database_uuid.bytes[i] = std::to_integer((*uuid_bytes)[i]); + } + out.segment_id = *seg_id; + out.previous_segment_id = *prev_id; + out.first_candidate_sequence = *first_seq; + out.flags = *flags; + return out; + } + + Result encode_wal_record_frame( + WalRecordType type, + Sequence batch_sequence, + std::uint32_t ordinal, + ByteView payload) + { + if (payload.size() > + static_cast(std::numeric_limits::max()) - + (kWalRecordHeaderSize + kWalRecordTrailerSize)) { + return Void::Result::fail(format_invalid("WAL record payload exceeds uint32 range")); + } + const auto payload_len = static_cast(payload.size()); + const std::uint32_t total_len = kWalRecordHeaderSize + payload_len + kWalRecordTrailerSize; + + Void::Binary::ByteBuffer buf(total_len); + if (auto r = buf.writeLittle(kWalRecordMagic); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(total_len); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(static_cast(type)); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(kWalRecordVersion); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(0); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(batch_sequence); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(ordinal); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(payload_len); !r) return Void::Result::fail(std::move(r).error()); + const std::uint32_t hdr_crc = crc32c(buf.view()); + if (auto r = buf.writeLittle(hdr_crc); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.append(payload); !r) return Void::Result::fail(std::move(r).error()); + const std::uint32_t rec_crc = crc32c(buf.view()); + if (auto r = buf.writeLittle(rec_crc); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(total_len); !r) return Void::Result::fail(std::move(r).error()); + return OwnedBytes{buf.view().begin(), buf.view().end()}; + } + + Result decode_wal_record_header( + ByteView header_bytes, + std::size_t max_payload_bytes) + { + if (header_bytes.size() < kWalRecordHeaderSize) { + return Void::Result::fail(format_corrupt("WAL record header shorter than 36 bytes")); + } + const std::uint32_t computed_hdr_crc = crc32c(header_bytes.subspan(0, kWalRecordHeaderSize - 4)); + Void::Binary::Reader rd{header_bytes.subspan(0, kWalRecordHeaderSize)}; + auto magic = rd.readLittle(); + auto total_len = rd.readLittle(); + auto type_u16 = rd.readLittle(); + auto rec_ver = rd.readLittle(); + auto flags = rd.readLittle(); + auto batch_seq = rd.readLittle(); + auto ordinal = rd.readLittle(); + auto payload_len = rd.readLittle(); + auto stored_hdr_crc = rd.readLittle(); + if (!magic || !total_len || !type_u16 || !rec_ver || !flags || + !batch_seq || !ordinal || !payload_len || !stored_hdr_crc) { + return Void::Result::fail(format_corrupt("WAL record header read failed")); + } + if (*magic != kWalRecordMagic) { + return Void::Result::fail(format_corrupt("WAL record magic mismatch")); + } + if (*stored_hdr_crc != computed_hdr_crc) { + return Void::Result::fail(format_corrupt("WAL record header CRC32C mismatch")); + } + if (*rec_ver != kWalRecordVersion) { + return Void::Result::fail(format_unsupported( + std::format("Unsupported WAL record version {}", *rec_ver))); + } + if (*flags != 0) { + return Void::Result::fail(format_unsupported( + std::format("Unsupported WAL record flags 0x{:08x}", *flags))); + } + if (*type_u16 < 1 || *type_u16 > 4) { + return Void::Result::fail(format_corrupt( + std::format("Unknown WAL record type {}", *type_u16))); + } + if (*payload_len > max_payload_bytes) { + return Void::Result::fail(format_corrupt( + std::format("WAL record payload {} exceeds limit {}", *payload_len, max_payload_bytes))); + } + const std::uint64_t expected_total = + static_cast(kWalRecordHeaderSize) + + static_cast(*payload_len) + + static_cast(kWalRecordTrailerSize); + if (expected_total != static_cast(*total_len)) { + return Void::Result::fail(format_corrupt("WAL record header length inconsistency")); + } + WalRecordHeader out; + out.total_length = *total_len; + out.type = static_cast(*type_u16); + out.record_version = *rec_ver; + out.flags = *flags; + out.batch_sequence = *batch_seq; + out.ordinal = *ordinal; + out.payload_length = *payload_len; + return out; + } + + Result verify_wal_record_frame( + const WalRecordHeader& hdr, + ByteView full_record_bytes) + { + if (full_record_bytes.size() != hdr.total_length || + hdr.total_length < kWalRecordHeaderSize + kWalRecordTrailerSize) { + return Void::Result::fail(format_corrupt("WAL record frame length mismatch")); + } + const std::size_t body_end = full_record_bytes.size() - kWalRecordTrailerSize; + const std::uint32_t expected_crc = crc32c(full_record_bytes.subspan(0, body_end)); + Void::Binary::Reader tr{full_record_bytes.subspan(body_end, kWalRecordTrailerSize)}; + auto stored_crc = tr.readLittle(); + auto repeated_len = tr.readLittle(); + if (!stored_crc || !repeated_len) { + return Void::Result::fail(format_corrupt("WAL record trailer read failed")); + } + if (*stored_crc != expected_crc) { + return Void::Result::fail(format_corrupt("WAL record payload CRC32C mismatch")); + } + if (*repeated_len != hdr.total_length) { + return Void::Result::fail(format_corrupt("WAL record repeated total_length mismatch")); + } + return {}; + } + + Result encode_wal_begin_payload(const WalBeginPayload& p) + { + Void::Binary::ByteBuffer buf(12); + if (auto r = buf.writeLittle(p.op_count); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(p.total_op_bytes); !r) return Void::Result::fail(std::move(r).error()); + return OwnedBytes{buf.view().begin(), buf.view().end()}; + } + + Result decode_wal_begin_payload(ByteView bytes) + { + if (bytes.size() != 12) { + return Void::Result::fail(format_corrupt("WAL BEGIN payload length != 12")); + } + Void::Binary::Reader rd{bytes}; + auto cnt = rd.readLittle(); + auto tot = rd.readLittle(); + if (!cnt || !tot) return Void::Result::fail(format_corrupt("WAL BEGIN decode failed")); + return WalBeginPayload{*cnt, *tot}; + } + + Result encode_wal_mutation_payload( + bool is_erase, ByteView key, ByteView value) + { + if (is_erase && !value.empty()) { + return Void::Result::fail(format_invalid("ERASE record cannot carry a non-empty value")); + } + const std::size_t total = 8 + key.size() + value.size(); + Void::Binary::ByteBuffer buf(total); + if (auto r = buf.writeLittle(static_cast(key.size())); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(static_cast(value.size())); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.append(key); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.append(value); !r) return Void::Result::fail(std::move(r).error()); + return OwnedBytes{buf.view().begin(), buf.view().end()}; + } + + Result decode_wal_mutation_payload( + bool is_erase, + ByteView bytes, + std::size_t max_key_bytes, + std::size_t max_value_bytes) + { + Void::Binary::Reader rd{bytes}; + auto klen = rd.readLittle(); + auto vlen = rd.readLittle(); + if (!klen || !vlen) { + return Void::Result::fail(format_corrupt("Truncated WAL mutation payload lengths")); + } + if (is_erase && *vlen != 0) { + return Void::Result::fail(format_corrupt("WAL ERASE record has non-zero value length")); + } + if (*klen > max_key_bytes || *vlen > max_value_bytes) { + return Void::Result::fail(format_corrupt("WAL mutation key/value length exceeds limits")); + } + auto kbytes = rd.readBytes(*klen); + auto vbytes = rd.readBytes(*vlen); + if (!kbytes || !vbytes || !rd.empty()) { + return Void::Result::fail(format_corrupt("WAL mutation payload length mismatch")); + } + WalMutationPayload out; + out.key.assign(kbytes->begin(), kbytes->end()); + out.value.assign(vbytes->begin(), vbytes->end()); + return out; + } + + Result encode_wal_commit_payload(const WalCommitPayload& p) + { + Void::Binary::ByteBuffer buf(16); + if (auto r = buf.writeLittle(p.op_count); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(p.total_op_bytes); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(p.aggregate_crc32c); !r) return Void::Result::fail(std::move(r).error()); + return OwnedBytes{buf.view().begin(), buf.view().end()}; + } + + Result decode_wal_commit_payload(ByteView bytes) + { + if (bytes.size() != 16) { + return Void::Result::fail(format_corrupt("WAL COMMIT payload length != 16")); + } + Void::Binary::Reader rd{bytes}; + auto cnt = rd.readLittle(); + auto tot = rd.readLittle(); + auto agg = rd.readLittle(); + if (!cnt || !tot || !agg) return Void::Result::fail(format_corrupt("WAL COMMIT decode failed")); + return WalCommitPayload{*cnt, *tot, *agg}; + } + + // ── Table Codecs ───────────────────────────────────────────────────────── + + Result encode_table_header(const TableHeader& hdr) + { + Void::Binary::ByteBuffer buf(kTableHeaderSize); + if (auto r = write_magic(buf, kTableMagic); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(hdr.major); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(hdr.minor); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(kTableHeaderSize); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.append(std::as_bytes(std::span{hdr.database_uuid.bytes})); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(hdr.table_id); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(hdr.level); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(hdr.flags); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(hdr.entry_count); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(hdr.min_sequence); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(hdr.max_sequence); !r) return Void::Result::fail(std::move(r).error()); + const std::uint32_t crc = crc32c(buf.view()); + if (auto r = buf.writeLittle(crc); !r) return Void::Result::fail(std::move(r).error()); + return OwnedBytes{buf.view().begin(), buf.view().end()}; + } + + Result decode_table_header(ByteView bytes) + { + if (bytes.size() < kTableHeaderSize || !check_magic(bytes, kTableMagic)) { + return Void::Result::fail(format_corrupt("Table header magic or size invalid")); + } + const std::uint32_t expected_crc = crc32c(bytes.subspan(0, kTableHeaderSize - 4)); + Void::Binary::Reader rd{bytes.subspan(8, kTableHeaderSize - 8)}; + auto major = rd.readLittle(); + auto minor = rd.readLittle(); + auto hdr_sz = rd.readLittle(); + auto uuid_bytes = rd.readBytes(16); + auto table_id = rd.readLittle(); + auto level = rd.readLittle(); + auto flags = rd.readLittle(); + auto cnt = rd.readLittle(); + auto min_seq = rd.readLittle(); + auto max_seq = rd.readLittle(); + auto crc = rd.readLittle(); + if (!major || !minor || !hdr_sz || !uuid_bytes || !table_id || + !level || !flags || !cnt || !min_seq || !max_seq || !crc) { + return Void::Result::fail(format_corrupt("Truncated table header")); + } + if (*crc != expected_crc) { + return Void::Result::fail(format_corrupt("Table header CRC32C mismatch")); + } + if (*major != 1 || *flags != 0 || *hdr_sz != kTableHeaderSize) { + return Void::Result::fail(format_unsupported("Unsupported table version/flags")); + } + TableHeader out; + out.major = *major; + out.minor = *minor; + out.header_size = *hdr_sz; + for (std::size_t i = 0; i < 16; ++i) { + out.database_uuid.bytes[i] = std::to_integer((*uuid_bytes)[i]); + } + out.table_id = *table_id; + out.level = *level; + out.flags = *flags; + out.entry_count = *cnt; + out.min_sequence = *min_seq; + out.max_sequence = *max_seq; + return out; + } + + Result encode_table_block( + std::span entries, + std::size_t max_bytes) + { + Void::Binary::ByteBuffer buf(max_bytes + 64); + if (auto r = buf.writeLittle(static_cast(entries.size())); !r) { + return Void::Result::fail(std::move(r).error()); + } + for (const auto& e : entries) { + if (auto r = buf.writeLittle(static_cast(e.key.size())); !r) { + return Void::Result::fail(std::move(r).error()); + } + const auto vlen = e.erased ? 0ULL : e.value.size(); + if (auto r = buf.writeLittle(static_cast(vlen)); !r) { + return Void::Result::fail(std::move(r).error()); + } + if (auto r = buf.writeLittle(e.sequence); !r) { + return Void::Result::fail(std::move(r).error()); + } + if (auto r = buf.writeLittle(e.erased ? 2u : 1u); !r) { + return Void::Result::fail(std::move(r).error()); + } + if (auto r = buf.append(e.key); !r) { + return Void::Result::fail(std::move(r).error()); + } + if (!e.erased) { + if (auto r = buf.append(e.value); !r) { + return Void::Result::fail(std::move(r).error()); + } + } + } + const std::uint32_t crc = crc32c(buf.view()); + if (auto r = buf.writeLittle(crc); !r) { + return Void::Result::fail(std::move(r).error()); + } + return OwnedBytes{buf.view().begin(), buf.view().end()}; + } + + Result> decode_table_block( + ByteView bytes, + std::size_t max_key_bytes, + std::size_t max_value_bytes) + { + if (bytes.size() < 8) { + return Void::Result::fail(format_corrupt("Table block shorter than 8 bytes")); + } + const std::size_t body_len = bytes.size() - 4; + const std::uint32_t expected_crc = crc32c(bytes.subspan(0, body_len)); + Void::Binary::Reader crc_rd{bytes.subspan(body_len, 4)}; + auto stored_crc = crc_rd.readLittle(); + if (!stored_crc || *stored_crc != expected_crc) { + return Void::Result::fail(format_corrupt("Table block CRC32C mismatch")); + } + + Void::Binary::Reader rd{bytes.subspan(0, body_len)}; + auto count = rd.readLittle(); + if (!count) return Void::Result::fail(format_corrupt("Table block count missing")); + std::vector out; + out.reserve(*count); + for (std::uint32_t i = 0; i < *count; ++i) { + auto klen = rd.readLittle(); + auto vlen = rd.readLittle(); + auto seq = rd.readLittle(); + auto kind_byte = rd.readBytes(1); + if (!klen || !vlen || !seq || !kind_byte) { + return Void::Result::fail(format_corrupt("Truncated table entry")); + } + const auto kind = std::to_integer((*kind_byte)[0]); + if (*klen > max_key_bytes || *vlen > max_value_bytes) { + return Void::Result::fail(format_corrupt("Table entry exceeds key/value limits")); + } + if (kind != 1 && kind != 2) { + return Void::Result::fail(format_corrupt("Unknown table entry kind")); + } + if (kind == 2 && *vlen != 0) { + return Void::Result::fail(format_corrupt("Table tombstone has non-zero value")); + } + auto k = rd.readBytes(*klen); + auto v = rd.readBytes(*vlen); + if (!k || !v) { + return Void::Result::fail(format_corrupt("Truncated table entry bytes")); + } + TableEntryRecord rec; + rec.key.assign(k->begin(), k->end()); + rec.sequence = *seq; + rec.erased = (kind == 2); + rec.value.assign(v->begin(), v->end()); + out.push_back(std::move(rec)); + } + if (!rd.empty()) { + return Void::Result::fail(format_corrupt("Trailing bytes inside table block")); + } + return out; + } + + Result encode_table_index( + std::span index, + std::size_t max_bytes) + { + Void::Binary::ByteBuffer buf(max_bytes); + if (auto r = buf.writeLittle(static_cast(index.size())); !r) { + return Void::Result::fail(std::move(r).error()); + } + for (const auto& b : index) { + if (auto r = buf.writeLittle(static_cast(b.first_key.size())); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.append(b.first_key); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(static_cast(b.last_key.size())); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.append(b.last_key); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(b.offset); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(b.byte_length); !r) return Void::Result::fail(std::move(r).error()); + } + const std::uint32_t crc = crc32c(buf.view()); + if (auto r = buf.writeLittle(crc); !r) return Void::Result::fail(std::move(r).error()); + return OwnedBytes{buf.view().begin(), buf.view().end()}; + } + + Result> decode_table_index( + ByteView bytes, + std::size_t max_key_bytes) + { + if (bytes.size() < 8) { + return Void::Result::fail(format_corrupt("Table index shorter than 8 bytes")); + } + const std::size_t body_len = bytes.size() - 4; + const std::uint32_t expected_crc = crc32c(bytes.subspan(0, body_len)); + Void::Binary::Reader crc_rd{bytes.subspan(body_len, 4)}; + auto stored_crc = crc_rd.readLittle(); + if (!stored_crc || *stored_crc != expected_crc) { + return Void::Result::fail(format_corrupt("Table index CRC32C mismatch")); + } + Void::Binary::Reader rd{bytes.subspan(0, body_len)}; + auto count = rd.readLittle(); + if (!count) return Void::Result::fail(format_corrupt("Table index missing count")); + std::vector out; + out.reserve(*count); + for (std::uint32_t i = 0; i < *count; ++i) { + auto fl = rd.readLittle(); + if (!fl || *fl > max_key_bytes) return Void::Result::fail(format_corrupt("Invalid index first_key length")); + auto fb = rd.readBytes(*fl); + auto ll = rd.readLittle(); + if (!fb || !ll || *ll > max_key_bytes) return Void::Result::fail(format_corrupt("Invalid index last_key length")); + auto lb = rd.readBytes(*ll); + auto off = rd.readLittle(); + auto blen = rd.readLittle(); + if (!lb || !off || !blen) return Void::Result::fail(format_corrupt("Truncated table index entry")); + TableBlockIndexEntry e; + e.first_key.assign(fb->begin(), fb->end()); + e.last_key.assign(lb->begin(), lb->end()); + e.offset = *off; + e.byte_length = *blen; + out.push_back(std::move(e)); + } + if (!rd.empty()) { + return Void::Result::fail(format_corrupt("Trailing bytes in table index")); + } + return out; + } + + Result encode_table_footer(const TableFooter& footer) + { + Void::Binary::ByteBuffer buf(kTableFooterSize); + if (auto r = write_magic(buf, kTableFooterMagic); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(footer.index_offset); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(footer.index_size); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(footer.data_end_offset); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(0); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(footer.file_crc32c); !r) return Void::Result::fail(std::move(r).error()); + const std::uint32_t crc = crc32c(buf.view()); + if (auto r = buf.writeLittle(crc); !r) return Void::Result::fail(std::move(r).error()); + return OwnedBytes{buf.view().begin(), buf.view().end()}; + } + + Result decode_table_footer(ByteView bytes) + { + if (bytes.size() < kTableFooterSize || !check_magic(bytes, kTableFooterMagic)) { + return Void::Result::fail(format_corrupt("Table footer magic or size invalid")); + } + const std::uint32_t expected_crc = crc32c(bytes.subspan(0, kTableFooterSize - 4)); + Void::Binary::Reader rd{bytes.subspan(8, kTableFooterSize - 8)}; + auto idx_off = rd.readLittle(); + auto idx_sz = rd.readLittle(); + auto data_end = rd.readLittle(); + auto reserved = rd.readLittle(); + auto file_crc = rd.readLittle(); + auto footer_crc = rd.readLittle(); + if (!idx_off || !idx_sz || !data_end || !reserved || !file_crc || !footer_crc) { + return Void::Result::fail(format_corrupt("Truncated table footer")); + } + if (*footer_crc != expected_crc) { + return Void::Result::fail(format_corrupt("Table footer CRC32C mismatch")); + } + if (*reserved != 0) { + return Void::Result::fail(format_corrupt("Non-zero reserved bytes in V1 table footer")); + } + return TableFooter{*idx_off, *idx_sz, *data_end, *file_crc}; + } + + // ── Manifest & CURRENT ─────────────────────────────────────────────────── + + Result encode_manifest( + const ManifestData& m, + std::size_t max_manifest_bytes) + { + Void::Binary::ByteBuffer buf(max_manifest_bytes); + if (auto r = write_magic(buf, kManifestMagic); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(m.major); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(m.minor); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(m.flags); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.append(std::as_bytes(std::span{m.database_uuid.bytes})); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(m.generation); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(m.checkpoint_sequence); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(m.next_sequence_hint); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(m.next_file_id); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(static_cast(m.comparator.size())); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeString(m.comparator); !r) return Void::Result::fail(std::move(r).error()); + + if (auto r = buf.writeLittle(static_cast(m.tables.size())); !r) return Void::Result::fail(std::move(r).error()); + for (const auto& t : m.tables) { + if (auto r = buf.writeLittle(t.table_id); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(t.level); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(t.file_size); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(t.entry_count); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(t.min_sequence); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(t.max_sequence); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(static_cast(t.min_key.size())); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.append(t.min_key); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(static_cast(t.max_key.size())); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.append(t.max_key); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(t.file_crc32c); !r) return Void::Result::fail(std::move(r).error()); + } + + if (auto r = buf.writeLittle(static_cast(m.wal_segments.size())); !r) return Void::Result::fail(std::move(r).error()); + for (const auto seg_id : m.wal_segments) { + if (auto r = buf.writeLittle(seg_id); !r) return Void::Result::fail(std::move(r).error()); + } + const std::uint32_t crc = crc32c(buf.view()); + if (auto r = buf.writeLittle(crc); !r) return Void::Result::fail(std::move(r).error()); + return OwnedBytes{buf.view().begin(), buf.view().end()}; + } + + Result decode_manifest( + ByteView bytes, + std::size_t max_manifest_bytes, + std::size_t max_tables, + std::size_t max_key_bytes) + { + if (bytes.size() > max_manifest_bytes || bytes.size() < 64) { + return Void::Result::fail(format_corrupt("Manifest file size out of valid bounds")); + } + if (!check_magic(bytes, kManifestMagic)) { + return Void::Result::fail(format_corrupt("Manifest magic mismatch")); + } + const std::size_t body_len = bytes.size() - 4; + const std::uint32_t expected_crc = crc32c(bytes.subspan(0, body_len)); + Void::Binary::Reader crc_rd{bytes.subspan(body_len, 4)}; + auto stored_crc = crc_rd.readLittle(); + if (!stored_crc || *stored_crc != expected_crc) { + return Void::Result::fail(format_corrupt("Manifest CRC32C mismatch")); + } + + Void::Binary::Reader rd{bytes.subspan(8, body_len - 8)}; + ManifestData m; + auto major = rd.readLittle(); + auto minor = rd.readLittle(); + auto flags = rd.readLittle(); + auto uuid_bytes = rd.readBytes(16); + auto gen = rd.readLittle(); + auto ckpt = rd.readLittle(); + auto next_seq = rd.readLittle(); + auto next_fid = rd.readLittle(); + auto cmp_len = rd.readLittle(); + if (!major || !minor || !flags || !uuid_bytes || !gen || + !ckpt || !next_seq || !next_fid || !cmp_len || *cmp_len > 256) { + return Void::Result::fail(format_corrupt("Malformed manifest header")); + } + if (*major != 1) { + return Void::Result::fail(format_unsupported( + std::format("Unsupported manifest major version {}", *major))); + } + if (*flags != 0) { + return Void::Result::fail(format_unsupported("Unsupported manifest flags")); + } + auto cmp_str = rd.readString(*cmp_len); + if (!cmp_str || *cmp_str != kComparatorIdV1) { + return Void::Result::fail(format_unsupported("Manifest comparator mismatch")); + } + m.major = *major; + m.minor = *minor; + m.flags = *flags; + for (std::size_t i = 0; i < 16; ++i) { + m.database_uuid.bytes[i] = std::to_integer((*uuid_bytes)[i]); + } + m.generation = *gen; + m.checkpoint_sequence = *ckpt; + m.next_sequence_hint = *next_seq; + m.next_file_id = *next_fid; + m.comparator = std::move(*cmp_str); + + auto tcnt = rd.readLittle(); + if (!tcnt || *tcnt > max_tables) { + return Void::Result::fail(format_corrupt("Manifest table count exceeds limit")); + } + m.tables.reserve(*tcnt); + for (std::uint32_t i = 0; i < *tcnt; ++i) { + TableMeta tm; + auto tid = rd.readLittle(); + auto lvl = rd.readLittle(); + auto fsz = rd.readLittle(); + auto ecnt = rd.readLittle(); + auto min_s = rd.readLittle(); + auto max_s = rd.readLittle(); + auto min_kl = rd.readLittle(); + if (!tid || !lvl || !fsz || !ecnt || !min_s || !max_s || !min_kl || *min_kl > max_key_bytes) { + return Void::Result::fail(format_corrupt("Malformed table entry in manifest")); + } + auto min_k = rd.readBytes(*min_kl); + auto max_kl = rd.readLittle(); + if (!min_k || !max_kl || *max_kl > max_key_bytes) { + return Void::Result::fail(format_corrupt("Malformed max_key in manifest")); + } + auto max_k = rd.readBytes(*max_kl); + auto fcrc = rd.readLittle(); + if (!max_k || !fcrc) { + return Void::Result::fail(format_corrupt("Truncated table metadata in manifest")); + } + tm.table_id = *tid; + tm.level = *lvl; + tm.file_size = *fsz; + tm.entry_count = *ecnt; + tm.min_sequence = *min_s; + tm.max_sequence = *max_s; + tm.min_key.assign(min_k->begin(), min_k->end()); + tm.max_key.assign(max_k->begin(), max_k->end()); + tm.file_crc32c = *fcrc; + m.tables.push_back(std::move(tm)); + } + + auto wcnt = rd.readLittle(); + if (!wcnt || *wcnt > 65536) { + return Void::Result::fail(format_corrupt("Manifest WAL segment count invalid")); + } + m.wal_segments.reserve(*wcnt); + for (std::uint32_t i = 0; i < *wcnt; ++i) { + auto seg = rd.readLittle(); + if (!seg) return Void::Result::fail(format_corrupt("Truncated WAL segment ID in manifest")); + m.wal_segments.push_back(*seg); + } + if (!rd.empty()) { + return Void::Result::fail(format_corrupt("Trailing bytes in manifest")); + } + return m; + } + + Result encode_current(const CurrentPointer& cur) + { + if (cur.manifest_filename.empty() || cur.manifest_filename.size() > 256) { + return Void::Result::fail(format_invalid("Invalid manifest filename in CURRENT")); + } + Void::Binary::ByteBuffer buf(512); + if (auto r = write_magic(buf, kCurrentMagic); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(cur.major); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(cur.minor); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.append(std::as_bytes(std::span{cur.database_uuid.bytes})); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(cur.generation); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeLittle(static_cast(cur.manifest_filename.size())); !r) return Void::Result::fail(std::move(r).error()); + if (auto r = buf.writeString(cur.manifest_filename); !r) return Void::Result::fail(std::move(r).error()); + const std::uint32_t crc = crc32c(buf.view()); + if (auto r = buf.writeLittle(crc); !r) return Void::Result::fail(std::move(r).error()); + return OwnedBytes{buf.view().begin(), buf.view().end()}; + } + + Result decode_current(ByteView bytes) + { + if (bytes.size() < 44 || bytes.size() > 512) { + return Void::Result::fail(format_corrupt("CURRENT file size out of valid bounds")); + } + if (!check_magic(bytes, kCurrentMagic)) { + return Void::Result::fail(format_corrupt("CURRENT magic mismatch")); + } + const std::size_t body_len = bytes.size() - 4; + const std::uint32_t expected_crc = crc32c(bytes.subspan(0, body_len)); + Void::Binary::Reader crc_rd{bytes.subspan(body_len, 4)}; + auto stored_crc = crc_rd.readLittle(); + if (!stored_crc || *stored_crc != expected_crc) { + return Void::Result::fail(format_corrupt("CURRENT CRC32C mismatch")); + } + Void::Binary::Reader rd{bytes.subspan(8, body_len - 8)}; + auto major = rd.readLittle(); + auto minor = rd.readLittle(); + auto uuid_bytes = rd.readBytes(16); + auto gen = rd.readLittle(); + auto flen = rd.readLittle(); + if (!major || !minor || !uuid_bytes || !gen || !flen || *flen == 0 || *flen > 256) { + return Void::Result::fail(format_corrupt("Malformed CURRENT record")); + } + if (*major != 1) { + return Void::Result::fail(format_unsupported("Unsupported CURRENT major version")); + } + auto fname = rd.readString(*flen); + if (!fname || !rd.empty()) { + return Void::Result::fail(format_corrupt("Truncated or trailing bytes in CURRENT")); + } + CurrentPointer cur; + cur.major = *major; + cur.minor = *minor; + for (std::size_t i = 0; i < 16; ++i) { + cur.database_uuid.bytes[i] = std::to_integer((*uuid_bytes)[i]); + } + cur.generation = *gen; + cur.manifest_filename = std::move(*fname); + return cur; + } + + // ── TableReader, TableWriter, and WAL Segment Scanners ─────────────────── + + namespace detail + { + Result> TableReader::open( + std::shared_ptr port, + std::filesystem::path path, + Void::Uuid::Uuid expected_uuid, + const TableMeta& meta, + const Limits& limits) + { + auto f = port->open_file(path, FileOpenMode::ReadOnly); + if (!f) return Void::Result::fail(std::move(f).error()); + auto sz_r = (*f)->size(); + if (!sz_r) return Void::Result::fail(std::move(sz_r).error()); + const std::uint64_t fsize = *sz_r; + if (fsize != meta.file_size || fsize < kTableHeaderSize + kTableFooterSize) { + return Void::Result::fail(format_corrupt( + std::format("Table '{}' size {} mismatches manifest size {}", + path.string(), fsize, meta.file_size))); + } + + OwnedBytes hdr_buf(kTableHeaderSize); + if (auto r = (*f)->pread_exact(0, hdr_buf); !r) { + return Void::Result::fail(std::move(r).error()); + } + auto hdr = decode_table_header(hdr_buf); + if (!hdr) return Void::Result::fail(std::move(hdr).error()); + if (hdr->database_uuid != expected_uuid || + hdr->table_id != meta.table_id || + hdr->entry_count != meta.entry_count) { + return Void::Result::fail(format_corrupt( + std::format("Table '{}' metadata mismatches manifest", path.string()))); + } + + OwnedBytes ftr_buf(kTableFooterSize); + if (auto r = (*f)->pread_exact(fsize - kTableFooterSize, ftr_buf); !r) { + return Void::Result::fail(std::move(r).error()); + } + auto ftr = decode_table_footer(ftr_buf); + if (!ftr) return Void::Result::fail(std::move(ftr).error()); + if (ftr->file_crc32c != meta.file_crc32c) { + return Void::Result::fail(format_corrupt("Table file_crc32c mismatches manifest")); + } + if (ftr->data_end_offset < kTableHeaderSize || + ftr->index_offset != ftr->data_end_offset || + ftr->index_size > fsize - kTableFooterSize - ftr->index_offset || + ftr->index_offset + ftr->index_size != fsize - kTableFooterSize || + ftr->index_size > limits.max_manifest_bytes) { + return Void::Result::fail(format_corrupt("Table footer offsets invalid")); + } + + OwnedBytes idx_buf(static_cast(ftr->index_size)); + if (auto r = (*f)->pread_exact(ftr->index_offset, idx_buf); !r) { + return Void::Result::fail(std::move(r).error()); + } + auto idx = decode_table_index(idx_buf, limits.max_key_bytes); + if (!idx) return Void::Result::fail(std::move(idx).error()); + + std::uint64_t cursor_off = kTableHeaderSize; + for (std::size_t i = 0; i < idx->size(); ++i) { + const auto& b = (*idx)[i]; + if (b.offset != cursor_off || + b.byte_length < 8 || + b.offset + b.byte_length > ftr->data_end_offset) { + return Void::Result::fail(format_corrupt("Table block offset/length overlap")); + } + if (byte_compare(b.first_key, b.last_key) > 0) { + return Void::Result::fail(format_corrupt("Table index block key order inverted")); + } + if (i > 0 && byte_compare((*idx)[i - 1].last_key, b.first_key) > 0) { + return Void::Result::fail(format_corrupt("Table index across blocks is not ordered")); + } + cursor_off += b.byte_length; + } + if (cursor_off != ftr->data_end_offset) { + return Void::Result::fail(format_corrupt("Table blocks do not cover data region")); + } + + auto reader = std::shared_ptr(new TableReader()); + reader->m_port = std::move(port); + reader->m_path = std::move(path); + reader->m_meta = meta; + reader->m_header = *hdr; + reader->m_footer = *ftr; + reader->m_limits = limits; + reader->m_index = std::move(*idx); + reader->m_cached_handle = std::move(*f); + return reader; + } + + Result> TableReader::read_block(std::size_t block_idx) const + { + if (block_idx >= m_index.size()) { + return Void::Result::fail(format_invalid("Table block index out of range")); + } + const auto& be = m_index[block_idx]; + OwnedBytes buf(be.byte_length); + { + std::lock_guard lk{m_handle_mu}; + if (!m_cached_handle) { + auto f = m_port->open_file(m_path, FileOpenMode::ReadOnly); + if (!f) return Void::Result::fail(std::move(f).error()); + m_cached_handle = std::move(*f); + } + if (auto r = m_cached_handle->pread_exact(be.offset, buf); !r) { + return Void::Result::fail(std::move(r).error()); + } + } + return decode_table_block(buf, m_limits.max_key_bytes, m_limits.max_value_bytes); + } + + Result> TableReader::lookup( + ByteView key, + Sequence snap_seq) const + { + if (m_index.empty() || snap_seq < m_meta.min_sequence) { + return std::optional{std::nullopt}; + } + if (byte_compare(key, m_meta.min_key) < 0 || + byte_compare(key, m_meta.max_key) > 0) { + return std::optional{std::nullopt}; + } + + // Find first block whose last_key >= key. + auto it = std::lower_bound( + m_index.begin(), m_index.end(), key, + [](const TableBlockIndexEntry& blk, ByteView k) { + return byte_compare(blk.last_key, k) < 0; + }); + if (it == m_index.end()) { + return std::optional{std::nullopt}; + } + + std::size_t bi = static_cast(it - m_index.begin()); + for (; bi < m_index.size(); ++bi) { + if (byte_compare(m_index[bi].first_key, key) > 0) { + break; + } + auto entries = read_block(bi); + if (!entries) return Void::Result::fail(std::move(entries).error()); + for (const auto& e : *entries) { + const int cmp = byte_compare(e.key, key); + if (cmp == 0) { + if (e.sequence <= snap_seq) { + return std::optional{e}; + } + } else if (cmp > 0) { + return std::optional{std::nullopt}; + } + } + } + return std::optional{std::nullopt}; + } + + Result TableReader::verify_all_blocks_and_file_crc() const + { + auto f = m_port->open_file(m_path, FileOpenMode::ReadOnly); + if (!f) return Void::Result::fail(std::move(f).error()); + + // 1. Verify full-file CRC32C up to footer. + const std::uint64_t hashed_bytes = m_meta.file_size - kTableFooterSize; + std::uint32_t running_crc = crc32c_init(); + std::vector chunk(65536); + std::uint64_t off = 0; + while (off < hashed_bytes) { + const std::size_t n = static_cast( + std::min(chunk.size(), hashed_bytes - off)); + if (auto r = (*f)->pread_exact(off, std::span{chunk.data(), n}); !r) { + return Void::Result::fail(std::move(r).error()); + } + running_crc = crc32c_update(running_crc, std::span{chunk.data(), n}); + off += n; + } + if (crc32c_finalize(running_crc) != m_footer.file_crc32c) { + return Void::Result::fail(format_corrupt( + std::format("Table '{}' full-file CRC32C mismatch", m_path.string()))); + } + + // 2. Verify every individual block CRC and entry sort order. + std::uint64_t total_entries = 0; + for (std::size_t i = 0; i < m_index.size(); ++i) { + auto entries = read_block(i); + if (!entries) return Void::Result::fail(std::move(entries).error()); + if (entries->empty()) { + return Void::Result::fail(format_corrupt("Empty block inside immutable table")); + } + for (std::size_t j = 1; j < entries->size(); ++j) { + const auto& prev = (*entries)[j - 1]; + const auto& cur = (*entries)[j]; + const int kc = byte_compare(prev.key, cur.key); + if (kc > 0 || (kc == 0 && prev.sequence <= cur.sequence)) { + return Void::Result::fail(format_corrupt("Table entries out of sorted order")); + } + } + total_entries += entries->size(); + } + if (total_entries != m_meta.entry_count) { + return Void::Result::fail(format_corrupt("Table entry_count mismatch")); + } + return static_cast(m_index.size()); + } + + Result write_sorted_table( + FilePort& port, + const std::filesystem::path& tmp_path, + const std::filesystem::path& final_path, + Void::Uuid::Uuid db_uuid, + std::uint64_t table_id, + std::uint32_t level, + const std::vector& sorted_entries, + const Limits& limits) + { + if (sorted_entries.empty()) { + return Void::Result::fail(format_invalid("Cannot write empty immutable table")); + } + + TableMeta meta; + meta.table_id = table_id; + meta.level = level; + meta.entry_count = sorted_entries.size(); + meta.min_sequence = sorted_entries.front().sequence; + meta.max_sequence = sorted_entries.front().sequence; + meta.min_key = sorted_entries.front().key; + meta.max_key = sorted_entries.back().key; + + for (std::size_t i = 0; i < sorted_entries.size(); ++i) { + const auto& e = sorted_entries[i]; + meta.min_sequence = std::min(meta.min_sequence, e.sequence); + meta.max_sequence = std::max(meta.max_sequence, e.sequence); + if (i > 0) { + const int kc = byte_compare(sorted_entries[i - 1].key, e.key); + if (kc > 0 || (kc == 0 && sorted_entries[i - 1].sequence <= e.sequence)) { + return Void::Result::fail(format_invalid( + "write_sorted_table received unsorted or duplicate-sequence entries")); + } + } + } + + TableHeader hdr; + hdr.database_uuid = db_uuid; + hdr.table_id = table_id; + hdr.level = level; + hdr.entry_count = meta.entry_count; + hdr.min_sequence = meta.min_sequence; + hdr.max_sequence = meta.max_sequence; + + auto hdr_bytes = encode_table_header(hdr); + if (!hdr_bytes) return Void::Result::fail(std::move(hdr_bytes).error()); + + (void)port.unlink_file(tmp_path); + auto f = port.open_file(tmp_path, FileOpenMode::CreateNew); + if (!f) return Void::Result::fail(std::move(f).error()); + + std::uint32_t file_crc = crc32c_init(); + auto write_and_crc = [&](ByteView data) -> Result { + file_crc = crc32c_update(file_crc, data); + return (*f)->append_all(data); + }; + + if (auto w = write_and_crc(*hdr_bytes); !w) { + (void)port.unlink_file(tmp_path); + return Void::Result::fail(std::move(w).error()); + } + + std::uint64_t cursor_off = hdr_bytes->size(); + std::vector index; + std::size_t idx = 0; + const std::size_t block_max_budget = + std::max(limits.table_block_target_bytes, + limits.max_key_bytes + limits.max_value_bytes + 1024); + + while (idx < sorted_entries.size()) { + std::vector chunk; + std::size_t approx_bytes = 8; + while (idx < sorted_entries.size()) { + const std::size_t rec_sz = + 24 + sorted_entries[idx].key.size() + sorted_entries[idx].value.size(); + if (!chunk.empty() && approx_bytes + rec_sz > limits.table_block_target_bytes) { + break; + } + approx_bytes += rec_sz; + chunk.push_back(sorted_entries[idx]); + ++idx; + } + + auto blk_bytes = encode_table_block(chunk, block_max_budget); + if (!blk_bytes) { + (void)port.unlink_file(tmp_path); + return Void::Result::fail(std::move(blk_bytes).error()); + } + auto off_r = write_and_crc(*blk_bytes); + if (!off_r) { + (void)port.unlink_file(tmp_path); + return Void::Result::fail(std::move(off_r).error()); + } + + TableBlockIndexEntry ie; + ie.first_key = chunk.front().key; + ie.last_key = chunk.back().key; + ie.offset = *off_r; + ie.byte_length = static_cast(blk_bytes->size()); + index.push_back(std::move(ie)); + cursor_off += blk_bytes->size(); + } + + const std::uint64_t index_offset = cursor_off; + auto idx_bytes = encode_table_index(index, limits.max_manifest_bytes); + if (!idx_bytes) { + (void)port.unlink_file(tmp_path); + return Void::Result::fail(std::move(idx_bytes).error()); + } + if (auto w = write_and_crc(*idx_bytes); !w) { + (void)port.unlink_file(tmp_path); + return Void::Result::fail(std::move(w).error()); + } + + TableFooter footer; + footer.index_offset = index_offset; + footer.index_size = idx_bytes->size(); + footer.data_end_offset = index_offset; + footer.file_crc32c = crc32c_finalize(file_crc); + + auto ftr_bytes = encode_table_footer(footer); + if (!ftr_bytes) { + (void)port.unlink_file(tmp_path); + return Void::Result::fail(std::move(ftr_bytes).error()); + } + if (auto w = (*f)->append_all(*ftr_bytes); !w) { + (void)port.unlink_file(tmp_path); + return Void::Result::fail(std::move(w).error()); + } + if (auto s = (*f)->sync(); !s) { + (void)port.unlink_file(tmp_path); + return Void::Result::fail(std::move(s).error()); + } + if (auto c = (*f)->close(); !c) { + (void)port.unlink_file(tmp_path); + return Void::Result::fail(std::move(c).error()); + } + + meta.file_crc32c = footer.file_crc32c; + meta.file_size = index_offset + idx_bytes->size() + ftr_bytes->size(); + + if (auto r = port.rename_atomic(tmp_path, final_path); !r) { + (void)port.unlink_file(tmp_path); + return Void::Result::fail(std::move(r).error()); + } + if (auto s = port.sync_dir(final_path.parent_path()); !s) { + return Void::Result::fail(std::move(s).error()); + } + return meta; + } + + Result scan_wal_segment_impl( + FilePort& port, + const std::filesystem::path& path, + Void::Uuid::Uuid expected_uuid, + std::uint64_t expected_seg_id, + std::optional expected_prev_seg_id, + bool check_seg_ids, + bool is_final_active_segment, + const Limits& limits, + bool salvage_mode) + { + auto f = port.open_file(path, FileOpenMode::ReadOnly); + if (!f) return Void::Result::fail(std::move(f).error()); + auto sz_r = (*f)->size(); + if (!sz_r) return Void::Result::fail(std::move(sz_r).error()); + const std::uint64_t fsize = *sz_r; + + if (fsize < kWalSegmentHeaderSize) { + return Void::Result::fail(format_corrupt( + std::format("WAL segment '{}' shorter than 64-byte header", path.string()))); + } + OwnedBytes seg_hdr_buf(kWalSegmentHeaderSize); + if (auto r = (*f)->pread_exact(0, seg_hdr_buf); !r) { + return Void::Result::fail(std::move(r).error()); + } + auto seg_hdr = decode_wal_segment_header(seg_hdr_buf); + if (!seg_hdr) return Void::Result::fail(std::move(seg_hdr).error()); + if (seg_hdr->database_uuid != expected_uuid) { + return Void::Result::fail(format_corrupt("WAL segment UUID mismatch")); + } + if (check_seg_ids) { + if (seg_hdr->segment_id != expected_seg_id) { + return Void::Result::fail(format_corrupt( + std::format("WAL segment ID mismatch on '{}'", path.string()))); + } + if (expected_prev_seg_id.has_value()) { + if (seg_hdr->previous_segment_id != *expected_prev_seg_id) { + return Void::Result::fail(format_corrupt( + std::format("WAL segment chain mismatch on '{}'", path.string()))); + } + } else if (seg_hdr->previous_segment_id == 0 || + seg_hdr->previous_segment_id >= seg_hdr->segment_id) { + return Void::Result::fail(format_corrupt( + std::format("WAL post-checkpoint previous_segment_id invalid on '{}'", path.string()))); + } + } + + WalSegmentScanResult out; + out.header = *seg_hdr; + out.file_size = fsize; + + std::uint64_t pos = kWalSegmentHeaderSize; + std::uint64_t batch_start_offset = pos; + bool in_batch = false; + Sequence active_batch_seq = 0; + std::uint32_t expected_ops = 0; + std::uint64_t expected_op_bytes = 0; + std::uint32_t seen_ops = 0; + std::uint64_t seen_op_bytes = 0; + std::uint32_t agg_crc = crc32c_init(); + std::vector pending_entries; + + auto trigger_tail_truncate = [&]() -> Result { + if (!is_final_active_segment) { + return Void::Result::fail(format_corrupt( + std::format("WAL segment '{}' is closed yet has uncommitted/incomplete tail at {}", + path.string(), batch_start_offset))); + } + out.truncate_offset = batch_start_offset; + return out; + }; + + while (pos < fsize) { + const std::uint64_t rem = fsize - pos; + if (rem < kWalRecordHeaderSize) { + if (salvage_mode) { + out.truncate_offset = batch_start_offset; + return out; + } + return trigger_tail_truncate(); + } + + OwnedBytes rh_buf(kWalRecordHeaderSize); + if (auto r = (*f)->pread_exact(pos, rh_buf); !r) { + return Void::Result::fail(std::move(r).error()); + } + auto rh = decode_wal_record_header(rh_buf, limits.max_batch_encoded_bytes); + if (!rh) { + if (salvage_mode) { + out.truncate_offset = batch_start_offset; + return out; + } + return Void::Result::fail(std::move(rh).error()); + } + + if (pos + rh->total_length > fsize) { + // Incomplete record body at physical EOF! + if (salvage_mode) { + out.truncate_offset = batch_start_offset; + return out; + } + return trigger_tail_truncate(); + } + + OwnedBytes full_rec(rh->total_length); + if (auto r = (*f)->pread_exact(pos, full_rec); !r) { + return Void::Result::fail(std::move(r).error()); + } + if (auto vr = verify_wal_record_frame(*rh, full_rec); !vr) { + if (salvage_mode) { + out.truncate_offset = batch_start_offset; + return out; + } + return Void::Result::fail(std::move(vr).error()); + } + + const ByteView payload{ + full_rec.data() + kWalRecordHeaderSize, + rh->payload_length}; + + if (rh->type == WalRecordType::Begin) { + if (in_batch || rh->ordinal != 0 || rh->batch_sequence == 0 || + rh->batch_sequence < seg_hdr->first_candidate_sequence) { + if (salvage_mode) { + out.truncate_offset = batch_start_offset; + return out; + } + return Void::Result::fail(format_corrupt("Malformed WAL BEGIN ordering or sequence")); + } + auto bp = decode_wal_begin_payload(payload); + if (!bp) { + if (salvage_mode) { + out.truncate_offset = batch_start_offset; + return out; + } + return Void::Result::fail(std::move(bp).error()); + } + if (bp->op_count > limits.max_batch_mutations || + bp->total_op_bytes > limits.max_batch_encoded_bytes) { + return Void::Result::fail(format_corrupt("WAL BEGIN exceeds batch limits")); + } + batch_start_offset = pos; + in_batch = true; + active_batch_seq = rh->batch_sequence; + expected_ops = bp->op_count; + expected_op_bytes = bp->total_op_bytes; + seen_ops = 0; + seen_op_bytes = 0; + pending_entries.clear(); + pending_entries.reserve(expected_ops); + agg_crc = crc32c_update(crc32c_init(), full_rec); + } else if (rh->type == WalRecordType::Put || rh->type == WalRecordType::Erase) { + if (!in_batch || rh->batch_sequence != active_batch_seq || + rh->ordinal != seen_ops + 1 || seen_ops >= expected_ops) { + if (salvage_mode) { + out.truncate_offset = batch_start_offset; + return out; + } + return Void::Result::fail(format_corrupt("WAL operation record out of sequence")); + } + const bool is_erase = (rh->type == WalRecordType::Erase); + auto mp = decode_wal_mutation_payload( + is_erase, payload, limits.max_key_bytes, limits.max_value_bytes); + if (!mp) { + if (salvage_mode) { + out.truncate_offset = batch_start_offset; + return out; + } + return Void::Result::fail(std::move(mp).error()); + } + seen_op_bytes += mp->key.size() + mp->value.size(); + if (seen_op_bytes > expected_op_bytes) { + return Void::Result::fail(format_corrupt("WAL batch operation byte count exceeded BEGIN header")); + } + TableEntryRecord tr; + tr.key = std::move(mp->key); + tr.value = std::move(mp->value); + tr.sequence = active_batch_seq; + tr.erased = is_erase; + pending_entries.push_back(std::move(tr)); + ++seen_ops; + agg_crc = crc32c_update(agg_crc, full_rec); + } else if (rh->type == WalRecordType::Commit) { + if (!in_batch || rh->batch_sequence != active_batch_seq || + rh->ordinal != expected_ops + 1 || + seen_ops != expected_ops || + seen_op_bytes != expected_op_bytes) { + if (salvage_mode) { + out.truncate_offset = batch_start_offset; + return out; + } + return Void::Result::fail(format_corrupt("WAL COMMIT record inconsistent with batch")); + } + auto cp = decode_wal_commit_payload(payload); + if (!cp) { + if (salvage_mode) { + out.truncate_offset = batch_start_offset; + return out; + } + return Void::Result::fail(std::move(cp).error()); + } + if (cp->op_count != expected_ops || + cp->total_op_bytes != expected_op_bytes || + cp->aggregate_crc32c != crc32c_finalize(agg_crc)) { + if (salvage_mode) { + out.truncate_offset = batch_start_offset; + return out; + } + return Void::Result::fail(format_corrupt("WAL COMMIT aggregate CRC32C or count mismatch")); + } + WalRecoveredBatch batch; + batch.sequence = active_batch_seq; + batch.entries = std::move(pending_entries); + out.batches.push_back(std::move(batch)); + + in_batch = false; + pending_entries.clear(); + batch_start_offset = pos + rh->total_length; + } + + pos += rh->total_length; + } + + if (in_batch) { + // Reached EOF with valid BEGIN[+ops] but no COMMIT! + if (salvage_mode) { + out.truncate_offset = batch_start_offset; + return out; + } + return trigger_tail_truncate(); + } + + return out; + } + + Result scan_wal_segment( + FilePort& port, + const std::filesystem::path& path, + Void::Uuid::Uuid expected_uuid, + std::uint64_t expected_seg_id, + std::optional expected_prev_seg_id, + bool is_final_active_segment, + const Limits& limits, + bool allow_uncommitted_tail) + { + auto r = scan_wal_segment_impl( + port, path, expected_uuid, expected_seg_id, expected_prev_seg_id, + true, is_final_active_segment, limits, false); + if (!r) return r; + if (!allow_uncommitted_tail && r->truncate_offset.has_value()) { + return Void::Result::fail(format_corrupt("Unexpected uncommitted WAL tail")); + } + return r; + } + + Result salvage_wal_segment( + FilePort& port, + const std::filesystem::path& path, + Void::Uuid::Uuid expected_uuid, + const Limits& limits) + { + return scan_wal_segment_impl( + port, path, expected_uuid, 0, std::nullopt, false, true, limits, true); + } + } // namespace detail + +} // namespace Void::Storage diff --git a/src/Storage/TableInternal.hpp b/src/Storage/TableInternal.hpp new file mode 100644 index 0000000..cba28c7 --- /dev/null +++ b/src/Storage/TableInternal.hpp @@ -0,0 +1,98 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include + +namespace Void::Storage::detail +{ + class TableReader final + { + public: + [[nodiscard]] static Result> open( + std::shared_ptr port, + std::filesystem::path path, + Void::Uuid::Uuid expected_uuid, + const TableMeta& meta, + const Limits& limits); + + [[nodiscard]] const TableMeta& meta() const noexcept { return m_meta; } + [[nodiscard]] const std::filesystem::path& path() const noexcept { return m_path; } + [[nodiscard]] const std::vector& index() const noexcept + { + return m_index; + } + + /// Lookup highest version <= snap_seq for exact `key`. + /// Returns std::nullopt if `key` is absent at <= snap_seq in this table; + /// returns TableEntryRecord{key, seq, erased, value} if present (including tombstone). + [[nodiscard]] Result> lookup( + ByteView key, + Sequence snap_seq) const; + + /// Read and decode block `block_idx` while verifying its CRC32C. + [[nodiscard]] Result> read_block( + std::size_t block_idx) const; + + /// Verify every block's CRC32C, key ordering, AND full-file CRC32C. + [[nodiscard]] Result verify_all_blocks_and_file_crc() const; + + private: + TableReader() = default; + + std::shared_ptr m_port{}; + std::filesystem::path m_path{}; + TableMeta m_meta{}; + TableHeader m_header{}; + TableFooter m_footer{}; + Limits m_limits{}; + std::vector m_index{}; + mutable std::mutex m_handle_mu{}; + mutable std::unique_ptr m_cached_handle{}; + }; + + [[nodiscard]] Result write_sorted_table( + FilePort& port, + const std::filesystem::path& tmp_path, + const std::filesystem::path& final_path, + Void::Uuid::Uuid db_uuid, + std::uint64_t table_id, + std::uint32_t level, + const std::vector& sorted_entries, + const Limits& limits); + + /// Validate and replay a WAL segment, filling `recovered_batches` with valid committed batches. + struct WalRecoveredBatch { + Sequence sequence{0}; + std::vector entries{}; + }; + + struct WalSegmentScanResult { + WalSegmentHeader header{}; + std::vector batches{}; + std::uint64_t file_size{0}; + std::optional truncate_offset{}; + }; + + [[nodiscard]] Result scan_wal_segment( + FilePort& port, + const std::filesystem::path& path, + Void::Uuid::Uuid expected_uuid, + std::uint64_t expected_seg_id, + std::optional expected_prev_seg_id, + bool is_final_active_segment, + const Limits& limits, + bool allow_uncommitted_tail = true); + + /// Salvage scan: recovers as many valid complete committed batches as possible before stopping. + [[nodiscard]] Result salvage_wal_segment( + FilePort& port, + const std::filesystem::path& path, + Void::Uuid::Uuid expected_uuid, + const Limits& limits); + +} // namespace Void::Storage::detail diff --git a/src/Storage/Tools.cpp b/src/Storage/Tools.cpp new file mode 100644 index 0000000..75f8d8e --- /dev/null +++ b/src/Storage/Tools.cpp @@ -0,0 +1,327 @@ +#include +#include +#include +#include +#include "TableInternal.hpp" + +#include +#include +#include +#include +#include + +namespace Void::Storage +{ + namespace + { + [[nodiscard]] Result read_entire_file( + FilePort& port, + const std::filesystem::path& path, + std::size_t max_bytes) + { + auto sz_r = port.file_size(path); + if (!sz_r) return Void::Result::fail(std::move(sz_r).error()); + if (*sz_r > max_bytes) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::corrupt, + std::format("Storage tool: '{}' size {} exceeds bound {}", + path.string(), *sz_r, max_bytes))); + } + OwnedBytes out(*sz_r); + auto f = port.open_file(path, FileOpenMode::ReadOnly); + if (!f) return Void::Result::fail(std::move(f).error()); + if (*sz_r > 0) { + if (auto r = (*f)->pread_exact(0, out); !r) { + return Void::Result::fail(std::move(r).error()); + } + } + return out; + } + } // namespace + + Result verify_directory( + const std::filesystem::path& directory, + const Limits& limits, + std::shared_ptr port) + { + if (directory.empty()) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::invalid_argument, "verify_directory: empty directory")); + } + if (auto vl = validate_limits(limits); !vl) { + return Void::Result::fail(std::move(vl).error()); + } + if (!port) port = make_posix_file_port(); + + auto cur_bytes = read_entire_file(*port, directory / "CURRENT", 512); + if (!cur_bytes) return Void::Result::fail(std::move(cur_bytes).error()); + auto cur = decode_current(*cur_bytes); + if (!cur) return Void::Result::fail(std::move(cur).error()); + + auto man_bytes = read_entire_file( + *port, directory / cur->manifest_filename, limits.max_manifest_bytes); + if (!man_bytes) return Void::Result::fail(std::move(man_bytes).error()); + auto man = decode_manifest( + *man_bytes, limits.max_manifest_bytes, limits.max_manifest_tables, limits.max_key_bytes); + if (!man) return Void::Result::fail(std::move(man).error()); + + if (man->database_uuid != cur->database_uuid || man->generation != cur->generation) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::corrupt, "verify_directory: manifest mismatches CURRENT")); + } + + VerifyReport report; + report.manifest_generation = man->generation; + report.checkpoint_sequence = man->checkpoint_sequence; + + for (const auto& tm : man->tables) { + auto tr = detail::TableReader::open( + port, + directory / make_table_filename(tm.table_id), + man->database_uuid, + tm, + limits); + if (!tr) return Void::Result::fail(std::move(tr).error()); + auto blks = (*tr)->verify_all_blocks_and_file_crc(); + if (!blks) return Void::Result::fail(std::move(blks).error()); + ++report.tables_verified; + report.blocks_verified += *blks; + } + + for (std::size_t i = 0; i < man->wal_segments.size(); ++i) { + const auto seg_id = man->wal_segments[i]; + const bool is_final = (i + 1 == man->wal_segments.size()); + const std::optional exp_prev = + (i > 0) ? std::optional{man->wal_segments[i - 1]} + : (seg_id == 1 ? std::optional{0} : std::nullopt); + auto scan = detail::scan_wal_segment( + *port, + directory / make_wal_filename(seg_id), + man->database_uuid, + seg_id, + exp_prev, + is_final, + limits, + true); + if (!scan) return Void::Result::fail(std::move(scan).error()); + ++report.wal_segments_verified; + report.wal_batches_verified += scan->batches.size(); + } + + return report; + } + + Result restore_backup( + const std::filesystem::path& backup_dir, + const std::filesystem::path& destination, + const Limits& limits, + std::shared_ptr port) + { + if (backup_dir.empty() || destination.empty()) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::invalid_argument, "restore_backup: empty path")); + } + if (!port) port = make_posix_file_port(); + + std::error_code ec; + if (std::filesystem::exists(destination, ec) && + std::filesystem::equivalent(backup_dir, destination, ec)) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::invalid_argument, + "restore_backup: source and destination cannot be identical")); + } + + auto vr = verify_directory(backup_dir, limits, port); + if (!vr) return Void::Result::fail(std::move(vr).error()); + + if (auto ed = port->ensure_dir(destination); !ed) return ed; + auto lock = port->lock_directory(destination); + if (!lock) return Void::Result::fail(std::move(lock).error()); + + auto cur_bytes = read_entire_file(*port, backup_dir / "CURRENT", 512); + if (!cur_bytes) return Void::Result::fail(std::move(cur_bytes).error()); + auto cur = decode_current(*cur_bytes); + if (!cur) return Void::Result::fail(std::move(cur).error()); + + auto man_bytes = read_entire_file( + *port, backup_dir / cur->manifest_filename, limits.max_manifest_bytes); + if (!man_bytes) return Void::Result::fail(std::move(man_bytes).error()); + auto man = decode_manifest( + *man_bytes, limits.max_manifest_bytes, limits.max_manifest_tables, limits.max_key_bytes); + if (!man) return Void::Result::fail(std::move(man).error()); + + auto copy_file = [&](const std::string& name) -> Result { + const auto src = backup_dir / name; + const auto dst = destination / name; + const auto dst_tmp = destination / (name + ".tmp"); + auto sz = port->file_size(src); + if (!sz) return Void::Result::fail(std::move(sz).error()); + OwnedBytes buf(*sz); + auto sf = port->open_file(src, FileOpenMode::ReadOnly); + if (!sf) return Void::Result::fail(std::move(sf).error()); + if (*sz > 0) { + if (auto r = (*sf)->pread_exact(0, buf); !r) return r; + } + (void)port->unlink_file(dst_tmp); + auto df = port->open_file(dst_tmp, FileOpenMode::CreateNew); + if (!df) return Void::Result::fail(std::move(df).error()); + if (!buf.empty()) { + if (auto w = (*df)->append_all(buf); !w) return Void::Result::fail(std::move(w).error()); + } + if (auto s = (*df)->sync(); !s) return s; + if (auto c = (*df)->close(); !c) return c; + return port->rename_atomic(dst_tmp, dst); + }; + + for (const auto& tm : man->tables) { + if (auto r = copy_file(make_table_filename(tm.table_id)); !r) return r; + } + for (const auto seg : man->wal_segments) { + if (auto r = copy_file(make_wal_filename(seg)); !r) return r; + } + if (auto r = copy_file(cur->manifest_filename); !r) return r; + if (auto r = copy_file("CURRENT"); !r) return r; + return port->sync_dir(destination); + } + + Result salvage_directory( + const std::filesystem::path& source_dir, + const std::filesystem::path& destination_dir, + const Limits& limits, + std::shared_ptr port) + { + if (source_dir.empty() || destination_dir.empty()) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::invalid_argument, "salvage_directory: empty path")); + } + if (auto vl = validate_limits(limits); !vl) { + return Void::Result::fail(std::move(vl).error()); + } + if (!port) port = make_posix_file_port(); + + std::error_code ec; + if (std::filesystem::exists(destination_dir, ec) && + std::filesystem::equivalent(source_dir, destination_dir, ec)) { + return Void::Result::fail(make_storage_error( + StorageErrorCode::invalid_argument, + "salvage_directory: offline salvage must write into a distinct destination directory")); + } + + // Collect latest committed/recoverable key states without mutating source_dir! + struct Val { + Sequence seq{0}; + bool erased{false}; + OwnedBytes bytes{}; + }; + std::map kv; + SalvageReport rep; + + std::optional db_uuid; + std::vector files; + if (auto fl = port->list_dir(source_dir); fl) { + files = std::move(*fl); + } else { + return Void::Result::fail(std::move(fl).error()); + } + + // Try CURRENT -> Manifest if intact, so valid checkpoint tables are recovered too. + if (auto ce = port->exists(source_dir / "CURRENT"); ce && *ce) { + auto cb = read_entire_file(*port, source_dir / "CURRENT", 512); + if (cb) { + if (auto cp = decode_current(*cb); cp) { + db_uuid = cp->database_uuid; + if (auto mb = read_entire_file(*port, source_dir / cp->manifest_filename, limits.max_manifest_bytes); mb) { + if (auto md = decode_manifest(*mb, limits.max_manifest_bytes, limits.max_manifest_tables, limits.max_key_bytes); md) { + for (const auto& tm : md->tables) { + auto tr = detail::TableReader::open( + port, source_dir / make_table_filename(tm.table_id), + md->database_uuid, tm, limits); + if (!tr) continue; + for (std::size_t bi = 0; bi < (*tr)->index().size(); ++bi) { + auto blk = (*tr)->read_block(bi); + if (!blk) continue; + for (const auto& e : *blk) { + auto it = kv.find(e.key); + if (it == kv.end() || e.sequence > it->second.seq) { + kv[e.key] = Val{e.sequence, e.erased, e.value}; + } + rep.highest_recovered_sequence = + std::max(rep.highest_recovered_sequence, e.sequence); + } + } + } + } + } + } + } + } + + // Scan every WAL-*.vwal in lexicographic name order stopping at first damaged record. + for (const auto& fname : files) { + if (!fname.starts_with("WAL-") || !fname.ends_with(".vwal")) continue; + const auto wpath = source_dir / fname; + // Peek segment header for UUID if CURRENT/Manifest wasn't usable. + if (!db_uuid.has_value()) { + OwnedBytes hdr_b(kWalSegmentHeaderSize); + auto wf = port->open_file(wpath, FileOpenMode::ReadOnly); + if (wf && (*wf)->pread_exact(0, hdr_b).has_value()) { + if (auto dec = decode_wal_segment_header(hdr_b); dec) { + db_uuid = dec->database_uuid; + } + } + } + if (!db_uuid.has_value()) continue; + auto scan = detail::salvage_wal_segment(*port, wpath, *db_uuid, limits); + if (!scan) continue; + if (scan->truncate_offset.has_value()) { + rep.truncated_or_skipped_bytes += (scan->file_size - *scan->truncate_offset); + } + for (const auto& b : scan->batches) { + ++rep.recovered_batches; + rep.highest_recovered_sequence = + std::max(rep.highest_recovered_sequence, b.sequence); + for (const auto& e : b.entries) { + auto it = kv.find(e.key); + if (it == kv.end() || e.sequence > it->second.seq) { + kv[e.key] = Val{e.sequence, e.erased, e.value}; + } + } + } + } + + // Materialize salvaged data into fresh destination directory preserving versions! + OpenOptions out_opts; + out_opts.directory = destination_dir; + out_opts.limits = limits; + out_opts.file_port = port; + out_opts.initial_sequence = rep.highest_recovered_sequence; + auto dest_eng = Engine::open(std::move(out_opts)); + if (!dest_eng) return Void::Result::fail(std::move(dest_eng).error()); + + Batch batch; + std::size_t approx = 0; + for (const auto& [k, v] : kv) { + if (v.erased) { + ++rep.tombstones_preserved; + continue; + } + ++rep.keys_recovered; + if (batch.mutations().size() + 1 > limits.max_batch_mutations || + approx + k.size() + v.bytes.size() + 128 > limits.max_batch_encoded_bytes) { + auto wr = dest_eng->write(std::move(batch), Durability::Sync); + if (!wr.has_value()) return Void::Result::fail(wr.error().cause.error); + batch = Batch{}; + approx = 0; + } + batch.put(k, v.bytes); + approx += k.size() + v.bytes.size() + 64; + } + if (!batch.empty()) { + auto wr = dest_eng->write(std::move(batch), Durability::Sync); + if (!wr.has_value()) return Void::Result::fail(wr.error().cause.error); + } + if (auto cl = dest_eng->close(); !cl) return Void::Result::fail(std::move(cl).error()); + return rep; + } + +} // namespace Void::Storage diff --git a/src/Storage/module.cmake b/src/Storage/module.cmake new file mode 100644 index 0000000..f1832eb --- /dev/null +++ b/src/Storage/module.cmake @@ -0,0 +1,3 @@ +void_add_module(Storage + INTERNAL_DEPS Core Functional Time Memory Binary IO Async +) diff --git a/tests/package/InstalledComponents.cmake b/tests/package/InstalledComponents.cmake index 8d93270..a580065 100644 --- a/tests/package/InstalledComponents.cmake +++ b/tests/package/InstalledComponents.cmake @@ -232,6 +232,11 @@ if(_has_sqlite_async) -DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE) endif() +has_modules(_has_storage Storage Core Functional Time Memory Binary IO Async) +if(_has_storage) + run_consumer(StorageOnly "${install_prefix}" "StorageOnly" ${_no_external_deps}) +endif() + # Foundation consumer with Core-formatting bridge and zero external packages. has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core) if(_has_foundation) diff --git a/tests/package/StorageOnly/CMakeLists.txt b/tests/package/StorageOnly/CMakeLists.txt new file mode 100644 index 0000000..841f2cf --- /dev/null +++ b/tests/package/StorageOnly/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidStorageOnlyConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS Storage) + +add_executable(void_storage_only_consumer main.cpp) +target_link_libraries(void_storage_only_consumer PRIVATE Void::Storage) +target_compile_features(void_storage_only_consumer PRIVATE cxx_std_26) + +enable_testing() +add_test(NAME StorageOnlyConsumer COMMAND void_storage_only_consumer) diff --git a/tests/package/StorageOnly/main.cpp b/tests/package/StorageOnly/main.cpp new file mode 100644 index 0000000..8dc4a4f --- /dev/null +++ b/tests/package/StorageOnly/main.cpp @@ -0,0 +1,36 @@ +#include + +#include +#include +#include + +int main() +{ + if (Void::Storage::crc32c(std::string_view{"123456789"}) != 0xE3069283u) { + return 1; + } + const auto dir = std::filesystem::temp_directory_path() / + ("void-storage-pkg-" + std::to_string(::getpid())); + std::error_code ec; + std::filesystem::remove_all(dir, ec); + + Void::Storage::OpenOptions opts; + opts.directory = dir; + auto eng = Void::Storage::Engine::open(opts); + if (!eng) return 2; + + Void::Storage::Batch b; + b.require_absent("hello").put("hello", "world"); + auto wr = eng->write(std::move(b), Void::Storage::Durability::Sync); + if (!wr) return 3; + + auto snap = eng->snapshot(); + if (!snap) return 4; + auto val = eng->get(*snap, "hello"); + const bool ok = val && val->as_string_view() == "world" && val->version == wr->sequence; + snap->reset(); + const bool closed = eng->close().has_value(); + + std::filesystem::remove_all(dir, ec); + return (ok && closed) ? 0 : 5; +} diff --git a/tests/standalone/Storage/Storage.cpp b/tests/standalone/Storage/Storage.cpp new file mode 100644 index 0000000..18c1cc0 --- /dev/null +++ b/tests/standalone/Storage/Storage.cpp @@ -0,0 +1,855 @@ +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + using namespace Void::Storage; + + struct TempStorageDir { + std::filesystem::path path; + TempStorageDir() + { + static std::atomic 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 run_async_stop_before_append( + AsyncStorageAdapter& adapter, + std::expected* 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 run_async_write_tracked( + AsyncStorageAdapter& adapter, + std::string key, + std::string val, + std::stop_token st, + std::expected* out, + std::atomic* 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(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(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{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{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 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 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(StorageErrorCode::busy)); + auto pg = cur->next_page(); + Void::Testing::require(pg.has_value()); + Void::Testing::expect_eq(pg->entries.size(), static_cast(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(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::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(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 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('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(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::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('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(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(); + 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(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(); + 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(); + 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(0)); + Void::Testing::require(eng2->close().has_value()); + } + } + + Void::Coro::Task drive_stop_before_append_test( + AsyncStorageAdapter& adapter, + std::expected* out, + bool* done) + { + co_await run_async_stop_before_append(adapter, out, done); + } + + Void::Coro::Task drive_tracked_write_test( + AsyncStorageAdapter& adapter, + std::string key, + std::string val, + std::stop_token st, + std::expected* out, + std::atomic* 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(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(); + 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 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 in_sync{false}; + std::atomic 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 out = + std::unexpected{WriteFailure{{}, Outcome::Unknown}}; + std::atomic 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 in_sync{false}; + std::atomic 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 out = CommitReceipt{}; + std::atomic 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