Qué hace
- Tablas con nombre, cursor ordenado y <code>GetRef</code> zero-copy
- Aislamiento por snapshot (MVCC), tres niveles de durabilidad
- XXH64 en cada página, cabecera guardada en dos copias
- TTL por clave, compresión y cifrado de páginas a través de interfaces
- Índices secundarios y registros tipados mediante <code>meta</code>
- Backup en línea, <code>Compact</code> y <code>Verify</code>
Medido
- Release, GCC 15.2 en ext4 bajo WSL2 / MSVC 19.51 en NTFS, 1M claves, 115 MB. Recorrido secuencial: 21 a 23 M y 16 a 19 M entradas/s (objetivo 1 M/s)
- Escrituras con 100 operaciones por commit: 922 a 933 k y 753 a 770 k ops/s (objetivo 500 k)
- Abrir una base de datos de 1 GB: 0.92 ms y 1.49 ms (objetivo 10 ms)
- Caídas simuladas en 1263 puntos x 4 discos: 5052 reaperturas, cero corrupciones
- Lectura puntual aleatoria en una base de datos de 115 MB, mayor que la caché de la CPU: 831 a 1578 ns y 870 a 1176 ns. Objetivo de 1 µs no cumplido de forma robusta
Límites conocidos
- Una transacción de escritura debe caber en la caché. Sin lectores en otros procesos y sin uso en sistemas de archivos de red
- Ningún test mata un proceso real sobre un disco real
Ethereal::Storage · Tier 2
It is not SQL and does not pretend to be. It is a B+ tree over pages with a full-page write-ahead log (WAL), named tables, ordered iteration, transactions with snapshot isolation, one writer and many readers that never wait for it. It is what the TorreSync block index, the Updater queue and the CrashReport queue need, and what would make an integrator go looking for SQLite. No thread is created.
The spec sets the bar like this: "if the crash consistency proofs cannot be built, the module is not delivered". They were built and are in the section Crash consistency.
#include <ethereal/cpp/storage/storage_inc.hpp>
namespace S = Ethereal::Storage;
S::CDatabase Db;
S::CDatabase::Open( "data.db", S::SOpenOptions{}, &Db ); // creates, or opens and recovers
S::CTransaction Tx;
Db.Begin( S::ETxMode::eReadWrite, &Tx );
Tx.Put( "queue", Chave, Valor ); // std::span<const uint8_t>
Tx.Commit(); // eFull: returns only with the WAL on disk
Db.Begin( S::ETxMode::eReadOnly, &Tx );
std::span< const std::uint8_t > V;
Tx.GetRef( "queue", Chave, &V ); // no copy: points into the cache
S::CCursor C;
Tx.Cursor( "queue", &C );
for( auto e = C.SeekPrefix( Prefixo ); e == S::EStorageStatus::eOk; e = C.Next() ) { ... }**Keys sort by bytes (memcmp). A little-endian integer does not** sort as a number: 256 comes before 1. Store integers in big-endian, with the sign bit inverted if they are signed. Everyone trips over this once. The typed layer does the correct encoding on its own:
#include <ethereal/cpp/storage/storage_typed.hpp> // separate: pulls in Meta
struct SUser { std::int64_t iId; std::string sName; double dBalance; };
ETL_META_DESCRIBE( SUser, ETL_META_FIELD( iId, S::Key() ), ETL_META_FIELD( sName ), ETL_META_FIELD( dBalance ) );
S::TTable< SUser > Users( "users" ); // -1 before 0, 255 before 256
Users.Put( Tx, SUser{ 42, "Ana", 10.5 } );---
Durability, which is the whole module
The protocol
Commit. The dirty pages become frames (a 64-byte header + the page), the last one carrying the commit mark and the database state (pages, root, free list). The checksum of each frame is chained: the seed is the checksum of the previous frame. The frames go to the end of the WAL, and only after the fsync (in eFull) is the transaction published. The main file does not change on Commit.
Checkpoint.
fsyncof the WAL.- The most recent version of each page, up to the oldest snapshot of an active reader, goes to the main file. An older reader never reads from the main file a page that has a frame in its snapshot, and so this copy never changes anything for it.
- The header (into the older of the two copies) and
fsyncof the database. - Only with everything copied and no reader, the WAL restarts with a new salt (and
fsync).
A failure at any point leaves the WAL whole and valid: recovery reads the pages from there again, and the copy is repeated (it is idempotent). A torn page in the main file is never read while the WAL has it. The checkpoint runs at the end of a Commit when the WAL exceeds uAutoCheckpointFrames, or manually.
Recovery (on Open). The valid header copy with the higher generation. The WAL is read frame by frame while the salt, the database id and the checksum chain match, and it is accepted up to the last complete commit. The rest (a half-done transaction, a torn frame, garbage from an old generation) is ignored and will be overwritten. The cost is proportional to the WAL, and the size of the database does not factor in.
Checksums on everything. Each tree page carries XXH64 seeded with the page number (a write that lands on the wrong page is also caught). A large value (overflow) carries the checksum of the whole value in the cell that points to it. Each WAL frame and each header copy has its own. **A wrong checksum is a hard error (eCorrupt), and the page is never used.** XXH64 is part of the format and is not a seam: a swappable checksum would make files unreadable across integrators. The test suite checks it against Compression::XxHash64.
What each durability level can lose
| Process death | Power failure | |
|---|---|---|
| eFull (default) | nothing committed | nothing committed |
| eBatched | nothing committed | the commits since the last fsync (the uBatchIntervalMs interval, and the ones at the end if the database went idle: with no thread, nobody syncs on their own, so call Sync or Checkpoint at your own pace) |
| eNone | nothing committed | everything since the last Checkpoint/Sync/Close |
In all three, the file is never left corrupted: it always comes back to a complete prefix of the committed transactions.
The details that usually get forgotten
- **
fsyncof the folder** after creating the database (created alongside and renamed), the WAL and the backup copy, and after theCompactswap. Without this a new file can vanish in a power failure even with its contents synced. On Windows it is a no-op: NTFS records the metadata in its journal, and Windows does not allow syncing a folder. - **
F_FULLFSYNCon macOS**: thefsyncthere only hands off to the disk and leaves the data in the disk's cache. The branch is invfs_os.cppand is checked bymacos_syntax_probe, which proves it is valid C++ against fake declarations. It does not prove it builds on macOS: there is no Mac on this machine. - **An
fsync(or a WAL write) that fails poisons the database** until it is reopened (eFailed): the system may have thrown away the dirty pages and said "ok" right afterwards (PostgreSQL's "fsyncgate"), and only recovery knows what remained. A Commit that returnseIooreFailedmay or may not have persisted. - The WAL of another database with the same name (a database deleted by hand, with the WAL left behind) is never reapplied: the WAL header carries the database's random id.
- The header in two copies, always writing the older one: a torn write ruins at most one.
---
Concurrency
- One writer at a time. The second
Begin( eReadWrite )waits up touWriteLockTimeoutMsand giveseBusy. With a single writer, a deadlock is impossible by construction. - Unlimited readers, each with the snapshot from its start, and none waits for a writer: a reader starts and reads with a write transaction open (the test suite does this even on the same thread). What exists are short internal locks (the cache map, the WAL index), never held during I/O or during a transaction.
- Across processes: an exclusive lock on
<path>.lock. One process at a time, and the second getseLocked. There are no readers in another process, and it does not work on a network file system (the locks andfsyncthere do not give the guarantees this depends on). - A transaction belongs to one thread. Do not share a
CTransactionacross threads.
---
Limits, stated before someone trips over them
| Key | up to 4051 bytes with 16 KiB pages (the default). With smaller pages, MaxKeySize() says how much. Beyond that: eKeyTooLarge |
| Value | up to uMaxValueBytes (default 16 MiB, maximum 1 GiB, and never more than half the cache: the whole value passes through it). Beyond that: eValueTooLarge |
| Database | up to uMaxDatabaseBytes (and 2³² pages). Beyond that: eDatabaseFull, never silent truncation |
| Memory | the cache (uCacheBytes, clean and dirty pages together) never exceeds the ceiling. Measured: the peak is exactly the ceiling |
| Write transaction | must fit in the cache. There is no spilling of dirty pages to the WAL before Commit: a transaction that dirties more than the cache returns eCacheFull and is rolled back entirely. With the default (64 MiB, 16 KiB pages) that is ~4000 dirty pages. Split larger transactions |
GetRef | in a read, valid until the end of the transaction. In a write, until the next write in the same transaction (the page may be reorganized). A compressed value is decompressed into the transaction's memory, and then there is a copy (counted in uValueBytesCopied) |
CCursor::Current | valid only until the cursor moves: a scan that pinned every page it passed through would break the cache ceiling. In a write, modifying the table repositions the cursor by key |
| Deletions | no rebalancing: an empty leaf is removed, and an internal node with no keys is replaced by its only child. Many deletions leave half-empty leaves. Compact rebuilds the tree full |
---
The rest of the spec
- Tables (internal 4-byte prefix with the id, created on the first
Put). - Per-key TTL (
SPutOptions::Ttl): expires lazily on read (and the cursor skips it), and is collected atCheckpointthrough an expiry index. Wall clock throughIClock. - Compression above a size, through the
ICompressorseam (only if it wins). - Page encryption at rest, through the
IPageCipherseam: it must preserve size and be tweakable by page number (like AES-XTS). The key belongs to the integrator. The header stays in the clear. Opening an encrypted database without a cipher, or the reverse, giveseCipher. - Secondary indexes (
SOpenOptions::pIndexes): a function extracts the index key from a value. The index is maintained in the same transaction as the table, andIndexCursorwalks it in index order, returning the primary key and value. It is not a planner: the caller chooses. - Records typed through Meta (
storage_typed.hpp, a layer on top. The core does not know it). - Online backup (
Backup): a snapshot copied while writes continue. - Free page management with reuse, and explicit
Compact(rewrites only what is live and swaps throughrename. Never automatic, never in the background). - **
Verify**: checksums, key order, bounds inherited from the parent, overflows, free list, and that no page is in two places. - Complete C layer (
ethereal/c/storage/storage.h): database, transaction and cursor through handles, tested in C11 and C17.
---
Crash consistency
The spec: "non-negotiable". The instrument is an in-memory VFS with faults (tests/storage_vfs_faults.hpp). Each file has its durable content and the list of writes since the last Sync. Names (create, delete, rename) only become durable with SyncDir. It can kill the process before any operation that changes the disk and, after the crash, returns one of four disks:
| Disk after the crash | What it models |
|---|---|
| only what was synced | everything in the system's memory was lost |
| a prefix of the pending writes | the disk was in the middle of writing |
| a prefix with the next write torn into random 512-byte sectors | torn write |
| any subset of the pending writes, out of order | a disk that ignores ordering without a barrier |
| Proof | Result |
|---|---|
Every kill point of two workloads (splits, overflows, checkpoints with the WAL restarting, a Compact), × the four disks | 1263 points, 5052 reopenings: zero corruptions. Each one opens, passes Verify, loses no pages, and has exactly the committed transactions (4782) or those plus the one that was in the middle of Commit (270). Never half of one |
| The same in eBatched | loses commits (55 times), but always a complete prefix. Never corrupts |
| Soak: random operations and kills against an in-memory model | 8 s in each run of the test suite (~800 kills, ~14,000 transactions). In a separate one-hour run: 26,482 kills, 444,511 committed transactions, zero divergences from the model |
| Randomly damaged files (database and WAL), under ASan and UBSan | 600: clean error or success, never an out-of-bounds access |
| Durable names after Open | the database and the WAL, always (SyncDir was called) |
And the tests actually work. Twelve defects planted in the protocol (tools/storage_check/mutants_storage.py), all caught. Two of them only after the missing tests were written, and a third was a real defect, found while reviewing the pins during the read optimization:
| Planted defect | Caught by |
|---|---|
eFull Commit without fsync of the WAL | the kill points, the soak, the poisoning |
the WAL restarts without fsync of the database | the kill points (eFull and eBatched), the soak |
WAL created without fsync of the folder | CreationSyncsTheFolder, the kill points, the soak |
| recovery that accepts frames after the last commit | the kill points (atomicity) |
| recovery without checking the frame checksums | the kill points, the soak |
| copy to the database without respecting the oldest reader | OldReaderDoesNotSeeCheckpointCopy (written after the defect survived: it needs cache pressure for the page to leave and come back from the file) |
| the WAL restarts with active readers | MVCC under load, CheckpointRestartsWalOnlyWithoutReaders |
| page read from disk without checking the checksum | VerifyCatchesACorruptPage |
Compact renames without fsync of the folder | the kill points, the soak |
| a leaf split loses the last cell | five functional tests |
| a freed page goes straight back to the committed free list | RollbackAfterFreeingPagesDoesNotLoseThem (written after it survived: it only shows up in a Rollback) |
| the WAL restart leaves a pinned entry in the cache map | PinnedPageAcrossWalRestartDoesNotGoStale. This was the original code: a page pinned by a cursor (or by a transaction finishing on another thread) kept the old key, and frame numbering restarts, so frame f of the same page would find the old content. Fixed (the entry leaves the map and lives as an orphan until the last pin is released) |
What was not done: a test that kills a real process mid-operation (SIGKILL) on the real disk. The fault VFS models this case (and also disks that lose, tear and reorder), but it does not exercise the real pwrite/fdatasync under a true kill.
---
Performance (spec §7)
Development machine, Release. GCC 15.2 on WSL2 over ext4 (ETL_STORAGE_DIR on the Linux disk: measuring on /mnt/c measures 9P, and the engine gets hidden), MSVC 19.51 over local NTFS. 16 KiB pages, 1M keys of 8 bytes with 32-byte values (115 MB). Everything comes from the storage.measurements test, two runs of each, with the machine idle.
| Spec target | GCC / ext4 | MSVC / NTFS | |
|---|---|---|---|
| Point read in cache < 1 µs | 332 to 425 ns on a hot set (20,000 keys). 831 to 1578 ns random over 1M keys (most between 0.85 and 1.3 µs) | 451 to 650 ns. 870 to 1176 ns | ⚠️ borderline: see below |
| Read outside the cache: one page read | 1.00 reads per Get (internal nodes already in cache) | 1.00 | ✅ |
| Sequential scan > 1 M/s | 21 to 23 M entries/s | 16 to 19 M | ✅ |
| eFull write: bounded by fsync, measured | 616 to 632 Commits/s | ~2000 Commits/s | measured |
| eBatched write > 500 k ops/s | 922 to 933 k ops/s with 100 per Commit. 21 k Commits/s with 1 per Commit | 753 to 770 k. 11 to 12 k | ✅ (batched). See below |
| Open < 10 ms for 1 GB after a clean close | 0.92 ms (1 GB). 0.55 to 0.65 ms (115 MB) | 1.49 ms (1 GB) | ✅ |
| Recovery proportional to the WAL, independent of the database | 1000 frames: 12 to 13 ms. 10,000: 92 to 95 ms | 20 ms. 186 ms | ✅ |
| Memory: never exceeds the ceiling | peak = ceiling, exactly (1 MiB cache, ~5 MiB database) | same | ✅ |
What this means:
- The point read stays below 1 µs while the pages are in the processor cache, which is the cost of the engine (0.33 to 0.65 µs). Random over a 115 MB database, it sits around 1 µs, some runs below and others above: the target is borderline and is not met consistently. The binary search inside a 16 KiB leaf takes ~8 misses to main memory, and on WSL2 each miss also pays the virtual machine's address translation (hence the larger spread on GCC). The value got here from 1.3 µs (GCC) and 2.2 µs (MSVC), through four measured changes:
- pins are released without a lock (atomics).
- a read transaction keeps the internal pages it has already pinned (the root and the upper levels no longer touch the cache lock).
- (batch 3, second pass) the binary search prefetches the two possible cells of the next step before comparing, and the miss of the next step happens in parallel with the current one.
- (same) with no frames in the WAL (after a checkpoint), a page read skips the shared lock and the frame map: an atomic, set by the writer before publishing the maximum frame, says that the map is empty.
Interpolation in the leaf was also tried (estimating the position from the first and last keys, galloping and finishing with a binary search). In an interleaved comparison, five runs of each, it was indistinguishable from this machine's noise (±30%), and it was removed. Getting consistently below 1 µs would require changing the format (a vector of key "hints" next to the offsets, so the binary search does not go to the cells). That was not done.
- "eBatched write > 500 k ops/s" is met with operations grouped into transactions. With one operation per Commit the ceiling is ~21 k Commits/s (GCC): each Commit writes the whole changed page (16 KiB) to the WAL, because the WAL is page-based (that is what makes recovery simple and proven). A logical WAL (the operation only) would exceed this, and would pay for it in recovery complexity.
- The WSL2 fsync (ext4 over a virtual disk) is slower than the NTFS one on this machine. The eFull numbers depend on the disk and say little outside of it.
---
Status (spec §10)
| Criterion | Status |
|---|---|
| Crash consistency: every kill point, thousands, zero corruptions | ✅ 1263 points × 4 disks = 5052 reopenings, on both compilers |
| Torn writes: detected by checksum, recovered from the WAL | ✅ (the "torn" disk) |
| Out-of-order writes: survived | ✅ (the "out of order" disk) |
F_FULLFSYNC on macOS | ⚠️ in the code and checked by the syntax probe. It has not run on a Mac (there is none here) |
fsync of the folder on the entire creation path | ✅ database, WAL, backup copy, Compact, and the CreationSyncsTheFolder test |
| Reference model in a soak of hours | ⚠️ one hour (26,482 kills, zero divergences). "Hours" has not run |
| MVCC: readers never block or see half-done writes, under load | ✅ 4 readers × 3000 transfers, the sum always correct. A reader opens with a writer open. TSan clean |
| Transaction destructor rolls back, also with an exception | ✅ |
No copy in GetRef and in the cursor, by instrumentation | ✅ the same pointer twice, and uValueBytesCopied unchanged (except compressed values, as stated above) |
| §7 performance | ⚠️ all met except the random point read on a database larger than the processor cache (around 1 µs, some runs below and others above). See above |
| Memory bounded by the cache | ✅ (and a transaction larger than the cache is rejected with eCacheFull, a documented limit) |
| Limits with clear errors | ✅ key, value, database, cache |
| Consistent online backup | ✅ with a writer committing in parallel |
Verify catches a damaged page | ✅ and says which one |
| File fuzzing: never breaks | ✅ 600 damaged files under ASan+UBSan |
| Sanitizers | ✅ ASan+UBSan and TSan: zero reports across all Storage tests |
| C layer | ✅ C11 and C17 |
| Secondary indexes and records typed through Meta | ✅ |
| Across processes | ✅ exclusive lock (eLocked). Readers in another process do not exist, as stated above |
| Full test suite afterwards | ✅ full ctest: GCC 124/124, MSVC 128/128. Zero warnings in the new files on both |