Belső működés · §4

Storage layer

nucleus-storage

Ez az oldal a nucleus saját dokumentációjából készül, ezért angol nyelvű.

Bottom to top: page format → pager → buffer pool → B+tree → WAL → store. Every layer reaches files only through nucleus-platform.

4.1 Page format (page)

A database file is an array of 8 KiB pages (PAGE_SIZE); page n is at offset n × 8192. Every page starts with a 24-byte header (little-endian):

Offset Size Field
0 4 CRC-32C of bytes 4..8192
4 1 page type
5 3 reserved, zero
8 8 birth: the commit (pager seq) that made the page durable (§M14.13; 0 in files from before)
16 8 the page’s own id

Payload: 8168 bytes (PAYLOAD_SIZE). Types below 16 belong to the pager (0 unused, 1 header, 2 free list); the B+tree uses 16 leaf, 17 internal, 18 overflow. Verification names the failure: checksum mismatch, never written (all zeros), page id mismatch (misdirected write). crc32c is CRC-32C by the CPU’s instructions where it has them (ARMv8 CRC, SSE 4.2; nucleus_kernels::crc32c; three streams over neighbouring blocks at once, joined by shifting with tables — Mark Adler’s crc32c.c, Intel’s iSCSI paper —, an 8 KiB page in 353 ns rather than one stream’s 934 on Apple M-series, §M14.20 W5), else portable and table-driven — the same value, checked against the RFC 3720 vectors and against each other.

4.2 Pager (pager::Pager)

The rule: the durable state is immutable. write_page accepts only pages allocated since the last sync (else Error::Immutable). Changing a committed page means copying it; a freed committed page goes to pending and becomes free after the next commit. A page allocated and freed within one epoch is free at once. So a crash at any moment leaves the last committed state untouched, and sync moves to a new one with one header write.

API. create, open; read_page, read_pages (a run of neighbouring pages in one read, each verified; reads go through a buffer each thread keeps, so a page is copied once into its own memory and nothing is zeroed first), write_page, is_writable, allocate (lowest free page, else grows the file — on disk ahead of the pages, by zeros an eighth of its length at a time, 1 to 64 MiB: a write into blocks the file has costs a fraction of one that makes APFS allocate them; zeros past the header’s page count are not the database’s — but a run of 16 pages or more written past the end (write_run, a checkpoint’s appended pages) grows the file by its own write, since zeros ahead of it wrote its pages twice; pages it skips read as never written), free (refuses double frees); meta/set_meta (16 u64 slots committed atomically with the pages); sync, close; check (on-disk free list vs. memory, no page in two places), accounting (free / pending / free-list pages / allocated). A read checks its page id against the page count and the poisoned flag mirrored in atomics, not under the pager’s lock (§M14.20 W5: a parallel scan’s workers queued on it — 14 % of TPC-H Q1’s time on row tables).

Header — pages 0 and 1; copy seq % 2 holds sequence number seq; a commit writes the older copy, open takes the valid copy with the highest seq. Payload: magic NUCLEUS\0, format version (4, 5 encrypted; files of versions 1 — before compressed values and key prefixes — and 2 and 3 — before key heads — are read, and say 4 or 5 from their next commit on, so an older build refuses them rather than misreads them), page size, seq, page count, first free-list page, free count, 16 meta slots.

Free list — a chain of free-list pages (next u64, count u32, then up to 1019 page numbers each), rewritten by every commit into pages the previous state does not use; the previous free-list pages are free in the new state. Nothing leaks: after a crash every page is live, free, or beyond the page count.

sync order: write the new free list; extend the file to the page count (unwritten allocated pages become zeros); a sync ordering the pages before the header (sync_order); write the header copy; fsync. Any failure poisons the pager.

A commit in two halves (§M14.20 W4): sync is freeze(meta) then commit_frozen. freeze, under the pager’s lock, takes the state as it is — the pages allocated so far, the meta slots — as the next to commit, computes its free list (its pages taken out of the free set, or past the end) and returns at once; its pages are frozen: no longer writable (a writer copies them, as it copies durable pages), still written back (write_page accepts them; is_frozen). Writing goes on meanwhile in pages the frozen state does not use — allocated from its free pages or past its end; a page freed after the freeze is free only after the next commit. commit_frozen writes the free list and the header without the lock. A write past the pages the file is known to hold takes the lock, as the commit’s extension of the file does, so the two never race (by construction; a single-threaded simulation cannot interleave them). One commit in flight at a time. create builds the file as <path>.creating, syncs it, renames it into place and syncs the directory.

Births and dead lists (§M14.13, ZFS’s). write_page stamps a page with its birth, the commit that makes it durable — the next one for a page allocated now, the one in flight for a frozen page, the one after it for a page allocated while one is in flight — in the header’s LSN field; fixed at allocation, so a page copied on write is never older than its children. set_space(branch, Space { origin, points }) tells the pager what a free in a branch means (none: a plain free, as for the main branch without branches and NO_BRANCH): release(id, branch, birth) keeps a page born at or before the branch’s origin (an ancestor’s), puts one of its own born at or before its latest branch point on that point’s dead list (take_dead, dead), and frees the rest as free does; keeps says which, beforehand. next_seq is the commit the next freeze makes.

4.3 Buffer pool (buffer::BufferPool)

fetch(id) -> PageRef pins a page (dropping the PageRef unpins); PageRef::read() / write() take the frame’s reader/writer latch, and write() marks it dirty — after checking the pager’s rule, so a missing copy-on-write fails at once. create(type) allocates a page into a frame; free(id) drops it (must be unpinned; a dirty page of a commit in flight is written back first — the frozen state still holds it: from the commit’s freeze until its flush_frozen ends, kept for that flush to write with its other pages, in the file’s order, and else at once). free_in(id, branch) is a branch’s free (§M14.13): with the page’s birth(id) (the pager’s for a page not durable yet, else the header’s) it asks Pager::keeps and leaves a page another branch still reads cached, then Pager::releases it. A write-back stamps the birth into the cached page too, so the header in memory says what the file does. flush_frozen writes back the dirty pages of the commit in flight while writers go on — and readers: in the file’s order, each run of neighbouring pages (up to 1 MiB) with one write (Pager::write_run; PostgreSQL’s checkpointer sorts its buffers so), each page copied under its shard’s read lock, so hits go on and a load or an eviction waits for one page’s copy, not the shard’s write (holding the shard’s write lock through it, a checkpoint after a large build held searches up for seconds). A frozen page does not change, so its dirty flag is cleared once its run is written: an eviction meanwhile writes the same contents again rather than dropping a page the file lacks. One flush at a time. Eviction is the clock algorithm over unpinned frames; dirty victims are written back first. flush writes every dirty frame, sync = flush + pager commit. The frames are split into up to 16 shards (at least 256 frames each; a page always in the shard of its id), each with its own page table, free frames, clock hand and reader/writer lock, so a parallel scan’s workers do not queue on one lock. A hit takes no lock: it finds the frame in its shard’s index (an open-addressed table of atomic words, written under the shard’s lock, read without it), pins it, and checks the frame’s owner is still the page — an eviction (or a free) clears the owner before it looks at the pins, a hit pins before it looks at the owner, so one of the two sees the other; a page not in the index (or found changing) is looked for under the shard’s read lock. Hits are counted on stripes, a cache line each, a thread adding to its own; a frame’s pin count and reference bit are atomics, the bit written only when it changes, and the page table hashes a page id with one multiplication. Each shard and each frame takes a 128-byte cache line of its own, so threads pinning neighbouring frames or finding pages in neighbouring shards do not write one line. A tree’s root, read by every descent, is read from the thread’s own copy (read_copy; a few a thread, made the second time a root is met unchanged): good while its frame holds the page with the same version — a frame’s version moves with every write latch and every page put in it — two loads, no pin, no latch. A tree’s pages change only under its store’s lock held for writing, which its readers exclude, so a copy found good stays so while the reader holds the tree. The store’s lock is striped (striped::Striped, 16 stripes): a reader takes its thread’s stripe’s read lock, a writer every stripe’s — tried, never waited for: the stripes taken kept while the others are tried again, and readers holding no read guard wait meanwhile, asleep on a condition variable (else readers coming back at once starved the writer: CI’s Windows and iOS runners hung; and readers waiting by spinning took the processor from those the writer waited for: Windows and Android stalled); the writer itself spins briefly, never yielding (on Windows a yield gave a busy reader the processor for a whole time slice: ~390 ms a write), then sleeps until a reader letting a stripe go wakes it (not polling with sleeps, whose length is a timer’s tick on some systems), and lets all go after 5 ms — a window doubled each time — to take them again later (so a reader that reads again never waits for a writer, and one waiting for a thread that reads waits a while at most); the tables sit in an Arc in each stripe, which a writer holding them all takes out to change them. Ten threads’ reads by key (crates/kv/examples/lookups.rs, 2,000,000 keys cached) went from 1.6× one thread’s speed to 5.7×: the one lock word, the root’s pin and latch and its shard’s lock, written by every read, had been most of their time (the Linux kernel’s big-reader lock and BRAVO’s reader slots; LeanStore’s and Umbra’s version-checked reads, safely, as a validated copy). A read by key that needs only the first entry at or after a key — a row’s newest version at a snapshot, where no intent is in sight — descends without a cursor (BTree::seek_one: no path kept, the entry read into buffers its thread keeps), a range made only where that entry does not settle it: one thread’s reads 860 → 780 ns. A miss reads the page without any (and reads again if a page was written back meanwhile), so threads reading cold pages do not wait on each other. read_ahead(ids) reads a run of consecutive page ids (up to 16, 128 KiB — PostgreSQL’s io_combine_limit) with one read, into frames not yet referenced, so the clock takes them first if unused; pages cached meanwhile are kept, and a write-back meanwhile drops the rest. A run in the clear is read into one buffer its pages share (Page::of_run, an Arc): one allocation a run and no copy (8 KiB allocations serialized a cold scan’s threads in the system allocator); a page is copied out when written to, and one kept while half or more of its run has gone is copied out at its next hit, the buffer left to the rest (a page in use holds 8 KiB, not the run’s 128). A B+tree cursor moving to a leaf that is not cached reads the parent’s next leaves with it, the window growing with the leaves it has moved through since its last seek (1, 2, 4 … 16, as Linux’s read-ahead ramps up), so an index lookup’s entries across a leaf’s end read one page and a scan soon reads 16 at a time (§M14.20 W5: with the pager’s lock gone, pread 23 % → 10 % of TPC-H Q1’s time on row tables). A leaf a scan moves on to (not the first after a seek) is read whole before its entries, a byte of each 64 (View::touch): its lines’ misses overlapped, not left to the hardware prefetcher, whose cover of a leaf read entry by entry turned on the page’s layout (issue #1: TPC-H Q6 on one worker 806 → ~711 ms). Errors: PoolExhausted (every frame pinned), Pinned. stats(): hits, misses, evictions, write-backs.

4.4 B+tree (btree::BTree, node)

Byte-string keys (≤ MAX_KEY = 1024) compared bytewise, values of any size. Node format (format version 4): kind (5 leaf, 6 internal), count, the key prefix’s length and offset, leftmost child, the key prefix all the node’s keys share, then a slot a key — its cell’s offset and its head, the first four bytes of the key past the prefix, big-endian — and cells packed from the end. A search compares the slots’ heads as integers and reads a cell only where a head ties with the key sought’s (View::search; LeanStore’s heads, prefix truncation in internal nodes as in leaves): a point lookup in a 2-million-row tree 1045 → ~800 ns. Nodes of versions 1–3 (kinds 1–3: no heads, a 12-byte header, an internal node without a prefix) are read as they are and rewritten in the new form when changed. Leaf cell klen u16, flags u8, vlen u32, key, value; a cell over 2048 bytes moves its value to an overflow chain (next u64, len u32, data) and stores first page, length. Internal cell klen u16, child u64, key; child i holds keys in [keys[i-1], keys[i]).

Compression (§M14.20 V5). Key prefixes: a leaf (kind 3) stores the prefix its first and last keys share — so all its keys — once, its cells only the rest; sizes, splits and packing count the prefix once, so a leaf holds more rows (a table’s keys share their table and index ids and the high bytes of their primary keys: a million-row table’s file 93 → 61 MB). Readers compare a key as prefix and rest (node::KeyRef). Values: a value of 1 KiB or more is stored compressed when that saves an eighth (shorter ones save little and would be decompressed at every read — a TPC-H scan spent a third of its time so; values stored compressed before read as they were) — an LZ block (LZ4’s block format, lz.rs, no dependency), flag 2 in the cell (length u32, block) or flag 3 in an overflow chain (first page, block length, length); reads decompress, checking every length and offset, so a damaged block is an error. The decoder copies as LZ4’s does, in fixed 16-byte pieces that may run past a sequence’s end into room left after the output (a match overlapping itself a byte at a time for 16 bytes, then 8 at a time a multiple of its period back), so a short sequence is a few loads and stores, not a call to memmove: 2–2.5× the plain decoder on hits’ text (1.2 → 2.4 GB/s in 1 KiB blocks, 1.7 → 4.1 in 64 KiB), tested against it on blocks whole, cut and damaged. Large text and documents shrink; rows of a few short columns do not (too little repeats within one).

Checksums: CRC-32C — the CPU’s instructions where there are (chosen at run time), else slicing-by-8 (eight bytes a step, tables built at compile time); the same values as the bytewise definition, tested.

Copy-on-write: a node is rewritten in place only if its page is writable; otherwise copied to a new page (old one freed) and the parent updated, up to a new root. Balance: split by bytes; a non-root node under MIN_FILL (¼ page) after an insert or delete is merged with a sibling, or the pair is split evenly; an internal root with one child is replaced by it.

API: create, open(root), root, get, insert, remove, set_workers(n), apply_sorted(ops) / insert_sorted(entries) (sets and removals sorted by key, without repeats: each node read and written once for all the keys reaching it; full leaves and full internal nodes packed to about 7/8, a small last piece evened out with the one before — a sorted build’s appends leave its pages full, as PostgreSQL’s nbtsort does; neighbours a batch of removals left under MIN_FILL merged until they are not, seams of merged internal nodes included; two leaves too large together are cut as a batch cuts them, by their size as stored — two leaves whose keys each shared a long prefix may share none together, so their even halves could each outgrow a page), range / range_rev (bounds; going forward a range checks its end on a key before reading the key’s value, so the first entry past the end — perhaps long, compressed, in overflow pages — is not read), cursor (seek, seek_after, seek_near, seek_end, next_entry, prev_entry), seek_group (up to GROUP = 8 keys’ first entries, the descents a level at a time: each level’s pages and their first kilobyte read for the whole group before any is searched, so that their cache misses overlap — group prefetching, AMAC; a page the keys next to each other share — the root always — fetched and latched once; what a secondary index’s row fetches use), destroy, check (ordering, separators, equal leaf depth, minimum fill, overflow lengths, no page used twice; returns the pages used). &self reads, &mut self writes: callers wrap the tree in an RwLock (D11). Reads in place: get and cursors read pages through node::View (binary search over the slots’ key heads, a key, a child or an entry checked as decode checks it) and copy out only the entry returned; a cursor keeps its leaf pinned and its path as page ids, and seek_near stays in its leaf when the key falls inside it (seeks to nearby keys in order — a commit’s checks — mostly without a descent). Writes decode nodes into structs, but a sorted batch’s leaves (apply_sorted, so every commit): a leaf’s cells and the new entries are merged by reference and encoded straight into the page (node::encode_leaf; the pieces cut as before, checked against the decoded packing), so a commit that touches every leaf allocates nothing per entry. A batch reaching many leaves (64 or more) prepares them on workers (set_workers; the store gives the platform’s CPUs, the simulation one): the leaves it reaches found first, then the workers claim them in order (a counter) and merge and encode each into a page of its own, at most 128 per worker ahead of the walk, while the walk installs each as it reaches it — the page swapped into the pool’s frame, not copied — and rebuilds the internal nodes; pages freed and taken in the order one thread takes them, so the tree is the same page for page (tested so, with a filter and without, and through a pool of 48 frames that evicts all the time). A worker reads only its leaf and the leaf’s overflow pages, which the walk touches only once it installs that leaf; the two sides meet without a shared lock per leaf (each result in its own slot; a condition variable only for a worker too far ahead, or the walk finding its leaf not ready). Compaction filter: apply_sorted_filtered(ops, &dyn LeafFilter) lets the layer above drop entries of the leaves the batch rewrites anyway — drops(entries, drop) sees a leaf’s keys and short values after the batch went in, one leaf at a time on whichever thread prepares it, so it must be a pure function of them (the MVCC engine drops the versions no snapshot sees, §5); a dropped entry’s overflow pages are freed with the rest.

4.5 Write-ahead log (wal::Wal)

Segments named by start LSN (20 digits, .wal); an LSN is a byte position in the log. Record: len u32, crc u32 (CRC-32C of LSN ‖ payload), lsn u64, payload. append → LSN past the record; sync_to(lsn) is group commit (one fsync for everything appended; waiters for earlier LSNs return at once); replay(from, f); truncate_before(lsn); size, start, end, durable. For erasure (§M14.24 R2b): roll() starts a new segment if the current one holds a record (PostgreSQL’s pg_switch_wal), so a checkpoint after it can drop every older record; truncate_before_zeroed overwrites the dropped segments and every spare with zeros, synced, before they are deleted or kept as spares (in place; on APFS the old blocks are the file system’s).

Preallocated and recycled segments (where writes_in_place; PLAN.md §M14.28 L0). A segment is grown ahead of its records by zeros, a mebibyte at a time up to the segment size, so a commit’s sync writes its block and no length; the segments a checkpoint drops are renamed to spares (<20 digits>.spare, kept up to as many as that checkpoint dropped, the rest deleted) and renamed into the next segments (PostgreSQL’s recycled segments). A spare’s old records carry older LSNs, which the checksum folds in, so none passes for a record at its new place. Elsewhere (APFS) segments grow as written and dropped ones are deleted, as before; spares found there are deleted.

Crash rules. open cuts a torn tail of the last segment — in a preallocated one, writes zeros over the rest of it if what follows the records is not zeros or a record older than the segment (a torn record of its own, whose bytes a later record must not leave behind); a segment before the last must end where the next begins, or it is corruption. Before a new segment is created, the previous one is synced — an ordering sync (sync_order): the sync that makes a record of the new segment durable flushes it too, and a barrier orders it before the new segment’s directory entry, so a non-last segment is never torn — and so is its directory entry. (Kept, not dropped as §M14.20 W4 first planned: it is what lets open tell a torn tail from corruption; PostgreSQL also syncs a finished segment.) Segments wholly before a checkpoint are deleted together with one directory sync (W4; they were one sync each): a crash may keep any of them, and open_from(…, from) — the store opens from its checkpoint’s LSN — deletes again those before the segment holding it; a log left with no segment starts at from (a segment created there whose entry a crash lost held nothing durable). Before dropping any, truncate_before syncs the directory: the segment holding the checkpoint may be new, its entry not yet durable, and a crash that kept an older segment but lost it would leave a log ending before the checkpoint (found by the simulation with recycling, 2026-11-06; the deletions before had the same window). A failed fsync poisons the log.

4.6 Store (store::Store)

The B+tree made durable by the WAL. Store::open(platform, dir, opts) takes an exclusive lock on dir/LOCK (FileSystem::lock: flock / LockFileEx on the OS, a lock table in the simulation that a crash clears) and holds it as long as the store — a second process (or store) fails with Error::Locked (“in use by another process”) instead of corrupting the database — then creates dir/data and dir/wal/ if needed and recovers; returns Recovery { meta, replayed }. The lock also tells whether dir/LOCK is still the file it locked (Lock::still_here: the same device and inode on Unix; elsewhere always true — Windows will not move a directory with files open in it): a checkpoint asks before it writes and removes files by their names, an opening before it removes stale ones, and a store whose directory was removed or replaced while open — another store made at the path — poisons itself rather than touch that one’s files. write(&Batch) appends the batch to the WAL and applies it under the tree’s write lock (visible at once); wait_durable(lsn); commit = both. Each write takes the batch borrowed or owned (WriteBatch): an owned one’s keys and values move into the leaves’ cells instead of being copied (the transaction layer’s commits and vacuums hand theirs over). write_filtered(&Batch, filter) applies it through a LeafFilter (§4.4) — not logged: replay applies the batch without it, so what a filter drops must be garbage its layer can find again after a crash. write_covering(&Batch, covered) logs a batch of deletes with key ranges it covers — ranges whose entries, in the tree as it is, are all among its deletes: replay deletes everything left in them, what a filtered write dropped there and replay brought back too, all of a batch’s ranges at once (Tables::remove_ranges: the B+tree’s entries in one sorted pass, an LSM tree’s range tombstones merged into its memtable’s in one — a vacuum’s batch covers a range per key, and a descent from the root for each entry made a recovery replay ~13 MB of WAL a second, now ~55) (WAL batch version 2: version 1’s layout, then the ranges; version 1 is still written and read for a batch without). write_deferring(&Batch, deferred, filter) logs puts with a batch but keeps them out of the tree (WAL batch version 3: version 2’s layout, its ranges maybe none, then the puts): they wait in memory (Store::deferred(), a BTreeMap; taken while read()‘s guard is held, the two agree — an entry is in one or the other) and go into the tree together at the next checkpoint’s freeze, or with the batch that brings more than DEFERRED_MAX (4096); replay puts them back in memory (and open checkpoints after a replay); a later batch’s put or delete of the key replaces the deferred entry. A memtable for entries read seldom — the commit times (§5.2), each of which would otherwise rewrite a leaf of its own per commit. write_moving(&Batch, covered, moves) logs some of a batch’s puts as moves (WAL batch version 4: version 3’s layout, an op tagged 2 a put without its value, the key it moves from given instead — the bytes it shares with the put’s key counted): the batch carries the value the source key holds, which the caller read with writes held off, and replay reads it from the tree, where the log replayed in order has brought it (gathered writes applied first; a source gone puts nothing). The vacuum’s versions made of committed intents (§5.3): their keys logged, not their rows again — the vacuum after TPC-H’s load wrote 0.94 GiB instead of 1.81. Every batch is now written as version 5: version 4’s sections, each op’s key given by the bytes it shares with the key before it and the rest, every length in an op a LEB128 number. A batch’s keys are sorted, so each key repeats most of the one before (versions 1–4 are still read). write_rekeying(&Batch, covered, &Rekeying) (WAL batch version 6: version 5’s sections, then key ranges and pairs of an old and a new key end, all of one length) rewrites, in each range, every key ending with an old end to end with its new one, the value kept (BTree::rekey): the leaves in the range listed by a walk of the internal nodes, looked through on the tree’s workers (read only), then each leaf patched in place on one thread — the key’s last bytes written over, and its slot’s head where the end reaches into it, where the new key keeps its order between its neighbours and separators and the end lies past the leaf’s prefix; a leaf a checkpoint holds copied to a new page, its parent’s pointer changed so. A key that cannot be patched so is moved (deleted and put). The log holds only the ranges and the ends: replay rewrites the same keys, the log having brought the tree to them. The vacuum makes committed intents versions so (§5.3): after TPC-H’s load it logs almost nothing (0.27 GiB with moves before) and takes ~1.4 s instead of 3.3 (issue #4). A batch whose keys are all distinct (every batch the engine writes) is applied in one sorted pass (apply_sorted); otherwise op by op, in order. write_unlogged(&Batch) applies a batch without logging it (D16): durable only once a checkpoint after it is, lost by a crash before — the transaction layer marks what it writes so first, in a logged record, and checkpoints before the commit that needs it (§5.2). read() gives the tree’s read guard; get. checkpoint() is checkpoint_begin() then finish() (§M14.20 W4): checkpoint_begin, under the writer lock, freezes the tree as it is — root, the LSN applied, the last batch’s meta — (Pager::freeze) and returns; finish, writes going on, syncs the WAL up to that LSN, writes back the frozen pages (flush_frozen), commits the pager (commit_frozen) and truncates the WAL. Writers wait only for the freeze; one checkpoint at a time; checkpoint_past(bytes) runs one only if the WAL since the last (after any running ends) is past bytes. wal_since_checkpoint() tells callers when to checkpoint. A Batch is meta: u64 (the transaction layer’s commit timestamp) and ordered puts/deletes; its WAL encoding is versioned. Keys over MAX_KEY are refused before logging. Any failure poisons the store. Recovery gathers the replayed batches’ puts and deletes, up to redo_bytes, and applies them sorted by key — for each key the last logged — in one pass over the tree (apply_sorted), each leaf read and written once a pass rather than once a row; a batch removing ranges is applied as logged, after what was gathered (page-ordered redo, issue #14). Recovery checkpoints once if it replayed anything; a checkpoint the WAL does not line up with (ahead of its end, or its start after it) is corruption. Options: cache_pages (default 1024), wal_segment_size (default 16 MiB), redo_bytes (default 64 MiB; the kv layer gives it an eighth of the machine’s memory; 0: each batch as logged). Meta slots: 0 the main tree’s root, 1 its checkpoint LSN, 2 its last meta, 3 the branch directory’s root.

Branches (§M14.13 B1). A Store is one branch of the database in dir; open gives the main one (MAIN, named MAIN_NAME = main) and opens and recovers every other. create_branch(name) makes a branch of this one in a checkpoint: its tree starts as this one’s root at the freeze (constant time and space), its origin the commit the freeze makes; branch(name), branches() (BranchInfo { id, name, parent, origin }), info(), recovery() (a new branch’s meta its parent’s). Each branch has its own tree, writer lock and WAL (wal/ the main branch’s, branches/<id>/wal/ another’s); all share the pager and the buffer pool, and a checkpoint takes every writer lock in id order, settles every tree’s deferred puts and freezes them all in one commit. The branch directory, a tree of its own (meta slot 3, frees plain): b+id → parent, origin, root, checkpoint LSN, meta, name (rewritten only when changed); n+name → id; i → the next id (ids are never reused); d+branch+point+page → birth, the dead lists, drained from the pager at every checkpoint. A free in a branch follows the pager’s rules above: a page an ancestor still has stays, one a branch of it may read waits on the dead list of the branch’s latest branch point. drop_branch(name) (not the main one, not one with branches: Error::Branch) in a checkpoint: the branch’s pages born after its origin freed (BTree::release_younger, a walk that skips a subtree whose root is older — it costs what the branch changed), its records gone, its parent’s dead list for its point either moved to the parent’s previous point (the pages born by it, still read through it) or freed — unless another branch shares the point —, its WAL files deleted after the commit (and, by open, those of branches the directory does not know); its handles fail with Error::Branch from then on. reset_branch(name) drops and makes it again from its parent in one checkpoint (a new id, the old handles fail). A branch costs what it changed plus what its parent freed since that it still reads. diff_ranges(base) (§M14.18 O3, an incremental backup’s) gives the key ranges this branch’s tree and base’s may differ in: this tree walked, a subtree whose root was born by base’s origin skipped, then base’s, a subtree skipped only where this tree reaches the same page between the same separators — exact for any two trees of the file, whatever either wrote since, and costing what changed (BTree::diff_ranges). check_pages() checks every tree and that every page is in exactly one place — in use (a tree, the directory, a dead list, allocated) or free (free, pending, holding the free list). Branch names: 1–63 ASCII letters, digits, -, _, . (valid_branch_name). A branch’s tag (create_branch_tagged(name, tag), tag(), set_tag(t)) is a number the layer above keeps in its record — committed with the branch, a change with the next checkpoint — for work a crash must not leave half done (B4’s roll-back).

Scrub (§M14.24 R2b). scrub() → Scrubbed { pages, wal_bytes } removes from the files what the tree no longer holds: a checkpoint, the WAL rolled, a second checkpoint (it frees the pages the first replaced; every checkpoint while a scrub runs truncates with zeroing), then Pager::zero_free writes a zeroed UNUSED page over every free page under the state lock and syncs (SQLite’s secure_delete, at once rather than at each free). Writes go on meanwhile. What then remains is in the process’s memory and, on a copy-on-write file system or a remapping disk, in blocks no file names. Before it, an erasure renews the tree’s separators in the ranges it reached (BTree::renew_separators, issue #25): a separator is a leaf’s first key as a split found it, kept in the internal nodes however that key was removed since — a row’s primary key, an index entry’s — so each that is not the first key of the subtree after it is made that key (one the tree holds), the nodes on the way written anew and split where a longer key no longer fits; the scrub’s checkpoints then free and zero the old ones. It reads the internal nodes and only the first key of each leaf below them (in place): ~3% of a FORGET SUBJECT on 100,000 rows. scan::find(fs, dir, needles) is the proof: every file but LOCK searched raw (a mebibyte at a time), and the data file’s leaves and internal nodes — reachable or free — decoded: keys put together from their shared prefix (a separator split across it is found whole), packed values decompressed, overflow chains read; results once per file offset (per page for the data file). An LSM tree’s runs keep deleted entries until merged, so the scrub first has each engine merge all its files into one without them (Engine::compact_all: for an LSM tree, every run merged into the last level, its tombstones and the versions its garbage filter drops left out; one merge at a time with compaction), and the checkpoint after removes the runs no manifest names any more, each overwritten with zeros and synced first while a scrub runs (issue #26). On an LSM table of 100,000 rows a FORGET SUBJECT takes ≈440 ms (≈360 ms on the B+tree). Store::find_bytes (what Kv::find_bytes calls) also reads each run’s blocks, decompressed, through the store’s file system for the engines (sealed on an encrypted database). Needles under 4 bytes are not looked for; each is anchored at the four-byte window the fewest other needles share (then the least like zeros and runs), and a place reaches the map of anchors only through a bitmap of their hashes (2^20 bits) — ~80 ms for 100 needles over 96 MiB.

Engines (engines, §M14.28 L1). A key range — a table, an index, a partition — can be routed to an engine other than the B+tree: add_engine(start, end, kind) → the route’s id, routes(). Routes are the store’s, apart and sorted (engines/routes, CRC-32C, written atomically); every key outside them — the reserved keys, the catalog, every table not routed — stays the B+tree’s. A branch’s tree is Tables: its B+tree and one engine a route (read() hands it out; tree() the B+tree, get, range, range_rev, cursor across all of them). A commit stays one WAL record whatever engines it touches — the record is the store’s, written before any engine sees it — so it is atomic across engines without two-phase commit; replay routes its ops the same way. The engines hold apart ranges, so a scan is their pieces one after another (Scan, TablesCursor), no merge. An engine keeps its state in memory between checkpoints, as dirty pages are; a checkpoint saves each branch’s in engines/<branch>-<route>-<lsn>, written and synced before the checkpoint commits, the older ones removed after it (and at open: of checkpoints that never committed, of branches gone); open loads the file of the checkpoint it starts from and replays the WAL after it. A branch starts with a copy of its parent’s engines (Engine::fork). diff_ranges adds a routed range whole where either side’s engine holds anything (an engine keeps no births). add_engine refuses (Error::Engine) an empty range, one meeting another route, and one the B+tree holds entries in on any branch; it holds every writer and tree while it writes the routes, then checkpoints. The Engine trait: get, scan(start, end, reverse), apply(ops), remove_range, is_empty, fork, prepare and saver (the state as of a checkpoint, taken under the writers’ locks and saved in Checkpoint::finish without them), files, and job / install for background work (§M14.28 L4a). EngineKind::Map is the trivial engine that proves the boundary — a sorted map saved whole at each checkpoint, not for tables of any size; the LSM tree (L2) is the engine the boundary is for. With no route, every call goes straight to the B+tree. On an encrypted database the engines’ files — runs, manifests, the map engine’s, the routes — are sealed by the file system the store hands them (sealed::SealedFs, §M14.28 L4e; Encrypted data files below), so no engine knows.

The LSM tree (lsm, §M14.28 L2; EngineKind::Lsm). Writes go to a memtable (puts, point tombstones, range tombstones for a removed range); the store’s WAL is its log. A checkpoint sets the memtable apart under the branch’s write lock (Engine::prepare, a swap; Engine::saver takes it and the runs as they are) and writes it as an immutable sorted run with no lock held — reads and writes go on (L4a) — and a manifest naming the runs in engines/<branch>-<route>-<lsn> before the checkpoint commits; the run joins the levels at the engine’s next change. Runs are engines/run-<branch>-<route>-<lsn>-0 (a flush) and …-<wal end>-c<n> (a compaction), shared between branches by name (a branch forks its parent’s), removed once no branch’s engine names them (Engine::files: the runs of its levels and of its last manifest). Reads merge the memtable(s) and the runs newest first: the first source holding a key decides, a range tombstone hides the key in every older source, and a source’s own points are newer than its own range tombstones. A run’s file: blocks of about 4 KiB (a key, put or tombstone, a value), each compressed by lz when that saves an eighth and closed by a CRC-32C; the block index (each block’s first key), the last key, a split-block Bloom filter (Parquet’s: a 256-bit block a key, eight bits set, one per 32-bit word — one cache line a probe, ~1 % false positives at 10 bits a key), the range tombstones, a CRC-32C, a 32-byte footer with the magic ncrun\0\0\x01. Compaction is lazy leveling with a fan-in of 4: tiered upper levels (four runs merge into one run of the next), one run at the last level, which the runs arriving from above merge into while it is at most four times their size (a level forms above it when larger); a merge into the last level drops tombstones. Compaction is background work (L4a): Engine::job plans the next merge from the levels as they are (under the branch’s read lock), the job writes its run with no lock held — within StoreOptions::compaction_bytes_per_sec (0, the default: no limit), told the bytes as it goes and stopping when asked — and Engine::install takes it in under the write lock: the inputs are still the oldest runs of their tier (flushes since went first; one job at a time, Store::compact), or nothing is changed. A job’s file is in flight (Shared::in_flight, held while stale files are removed) until installed, so a checkpoint meanwhile does not take it for stale. Its run is durable with the next checkpoint’s manifest; a crash before opens the last manifest, whose runs are kept. The transaction layer runs Store::compact on a thread of its own (nucleus-compact), woken after each checkpoint; without threads to spare, after the checkpoint where it falls due. Bulk loads (L4b): keys a memtable is given in ascending order past all it holds — D16’s writes into a fresh range always come so — are appended to a sorted vector at its end instead of its map (a key among them moves them into the map); past 64 MiB (lsm::SPILL) the vector is spilled as a run by the loader in Store::write_unlogged (Engine::spill: the writer lock held, readers going on; installed below the memtable when nothing of the memtable’s range tombstones or of the memtable set apart touches its keys), so a load is not held in memory whole. A run’s file is written in 1 MiB writes. A flush takes the first free name run-<branch>-<route>-<lsn>-<n> (two checkpoints may share an LSN when only unlogged writes came between). The block cache (L4c): a block read is decoded once — its bytes and each entry’s key offset, searched in place — and kept in one cache for the process (lsm::CACHE: CLOCK in 16 shards, as large as the largest store’s StoreOptions::lsm_cache_bytes, 64 MiB by default; nucleus-kv gives it cache_bytes, a budget it shares with the page cache: it holds what the buffer pools’ frames leave of it — buffer::FRAME_BYTES, the frames made so far — and at least a quarter, so a store of LSM tables has the whole of it for their blocks, issues #11 and #13). A look-up takes its shard’s lock shared — a block’s use marked by an atomic flag, the key hashed by mix — so a parallel scan’s workers do not wait on each other (issue #11). A forward scan reads a run’s blocks ahead (Ahead, issue #13): a part of a parallel scan whose blocks fit in 256 KiB reads them in one call, a longer range one block first and then reads doubled each time up to 256 KiB, never past the block that holds the range’s end — each block then checked, decompressed and decoded on the scan’s worker as it reaches it. Lookups and scans fill it, compactions read through it without filling it; blocks are keyed by a run’s number in the process, so a run reopened after a crash is never served another’s. Versions dropped by merges (L4d): Store::set_compaction_filter takes a maker of a LeafFilter as of when a merge begins — the transaction layer sets its Collect, the filter its commits apply to the B+tree leaves they rewrite — and a merge shows it 512 entries at a time (those with values); above the last level it asks drops_above, which keeps a key’s newest tombstone at or below the watermark (older versions may be in runs not merged). Versions dropped by commits (L5): a commit’s filter reaches the engines too (Engine::apply_filtered, apply by default); the LSM tree shows it, as drops_above, the memtable’s entries sharing the escape(user) 00 00 prefix of each key written — so a key written over and over keeps a few versions in memory, as in a B+tree leaf, not one a write until a save (a read steps over each one kept: 5000 versions of a key made its read 12 → 420 µs). A commit hands its ops over (Engine::apply_owned: keys and values moved into the memtable, not copied), and where its user keys are many beside the memtable’s keys (one in 32 or more) their versions are found by one walk over the memtable from the first, a merge join, not two descents of the map for each (issue #12). The memtable’s ascending tail is left as it is. Scans in parallel (L5): Engine::split_keys cuts a range into parts for a parallel scan’s morsels — the B+tree’s leaf separators where no route is, and within one engine’s range that engine’s: the LSM tree’s runs’ blocks’ first keys and its memtables’ sampled keys (a key put in the map is kept in a sample when its hash is a multiple of 64; the ascending tail every 64th, by index), evenly chosen; across engines one part. A merge compares its sources’ next entries where they lie — a memtable’s by reference, a run’s in its decoded block (Src::ready, key, value, bump) —, each source’s key once an entry (the older sources holding the same key marked as it goes and passed over), a run’s block checked against the range’s end once when its last key is within it; an entry is copied only into the buffers it is given in. A forward scan takes the merged entries 256 at a time, as a B+tree leaf (Entries::leaf_entries, through Tables’ pieces, to the transaction layer’s callback); one source is read straight, unmerged — a run’s block, or 256 of a memtable’s entries, a call (issue #11); a scan leaves out the sources that hold nothing in its range (an empty memtable, a run whose keys are all outside it and that has no range tombstone).

Tables of the LSM engine (§M14.28 L3). CREATE TABLE … WITH (engine = lsm) (or btree, the default; the session setting default_table_engine names the engine of a table that names none, a partition takes its parent’s unless its own WITH names one) routes the table’s key range — its data prefix 01 | id, rows, indexes and column segments alike — to an LSM tree: catalog::create_table asks the transaction (KvTxn::engine_of, KvTxn::add_engine, on the store’s add_engine_if_free, the user keys escaped — the escaping keeps prefixes and order, so every version of every key in the range is in it). The route is durable at once, on every branch, whatever becomes of the transaction; table ids come from a per-branch sequence, so a later table of that id — the transaction rolled back, or another branch’s — finds the range routed: an LSM table takes the id, a B+tree table passes it over, as an LSM table passes over an id whose range is not free (up to 1000 ids, then 54000). Two branches making a table of one id at once, one of each engine, may leave the B+tree one’s keys in the LSM tree — the right rows in the other engine. The record keeps the engine (table record version 22), nc_catalog.tables.engine shows it, and a restore routes an LSM table’s range when its definition comes, before its keys (the catalog’s sort first). On an encrypted database the runs are sealed (§M14.28 L4e). DROP TABLE, DELETE and a vacuum delete key by key — tombstones in the LSM tree, merged away by compaction; range tombstones there wait for L4’s compaction by the oldest snapshot.

A table’s engine changed online (§M14.28 L3b). ALTER TABLE t SET (engine = lsm | btree) (convert::set_engine; outside a transaction block, 25001; an unknown option 22023) moves the table’s keys to a new table id whose range is the other engine’s (catalog::claim_id, as CREATE TABLE takes one), while other sessions read and write it — as MySQL’s ALTER TABLE … ENGINE= copies a table, but without stopping its writers. Everything under the old id moves: catalog::id_prefixes — the data prefix, the hidden row id’s counter (00 03), the statistics and their sample (00 04), the embedding jobs and next model’s vectors (00 17, 00 18). Four steps, each its own transactions:

  1. The claim takes the new id, records it (00 1C <old id> → the new id, catalog::moving_to) and writes the table’s record again — a write that read the record validated before (every DML statement’s writer does, and the vector and text indexes’ upkeep) fails and runs again — and, before it commits, has the transaction layer mirror the old prefixes onto the new ones (Kv::mirror, txn::Engine::mirror): from then on a transaction’s write of a key under an old prefix, in any transaction, holds the same write under the new one, in the same write set (so it spills, logs and commits with it). A mirrored write is not checked for conflicts at its destination, and no fresh range (D16) is taken within a mirrored prefix.
  2. The copy reads the old keys a part a transaction and writes them under the new prefixes — each part from where the last one ended, 1024 keys at first, doubled after a part that commits at once (up to 65 536, or 16 MiB), halved on each retry (down to 64). Its writes are checked as any are: a part that read a key before a mirrored write of it committed fails and runs again; a mirrored write committed after the part wins, being newer — so the copy ends equal to the source.
  3. The switch reads the record validated and writes it with the new id and engine, clearing the move’s record; writes begun before fail and run again on the new keys. The mirror ends after it.
  4. The clean deletes the old keys, a part a transaction; snapshots older than the switch read them as any deleted keys until the vacuum takes them.

Values hold no table id (index entries hold primary keys, a row’s chunks and a vector or text index’s entries are keyed by them), but a column copy’s directory once keyed segments by whole row keys: it now keys them by the keys’ suffixes after the table’s prefix (relative_directory, table record version 23; new tables), and a move first rewrites an older table’s directory (column_store::relativize, in one transaction — a directory has an entry per segment). Refused: a sealed table (each row is sealed with its key as associated data, §8.40), a table whose storage or a column’s type is being changed. A partitioned table moves each partition, then takes the engine for its next ones. One move of a table at a time per process; the mirror is the process’s, so a move cut short (a crash) leaves the table where it was and its copy stale — the next move, or DROP TABLE, removes the copy first, and the consistency check (check::check) knows a moving table’s copy.

4.7 Tests

  • pager.rs — round trips (simulated and real), the immutability rule, flipped bits, misdirected and unwritten pages, foreign files, header copies, free list reuse and spanning pages, poisoning, torn writes, and a crash at every I/O point (both modes): exact committed state, every live page intact, every page accounted for.
  • buffer.rs — hits, write-back on eviction, pinning, the copy-on-write check, reopen, and an 8-thread stress test on real and simulated files.
  • btree.rs — model-based property test with commits between epochs, deep trees, oversized keys, megabyte values, crashes after a commit, a crash at every I/O point of a 4-commit workload (exactly the last commit or the one in flight), and the million-operation test (--ignored; CI runs it on x86_64 Linux).
  • store.rs — replay, acknowledged vs. unacknowledged writes, WAL truncation, corruption, poisoning, concurrency, real files, and a crash at every I/O point (both modes, 8 seeds) of batches with unsynced writes piling up across segments and checkpoints; the same with batches written between a checkpoint’s halves (W4), and writers with a checkpointer thread on real files.
  • branch.rs (§M14.13) — a branch as a copy in constant space, writes on each side invisible to the other, names, a drop giving back what the branch changed, dead lists over several branch points dropped in either order, branches of branches, reset, real files, writers on two branches while a thread makes, writes, checkpoints and drops branches, and a crash at every I/O point (both modes) of writes, makes, a drop and a reset — the steps done or the one in flight, every page in one place.
  • engines.rs (§M14.28 L1) — a routed range read as one map (gets, scans either way, a cursor; the routed keys not in the B+tree; after a crash), the refusals, branches with engines of their own (and their files gone with a dropped branch), and a crash at every I/O point (both modes) of batches across the B+tree and the map engine with checkpoints between: a prefix of the batches, every acknowledged one, in both engines alike. The unit tests: every bound of a scan across two routes, either way, and a range removed across them; a map engine’s file saved, loaded and refused when damaged.

Mutations each caught by these tests: writing committed pages in place, reusing freed committed pages before a commit, header before data, skipped rebalancing, wrong split separators, segment creation without a directory sync, checkpoint without a WAL sync, a checkpoint that does not save the engines (and, by pager.rs’s first version: allocating from the durable free list, in-place create, no file extension).