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

Transaction layer

nucleus-txn

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

5.1 Versions (mvcc)

Each version of a user key is a store entry escape(key) 00 00 ‖ (u64::MAX − ts) big-endian → tag ‖ value (tag 1 value, 0 tombstone). escape doubles 00 into 00 FF, so the encoding is prefix-free and bytewise order is (user key ascending, timestamp descending). A read at ts is one seek to encode_key(k, ts). first_version(k) and after_versions(k) bound all versions of k. A user key may be at most 1014 bytes after escaping.

Intents. A large transaction’s spilled writes are versions too — write intents — stamped not with a commit timestamp but with the transaction’s id from the top of the range (intent_ts(id) = u64::MAX - id, at or above INTENT_FLOOR = 2⁶³), so a key’s intents come before its versions.

Reserved keys. No encoded key starts with 00 and a byte other than 00 or FF, so store keys from 00 01 to 00 FF are the engine’s own: status records 00 02 ‖ id → commit ts (a large transaction that committed), the next transaction id 00 03 → id (written before a transaction’s first intents, so no later one is given an id an intent has), the marks of fresh ranges a running transaction writes without the WAL 00 04 ‖ start → end (§5.2), commit times 00 05 ‖ ts (u64 BE) → µs (u64 BE) while a retention by time is set (§5.2), where the history begins 00 06 → ts (a replica’s seed: no snapshot before it, §9 “Read replicas”), and an older engine’s side area 00 01 ‖ id (u64 BE) ‖ user key → tag ‖ value, moved into versions when such a database opens. Every walk over versions skips them.

5.2 Engine and transactions

Engine::open(platform, dir, EngineOptions) (cheap to clone). begin() / begin_with(TxnOptions { isolation, read_only, at }). Transaction: get, put, delete, scan(start, end) (ascending; merges the transaction’s own writes), commit() -> Timestamp, rollback(); dropping it rolls back. savepoint(), release_savepoint(), rollback_to_savepoint() (nested; issue #24): from a savepoint on, each key’s first write notes the transaction’s own write of it before — held in memory, else its spilled intent (read from the tree), else none — and a rollback to it puts those back, deleting the intents spilled since of keys it had none of (under the commit lock); a release hands its notes to the savepoint outside it, the older note kept. While one is set, a fresh range’s writes go through the write set (not the WAL-less path, D16), a range written so before looked up in the tree by put_new. Timestamp is opaque outside the crate (principle 3): compared, printed and parsed (Display, FromStr), never computed with. Engine: visible, checkpoint, vacuum, intents_pending, version_count, intent_count, side_count, store, oldest_snapshot (the oldest running transaction’s start, else the visible timestamp), purge_range(start, end) (a range’s versions below that, history or not — erasure’s).

Branches (§M14.13 B2). An engine per branch of the store (§4.6): create_branch(name) makes one of this engine’s branch — every commit applied so far, made durable by the branch’s checkpoint — and starts its engine, its clock at this one’s last commit (each side’s next commit takes the next timestamp, and from then on neither sees the other’s); branch(name) gives the engine running for a branch, or starts one (a registry the engines share, of weak references, keeps one per branch: two would hand out the same timestamps); drop_branch, reset_branch, branches, branch_info. A new engine reads its store as after a crash (recover_side): what transactions running in the parent at the branch point wrote — spilled intents, unlogged fresh ranges — is no one’s there (an unlogged range deleted at once, intents vacuumed as aborted ones). Each branch’s engine has its own checkpointer thread, waking at its own WAL’s size (a checkpoint commits them all). create_branch_at(name, at) (B4) makes a branch as this one was at snapshot at — refused with SnapshotTooOld unless the history kept reaches it, and a read-only transaction at at held meanwhile so vacuum keeps it —: the branch is made of the present, tagged at + 1, and its engine, before anything else, takes out every commit after at (roll_back_to: versions newer than at, the intents and status records of transactions committed after it, the commit times after it), logged under the store’s last meta so the clock stays, then checkpoints with the tag cleared. A crash midway leaves the tag: the next start does it again (idempotent). A pass over the branch’s entries — the commits after at are not listed anywhere.

Snapshot isolation. A transaction reads at its start timestamp — the engine’s visible timestamp, which advances only once a commit is durable, so nobody reads what a crash could undo. Writes are buffered — the newest of each key, in key order: a sorted vector while they come in order (a statement writes the rows a scan found; a write past the last key is a push, the question whether a key was written already one comparison), a write a little out of order moved into place, and a B-tree map from the first far out of order on (writes.rs). Commit, under the commit lock: for each written key, if its newest version (durable or not) is newer than the snapshot → Error::Conflict (retryable; first committer wins); else one WAL batch with the next timestamp, applied at once (its ops built in key order, as the write set is: not sorted again); then the group-commit wait, then visible moves. put_new (an INSERT’s write: set the key unless it has a value) looks at the key’s versions — and, finding no entry of the key at all, notes the run of keys up to the tree’s next entry: the next put_new inside it needs no look (whatever committed before the snapshot was in the tree then, and a later commit of such a key conflicts at commit as it would have at the look). A bulk insert of new keys in key order looks at the tree once, not once a row; the run ends at a spill, where its own intents enter the tree. A checkpoint is due when the WAL since the last one exceeds checkpoint_wal_bytes (1 GiB, as PostgreSQL’s max_wal_size; 64 MiB on 32-bit targets), or what the branch wrote without the WAL (D16) an eighth of that (Store::unlogged_since_checkpoint) — asked in one place after every write to the store (a commit’s, a spill’s, an unlogged batch’s; §M14.20 W4: it was two, both under the commit lock). Writes without the WAL only wake the checkpointer, never wait for a checkpoint: the checkpoint their commit waits for then finds most of them written (issue #9). Where the platform has threads to spare (parallelism() > 1) a checkpointer thread is woken and runs it — its slow half while commits go on (§4.6) —; in the simulation, or when the WAL passes twice the limit (the thread fell behind), it runs where it fell due, waiting for one running. The thread stops with the engine, after the checkpoint it may be running. Write skew is possible under snapshot isolation (tested and documented).

Large transactions (§M14.11, §M14.20 V11). A transaction keeps its writes in memory up to txn_memory (64 MiB); past it they spill into the store as its intents, under the commit lock, in 1 MiB batches: each key is checked as a commit checks it (a newer version, or another running transaction’s intent of it → Conflict; told by the recent commits’ keys where they tell, else by the tree), and from then on any commit — any write, even — of that key conflicts. A reader resolves an intent by its transaction’s status: its own (above every version; writes still in memory above that), committed at a timestamp (a version at that timestamp, ranked with the others), or neither — running or aborted — and passed over. The commit is one batch as always — the writes in memory as versions (the intents of those inside the spilled span deleted) and the status record (id → ts) — so it is atomic however large the transaction, and each write is written once: nothing moves after the commit. vacuum() later rewrites committed intents as versions at their timestamps and deletes aborted ones — a committed intent’s key ends 00 00 ‖ id and its version’s 00 00 ‖ MAX − ts, so the vacuum rekeys each swept range’s keys from the one end to the other (Store::write_rekeying), its rows left where they are; once a whole sweep is done (durable), the statuses of the transactions committed before it began are dropped. Meanwhile reads pay a little for them (a read of a key with intents walks them before its versions; a scan merges them in one streaming pass), and vacuum leaves alone the keys that have one. So does a commit’s collection for a key’s newest tombstone while committed intents are pending: an intent sorts before the versions but may have committed before the tombstone, which alone hides it — a key’s first in a leaf may have its intent in the leaf before, so there too. Only the reads its intents can reach pay (§M14.20 W5): a spilled transaction keeps the ranges of its intents’ keys — up to eight, disjoint; a key past them starts one of its own, and beyond eight the two neighbours whose facing keys share the longest prefix become one, so a load’s catalog key, its rows and its index stay apart and the tables between them stay out — running and, once committed, until vacuum (after a restart they are not known: every read counts them). The statuses and the running ranges are read under a reader-writer lock, so the workers sharing a transaction’s reads look at them at once (a mutex queued them: TPC-H Q19’s lookups on a just loaded lineitem, §M14.20 W6), and a read flushes pending unlogged writes (D16) only in a transaction that has a fresh range. A scan or a key’s read that no range reaches takes the plain path, as with no intents at all; a write’s conflict check looks at the tree only for keys another’s running ranges cover (or a large commit’s span). The merging pass decodes each key into the batch once, its value replaced by a better ranked version’s (TPC-H Q6 over a just loaded lineitem: 385 → 330 ms, 301 ms vacuumed; a query of orders loaded before it, 67 → 51 ms, as fast as vacuumed). A rollback (or a drop) aborts the transaction — its intents nobody sees from then — and deletes them in the key span it spilled; on opening, the status records say which transactions committed, every other’s intents are aborted (vacuum sweeps them). Serializable reads validate against the key span a large commit wrote (lowest to highest key) beside the recent keys. Store reads let a waiting writer go first (a few hundred yields at most), so a stream of scans over a large transaction’s intents does not keep it from spilling.

Fresh ranges without the WAL (D16, §M14.20 W4; PostgreSQL’s wal_level = minimal and COPY FREEZE, CockroachDB’s AddSSTable). fresh(start, end) declares a range no version is in, no other transaction writes before this one ends and none reads before it commits (a new index’s keys): its writes skip the conflict checks. With EngineOptions::wal_minimal (the default; --wal full turns it off, as anything replaying the whole WAL — a replica, a point-in-time restore — will) its values skip the WAL too. The first write registers the range, under the commit lock: declined — the writes logged as any — when another running transaction writes an overlapping range so, or the store holds any entry in it (a commit after this snapshot’s, anyone’s intent: what a rollback would delete); else its mark 00 04 ‖ start → end is logged. Then each value above the highest key the transaction wrote in the range (by either path: a key above it has no entry anywhere) goes into the store as a final version at the transaction’s snapshot — not an intent a vacuum rewrites — gathered into 1 MiB batches (Store::write_unlogged) — where there are threads, a full batch goes in on a thread of its own while the next is gathered, and every other flush (a read’s, the commit’s, a rollback’s) waits for it first; a key at or below it (out of order, or written again) takes the regular path, whose write wins. The transaction’s reads write the gathered batch first; put_new’s run of keys found empty and first’s empty ranges forget where such a write enters them. The commit writes the rest, checkpoints (commits go on meanwhile, §4.6) and then logs its commit record, which deletes the marks: what the commit record says committed is in the database file before it. A spill or a commit of anyone else with a key inside a registered range conflicts. A rollback deletes every entry of the range (logged deletes, in batches) and then its mark; on opening, every mark left — a transaction a crash ended — has its range deleted the same way. Before its commit the range is readable at snapshots from the transaction’s on — no one reads it, which the caller answers for (a new index nobody else’s catalog shows); after it, it is an ordinary one. A rollback writes a delete per entry to the WAL (rollbacks of index builds are rare; a range delete would make it one record).

Serializable (Isolation::Serializable, §M14). The transaction also records the keys it read and the key ranges its scans consumed (a scan counts up to the last row taken). The engine keeps the keys of recent commits with their timestamps (recent.rs): a small commit’s in a map, a large one’s (256 keys or more) as the sorted run its write set already is, moved — no key inserted one by one —, a spilled one’s as its span; the commits before a snapshot are skipped as a whole when a question is asked for it. Pruned below the oldest running transaction — and the visible snapshot, which a transaction may still begin at while a commit waits to be durable — once the map holds 4096 keys, or there are 64 spans or 32 runs; runs a long snapshot keeps past that go into the map. At commit, if any recorded key or range was written by a commit newer than the snapshot, the commit fails with a retryable Conflict. Read-only transactions never conflict. This is FoundationDB’s read-conflict check rather than Cahill’s SSI (D12): more aborts in some patterns, much less state, and it distributes. A write whose key already has a newer version fails at the write, under both levels — told by the recent commits’ keys (every commit after a running snapshot is among them), without a look at the tree, unless another running transaction’s intents’ ranges or a large commit’s span cover the key; the commit’s own check — told the same way under the commit lock, the tree read, with one cursor, only for the keys the recent ones cannot answer — stays the guarantee.

Validated reads (§M14.5). get_validated / scan_validated record the key or consumed range in the same read set at any isolation level, so a snapshot-isolation transaction can make one decision safe without becoming serializable: its commit fails if a newer commit wrote what it read. Foreign key checks use them (§8.10). validate_range(start, end) records a range unread, as a scan_validated read to its end would: DDL that depends on a table’s rows validates the whole table (§8.7).

Garbage collection. Watermark = the oldest running snapshot (or visible) minus history commits. Garbage is every version but the newest at or below the watermark (and that one if it is a tombstone). A commit drops it from the leaves it rewrites anyway — a compaction filter on its batch (Collect, §4.4), for every key in those leaves, with no read or write of its own: a leaf may hold only part of a key’s versions, which is enough (newer ones in an earlier leaf only make one more garbage), but a tombstone a leaf ends with stays (older versions of its key may go on in the next leaf). What it drops is not logged; after a crash, replay brings it back, invisible still — under a newer version replay brings back as well. vacuum() sweeps all keys, in chunks; a sweep’s deletes of a key are its versions from the first it removes to the last, so it logs them covering that range (Store::write_covering, §4.5): replay deletes the older versions a commit dropped there too. Without it a tombstone the sweep removed — the commit having dropped the value under it, and so the sweep finding the tombstone alone — let replay’s value under it back: a deleted row back after a crash (the embedding queue’s crash test found it, its range vacuumed after each round, §8.24). A sweep reads every entry, so it copies none: keys compared escaped, the few it writes built from the escaped bytes, a value read only for an intent it rewrites or to tell a tombstone (its one byte). Snapshots register under the same lock the watermark is read under, so GC never removes a version a snapshot can see. begin_with(at) reads an older snapshot within the history window (read-only), else SnapshotTooOld.

Time travel’s engine (§M14.14 TT1). EngineOptions::history_time (µs; 0 by default: off) keeps old versions for a time as history does for a number of commits — the watermark is the lower of the two. While it is set, each commit records its time with its own batch (00 05 ‖ ts → µs, a deferred put — Store::write_deferring, §4.5: logged with the commit, into the tree four thousand at a time or at a checkpoint, so a commit rewrites no leaf of times; the readers look at both; the platform’s wall clock, never before the last time recorded, so the times are monotonic in the timestamps — a clock stepping back, a restart on a slower clock, takes the last), exactly, as PostgreSQL’s track_commit_timestamp does rather than Oracle’s sampled SCN↔time map: a time then names its commit exactly. Engine::snapshot_at(time) is the last commit at or before time (a binary search over the records by seeks, up to the visible commit — 5.5 µs measured; the newest snapshot past the last commit; SnapshotTooOld before the first known), commit_time(ts) a commit’s recorded time, reach() the oldest snapshot readable with its time. The retention’s floor — the last commit at or before now − retention — is found again at most once a second (refresh_time_floor, from a commit, a past begin_with, a reach; never under a lock: it reads the store), and an older floor only keeps more. A whole vacuum then deletes the time records below the watermark (the one at it maps the times since). Tests: crates/txn/tests/time.rs (a time reads the last commit at or before it against a logged workload, the retention kept and no more, nothing recorded without it, the times through a crash at every I/O point); crates/sql/tests/time_travel.rs a_logged_workload_reads_back_at_random_times_through_every_index (TT5: 80 rounds of writes, upkeep, vacuums and a reopen, then 150 queries at random times — a block’s and a table’s — through a B-tree index made halfway, the text index, HNSW and a column table, against the log). The cost (crates/kv/examples/bench.rs, NUCLEUS_HISTORY): none measurable — one-row commits from 8 threads 15.2k/s with times, 15.9k/s without, within the runs’ spread.

Scans read the store in batches — 8 visible keys at first, twice as many each time up to 128, and no more than 4096 entries passed over (intents nobody sees, versions too new) — re-seeking each time, so no store lock is held between calls; MVCC makes the re-seek consistent. Reverse scans are not implemented yet.

Watched ranges (§M14.20 W8; SQLite’s schema cookie, made snapshot-aware). Engine::watch(start, end) adds a key range to the watched ones; a commit that wrote into one — in memory, spilled or into a fresh range — raises one mark, watched_at, to its timestamp under the commit lock, before the commit is visible, and a range begins to be watched with the mark at the last commit. watched_as_at(at) answers whether a transaction reads the watched keys as a snapshot at at did: the mark at or below both its snapshot and at, and none of its own writes in a watched range; never for a serializable transaction that writes (its reads must be recorded). A snapshot at or past a commit sees its mark, so what a reader derived from the watched keys at at (the SQL layer’s catalog, §8.2) holds for every transaction that answers yes.

Watches of writes (§M16.6 S1; what live queries re-run on).

  • Engine::watch_writes(ranges) returns a WriteWatch that has a mark of its own. The mark is the timestamp of the newest commit that wrote into one of its ranges. Writes in memory, spilled spans, fresh ranges and stream appends all count.
  • A watch begins under the commit lock with its mark at the newest commit assigned then. So a reader that read at a snapshot S, then waits with WriteWatch::wait(S, timeout) until the mark is past S, misses no commit it did not see.
  • A commit looks at the watches only while one lives (one atomic read otherwise). It raises the marks of those it wrote into after it is visible, then wakes the waiters under the mutex they check their marks under.
  • With 100 watches a single-row commit takes ≈0.8 µs more on the in-memory platform. On a real disk the difference is within fsync’s noise.
  • Engine::write_watches() counts the live watches.

Errors: Storage, Conflict { key }, SnapshotTooOld, ReadOnly, KeyTooLarge, Corrupt; is_retryable().

5.3 Tests (tests/mvcc.rs)

Own writes and rollback; stable snapshots (no dirty or non-repeatable reads, no phantoms); uncommitted writes invisible; first committer wins; write skew possible; no lost updates (6 threads incrementing with retries); transfers between 8 accounts from 4 threads keep the total in every snapshot a concurrent reader takes; GC with pinned snapshots, tombstones and vacuum; commits collecting over many leaves, batches of every size, snapshots of every age reading what they began with, through a crash and replay, about a version a key left (the filter’s own cases — a tombstone a leaf ends with, a leaf beginning inside a key’s versions, intents, reserved keys — in engine.rs); a large commit (its keys one run) conflicting as a small one does, at the write, at the commit and for validated key and range reads (the write set’s and the recent keys’ own cases in writes.rs, recent.rs); history; zero bytes and prefixes in keys; model-based scans inside transactions; recovery of data and timestamps; a crash at every I/O point (both modes). Mutations caught: no conflict check; a GC watermark that ignores running snapshots; a commit’s collection dropping a tombstone a leaf ends with, or a version at the watermark plus one; the recent keys’ runs left out of a key’s or a range’s question. tests/large.rs: transactions past their budget read, overwrite and delete their spilled writes and commit them (their intents read as versions, then vacuumed into them, the same after reopening); rollbacks and drops leave no intent, crashes leave aborted ones vacuum removes; conflicts with intents both ways; committed intents ranked with newer and older versions for readers at three snapshots, through vacuum, and by a row table’s scan with its keys left escaped (a leaf at a time, batches of 1 to 1024 entries); an older engine’s side area moved into versions on opening (its uncommitted one dropped, new ids past its ids); serializable reads against a large commit’s span; a concurrent reader never sees part of a large commit, and does not keep the writer from spilling; a crash at every third I/O point (both modes) with spilling transactions, each state a commit’s, vacuumed to no intent. tests/unlogged.rs (D16): a fresh range’s load writes almost no WAL (and the same load with wal_minimal off writes it all), reads back pending and stored, commits versions — no intent, no mark left — and survives a crash after its commit; a rollback, a drop, and a crash before the commit (with a checkpoint midway, half of the range in the database file) delete the range, which is free again after; declined for a snapshot older than a commit into the range (whose entry its rollback keeps) and for a range overlapping another’s; others’ commits and spills into a range being written so conflict; put_new sees an unlogged write inside a run it found empty; a model test (8 seeds) of in-order, out-of-order and repeated writes, deletes, put_new, get, first and scans, with spills, through commit, crash and vacuum; a crash at every I/O point (both modes) of loads past the cache with a rollback among them, each state a commit’s, no mark left. Mutations caught (14): no checkpoint at the commit, a rollback keeping the range, recovery ignoring marks, no check of the store at registration, others’ commits or spills into the range let through, reads not writing the pending batch first (get, scan), first’s empty ranges or put_new’s run kept across an unlogged write, marks left by the commit, the highest key not raised by logged writes, overlapping ranges both registered, put_new looking at the tree before the pending batch is in it.

Checked by Elle (§M14.29 S5; crates/sql/tests/elle.rs). Eight sessions run transactions of appends to and reads of short lists (Jepsen’s list-append workload: eight lists at a time, each retired after 32 appends; a list a row, an append UPDATE … SET v = v || 'x,', a read a key’s lookup or a scan of a range) at one isolation level, on real files; the history — each transaction’s invocation and its completion, committed or failed with 40001, in real-time order — is written in Elle’s format and checked by Jepsen’s checker, Elle, through elle-cli (CI’s elle job, 8,000 transactions a level). SERIALIZABLE is checked as strict serializability and REPEATABLE READ and READ COMMITTED as strong snapshot isolation: on one node a transaction begins at the visible snapshot and a commit returns once it is visible, so real-time order holds too. The snapshot-isolation histories, checked for serializability, show G2-item — the write skew the level allows. A control makes a write skew on purpose: Elle must find it under REPEATABLE READ asked for serializability, and under SERIALIZABLE the second commit fails. Without Java the test checks what needs no graph: each list’s reads are prefixes of one another, and every element read was appended once, by a committed transaction.

tests/branch.rs (§M14.13): a branch from its parent’s commits, its own way after, the engine one per branch, both through a crash; transactions running at the branch point (spilled, unlogged) not in it; drop and reset failing the old handles.

5.4 The log decoded into commits (decode, §M17.5 R1, D25)

What a replica applies: the primary’s own WAL, read beside the writer and turned back into commits of user keys (PostgreSQL’s logical decoding). Only with EngineOptions::replication (kv::Options too), which turns wal_minimal off: a fresh range written without the WAL (D16) would not be in it.

  • The store’s side. Wal::read(from, until, f) reads records from a record’s start across segments, up to the durable end only (a torn tail’s LSNs are reused after a crash). Wal::hold(lsn) keeps segments from lsn through checkpoints; the hold is persisted in the log’s hold file (an LSN and a CRC-32C, written and renamed at the truncation that needs it), so a restarted database keeps what a replica will read. Wal::wait_durable lets a reader wait for more. The store passes these on (read_log, hold_log, wait_log, log_start, log_end, log_durable); decode_logged turns a record into its batch (meta, ops, deferred writes, covered ranges).
  • What a record is. A batch whose meta passes every one before it is a commit at that timestamp; every other batch carries the last commit’s (a spill’s intents, a savepoint’s or an abort’s undoing of them, the vacuum’s rewrites and deletes). A commit’s writes are its versions at its timestamp, and for a transaction that spilled, its intents (ts = u64::MAX - id), gathered by id in the Decoder until its status record (00 02 | id → ts) comes with the commit; an intent deleted before then is dropped. A key written again after it spilled is in the commit as a version, with its intent’s delete. A version deleted is the vacuum’s: passed over. The commit-time record gives Commit::time. A batch that moves values is an error (no transaction makes one).
  • Where decoding starts again. The decoder holds a spilled transaction’s intents from its first one; Decoder::restart(at) is the oldest such first intent, or at (PostgreSQL’s restart_lsn). Each Read carries it: a replica keeps the last one with its last commit and starts there again, passing over the commits it had.
  • Where a replica starts. Engine::replication_start(slot) gives a snapshot S (the last commit, visible) and the record L to read from: the log’s end, or a spilling transaction’s first intent before it. Under the commit lock, so no commit after S began to be logged before L. The engine keeps where each spilling transaction began (Holds::spills, from its first spill to its end) for this.
  • Slots. Engine::hold_log(slot, lsn) holds the log for a replica from where it reads again; the log is held from the oldest slot or spill. After a restart the persisted hold stands for every slot as RESTORED_SLOT, until the slots are given again and it is dropped.
  • Transactions that end without committing. An abort deletes its intents in logged batches; one cut short by a crash leaves them to the next vacuum. Until then the reader would hold them and the log from them, so LogReader takes a horizon while it holds any (under the commit lock: the log’s end, the next transaction id, the spilling ones). Once past its end, it drops a held transaction below that id and not spilling then. A commit’s record is logged before its transaction stops spilling, so such a transaction never committed.
  • Memory (§M17.5, R2’s, done in R7). The decoder keeps a spilled transaction’s intents until its commit, in memory up to a limit (Decoder::spill_to; a primary’s stream: 64 MiB, Primary::set_decode_memory, PostgreSQL’s logical_decoding_work_mem). Past it, the largest transactions’ go to a space of their own — the database’s scratch files, sealed when it is encrypted — as sorted runs, until half the limit is held. An intent deleted after its transaction has runs stays as a mark that hides the key in them. At the commit, its writes are its own record’s, the intents in memory and the runs merged in key order — the first holding a key decides, the newest run before older ones (an external sort’s k-way merge) — and read as they are sent (Commit::into_writes, CommitParts of 4 MiB): never whole in memory. A 400 MiB transaction replicated: the primary’s peak 820 → 360 MiB. Tests: the decoder’s random workloads run with a 512-byte limit on every other seed (the same commits; three mutants of the merge killed); the server’s 6 MiB transaction crosses through scratch files.
  • Applying on a replica (R2). Engine::set_replica(true) makes every transaction begun after it read only, so a write fails with ReadOnly at once; set_replica(false) is a promotion. The applier writes in Engine::begin_replicated() and commits with Transaction::commit_replicated(ts, time). That is the ordinary commit, so watches, the catalog cache and live queries see it, but at the primary’s timestamp: after the last one here, not necessarily the next, so a seed lands at the snapshot’s S. With a retention by time, the commit takes the primary’s commit time when it had one (its own clock otherwise), never before the last. Snapshots, AS OF and snapshot_at on a replica are the primary’s. Its history and vacuum are its own. Stream heads are cached at append time only and read from the store otherwise, so a promoted replica’s first append finds them. A demoted primary reopens its engine. nucleus_kv::Database::engine() gives the engine to the server’s replication.
  • Each branch decoded on its own: a branch (§M14.13) has its own log, so its slots are its own (replication-slots-b<id> beside the main branch’s file); Primary::for_branch gives a branch’s, made when a replica first asks for it or its parent’s stream first tells of it (n, §10). nc_drop_slot drops the branches’ slots of its name too.

tests/replication.rs checks the decoded commits against what each transaction wrote. The workloads are random: big spilling transactions, savepoints rolled back, aborts, deletes, vacuums, checkpoints and restarts. The tests cover:

  • a reader starting while a big transaction spills: its snapshot and the commits after it make the database now;
  • a reader that stops and starts again from its restart point, across the primary’s restarts;
  • a transaction cut short by a crash, let go by the reader without a vacuum, while one that began to spill after the horizon keeps its intents.
  • a replica seeded while a large transaction spills, then fed the commits: at every applied timestamp its snapshot and commit time are the primary’s, its own transactions cannot write, and the applier cannot write at or before its last commit.

Each was mutation-checked: restart ignoring held intents, spills not holding the log, the sweep and each of its conditions; the applied timestamp, the primary’s time and the replica’s refusal. crates/storage/tests/store.rs checks a reader following the log through checkpoints while it holds it, and a hold outliving a restart.