Repository navigation
audit high fixes - #997
Open
citizen-stig wants to merge 9 commits into
Open
audit high fixes#997citizen-stig wants to merge 9 commits into
citizen-stig wants to merge 9 commits into
Conversation
…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]>
citizen-stig
force-pushed
the
nikolai/audit-high-fixes
branch
from
November 24, 2026 13:58
fc388fa to
63842ec
Compare
citizen-stig
marked this pull request as ready for review
November 24, 2026 13:58
This was referenced Nov 24, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fix High-severity findings from the 2026-11-23 audit
Independent fixes, one commit each, for defects found by an audit of
masterat0224973. 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_nodealways 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_writeinnomt/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_separatorinnomt/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_chunkandcopy_and_shift_separators, which re-cut separators when a node is rebuilt with a different prefix length.Why.
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 throughBranchUpdater, 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::rollbacknow 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_truncatefirst. 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 stalepending_truncateand pruned live records, and a laterrollbacksucceeded but restored the wrong state.Tested. New
nomt/tests/rollback_failure.rs: fails arollback(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::submitstops 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:EINTRis retried, anything else is an error. The decision is in a small function,completion_result.Why. The failure was mapped to
-1and passed toIoKind::get_result, which is written forpread/pwriteand reads the thread'serrno. io_uring does not seterrno, so the outcome depended on the worker thread's last failing syscall: anEINTRcompletion could be reported as an error, and a real error such asEIOwas retried indefinitely iferrnostill heldEINTR.Tested. New unit test
completion_error_does_not_depend_on_errnoinnomt/src/io/linux.rs, which setserrnoto the opposite of what the completion carries. Run against the old logic it fails on the first assertion (EIOclassified as retry); it passes here.1a84080 beatree: derive the branch cell pointer for writing from a mutable borrow
What.
BranchNode::cells_muttakes its pointer withas_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, andBranchNodeBuilder::push_chunkwrote 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.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.
Sessionis no longerSend. It staysSync. This is a breaking API change for callers that hand a session to another thread, including across an.awaiton 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_sessionorNomt::readqueued 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.torturemoved 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
Sessionasserts that it isSyncand notSend; 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 changebenchtop
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.finishwith read-write witnesses and a durable commit; throughput is operations divided by the mean iteration time. Six workload threads,commit_concurrency4, three I/O workers. Runs of the two builds are interleaved, and the difference is taken per round.transfer(2 reads + 2 writes per op)randw(100% writes)randr(100% reads)randrw(50% reads, 50% writes)Every interval includes zero.
randwgot 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, somasterwas also compared against its own baseline to show the run-to-run spread.separateseparator_lenprefix_lensearch_branchsearch_leafreconstruct_key_small_separatorreconstruct_key_big_separatorbranch_builderleaf_builder