Skip to content

#297 #679 Six OLC B+Tree defects: silent key loss on insert, remove and read - #737

Merged
nockawa merged 2 commits into
mainfrom
olc-lost-key
Aug 9, 2026
Merged

nockawa merged 2 commits into
mainfrom
olc-lost-key

Conversation

@nockawa

@nockawa nockawa commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator

Six defects in the OLC B+Tree, found by signature rather than by rate, each verified against the thing that made it observable. Related to #297 / #679; neither is closed by this — see Still open below.

What is fixed

# defect why it happened
1 Root republished over a live one — a key orphaned and Height left permanently wrong the emptiness test reads the entry COUNT, and the OLC init publishes the root several instructions before its IncCount()
2 Separator invalidation — insert at slot 0 of an interior leaf drops its first key below its parent separator, so descent routes left of it forever every insert path validated the upper bound; none validated the lower
3 Stale HighKey after a split SplitRight pins HighKey to the right half's first key, and InsertLeaf then changes that key
4 Descent false not-found — hits Remove and TryGet the B-link hop loop had two exits that establish nothing (hop budget, empty leaf) yet every caller reads them as definitive
5 Remove false not-found the pessimistic path carried only the upper half of the stale-separator guard
6 Routing id vs catalog id (test-side) EntityId.ArchetypeId is the per-DB routing id, fed to a per-process catalog-keyed registry

Evidence

  • Root clobber: 12 runs / ~82k iterations with the signature gone; it appeared in 6 of 16 runs before.
  • Separator and HighKey: 0 mismatches in ~47k iterations. The HighKey check is mutation-proven — disabling the one-line fix makes the new assertion fire in a sub-second fixture, on a tree that passed the old CheckConsistency clean.
  • Remove key-loss: roughly half of stress runs down to 1-2 in 10.
  • Suite 5070 to 5072 passing. Index fixtures 447/447.

CheckConsistency was the reason these survived

It asserted neither the separator invariant nor the HighKey invariant, and its first assertion derived each node's expected leaf-ness by counting down from Height — so a Height one too large made every leaf trip it and aborted the walk before a single separator was examined. It now validates chain integrity, leaf depth, separators and HighKey up front, each reporting as itself.

Both new invariant checks are deliberately one-sided, and that is the part worth reviewing: only separator > firstKey and HighKey > nextFirstKey lose keys. The opposite slack is the normal residue of a removal, and an equality version fails a plain single-threaded delete test.

Still open

The Add_* scenario HANG remains, at 10-25% of stress runs. Five hypotheses are refuted with evidence and recorded in the commit bodies so nobody re-runs them: an SMO sibling lock cycle, Sleep(1) amplification in the pessimistic retry loops, restarts introduced by the mode 1 guard, a cycle in the leaf chain, and page-cache backpressure. Also open: residual Remove_Merges key-loss (1-2 in 10) and a garbage chunk id written during merge unlink (~1 in 12). A candidate fix for the latter tripled the hang rate and was reverted rather than shipped unexplained.

A 64-hop bound on the move-right loop was added during that hunt and removed again before this branch was banked: its own counter proved it never fired, so it was a branch in a hot loop bought with no evidence.

Perf is unmeasured. Guards were added to hot insert paths and no benchmark has been run.

nockawa and others added 2 commits August 9, 2026 12:31
… live one

AddOrUpdateCorePessimistic decided the tree was empty from IsEmpty(), which reads the entry COUNT. The OLC initialisation publishes _rootChunkId via CAS several instructions before its IncCount(), so a writer that lost that CAS, exhausted MaxOptimisticRestarts against the winner's still-locked leaf and reached the pessimistic path inside that window observed count==0 with a live root — and the unconditional `Root = AllocNode(...)` there republished a fresh EMPTY leaf over it. The winner's root and the key it held were orphaned: counted by EntryCount, reachable from nothing. Height took two increments for one level and stayed wrong for the life of the tree.

The trigger is now root existence and the publication is a CAS, so the loser frees its node exactly as the OLC path's loser does. EmptyInitRacesLost counts that; non-zero is healthy, it is the defect being caught.

Both symptoms outlive the microsecond that produced them, which is why this read as an insert-path defect for so long: a key simply absent from a structurally flawless tree, and a scalar wrong forever. The drift is also what hid it. NodeWrapper.CheckConsistency derives each node's expected leaf-ness by counting DOWN from Height, so a Height one too large makes every leaf trip its FIRST assertion and abort the walk before a single separator, ordering rule or child pointer is examined. It reported "Mismatch node's Height 2 with True" — a leaf at the wrong level — on trees that were in fact perfectly balanced, and that description sent the hunt at the split paths.

CheckConsistency now validates three things up front that the recursive walk never enforced:

  - every leaf at one depth, with Height agreeing (the masking one above)
  - no separator ABOVE the first key of the leaf it points at — mode 1, where an insert at slot 0 of an interior leaf drops its first key below the separator, so descent for that key routes left of the separator and never reaches the leaf. The walk only asserts the ordering bound parentKey <= childKeys, which a too-high separator satisfies.
  - no HighKey reaching PAST the next leaf's first key — mode 2, where SplitRight pins HighKey to the right half's first key and InsertLeaf then moves a smaller key into that half. Nothing in the walk read HighKey at all, so the bound the entire B-link descent steers by had no enforcement.

Both new checks are one-sided, and that is the part worth stating: only separator > firstKey and HighKey > nextFirstKey lose keys. The opposite slack is the normal residue of a removal — deleting a leaf's first key raises its minimum above a separator nobody rewrites, and routing stays correct. An equality version of the separator check fails DeferredDeallocation_PinnedEpoch_DefersReclamation on a plain single-threaded delete (separator=392 against a leaf whose firstKey=400), which is how a check earns a suppression instead of catching a defect.

DescribeKeyLocation goes away with them. It answered which node held a lost key, which is forensics rather than an invariant, and its answer is now recorded in the comments at the sites it pointed at.

Verified. Twelve race-stress runs, roughly 82k iterations, with no lost key and no height drift; the same signature appeared in 6 of 16 runs before. Attribution was measured rather than argued: per-site tallies showed olcInit=1 pessInit=0 rootSplit=1 on healthy rounds, and a probe caught the real thing live at rootClobbers=1 with height=3 on a depth-2 tree. The new HighKey check is mutation-proven — disabling the mode 2 one-liner makes it fire in a sub-second fixture, on a tree that passed the old CheckConsistency clean. Full suite matches baseline exactly, same pre-existing failures with and without this change.

Two things this does NOT address, both pre-existing and both confirmed against an unmodified tree: the Add_* scenario HANG (~20% of stress runs, same rate before and after), and the Remove-side defects (Remove_Merges EntryCount off by one, Remove_Disjoint errors).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FE5GUBSF5D1DhyPAuTBbYk
…se the blind spot that hid them

Both defects have the same shape: a path concludes "this key is definitively not in the tree" from evidence that does not support it.

OptimisticDescendToLeaf. Every caller reads `keyIndex < 0` as a definitive answer, but two of the B-link hop loop's exits establish nothing — the hop budget running out, and meeting an empty leaf, which ended the loop through its own condition. Both are reachable while the key sits further right, and the second is routine rather than exotic: a merge empties a leaf before it unlinks it. Empty leaves are now hopped OVER, and an inconclusive exit restarts instead of lying. This one is not remove-only. The same descent backs TryGet, so a plain read could report not-found for a key that was present.

RemoveIterative. It carried the upper half of the stale-separator guard — `key >= HighKey` with a right sibling means restart — and treated everything else as "genuinely not in the tree". A stale separator routes a descent too far RIGHT just as easily, and then Find fails on a leaf whose first key is already past the search key while the key sits in a leaf to the left. Measured in Remove_Merges: key 584 removed by nobody, still on the chain, EntryCount 1201 against an expected 1200. An empty leaf is inconclusive here for the same reason and gets the same treatment.

The instrumentation blind spot is why this took as long as it did. The Remove not-found branch counters covered the four OLC exits and neither of the pessimistic ones, so the harness kept reporting a Remove that returned false with every counter reading zero — which reads as "no not-found path was taken" and sends the investigation at the counter rather than the lookup. Both pessimistic exits are wired now, and RemoveBranchCount sizes the array so the next one cannot be lost to an off-by-one.

The harness now separates the two explanations for a wrong EntryCount instead of printing only the number: chainCount is what the tree actually holds, EntryCount is what the counter claims, and removeReturnedFalse is the return value the scenario had been discarding. chain == expected means a lost decrement; chain == EntryCount means a key survived its Remove. It was the second, every time.

ExceptionPathLeakTests resolved an entity's archetype state through ArchetypeRegistry.GetMetadata(entityId.ArchetypeId). EntityId.ArchetypeId is the per-DB ROUTING id and that registry is keyed by the per-process CATALOG id, so it returned whichever archetype happened to hold that catalog id — usually one this engine never registered, whose state slot is null. Both tests failed 3/3 locally on "EntityMap should exist" without ever reaching the leak assertions they exist for, while the quarantine note above them claimed they were "deterministically green locally". GetMetaByRouting is the translation the engine itself uses, and _archetypeStates' own remarks say so.

Suite goes 5070 to 5072 passing. Remove_Merges key-loss drops from roughly half of stress runs to 1-2 in 10.

NOT solved, stated here because the diff could easily suggest otherwise: the Add_* scenario HANG is still present at 10-25% of stress runs. Five hypotheses have been refuted with evidence rather than argued away — an SMO sibling lock cycle, Sleep(1) amplification in the pessimistic retry loops, restarts introduced by the mode 1 lower-bound guard, a cycle in the leaf chain, and page-cache backpressure. A 64-hop bound on the move-right loop was added during that hunt and is removed again in this change: its own counter proved it never fired once, so it was a branch in a hot loop bought with no evidence behind it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FE5GUBSF5D1DhyPAuTBbYk
@nockawa
nockawa merged commit 3958c15 into main Aug 9, 2026
16 checks passed
@nockawa
nockawa deleted the olc-lost-key branch August 9, 2026 22:21
nockawa added a commit that referenced this pull request Aug 10, 2026
…ommit

Rebasing onto main hit the one conflict this move can produce: `rules/indexing.md` was deleted on this branch and modified on the docs repo's main, where #740 added IXW-03 (a leaf's lower bound is the previous leaf's HighKey). Resolving it the obvious way — deletion wins, the file is going away — would have dropped a `[fatal]` rule added a few hours earlier. So the resolution is main's version of the file, with this branch's link change re-applied on top, not the version this branch started from.

That IXW-03 exists at all is worth noting here, because it is the same failure mode from a different angle: the guard shipped in PR #737 was strictly stronger than the invariant it protected, and nothing could see the contradiction because the guard and the consistency check that disagreed with it never met. A rule deleted by a clean merge resolution would be invisible in exactly the same way.

Its `scope:` resolves — `KeyBelowLeafLowerBound` and `InsertIterative` in `BTree.Insert.cs` — because the fix landed in PR #745 meanwhile. Worth stating plainly, since this branch deletes the `--baseline-rules` mode that used to demote a not-yet-landed citation to a warning: had the rule arrived before its fix, the scope check would now fail, and that is the intended behaviour rather than an oversight. The window in which a rule can outrun its code is the width of one commit.

`rules_total` goes 191 to 192. The three coverage figures are untouched — IXW-03 is covered by its `verified:` line but carries no `[VerifiesRule]` attribute, so nothing the ratchet protects moves. That the count and the rule it counts can be corrected together is the whole point: PR #745 could not touch the rule, PR #73 could not touch the counter, and neither was wrong to leave it.
nockawa added a commit that referenced this pull request Aug 10, 2026
…nd widen IXW-03 to cover it (#766)

PR #745 replaced `key < leaf.firstKey` with a comparison against the previous leaf's HighKey on the insert side, and left the identical predicate standing in RemoveIterative. Both were written by the same change (#737), one was found wrong, one was fixed. BTree.Remove.cs:610 carried `count > 0 && key < firstKey && previous.IsValid` verbatim until this commit, and KeyBelowLeafLowerBound had five uses in BTree.Insert.cs against zero in Remove.cs and zero in Move.cs.

The predicate fails for the same reason it failed on the insert side: a leaf's first key equals the separator routing to it only until something is removed from the front, after which the band prevHighKey <= key < firstKey is one the leaf IS authoritative for. Answering "not authoritative" there releases the latch and re-descends to the same leaf.

It is NOT single-threaded reachable, and the difference from #740 is worth stating because it was asserted the other way before it was tested. TryRemoveOlc answers NotFound from the optimistic descent before its count check, so an absent key never arrives at the pessimistic guard at all. Reaching it needs the descent to FIND the key, the leaf underfull enough to defer to the pessimistic path, and a concurrent writer to raise the leaf's first key above it in between — concurrency-gated, and the #738 class rather than #740's.

That is also why this ships without a red-to-green regression test. RemoveAbsentKeyBelowLeafFirstKey_ReportsNotFound is included because the coverage is real and was missing — double-remove across every leaf boundary of a 2,000-key tree, with a consistency check either side — but it passed before this change as well as after, and its remarks say so. Presenting it as proof of the fix would be the same "green means verified" error the assessment condemns. The justification here is the invariant, not the test.

Verified against the race harness instead: four runs, 41,934 iterations, no hangs, no crashes, failure counts unchanged from baseline. Full suite 5,116 passed with five failures, all in the known flake band and none in indexing.

IXW-03 scoped itself to BTree.Insert.cs alone — the rule written to stop this exact drift did not cover its own twin, and shipped that way for a day. Its scope now names Remove.cs and Move.cs, and it carries an explicit gap note: Move.cs performs leaf inserts with no lower-bound guard at all, which is not a drifted copy but a missing one. Collapsing the five hand-maintained leaf-insert copies onto one authority is the only fix that scales, and it is #765 step S2.
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