Skip to content

#740 Compare the insert lower-bound guard against the previous leaf's HighKey, not the leaf's own first key - #745

Merged
nockawa merged 1 commit into
mainfrom
fix-740-insert-lower-bound
Aug 10, 2026
Merged

nockawa merged 1 commit into
mainfrom
fix-740-insert-lower-bound

Conversation

@nockawa

@nockawa nockawa commented Aug 10, 2026

Copy link
Copy Markdown
Collaborator

Corrects a P0 liveness regression shipped by PR #737, live on main since 3958c154. Addresses #740; deliberately not auto-closed, so the board flow stays in charge of closing it.

A plain single-threaded Remove(k) then Add(k), where k is the first key of any non-leftmost leaf, burns all 10,000 pessimistic restarts over 2 m 34 s and throws. No concurrency involved.

The defect: a guard strictly stronger than the invariant it protects

KeyBelowLeafLowerBound restarted the descent whenever the key sat below the target leaf's first key and the leaf had a previous sibling. Its stated premise was "a leaf's first key IS the separator its parent holds."

That holds only immediately after a split. Removing a leaf's first key raises the leaf's minimum and leaves the separator where it was, so separator <= key < firstKey is a legitimate destination — the leaf is correct, and the insert lowers its minimum back toward a separator that already routes to it.

Mode 1 is a defect only when key < separator. Testing key < firstKey also rejects that whole band, on a path whose only other exit is a restart. Single-threaded there is nothing to mutate between attempts, so every re-descent reaches the same leaf and fails the same test until the bound throws.

The guard and the consistency check contradicted each other. That band is the same one-sided slack ValidateLeafSeparators was deliberately written to tolerate — in the same PR.

The fix

Compare against the previous leaf's HighKey, the exclusive upper bound the whole B-link descent already steers by, so the guard asks the same question the descent asked rather than a stricter one.

if (leaf.GetCount(ref accessor) == 0 || comparer.Compare(key, leaf.GetFirst(ref accessor).Key) >= 0)
{
    return false;
}
var previous = leaf.GetPrevious(ref accessor);
return previous.IsValid && comparer.Compare(key, previous.GetHighKey(ref accessor)) < 0;

Common path is unchanged — one GetCount, one GetFirst, one compare. The previous-leaf read happens only once the first-key comparison has already failed.

Why 5,072 passing tests did not catch it

Nothing in the suite removed a leaf's first key and re-inserted it on a tree large enough to have interior leaves. It was found by BTreeMicroBenchmarks.Insert_Random reporting NA — BenchmarkDotNet for a process that exited on an error. That benchmark does exactly Remove(key) then Add(key) over a 10,000-key tree.

The benchmark that had been sitting unrun as the "perf is unmeasured" caveat on #297 was also the only thing in the repo exercising this shape.

BtreeTests.RemoveThenReinsertLeafFirstKey_DoesNotStallInsert now covers it, sweeping every leaf boundary: 2 m 34 s and failing before, 130 ms and green after.

Perf, since the guards went into hot insert paths and had never been benchmarked

Three BTreeMicroBenchmarks runs — one on pre-#737 f664beed, two on this branch, so the two same-build runs give a noise floor instead of leaving a single A/B uninterpretable.

ns pre-#737 fixed (1) fixed (2) same-build spread pre → fixed
Lookup_Hit (control) 182.9 189.9 193.9 4.0 +9.0
Lookup_Miss (control) 187.8 186.1 189.7 3.6 +0.1
Insert_Sequential 227.3 204.1 212.8 8.7 −18.8
Insert_Random 251.2 264.1 254.8 9.3 +8.3
Delete_Reinsert 466.3 484.0 471.0 13.0 +11.2
SequentialScan_100 143.9 143.2 143.9 0.7 −0.3

The two lookups are the control — they execute none of this code by construction, and Lookup_Hit still moved +9.0 ns between builds. Every insert-path delta sits inside that band. Insert_Sequential reading 18.8 ns faster points the same way: adding a branch does not speed up a path, so that is layout or ambient load, and it sets the scale for how much of the rest to believe. No regression attributable to the guards.

Caveat rather than a buried footnote: another process was active on the box throughout, which is the likeliest source of what the control picked up. A clean absolute number needs a quiet machine; this conclusion does not, because the control bounds it either way.

Verification

  • Full suite on this branch alone: 5,073 passed, 3 failed. Those three (PayloadAxes_SurviveACrash, DirtyCounter_IsConservedAtQuiesce, ParallelOperations_AreLinearizable) were baselined on unmodified main and fail identically there.
  • All 70 B+Tree fixture tests green.

Docs: the invariant is recorded as IXW-03 in the companion typhon-claude PR.

… HighKey, not the leaf's own first key

KeyBelowLeafLowerBound restarted the descent whenever the key sat below the target leaf's first key and that leaf had a previous sibling, on the premise that such a leaf is reached through a separator equal to its first key. That premise holds only immediately after a split. Removing a leaf's first key raises the leaf's minimum and leaves the separator where it was, so the band separator <= key < firstKey is a legitimate destination: the leaf IS correct, and the insert lowers its minimum back toward a separator that already routes to it.

That band is the same one-sided slack ValidateLeafSeparators was deliberately written to tolerate in the same change, so the guard rejected exactly the states the consistency check was built to accept. Mode 1 is a defect only when key < separator; testing key < firstKey is strictly stronger, and on a path whose only other exit is a restart. Single-threaded there is nothing to mutate between attempts, so every re-descent reached the same leaf and failed the same test until MaxPessimisticRestarts threw. A plain Remove(k) followed by Add(k) on any leaf's first key took 2m34s and died, with no contention of any kind.

The bound is the previous leaf's HighKey, the exclusive upper bound the whole B-link descent already steers by, so the guard now asks the same question the descent asked rather than a stricter one. Cost on the common path is unchanged at one GetCount, one GetFirst and one compare; the previous-leaf read happens only after the first-key comparison has already failed.

Perf measured rather than asserted, since the guards went into hot insert paths and had never been benchmarked. Three BTreeMicroBenchmarks runs, one on pre-737 f664bee and two on this fix, so the two same-build runs give a noise floor instead of leaving a single A/B uninterpretable. Lookup_Hit and Lookup_Miss execute none of this code and still moved 9.0ns between builds; every insert-path delta sits inside that band, and Insert_Sequential reads 18.8ns faster, which sets the scale for how much of the rest to believe. No regression attributable to the guards.

Found by BTreeMicroBenchmarks.Insert_Random reporting NA, which is BenchmarkDotNet for a benchmark process that exited on an error, and not by any of the 5,072 passing tests: nothing in the suite removed a leaf's first key and re-inserted it on a tree large enough to have interior leaves. RemoveThenReinsertLeafFirstKey_DoesNotStallInsert now does, and it sweeps every leaf boundary. 2m34s and failing before, 130ms and green after.
@nockawa
nockawa merged commit 6dae31e into main Aug 10, 2026
16 checks passed
@nockawa
nockawa deleted the fix-740-insert-lower-bound branch August 10, 2026 09:05
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