Skip to content

audit high fixes - #997

Open
citizen-stig wants to merge 9 commits into
thrumdev:masterfrom
citizen-stig:nikolai/audit-high-fixes
Open

citizen-stig wants to merge 9 commits into
thrumdev:masterfrom
citizen-stig:nikolai/audit-high-fixes

Conversation

@citizen-stig

@citizen-stig citizen-stig commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Fix High-severity findings from the 2026-11-23 audit

Independent fixes, one commit each, for defects found by an audit of master at 0224973. Each commit carries its own test, except the Miri-only one. The commits do not depend on each other.

Critical

d97d881 merkle: record a node in the page diff even when it empties the page

What. PageWalker::set_node always records the node as changed, and sets the diff's clear bit on top when the page becomes empty.

Why. A terminator written to the first layer of a page, next to a terminator sibling, was recorded only through the clear bit. Any later write to the same page in the same commit erases that bit, and the node was then recorded in neither form. The hash-table writeout is unaffected, because it writes whole pages. The WAL logs only the nodes the diff lists, and recovery applies them over the old bucket. After a crash between the meta write and the end of the hash-table writeout, the old node survived: the root after reopening was wrong while every value was right.

Tested. New wal_recovery_restores_a_node_cleared_before_another_write in nomt/tests/wal.rs: one commit empties the left half of the root page and fills the right half, panics after the meta write, and the root after reopening is compared with the same commit done cleanly. Fails on master, passes here.

5262f87 beatree: keep a worker's new node when the right worker hands over a deletion

What. When a commit worker extends its range, the entries it receives from its right neighbour are merged into its own tracker; they no longer replace entries that are already there.

Why. The right worker can merge two leaves, hand over the merged leaf, and keep its note that the second old leaf is deleted. The left worker splits the merged leaf, and if the split falls on the old boundary it places a new leaf under that same separator. On its next extension it received the "deleted" note, which replaced the entry holding the new leaf. The leaf was written but never linked into the tree, and the keys in it, which the commit had not touched, read as absent afterwards. This needs commit_concurrency >= 2. The same code runs for branch nodes.

Tested. New extend_range_protocol_keeps_leaf_placed_under_deleted_separator in nomt/tests/extend_range_protocol.rs: two workers, 14 keys sized to fill four leaves, three keys deleted, all keys read back. On master an untouched key reads as absent; here it passes.

572930a beatree: fix three errors when a branch node is rebuilt with another prefix

What. Three fixes in BranchNodeBuilder::push_chunk and copy_and_shift_separators, which re-cut separators when a node is rebuilt with a different prefix length.

Why.

  1. A node's first separator can be shorter than the node's prefix and is then stored with no bits. Its length under a shorter prefix was taken to be the difference of the prefixes, while the gauge that sizes the node counts its real length. In a node the gauge found exactly full, the last separator ran into the first child pointer.
  2. The bytes of the old prefix to carry over were sliced without their starting bit offset. When the prefix shrank by 58 bits or more, the last carried bits could be dropped from every kept separator.
  3. When the prefix grew, bytes of each old separator are skipped but the slice kept its old length, so the last chunk was written without a mask and a trailing bit could be lost.

Each gives a node whose separators or child pointers differ from the keys it was built from, so lookups go to the wrong leaf. Uniformly hashed keys rarely produce the prefix changes involved; keys with long shared prefixes do.

Tested. New nomt/src/beatree/ops/update/branch_prefix_tests.rs: four tests reproduce the cases through BranchUpdater, and a fifth rebuilds 4,000 random nodes with a long shared prefix, inserting or deleting a key outside it, and compares every separator and pointer. All five fail without the change.

63842ec Reject a changeset when the root has changed and returned

What. The database counts the commits that change its root. A session records the count when it begins. Its changeset is accepted only if the count is unchanged, or, for a session built on an overlay, if that overlay was the last thing committed. Behaviour change: a changeset prepared before a commit and its rollback, or before a delete and re-insert, is now rejected with an error.

Why. A finished session or an overlay is built against the pages of the database as they were when its session began. The only check at commit was that the root still equalled the changeset's previous root. The root does not identify the pages: after a commit and its rollback the root is the same while pages have been freed, moved or created. A changeset prepared before was accepted and wrote its pages into that different layout, and after a reopen proofs panicked or read wrong pages. Preparing two blocks on one parent, committing one, rolling it back and committing the other is this sequence.

An overlay with a parent was already tied to its parent's commit and is unchanged. A commit that leaves the root as it is does not invalidate other changesets, as before.

Tested. New nomt/tests/stale_changeset.rs: a session is rejected after a commit and its rollback, and an overlay after a delete and re-insert; both were accepted on master. Two more tests pin what must keep working: a session on an overlay commits after that overlay, and a session commits after a commit that changes nothing. The overlay fuzz target's model now counts root changes as well.

High

63d3791 rollback: leave the log untouched when a rollback fails before its commit

What. Nomt::rollback now reads the prior values without consuming the in-memory rollback log (Rollback::traceback), and truncates the log only after the restoring session has finished.

Why. It used to pop the deltas and set pending_truncate first. If the session then failed (for example on a read error), the store was not poisoned and stayed usable, but the log had already lost the deltas. The next ordinary commit took the stale pending_truncate and pruned live records, and a later rollback succeeded but restored the wrong state.

Tested. New nomt/tests/rollback_failure.rs: fails a rollback(1) by making merkle page reads fail, commits, reopens, and checks that rolling back that commit restores the root from before it. Fails on master (wrong root), passes here. Existing rollback tests pass.

246b40a beatree: don't request overflow pages whose numbers are not known yet

What. AsyncReader::submit stops at the last page number it knows, not at the total page count.

Why. An overflow cell holds at most 15 page numbers; the rest are stored in the first overflow pages and become known as those are read. A caller that submits ahead of the completions indexed past the known numbers. The rollback worker does that when it fetches the prior value of a key whose leaf is not cached: for a value of more than 15 pages it panicked, the panic was raised again while unwinding through ReverseDeltaBuilder::drop, and the process aborted. After a restart the cache is cold again, so overwriting or deleting such a value kept aborting.

Tested. New nomt/tests/rollback_large_value.rs: in a fresh process with rollback enabled, deletes a 100 kB value, rolls the deletion back and reads the value. On master the child dies with SIGABRT (index out of bounds: the len is 15 but the index is 15); here it passes.

a05b134 io: classify io_uring completion errors by the code in the completion

What. A failed completion is classified from its own -errno: EINTR is retried, anything else is an error. The decision is in a small function, completion_result.

Why. The failure was mapped to -1 and passed to IoKind::get_result, which is written for pread/pwrite and reads the thread's errno. io_uring does not set errno, so the outcome depended on the worker thread's last failing syscall: an EINTR completion could be reported as an error, and a real error such as EIO was retried indefinitely if errno still held EINTR.

Tested. New unit test completion_error_does_not_depend_on_errno in nomt/src/io/linux.rs, which sets errno to the opposite of what the completion carries. Run against the old logic it fails on the first assertion (EIO classified as retry); it passes here.

1a84080 beatree: derive the branch cell pointer for writing from a mutable borrow

What. BranchNode::cells_mut takes its pointer with as_mut_ptr() from a borrow of all the cells.

Why. It took the pointer from a shared borrow of the first cell, cast it to *mut, and BranchNodeBuilder::push_chunk wrote through it. That is undefined behaviour.

Tested. Miri on the existing beatree::branch::node::test::push_chunk: undefined behaviour under both Stacked Borrows and Tree Borrows before, clean under Tree Borrows after.

MIRIFLAGS="-Zmiri-disable-isolation -Zmiri-tree-borrows" cargo +nightly miri test -p nomt --lib -- beatree::branch::node::test::push_chunk

Stacked Borrows still flags this test, now at FatPage::deref, which builds a mutable slice from a shared reference. That is a separate issue and is not changed here.

49ad30c Tie a session to the thread that created it

What. Session is no longer Send. It stays Sync. This is a breaking API change for callers that hand a session to another thread, including across an .await on a multi-threaded runtime.

Why. A thread that holds a session may open another one past a queued commit; whether a thread holds one is tracked by the thread that created the session. A session created on one thread and held by another was not counted there, so that thread's next begin_session or Nomt::read queued behind a waiting commit, while the commit waited for the session that thread held. The lock cannot see which thread holds a moved session, so the move is made impossible.

torture moved sessions between the runtime thread and blocking tasks. It now opens the session, reads with scoped threads and commits inside one blocking call. A failed read there is now reported as a failed commit outcome, not as a panic of the agent.

Tested. A doc test on Session asserts that it is Sync and not Send; the second half failed before the change. A four-minute torture swarm with the reworked agent completed 137 commits, 74 crash-aborted commits and 2 rollbacks with no new failure kind.



Benchmarks

Compared master (0224973) with this branch (63842ec) on every benchmark in the repository. No measurable change

benchtop

Each run starts from a fresh copy of a seed database, does 60,000 warm-up operations and then measures for two seconds. An iteration is 12,000 operations followed by session.finish with read-write witnesses and a durable commit; throughput is operations divided by the mean iteration time. Six workload threads, commit_concurrency 4, three I/O workers. Runs of the two builds are interleaved, and the difference is taken per round.

Workload Database Rounds master, median ops/s branch, median ops/s Paired difference 95% interval
transfer (2 reads + 2 writes per op) 4M accounts 6 73,844 74,501 +0.60% −2.17% to +3.38%
randw (100% writes) 1M keys 20 184,365 181,413 −1.06% −2.43% to +0.32%
randr (100% reads) 1M keys 6 530,777 534,454 +0.13% −4.17% to +4.44%
randrw (50% reads, 50% writes) 1M keys 6 240,616 237,925 −0.23% −3.33% to +2.88%

Every interval includes zero. randw got 14 extra rounds because its first six leaned negative; 14 of the 20 rounds were below master, so a cost of about 1% on pure writes cannot be ruled out, and it is at most about 2.4%. The 1M-key database fits in the page cache, so the three random workloads measure the CPU path and the commit's fsync, not cold reads.

criterion (cargo bench -p nomt --features benchmarks --bench beatree)

50 micro-benchmarks, 1 s warm-up and 3 s measurement each, against a saved baseline of master. The benchmarks draw fresh random keys on every run, so master was also compared against its own baseline to show the run-to-run spread.

Group Benchmarks master vs master branch, run 1 branch, run 2
separate 5 −0.4% to +52.8% −0.9% to +53.2% −0.2% to +0.4%
separator_len 5 ±0.0% ±0.0% −0.1% to 0.0%
prefix_len 5 ±0.0% 0.0% to +0.1% ±0.0%
search_branch 5 −1.9% to +3.7% −6.8% to +2.2% −6.4% to −0.4%
search_leaf 1 0.0% −0.3% +1.4%
reconstruct_key_small_separator 9 −0.4% to +1.1% −0.4% to +0.1% −0.4% to +0.1%
reconstruct_key_big_separator 9 −0.2% to +0.5% −1.8% to +0.2% −0.1% to +0.8%
branch_builder 5 −1.2% to +0.9% −2.9% to +1.6% −1.1% to +1.7%
leaf_builder 6 −0.7% to +0.5% +1.5% to +6.6% −0.8% to +0.3%

citizen-stig and others added 9 commits November 23, 2026 16:11
…mmit

Nomt::rollback popped the deltas from the in-memory log and set
pending_truncate before running the session that restores the old values.
If that session failed, for example on a read error, the store was not
poisoned and stayed usable, but the log had already lost the deltas. The
next ordinary commit then took the stale pending_truncate and pruned live
records, and a later rollback restored the wrong state.

Read the prior values without consuming the log, and truncate it only
once the session has finished. From there on the only failure left is in
Store::commit, which poisons the store.

The test fails a rollback by making merkle page reads fail, commits,
reopens, and checks that rolling back that commit restores the root from
before it.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
An overflow cell holds at most 15 page numbers. The numbers of the
remaining pages are stored in the first overflow pages and become known
as those are read. AsyncReader::submit only stopped once it had requested
the total number of pages, so a caller that submits ahead of the
completions indexed past the page numbers it had.

The rollback worker does that when it fetches the prior value of a key
whose leaf is not cached: for a value of more than 15 pages it panicked
with an index out of bounds. The panic was raised again while unwinding
through ReverseDeltaBuilder::drop and aborted the process. After a
restart the cache is cold again, so overwriting or deleting such a value
kept aborting.

Stop at the last known page number instead. The remaining pages are
requested when the completions that carry their numbers arrive.

The test deletes a 100 kB value in a fresh process with rollback enabled,
rolls the deletion back and reads the value.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
A failed completion was mapped to -1 and handed to IoKind::get_result,
which is written for pread/pwrite and decides between retry and error
from the thread's errno. io_uring reports the error in the completion
and leaves errno alone, so the decision depended on whatever the worker
thread's last failing syscall was. An EINTR completion could be reported
as an error, and a real error such as EIO was retried, again and again,
if errno still held EINTR from an interrupted submit.

Decide from the completion's own code. This is the change of 3e97222 on
nikolai/hardenings-and-nice-to-haves, moved into a function so that it
can be tested: the test sets errno to the opposite of what the
completion carries.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
…rrow

BranchNode::cells_mut took the pointer for its mutable slice from
`self.page[..].as_ptr()`, a shared borrow of the page, and cast it to
`*mut`. BranchNodeBuilder::push_chunk writes the cell offsets through
that slice, which is undefined behaviour: the bytes are written through a
pointer that only grants read access. The borrow also covered just the
first cell, not the n cells the slice spans.

Take the pointer with as_mut_ptr() from a borrow of all the cells.

Miri reports the write under both Stacked Borrows and Tree Borrows
before this change and nothing under Tree Borrows after it:

    MIRIFLAGS="-Zmiri-disable-isolation -Zmiri-tree-borrows" \
      cargo +nightly miri test -p nomt --lib -- \
      beatree::branch::node::test::push_chunk

Stacked Borrows still flags this test, now at FatPage::deref, which
builds a mutable slice from a shared reference (io/page_pool.rs). That
is a separate issue and is not changed here.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
A commit or rollback waits for every live session, and parking_lot's
fair RwLock makes new sessions wait behind a queued commit. So that a
thread holding a session can still open another one, such a thread takes
the read lock recursively. "Holds a session" is tracked per thread, by
the thread that created the session.

Session was Send, so it could be created on one thread and held by
another. That thread did not count as holding a session: its next
begin_session or Nomt::read queued behind a waiting commit, and the
commit waited for the session the thread held. Neither could proceed.

The lock cannot see which thread holds a moved session, so make the move
impossible: Session is no longer Send. It stays Sync, so other threads
can still read through a shared reference. This is a breaking change for
callers that hand a session to another thread, including across an
.await on a multi-threaded runtime.

torture did that: it opened the session on the runtime thread and moved
it into blocking tasks to read and to commit. It now opens the session,
reads with scoped threads and commits inside one blocking call.

The doc test on Session checks that it is Sync and not Send. The second
half failed before this change.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
PageWalker::set_node recorded a terminator written to the first layer of
a page, next to a terminator sibling, only by setting the diff's clear
bit. Any later write to the same page in the same commit erases that bit
(PageDiff::set_changed), and the node was then recorded in neither form.

The hash-table writeout is not affected, because it writes the whole
page. The WAL is: it logs only the nodes the diff lists, and recovery
applies them on top of the old bucket. After a crash between the meta
write and the end of the hash-table writeout, the old node survived, and
the root after reopening was wrong while every value was right.

Always record the node as changed, and set the clear bit on top.

The test empties the left half of the root page and fills the right half
in one commit that panics after the meta write, reopens, and compares
the root with the same commit done cleanly.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
…deletion

With more than one commit worker, a worker that runs out of range asks
its right neighbour for more and adds the entries it gets back to its
own tracker. It did so with BTreeMap::extend, which replaces an entry
that is already there.

That happens: the right worker merges two leaves and hands over the
merged leaf, but keeps its entry saying that the second of the old
leaves is deleted. The left worker splits the merged leaf, and if the
split falls on the old boundary it places a new leaf under that same
separator. On its next extension it receives the "deleted" entry, which
replaced the entry holding the new leaf. The leaf was written to disk
but never linked into the tree, and the keys in it, which the commit had
not touched, read as absent afterwards. The same code runs for branch
nodes.

Merge instead: keep the node placed here and take over the deletion.
Two workers changing the same separator, one deleting and one
inserting, is already an expected case in filter_leaves_changeset.

The test uses two workers and 14 keys sized to fill four leaves, deletes
three keys, and reads all of them back. Before the fix keys 8, 9 and 10
were gone.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
…prefix

BranchNodeBuilder::push_chunk copies separators from an existing node
into a new one. When the two nodes have different prefix lengths, each
separator is re-cut: bits move between the shared prefix and the
separator. Three things went wrong there.

1. The first separator of a node can be shorter than the node's prefix
   (trailing zeros are not stored), and is then stored with no bits. Its
   length under a shorter prefix was taken to be the difference of the
   prefixes, although the gauge that sizes the node counts its real
   length. The builder then wrote more bits than the gauge had allowed,
   and in a node that the gauge found exactly full the last separator
   ran into the first child pointer. The length now comes from the key,
   and only that many prefix bits are carried over.

2. The bytes of the old prefix to carry over were sliced without taking
   the bit offset of their start into account. When the prefix shrank by
   58 bits or more, the slice could be one 8-byte chunk short and the
   last carried bits were dropped from every kept separator.

3. When the prefix grew, whole bytes of each old separator are skipped,
   but the slice kept its old length. bitwise_memcpy takes the number of
   chunks from that length: the real last chunk was treated as a middle
   one, written without a mask, and a trailing bit could be lost.

Each of these gives a node whose separators or child pointers differ
from the keys it was built from, so lookups go to the wrong leaf.
Uniformly hashed keys rarely produce the prefix changes involved; keys
with long shared prefixes do.

Four tests reproduce the cases through BranchUpdater. A fifth rebuilds
4000 random nodes with a long shared prefix, inserting or deleting a key
outside it, and compares every separator and pointer. All five fail
without the change.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
A finished session or an overlay is built against the pages of the
database as they were when its session began: which pages exist, in
which buckets, and which child pages are elided. At commit the only
check was that the database's root still equalled the changeset's
previous root.

The root does not identify the pages. After a commit and its rollback,
or a delete and a re-insert, the root is the same again while pages have
been freed, moved or created. A changeset prepared before was accepted
and wrote its page images into that different layout: pages landed in
buckets that had been released, or twice under one id, and after a
reopen proofs panicked or read wrong pages. Preparing two blocks on one
parent, committing one, rolling it back and committing the other is
exactly this sequence.

Count the root changes. A session records the count when it begins, and
its changeset is accepted only if the count is still the same, or, for
one built on an overlay, if that overlay was the last thing committed.
An overlay with a parent was already tied to its parent's commit and is
unchanged. A commit that leaves the root as it is does not invalidate
other changesets, as before.

Tests: a session is rejected after a commit and its rollback, and an
overlay after a delete and re-insert; both were accepted before. A
session on an overlay still commits after that overlay, and a session
still commits after a commit that changes nothing.

The overlay fuzz target's model expected a parentless overlay to commit
whenever the roots are equal. It now counts root changes as well.

Co-Authored-By: Claude Mythos 5.2 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant