diff --git a/docs/agent-workflow/STATE.md b/docs/agent-workflow/STATE.md index 39cff26..affc963 100644 --- a/docs/agent-workflow/STATE.md +++ b/docs/agent-workflow/STATE.md @@ -1,9 +1,8 @@ # Workflow state -Updated: 2026-11-25. -Repository: VoidLibrary; active branch `feat/roadmap-p2-wave6b` (from `main` -at `acd77ee`, merged Waves 1–6A plus RFC 8259 decimal `StrictJson` and pushed -to `origin/main`). +Updated: 2026-11-26. +Repository: VoidLibrary; active branch `feat/roadmap-p2-wave7` (from `main` +at `43922d1`, merged Waves 1–6B and pushed to `origin/main`). ## Completed objective @@ -302,10 +301,17 @@ while leaving local untracked files untouched. `binary_reader_u64_be` 1.31 ns, `data_json_parse_small_object` 333.32 ns, `data_json_serialize_small_object` 165.99 ns. +### Wave 7 (P2 Persistence & Storage: `Sqlite`, `SqliteAsync`, and NEW Original `Storage` — `G-STORE` Gate) + +- Task specs committed on `feat/roadmap-p2-wave7` (`9925ea1`): `tasks/M-SQLITE-01-05.md`, `tasks/S-STORAGE-01-06.md`. +- **`Void::Sqlite` & `Void::SqliteAsync`** (`427cc9a`, TSan lock-order fix `84e6fe8`): hardened `ConnectionState`, `open_database`/`OpenOptions` with checked WAL/FULL/`foreign_keys` pragmas and disabled extension loading, checked positional/named binds, borrowed lifetime owners, strict typed `RowView`/getters, `Transaction` (`sqlite3_get_autocommit`), `Savepoint`, `close()` busy guard, `migrate_checked` with `_void_schema_migrations`, `checkpoint`/`backup_to`/`restore_from`/`health`, exception-safe callbacks, `ScopedFaultGuard`, plus optional `Void::SqliteAsync` (`AsyncPool`, bounded workers, leased interrupt cleanup) and `SqliteOnly`/`SqliteAsyncOnly` installed consumers. +- **`Void::Storage` (`G-STORE` Gate)** (`fdf0da5`): built NEW original durable single-writer key-value storage engine with zero SQLite or external dependencies (`Crc32c`, `Types`, `FilePort`/`PosixFilePort`/`FaultInjectingFilePort`, V1 binary codecs `VOIDWAL1`/`VOIDTBL1`/`VOIDMNF1`/`VOIDCUR1`, `Batch` with preconditions, `Engine` with bootstrap/recovery/tail-truncation/checkpoint/incremental compaction/backup, `Tools` verify/restore/salvage, `AsyncStorageAdapter` C-03 stop-race conformance) and `StorageOnly` installed consumer. +- Integrated verification (`84e6fe8`): `VoidTests` 1,417 tests (1,414 passed, 3 intentionally skipped hardware/root checks, 0 failed across 43 modules in 21.06s), `ctest` 2/2 (all 28 installed consumers in 65.05s), Debug ASan+UBSan 1,417 tests (0 leaks, 0 UB in 36.47s), TSan (`SqliteAsync;Storage;Testing`) 19/19 in 15.38s with 0 warnings, and post-Wave-7 `VoidFoundationBench`. + ## Ownership and next step -Waves 1–6B (`P0`, `P1`, `P2` Operations Foundations, `System`/`SystemAsync`/`IPC`, and -`Crypto`/`CryptoAsync`/`Security`/`SecurityAsync`/`Archive`/`Update`) are complete and -verified on `feat/roadmap-p2-wave6b`, ready to merge into `main`, push to `origin`, and -proceed continuously to **Wave 7 (`Sqlite`, `SqliteAsync`, and NEW original `Storage` -engine — `G-STORE` gate)**. +Waves 1–7 (`P0`, `P1`, `P2` Operations Foundations, `System`/`SystemAsync`/`IPC`, +`Crypto`/`CryptoAsync`/`Security`/`SecurityAsync`/`Archive`/`Update`, and +`Sqlite`/`SqliteAsync`/`Storage` `G-STORE`) are complete and verified on +`feat/roadmap-p2-wave7`, ready to merge `--no-ff` into `main`, push to `origin`, and +proceed continuously to **Wave 8 (`Configuration`, `Fsm`, `Plugin`, `Service`)**. diff --git a/docs/agent-workflow/TASKS.md b/docs/agent-workflow/TASKS.md index 956dc47..25bffc1 100644 --- a/docs/agent-workflow/TASKS.md +++ b/docs/agent-workflow/TASKS.md @@ -94,6 +94,13 @@ These tasks author plans. Future feature task IDs inside those plans remain plan | M-ARCHIVE-01..05 | Hardened `Archive` (`kArchiveErrorDomain = 17`, streaming `Reader` + forensic listing, file-as-parent conflict rejection, exclusive `0700` `StagedTree` + bottom-up `fsync` + Linux `SYS_renameat2(RENAME_NOREPLACE)` atomic `publish()` with `PublicationOutcome::Unknown`, `cleanup_stale_staging`, reproducible `O_NOFOLLOW` `create_archive`, isolated `VoidArchiveWorker` extraction with rlimits + RSS check + parent inventory verification), `ArchiveOnly` consumer (`00d7478`) | [M-ARCHIVE-01-05](tasks/M-ARCHIVE-01-05.md) | VERIFIED | `Archive` 6 + `ArchiveHardening` 3 = 9/9 (`259.0ms`), `ctest` 2/2 (`5.76s`), full RelWithDebInfo (`1,403 ✔`), ASan+UBSan (0 leaks/UB), TSan 9/9 (0 races) | | M-UPDATE-01..06 | Hardened `Update` (`kUpdateErrorDomain = 20`, schema-3 verify-before-payload-parse fix, `StrictJsonProfile` integer-only option, non-forgeable `VerifiedSelection`, `VersionStore::pruneWithPins`, atomic checksummed `ReplayFloorStore`, Ed25519 `TrustStore` rotation/revocation, `ArtifactTransport`, `LifecycleHooks`, checksummed `OperationJournal` halting with `RecoveryRequired`, `InstallCoordinator` with staged archive + `CleanupPending` + idempotent `reconcile`/`retry_cleanup`), `UpdateOnly` consumer (`47736cb`) | [M-UPDATE-01-06](tasks/M-UPDATE-01-06.md) | VERIFIED | `Update` 22 + `UpdateHardening` 3 = 25/25 (`1.91s`), `ctest` 2/2 (`10.64s`), full RelWithDebInfo (`1,403 ✔`), ASan+UBSan (0 leaks/UB), TSan 25/25 (0 races) | +## Wave 7 — P2 Sqlite, SqliteAsync, and Storage (`feat/roadmap-p2-wave7`) + +| ID | Deliverable | Spec | State | Verification summary | +| --- | --- | --- | --- | --- | +| M-SQLITE-01..05 | Hardened `Sqlite` (`kSqliteErrorDomain = 21`, `ConnectionState`, `OpenOptions` checked WAL/FULL/FK pragmas & disabled extension loading, checked binds & borrowed lifetime owners, typed `RowView`, `Transaction` autocommit/busy guards, `Savepoint`, `migrate_checked`, `checkpoint`/`backup_to`/`restore_from`/`health`, exception-safe callbacks, `ScopedFaultGuard`, TSan lock-order fix outside `interrupt_mu`) + optional `SqliteAsync` (`AsyncPool`), `SqliteOnly` & `SqliteAsyncOnly` consumers (`427cc9a`, `84e6fe8`) | [M-SQLITE-01-05](tasks/M-SQLITE-01-05.md) | VERIFIED | Standalone `Sqlite` 14/14 (`426.5ms`), `ctest` 2/2 (`5.11s`), TSan 19/19 (`15.38s`, 0 warnings), full RelWithDebInfo (`1,414 ✔`), ASan+UBSan (0 leaks/UB) | +| S-STORAGE-01..06 | NEW original `Void::Storage` (`kStorageErrorDomain = 9`, zero SQLite/external deps, `Crc32c`, `PosixFilePort`/`FaultInjectingFilePort`, V1 `VOIDWAL1`/`VOIDTBL1`/`VOIDMNF1`/`VOIDCUR1` codecs, `Batch` preconditions, single-writer `Engine` with recovery/tail-truncation/checkpoint/compaction/backup, `Tools` verify/restore/salvage, `AsyncStorageAdapter` C-03 stop-race conformance), `G-STORE` gate, `StorageOnly` consumer (`fdf0da5`) | [S-STORAGE-01-06](tasks/S-STORAGE-01-06.md) | VERIFIED | Standalone zero-ext-deps `Storage` 5/5 (`14.53s`), `ctest` 2/2 (`24.07s`), TSan 19/19 (`15.38s`, 0 warnings), full RelWithDebInfo (`1,414 ✔`), ASan+UBSan (0 leaks/UB) | + All workers share the checkout and have disjoint file ownership defined in their persisted task specifications. Root owns all cross-cutting files and resolves contract changes. No worker owns application code, build files, existing docs/short-url.md, or Git diff --git a/docs/agent-workflow/VERIFICATION.md b/docs/agent-workflow/VERIFICATION.md index fcb3bd3..79302d4 100644 --- a/docs/agent-workflow/VERIFICATION.md +++ b/docs/agent-workflow/VERIFICATION.md @@ -267,3 +267,9 @@ Branch: `feat/roadmap-p2-wave6b` (branched from `main` at `acd77ee`). Toolchain | Full Integrated ASan+UBSan (`47736cb`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug (`/tmp/void-w6b-asan`, 41 modules, `-DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1 UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1 /tmp/void-w6b-asan/tests/VoidTests` | `VoidTests`: 1,406 tests — 1,403 passed, 3 intentional skips (`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed (`21.78s`), 0 ASan/LSan leaks, 0 UBSan errors | | Wave 6B TSan Subset (`47736cb`) | `dev cpp-gcc -p libarchive -p openssl -p libsodium` Debug (`CryptoAsync;SecurityAsync;Update;Testing`, `/tmp/void-w6b-tsan`, 20 modules, `-DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `/tmp/void-w6b-tsan/tests/VoidTests --filter "Crypto*\|crypto_*\|Security*\|security_*\|Archive*\|archive_*\|Update*\|update_*\|component_feed_*\|readable_component_*\|version_store_*"` | 56/56 passed (`4.86s`: `Archive` 6, `ArchiveHardening` 3, `Crypto` 3, `CryptoHardening` 3, `CryptoAsync` 2, `SecurityTests` 8, `SecurityHardening` 4, `SecurityAsync` 2, `Update` 22, `UpdateHardening` 3), 0 TSan data races | | Post-W6B Benchmark (`47736cb`, `rev=47736cb6ce2f`) | `/tmp/void-w6b-full/benchmarks/VoidFoundationBench --json /tmp/void-w6b-full/post-w6b.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.38ns, `core_uuid_parse_hyphenated` 24.52ns, `core_uuid_to_string` 16.53ns, `core_hash_fnv1a64_256b` 179.95ns, `core_hash_murmur3_256b` 67.37ns, `functional_result_ok_chain` 1.12ns, `functional_error_with_context` 58.37ns, `math_checked_add_loop` 0.47ns, `containers_spsc_ring_push_pop` 8.76ns, `containers_lru_get_put` 21.02ns, `binary_reader_u64_be` 1.31ns, `data_json_parse_small_object` 333.32ns, `data_json_serialize_small_object` 165.99ns | +| Wave 7 `Sqlite` & `SqliteAsync` standalone (`84e6fe8`) | `dev cpp-gcc -p sqlite` RelWithDebInfo (`-Werror`, `/tmp/void-w7-sqlite`), 8 modules, `VoidTests --filter 'Sqlite*\|...'` + `ctest` | **PASSED**: `SqliteTests` 8 + `SqliteHardening` 4 + `SqliteAsync` 2 = 14/14 in `426.5ms`; `ctest` 2/2 in `5.11s` (`VoidTests` 0.87s, `VoidInstalledComponentConsumers` including `SqliteOnly` & `SqliteAsyncOnly` 4.23s) | +| Wave 7 `Storage` standalone (`fdf0da5`, `G-STORE`) | `dev cpp-gcc` zero `-p` external deps RelWithDebInfo (`-Werror`, `/tmp/void-w7-storage`), 10 modules, `VoidTests --filter '^storage_'` + `ctest` | **PASSED**: `Storage` 5/5 in `14.53s`; `ctest` 2/2 in `24.07s` (`StorageOnly` verified with Boost/LibArchive/OpenSSL/PkgConfig/SQLite3/Threads disabled) | +| Wave 7 TSan (`84e6fe8`) | `dev cpp-gcc -p sqlite` Debug TSan (`-Werror`, `/tmp/void-w7-tsan`, `TSAN_OPTIONS=halt_on_error=1:second_deadlock_stack=1`), 12 modules (`SqliteAsync;Storage;Testing`) | **PASSED**: 19/19 in `15.38s` (`SqliteTests` 8, `SqliteHardening` 4, `SqliteAsync` 2, `Storage` 5), exit 0, 0 TSan data races / lock-order warnings | +| Wave 7 integrated RelWithDebInfo + consumers (`84e6fe8`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` RelWithDebInfo (`-Werror`, `/tmp/void-w7-full`), 43 modules, `VoidTests` + `ctest` | **PASSED**: `1,417` discovered (`1,414 ✔`, `3 ⊘` skipped, `0 ✘`) in `21.06s`; `ctest` 2/2 in `65.05s` (`VoidTests` 20.95s, all 28 installed consumers 44.10s) | +| Wave 7 full Debug ASan+UBSan (`84e6fe8`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug ASan+UBSan (`-Werror`, `/tmp/void-w7-asan`, `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1`, `UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1`), 43 modules | **PASSED**: `1,417` discovered (`1,414 ✔`, `3 ⊘` skipped, `0 ✘`) in `36.47s`, 0 leaks, 0 UB | +| Post-W7 Benchmark (`84e6fe8`, `VOID_GIT_REV=fdf0da5ca883`) | `/tmp/void-w7-full/benchmarks/VoidFoundationBench --json /tmp/void-w7-full/post-w7.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.40ns, `core_uuid_parse_hyphenated` 25.06ns, `core_uuid_to_string` 16.69ns, `core_hash_fnv1a64_256b` 181.03ns, `core_hash_murmur3_256b` 67.90ns, `functional_result_ok_chain` 1.13ns, `functional_error_with_context` 58.24ns, `math_checked_add_loop` 0.47ns, `containers_spsc_ring_push_pop` 8.80ns, `containers_lru_get_put` 20.62ns, `binary_reader_u64_be` 1.31ns, `data_json_parse_small_object` 310.70ns, `data_json_serialize_small_object` 160.98ns | diff --git a/docs/agent-workflow/tasks/M-SQLITE-01-05.md b/docs/agent-workflow/tasks/M-SQLITE-01-05.md new file mode 100644 index 0000000..9ca8efe --- /dev/null +++ b/docs/agent-workflow/tasks/M-SQLITE-01-05.md @@ -0,0 +1,26 @@ +# M-SQLITE-01..05 — Hardened Sqlite C API Integration & Optional SqliteAsync Pool + +- **Wave**: Wave 7 (`feat/roadmap-p2-wave7`, branched from `main` at `43922d1`) +- **Roadmap reference**: `docs/roadmap/modules/Sqlite.md`, `docs/roadmap/DEPENDENCIES.md` +- **Supported runtime observed**: SQLite 3.54.0 via Nix `sqlite` package + +## Scope & Ownership +- `src/Sqlite/module.cmake`: `INTERNAL_DEPS Functional Time`, `EXTERNAL_DEPS SQLite3::SQLite3`, `EXCLUDE_HEADERS Void/Sqlite/AsyncPool.hpp`. +- `include/Void/Sqlite/Types.hpp`: `kSqliteErrorDomain = 21`, `SqliteErrorCode`, `JournalMode`, `SyncMode`, `BeginMode`, `CheckpointMode`, `TransactionState`, `SqliteLimits`, `OpenOptions`, `EffectiveCapabilities`, `ColumnType`, `ValueView`, `OwnedValue`, `OwnedRow`, `CheckpointReport`, `BackupOptions`, `BackupReport`, `CheckedMigration`, `ConnectionHealth`, `ScopedFaultGuard`. +- `include/Void/Sqlite/Sqlite.hpp` + `src/Sqlite/Sqlite.cpp`: + - Shared `ConnectionState` held by `Database`, `Statement`, `Transaction`, and `Savepoint` so moving/destroying `Database` never leaves dangling pointers. + - Preserve 1.x APIs (`Database::open`, `exec`, `prepare`, `begin`, `last_insert_rowid`, `changes`, `user_version`, `migrate`, `Statement::bind`/`step`/`reset`/`clear_bindings`/column getters, `Transaction::commit`/`rollback`, `Migration`, `OpenMode`). + - Add `open_database(path, OpenOptions)` validating limits/pragmas (`WAL`, `FULL`, `foreign_keys`, disabling extension loading by default, querying effective pragma results). + - Add checked `bind_checked` (positional & named, `ValueView`, `max_value_bytes` cap), borrowed lifetime-owned bindings, `reset_checked`, `clear_bindings_checked`, `finalize_checked`, strict single-statement `prepare` (rejecting non-whitespace trailing SQL), `RowView` with expiration generation, strict typed column reads rejecting coercion, `query_all` with row/byte caps. + - Transaction state machine (`Active`, `Committed`, `RolledBack`, `RecoveryRequired`): never mark `Committed` before `COMMIT` succeeds; inspect `sqlite3_get_autocommit` on error; reject nested `begin`; add RAII `Savepoint`. + - Checked `Database::close()` rejecting with `busy` while statements/transactions/savepoints remain open; deferred close in destructor reports errors to optional diagnostic hook. + - Validate migration lists before any SQL; add `migrate_checked` recording `id`+`checksum` in `_void_schema_migrations` in the same transaction as `PRAGMA user_version` and rejecting newer schemas and checksum drift. + - Operational methods: `checkpoint()`, `backup_to()`, `restore_from()`, `health()`, WAL write-admission threshold gating, and exception-safe `create_scalar_function` / `set_authorizer` adapters. +- `src/SqliteAsync/module.cmake` + `include/Void/Sqlite/AsyncPool.hpp` + `src/SqliteAsync/AsyncPool.cpp`: + - Optional async leased connection pool (default 4 readers + 1 writer, bounded blocking workers, `max_queued_jobs = 1024`, `max_pending_input_bytes = 64 MiB`). + - Leases one connection for the complete read/write/transaction with serialized progress/interrupt cleanup so cancellation never leaks to the next borrower. +- Tests & consumers: `tests/standalone/Sqlite/SqliteHardening.cpp`, `tests/standalone/SqliteAsync/SqliteAsync.cpp`, `tests/package/SqliteOnly/*`, `tests/package/SqliteAsyncOnly/*`, updated `tests/package/InstalledComponents.cmake`. + +## Verification Criteria +- Standalone `Sqlite;SqliteAsync;Testing` RelWithDebInfo `-Werror` (`-p sqlite`): all `Sqlite*` tests + `ctest` 2/2 (`SqliteOnly`, `SqliteAsyncOnly`). +- Full Wave 7 integrated RelWithDebInfo `-Werror`, full Debug ASan+UBSan `-Werror`, and Wave 7 Debug TSan subset. diff --git a/docs/agent-workflow/tasks/S-STORAGE-01-06.md b/docs/agent-workflow/tasks/S-STORAGE-01-06.md new file mode 100644 index 0000000..e3a7d7c --- /dev/null +++ b/docs/agent-workflow/tasks/S-STORAGE-01-06.md @@ -0,0 +1,27 @@ +# S-STORAGE-01..06 — Original Durable Key-Value Storage Engine (`G-STORE`) + +- **Wave**: Wave 7 (`feat/roadmap-p2-wave7`, branched from `main` at `43922d1`) +- **Roadmap reference**: `docs/roadmap/subsystems/Storage.md`, `docs/roadmap/DEPENDENCIES.md` + +## Scope & Ownership +- Zero SQLite dependency (`src/Storage/module.cmake`: `INTERNAL_DEPS Core Functional Time Memory Binary IO Async`, zero external deps). +- `include/Void/Storage/Crc32c.hpp`: native Castagnoli CRC32C (`0x1EDC6F41` / reflected `0x82F63B78`, golden `"123456789"` == `0xE3069283`). +- `include/Void/Storage/Types.hpp`: `kStorageErrorDomain = 9`, `StorageErrorCode`, `Sequence`, `ByteView`, `OwnedBytes`, `OwnedValue`, `Durability::{Sync,Buffered}`, `Outcome::{NotCommitted,Committed,Unknown}`, `Limits` (all roadmap defaults + non-zero validation), `CommitReceipt`, `WriteFailure`, `ScanBounds` (with `prefix`), `ScanEntry`, `ScanPage`, `EngineState`, `EngineStats`, unsigned-byte lexicographic comparator. +- `include/Void/Storage/FilePort.hpp` + `src/Storage/FilePort.cpp`: `FilePort`, `FileHandle`, `PosixFilePort` (exclusive `flock`, `EINTR`/short-write loops, file & dir `fsync`, atomic same-dir rename capability check), and `FaultInjectingFilePort` for deterministic power-loss / short-write / sync-failure / rename-failure / unsynced-discard simulation. +- `include/Void/Storage/Format.hpp` + `src/Storage/Format.cpp`: + - V1 WAL (`VOIDWAL1` 64B segment header with CRC32C, 36B `VWR1` record header with header CRC32C checked before allocating payload, 8B trailer with record CRC32C + repeated length, `BEGIN`/`PUT`/`ERASE`/`COMMIT` payloads with aggregate CRC32C). + - V1 Immutable Sorted Table (`VOIDTBL1` header, 32 KiB target sorted blocks with per-block CRC32C, sparse block index, checksummed `VOIDTBF1` footer). + - V1 Immutable Manifest (`VOIDMNF1`) and atomic `CURRENT` (`VOIDCUR1`). +- `include/Void/Storage/Batch.hpp`, `include/Void/Storage/Engine.hpp`, `src/Storage/Engine.cpp`: + - Conditional atomic `Batch` (`put`, `erase`, `require_absent`, `require_version`, `require_value`; rejects duplicate keys/conditions; sequence-based versioning prevents ABA). + - Exclusive directory lock, minimal `CURRENT`/manifest bootstrap & WAL segment rotation publication before write admission, deterministic recovery with tail-only truncation of final active segment and fail-closed `corrupt` on damaged complete records or earlier closed segments. + - Single serialized writer, pre-append reservation/encoding, infallible visibility publication, `RecoveryRequired` + `Outcome::Unknown` on post-append failure, pinned `Snapshot`/`Cursor` with continuation scans and `page_too_small` enforcement. + - `checkpoint()` freezing memtable -> immutable table -> manifest -> `CURRENT` -> deferred retirement after snapshot pins release; bounded incremental `compact()` merging <= 4 overlapping runs while preserving versions needed by live snapshots. +- `include/Void/Storage/Tools.hpp` + `src/Storage/Tools.cpp`: `verify_directory` (full block-level read-only verification), pinned `export_backup` / `restore_backup`, offline `salvage_directory` into a separate destination. +- `include/Void/Storage/AsyncAdapter.hpp` + `src/Storage/AsyncAdapter.cpp`: bounded blocking async adapter following C-03 domain-result classification (`stop before append -> NotCommitted`, `stop during sync -> retain until settled`, `sync succeeds after stop -> CommitReceipt`, `sync fails after append -> Unknown + RecoveryRequired`, single delivery). +- `include/Void/Storage/Storage.hpp`: umbrella header. +- Tests & consumer: `tests/standalone/Storage/Storage.cpp` (CRC32C golden, format/overflow, model checker vs reference map, byte-offset truncation, corruption, fault-injected creation/rotation/sync/checkpoint/compaction crashes, retention under slow snapshots, async stop-race conformance, verify/backup/salvage), `tests/package/StorageOnly/*`, updated `tests/package/InstalledComponents.cmake`. + +## Verification Criteria +- Standalone `Storage;Testing` RelWithDebInfo `-Werror` (zero external deps!): `storage_*` tests + `ctest` 2/2 (`StorageOnly`). +- Full Wave 7 integrated RelWithDebInfo `-Werror`, full Debug ASan+UBSan `-Werror`, and Wave 7 Debug TSan subset. diff --git a/include/Void/Sqlite/AsyncPool.hpp b/include/Void/Sqlite/AsyncPool.hpp new file mode 100644 index 0000000..1cb42a7 --- /dev/null +++ b/include/Void/Sqlite/AsyncPool.hpp @@ -0,0 +1,179 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace Void::Sqlite +{ + struct AsyncPoolOptions { + std::filesystem::path path{}; + OpenOptions open_options{}; + /// Default 4 reader connections alongside 1 dedicated writer lane. + std::size_t reader_connections{4}; + std::size_t max_queued_jobs{1024}; + std::size_t max_pending_input_bytes{64ULL * 1024ULL * 1024ULL}; + int progress_handler_steps{64}; + const Void::Time::MonotonicClock* clock{nullptr}; + }; + + struct AsyncPoolStats { + std::size_t reader_connections{0}; + std::size_t queued_read_jobs{0}; + std::size_t queued_write_jobs{0}; + std::size_t active_read_jobs{0}; + std::size_t active_write_jobs{0}; + std::size_t pending_input_bytes{0}; + std::uint64_t completed_jobs{0}; + std::uint64_t rejected_jobs{0}; + std::uint64_t cancelled_jobs{0}; + }; + + /// Bounded blocking SQLite connection pool (1 writer lane + N reader lanes). + /// Leases one connection exclusively for the entire callback/transaction + /// without ever running SQLite calls on an IO event-loop thread or leaking + /// interrupts across subsequent borrowers. + class AsyncPool + { + public: + ~AsyncPool(); + AsyncPool(AsyncPool&&) noexcept; + AsyncPool& operator=(AsyncPool&&) noexcept; + AsyncPool(const AsyncPool&) = delete; + AsyncPool& operator=(const AsyncPool&) = delete; + + [[nodiscard]] static Result open( + AsyncPoolOptions options, + Void::Async::Executor* completion_executor = nullptr); + + /// Execute a read-only unit of work on a leased reader connection. + template + [[nodiscard]] Void::Coro::Task> run_read( + std::function(Database&)> fn, + Void::Async::OperationOptions op = {}, + std::size_t input_bytes = 0) + { + auto box = std::make_shared>>(); + auto r = co_await submit_erased( + false, + [box, f = std::move(fn)](Database& db) -> Result { + *box = f(db); + return {}; + }, + std::move(op), + input_bytes); + if (!r) { + co_return Void::Result::fail(std::move(r).error()); + } + if (!box->has_value()) { + co_return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::sqlite_error, + "AsyncPool read callback produced no result")); + } + co_return std::move(**box); + } + + /// Execute a write unit of work on the serialized writer lane. + template + [[nodiscard]] Void::Coro::Task> run_write( + std::function(Database&)> fn, + Void::Async::OperationOptions op = {}, + std::size_t input_bytes = 0) + { + auto box = std::make_shared>>(); + auto r = co_await submit_erased( + true, + [box, f = std::move(fn)](Database& db) -> Result { + *box = f(db); + return {}; + }, + std::move(op), + input_bytes); + if (!r) { + co_return Void::Result::fail(std::move(r).error()); + } + if (!box->has_value()) { + co_return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::sqlite_error, + "AsyncPool write callback produced no result")); + } + co_return std::move(**box); + } + + /// Execute a full transaction on the leased writer connection. + /// Commits if `fn` returns ok; rolls back on error. Never releases + /// the writer lease mid-transaction. + template + [[nodiscard]] Void::Coro::Task> run_write_transaction( + BeginMode mode, + std::function(Database&, Transaction&)> fn, + Void::Async::OperationOptions op = {}, + std::size_t input_bytes = 0) + { + return run_write( + [mode, f = std::move(fn)](Database& db) -> Result { + auto tx = db.begin(mode); + if (!tx) { + return Void::Result::fail(std::move(tx).error()); + } + auto res = f(db, *tx); + if (!res) { + (void)tx->rollback_checked(); + return res; + } + if (tx->is_active()) { + auto c = tx->commit(); + if (!c) { + if (tx->is_active()) { + (void)tx->rollback_checked(); + } + return Void::Result::fail(std::move(c).error()); + } + } + return res; + }, + std::move(op), + input_bytes); + } + + [[nodiscard]] Void::Coro::Task> run_read_void( + std::function(Database&)> fn, + Void::Async::OperationOptions op = {}, + std::size_t input_bytes = 0); + + [[nodiscard]] Void::Coro::Task> run_write_void( + std::function(Database&)> fn, + Void::Async::OperationOptions op = {}, + std::size_t input_bytes = 0); + + [[nodiscard]] AsyncPoolStats stats() const noexcept; + + /// Stop new admission, drain all admitted jobs, join worker threads, + /// and close all pooled SQLite connections. + [[nodiscard]] Result close_and_join(); + + private: + struct Impl; + explicit AsyncPool(std::shared_ptr impl) noexcept; + + [[nodiscard]] Void::Coro::Task> submit_erased( + bool is_write, + std::function(Database&)> fn, + Void::Async::OperationOptions op, + std::size_t input_bytes); + + std::shared_ptr m_impl{}; + }; + +} // namespace Void::Sqlite diff --git a/include/Void/Sqlite/Sqlite.hpp b/include/Void/Sqlite/Sqlite.hpp index ab85307..ff4c54f 100644 --- a/include/Void/Sqlite/Sqlite.hpp +++ b/include/Void/Sqlite/Sqlite.hpp @@ -2,36 +2,79 @@ #include #include +#include #include #include +#include +#include #include #include #include #include #include +#include struct sqlite3; struct sqlite3_stmt; -// A thin, RAII, Result-based wrapper over the SQLite C API. Generic — no -// application schema baggage. Open a Database, prepare Statements, bind by -// 1-based index, step over result rows, read columns by 0-based index. Schema -// versioning is handled via PRAGMA user_version (migrate()). +// A hardened RAII, Result-based wrapper over the SQLite C API. Generic — no +// application schema baggage. Open a Database (or open_database with explicit +// OpenOptions), prepare Statements, bind by 1-based index or parameter name, +// step over result rows, and read typed columns by 0-based index. namespace Void::Sqlite { - using Void::Result::Error; - template using Result = Void::Result::Result; - - enum class OpenMode { ReadOnly, ReadWrite, ReadWriteCreate }; + namespace detail + { + struct ConnectionState; + } // namespace detail class Database; + class Statement; + class Transaction; + class Savepoint; - /// A prepared statement. Move-only; finalizes on destruction. + /// Non-owning view of the current row of a Statement. Expires on the next + /// step(), reset(), reset_checked(), finalize_checked(), or destruction. + /// Must never cross an await or outlive the Statement step that produced it. + class RowView + { + public: + RowView() noexcept = default; + + [[nodiscard]] bool is_valid() const noexcept; + [[nodiscard]] int column_count() const noexcept; + [[nodiscard]] Result column_type(int col) const; + [[nodiscard]] Result is_null(int col) const; + [[nodiscard]] Result get_int(int col) const; + [[nodiscard]] Result get_double(int col) const; + [[nodiscard]] Result get_text_view(int col) const; + [[nodiscard]] Result get_text(int col) const; + [[nodiscard]] Result> get_blob_view(int col) const; + [[nodiscard]] Result> get_blob(int col) const; + [[nodiscard]] Result> get_optional_int(int col) const; + [[nodiscard]] Result> get_optional_double(int col) const; + [[nodiscard]] Result> get_optional_text(int col) const; + [[nodiscard]] Result>> get_optional_blob(int col) const; + [[nodiscard]] Result get_value(int col) const; + [[nodiscard]] Result copy() const; + + private: + friend class Statement; + RowView(const Statement* stmt, std::uint64_t generation) noexcept + : m_stmt(stmt), m_generation(generation) + { + } + + const Statement* m_stmt{nullptr}; + std::uint64_t m_generation{0}; + }; + + /// A prepared statement. Move-only; retains shared ConnectionState so moving + /// or destroying Database cannot dangle this statement. class Statement { public: - Statement() = default; ~Statement(); Statement(Statement&&) noexcept; @@ -39,7 +82,7 @@ namespace Void::Sqlite Statement(const Statement&) = delete; Statement& operator=(const Statement&) = delete; - // Bind parameters (1-based, matching SQLite). Chainable. + // ── Legacy 1.x chainable bind methods (1-based) ────────────────── Statement& bind(int index, std::int64_t value); Statement& bind(int index, int value) { @@ -56,48 +99,143 @@ namespace Void::Sqlite Statement& bind(int index, std::nullptr_t); Statement& bind(int index, const std::optional& value); + /// Error captured by the most recent legacy unchecked bind() call, if any. + [[nodiscard]] const std::optional& last_bind_error() const noexcept + { + return m_last_bind_error; + } + + // ── Checked bind / parameter metadata ──────────────────────────── + [[nodiscard]] int bind_parameter_count() const noexcept; + [[nodiscard]] Result bind_parameter_index(std::string_view name) const; + + [[nodiscard]] Result bind_checked(int index, ValueView value); + [[nodiscard]] Result bind_checked(std::string_view name, ValueView value); + + /// Zero-copy borrowed text/blob binding keeping `owner` alive until + /// reset(), clear_bindings(), rebind, finalize, or destruction. + [[nodiscard]] Result bind_borrowed_text( + int index, std::string_view value, std::shared_ptr owner); + [[nodiscard]] Result bind_borrowed_blob( + int index, std::span value, std::shared_ptr owner); + /// Advance to the next row. Returns true with a row available, /// false when the statement is done, or an Error on failure. [[nodiscard]] Result step(); /// Reset for re-execution (keeps bindings unless clear_bindings). void reset() noexcept; - void clear_bindings() noexcept; + [[nodiscard]] Result reset_checked(); - // Column accessors (0-based), valid after step() yields a row. + void clear_bindings() noexcept; + [[nodiscard]] Result clear_bindings_checked(); + + /// Explicitly finalize the statement and report any native error. + [[nodiscard]] Result finalize_checked(); + + [[nodiscard]] bool is_open() const noexcept { return m_stmt != nullptr; } + [[nodiscard]] bool has_row() const noexcept { return m_has_row; } + [[nodiscard]] std::uint64_t row_generation() const noexcept + { + return m_row_generation; + } + + // ── Legacy 1.x column accessors (0-based) ──────────────────────── [[nodiscard]] int column_count() const noexcept; [[nodiscard]] bool is_null(int col) const noexcept; [[nodiscard]] std::int64_t column_int(int col) const noexcept; [[nodiscard]] double column_double(int col) const noexcept; [[nodiscard]] std::string column_text(int col) const; - private: + // ── Strict typed column accessors & row views ──────────────────── + [[nodiscard]] Result current_row() const; + [[nodiscard]] Result copy_row() const; + [[nodiscard]] Result column_type(int col) const; + [[nodiscard]] Result try_column_int(int col) const; + [[nodiscard]] Result try_column_double(int col) const; + [[nodiscard]] Result try_column_text_view(int col) const; + [[nodiscard]] Result try_column_text(int col) const; + [[nodiscard]] Result> try_column_blob_view(int col) const; + [[nodiscard]] Result> try_column_blob(int col) const; + [[nodiscard]] Result> try_column_optional_int(int col) const; + [[nodiscard]] Result> try_column_optional_double(int col) const; + [[nodiscard]] Result> try_column_optional_text(int col) const; + [[nodiscard]] Result>> try_column_optional_blob(int col) const; + [[nodiscard]] Result try_column_value(int col) const; + private: friend class Database; - explicit Statement(sqlite3_stmt* stmt) : m_stmt(stmt) {} - sqlite3_stmt* m_stmt = nullptr; + friend class RowView; + + Statement(std::shared_ptr conn, + sqlite3_stmt* stmt) noexcept; + void release_handle() noexcept; + [[nodiscard]] Result validate_column_access(int col) const; + + std::shared_ptr m_conn{}; + sqlite3_stmt* m_stmt{nullptr}; + bool m_has_row{false}; + std::uint64_t m_row_generation{0}; + std::vector> m_borrowed_owners{}; + std::optional m_last_bind_error{}; }; - /// RAII transaction. Rolls back on destruction unless commit() was called. + /// RAII transaction retaining shared ConnectionState. Never marks Committed + /// before COMMIT succeeds; inspects sqlite3_get_autocommit on error. class Transaction { public: - + Transaction() noexcept = default; ~Transaction(); Transaction(Transaction&&) noexcept; Transaction& operator=(Transaction&&) noexcept; Transaction(const Transaction&) = delete; Transaction& operator=(const Transaction&) = delete; + [[nodiscard]] TransactionState state() const noexcept { return m_state; } + [[nodiscard]] bool is_active() const noexcept + { + return m_state == TransactionState::Active; + } + Result commit(); + [[nodiscard]] Result rollback_checked(); void rollback() noexcept; private: - friend class Database; - explicit Transaction(Database* db) : m_db(db) {} - Database* m_db = nullptr; - bool m_done = false; + explicit Transaction(std::shared_ptr conn) noexcept; + + std::shared_ptr m_conn{}; + TransactionState m_state{TransactionState::RolledBack}; + }; + + /// Separately owned nested savepoint scope. + class Savepoint + { + public: + Savepoint() noexcept = default; + ~Savepoint(); + Savepoint(Savepoint&&) noexcept; + Savepoint& operator=(Savepoint&&) noexcept; + Savepoint(const Savepoint&) = delete; + Savepoint& operator=(const Savepoint&) = delete; + + [[nodiscard]] bool is_active() const noexcept { return m_active; } + [[nodiscard]] std::string_view name() const noexcept { return m_name; } + + [[nodiscard]] Result release(); + [[nodiscard]] Result rollback_to(); + [[nodiscard]] Result rollback_and_release(); + + private: + friend class Database; + Savepoint(std::shared_ptr conn, + std::string name) noexcept; + + std::shared_ptr m_conn{}; + std::string m_name{}; + bool m_active{false}; }; /// A single forward schema migration applied when the database's @@ -107,10 +245,18 @@ namespace Void::Sqlite std::string_view sql; ///< DDL/DML to reach this version }; + using ScalarFunction = + std::function(std::span)>; + using AuthorizerCallback = std::function; + class Database { public: - Database() = default; ~Database(); Database(Database&&) noexcept; @@ -119,19 +265,46 @@ namespace Void::Sqlite Database& operator=(const Database&) = delete; /// Open (or create) a database file. Use ":memory:" for an - /// in-memory db. Enables WAL + a busy timeout for ReadWrite modes. + /// in-memory db. Enables checked WAL + FULL + foreign_keys for + /// writable file databases. [[nodiscard]] static Result open(const std::filesystem::path& path, OpenMode mode = OpenMode::ReadWriteCreate); + /// Open with explicit checked options, limits, and diagnostics. + [[nodiscard]] static Result + open_with_options(const std::filesystem::path& path, + OpenOptions options); + /// Execute one or more semicolon-separated statements (no results). Result exec(std::string_view sql); - /// Prepare a single statement for binding/stepping. + /// Prepare a single statement for binding/stepping. Rejects + /// non-whitespace trailing SQL and enforces statement/SQL limits. [[nodiscard]] Result prepare(std::string_view sql); - /// Begin a transaction (BEGIN; commit/rollback via the handle). - [[nodiscard]] Result begin(); + /// Begin a transaction. Rejects nested begin() while a transaction + /// is already active (use savepoint() for nesting). + [[nodiscard]] Result begin(BeginMode mode = BeginMode::Deferred); + + /// Create a named nested savepoint (ASCII identifier only). + [[nodiscard]] Result savepoint(std::string_view name); + + /// Stream all rows from a prepared statement with row & byte caps. + [[nodiscard]] Result> query_all( + Statement& stmt, + std::size_t max_rows = 0, + std::size_t max_bytes = 0); + + /// Explicitly close the connection. Stops admission and returns + /// SqliteErrorCode::busy while live statements/transactions/savepoints + /// remain open. + [[nodiscard]] Result close(); + + [[nodiscard]] bool is_open() const noexcept; + [[nodiscard]] EffectiveCapabilities capabilities() const; + [[nodiscard]] ConnectionHealth health() const; + [[nodiscard]] const SqliteLimits& limits() const noexcept; [[nodiscard]] std::int64_t last_insert_rowid() const noexcept; [[nodiscard]] int changes() const noexcept; @@ -139,16 +312,63 @@ namespace Void::Sqlite /// Current schema version (PRAGMA user_version). [[nodiscard]] Result user_version(); - /// Apply, in order, any migrations whose version exceeds the - /// current user_version, each inside a transaction, then bump - /// user_version. Idempotent and safe to call on every startup. + /// Validate strictly increasing unique versions before mutation, + /// reject unexpected newer schemas, and apply pending migrations. Result migrate(std::span migrations); - [[nodiscard]] sqlite3* handle() const noexcept { return m_db; } + /// Validate migrations, record immutable id & checksum in + /// `_void_schema_migrations` in the same transaction as user_version, + /// and reject checksum drift or unexpected newer schemas. + [[nodiscard]] Result + migrate_checked(std::span migrations); + + /// Run a WAL checkpoint and report completed/remaining frames and busy state. + [[nodiscard]] Result + checkpoint(CheckpointMode mode = CheckpointMode::Passive); + + /// Copy this database consistently to `destination` via SQLite's backup API. + [[nodiscard]] Result + backup_to(const std::filesystem::path& destination, + BackupOptions options = {}); + + /// Restore this database consistently from `source` via SQLite's backup API. + [[nodiscard]] Result + restore_from(const std::filesystem::path& source, + BackupOptions options = {}); + + /// Register an exception-safe custom scalar SQL function owned by + /// this connection's ConnectionState. + [[nodiscard]] Result create_scalar_function( + std::string name, + int num_args, + ScalarFunction fn, + bool deterministic = true); + + /// Register (or clear when empty) an exception-safe SQLite authorizer. + [[nodiscard]] Result set_authorizer(AuthorizerCallback cb); + + /// Expert native handle borrow under caller's execution lease. + [[nodiscard]] sqlite3* handle() const noexcept; + + /// Operation-scoped interrupt/progress hooks for leased async execution + /// (serialized with end_operation so interrupts never leak across queries). + void begin_leased_operation(std::uint64_t generation, + int progress_steps, + std::function should_interrupt); + void interrupt_leased_operation(std::uint64_t generation) noexcept; + void end_leased_operation(std::uint64_t generation) noexcept; private: - - sqlite3* m_db = nullptr; + explicit Database(std::shared_ptr conn) noexcept; + std::shared_ptr m_conn{}; }; + /// Free-function helper matching roadmap `open_database(path, OpenOptions)`. + [[nodiscard]] inline Result open_database( + const std::filesystem::path& path, + OpenOptions options = {}) + { + return Database::open_with_options(path, std::move(options)); + } + } // namespace Void::Sqlite diff --git a/include/Void/Sqlite/Types.hpp b/include/Void/Sqlite/Types.hpp new file mode 100644 index 0000000..391fd6c --- /dev/null +++ b/include/Void/Sqlite/Types.hpp @@ -0,0 +1,405 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Sqlite +{ + using Void::Result::Error; + template using Result = Void::Result::Result; + + enum class OpenMode : std::uint8_t { + ReadOnly, + ReadWrite, + ReadWriteCreate + }; + + enum class JournalMode : std::uint8_t { + Wal, + Rollback + }; + + enum class SyncMode : std::uint8_t { + Full, + Normal + }; + + enum class BeginMode : std::uint8_t { + Deferred, + Immediate, + Exclusive + }; + + enum class CheckpointMode : std::uint8_t { + Passive, + Full, + Restart, + Truncate + }; + + enum class TransactionState : std::uint8_t { + Active, + Committed, + RolledBack, + RecoveryRequired + }; + + enum class ColumnType : std::uint8_t { + Null = 0, + Integer = 1, + Real = 2, + Text = 3, + Blob = 4 + }; + + enum class SqliteErrorCode : std::int32_t { + none = 0, + invalid_argument = 1, + busy = 2, + locked = 3, + constraint = 4, + corrupt = 5, + io = 6, + readonly = 7, + full = 8, + misuse = 9, + not_found = 10, + range = 11, + type_mismatch = 12, + trailing_sql = 13, + statement_limit = 14, + size_limit = 15, + unsupported_pragma = 16, + recovery_required = 17, + closed = 18, + cancelled = 19, + timeout = 20, + overloaded = 21, + migration_error = 22, + backup_error = 23, + sqlite_error = 24 + }; + + [[nodiscard]] inline Error make_sqlite_error( + SqliteErrorCode code, + std::string message, + int primary_code = 0, + int extended_code = 0) + { + using Void::Result::ErrorCode; + using Void::Result::ErrorKind; + + ErrorKind kind = ErrorKind::internal; + switch (code) { + case SqliteErrorCode::none: + case SqliteErrorCode::sqlite_error: + kind = ErrorKind::internal; + break; + case SqliteErrorCode::invalid_argument: + case SqliteErrorCode::misuse: + case SqliteErrorCode::range: + case SqliteErrorCode::type_mismatch: + case SqliteErrorCode::trailing_sql: + kind = ErrorKind::invalid_argument; + break; + case SqliteErrorCode::busy: + case SqliteErrorCode::locked: + case SqliteErrorCode::constraint: + case SqliteErrorCode::recovery_required: + case SqliteErrorCode::migration_error: + kind = ErrorKind::conflict; + break; + case SqliteErrorCode::corrupt: + kind = ErrorKind::corrupt; + break; + case SqliteErrorCode::io: + case SqliteErrorCode::readonly: + case SqliteErrorCode::backup_error: + kind = ErrorKind::io; + break; + case SqliteErrorCode::full: + case SqliteErrorCode::statement_limit: + case SqliteErrorCode::size_limit: + kind = ErrorKind::exhausted; + break; + case SqliteErrorCode::not_found: + kind = ErrorKind::not_found; + break; + case SqliteErrorCode::unsupported_pragma: + kind = ErrorKind::unsupported; + break; + case SqliteErrorCode::closed: + case SqliteErrorCode::cancelled: + kind = ErrorKind::cancelled; + break; + case SqliteErrorCode::timeout: + kind = ErrorKind::timeout; + break; + case SqliteErrorCode::overloaded: + kind = ErrorKind::overloaded; + break; + } + + if (primary_code != 0 || extended_code != 0) { + message += " (sqlite rc="; + message += std::to_string(primary_code); + if (extended_code != 0 && extended_code != primary_code) { + message += ", extended="; + message += std::to_string(extended_code); + } + message += ")"; + } + + return Error{ + kind, + std::move(message), + ErrorCode{Void::Result::kSqliteErrorDomain, + static_cast(code)}}; + } + + struct SqliteLimits { + std::size_t max_live_statements{128}; + std::size_t max_sql_bytes{1024ULL * 1024ULL}; + std::size_t max_value_bytes{16ULL * 1024ULL * 1024ULL}; + std::size_t max_query_all_rows{10000}; + std::size_t max_query_all_bytes{16ULL * 1024ULL * 1024ULL}; + std::size_t max_cached_statements{64}; + std::size_t max_cache_bytes{8ULL * 1024ULL * 1024ULL}; + std::chrono::milliseconds busy_timeout{5000}; + std::uint64_t wal_checkpoint_threshold_bytes{16ULL * 1024ULL * 1024ULL}; + std::uint64_t wal_warn_threshold_bytes{64ULL * 1024ULL * 1024ULL}; + std::uint64_t wal_stop_writes_threshold_bytes{256ULL * 1024ULL * 1024ULL}; + std::size_t max_queued_jobs{1024}; + std::size_t max_pending_input_bytes{64ULL * 1024ULL * 1024ULL}; + }; + + [[nodiscard]] inline Result validate_limits(const SqliteLimits& limits) + { + if (limits.max_live_statements == 0 || + limits.max_sql_bytes == 0 || + limits.max_value_bytes == 0 || + limits.max_query_all_rows == 0 || + limits.max_query_all_bytes == 0 || + limits.max_cached_statements == 0 || + limits.max_cache_bytes == 0 || + limits.busy_timeout.count() < 0 || + limits.wal_checkpoint_threshold_bytes == 0 || + limits.wal_warn_threshold_bytes == 0 || + limits.wal_stop_writes_threshold_bytes == 0 || + limits.max_queued_jobs == 0 || + limits.max_pending_input_bytes == 0) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::invalid_argument, + "SqliteLimits must specify positive finite bounds")); + } + if (limits.wal_checkpoint_threshold_bytes > limits.wal_warn_threshold_bytes || + limits.wal_warn_threshold_bytes > limits.wal_stop_writes_threshold_bytes) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::invalid_argument, + "SqliteLimits WAL thresholds must be non-decreasing")); + } + return {}; + } + + struct OpenOptions { + OpenMode mode{OpenMode::ReadWriteCreate}; + JournalMode journal_mode{JournalMode::Wal}; + SyncMode sync_mode{SyncMode::Full}; + bool foreign_keys{true}; + bool allow_extension_loading{false}; + SqliteLimits limits{}; + std::function diagnostic_hook{}; + }; + + struct EffectiveCapabilities { + std::string sqlite_version{}; + int sqlite_version_number{0}; + int threadsafe_mode{0}; + bool in_memory{false}; + bool read_only{false}; + std::string journal_mode{}; + int synchronous_mode{0}; + bool foreign_keys{false}; + bool extension_loading_enabled{false}; + }; + + struct ValueView { + using Storage = std::variant< + std::nullptr_t, + std::int64_t, + double, + std::string_view, + std::span>; + + Storage value{nullptr}; + + constexpr ValueView() noexcept = default; + constexpr ValueView(std::nullptr_t) noexcept : value(nullptr) {} + constexpr ValueView(std::int64_t v) noexcept : value(v) {} + constexpr ValueView(int v) noexcept : value(static_cast(v)) {} + constexpr ValueView(double v) noexcept : value(v) {} + constexpr ValueView(std::string_view v) noexcept : value(v) {} + ValueView(const std::string& v) noexcept : value(std::string_view{v}) {} + constexpr ValueView(const char* v) noexcept + : value(v ? Storage{std::string_view{v}} : Storage{nullptr}) {} + constexpr ValueView(std::span v) noexcept : value(v) {} + + [[nodiscard]] constexpr ColumnType type() const noexcept + { + switch (value.index()) { + case 0: return ColumnType::Null; + case 1: return ColumnType::Integer; + case 2: return ColumnType::Real; + case 3: return ColumnType::Text; + case 4: return ColumnType::Blob; + default: return ColumnType::Null; + } + } + + [[nodiscard]] constexpr bool is_null() const noexcept + { + return std::holds_alternative(value); + } + }; + + struct OwnedValue { + using Storage = std::variant< + std::nullptr_t, + std::int64_t, + double, + std::string, + std::vector>; + + Storage value{nullptr}; + + OwnedValue() noexcept = default; + OwnedValue(std::nullptr_t) noexcept : value(nullptr) {} + OwnedValue(std::int64_t v) noexcept : value(v) {} + OwnedValue(double v) noexcept : value(v) {} + OwnedValue(std::string v) noexcept : value(std::move(v)) {} + OwnedValue(std::vector v) noexcept : value(std::move(v)) {} + + [[nodiscard]] ColumnType type() const noexcept + { + switch (value.index()) { + case 0: return ColumnType::Null; + case 1: return ColumnType::Integer; + case 2: return ColumnType::Real; + case 3: return ColumnType::Text; + case 4: return ColumnType::Blob; + default: return ColumnType::Null; + } + } + + [[nodiscard]] bool is_null() const noexcept + { + return std::holds_alternative(value); + } + + [[nodiscard]] ValueView as_view() const noexcept + { + if (const auto* i = std::get_if(&value)) return ValueView{*i}; + if (const auto* d = std::get_if(&value)) return ValueView{*d}; + if (const auto* s = std::get_if(&value)) return ValueView{std::string_view{*s}}; + if (const auto* b = std::get_if>(&value)) { + return ValueView{std::span{b->data(), b->size()}}; + } + return ValueView{nullptr}; + } + + [[nodiscard]] bool operator==(const OwnedValue&) const = default; + }; + + struct OwnedRow { + std::vector columns{}; + + [[nodiscard]] std::size_t size() const noexcept { return columns.size(); } + [[nodiscard]] bool empty() const noexcept { return columns.empty(); } + [[nodiscard]] const OwnedValue& operator[](std::size_t idx) const noexcept + { + return columns[idx]; + } + }; + + struct CheckpointReport { + int log_frames{0}; + int checkpointed_frames{0}; + bool busy{false}; + std::uint64_t wal_size_bytes{0}; + }; + + struct BackupOptions { + int pages_per_step{64}; + int max_steps{1000000}; + std::chrono::milliseconds step_sleep{0}; + }; + + struct BackupReport { + int total_pages{0}; + int remaining_pages{0}; + int steps{0}; + }; + + /// Immutable schema migration with explicit identity & checksum verification. + struct CheckedMigration { + int version{0}; + std::string_view id{}; + std::string_view checksum{}; + std::string_view sql{}; + }; + + struct ConnectionHealth { + std::size_t live_statements{0}; + bool active_transaction{false}; + std::size_t open_savepoints{0}; + std::uint64_t wal_size_bytes{0}; + bool wal_checkpoint_recommended{false}; + bool wal_warn_exceeded{false}; + bool wal_write_admission_blocked{false}; + }; + + enum class AuthorizerDecision : std::uint8_t { + Allow, + Deny, + Ignore + }; + + struct FaultConfig { + /// If non-zero, next COMMIT returns this SQLite error code without + /// calling SQLite COMMIT (leaving transaction active so autocommit==0). + int fail_next_commit_rc{0}; + /// If true along with fail_next_commit_rc, simulates SQLite + /// auto-rollback before returning the error. + bool auto_rollback_on_faulted_commit{false}; + /// If non-zero, next explicit close() returns this SQLite error code. + int fail_next_close_rc{0}; + }; + + /// Process-local RAII guard for deterministic fault injection in tests. + class ScopedFaultGuard + { + public: + explicit ScopedFaultGuard(FaultConfig cfg) noexcept; + ~ScopedFaultGuard(); + + ScopedFaultGuard(const ScopedFaultGuard&) = delete; + ScopedFaultGuard& operator=(const ScopedFaultGuard&) = delete; + + [[nodiscard]] static FaultConfig current() noexcept; + + private: + FaultConfig prev_{}; + }; + +} // namespace Void::Sqlite 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/Sqlite/Sqlite.cpp b/src/Sqlite/Sqlite.cpp index 4047d98..3430869 100644 --- a/src/Sqlite/Sqlite.cpp +++ b/src/Sqlite/Sqlite.cpp @@ -1,65 +1,702 @@ #include +#include #include +#include +#include +#include +#include +#include +#include #include +#include +#include +#include +#include +#include #include +#include namespace Void::Sqlite { namespace { - [[nodiscard]] Error sqlite_error(sqlite3* db, std::string_view what) + std::mutex g_fault_mutex; + FaultConfig g_fault_config{}; + + [[nodiscard]] FaultConfig consume_fault_commit() noexcept { - const char* msg = db ? sqlite3_errmsg(db) : "no database"; - return Error{std::format("Sqlite: {}: {}", what, - msg ? msg : "unknown error")}; + std::lock_guard lk{g_fault_mutex}; + FaultConfig out{}; + if (g_fault_config.fail_next_commit_rc != 0) { + out.fail_next_commit_rc = std::exchange(g_fault_config.fail_next_commit_rc, 0); + out.auto_rollback_on_faulted_commit = + std::exchange(g_fault_config.auto_rollback_on_faulted_commit, false); + } + return out; } + + [[nodiscard]] int consume_fault_close() noexcept + { + std::lock_guard lk{g_fault_mutex}; + return std::exchange(g_fault_config.fail_next_close_rc, 0); + } + + [[nodiscard]] SqliteErrorCode map_sqlite_rc(int rc) noexcept + { + const int primary = rc & 0xFF; + switch (primary) { + case SQLITE_OK: + case SQLITE_ROW: + case SQLITE_DONE: + return SqliteErrorCode::none; + case SQLITE_BUSY: + return SqliteErrorCode::busy; + case SQLITE_LOCKED: + return SqliteErrorCode::locked; + case SQLITE_CONSTRAINT: + return SqliteErrorCode::constraint; + case SQLITE_CORRUPT: + case SQLITE_NOTADB: + return SqliteErrorCode::corrupt; + case SQLITE_IOERR: + return SqliteErrorCode::io; + case SQLITE_READONLY: + return SqliteErrorCode::readonly; + case SQLITE_FULL: + case SQLITE_TOOBIG: + case SQLITE_NOMEM: + return SqliteErrorCode::full; + case SQLITE_MISUSE: + return SqliteErrorCode::misuse; + case SQLITE_RANGE: + return SqliteErrorCode::range; + case SQLITE_CANTOPEN: + case SQLITE_NOTFOUND: + return SqliteErrorCode::not_found; + case SQLITE_INTERRUPT: + return SqliteErrorCode::cancelled; + default: + return SqliteErrorCode::sqlite_error; + } + } + + [[nodiscard]] Error sqlite_error_from_db( + sqlite3* db, + int primary_rc, + std::string_view what) + { + const int ext = db ? sqlite3_extended_errcode(db) : primary_rc; + const char* msg = db ? sqlite3_errmsg(db) : sqlite3_errstr(primary_rc); + return make_sqlite_error( + map_sqlite_rc(primary_rc), + std::format("Sqlite: {}: {}", what, msg ? msg : "unknown error"), + primary_rc, + ext); + } + + [[nodiscard]] std::string ascii_lower(std::string_view s) + { + std::string out; + out.reserve(s.size()); + for (const unsigned char c : s) { + out.push_back(static_cast(std::tolower(c))); + } + return out; + } + + [[nodiscard]] bool is_ascii_whitespace(char c) noexcept + { + return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v'; + } + + [[nodiscard]] bool is_valid_savepoint_name(std::string_view name) noexcept + { + if (name.empty() || name.size() > 64) { + return false; + } + const auto is_start = [](unsigned char c) { + return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_'; + }; + if (!is_start(static_cast(name.front()))) { + return false; + } + for (const unsigned char c : name) { + if (!is_start(c) && !(c >= '0' && c <= '9')) { + return false; + } + } + return true; + } + + [[nodiscard]] bool is_memory_path(const std::filesystem::path& path) + { + const std::string s = path.string(); + return s.empty() || s == ":memory:" || s.starts_with("file::memory:"); + } + + [[nodiscard]] int clamp_to_int(std::size_t v) noexcept + { + if (v >= static_cast(INT_MAX)) { + return INT_MAX; + } + return static_cast(v); + } + + [[nodiscard]] ColumnType map_column_type(int sqlite_type) noexcept + { + switch (sqlite_type) { + case SQLITE_INTEGER: return ColumnType::Integer; + case SQLITE_FLOAT: return ColumnType::Real; + case SQLITE_TEXT: return ColumnType::Text; + case SQLITE_BLOB: return ColumnType::Blob; + case SQLITE_NULL: + default: + return ColumnType::Null; + } + } + + [[nodiscard]] Result query_single_text_pragma( + sqlite3* db, + std::string_view sql, + std::string& out_value) + { + sqlite3_stmt* raw = nullptr; + const int prep_rc = sqlite3_prepare_v2( + db, sql.data(), static_cast(sql.size()), &raw, nullptr); + if (prep_rc != SQLITE_OK) { + return Void::Result::fail(sqlite_error_from_db(db, prep_rc, sql)); + } + struct StmtGuard { + sqlite3_stmt* s; + ~StmtGuard() { if (s) sqlite3_finalize(s); } + } guard{raw}; + const int step_rc = sqlite3_step(raw); + if (step_rc != SQLITE_ROW) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::unsupported_pragma, + std::format("Sqlite: pragma '{}' returned no result", sql), + step_rc, + db ? sqlite3_extended_errcode(db) : step_rc)); + } + const auto* p = sqlite3_column_text(raw, 0); + const int n = sqlite3_column_bytes(raw, 0); + out_value = (p && n > 0) + ? std::string{reinterpret_cast(p), + static_cast(n)} + : std::string{}; + return {}; + } + + [[nodiscard]] Result query_single_int_pragma( + sqlite3* db, + std::string_view sql) + { + sqlite3_stmt* raw = nullptr; + const int prep_rc = sqlite3_prepare_v2( + db, sql.data(), static_cast(sql.size()), &raw, nullptr); + if (prep_rc != SQLITE_OK) { + return Void::Result::fail(sqlite_error_from_db(db, prep_rc, sql)); + } + struct StmtGuard { + sqlite3_stmt* s; + ~StmtGuard() { if (s) sqlite3_finalize(s); } + } guard{raw}; + const int step_rc = sqlite3_step(raw); + if (step_rc != SQLITE_ROW) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::unsupported_pragma, + std::format("Sqlite: pragma '{}' returned no result", sql), + step_rc, + db ? sqlite3_extended_errcode(db) : step_rc)); + } + return static_cast(sqlite3_column_int(raw, 0)); + } + + [[nodiscard]] Result exec_raw_sql( + sqlite3* db, + const std::string& sql, + std::string_view what) + { + char* err = nullptr; + const int rc = sqlite3_exec(db, sql.c_str(), nullptr, nullptr, &err); + if (rc != SQLITE_OK) { + std::string msg = err ? err : (db ? sqlite3_errmsg(db) : sqlite3_errstr(rc)); + if (err) sqlite3_free(err); + const int ext = db ? sqlite3_extended_errcode(db) : rc; + return Void::Result::fail(make_sqlite_error( + map_sqlite_rc(rc), + std::format("Sqlite: {}: {}", what, msg), + rc, + ext)); + } + return {}; + } + + struct ScalarFunctionBox { + ScalarFunction fn{}; + }; + + struct AuthorizerBox { + AuthorizerCallback cb{}; + }; + + void scalar_function_trampoline( + sqlite3_context* ctx, + int argc, + sqlite3_value** argv) noexcept + { + const auto* box = static_cast(sqlite3_user_data(ctx)); + if (!box || !box->fn) { + sqlite3_result_error(ctx, "Sqlite: scalar function missing target", -1); + return; + } + try { + std::vector args; + args.reserve(static_cast(std::max(0, argc))); + for (int i = 0; i < argc; ++i) { + sqlite3_value* v = argv[i]; + switch (sqlite3_value_type(v)) { + case SQLITE_NULL: + args.emplace_back(nullptr); + break; + case SQLITE_INTEGER: + args.emplace_back(static_cast(sqlite3_value_int64(v))); + break; + case SQLITE_FLOAT: + args.emplace_back(sqlite3_value_double(v)); + break; + case SQLITE_TEXT: { + const auto* p = sqlite3_value_text(v); + const int n = sqlite3_value_bytes(v); + args.emplace_back(std::string_view{ + p && n > 0 ? reinterpret_cast(p) : "", + n > 0 ? static_cast(n) : 0ULL}); + break; + } + case SQLITE_BLOB: { + const auto* p = sqlite3_value_blob(v); + const int n = sqlite3_value_bytes(v); + args.emplace_back(std::span{ + p && n > 0 ? static_cast(p) : nullptr, + n > 0 ? static_cast(n) : 0ULL}); + break; + } + default: + args.emplace_back(nullptr); + break; + } + } + auto res = box->fn(args); + if (!res) { + const std::string& msg = res.error().message(); + sqlite3_result_error( + ctx, + msg.empty() ? "Sqlite scalar function failed" : msg.c_str(), + clamp_to_int(msg.size())); + return; + } + const OwnedValue& out = *res; + if (out.is_null()) { + sqlite3_result_null(ctx); + } else if (const auto* iv = std::get_if(&out.value)) { + sqlite3_result_int64(ctx, *iv); + } else if (const auto* dv = std::get_if(&out.value)) { + sqlite3_result_double(ctx, *dv); + } else if (const auto* sv = std::get_if(&out.value)) { + sqlite3_result_text( + ctx, + sv->empty() ? "" : sv->data(), + clamp_to_int(sv->size()), + SQLITE_TRANSIENT); + } else if (const auto* bv = std::get_if>(&out.value)) { + sqlite3_result_blob( + ctx, + bv->empty() ? static_cast("") : bv->data(), + clamp_to_int(bv->size()), + SQLITE_TRANSIENT); + } + } catch (const std::exception& ex) { + sqlite3_result_error(ctx, ex.what(), -1); + } catch (...) { + sqlite3_result_error(ctx, "Sqlite: scalar function threw unknown exception", -1); + } + } + + int authorizer_trampoline( + void* user_data, + int action_code, + const char* arg1, + const char* arg2, + const char* db_name, + const char* trigger_or_view) noexcept + { + const auto* box = static_cast(user_data); + if (!box || !box->cb) { + return SQLITE_OK; + } + try { + const auto decision = box->cb( + action_code, + arg1 ? std::string_view{arg1} : std::string_view{}, + arg2 ? std::string_view{arg2} : std::string_view{}, + db_name ? std::string_view{db_name} : std::string_view{}, + trigger_or_view ? std::string_view{trigger_or_view} : std::string_view{}); + switch (decision) { + case AuthorizerDecision::Allow: return SQLITE_OK; + case AuthorizerDecision::Ignore: return SQLITE_IGNORE; + case AuthorizerDecision::Deny: return SQLITE_DENY; + } + return SQLITE_DENY; + } catch (...) { + return SQLITE_DENY; + } + } + + inline constexpr char kStaticEmptySentinel = '\0'; } // namespace - // ── Statement ─────────────────────────────────────────────────────────── + // ── ScopedFaultGuard ───────────────────────────────────────────────────── + + ScopedFaultGuard::ScopedFaultGuard(FaultConfig cfg) noexcept + { + std::lock_guard lk{g_fault_mutex}; + prev_ = g_fault_config; + g_fault_config = cfg; + } + + ScopedFaultGuard::~ScopedFaultGuard() + { + std::lock_guard lk{g_fault_mutex}; + g_fault_config = prev_; + } + + FaultConfig ScopedFaultGuard::current() noexcept + { + std::lock_guard lk{g_fault_mutex}; + return g_fault_config; + } + + // ── detail::ConnectionState ────────────────────────────────────────────── + + namespace detail + { + struct ConnectionState { + sqlite3* db{nullptr}; + std::filesystem::path path{}; + OpenOptions options{}; + EffectiveCapabilities caps{}; + bool closing{false}; + bool closed{false}; + std::size_t live_statements{0}; + bool active_transaction{false}; + std::size_t open_savepoints{0}; + + std::vector> scalar_functions{}; + std::unique_ptr authorizer{}; + + std::mutex interrupt_mu{}; + std::uint64_t active_op_gen{0}; + std::atomic cancel_requested{false}; + std::shared_ptr> progress_predicate{}; + + void emit_diagnostic(std::string_view msg) const noexcept + { + if (options.diagnostic_hook) { + try { + options.diagnostic_hook(msg); + } catch (...) { + } + } + } + + [[nodiscard]] std::uint64_t current_wal_size_bytes() const noexcept + { + if (caps.in_memory || path.empty()) { + return 0; + } + std::error_code ec; + const std::filesystem::path wal_path{path.string() + "-wal"}; + const auto sz = std::filesystem::file_size(wal_path, ec); + return ec ? 0ULL : static_cast(sz); + } + + ~ConnectionState() + { + if (db != nullptr) { + // Unregister SQLite hooks outside interrupt_mu so db->mutex never + // nests inside interrupt_mu (lock order is strictly interrupt_mu -> db->mutex). + sqlite3_progress_handler(db, 0, nullptr, nullptr); + sqlite3_set_authorizer(db, nullptr, nullptr); + sqlite3* const db_to_close = db; + { + std::lock_guard lk{interrupt_mu}; + active_op_gen = 0; + cancel_requested.store(false, std::memory_order_release); + db = nullptr; + } + progress_predicate.reset(); + const int rc = sqlite3_close(db_to_close); + if (rc != SQLITE_OK) { + emit_diagnostic(std::format( + "Sqlite: deferred close failed (rc={}, msg={})", + rc, + sqlite3_errmsg(db_to_close) ? sqlite3_errmsg(db_to_close) : "unknown")); + (void)sqlite3_close_v2(db_to_close); + } + } + scalar_functions.clear(); + authorizer.reset(); + } + }; + + int progress_handler_trampoline(void* ctx) noexcept + { + auto* conn = static_cast(ctx); + if (conn == nullptr) { + return 0; + } + // Invoked synchronously on the connection's worker thread while SQLite + // holds db->mutex; never acquire interrupt_mu here to avoid lock inversion. + if (conn->cancel_requested.load(std::memory_order_acquire)) { + return 1; + } + const auto pred = conn->progress_predicate; + if (!pred || !(*pred)) { + return 0; + } + try { + if ((*pred)()) { + conn->cancel_requested.store(true, std::memory_order_release); + return 1; + } + } catch (...) { + conn->cancel_requested.store(true, std::memory_order_release); + return 1; + } + return 0; + } + } // namespace detail + + // ── RowView ────────────────────────────────────────────────────────────── + + bool RowView::is_valid() const noexcept + { + return m_stmt != nullptr && + m_stmt->is_open() && + m_stmt->has_row() && + m_stmt->row_generation() == m_generation; + } + + int RowView::column_count() const noexcept + { + return is_valid() ? m_stmt->column_count() : 0; + } + + Result RowView::column_type(int col) const + { + if (!is_valid()) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::misuse, + "Sqlite: RowView has expired or belongs to an invalid statement")); + } + return m_stmt->column_type(col); + } + + Result RowView::is_null(int col) const + { + auto ct = column_type(col); + if (!ct) return Void::Result::fail(std::move(ct).error()); + return *ct == ColumnType::Null; + } + + Result RowView::get_int(int col) const + { + if (!is_valid()) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::misuse, "Sqlite: RowView expired before get_int")); + } + return m_stmt->try_column_int(col); + } + + Result RowView::get_double(int col) const + { + if (!is_valid()) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::misuse, "Sqlite: RowView expired before get_double")); + } + return m_stmt->try_column_double(col); + } + + Result RowView::get_text_view(int col) const + { + if (!is_valid()) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::misuse, "Sqlite: RowView expired before get_text_view")); + } + return m_stmt->try_column_text_view(col); + } + + Result RowView::get_text(int col) const + { + if (!is_valid()) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::misuse, "Sqlite: RowView expired before get_text")); + } + return m_stmt->try_column_text(col); + } + + Result> RowView::get_blob_view(int col) const + { + if (!is_valid()) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::misuse, "Sqlite: RowView expired before get_blob_view")); + } + return m_stmt->try_column_blob_view(col); + } + + Result> RowView::get_blob(int col) const + { + if (!is_valid()) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::misuse, "Sqlite: RowView expired before get_blob")); + } + return m_stmt->try_column_blob(col); + } + + Result> RowView::get_optional_int(int col) const + { + if (!is_valid()) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::misuse, "Sqlite: RowView expired before get_optional_int")); + } + return m_stmt->try_column_optional_int(col); + } + + Result> RowView::get_optional_double(int col) const + { + if (!is_valid()) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::misuse, "Sqlite: RowView expired before get_optional_double")); + } + return m_stmt->try_column_optional_double(col); + } + + Result> RowView::get_optional_text(int col) const + { + if (!is_valid()) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::misuse, "Sqlite: RowView expired before get_optional_text")); + } + return m_stmt->try_column_optional_text(col); + } + + Result>> RowView::get_optional_blob(int col) const + { + if (!is_valid()) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::misuse, "Sqlite: RowView expired before get_optional_blob")); + } + return m_stmt->try_column_optional_blob(col); + } + + Result RowView::get_value(int col) const + { + if (!is_valid()) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::misuse, "Sqlite: RowView expired before get_value")); + } + return m_stmt->try_column_value(col); + } + + Result RowView::copy() const + { + if (!is_valid()) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::misuse, "Sqlite: RowView expired before copy")); + } + return m_stmt->copy_row(); + } + + // ── Statement ──────────────────────────────────────────────────────────── + + Statement::Statement( + std::shared_ptr conn, + sqlite3_stmt* stmt) noexcept + : m_conn(std::move(conn)), m_stmt(stmt) + { + } + + void Statement::release_handle() noexcept + { + ++m_row_generation; + m_has_row = false; + if (m_stmt != nullptr) { + sqlite3_finalize(m_stmt); + m_stmt = nullptr; + if (m_conn && m_conn->live_statements > 0) { + --m_conn->live_statements; + } + } + m_borrowed_owners.clear(); + m_conn.reset(); + } Statement::~Statement() { - if (m_stmt) sqlite3_finalize(m_stmt); + release_handle(); } Statement::Statement(Statement&& o) noexcept - : m_stmt(std::exchange(o.m_stmt, nullptr)) + : m_conn(std::move(o.m_conn)), + m_stmt(std::exchange(o.m_stmt, nullptr)), + m_has_row(std::exchange(o.m_has_row, false)), + m_row_generation(o.m_row_generation), + m_borrowed_owners(std::move(o.m_borrowed_owners)), + m_last_bind_error(std::move(o.m_last_bind_error)) { } Statement& Statement::operator=(Statement&& o) noexcept { if (this != &o) { - if (m_stmt) sqlite3_finalize(m_stmt); + release_handle(); + m_conn = std::move(o.m_conn); m_stmt = std::exchange(o.m_stmt, nullptr); + m_has_row = std::exchange(o.m_has_row, false); + m_row_generation = o.m_row_generation; + m_borrowed_owners = std::move(o.m_borrowed_owners); + m_last_bind_error = std::move(o.m_last_bind_error); } return *this; } Statement& Statement::bind(int index, std::int64_t value) { - sqlite3_bind_int64(m_stmt, index, value); + auto r = bind_checked(index, ValueView{value}); + m_last_bind_error = r ? std::nullopt : std::optional{std::move(r).error()}; return *this; } Statement& Statement::bind(int index, double value) { - sqlite3_bind_double(m_stmt, index, value); + auto r = bind_checked(index, ValueView{value}); + m_last_bind_error = r ? std::nullopt : std::optional{std::move(r).error()}; return *this; } Statement& Statement::bind(int index, std::string_view value) { - sqlite3_bind_text(m_stmt, index, value.data(), - static_cast(value.size()), SQLITE_TRANSIENT); + auto r = bind_checked(index, ValueView{value}); + m_last_bind_error = r ? std::nullopt : std::optional{std::move(r).error()}; return *this; } Statement& Statement::bind(int index, std::nullptr_t) { - sqlite3_bind_null(m_stmt, index); + auto r = bind_checked(index, ValueView{nullptr}); + m_last_bind_error = r ? std::nullopt : std::optional{std::move(r).error()}; return *this; } @@ -69,36 +706,313 @@ namespace Void::Sqlite return bind(index, nullptr); } - Result Statement::step() + int Statement::bind_parameter_count() const noexcept { - const int rc = sqlite3_step(m_stmt); - if (rc == SQLITE_ROW) return true; - if (rc == SQLITE_DONE) return false; - return Void::Result::fail( - Error{std::format("Sqlite: step failed (code {})", rc)}); + return m_stmt ? sqlite3_bind_parameter_count(m_stmt) : 0; } - void Statement::reset() noexcept { sqlite3_reset(m_stmt); } - void Statement::clear_bindings() noexcept { sqlite3_clear_bindings(m_stmt); } + Result Statement::bind_parameter_index(std::string_view name) const + { + if (!m_stmt) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::misuse, "Sqlite: bind_parameter_index on closed statement")); + } + if (name.empty() || name.find('\0') != std::string_view::npos) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::invalid_argument, + "Sqlite: invalid bind parameter name")); + } + const std::string zname{name}; + const int idx = sqlite3_bind_parameter_index(m_stmt, zname.c_str()); + if (idx <= 0) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::not_found, + std::format("Sqlite: bind parameter '{}' not found", name))); + } + return idx; + } + + Result Statement::bind_checked(int index, ValueView value) + { + if (!m_stmt || !m_conn || m_conn->db == nullptr) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::misuse, "Sqlite: bind_checked on finalized statement")); + } + const int param_count = sqlite3_bind_parameter_count(m_stmt); + if (index < 1 || index > param_count) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::range, + std::format("Sqlite: bind index {} out of range [1, {}]", index, param_count), + SQLITE_RANGE, + SQLITE_RANGE)); + } + + const std::size_t max_val = m_conn->options.limits.max_value_bytes; + int rc = SQLITE_OK; + if (value.is_null()) { + rc = sqlite3_bind_null(m_stmt, index); + } else if (const auto* iv = std::get_if(&value.value)) { + rc = sqlite3_bind_int64(m_stmt, index, *iv); + } else if (const auto* dv = std::get_if(&value.value)) { + rc = sqlite3_bind_double(m_stmt, index, *dv); + } else if (const auto* sv = std::get_if(&value.value)) { + if (sv->size() > max_val) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::size_limit, + std::format("Sqlite: bound text length {} exceeds max_value_bytes {}", + sv->size(), max_val))); + } + const char* ptr = sv->empty() ? &kStaticEmptySentinel : sv->data(); + rc = sqlite3_bind_text64( + m_stmt, index, ptr, static_cast(sv->size()), + SQLITE_TRANSIENT, SQLITE_UTF8); + } else if (const auto* bv = std::get_if>(&value.value)) { + if (bv->size() > max_val) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::size_limit, + std::format("Sqlite: bound blob length {} exceeds max_value_bytes {}", + bv->size(), max_val))); + } + const void* ptr = bv->empty() + ? static_cast(&kStaticEmptySentinel) + : bv->data(); + rc = sqlite3_bind_blob64( + m_stmt, index, ptr, static_cast(bv->size()), + SQLITE_TRANSIENT); + } + + if (rc != SQLITE_OK) { + return Void::Result::fail(sqlite_error_from_db(m_conn->db, rc, "bind")); + } + + const auto slot = static_cast(index); + if (slot < m_borrowed_owners.size()) { + m_borrowed_owners[slot].reset(); + } + return {}; + } + + Result Statement::bind_checked(std::string_view name, ValueView value) + { + auto idx = bind_parameter_index(name); + if (!idx) return Void::Result::fail(std::move(idx).error()); + return bind_checked(*idx, value); + } + + Result Statement::bind_borrowed_text( + int index, std::string_view value, std::shared_ptr owner) + { + if (!m_stmt || !m_conn || m_conn->db == nullptr) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::misuse, "Sqlite: bind_borrowed_text on finalized statement")); + } + if (!owner) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::invalid_argument, + "Sqlite: bind_borrowed_text requires a non-null lifetime owner")); + } + const int param_count = sqlite3_bind_parameter_count(m_stmt); + if (index < 1 || index > param_count) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::range, + std::format("Sqlite: bind index {} out of range [1, {}]", index, param_count), + SQLITE_RANGE, + SQLITE_RANGE)); + } + if (value.size() > m_conn->options.limits.max_value_bytes) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::size_limit, + "Sqlite: borrowed text exceeds max_value_bytes")); + } + const char* ptr = value.empty() ? &kStaticEmptySentinel : value.data(); + const int rc = sqlite3_bind_text64( + m_stmt, index, ptr, static_cast(value.size()), + SQLITE_STATIC, SQLITE_UTF8); + if (rc != SQLITE_OK) { + return Void::Result::fail(sqlite_error_from_db(m_conn->db, rc, "bind_borrowed_text")); + } + const auto slot = static_cast(index); + if (m_borrowed_owners.size() <= slot) { + m_borrowed_owners.resize(slot + 1); + } + m_borrowed_owners[slot] = std::move(owner); + return {}; + } + + Result Statement::bind_borrowed_blob( + int index, std::span value, std::shared_ptr owner) + { + if (!m_stmt || !m_conn || m_conn->db == nullptr) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::misuse, "Sqlite: bind_borrowed_blob on finalized statement")); + } + if (!owner) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::invalid_argument, + "Sqlite: bind_borrowed_blob requires a non-null lifetime owner")); + } + const int param_count = sqlite3_bind_parameter_count(m_stmt); + if (index < 1 || index > param_count) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::range, + std::format("Sqlite: bind index {} out of range [1, {}]", index, param_count), + SQLITE_RANGE, + SQLITE_RANGE)); + } + if (value.size() > m_conn->options.limits.max_value_bytes) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::size_limit, + "Sqlite: borrowed blob exceeds max_value_bytes")); + } + const void* ptr = value.empty() + ? static_cast(&kStaticEmptySentinel) + : value.data(); + const int rc = sqlite3_bind_blob64( + m_stmt, index, ptr, static_cast(value.size()), + SQLITE_STATIC); + if (rc != SQLITE_OK) { + return Void::Result::fail(sqlite_error_from_db(m_conn->db, rc, "bind_borrowed_blob")); + } + const auto slot = static_cast(index); + if (m_borrowed_owners.size() <= slot) { + m_borrowed_owners.resize(slot + 1); + } + m_borrowed_owners[slot] = std::move(owner); + return {}; + } + + Result Statement::step() + { + if (!m_stmt || !m_conn || m_conn->db == nullptr) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::misuse, "Sqlite: step on finalized statement")); + } + ++m_row_generation; + m_has_row = false; + + if (!m_conn->active_transaction && + sqlite3_stmt_readonly(m_stmt) == 0 && + m_conn->current_wal_size_bytes() >= + m_conn->options.limits.wal_stop_writes_threshold_bytes) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::overloaded, + "Sqlite: WAL size reached write-admission stop threshold; checkpoint required")); + } + + const int rc = sqlite3_step(m_stmt); + if (rc == SQLITE_ROW) { + m_has_row = true; + return true; + } + if (rc == SQLITE_DONE) { + return false; + } + return Void::Result::fail(sqlite_error_from_db(m_conn->db, rc, "step")); + } + + void Statement::reset() noexcept + { + ++m_row_generation; + m_has_row = false; + if (m_stmt) { + sqlite3_reset(m_stmt); + } + } + + Result Statement::reset_checked() + { + if (!m_stmt || !m_conn || m_conn->db == nullptr) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::misuse, "Sqlite: reset_checked on finalized statement")); + } + ++m_row_generation; + m_has_row = false; + const int rc = sqlite3_reset(m_stmt); + if (rc != SQLITE_OK) { + return Void::Result::fail(sqlite_error_from_db(m_conn->db, rc, "reset")); + } + return {}; + } + + void Statement::clear_bindings() noexcept + { + if (m_stmt) { + sqlite3_clear_bindings(m_stmt); + } + m_borrowed_owners.clear(); + m_last_bind_error.reset(); + } + + Result Statement::clear_bindings_checked() + { + if (!m_stmt || !m_conn || m_conn->db == nullptr) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::misuse, "Sqlite: clear_bindings_checked on finalized statement")); + } + const int rc = sqlite3_clear_bindings(m_stmt); + m_borrowed_owners.clear(); + m_last_bind_error.reset(); + if (rc != SQLITE_OK) { + return Void::Result::fail(sqlite_error_from_db(m_conn->db, rc, "clear_bindings")); + } + return {}; + } + + Result Statement::finalize_checked() + { + ++m_row_generation; + m_has_row = false; + if (!m_stmt) { + return {}; + } + sqlite3* db = m_conn ? m_conn->db : nullptr; + const int rc = sqlite3_finalize(m_stmt); + m_stmt = nullptr; + if (m_conn && m_conn->live_statements > 0) { + --m_conn->live_statements; + } + m_borrowed_owners.clear(); + auto conn_keep = std::move(m_conn); + if (rc != SQLITE_OK) { + return Void::Result::fail(sqlite_error_from_db(db, rc, "finalize")); + } + return {}; + } int Statement::column_count() const noexcept { - return sqlite3_column_count(m_stmt); + return m_stmt ? sqlite3_column_count(m_stmt) : 0; } + bool Statement::is_null(int col) const noexcept { + if (!m_stmt || !m_has_row || col < 0 || col >= column_count()) { + return true; + } return sqlite3_column_type(m_stmt, col) == SQLITE_NULL; } + std::int64_t Statement::column_int(int col) const noexcept { + if (!m_stmt || !m_has_row || col < 0 || col >= column_count()) { + return 0; + } return sqlite3_column_int64(m_stmt, col); } + double Statement::column_double(int col) const noexcept { + if (!m_stmt || !m_has_row || col < 0 || col >= column_count()) { + return 0.0; + } return sqlite3_column_double(m_stmt, col); } + std::string Statement::column_text(int col) const { + if (!m_stmt || !m_has_row || col < 0 || col >= column_count()) { + return {}; + } const auto* p = sqlite3_column_text(m_stmt, col); const int n = sqlite3_column_bytes(m_stmt, col); if (!p || n <= 0) return {}; @@ -106,142 +1020,926 @@ namespace Void::Sqlite static_cast(n)}; } - // ── Transaction ───────────────────────────────────────────────────────── + Result Statement::validate_column_access(int col) const + { + if (!m_stmt || !m_conn) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::misuse, "Sqlite: column access on finalized statement")); + } + if (!m_has_row) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::misuse, "Sqlite: column access without an active row")); + } + const int cols = sqlite3_column_count(m_stmt); + if (col < 0 || col >= cols) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::range, + std::format("Sqlite: column index {} out of range [0, {})", col, cols), + SQLITE_RANGE, + SQLITE_RANGE)); + } + return {}; + } + + Result Statement::current_row() const + { + if (!m_stmt || !m_has_row) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::misuse, + "Sqlite: current_row() requested with no active row")); + } + return RowView{this, m_row_generation}; + } + + Result Statement::column_type(int col) const + { + if (auto v = validate_column_access(col); !v) { + return Void::Result::fail(std::move(v).error()); + } + return map_column_type(sqlite3_column_type(m_stmt, col)); + } + + Result Statement::try_column_int(int col) const + { + if (auto v = validate_column_access(col); !v) { + return Void::Result::fail(std::move(v).error()); + } + const int t = sqlite3_column_type(m_stmt, col); + if (t != SQLITE_INTEGER) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::type_mismatch, + std::format("Sqlite: column {} expected INTEGER, got type {}", col, t))); + } + return static_cast(sqlite3_column_int64(m_stmt, col)); + } + + Result Statement::try_column_double(int col) const + { + if (auto v = validate_column_access(col); !v) { + return Void::Result::fail(std::move(v).error()); + } + const int t = sqlite3_column_type(m_stmt, col); + if (t != SQLITE_FLOAT) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::type_mismatch, + std::format("Sqlite: column {} expected REAL, got type {}", col, t))); + } + return sqlite3_column_double(m_stmt, col); + } + + Result Statement::try_column_text_view(int col) const + { + if (auto v = validate_column_access(col); !v) { + return Void::Result::fail(std::move(v).error()); + } + const int t = sqlite3_column_type(m_stmt, col); + if (t != SQLITE_TEXT) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::type_mismatch, + std::format("Sqlite: column {} expected TEXT, got type {}", col, t))); + } + const auto* p = sqlite3_column_text(m_stmt, col); + const int n = sqlite3_column_bytes(m_stmt, col); + if (n < 0) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::sqlite_error, "Sqlite: negative column byte length")); + } + const auto sz = static_cast(n); + if (sz > m_conn->options.limits.max_value_bytes) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::size_limit, + std::format("Sqlite: column {} text size {} exceeds max_value_bytes {}", + col, sz, m_conn->options.limits.max_value_bytes))); + } + if (sz == 0 || p == nullptr) { + return std::string_view{}; + } + return std::string_view{reinterpret_cast(p), sz}; + } + + Result Statement::try_column_text(int col) const + { + auto sv = try_column_text_view(col); + if (!sv) return Void::Result::fail(std::move(sv).error()); + return std::string{*sv}; + } + + Result> Statement::try_column_blob_view(int col) const + { + if (auto v = validate_column_access(col); !v) { + return Void::Result::fail(std::move(v).error()); + } + const int t = sqlite3_column_type(m_stmt, col); + if (t != SQLITE_BLOB) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::type_mismatch, + std::format("Sqlite: column {} expected BLOB, got type {}", col, t))); + } + const auto* p = sqlite3_column_blob(m_stmt, col); + const int n = sqlite3_column_bytes(m_stmt, col); + if (n < 0) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::sqlite_error, "Sqlite: negative blob length")); + } + const auto sz = static_cast(n); + if (sz > m_conn->options.limits.max_value_bytes) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::size_limit, + std::format("Sqlite: column {} blob size {} exceeds max_value_bytes {}", + col, sz, m_conn->options.limits.max_value_bytes))); + } + if (sz == 0 || p == nullptr) { + return std::span{}; + } + return std::span{static_cast(p), sz}; + } + + Result> Statement::try_column_blob(int col) const + { + auto bv = try_column_blob_view(col); + if (!bv) return Void::Result::fail(std::move(bv).error()); + return std::vector{bv->begin(), bv->end()}; + } + + Result> Statement::try_column_optional_int(int col) const + { + auto ct = column_type(col); + if (!ct) return Void::Result::fail(std::move(ct).error()); + if (*ct == ColumnType::Null) return std::optional{std::nullopt}; + auto v = try_column_int(col); + if (!v) return Void::Result::fail(std::move(v).error()); + return std::optional{*v}; + } + + Result> Statement::try_column_optional_double(int col) const + { + auto ct = column_type(col); + if (!ct) return Void::Result::fail(std::move(ct).error()); + if (*ct == ColumnType::Null) return std::optional{std::nullopt}; + auto v = try_column_double(col); + if (!v) return Void::Result::fail(std::move(v).error()); + return std::optional{*v}; + } + + Result> Statement::try_column_optional_text(int col) const + { + auto ct = column_type(col); + if (!ct) return Void::Result::fail(std::move(ct).error()); + if (*ct == ColumnType::Null) return std::optional{std::nullopt}; + auto v = try_column_text(col); + if (!v) return Void::Result::fail(std::move(v).error()); + return std::optional{std::move(*v)}; + } + + Result>> Statement::try_column_optional_blob(int col) const + { + auto ct = column_type(col); + if (!ct) return Void::Result::fail(std::move(ct).error()); + if (*ct == ColumnType::Null) return std::optional>{std::nullopt}; + auto v = try_column_blob(col); + if (!v) return Void::Result::fail(std::move(v).error()); + return std::optional>{std::move(*v)}; + } + + Result Statement::try_column_value(int col) const + { + auto ct = column_type(col); + if (!ct) return Void::Result::fail(std::move(ct).error()); + switch (*ct) { + case ColumnType::Null: + return OwnedValue{nullptr}; + case ColumnType::Integer: { + auto v = try_column_int(col); + if (!v) return Void::Result::fail(std::move(v).error()); + return OwnedValue{*v}; + } + case ColumnType::Real: { + auto v = try_column_double(col); + if (!v) return Void::Result::fail(std::move(v).error()); + return OwnedValue{*v}; + } + case ColumnType::Text: { + auto v = try_column_text(col); + if (!v) return Void::Result::fail(std::move(v).error()); + return OwnedValue{std::move(*v)}; + } + case ColumnType::Blob: { + auto v = try_column_blob(col); + if (!v) return Void::Result::fail(std::move(v).error()); + return OwnedValue{std::move(*v)}; + } + } + return OwnedValue{nullptr}; + } + + Result Statement::copy_row() const + { + if (!m_stmt || !m_has_row) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::misuse, "Sqlite: copy_row with no active row")); + } + const int cols = sqlite3_column_count(m_stmt); + OwnedRow row; + row.columns.reserve(static_cast(std::max(0, cols))); + for (int c = 0; c < cols; ++c) { + auto val = try_column_value(c); + if (!val) return Void::Result::fail(std::move(val).error()); + row.columns.push_back(std::move(*val)); + } + return row; + } + + // ── Transaction ────────────────────────────────────────────────────────── + + Transaction::Transaction(std::shared_ptr conn) noexcept + : m_conn(std::move(conn)), m_state(TransactionState::Active) + { + } Transaction::~Transaction() { - if (!m_done && m_db && m_db->handle()) { - sqlite3_exec(m_db->handle(), "ROLLBACK", nullptr, nullptr, nullptr); + if (m_state == TransactionState::Active) { + auto r = rollback_checked(); + if (!r && m_conn) { + m_conn->emit_diagnostic(r.error().message()); + } } } Transaction::Transaction(Transaction&& o) noexcept - : m_db(std::exchange(o.m_db, nullptr)), - m_done(std::exchange(o.m_done, true)) + : m_conn(std::move(o.m_conn)), + m_state(std::exchange(o.m_state, TransactionState::RolledBack)) { } Transaction& Transaction::operator=(Transaction&& o) noexcept { if (this != &o) { - if (!m_done && m_db && m_db->handle()) { - sqlite3_exec(m_db->handle(), "ROLLBACK", nullptr, nullptr, - nullptr); + if (m_state == TransactionState::Active) { + auto r = rollback_checked(); + if (!r && m_conn) { + m_conn->emit_diagnostic(r.error().message()); + } } - m_db = std::exchange(o.m_db, nullptr); - m_done = std::exchange(o.m_done, true); + m_conn = std::move(o.m_conn); + m_state = std::exchange(o.m_state, TransactionState::RolledBack); } return *this; } Result Transaction::commit() { - if (m_done) return {}; - m_done = true; - if (sqlite3_exec(m_db->handle(), "COMMIT", nullptr, nullptr, nullptr) != - SQLITE_OK) { - return Void::Result::fail(sqlite_error(m_db->handle(), "commit")); + if (m_state != TransactionState::Active) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::misuse, + "Sqlite: commit() called on non-active transaction")); } - return {}; + if (!m_conn || m_conn->db == nullptr) { + m_state = TransactionState::RecoveryRequired; + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::recovery_required, + "Sqlite: transaction lost its underlying connection before commit")); + } + + const auto fault = consume_fault_commit(); + if (fault.fail_next_commit_rc != 0) { + if (fault.auto_rollback_on_faulted_commit) { + (void)sqlite3_exec(m_conn->db, "ROLLBACK", nullptr, nullptr, nullptr); + } + if (sqlite3_get_autocommit(m_conn->db) == 0) { + m_state = TransactionState::Active; + m_conn->active_transaction = true; + } else { + m_state = TransactionState::RolledBack; + m_conn->active_transaction = false; + } + return Void::Result::fail(make_sqlite_error( + map_sqlite_rc(fault.fail_next_commit_rc), + "Sqlite: injected commit failure", + fault.fail_next_commit_rc, + fault.fail_next_commit_rc)); + } + + char* err = nullptr; + const int rc = sqlite3_exec(m_conn->db, "COMMIT", nullptr, nullptr, &err); + if (rc == SQLITE_OK) { + m_state = TransactionState::Committed; + m_conn->active_transaction = false; + return {}; + } + + std::string msg = err ? err : sqlite3_errmsg(m_conn->db); + if (err) sqlite3_free(err); + const int ext = sqlite3_extended_errcode(m_conn->db); + + // SQLite may leave the transaction active after errors like SQLITE_BUSY + // or auto-roll it back on constraints/IO/full. Query autocommit before + // updating wrapper state! + if (sqlite3_get_autocommit(m_conn->db) == 0) { + m_state = TransactionState::Active; + m_conn->active_transaction = true; + } else { + m_state = TransactionState::RolledBack; + m_conn->active_transaction = false; + } + + return Void::Result::fail(make_sqlite_error( + map_sqlite_rc(rc), + std::format("Sqlite: commit: {}", msg), + rc, + ext)); + } + + Result Transaction::rollback_checked() + { + if (m_state == TransactionState::RolledBack) { + return {}; + } + if (m_state != TransactionState::Active) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::misuse, + "Sqlite: rollback() called on finalized transaction")); + } + if (!m_conn || m_conn->db == nullptr) { + m_state = TransactionState::RecoveryRequired; + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::recovery_required, + "Sqlite: transaction missing connection during rollback")); + } + + char* err = nullptr; + const int rc = sqlite3_exec(m_conn->db, "ROLLBACK", nullptr, nullptr, &err); + std::string msg = err ? err : (rc == SQLITE_OK ? "" : sqlite3_errmsg(m_conn->db)); + if (err) sqlite3_free(err); + + if (rc == SQLITE_OK || sqlite3_get_autocommit(m_conn->db) != 0) { + m_state = TransactionState::RolledBack; + m_conn->active_transaction = false; + return {}; + } + + m_state = TransactionState::RecoveryRequired; + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::recovery_required, + std::format("Sqlite: rollback failed while autocommit remains 0: {}", msg), + rc, + sqlite3_extended_errcode(m_conn->db))); } void Transaction::rollback() noexcept { - if (m_done) return; - m_done = true; - sqlite3_exec(m_db->handle(), "ROLLBACK", nullptr, nullptr, nullptr); + (void)rollback_checked(); } - // ── Database ──────────────────────────────────────────────────────────── + // ── Savepoint ──────────────────────────────────────────────────────────── - Database::~Database() - { - if (m_db) sqlite3_close(m_db); - } - - Database::Database(Database&& o) noexcept - : m_db(std::exchange(o.m_db, nullptr)) + Savepoint::Savepoint( + std::shared_ptr conn, + std::string name) noexcept + : m_conn(std::move(conn)), m_name(std::move(name)), m_active(true) { } - Database& Database::operator=(Database&& o) noexcept + Savepoint::~Savepoint() + { + if (m_active) { + auto r = rollback_and_release(); + if (!r && m_conn) { + m_conn->emit_diagnostic(r.error().message()); + } + } + } + + Savepoint::Savepoint(Savepoint&& o) noexcept + : m_conn(std::move(o.m_conn)), + m_name(std::move(o.m_name)), + m_active(std::exchange(o.m_active, false)) + { + } + + Savepoint& Savepoint::operator=(Savepoint&& o) noexcept { if (this != &o) { - if (m_db) sqlite3_close(m_db); - m_db = std::exchange(o.m_db, nullptr); + if (m_active) { + auto r = rollback_and_release(); + if (!r && m_conn) { + m_conn->emit_diagnostic(r.error().message()); + } + } + m_conn = std::move(o.m_conn); + m_name = std::move(o.m_name); + m_active = std::exchange(o.m_active, false); } return *this; } - Result Database::open(const std::filesystem::path& path, - OpenMode mode) + Result Savepoint::release() { - int flags = 0; - switch (mode) { - case OpenMode::ReadOnly: flags = SQLITE_OPEN_READONLY; break; - case OpenMode::ReadWrite: flags = SQLITE_OPEN_READWRITE; break; + if (!m_active || !m_conn || m_conn->db == nullptr) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::misuse, "Sqlite: savepoint is not active")); + } + auto r = exec_raw_sql(m_conn->db, std::format("RELEASE SAVEPOINT {}", m_name), "release savepoint"); + if (r) { + m_active = false; + if (m_conn->open_savepoints > 0) { + --m_conn->open_savepoints; + } + } + return r; + } + + Result Savepoint::rollback_to() + { + if (!m_active || !m_conn || m_conn->db == nullptr) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::misuse, "Sqlite: savepoint is not active")); + } + return exec_raw_sql(m_conn->db, std::format("ROLLBACK TO SAVEPOINT {}", m_name), "rollback savepoint"); + } + + Result Savepoint::rollback_and_release() + { + if (!m_active) { + return {}; + } + if (!m_conn || m_conn->db == nullptr) { + m_active = false; + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::misuse, "Sqlite: savepoint connection missing")); + } + auto r1 = exec_raw_sql(m_conn->db, std::format("ROLLBACK TO SAVEPOINT {}", m_name), "rollback savepoint"); + auto r2 = exec_raw_sql(m_conn->db, std::format("RELEASE SAVEPOINT {}", m_name), "release savepoint"); + if (r2) { + m_active = false; + if (m_conn->open_savepoints > 0) { + --m_conn->open_savepoints; + } + } + if (!r1) return r1; + return r2; + } + + // ── Database ───────────────────────────────────────────────────────────── + + Database::Database(std::shared_ptr conn) noexcept + : m_conn(std::move(conn)) + { + } + + Database::~Database() = default; + Database::Database(Database&&) noexcept = default; + Database& Database::operator=(Database&&) noexcept = default; + + Result Database::open(const std::filesystem::path& path, OpenMode mode) + { + OpenOptions opts; + opts.mode = mode; + return open_with_options(path, std::move(opts)); + } + + Result Database::open_with_options( + const std::filesystem::path& path, + OpenOptions options) + { + if (auto v = validate_limits(options.limits); !v) { + return Void::Result::fail(std::move(v).error()); + } + + int flags = SQLITE_OPEN_FULLMUTEX; + switch (options.mode) { + case OpenMode::ReadOnly: + flags |= SQLITE_OPEN_READONLY; + break; + case OpenMode::ReadWrite: + flags |= SQLITE_OPEN_READWRITE; + break; case OpenMode::ReadWriteCreate: - flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE; + flags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE; break; } - sqlite3* db = nullptr; - const int rc = - sqlite3_open_v2(path.string().c_str(), &db, flags, nullptr); - if (rc != SQLITE_OK) { - Error e = sqlite_error(db, "open"); - if (db) sqlite3_close(db); - return Void::Result::fail(std::move(e)); + const std::string path_str = path.string(); + if (path_str.starts_with("file:")) { + flags |= SQLITE_OPEN_URI; } - Database out; - out.m_db = db; - if (mode != OpenMode::ReadOnly) { - sqlite3_busy_timeout(db, 5000); - sqlite3_exec(db, "PRAGMA journal_mode=WAL", nullptr, nullptr, - nullptr); - sqlite3_exec(db, "PRAGMA foreign_keys=ON", nullptr, nullptr, - nullptr); + + sqlite3* raw_db = nullptr; + const int open_rc = sqlite3_open_v2(path_str.c_str(), &raw_db, flags, nullptr); + if (open_rc != SQLITE_OK) { + Error err = raw_db ? sqlite_error_from_db(raw_db, open_rc, "open") + : make_sqlite_error(map_sqlite_rc(open_rc), + std::format("Sqlite: open failed: {}", + sqlite3_errstr(open_rc)), + open_rc, open_rc); + if (raw_db) { + sqlite3_close_v2(raw_db); + } + return Void::Result::fail(std::move(err)); } - return out; + + auto state = std::make_shared(); + state->db = raw_db; + state->path = path; + state->options = std::move(options); + state->caps.sqlite_version = sqlite3_libversion(); + state->caps.sqlite_version_number = sqlite3_libversion_number(); + state->caps.threadsafe_mode = sqlite3_threadsafe(); + state->caps.in_memory = is_memory_path(path); + state->caps.read_only = (state->options.mode == OpenMode::ReadOnly) || + (sqlite3_db_readonly(raw_db, "main") > 0); + + // Disable extension loading by default. + int ext_enabled = 0; + const int want_ext = state->options.allow_extension_loading ? 1 : 0; + const int cfg_rc = sqlite3_db_config( + raw_db, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, want_ext, &ext_enabled); + if (cfg_rc != SQLITE_OK || ext_enabled != want_ext) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::unsupported_pragma, + "Sqlite: failed to configure extension-loading policy", + cfg_rc, + cfg_rc)); + } + state->caps.extension_loading_enabled = (ext_enabled != 0); + + // Apply native SQLite byte limits. Keep SQLITE_LIMIT_LENGTH at least 4096 + // so internal sqlite_schema DDL rows remain functional even when callers + // configure strict small value limits on wrapper binds/reads. + sqlite3_limit(raw_db, SQLITE_LIMIT_SQL_LENGTH, + clamp_to_int(state->options.limits.max_sql_bytes)); + sqlite3_limit(raw_db, SQLITE_LIMIT_LENGTH, + clamp_to_int(std::max( + state->options.limits.max_value_bytes, 4096))); + + // Apply busy timeout. + const auto busy_ms = state->options.limits.busy_timeout.count(); + const int clamped_busy = busy_ms > INT_MAX ? INT_MAX : static_cast(busy_ms); + const int busy_rc = sqlite3_busy_timeout(raw_db, clamped_busy); + if (busy_rc != SQLITE_OK) { + return Void::Result::fail(sqlite_error_from_db(raw_db, busy_rc, "busy_timeout")); + } + + if (!state->caps.read_only) { + // Apply and verify foreign_keys pragma. + const char* fk_sql = state->options.foreign_keys ? "PRAGMA foreign_keys=ON" + : "PRAGMA foreign_keys=OFF"; + if (auto r = exec_raw_sql(raw_db, fk_sql, "pragma foreign_keys"); !r) { + return Void::Result::fail(std::move(r).error()); + } + auto fk_eff = query_single_int_pragma(raw_db, "PRAGMA foreign_keys"); + if (!fk_eff) return Void::Result::fail(std::move(fk_eff).error()); + const int want_fk = state->options.foreign_keys ? 1 : 0; + if (*fk_eff != want_fk) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::unsupported_pragma, + "Sqlite: effective foreign_keys pragma did not match requested configuration")); + } + state->caps.foreign_keys = (*fk_eff != 0); + + if (!state->caps.in_memory) { + // Apply and verify journal_mode. + const std::string want_jm = + (state->options.journal_mode == JournalMode::Wal) ? "wal" : "delete"; + std::string got_jm; + if (auto r = query_single_text_pragma( + raw_db, + std::format("PRAGMA journal_mode={}", want_jm), + got_jm); + !r) { + return Void::Result::fail(std::move(r).error()); + } + if (ascii_lower(got_jm) != want_jm) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::unsupported_pragma, + std::format("Sqlite: requested journal_mode='{}', effective='{}'", + want_jm, got_jm))); + } + state->caps.journal_mode = ascii_lower(got_jm); + + // Apply and verify synchronous mode. + const int want_sync = (state->options.sync_mode == SyncMode::Full) ? 2 : 1; + const char* sync_sql = (state->options.sync_mode == SyncMode::Full) + ? "PRAGMA synchronous=FULL" + : "PRAGMA synchronous=NORMAL"; + if (auto r = exec_raw_sql(raw_db, sync_sql, "pragma synchronous"); !r) { + return Void::Result::fail(std::move(r).error()); + } + auto got_sync = query_single_int_pragma(raw_db, "PRAGMA synchronous"); + if (!got_sync) return Void::Result::fail(std::move(got_sync).error()); + if (*got_sync != want_sync) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::unsupported_pragma, + std::format("Sqlite: requested synchronous={}, effective={}", + want_sync, *got_sync))); + } + state->caps.synchronous_mode = *got_sync; + } else { + state->caps.journal_mode = "memory"; + auto got_sync = query_single_int_pragma(raw_db, "PRAGMA synchronous"); + if (got_sync) state->caps.synchronous_mode = *got_sync; + } + } else { + std::string got_jm; + if (auto r = query_single_text_pragma(raw_db, "PRAGMA journal_mode", got_jm); r) { + state->caps.journal_mode = ascii_lower(got_jm); + } + if (auto s = query_single_int_pragma(raw_db, "PRAGMA synchronous"); s) { + state->caps.synchronous_mode = *s; + } + if (auto f = query_single_int_pragma(raw_db, "PRAGMA foreign_keys"); f) { + state->caps.foreign_keys = (*f != 0); + } + } + + return Database{std::move(state)}; } Result Database::exec(std::string_view sql) { - char* err = nullptr; - const std::string s{sql}; - if (sqlite3_exec(m_db, s.c_str(), nullptr, nullptr, &err) != SQLITE_OK) { - std::string msg = err ? err : "unknown error"; - if (err) sqlite3_free(err); - return Void::Result::fail( - Error{std::format("Sqlite: exec: {}", msg)}); + if (!m_conn || m_conn->db == nullptr || m_conn->closed) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::closed, "Sqlite: exec on closed database")); } - return {}; + if (m_conn->closing) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::closed, "Sqlite: exec rejected while closing")); + } + if (sql.size() > m_conn->options.limits.max_sql_bytes) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::size_limit, + std::format("Sqlite: exec SQL length {} exceeds max_sql_bytes {}", + sql.size(), m_conn->options.limits.max_sql_bytes))); + } + if (sql.find('\0') != std::string_view::npos) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::invalid_argument, "Sqlite: SQL contains embedded NUL byte")); + } + const std::string s{sql}; + return exec_raw_sql(m_conn->db, s, "exec"); } Result Database::prepare(std::string_view sql) { - sqlite3_stmt* stmt = nullptr; - if (sqlite3_prepare_v2(m_db, sql.data(), static_cast(sql.size()), - &stmt, nullptr) != SQLITE_OK) { - return Void::Result::fail(sqlite_error(m_db, "prepare")); + if (!m_conn || m_conn->db == nullptr || m_conn->closed) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::closed, "Sqlite: prepare on closed database")); } - return Statement{stmt}; + if (m_conn->closing) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::closed, "Sqlite: prepare rejected while closing")); + } + if (sql.size() > m_conn->options.limits.max_sql_bytes) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::size_limit, + std::format("Sqlite: prepare SQL length {} exceeds max_sql_bytes {}", + sql.size(), m_conn->options.limits.max_sql_bytes))); + } + if (m_conn->live_statements >= m_conn->options.limits.max_live_statements) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::statement_limit, + std::format("Sqlite: live_statements {} reached max_live_statements {}", + m_conn->live_statements, + m_conn->options.limits.max_live_statements))); + } + if (sql.find('\0') != std::string_view::npos) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::invalid_argument, "Sqlite: SQL contains embedded NUL byte")); + } + + sqlite3_stmt* stmt = nullptr; + const char* tail = nullptr; + const int rc = sqlite3_prepare_v2( + m_conn->db, + sql.data(), + clamp_to_int(sql.size()), + &stmt, + &tail); + if (rc != SQLITE_OK) { + if (stmt) sqlite3_finalize(stmt); + return Void::Result::fail(sqlite_error_from_db(m_conn->db, rc, "prepare")); + } + if (tail != nullptr) { + const char* const end = sql.data() + sql.size(); + for (const char* p = tail; p < end; ++p) { + if (!is_ascii_whitespace(*p)) { + if (stmt) sqlite3_finalize(stmt); + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::trailing_sql, + "Sqlite: prepare requires a single statement (non-whitespace trailing SQL rejected)")); + } + } + } + if (stmt == nullptr) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::invalid_argument, + "Sqlite: prepare received empty or comment-only SQL")); + } + ++m_conn->live_statements; + return Statement{m_conn, stmt}; } - Result Database::begin() + Result Database::begin(BeginMode mode) { - if (sqlite3_exec(m_db, "BEGIN", nullptr, nullptr, nullptr) != - SQLITE_OK) { - return Void::Result::fail(sqlite_error(m_db, "begin")); + if (!m_conn || m_conn->db == nullptr || m_conn->closed) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::closed, "Sqlite: begin on closed database")); } - return Transaction{this}; + if (m_conn->closing) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::closed, "Sqlite: begin rejected while closing")); + } + if (m_conn->active_transaction) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::misuse, + "Sqlite: nested begin() rejected; use savepoint() for nested scopes")); + } + if (mode != BeginMode::Deferred && + m_conn->current_wal_size_bytes() >= + m_conn->options.limits.wal_stop_writes_threshold_bytes) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::overloaded, + "Sqlite: WAL size reached write-admission stop threshold; checkpoint required")); + } + + const char* sql = "BEGIN"; + switch (mode) { + case BeginMode::Deferred: sql = "BEGIN DEFERRED"; break; + case BeginMode::Immediate: sql = "BEGIN IMMEDIATE"; break; + case BeginMode::Exclusive: sql = "BEGIN EXCLUSIVE"; break; + } + if (auto r = exec_raw_sql(m_conn->db, sql, "begin"); !r) { + return Void::Result::fail(std::move(r).error()); + } + m_conn->active_transaction = true; + return Transaction{m_conn}; + } + + Result Database::savepoint(std::string_view name) + { + if (!m_conn || m_conn->db == nullptr || m_conn->closed || m_conn->closing) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::closed, "Sqlite: savepoint on closed database")); + } + if (!is_valid_savepoint_name(name)) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::invalid_argument, + "Sqlite: invalid savepoint identifier")); + } + const std::string sp_name{name}; + if (auto r = exec_raw_sql(m_conn->db, std::format("SAVEPOINT {}", sp_name), "savepoint"); !r) { + return Void::Result::fail(std::move(r).error()); + } + ++m_conn->open_savepoints; + return Savepoint{m_conn, sp_name}; + } + + Result> Database::query_all( + Statement& stmt, + std::size_t max_rows, + std::size_t max_bytes) + { + if (!m_conn || m_conn->db == nullptr || m_conn->closed) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::closed, "Sqlite: query_all on closed database")); + } + const std::size_t row_cap = + max_rows == 0 ? m_conn->options.limits.max_query_all_rows : max_rows; + const std::size_t byte_cap = + max_bytes == 0 ? m_conn->options.limits.max_query_all_bytes : max_bytes; + + std::vector rows; + std::size_t total_bytes = 0; + + for (;;) { + auto has = stmt.step(); + if (!has) return Void::Result::fail(std::move(has).error()); + if (!*has) break; + + if (rows.size() >= row_cap) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::size_limit, + std::format("Sqlite: query_all exceeded max_rows {}", row_cap))); + } + auto row = stmt.copy_row(); + if (!row) return Void::Result::fail(std::move(row).error()); + + std::size_t row_bytes = 0; + for (const auto& col : row->columns) { + if (const auto* s = std::get_if(&col.value)) { + row_bytes += s->size(); + } else if (const auto* b = std::get_if>(&col.value)) { + row_bytes += b->size(); + } else if (!col.is_null()) { + row_bytes += 8; + } + } + if (row_bytes > byte_cap || total_bytes > byte_cap - row_bytes) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::size_limit, + std::format("Sqlite: query_all exceeded max_bytes {}", byte_cap))); + } + total_bytes += row_bytes; + rows.push_back(std::move(*row)); + } + + return rows; + } + + Result Database::close() + { + if (!m_conn || m_conn->db == nullptr || m_conn->closed) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::closed, "Sqlite: database is already closed")); + } + + m_conn->closing = true; + if (m_conn->live_statements > 0 || + m_conn->active_transaction || + m_conn->open_savepoints > 0) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::busy, + std::format( + "Sqlite: cannot close while {} statements, {} tx, {} savepoints are open", + m_conn->live_statements, + m_conn->active_transaction ? 1 : 0, + m_conn->open_savepoints), + SQLITE_BUSY, + SQLITE_BUSY)); + } + + if (const int injected = consume_fault_close(); injected != 0) { + return Void::Result::fail(make_sqlite_error( + map_sqlite_rc(injected), + "Sqlite: injected close failure", + injected, + injected)); + } + + sqlite3_progress_handler(m_conn->db, 0, nullptr, nullptr); + sqlite3_set_authorizer(m_conn->db, nullptr, nullptr); + { + std::lock_guard lk{m_conn->interrupt_mu}; + m_conn->active_op_gen = 0; + m_conn->cancel_requested.store(false, std::memory_order_release); + } + m_conn->progress_predicate.reset(); + + const int rc = sqlite3_close(m_conn->db); + if (rc != SQLITE_OK) { + return Void::Result::fail(sqlite_error_from_db(m_conn->db, rc, "close")); + } + { + std::lock_guard lk{m_conn->interrupt_mu}; + m_conn->db = nullptr; + } + m_conn->closed = true; + m_conn->scalar_functions.clear(); + m_conn->authorizer.reset(); + return {}; + } + + bool Database::is_open() const noexcept + { + return m_conn && m_conn->db != nullptr && !m_conn->closed; + } + + EffectiveCapabilities Database::capabilities() const + { + return m_conn ? m_conn->caps : EffectiveCapabilities{}; + } + + ConnectionHealth Database::health() const + { + ConnectionHealth out; + if (!m_conn) return out; + out.live_statements = m_conn->live_statements; + out.active_transaction = m_conn->active_transaction; + out.open_savepoints = m_conn->open_savepoints; + out.wal_size_bytes = m_conn->current_wal_size_bytes(); + out.wal_checkpoint_recommended = + out.wal_size_bytes >= m_conn->options.limits.wal_checkpoint_threshold_bytes; + out.wal_warn_exceeded = + out.wal_size_bytes >= m_conn->options.limits.wal_warn_threshold_bytes; + out.wal_write_admission_blocked = + out.wal_size_bytes >= m_conn->options.limits.wal_stop_writes_threshold_bytes; + return out; + } + + const SqliteLimits& Database::limits() const noexcept + { + static const SqliteLimits kDefaultLimits{}; + return m_conn ? m_conn->options.limits : kDefaultLimits; } std::int64_t Database::last_insert_rowid() const noexcept { - return sqlite3_last_insert_rowid(m_db); + return (m_conn && m_conn->db) ? sqlite3_last_insert_rowid(m_conn->db) : 0; } - int Database::changes() const noexcept { return sqlite3_changes(m_db); } + int Database::changes() const noexcept + { + return (m_conn && m_conn->db) ? sqlite3_changes(m_conn->db) : 0; + } Result Database::user_version() { @@ -249,29 +1947,58 @@ namespace Void::Sqlite if (!stmt) return Void::Result::fail(std::move(stmt).error()); auto row = stmt->step(); if (!row) return Void::Result::fail(std::move(row).error()); + if (!*row) return 0; return static_cast(stmt->column_int(0)); } Result Database::migrate(std::span migrations) { + if (!is_open()) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::closed, "Sqlite: migrate on closed database")); + } + + // Validate entire migration plan before executing any SQL. + int prev_version = 0; + for (const auto& m : migrations) { + if (m.version <= 0 || m.version <= prev_version) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::migration_error, + std::format("Sqlite: migration versions must be strictly increasing positive ints (got {}, prev {})", + m.version, prev_version))); + } + if (m.sql.empty()) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::migration_error, + std::format("Sqlite: migration v{} has empty SQL", m.version))); + } + prev_version = m.version; + } + auto current = user_version(); if (!current) return Void::Result::fail(std::move(current).error()); int version = *current; + if (!migrations.empty() && version > migrations.back().version) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::migration_error, + std::format("Sqlite: database schema v{} is newer than max supplied migration v{}", + version, migrations.back().version))); + } for (const auto& m : migrations) { if (m.version <= version) continue; - auto tx = begin(); + auto tx = begin(BeginMode::Immediate); if (!tx) return Void::Result::fail(std::move(tx).error()); if (auto r = exec(m.sql); !r) { - tx->rollback(); + (void)tx->rollback_checked(); return r; } - if (auto r = exec(std::format("PRAGMA user_version={}", m.version)); - !r) { - tx->rollback(); + if (auto r = exec(std::format("PRAGMA user_version={}", m.version)); !r) { + (void)tx->rollback_checked(); return r; } if (auto r = tx->commit(); !r) { + if (tx->is_active()) (void)tx->rollback_checked(); return r; } version = m.version; @@ -279,4 +2006,516 @@ namespace Void::Sqlite return {}; } + Result Database::migrate_checked(std::span migrations) + { + if (!is_open()) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::closed, "Sqlite: migrate_checked on closed database")); + } + if (m_conn->caps.read_only) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::readonly, "Sqlite: migrate_checked on read-only database")); + } + + // Validate plan strictly before any read or write. + int prev_version = 0; + for (std::size_t i = 0; i < migrations.size(); ++i) { + const auto& m = migrations[i]; + if (m.version <= 0 || m.version <= prev_version) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::migration_error, + "Sqlite: checked migration versions must be strictly increasing positive ints")); + } + if (m.id.empty() || m.checksum.empty() || m.sql.empty()) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::migration_error, + std::format("Sqlite: checked migration v{} requires non-empty id, checksum, and sql", + m.version))); + } + for (std::size_t j = 0; j < i; ++j) { + if (migrations[j].id == m.id) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::migration_error, + std::format("Sqlite: duplicate migration id '{}'", m.id))); + } + } + prev_version = m.version; + } + + auto current = user_version(); + if (!current) return Void::Result::fail(std::move(current).error()); + int version = *current; + + if (migrations.empty()) { + if (version > 0) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::migration_error, + "Sqlite: database schema version exceeds empty migration list")); + } + return {}; + } + if (version > migrations.back().version) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::migration_error, + std::format("Sqlite: database schema v{} is newer than max supplied migration v{}", + version, migrations.back().version))); + } + + // Verify existing migration table (without mutating yet). + bool table_exists = false; + { + auto chk = prepare( + "SELECT 1 FROM sqlite_master WHERE type='table' AND name='_void_schema_migrations'"); + if (!chk) return Void::Result::fail(std::move(chk).error()); + auto step_r = chk->step(); + if (!step_r) return Void::Result::fail(std::move(step_r).error()); + table_exists = *step_r; + } + + if (table_exists) { + auto sel = prepare( + "SELECT version, id, checksum FROM _void_schema_migrations ORDER BY version ASC"); + if (!sel) return Void::Result::fail(std::move(sel).error()); + for (;;) { + auto has = sel->step(); + if (!has) return Void::Result::fail(std::move(has).error()); + if (!*has) break; + auto rv = sel->try_column_int(0); + auto rid = sel->try_column_text(1); + auto rsum = sel->try_column_text(2); + if (!rv || !rid || !rsum) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::corrupt, + "Sqlite: malformed row in _void_schema_migrations")); + } + const CheckedMigration* match = nullptr; + for (const auto& m : migrations) { + if (m.version == static_cast(*rv)) { + match = &m; + break; + } + } + if (match == nullptr) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::migration_error, + std::format("Sqlite: applied migration v{} missing from migration plan", *rv))); + } + if (match->id != *rid || match->checksum != *rsum) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::migration_error, + std::format("Sqlite: migration checksum or id drift at version {}", *rv))); + } + } + } else if (version > 0) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::migration_error, + "Sqlite: non-zero user_version without _void_schema_migrations history")); + } + + bool table_created = table_exists; + for (const auto& m : migrations) { + if (m.version <= version) continue; + + auto tx = begin(BeginMode::Immediate); + if (!tx) return Void::Result::fail(std::move(tx).error()); + + if (!table_created) { + if (auto r = exec( + "CREATE TABLE IF NOT EXISTS _void_schema_migrations(" + "version INTEGER PRIMARY KEY, " + "id TEXT NOT NULL, " + "checksum TEXT NOT NULL, " + "applied_at_ms INTEGER NOT NULL)"); + !r) { + (void)tx->rollback_checked(); + return r; + } + } + + if (auto r = exec(m.sql); !r) { + (void)tx->rollback_checked(); + return r; + } + + { + auto ins = prepare( + "INSERT INTO _void_schema_migrations(version, id, checksum, applied_at_ms) " + "VALUES(?, ?, ?, ?)"); + if (!ins) { + (void)tx->rollback_checked(); + return Void::Result::fail(std::move(ins).error()); + } + const auto now_ms = std::chrono::duration_cast( + Void::Time::SystemCivilClock::instance().now().time_since_epoch()).count(); + if (auto r = ins->bind_checked(1, ValueView{static_cast(m.version)}); !r) { + (void)tx->rollback_checked(); + return r; + } + if (auto r = ins->bind_checked(2, ValueView{m.id}); !r) { + (void)tx->rollback_checked(); + return r; + } + if (auto r = ins->bind_checked(3, ValueView{m.checksum}); !r) { + (void)tx->rollback_checked(); + return r; + } + if (auto r = ins->bind_checked(4, ValueView{static_cast(now_ms)}); !r) { + (void)tx->rollback_checked(); + return r; + } + auto sr = ins->step(); + if (!sr) { + (void)tx->rollback_checked(); + return Void::Result::fail(std::move(sr).error()); + } + } + + if (auto r = exec(std::format("PRAGMA user_version={}", m.version)); !r) { + (void)tx->rollback_checked(); + return r; + } + + if (auto r = tx->commit(); !r) { + if (tx->is_active()) (void)tx->rollback_checked(); + return r; + } + table_created = true; + version = m.version; + } + + return {}; + } + + Result Database::checkpoint(CheckpointMode mode) + { + if (!is_open()) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::closed, "Sqlite: checkpoint on closed database")); + } + + int native_mode = SQLITE_CHECKPOINT_PASSIVE; + switch (mode) { + case CheckpointMode::Passive: native_mode = SQLITE_CHECKPOINT_PASSIVE; break; + case CheckpointMode::Full: native_mode = SQLITE_CHECKPOINT_FULL; break; + case CheckpointMode::Restart: native_mode = SQLITE_CHECKPOINT_RESTART; break; + case CheckpointMode::Truncate: native_mode = SQLITE_CHECKPOINT_TRUNCATE; break; + } + + int log_frames = 0; + int ckpt_frames = 0; + const int rc = sqlite3_wal_checkpoint_v2( + m_conn->db, "main", native_mode, &log_frames, &ckpt_frames); + if (rc != SQLITE_OK && rc != SQLITE_BUSY) { + return Void::Result::fail(sqlite_error_from_db(m_conn->db, rc, "checkpoint")); + } + + CheckpointReport rep; + rep.log_frames = std::max(0, log_frames); + rep.checkpointed_frames = std::max(0, ckpt_frames); + rep.busy = (rc == SQLITE_BUSY) || (rep.log_frames > rep.checkpointed_frames); + rep.wal_size_bytes = m_conn->current_wal_size_bytes(); + return rep; + } + + Result Database::backup_to( + const std::filesystem::path& destination, + BackupOptions options) + { + if (!is_open()) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::closed, "Sqlite: backup_to on closed database")); + } + if (m_conn->caps.in_memory && destination.empty()) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::invalid_argument, "Sqlite: backup destination path is empty")); + } + if (options.pages_per_step <= 0 || options.max_steps <= 0) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::invalid_argument, "Sqlite: BackupOptions bounds must be positive")); + } + if (!m_conn->caps.in_memory) { + std::error_code ec; + if (std::filesystem::exists(destination, ec) && + std::filesystem::equivalent(m_conn->path, destination, ec)) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::invalid_argument, + "Sqlite: backup destination cannot be the active source database")); + } + } + + sqlite3* dst_db = nullptr; + const int open_rc = sqlite3_open_v2( + destination.string().c_str(), + &dst_db, + SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX, + nullptr); + if (open_rc != SQLITE_OK) { + Error err = sqlite_error_from_db(dst_db, open_rc, "backup open dest"); + if (dst_db) sqlite3_close_v2(dst_db); + return Void::Result::fail(std::move(err)); + } + + struct CloseGuard { + sqlite3* d; + ~CloseGuard() { if (d) sqlite3_close_v2(d); } + } dst_guard{dst_db}; + + sqlite3_backup* backup = sqlite3_backup_init(dst_db, "main", m_conn->db, "main"); + if (backup == nullptr) { + return Void::Result::fail(sqlite_error_from_db(dst_db, sqlite3_errcode(dst_db), "backup_init")); + } + + BackupReport report; + int rc = SQLITE_OK; + for (;;) { + if (report.steps >= options.max_steps) { + sqlite3_backup_finish(backup); + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::timeout, "Sqlite: backup exceeded max_steps")); + } + rc = sqlite3_backup_step(backup, options.pages_per_step); + ++report.steps; + if (rc == SQLITE_OK) { + continue; + } + if (rc == SQLITE_BUSY || rc == SQLITE_LOCKED) { + if (options.step_sleep.count() > 0) { + std::this_thread::sleep_for(options.step_sleep); + } + continue; + } + break; + } + + report.total_pages = sqlite3_backup_pagecount(backup); + report.remaining_pages = sqlite3_backup_remaining(backup); + const int fin_rc = sqlite3_backup_finish(backup); + if (rc != SQLITE_DONE || fin_rc != SQLITE_OK) { + const int err_rc = (fin_rc != SQLITE_OK) ? fin_rc : rc; + return Void::Result::fail(sqlite_error_from_db(dst_db, err_rc, "backup_step")); + } + + // Sync destination explicitly. + (void)exec_raw_sql(dst_db, "PRAGMA synchronous=FULL", "backup sync"); + const int close_rc = sqlite3_close(dst_db); + dst_guard.d = nullptr; + if (close_rc != SQLITE_OK) { + return Void::Result::fail(sqlite_error_from_db(nullptr, close_rc, "backup close dest")); + } + return report; + } + + Result Database::restore_from( + const std::filesystem::path& source, + BackupOptions options) + { + if (!is_open()) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::closed, "Sqlite: restore_from on closed database")); + } + if (m_conn->caps.read_only) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::readonly, "Sqlite: cannot restore into read-only database")); + } + if (m_conn->active_transaction) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::misuse, "Sqlite: cannot restore while transaction is active")); + } + if (options.pages_per_step <= 0 || options.max_steps <= 0) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::invalid_argument, "Sqlite: BackupOptions bounds must be positive")); + } + std::error_code ec; + if (!std::filesystem::exists(source, ec)) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::not_found, + std::format("Sqlite: restore source '{}' does not exist", source.string()))); + } + if (!m_conn->caps.in_memory && + std::filesystem::equivalent(m_conn->path, source, ec)) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::invalid_argument, + "Sqlite: restore source cannot be the active target database")); + } + + sqlite3* src_db = nullptr; + const int open_rc = sqlite3_open_v2( + source.string().c_str(), + &src_db, + SQLITE_OPEN_READONLY | SQLITE_OPEN_FULLMUTEX, + nullptr); + if (open_rc != SQLITE_OK) { + Error err = sqlite_error_from_db(src_db, open_rc, "restore open source"); + if (src_db) sqlite3_close_v2(src_db); + return Void::Result::fail(std::move(err)); + } + + struct CloseGuard { + sqlite3* d; + ~CloseGuard() { if (d) sqlite3_close_v2(d); } + } src_guard{src_db}; + + sqlite3_backup* backup = sqlite3_backup_init(m_conn->db, "main", src_db, "main"); + if (backup == nullptr) { + return Void::Result::fail(sqlite_error_from_db(m_conn->db, sqlite3_errcode(m_conn->db), "restore_init")); + } + + BackupReport report; + int rc = SQLITE_OK; + for (;;) { + if (report.steps >= options.max_steps) { + sqlite3_backup_finish(backup); + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::timeout, "Sqlite: restore exceeded max_steps")); + } + rc = sqlite3_backup_step(backup, options.pages_per_step); + ++report.steps; + if (rc == SQLITE_OK) { + continue; + } + if (rc == SQLITE_BUSY || rc == SQLITE_LOCKED) { + if (options.step_sleep.count() > 0) { + std::this_thread::sleep_for(options.step_sleep); + } + continue; + } + break; + } + + report.total_pages = sqlite3_backup_pagecount(backup); + report.remaining_pages = sqlite3_backup_remaining(backup); + const int fin_rc = sqlite3_backup_finish(backup); + if (rc != SQLITE_DONE || fin_rc != SQLITE_OK) { + const int err_rc = (fin_rc != SQLITE_OK) ? fin_rc : rc; + return Void::Result::fail(sqlite_error_from_db(m_conn->db, err_rc, "restore_step")); + } + + const int close_rc = sqlite3_close(src_db); + src_guard.d = nullptr; + if (close_rc != SQLITE_OK) { + return Void::Result::fail(sqlite_error_from_db(nullptr, close_rc, "restore close source")); + } + return report; + } + + Result Database::create_scalar_function( + std::string name, + int num_args, + ScalarFunction fn, + bool deterministic) + { + if (!is_open()) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::closed, "Sqlite: create_scalar_function on closed database")); + } + if (name.empty() || !fn) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::invalid_argument, + "Sqlite: create_scalar_function requires non-empty name and callback")); + } + + auto box = std::make_unique(ScalarFunctionBox{std::move(fn)}); + int enc = SQLITE_UTF8; + if (deterministic) { + enc |= SQLITE_DETERMINISTIC; + } + const int rc = sqlite3_create_function_v2( + m_conn->db, + name.c_str(), + num_args, + enc, + box.get(), + &scalar_function_trampoline, + nullptr, + nullptr, + nullptr); + if (rc != SQLITE_OK) { + return Void::Result::fail(sqlite_error_from_db(m_conn->db, rc, "create_scalar_function")); + } + m_conn->scalar_functions.push_back(std::move(box)); + return {}; + } + + Result Database::set_authorizer(AuthorizerCallback cb) + { + if (!is_open()) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::closed, "Sqlite: set_authorizer on closed database")); + } + if (!cb) { + const int rc = sqlite3_set_authorizer(m_conn->db, nullptr, nullptr); + if (rc != SQLITE_OK) { + return Void::Result::fail(sqlite_error_from_db(m_conn->db, rc, "clear authorizer")); + } + m_conn->authorizer.reset(); + return {}; + } + auto box = std::make_unique(AuthorizerBox{std::move(cb)}); + const int rc = sqlite3_set_authorizer(m_conn->db, &authorizer_trampoline, box.get()); + if (rc != SQLITE_OK) { + return Void::Result::fail(sqlite_error_from_db(m_conn->db, rc, "set_authorizer")); + } + m_conn->authorizer = std::move(box); + return {}; + } + + sqlite3* Database::handle() const noexcept + { + return m_conn ? m_conn->db : nullptr; + } + + void Database::begin_leased_operation( + std::uint64_t generation, + int progress_steps, + std::function should_interrupt) + { + if (!m_conn || m_conn->db == nullptr) return; + m_conn->progress_predicate = + should_interrupt + ? std::make_shared>(std::move(should_interrupt)) + : nullptr; + if (progress_steps > 0 && m_conn->progress_predicate) { + sqlite3_progress_handler( + m_conn->db, + progress_steps, + &detail::progress_handler_trampoline, + m_conn.get()); + } else { + sqlite3_progress_handler(m_conn->db, 0, nullptr, nullptr); + } + std::lock_guard lk{m_conn->interrupt_mu}; + m_conn->active_op_gen = generation; + m_conn->cancel_requested.store(false, std::memory_order_release); + } + + void Database::interrupt_leased_operation(std::uint64_t generation) noexcept + { + if (!m_conn) return; + std::lock_guard lk{m_conn->interrupt_mu}; + if (m_conn->db != nullptr && m_conn->active_op_gen == generation && generation != 0) { + m_conn->cancel_requested.store(true, std::memory_order_release); + sqlite3_interrupt(m_conn->db); + } + } + + void Database::end_leased_operation(std::uint64_t generation) noexcept + { + if (!m_conn) return; + bool ended = false; + { + std::lock_guard lk{m_conn->interrupt_mu}; + if (m_conn->active_op_gen == generation) { + m_conn->active_op_gen = 0; + m_conn->cancel_requested.store(false, std::memory_order_release); + ended = true; + } + } + if (ended) { + if (m_conn->db != nullptr) { + sqlite3_progress_handler(m_conn->db, 0, nullptr, nullptr); + } + m_conn->progress_predicate.reset(); + } + } + } // namespace Void::Sqlite diff --git a/src/Sqlite/module.cmake b/src/Sqlite/module.cmake index 5619d20..ce29d6b 100644 --- a/src/Sqlite/module.cmake +++ b/src/Sqlite/module.cmake @@ -1,4 +1,5 @@ void_add_module(Sqlite - INTERNAL_DEPS Functional + INTERNAL_DEPS Functional Time EXTERNAL_DEPS SQLite3::SQLite3 + EXCLUDE_HEADERS Void/Sqlite/AsyncPool.hpp ) diff --git a/src/SqliteAsync/AsyncPool.cpp b/src/SqliteAsync/AsyncPool.cpp new file mode 100644 index 0000000..07b051a --- /dev/null +++ b/src/SqliteAsync/AsyncPool.cpp @@ -0,0 +1,461 @@ +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Sqlite +{ + struct AsyncPool::Impl : public std::enable_shared_from_this { + struct Job { + std::shared_ptr> op_state{}; + std::function(Database&)> fn{}; + std::size_t input_bytes{0}; + std::uint64_t generation{0}; + }; + + explicit Impl(AsyncPoolOptions opts, Void::Async::Executor* exec) + : options(std::move(opts)), + clock(options.clock ? options.clock + : &Void::Time::SystemMonotonicClock::instance()), + completion_executor(exec) + { + } + + ~Impl() + { + (void)close_and_join(); + } + + Result start() + { + if (options.path.empty()) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::invalid_argument, + "AsyncPool: database path must not be empty")); + } + if (options.reader_connections > 0 && + (options.path == ":memory:" || + options.path.string().starts_with("file::memory:"))) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::invalid_argument, + "AsyncPool: multi-connection pool does not support private :memory: paths")); + } + if (options.max_queued_jobs == 0 || options.max_pending_input_bytes == 0) { + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::invalid_argument, + "AsyncPool: max_queued_jobs and max_pending_input_bytes must be positive")); + } + if (auto v = validate_limits(options.open_options.limits); !v) { + return v; + } + + // Open writer first so the file and WAL mode are initialized before + // read-only connections open. + OpenOptions writer_opts = options.open_options; + if (writer_opts.mode == OpenMode::ReadOnly) { + writer_opts.mode = OpenMode::ReadWriteCreate; + } + auto wdb = Database::open_with_options(options.path, std::move(writer_opts)); + if (!wdb) { + return Void::Result::fail(std::move(wdb).error()); + } + writer_db = std::move(*wdb); + + readers.reserve(options.reader_connections); + for (std::size_t i = 0; i < options.reader_connections; ++i) { + OpenOptions ropts = options.open_options; + ropts.mode = OpenMode::ReadOnly; + auto rdb = Database::open_with_options(options.path, std::move(ropts)); + if (!rdb) { + (void)writer_db.close(); + for (auto& existing : readers) { + (void)existing.close(); + } + readers.clear(); + return Void::Result::fail(std::move(rdb).error()); + } + readers.push_back(std::move(*rdb)); + } + + writer_thread = std::thread([this]() { run_writer_loop(); }); + reader_threads.reserve(readers.size()); + for (std::size_t i = 0; i < readers.size(); ++i) { + reader_threads.emplace_back([this, i]() { run_reader_loop(i); }); + } + return {}; + } + + Void::Coro::Task> submit_erased( + bool is_write, + std::function(Database&)> fn, + Void::Async::OperationOptions op, + std::size_t input_bytes) + { + if (!fn) { + rejected_jobs.fetch_add(1, std::memory_order_relaxed); + co_return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::invalid_argument, + "AsyncPool: null work callback")); + } + if (is_write == false && readers.empty()) { + // Route read to writer lane when configured with 0 readers. + is_write = true; + } + if (op.stop.stop_requested()) { + cancelled_jobs.fetch_add(1, std::memory_order_relaxed); + co_return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::cancelled, + "AsyncPool: operation cancelled before admission")); + } + if (op.deadline.has_value() && clock->now() >= *op.deadline) { + cancelled_jobs.fetch_add(1, std::memory_order_relaxed); + co_return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::timeout, + "AsyncPool: operation deadline expired before admission")); + } + + auto state = Void::Async::OperationState::create( + op, completion_executor, Void::Async::StopBehavior::notify_only); + + Job job; + job.op_state = state; + job.fn = std::move(fn); + job.input_bytes = input_bytes; + + { + std::lock_guard lk{mu}; + if (closing || closed) { + rejected_jobs.fetch_add(1, std::memory_order_relaxed); + co_return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::closed, + "AsyncPool: pool is closing")); + } + const std::size_t total_queued = write_queue.size() + read_queue.size(); + if (total_queued >= options.max_queued_jobs || + input_bytes > options.max_pending_input_bytes || + pending_input_bytes > options.max_pending_input_bytes - input_bytes) { + rejected_jobs.fetch_add(1, std::memory_order_relaxed); + co_return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::overloaded, + "AsyncPool: queue depth or pending input byte budget exceeded")); + } + job.generation = ++next_generation; + pending_input_bytes += input_bytes; + state->acquire_backend_ref(); + if (is_write) { + write_queue.push_back(std::move(job)); + } else { + read_queue.push_back(std::move(job)); + } + } + + if (is_write) { + write_cv.notify_one(); + } else { + read_cv.notify_one(); + } + + auto res = co_await state->awaitable(completion_executor); + co_return res; + } + + void execute_job(Database& db, Job& job) + { + auto& state = job.op_state; + if (state->stop_requested()) { + cancelled_jobs.fetch_add(1, std::memory_order_relaxed); + if (auto t = state->try_commit_error(make_sqlite_error( + SqliteErrorCode::cancelled, + "AsyncPool: operation cancelled before execution")); + t) { + t->dispatch(); + } + state->release_backend_ref_and_dispatch(); + return; + } + if (state->is_deadline_expired(*clock)) { + cancelled_jobs.fetch_add(1, std::memory_order_relaxed); + if (auto t = state->try_commit_error(make_sqlite_error( + SqliteErrorCode::timeout, + "AsyncPool: operation deadline expired before execution")); + t) { + t->dispatch(); + } + state->release_backend_ref_and_dispatch(); + return; + } + + const auto gen = job.generation; + const int steps = std::max(1, options.progress_handler_steps); + db.begin_leased_operation( + gen, + steps, + [state, clk = this->clock]() { + return state->stop_requested() || state->is_deadline_expired(*clk); + }); + + struct StopInterrupter { + Database* target_db{nullptr}; + std::uint64_t target_gen{0}; + void operator()() const noexcept + { + if (target_db != nullptr) { + target_db->interrupt_leased_operation(target_gen); + } + } + }; + // Registered before job.fn runs and destroyed BEFORE end_leased_operation, + // so stop callbacks never race with subsequent borrowers. + Result exec_result; + { + std::optional> stop_cb; + const auto st = state->stop_token(); + if (st.stop_possible()) { + stop_cb.emplace(st, StopInterrupter{&db, gen}); + } + exec_result = job.fn(db); + } + db.end_leased_operation(gen); + + std::optional ticket; + if (exec_result) { + completed_jobs.fetch_add(1, std::memory_order_relaxed); + ticket = state->try_commit_value(); + } else { + const auto kind = exec_result.error().kind(); + if (kind == Void::Result::ErrorKind::cancelled || + kind == Void::Result::ErrorKind::timeout) { + cancelled_jobs.fetch_add(1, std::memory_order_relaxed); + } + // Reclassify SQLITE_INTERRUPT when caused by deadline expiry. + if (kind == Void::Result::ErrorKind::cancelled && + !state->stop_requested() && + state->is_deadline_expired(*clock)) { + ticket = state->try_commit_error(make_sqlite_error( + SqliteErrorCode::timeout, + "AsyncPool: operation interrupted due to deadline expiry")); + } else { + ticket = state->try_commit_error(std::move(exec_result).error()); + } + } + if (ticket) { + ticket->dispatch(); + } + state->release_backend_ref_and_dispatch(); + } + + void run_writer_loop() + { + for (;;) { + Job job; + { + std::unique_lock lk{mu}; + write_cv.wait(lk, [this]() { + return !write_queue.empty() || closing; + }); + if (write_queue.empty() && closing) { + return; + } + job = std::move(write_queue.front()); + write_queue.pop_front(); + pending_input_bytes -= job.input_bytes; + ++active_write_jobs; + } + + execute_job(writer_db, job); + + { + std::lock_guard lk{mu}; + --active_write_jobs; + } + } + } + + void run_reader_loop(std::size_t idx) + { + for (;;) { + Job job; + { + std::unique_lock lk{mu}; + read_cv.wait(lk, [this]() { + return !read_queue.empty() || closing; + }); + if (read_queue.empty() && closing) { + return; + } + job = std::move(read_queue.front()); + read_queue.pop_front(); + pending_input_bytes -= job.input_bytes; + ++active_read_jobs; + } + + execute_job(readers[idx], job); + + { + std::lock_guard lk{mu}; + --active_read_jobs; + } + } + } + + Result close_and_join() + { + { + std::lock_guard lk{mu}; + if (closed) { + return {}; + } + closing = true; + } + write_cv.notify_all(); + read_cv.notify_all(); + + if (writer_thread.joinable()) { + writer_thread.join(); + } + for (auto& t : reader_threads) { + if (t.joinable()) { + t.join(); + } + } + reader_threads.clear(); + + std::optional first_err; + if (writer_db.is_open()) { + if (auto r = writer_db.close(); !r && !first_err) { + first_err = std::move(r).error(); + } + } + for (auto& rdb : readers) { + if (rdb.is_open()) { + if (auto r = rdb.close(); !r && !first_err) { + first_err = std::move(r).error(); + } + } + } + readers.clear(); + + { + std::lock_guard lk{mu}; + closed = true; + } + if (first_err) { + return Void::Result::fail(std::move(*first_err)); + } + return {}; + } + + AsyncPoolOptions options; + const Void::Time::MonotonicClock* clock; + Void::Async::Executor* completion_executor{nullptr}; + + Database writer_db{}; + std::vector readers{}; + + mutable std::mutex mu{}; + std::condition_variable write_cv{}; + std::condition_variable read_cv{}; + std::deque write_queue{}; + std::deque read_queue{}; + std::size_t pending_input_bytes{0}; + std::size_t active_read_jobs{0}; + std::size_t active_write_jobs{0}; + std::uint64_t next_generation{0}; + bool closing{false}; + bool closed{false}; + + std::atomic completed_jobs{0}; + std::atomic rejected_jobs{0}; + std::atomic cancelled_jobs{0}; + + std::thread writer_thread{}; + std::vector reader_threads{}; + }; + + AsyncPool::AsyncPool(std::shared_ptr impl) noexcept + : m_impl(std::move(impl)) + { + } + + AsyncPool::~AsyncPool() + { + if (m_impl) { + (void)m_impl->close_and_join(); + } + } + + AsyncPool::AsyncPool(AsyncPool&&) noexcept = default; + AsyncPool& AsyncPool::operator=(AsyncPool&&) noexcept = default; + + Result AsyncPool::open( + AsyncPoolOptions options, + Void::Async::Executor* completion_executor) + { + auto impl = std::make_shared(std::move(options), completion_executor); + if (auto r = impl->start(); !r) { + return Void::Result::fail(std::move(r).error()); + } + return AsyncPool{std::move(impl)}; + } + + Void::Coro::Task> AsyncPool::submit_erased( + bool is_write, + std::function(Database&)> fn, + Void::Async::OperationOptions op, + std::size_t input_bytes) + { + if (!m_impl) { + co_return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::closed, "AsyncPool: moved-from pool")); + } + co_return co_await m_impl->submit_erased( + is_write, std::move(fn), std::move(op), input_bytes); + } + + Void::Coro::Task> AsyncPool::run_read_void( + std::function(Database&)> fn, + Void::Async::OperationOptions op, + std::size_t input_bytes) + { + co_return co_await submit_erased(false, std::move(fn), std::move(op), input_bytes); + } + + Void::Coro::Task> AsyncPool::run_write_void( + std::function(Database&)> fn, + Void::Async::OperationOptions op, + std::size_t input_bytes) + { + co_return co_await submit_erased(true, std::move(fn), std::move(op), input_bytes); + } + + AsyncPoolStats AsyncPool::stats() const noexcept + { + AsyncPoolStats out; + if (!m_impl) return out; + std::lock_guard lk{m_impl->mu}; + out.reader_connections = m_impl->readers.size(); + out.queued_read_jobs = m_impl->read_queue.size(); + out.queued_write_jobs = m_impl->write_queue.size(); + out.active_read_jobs = m_impl->active_read_jobs; + out.active_write_jobs = m_impl->active_write_jobs; + out.pending_input_bytes = m_impl->pending_input_bytes; + out.completed_jobs = m_impl->completed_jobs.load(std::memory_order_relaxed); + out.rejected_jobs = m_impl->rejected_jobs.load(std::memory_order_relaxed); + out.cancelled_jobs = m_impl->cancelled_jobs.load(std::memory_order_relaxed); + return out; + } + + Result AsyncPool::close_and_join() + { + if (!m_impl) return {}; + return m_impl->close_and_join(); + } + +} // namespace Void::Sqlite diff --git a/src/SqliteAsync/module.cmake b/src/SqliteAsync/module.cmake new file mode 100644 index 0000000..e8b106b --- /dev/null +++ b/src/SqliteAsync/module.cmake @@ -0,0 +1,4 @@ +void_add_module(SqliteAsync + INTERNAL_DEPS Sqlite Async Time Functional + EXTRA_HEADERS Void/Sqlite/AsyncPool.hpp +) 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/CMakeLists.txt b/tests/CMakeLists.txt index 8d6e724..458d156 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -133,6 +133,9 @@ if(_all_generated) if(TARGET OpenSSL::Crypto) target_link_libraries(VoidTests PRIVATE OpenSSL::Crypto) endif() + if(TARGET SQLite3::SQLite3) + target_link_libraries(VoidTests PRIVATE SQLite3::SQLite3) + endif() add_test(NAME VoidTests COMMAND VoidTests) diff --git a/tests/package/InstalledComponents.cmake b/tests/package/InstalledComponents.cmake index dc26c00..a580065 100644 --- a/tests/package/InstalledComponents.cmake +++ b/tests/package/InstalledComponents.cmake @@ -214,6 +214,29 @@ if(_has_update) -DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE) endif() +has_modules(_has_sqlite Sqlite Functional Time) +if(_has_sqlite) + run_consumer(SqliteOnly "${install_prefix}" "SqliteOnly" + -DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE) +endif() + +has_modules(_has_sqlite_async SqliteAsync Sqlite Async Time Functional LogState) +if(_has_sqlite_async) + run_consumer(SqliteAsyncOnly "${install_prefix}" "SqliteAsyncOnly" + -DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE + -DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE + -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/SqliteAsyncOnly/CMakeLists.txt b/tests/package/SqliteAsyncOnly/CMakeLists.txt new file mode 100644 index 0000000..09e6229 --- /dev/null +++ b/tests/package/SqliteAsyncOnly/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidSqliteAsyncOnlyConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS SqliteAsync) + +add_executable(void_sqlite_async_only_consumer main.cpp) +target_link_libraries(void_sqlite_async_only_consumer PRIVATE Void::SqliteAsync) +target_compile_features(void_sqlite_async_only_consumer PRIVATE cxx_std_26) + +enable_testing() +add_test(NAME SqliteAsyncOnlyConsumer COMMAND void_sqlite_async_only_consumer) diff --git a/tests/package/SqliteAsyncOnly/main.cpp b/tests/package/SqliteAsyncOnly/main.cpp new file mode 100644 index 0000000..2ab913a --- /dev/null +++ b/tests/package/SqliteAsyncOnly/main.cpp @@ -0,0 +1,24 @@ +#include + +#include +#include +#include +#include + +int main() +{ + const auto dir = std::filesystem::temp_directory_path() / + ("void-sqlite-async-pkg-" + std::to_string(::getpid())); + std::error_code ec; + std::filesystem::remove_all(dir, ec); + std::filesystem::create_directories(dir, ec); + + Void::Sqlite::AsyncPoolOptions opts; + opts.path = dir / "pkg.db"; + opts.reader_connections = 2; + auto pool = Void::Sqlite::AsyncPool::open(opts); + const bool ok = pool.has_value() && pool->stats().reader_connections == 2 && + pool->close_and_join().has_value(); + std::filesystem::remove_all(dir, ec); + return ok ? 0 : 1; +} diff --git a/tests/package/SqliteOnly/CMakeLists.txt b/tests/package/SqliteOnly/CMakeLists.txt new file mode 100644 index 0000000..bbd0c3e --- /dev/null +++ b/tests/package/SqliteOnly/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidSqliteOnlyConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS Sqlite) + +add_executable(void_sqlite_only_consumer main.cpp) +target_link_libraries(void_sqlite_only_consumer PRIVATE Void::Sqlite) +target_compile_features(void_sqlite_only_consumer PRIVATE cxx_std_26) + +enable_testing() +add_test(NAME SqliteOnlyConsumer COMMAND void_sqlite_only_consumer) diff --git a/tests/package/SqliteOnly/main.cpp b/tests/package/SqliteOnly/main.cpp new file mode 100644 index 0000000..f147346 --- /dev/null +++ b/tests/package/SqliteOnly/main.cpp @@ -0,0 +1,19 @@ +#include + +int main() +{ + Void::Sqlite::OpenOptions opts; + auto db = Void::Sqlite::open_database(":memory:", opts); + if (!db) return 1; + if (!db->exec("CREATE TABLE t(id INTEGER PRIMARY KEY)").has_value()) return 2; + auto tx = db->begin(Void::Sqlite::BeginMode::Immediate); + if (!tx) return 3; + auto st = db->prepare("INSERT INTO t(id) VALUES(?)"); + if (!st) return 4; + if (!st->bind_checked(1, Void::Sqlite::ValueView{7}).has_value()) return 5; + if (!st->step().has_value()) return 6; + if (!st->finalize_checked().has_value()) return 7; + if (!tx->commit().has_value()) return 8; + if (!db->close().has_value()) return 9; + return 0; +} 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/Sqlite/SqliteHardening.cpp b/tests/standalone/Sqlite/SqliteHardening.cpp new file mode 100644 index 0000000..dc63a9e --- /dev/null +++ b/tests/standalone/Sqlite/SqliteHardening.cpp @@ -0,0 +1,469 @@ +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + using namespace Void::Sqlite; + + struct TempSqliteDir { + std::filesystem::path path; + TempSqliteDir() + { + static std::atomic seq{0}; + const auto id = seq.fetch_add(1, std::memory_order_relaxed); + path = std::filesystem::temp_directory_path() / + ("void-sqlite-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); + } + ~TempSqliteDir() + { + std::error_code ec; + std::filesystem::remove_all(path, ec); + } + }; + +Void::Testing::Test sqlite_connection_state_lifetime_close_and_statement_limits() + { + TempSqliteDir dir; + const auto db_path = dir.path / "state.db"; + + std::vector diagnostics; + OpenOptions opts; + opts.journal_mode = JournalMode::Wal; + opts.sync_mode = SyncMode::Full; + opts.foreign_keys = true; + opts.limits.max_live_statements = 2; + opts.limits.max_sql_bytes = 256; + opts.limits.max_value_bytes = 64; + opts.diagnostic_hook = [&](std::string_view msg) { diagnostics.emplace_back(msg); }; + + auto db_res = open_database(db_path, opts); + Void::Testing::require(db_res.has_value()); + auto db = std::move(*db_res); + + const auto caps = db.capabilities(); + Void::Testing::expect(!caps.in_memory); + Void::Testing::expect(!caps.read_only); + Void::Testing::expect_eq(caps.journal_mode, std::string{"wal"}); + Void::Testing::expect_eq(caps.synchronous_mode, 2); + Void::Testing::expect(caps.foreign_keys); + Void::Testing::expect(!caps.extension_loading_enabled); + + // load_extension is disabled by default. + Void::Testing::expect(!db.exec("SELECT load_extension('nonexistent')").has_value()); + + Void::Testing::require(db.exec("CREATE TABLE t(id INTEGER PRIMARY KEY, val TEXT)").has_value()); + + // Prepare rejects trailing SQL and SQL exceeding max_sql_bytes. + auto trailing = db.prepare("SELECT 1; SELECT 2"); + Void::Testing::expect(!trailing.has_value()); + Void::Testing::expect(trailing.error().code().value == + static_cast(SqliteErrorCode::trailing_sql)); + + const std::string too_long_sql(300, ' '); + auto oversized = db.prepare("SELECT 1" + too_long_sql); + Void::Testing::expect(!oversized.has_value()); + Void::Testing::expect(oversized.error().code().value == + static_cast(SqliteErrorCode::size_limit)); + + // Move Database and destroy original while Transaction + Statement remain alive! + auto tx = db.begin(BeginMode::Immediate); + Void::Testing::require(tx.has_value()); + auto s1 = db.prepare("INSERT INTO t(id, val) VALUES(?, ?)"); + Void::Testing::require(s1.has_value()); + + // Statement limit enforcement. + auto s2 = db.prepare("SELECT COUNT(*) FROM t"); + Void::Testing::require(s2.has_value()); + auto s3 = db.prepare("SELECT 1"); + Void::Testing::expect(!s3.has_value()); + Void::Testing::expect(s3.error().code().value == + static_cast(SqliteErrorCode::statement_limit)); + + Database moved_db{std::move(db)}; + // Old moved-from handle has no connection; new handle owns it, and close() + // refuses while s1, s2, tx are live! + auto busy_close = moved_db.close(); + Void::Testing::expect(!busy_close.has_value()); + Void::Testing::expect(busy_close.error().code().value == + static_cast(SqliteErrorCode::busy)); + + Void::Testing::require(s1->bind_checked(1, ValueView{42}).has_value()); + Void::Testing::require(s1->bind_checked(2, ValueView{"survived_move"}).has_value()); + Void::Testing::require(s1->step().has_value()); + Void::Testing::require(s1->finalize_checked().has_value()); + Void::Testing::require(s2->finalize_checked().has_value()); + Void::Testing::require(tx->commit().has_value()); + Void::Testing::expect(tx->state() == TransactionState::Committed); + + // Injected close error test, followed by real clean close. + { + ScopedFaultGuard guard{FaultConfig{.fail_next_close_rc = SQLITE_IOERR}}; + auto fail_close = moved_db.close(); + Void::Testing::expect(!fail_close.has_value()); + Void::Testing::expect(fail_close.error().kind() == Void::Result::ErrorKind::io); + } + Void::Testing::require(moved_db.close().has_value()); + Void::Testing::expect(!moved_db.is_open()); + + // Reopen to confirm persistence on disk after move + commit. + auto reopened = open_database(db_path, opts); + Void::Testing::require(reopened.has_value()); + auto sel = reopened->prepare("SELECT val FROM t WHERE id=42"); + Void::Testing::require(sel.has_value()); + auto has = sel->step(); + Void::Testing::require(has.has_value() && *has); + Void::Testing::expect_eq(*sel->try_column_text(0), std::string{"survived_move"}); + } + +Void::Testing::Test sqlite_checked_binds_borrowed_owners_typed_rows_and_query_all() + { + OpenOptions opts; + opts.limits.max_value_bytes = 32; + opts.limits.max_query_all_rows = 3; + auto db_res = open_database(":memory:", opts); + Void::Testing::require(db_res.has_value()); + auto& db = *db_res; + + Void::Testing::require( + db.exec("CREATE TABLE items(id INTEGER, r REAL, txt TEXT, bin BLOB)").has_value()); + + auto ins = db.prepare( + "INSERT INTO items(id, r, txt, bin) VALUES(:id, :r, :txt, :bin)"); + Void::Testing::require(ins.has_value()); + Void::Testing::expect_eq(ins->bind_parameter_count(), 4); + + // Out of range & missing named param + auto bad_idx = ins->bind_checked(5, ValueView{1}); + Void::Testing::expect(!bad_idx.has_value()); + Void::Testing::expect(bad_idx.error().code().value == + static_cast(SqliteErrorCode::range)); + auto bad_name = ins->bind_checked(":missing", ValueView{1}); + Void::Testing::expect(!bad_name.has_value()); + Void::Testing::expect(bad_name.error().code().value == + static_cast(SqliteErrorCode::not_found)); + + // Oversized value fails before bind + const std::string huge(100, 'x'); + auto too_big = ins->bind_checked(":txt", ValueView{huge}); + Void::Testing::expect(!too_big.has_value()); + Void::Testing::expect(too_big.error().code().value == + static_cast(SqliteErrorCode::size_limit)); + + // Row 1: INT64_MIN, double, embedded NUL text via borrowed owner, empty blob + auto borrowed_str = std::make_shared(std::string_view{"ab\0cd", 5}); + const std::string_view borrowed_view{borrowed_str->data(), borrowed_str->size()}; + const std::vector empty_blob{}; + + Void::Testing::require(ins->bind_checked(":id", ValueView{std::numeric_limits::min()}).has_value()); + Void::Testing::require(ins->bind_checked(":r", ValueView{3.25}).has_value()); + Void::Testing::require(ins->bind_borrowed_text(3, borrowed_view, borrowed_str).has_value()); + Void::Testing::require(ins->bind_checked(":bin", ValueView{std::span{empty_blob}}).has_value()); + // Drop caller's shared_ptr — Statement retains borrowed_str safely until clear/finalize! + const std::weak_ptr weak_owner = borrowed_str; + borrowed_str.reset(); + Void::Testing::expect(!weak_owner.expired()); + + auto step1 = ins->step(); + Void::Testing::require(step1.has_value() && !*step1); + Void::Testing::require(ins->reset_checked().has_value()); + // Still alive after reset because SQLite retains SQLITE_STATIC until clear_bindings/finalize! + Void::Testing::expect(!weak_owner.expired()); + Void::Testing::require(ins->clear_bindings_checked().has_value()); + Void::Testing::expect(weak_owner.expired()); + + // Row 2: numeric string "123", INT64_MAX, NULL blob + Void::Testing::require(ins->bind_checked(1, ValueView{std::numeric_limits::max()}).has_value()); + Void::Testing::require(ins->bind_checked(2, ValueView{nullptr}).has_value()); + Void::Testing::require(ins->bind_checked(3, ValueView{"123"}).has_value()); + Void::Testing::require(ins->bind_checked(4, ValueView{nullptr}).has_value()); + Void::Testing::require(ins->step().has_value()); + + auto sel = db.prepare("SELECT id, r, txt, bin FROM items ORDER BY id ASC"); + Void::Testing::require(sel.has_value()); + + auto has1 = sel->step(); + Void::Testing::require(has1.has_value() && *has1); + auto rv1 = sel->current_row(); + Void::Testing::require(rv1.has_value() && rv1->is_valid()); + Void::Testing::expect_eq(*rv1->get_int(0), std::numeric_limits::min()); + Void::Testing::expect(*rv1->get_double(1) == 3.25); + const std::string got_nul_txt = *rv1->get_text(2); + Void::Testing::expect_eq(got_nul_txt.size(), static_cast(5)); + Void::Testing::expect_eq(got_nul_txt[2], '\0'); + auto ct_blob = rv1->column_type(3); + Void::Testing::require(ct_blob.has_value() && *ct_blob == ColumnType::Blob); + Void::Testing::expect(rv1->get_blob(3)->empty()); + + auto has2 = sel->step(); + Void::Testing::require(has2.has_value() && *has2); + // rv1 expired at next step! + Void::Testing::expect(!rv1->is_valid()); + Void::Testing::expect(!rv1->get_int(0).has_value()); + + // Typed reads reject coercion ("123" is TEXT, not INTEGER!). + Void::Testing::expect_eq(*sel->try_column_int(0), std::numeric_limits::max()); + Void::Testing::expect(!sel->try_column_optional_double(1)->has_value()); + auto bad_coercion = sel->try_column_int(2); + Void::Testing::expect(!bad_coercion.has_value()); + Void::Testing::expect(bad_coercion.error().code().value == + static_cast(SqliteErrorCode::type_mismatch)); + Void::Testing::expect(!sel->try_column_optional_blob(3)->has_value()); + + // query_all row cap + for (int i = 0; i < 4; ++i) { + Void::Testing::require(db.exec("INSERT INTO items(id, txt) VALUES(1, 'z')").has_value()); + } + auto all_q = db.prepare("SELECT id, txt FROM items"); + Void::Testing::require(all_q.has_value()); + auto over_rows = db.query_all(*all_q, 3, 4096); + Void::Testing::expect(!over_rows.has_value()); + Void::Testing::expect(over_rows.error().code().value == + static_cast(SqliteErrorCode::size_limit)); + } + +Void::Testing::Test sqlite_transactions_busy_commit_savepoints_and_checked_migrations() + { + TempSqliteDir dir; + const auto db_path = dir.path / "tx.db"; + + OpenOptions opts; + opts.limits.busy_timeout = std::chrono::milliseconds{20}; + auto db1_r = open_database(db_path, opts); + Void::Testing::require(db1_r.has_value()); + auto& db1 = *db1_r; + Void::Testing::require(db1.exec("CREATE TABLE t(k INTEGER PRIMARY KEY, v TEXT)").has_value()); + + // Real two-connection BUSY test + auto db2_r = open_database(db_path, opts); + Void::Testing::require(db2_r.has_value()); + auto& db2 = *db2_r; + { + auto tx1 = db1.begin(BeginMode::Immediate); + Void::Testing::require(tx1.has_value()); + Void::Testing::require(db1.exec("INSERT INTO t VALUES(1, 'holder')").has_value()); + + auto tx2_busy = db2.begin(BeginMode::Immediate); + Void::Testing::expect(!tx2_busy.has_value()); + Void::Testing::expect(tx2_busy.error().code().value == + static_cast(SqliteErrorCode::busy)); + Void::Testing::require(tx1->commit().has_value()); + } + + // Faulted COMMIT leaving autocommit==0 keeps Transaction active for retry/rollback! + { + auto tx = db1.begin(BeginMode::Immediate); + Void::Testing::require(tx.has_value()); + Void::Testing::require(db1.exec("INSERT INTO t VALUES(2, 'retried')").has_value()); + // Nested begin is rejected. + auto nested = db1.begin(); + Void::Testing::expect(!nested.has_value()); + Void::Testing::expect(nested.error().code().value == + static_cast(SqliteErrorCode::misuse)); + + { + ScopedFaultGuard guard{FaultConfig{ + .fail_next_commit_rc = SQLITE_BUSY, + .auto_rollback_on_faulted_commit = false}}; + auto failed_commit = tx->commit(); + Void::Testing::expect(!failed_commit.has_value()); + Void::Testing::expect(failed_commit.error().code().value == + static_cast(SqliteErrorCode::busy)); + Void::Testing::expect(tx->state() == TransactionState::Active); + Void::Testing::expect(sqlite3_get_autocommit(db1.handle()) == 0); + } + // Now retry commit succeeds! + Void::Testing::require(tx->commit().has_value()); + Void::Testing::expect(tx->state() == TransactionState::Committed); + } + + // Faulted COMMIT with auto-rollback transitions to RolledBack properly! + { + auto tx = db1.begin(BeginMode::Immediate); + Void::Testing::require(tx.has_value()); + Void::Testing::require(db1.exec("INSERT INTO t VALUES(3, 'rolled')").has_value()); + { + ScopedFaultGuard guard{FaultConfig{ + .fail_next_commit_rc = SQLITE_FULL, + .auto_rollback_on_faulted_commit = true}}; + auto failed_commit = tx->commit(); + Void::Testing::expect(!failed_commit.has_value()); + Void::Testing::expect(tx->state() == TransactionState::RolledBack); + } + } + + // Savepoint rollback_to + release + { + auto tx = db1.begin(BeginMode::Immediate); + Void::Testing::require(tx.has_value()); + Void::Testing::require(db1.exec("INSERT INTO t VALUES(10, 'kept')").has_value()); + { + auto sp = db1.savepoint("inner_sp"); + Void::Testing::require(sp.has_value()); + Void::Testing::require(db1.exec("INSERT INTO t VALUES(11, 'undone')").has_value()); + Void::Testing::require(sp->rollback_and_release().has_value()); + } + Void::Testing::require(tx->commit().has_value()); + } + + auto cnt = db1.prepare("SELECT COUNT(*) FROM t WHERE k IN (1, 2, 10, 11)"); + Void::Testing::require(cnt.has_value() && *cnt->step()); + Void::Testing::expect_eq(*cnt->try_column_int(0), static_cast(3)); + + // Checked migrations: invalid order rejected before mutation, checksum drift rejected! + const auto mig_db_path = dir.path / "mig.db"; + auto mdb_r = open_database(mig_db_path); + Void::Testing::require(mdb_r.has_value()); + auto& mdb = *mdb_r; + + const std::array bad_order{{ + {2, "v2", "sum2", "CREATE TABLE x(id INTEGER)"}, + {2, "v2b", "sum2b", "CREATE TABLE y(id INTEGER)"}, + }}; + Void::Testing::expect(!mdb.migrate_checked(bad_order).has_value()); + Void::Testing::expect_eq(*mdb.user_version(), 0); + + const std::array good_migs{{ + {1, "init_x", "sha256:aaa", "CREATE TABLE x(id INTEGER PRIMARY KEY)"}, + {2, "add_name", "sha256:bbb", "ALTER TABLE x ADD COLUMN name TEXT"}, + }}; + Void::Testing::require(mdb.migrate_checked(good_migs).has_value()); + Void::Testing::expect_eq(*mdb.user_version(), 2); + + // Checksum drift must fail without mutating. + const std::array drifted{{ + {1, "init_x", "sha256:TAMPERED", "CREATE TABLE x(id INTEGER PRIMARY KEY)"}, + {2, "add_name", "sha256:bbb", "ALTER TABLE x ADD COLUMN name TEXT"}, + }}; + auto drift_res = mdb.migrate_checked(drifted); + Void::Testing::expect(!drift_res.has_value()); + Void::Testing::expect(drift_res.error().code().value == + static_cast(SqliteErrorCode::migration_error)); + + // Unexpected newer schema (only supplying v1 when DB is at v2) rejected. + const std::array older_plan{{good_migs[0]}}; + Void::Testing::expect(!mdb.migrate_checked(older_plan).has_value()); + } + +Void::Testing::Test sqlite_checkpoint_wal_admission_backup_restore_and_safe_callbacks() + { + TempSqliteDir dir; + const auto db_path = dir.path / "ops.db"; + const auto backup_path = dir.path / "backup.db"; + + OpenOptions wopts; + wopts.limits.busy_timeout = std::chrono::milliseconds{20}; + wopts.limits.wal_checkpoint_threshold_bytes = 4096; + wopts.limits.wal_warn_threshold_bytes = 8192; + wopts.limits.wal_stop_writes_threshold_bytes = 16384; + + auto writer_r = open_database(db_path, wopts); + Void::Testing::require(writer_r.has_value()); + auto& writer = *writer_r; + Void::Testing::require(writer.exec("CREATE TABLE logs(id INTEGER PRIMARY KEY, payload TEXT)").has_value()); + Void::Testing::require(writer.exec("INSERT INTO logs VALUES(1, 'seed')").has_value()); + + // Open a long-lived reader transaction that pins the old snapshot so WAL + // cannot truncate past it! + OpenOptions ropts; + ropts.mode = OpenMode::ReadOnly; + auto reader_r = open_database(db_path, ropts); + Void::Testing::require(reader_r.has_value()); + auto rtx = reader_r->begin(BeginMode::Deferred); + Void::Testing::require(rtx.has_value()); + { + auto rsel = reader_r->prepare("SELECT COUNT(*) FROM logs"); + Void::Testing::require(rsel.has_value() && *rsel->step()); + } + + // Write > 16 KiB across commits to push WAL past wal_stop_writes_threshold_bytes. + { + auto tx = writer.begin(BeginMode::Immediate); + Void::Testing::require(tx.has_value()); + auto ins = writer.prepare("INSERT INTO logs(payload) VALUES(?)"); + Void::Testing::require(ins.has_value()); + const std::string blob(1024, 'W'); + for (int i = 0; i < 40; ++i) { + Void::Testing::require(ins->bind_checked(1, ValueView{blob}).has_value()); + Void::Testing::require(ins->step().has_value()); + Void::Testing::require(ins->reset_checked().has_value()); + } + Void::Testing::require(tx->commit().has_value()); + } + + // While reader holds snapshot, FULL/TRUNCATE checkpoint reports busy! + auto blocked_ckpt = writer.checkpoint(CheckpointMode::Truncate); + Void::Testing::require(blocked_ckpt.has_value()); + Void::Testing::expect(blocked_ckpt->busy); + + const auto h1 = writer.health(); + Void::Testing::expect(h1.wal_write_admission_blocked); + + auto rejected_begin = writer.begin(BeginMode::Immediate); + Void::Testing::expect(!rejected_begin.has_value()); + Void::Testing::expect(rejected_begin.error().code().value == + static_cast(SqliteErrorCode::overloaded)); + + // Backup while reader+writer active still copies consistent committed state. + auto bkup = writer.backup_to(backup_path); + Void::Testing::require(bkup.has_value()); + Void::Testing::expect_eq(bkup->remaining_pages, 0); + + // Release reader snapshot and truncate checkpoint -> unblocks write admission! + Void::Testing::require(rtx->commit().has_value()); + auto ok_ckpt = writer.checkpoint(CheckpointMode::Truncate); + Void::Testing::require(ok_ckpt.has_value()); + Void::Testing::expect(!writer.health().wal_write_admission_blocked); + + auto unblocked_tx = writer.begin(BeginMode::Immediate); + Void::Testing::require(unblocked_tx.has_value()); + Void::Testing::require(writer.exec("INSERT INTO logs(payload) VALUES('after_ckpt')").has_value()); + Void::Testing::require(unblocked_tx->commit().has_value()); + + // Restore from earlier backup into another DB and verify count matches 41! + const auto restored_path = dir.path / "restored.db"; + auto restored_r = open_database(restored_path); + Void::Testing::require(restored_r.has_value()); + Void::Testing::require(restored_r->restore_from(backup_path).has_value()); + auto rcnt = restored_r->prepare("SELECT COUNT(*) FROM logs"); + Void::Testing::require(rcnt.has_value() && *rcnt->step()); + Void::Testing::expect_eq(*rcnt->try_column_int(0), static_cast(41)); + + // Throwing scalar function & authorizer never unwind across SQLite C frames. + Void::Testing::require(writer.create_scalar_function( + "boom_fn", 0, + [](std::span) -> Result { + throw std::runtime_error{"boom"}; + }).has_value()); + auto boom = writer.prepare("SELECT boom_fn()"); + Void::Testing::require(boom.has_value()); + auto boom_step = boom->step(); + Void::Testing::expect(!boom_step.has_value()); + + Void::Testing::require(writer.set_authorizer( + [](int action, std::string_view arg1, std::string_view, std::string_view, std::string_view) { + if (action == SQLITE_DROP_TABLE || arg1 == "blocked_tbl") { + throw std::runtime_error{"auth boom converts to deny"}; + } + return AuthorizerDecision::Allow; + }).has_value()); + Void::Testing::expect(!writer.exec("DROP TABLE logs").has_value()); + } +} // namespace diff --git a/tests/standalone/SqliteAsync/SqliteAsync.cpp b/tests/standalone/SqliteAsync/SqliteAsync.cpp new file mode 100644 index 0000000..5d38a62 --- /dev/null +++ b/tests/standalone/SqliteAsync/SqliteAsync.cpp @@ -0,0 +1,250 @@ +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + using namespace Void::Sqlite; + + struct TempPoolDir { + std::filesystem::path path; + TempPoolDir() + { + static std::atomic seq{0}; + const auto id = seq.fetch_add(1, std::memory_order_relaxed); + path = std::filesystem::temp_directory_path() / + ("void-sqlite-async-" + std::to_string(::getpid()) + "-" + std::to_string(id)); + std::error_code ec; + std::filesystem::remove_all(path, ec); + std::filesystem::create_directories(path, ec); + } + ~TempPoolDir() + { + std::error_code ec; + std::filesystem::remove_all(path, ec); + } + }; + + Void::Coro::Task run_pool_crud_and_backpressure( + AsyncPool& pool, + Void::Async::ManualExecutor& exec) + { + (void)exec; + auto init = co_await pool.run_write_void([](Database& db) { + return db.exec("CREATE TABLE kv(k INTEGER PRIMARY KEY, v TEXT)"); + }); + Void::Testing::require(init.has_value()); + + // Write transaction commit + auto tx_ok = co_await pool.run_write_transaction( + BeginMode::Immediate, + [](Database& db, Transaction&) -> Result { + auto r1 = db.exec("INSERT INTO kv VALUES(1, 'one')"); + if (!r1) return Void::Result::fail(std::move(r1).error()); + auto r2 = db.exec("INSERT INTO kv VALUES(2, 'two')"); + if (!r2) return Void::Result::fail(std::move(r2).error()); + return 2; + }); + Void::Testing::require(tx_ok.has_value() && *tx_ok == 2); + + // Write transaction error rolls back cleanly inside same lease + auto tx_err = co_await pool.run_write_transaction( + BeginMode::Immediate, + [](Database& db, Transaction&) -> Result { + auto r1 = db.exec("INSERT INTO kv VALUES(3, 'rolled')"); + if (!r1) return Void::Result::fail(std::move(r1).error()); + return Void::Result::fail(make_sqlite_error( + SqliteErrorCode::constraint, "intentional rollback")); + }); + Void::Testing::expect(!tx_err.has_value()); + + // 4 concurrent reads via coroutine calls + for (int i = 0; i < 4; ++i) { + auto count = co_await pool.run_read([](Database& db) -> Result { + auto st = db.prepare("SELECT COUNT(*) FROM kv"); + if (!st) return Void::Result::fail(std::move(st).error()); + auto s = st->step(); + if (!s) return Void::Result::fail(std::move(s).error()); + return st->try_column_int(0); + }); + Void::Testing::require(count.has_value()); + Void::Testing::expect_eq(*count, static_cast(2)); + } + + // Oversized input bytes rejected before queueing + auto over_bytes = co_await pool.run_read_void( + [](Database&) -> Result { return {}; }, + {}, + 4096); + Void::Testing::expect(!over_bytes.has_value()); + Void::Testing::expect(over_bytes.error().kind() == Void::Result::ErrorKind::overloaded); + } + + Void::Coro::Task run_heavy_query( + AsyncPool& pool, + std::stop_token st, + Result* out) + { + Void::Async::OperationOptions op; + op.stop = st; + *out = co_await pool.run_read( + [](Database& db) -> Result { + auto stmt = db.prepare( + "WITH RECURSIVE cnt(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM cnt WHERE x < 20000000) " + "SELECT MAX(x) FROM cnt"); + if (!stmt) return Void::Result::fail(std::move(stmt).error()); + auto s = stmt->step(); + if (!s) return Void::Result::fail(std::move(s).error()); + return stmt->try_column_int(0); + }, + op); + } + + Void::Coro::Task verify_follow_up_reads(AsyncPool& pool) + { + for (int i = 0; i < 10; ++i) { + auto r = co_await pool.run_read( + [](Database& db) -> Result { + auto st = db.prepare("SELECT 42"); + if (!st) return Void::Result::fail(std::move(st).error()); + auto has = st->step(); + if (!has) return Void::Result::fail(std::move(has).error()); + return st->try_column_int(0); + }); + Void::Testing::require(r.has_value()); + Void::Testing::expect_eq(*r, static_cast(42)); + } + } + + Void::Coro::Task drive_pool_crud( + AsyncPool& pool, + Void::Async::ManualExecutor& exec, + bool* done) + { + co_await run_pool_crud_and_backpressure(pool, exec); + *done = true; + } + + Void::Coro::Task drive_warmup(AsyncPool& pool, bool* done) + { + auto r = co_await pool.run_write_void([](Database& db) { + return db.exec("CREATE TABLE dummy(id INTEGER)"); + }); + Void::Testing::require(r.has_value()); + *done = true; + } + + Void::Coro::Task drive_heavy_query( + AsyncPool& pool, + std::stop_token st, + Result* out, + bool* done) + { + co_await run_heavy_query(pool, st, out); + *done = true; + } + + Void::Coro::Task drive_followups(AsyncPool& pool, bool* done) + { + co_await verify_follow_up_reads(pool); + *done = true; + } + +Void::Testing::Test sqlite_async_pool_readers_writer_transactions_and_backpressure() + { + TempPoolDir dir; + Void::Async::ManualExecutor exec; + + AsyncPoolOptions opts; + opts.path = dir.path / "pool.db"; + opts.reader_connections = 4; + opts.max_queued_jobs = 8; + opts.max_pending_input_bytes = 1024; + + auto pool_r = AsyncPool::open(opts, &exec); + Void::Testing::require(pool_r.has_value()); + auto pool = std::move(*pool_r); + + bool done = false; + auto t = drive_pool_crud(pool, exec, &done); + t.handle().resume(); + while (!done) { + if (exec.drain() == 0) { + std::this_thread::sleep_for(std::chrono::milliseconds{1}); + } + } + + const auto st = pool.stats(); + Void::Testing::expect_eq(st.reader_connections, static_cast(4)); + Void::Testing::expect(st.completed_jobs >= 7); + Void::Testing::expect(st.rejected_jobs >= 1); + Void::Testing::require(pool.close_and_join().has_value()); + } + +Void::Testing::Test sqlite_async_pool_cancellation_no_cross_query_interrupt_leak() + { + TempPoolDir dir; + Void::Async::ManualExecutor exec; + + AsyncPoolOptions opts; + opts.path = dir.path / "cancel.db"; + opts.reader_connections = 1; // force all follow-up reads onto the exact same connection + opts.progress_handler_steps = 32; + + auto pool_r = AsyncPool::open(opts, &exec); + Void::Testing::require(pool_r.has_value()); + auto pool = std::move(*pool_r); + + // Warm up DB with initial table/checkpoint + { + bool warmup_done = false; + auto wt = drive_warmup(pool, &warmup_done); + wt.handle().resume(); + while (!warmup_done) { + if (exec.drain() == 0) std::this_thread::sleep_for(std::chrono::milliseconds{1}); + } + } + + std::stop_source ss; + Result cancel_res = Void::Result::fail("uninitialized"); + bool cancel_done = false; + + auto rt = drive_heavy_query(pool, ss.get_token(), &cancel_res, &cancel_done); + rt.handle().resume(); + + // Wait until reader is actively running, then interrupt it. + for (int i = 0; i < 100 && pool.stats().active_read_jobs == 0 && !cancel_done; ++i) { + exec.drain(); + std::this_thread::sleep_for(std::chrono::milliseconds{1}); + } + ss.request_stop(); + + while (!cancel_done) { + if (exec.drain() == 0) std::this_thread::sleep_for(std::chrono::milliseconds{1}); + } + Void::Testing::expect(!cancel_res.has_value()); + Void::Testing::expect(cancel_res.error().kind() == Void::Result::ErrorKind::cancelled); + + // Immediately run 10 follow-up queries on the same single reader connection; + // zero interrupts may leak to subsequent borrowers! + bool followup_done = false; + auto ft = drive_followups(pool, &followup_done); + ft.handle().resume(); + while (!followup_done) { + if (exec.drain() == 0) std::this_thread::sleep_for(std::chrono::milliseconds{1}); + } + + Void::Testing::require(pool.close_and_join().has_value()); + } +} // namespace 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