Files
Library/docs/roadmap/subsystems/Storage.md
T

305 lines
23 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Storage — original durable key-value engine
Status: NEW design; all implementation tasks below are PLANNED. Source baseline:
`main` at `f1f9ba375b22abf1adcc7c550ec21ac20895c0a4`. No Storage source directory,
format, target, or test runner exists at this baseline. R-007/R-008 and
[architecture C-02–C-05, C-08, C-12](../ARCHITECTURE.md) govern this plan.
## Boundary and selected implementation
Build an original engine with an append-only WAL, ordered memory index and immutable
sorted table files. SQLite remains the distinct [Sqlite integration](../modules/Sqlite.md).
There is no SQL parser, SQLite file compatibility, or database-server dependency here.
Native format/recovery code uses [Binary](../modules/Binary.md) field encoders; Storage
owns the framing, native CRC32C helper and checksum fixtures.
[IO](IO.md) supplies file and synchronization operations. Initial synchronous operations
also work without Runtime. Async adapters own their jobs and use Async's operation options;
they never perform blocking file work on an event-loop thread.
Adjacent existing persistence evidence is
[VersionStore](../../../src/Update/VersionStore.cpp), whose activation journal and durable
health marker are application-specific, and
[Sqlite.cpp](../../../src/Sqlite/Sqlite.cpp), which delegates transactions to SQLite.
Neither is an existing generic storage engine. New paths are PROPOSED:
`include/Void/Storage/`, `src/Storage/`, `tests/standalone/Storage/`; the NEW target is
`Void::Storage`. Replication ports belong above this engine, avoiding a Storage→Coordination
dependency. [Dependencies](../DEPENDENCIES.md) is the package-edge authority.
Initial deployment is one process holding an exclusive database-directory lock, with one
serialized writer and concurrent readers. Read-only access from another process is not
promised while the writer is open. Local filesystems with working file/directory sync and
atomic same-directory rename are required for durable mode; `Engine::open` returns
UnsupportedCapability without mutation when these are unavailable. A successful fsync
cannot compensate for a device that lies about flushes.
## NEW API sketch and consistency contract
Illustrative declarations, not compiling examples; `Result` is the C-02 shorthand.
Storage owns all domain types below. Operation options are owned by [Async](../modules/Async.md).
```cpp
namespace Void::Storage { // NEW
using Sequence = std::uint64_t;
enum class Durability { Sync, Buffered };
enum class Outcome { NotCommitted, Committed, Unknown };
struct Limits; // concrete defaults below
struct OpenOptions; // directory, durability, limits, allocator, IO ports
struct CommitReceipt { Sequence sequence; Durability durability; };
struct WriteFailure { StorageError cause; Outcome outcome; };
class Batch; // owning key/value bytes, puts, erases, preconditions
class Snapshot; // move-only pin of a committed sequence and source versions
class Cursor; // move-only ordered iterator retaining its Snapshot
class Engine {
public:
static Result<Engine> open(OpenOptions);
Result<Snapshot> snapshot();
std::expected<CommitReceipt, WriteFailure> write(Batch, Durability);
Result<OwnedValue> get(const Snapshot&, ByteView key) const;
Result<Cursor> scan(Snapshot, ScanBounds) const;
Result<void> checkpoint();
Result<void> sync();
Result<void> close();
};
}
```
`ByteView`, `OwnedValue`, `ScanBounds`, `StorageError`, and `Batch` are NEW Storage
interfaces, using standard byte spans/vectors and Binary encoding internally. Key order
is unsigned-byte lexicographic order, independent of locale. Empty keys and empty values
are distinct from absence. Erase writes a tombstone. A batch forbids duplicate mutation
keys, allows at most one precondition per key, and evaluates all conditions against the
latest committed state in writer order before any change. Conditions are absent,
version-equals, or exact-value-equals. Versions are sequence numbers, not value hashes;
delete/reinsert cannot pass an obsolete version check. Conflicts return NotCommitted.
One commit sequence covers the entire batch. Snapshot reads see the highest version no
greater than their captured sequence; no partial batch is ever observable. This is atomic
conditional batching, not arbitrary snapshot-isolated read/write transactions. A caller
that reads then writes must supply the read version as a precondition to prevent lost
updates. For an idempotent request, condition on absence of an application deduplication
key and write its result in the same batch as business mutations. The application owns
that key's retention; after eviction, replay safety is no longer implied. Replication uses
the same batch for application state, deduplication and applied-log position (C-12).
`get` returns an owning value; cursor output owns a bounded page. No public reference into
a mutable map or mapped file outlives its pin. Half-open scan bounds `[begin, end)` and a
prefix helper share the byte comparator. Each page has a last-key continuation within
the same snapshot, never a fresh snapshot per page. Closing a cursor releases its pin.
Snapshots are process-local and not serializable capabilities.
## Writer, visibility and failure state machine
1. Admit the entire batch by operation/byte budget. Own all input bytes; validate lengths
and conditions. Reserve memory for every index mutation and its version metadata before
emitting WAL bytes. Reject an exhausted sequence counter rather than wrapping it.
2. Under the writer strand, assign the next sequence, encode BEGIN, operations, COMMIT,
and append in order with short-write/EINTR handling. There is no interleaving between
batches in the initial engine. Cancellation before append returns NotCommitted.
3. In Sync mode, sync the WAL and all newly created recovery dependencies. Publish the
prepared index changes and committed sequence under a short visibility lock, with no
fallible allocation in this publication step. Only then acknowledge durable success.
Readers capture the sequence and source-version set under that same lock.
4. In Buffered mode, acknowledge after complete WAL append and index publication, clearly
indicating weaker durability. A later `sync()` establishes a durable prefix. A Sync
write also syncs all earlier buffered batches; later durable success must never depend
on an earlier unpersisted batch.
5. Any write/sync failure after append starts returns Unknown unless non-commit can be
proved. The engine enters RecoveryRequired, stops writes, and retains the last published
view for existing readers. Reopen/recovery decides which complete batches exist.
It must not retry the append, reuse the tentative sequence, or report rollback solely
because sync failed. Allocation failure before append is NotCommitted.
An async cancellation/deadline after append cannot revoke a commit. It returns the receipt
when the commit becomes known, or a WriteFailure with Unknown; exactly one result is delivered
after backend access ends. `close()` stops admission, joins admitted writes, syncs buffered
state when requested by policy, and reports outstanding pins as Busy. Snapshot/control-block
ownership keeps resources alive after an Engine handle is dropped; destructors cannot turn
an unreported sync failure into a durability guarantee. Embedded callers explicitly drive
maintenance; managed Runtime schedules it and joins it before releasing IO.
The async adapter follows Async's domain-result classification, not a first-stop-wins
replacement result. Conformance cases are explicit: stop before append → NotCommitted;
stop while sync is pending → retain the operation without delivering yet; sync succeeds
after stop → finish infallible index publication and return CommitReceipt; sync fails
after append → Unknown and RecoveryRequired unless non-commit can be proved. Stop and
deadline expiry cannot skip required publication after successful persistence or produce
a second notification when the backend later retires.
## V1 WAL format and recovery protocol
This is a selected NEW format specification to implement and freeze with golden fixtures,
not a claim that files already exist. All integers are little-endian with checked unsigned
length arithmetic. No raw C++ structs, host padding, native pointers, or native `size_t` are
written. Storage's CRC32C uses polynomial `0x1EDC6F41` (reflected `0x82F63B78`), reflected
input/output, initial register `0xFFFFFFFF`, final xor `0xFFFFFFFF`, and little-endian
checksum storage. The golden ASCII `123456789` check is `0xE3069283`; these parameters
are independently documented in [Cyphal specification appendix A.2](https://specification.opencyphal.org/Cyphal_Specification.pdf).
Storage owns those tests, including empty input, incremental updates and full-record
fixtures. CRC detects accidental corruption and is not authentication. Header CRC covers
the bytes preceding its own field (60 segment-header bytes or 32 record-header bytes).
| Structure | Required fields and validation |
| --- | --- |
| Segment header | 8-byte magic `VOIDWAL1`, major/minor u16, header size u32, database UUID 16 bytes, segment id u64, previous segment id u64, first candidate sequence u64, flags u32, header CRC32C u32. V1 header size is 64 bytes. Reject opening unknown required flags or major versions without mutation. |
| Record header | Magic u32, total record length u32, type u16, record version u16, flags u32, batch sequence u64, ordinal u32, payload length u32, header CRC32C u32. Header size 36 bytes; validate header CRC before trusting any allocation length. |
| Record trailer | CRC32C u32 over the complete header and payload, then repeated total length u32. Length includes the 36-byte header and 8-byte trailer; padding is not used. |
| BEGIN payload | operation count u32, total operation-payload bytes u64; these are bounded by admission limits. Ordinal zero. |
| PUT/ERASE payload | key length u32, value length u32, then raw bytes; ERASE requires value length zero. Ordinals 1 through operation count. Preconditions are evaluated before logging and are not re-evaluated during redo. |
| COMMIT payload | operation count u32, total operation-payload bytes u64, aggregate CRC32C u32 over the ordered BEGIN and operation records including their trailers. Ordinal count+1, same sequence. |
The writer never splits a batch across segments; rotate first if it would exceed the
64 MiB segment target. A maximum-sized batch fits in one segment. Register and durably
publish the new segment in the manifest before accepting writes to it. This avoids a
durable receipt whose only WAL is an undiscoverable orphan. Do not preallocate logical
EOF with indistinguishable zero records in V1.
Recovery obtains the exclusive lock, validates CURRENT and its manifest, then table metadata,
then manifest-listed segments in id order. Database UUIDs, segment chain, record ordinals,
sequences, sizes and checksums must agree. Buffer one bounded batch while scanning; apply
only after a matching COMMIT and only above the manifest's checkpoint sequence. Reject
sequence gaps/duplicates among batches that need redo. COMMIT presence establishes recovery
visibility, even if the caller never received an acknowledgement.
Only an incomplete header/body at physical EOF of the final active segment, or a valid
BEGIN/operation suffix without COMMIT, is treated as an uncommitted tail. Preserve diagnostic
offsets, truncate that tail to the last complete batch, and sync before resuming writes.
A complete record with a bad checksum, malformed length, unexpected type or broken sequence
is Corruption, including at EOF: a fully sized torn write cannot reliably be distinguished
from later media damage. Fail closed and require explicit offline salvage into a different
directory; never skip damaged bytes and continue. Earlier/closed segments permit no tail
exception. Recovery interruption is safe because redo is deterministic and only tail
truncation mutates the old WAL. Test crash during that truncation and its sync.
## Checkpoints, manifest and compaction
Minimal CURRENT/manifest handling belongs to P1 alongside WAL recovery, before any durable
receipt is possible. Under the exclusive directory lock, initial creation persists the
database identity and first segment header, writes/syncs a manifest with no tables and
checkpoint sequence zero, then publishes/syncs CURRENT and the containing directory.
Only then may write admission open. Segment rotation reuses that publication protocol to
register the new segment while retaining every older segment needed for recovery; no
batch enters it before publication is durable. A crash before a valid CURRENT exists
cannot have an acknowledged batch and normal open reports incomplete initialization;
it never adopts the highest orphan manifest. Fault tests cover each creation and rotation
boundary. P2 extends this already working protocol with tables/checkpoint generations.
P1 keeps an ordered `std::map` of keys with version chains, guarded by short read/write
index locks. Reads copy data under a lock; cursors seek afresh by last key, so no tree
iterator survives mutation. P2 freezes a memtable at sequence S and starts a new mutable
one. A snapshot pins the active/frozen sources and table version set; publication replaces
sources without invalidating existing pins. This selected simple index provides a reference
before a future native tree optimization is justified by profiles.
NEW table files contain a versioned header/UUID/table id, sorted blocks of
`(key, descending sequence, put-or-tombstone, value)`, a sparse key/offset index, and a
checksummed footer naming every block, range and sequence interval. Default blocks target
32 KiB; a record larger than that occupies a dedicated bounded block. The maximum physical
block is bounded by the 4 MiB value limit plus key/header overhead. Index offsets and key
ordering are validated; each read verifies block CRC. The whole-file digest/checksum in
the manifest protects identity and metadata, while lazy block verification bounds open cost.
The offline verifier reads every block. V1 uses no compression or mmap requirement.
Manifest generations are immutable, checksummed files listing table ids, lengths, key/sequence
ranges, replay segments, checkpoint sequence, comparator identity and minimum reader/writer
format versions. CURRENT contains a generation name, generation number, database UUID and
checksum. Publication ordering is mandatory:
1. Write table temporary files in the database directory; finish checksums; sync each file.
2. Rename each to its unique immutable final name; sync the containing directory.
3. Write and sync a new manifest temporary file, rename it, and sync the directory.
4. Write and sync CURRENT.tmp, atomically rename it to CURRENT, then sync the directory.
5. Publish the new in-memory source set. Only now can old WAL/table files become retirement
candidates. Remove them only after all pins release, and sync directory deletions.
A crash before CURRENT publication leaves the old manifest authoritative and new files
orphaned; after it, every named dependency is already durable. Unknown CURRENT publication
outcome stops maintenance and requires recovery, without deleting either generation's inputs.
Do not select the highest manifest filename on recovery: it may be an uncommitted candidate.
A missing/corrupt CURRENT or referenced file is Corruption, not permission to discard newer
acknowledged data. Offline repair is separately authorized and writes a new destination.
Initial checkpoint produces a complete table view through S; all WAL through S is removable
only after that view is durably selected. Incremental compaction in P2 merges at most four
overlapping immutable runs per job using a min-heap ordered by key/version, with one output
file open at a time and 64 MiB target outputs. Keep all versions newer than the oldest live
snapshot and the newest at/below it. A tombstone may be discarded only when every older
overlapping run is included and no pinned reader needs it. Old pinned source sets stay
readable even after a replacement manifest is durable. Compaction never mutates input files.
Cancellation between blocks discards unreferenced temporary outputs; after manifest selection
it completes bookkeeping rather than undoing publication.
## Defaults and performance gates
| Budget | Initial default and exhaustion behavior |
| --- | --- |
| Key/value/batch | 4 KiB key, 4 MiB value, 16 MiB encoded batch, 1,024 mutations and 1,024 conditions; reject before WAL. |
| Pending writes | 64 admitted batches and 64 MiB total including active writer input/encoded copies; nonblocking overload by default. |
| Memtables | 64 MiB active target, 256 MiB total live index/version budget including frozen and pinned memory; reserve at admission, pause writes when maintenance cannot reclaim. |
| Read resources | 128 snapshots, 128 cursors, 1 MiB normal scan page/1,024 rows; a larger single value is reported as PageTooSmall unless caller opts into a page up to 8 MiB. |
| Retention/cache | 1 GiB obsolete pinned-file budget, 32 MiB block cache, 16 MiB compaction workspace; count actual bytes and allocator overhead. Never invalidate live snapshots to meet a budget. |
| Disk | 4 GiB WAL hard cap, at most 32 active runs, compaction output reserve checked before work; backpressure writes if pins or disk space prevent progress. |
| Maintenance | One compactor; 8 MiB work slices, check stop/deadline between blocks; 64 MiB/s optional default managed rate limit, injectable clock. |
Limits are configurable finite values; zero is invalid unless a field explicitly permits
zero. Persistent data size itself is governed by a configured volume quota and free-space
reserve. Bound manifest/table-index metadata too: 64 MiB per manifest, 65,536 table entries;
larger databases require a later format/capability gate, not unbounded open allocations.
Long-lived snapshots can stall write admission; expose oldest pin age, retained bytes and
compaction debt through optional [Observability](Observability.md) hooks.
[Performance](../PERFORMANCE.md) profiles compare point reads, mixed read/write, sequential
scan, hot-key churn, large values, and slow-reader compaction. Measure Sync and Buffered
separately: p50/p95/p99 including admission and sync, throughput, write amplification,
allocations, peak RSS/CPU, disk use, recovery time and build cost. Do not claim a speedup
or durability from an in-memory benchmark. A native index replacement is gated on measured
benefit with identical format/consistency tests, not part of the initial core.
## Ordered implementation backlog
All rows are PLANNED; phases follow [delivery](../DELIVERY.md). External dependencies name
capabilities owned by their area plans rather than inventing their task identifiers.
| ID | Phase / dependencies | Implementation scope and acceptance | Recommended role |
| --- | --- | --- | --- |
| S-STORAGE-01 | P0; Binary encoding, IO durability contracts | Freeze format fixtures, invariants and fault-injectable file port; reject overflow/unknown versions and show exact crash points. | astra_implementer |
| S-STORAGE-02 | P1; S-STORAGE-01, Functional errors, Memory bounds | Implement single writer, byte comparator, conditional batches and pinned in-memory snapshots; model tests prove atomicity, conflicts and ordered scans. | astra_implementer |
| S-STORAGE-03 | P1; S-STORAGE-02 | Directory lock, minimal CURRENT/manifest bootstrap and durable WAL-segment registration, append/sync/recovery; crash initial creation and rotation, preserve every acknowledged Sync batch, reject partial batches and expose Unknown after failed sync. | astra_implementer |
| S-STORAGE-04 | P2; S-STORAGE-03 | Extend the existing manifest protocol with immutable tables/checkpoints; crash every table/checkpoint publication step and recover the selected generation without lost committed data. | astra_implementer |
| S-STORAGE-05 | P2; S-STORAGE-04 | Bounded incremental compaction, retention, scans and quotas; a pinned snapshot survives replacements and stalls safely under budget pressure. | astra_implementer |
| S-STORAGE-06 | P3; S-STORAGE-05, Async/Runtime ownership | Async adapters, backup pin/export, verify/restore tools, diagnostics and benchmark profiles; tools cannot mutate a live directory without its lock. | sol_implementer |
| S-STORAGE-07 | P3; S-STORAGE-06, Data schema evolution | Optional document and secondary-index layer; update document/index keys atomically, rebuild into a new namespace, define optimistic conflict semantics explicitly. | astra_implementer |
| S-STORAGE-08 | P4; S-STORAGE-06, Replication contracts | Atomic application/dedup/applied-position adapter and versioned snapshot export; restart never re-applies a committed external side effect by implication. | astra_implementer |
## Validation, migration and rollback
CURRENT: no Storage tests or target exist. Existing baseline commands and their known
environmental failures are in [validation](../VALIDATION.md); they are not Storage evidence.
PROPOSED, after S-STORAGE-03 adds/discovers `storage_` tests in the normal test build:
`<configured-build>/tests/VoidTests --filter '^storage_'`. Angle-bracket paths are command
templates. S-STORAGE-03 and subsequent durability tasks require an isolated filesystem
fault harness and subprocess crash runner, including initial CURRENT creation and WAL
rotation; do not substitute clean shutdown tests for power-loss simulation.
Required tests enumerate every short write, failed fsync, rename and directory sync; truncate
every WAL byte offset; corrupt each header/record/table/manifest field; reorder or discard
unsynced writes; interrupt recovery; repeat recovery twice. Model checking compares all
committed batches and snapshots against an ordered reference map. Include delete/reinsert,
precondition races, empty values, binary keys, sequence exhaustion, cross-page scan stability,
retention pressure and disk-full compaction. SQLite's
[crash-test methodology](https://sqlite.org/atomiccommit.html#_testing_atomic_commit_behavior)
motivates the injected-filesystem campaign; it does not validate this new engine.
Format major versions reject incompatible writers/readers. Additive minor features require
feature bits and explicit capability negotiation; never reinterpret old bytes. Upgrades use
read-old/write-new export into another directory, verify counts/checksums and a consistent
snapshot, then perform an operator-controlled directory selection with old data retained.
Backups pin a manifest, tables and necessary WAL prefix until their copy is complete and
verified; copying only tables from a changing directory is not a backup. Rollback selects
the verified old directory only before accepting new writes, or requires explicit data
reconciliation afterward. [Migration](../MIGRATION.md) owns release policy; richer isolation,
encryption-at-rest and multi-process writers require separate named capability gates.
Evidence: graph coverage was checked for the cited adjacent implementation files and their
source inspected. New Storage behavior is entirely proposed; no build, crash test, benchmark
or production durability result is claimed by this document.