Repository navigation
Description
Two symptoms, likely one root cause, both in the merge/unlink path
Residual after PR #737, which cut the second from roughly half of stress runs to 1-2 in 10 but did not eliminate it.
1. Garbage chunk id during merge unlink (~1 in 12 runs)
RemoveLeaf reads a chunk id that is not a valid chunk. A candidate fix eliminated this crash but tripled the Add_* hang rate (0-1/10 became 3/12, then 3/6), so it was reverted rather than shipped unexplained. The coupling is itself the evidence worth keeping: the unlink protocol and whatever hangs in #738 share a window.
2. A key survives its Remove (1-2 in 10 runs)
Remove_Merges, measured with the harness's evidence fields rather than the count alone:
chainCount == EntryCount, both one above expected — so the key was never removed, rather than a decrement being lost. The harness now separates those two explanations instead of printing only the number.removeReturnedFalseis set:Removereported not-found for a key that was still on the leaf chain.
PR #737 fixed two paths that produce exactly this — OptimisticDescendToLeaf treating an inconclusive exit (hop budget, empty leaf) as definitive, and RemoveIterative carrying only the upper half of the stale-separator guard — and the rate fell accordingly. A third path remains.
Where to look first
The not-found branch counters now cover all six exits (OlcDescentTrace.RemoveBranch*, sized by RemoveBranchCount so the next one cannot be lost to an off-by-one). A reproducing run should now name its exit. If every counter reads zero again, the lookup is succeeding and the defect is in the removal itself rather than in finding the key — which is the opposite of where the last three weeks went.
Structural note
AddOrUpdateCorePessimistic, RemoveCorePessimistic and RemoveIterative are hand-duplicated copies of the OLC fast paths that have drifted and lost guards the originals still document. Three of the six defects in PR #737 were that drift. Worth considering whether the pessimistic paths should share code with the optimistic ones rather than mirror them, before more guards are added to both by hand.
Related
- OLC B+Tree: concurrent splits drive AddOrUpdateCorePessimistic to its 10,000-restart bound #738 — the
Add_*hang, which a candidate fix for symptom 1 provably made worse - OLC: concurrent inserts can lose keys under contention without throwing #297 — insert-side silent key loss, partially fixed by the same PR
Activity
nockawa commentedon Aug 9, 2026
Reproduced with a stable signature — and it is
Remove_Disjoint, notRemove_MergesSix runs of the repaired harness (see #738 — the previous instrument was failing on its own leaked file before it reached the tree), 68,123 iterations total:
Add_SplitsAdd_DisjointRemove_DisjointRemove_MergesRemove_MixedFailure kinds across all six runs: 8
DEADLINE(#738), 2 chunk-id exceptions (this issue), and 0 missing keys.The chunk id is not garbage
Two independent runs produced the identical
ChunkId=589824and the identical page index 19027. A corrupted pointer or a use-after-free would vary.589824is0x90000— the low 16 bits are zero, which is the shape of a packed field read as a whole chunk id, or of a sentinel, not of arbitrary memory.That is a much narrower question than "the merge path writes a garbage chunk id": what produces exactly
0x90000here, and is 9 an index or a count?Where it happens
RemoveLeaf's merge-from-right branch —else if (relatives.HasTrueRightSibling),BTree.NodeWrapper.cs:551-560:The accessor split reads correctly on inspection —
GetNext(ref accessor)reads this node's own field, and the sibling's field is then read throughsibAccessor— so the fault is not obviously the accessor convention. Left un-diagnosed rather than half-diagnosed.Note on symptom 2
Remove_Mergesrecorded 1 failure in 15,977 iterations, and no missing keys were seen in any scenario across all 68,123 iterations. The previously reported "1-2 in 10 runs" key loss did not reproduce. That is not a claim it is fixed — the measurements it came from used the broken harness, so the old rate and this one are not comparable. What can be said is that on a working instrument, key loss did not appear.Repro
Roughly 1 run in 3 on the current branch. Requires the harness fixes from #738 (unique per-process database names) or it fails on the leaked file first.
#738 Stop the race harness calling slowness a hang, and leaking a loc…
#739 Revert the descent lower-bound guard — it crashes the test host …
#765 Retire the OLC B+Tree defect generators, and fix two defects tha…
nockawa commentedon Aug 10, 2026
Root-caused, fix attempted, fix REVERTED. Staying open — but the hard part is done and written down. (PR #768, merged as
839a3902.)The mechanism, measured
The B-link right-walk in
OptimisticDescendToLeaftests only the upper side — is the key past this leaf — and it can only travel right. So overshooting is unrecoverable by construction: land one leaf too far right andkey <= leaf.lastKeyis trivially true, the loop declares itself conclusive, and every caller reads that as "definitively not in the tree".The branch counters left no ambiguity. Over 25,701 race-harness iterations: 6 Remove-NotFound events, all on the general-descent branch, all with
key < landedLeaf.firstKey— key 378 on a leaf whose first key is 381, key 474 on one starting at 475, key 88 on one starting at 89 — every one on a leaf holding 14–21 entries, which is what a leaf looks like just after a concurrent merge or borrow has shifted keys out of it.The tree is not damaged when this happens.
EntryCountand the leaf chain agree, the key is present, correctly chained and reachable; every structural validator passes. Only the answer is wrong. That is why S1's four new invariants found nothing while the harness underneath them was failing.#297 is the same descent reaching the same wrong conclusion from
TryGetinstead ofRemove. They should be closed together.Why the fix was reverted
Calling
KeyBelowLeafLowerBoundbefore concluding took it to 0 events in 94,854 iterations. It also crashed the test host.That predicate reads
leaf.GetPrevious()and then dereferences the neighbour for itsHighKey. On the four write paths that call it the leaf is write-locked, so the neighbour id is stable. The descent is lock-free: the id can be torn or name a chunk a merge has just detached, and dereferencing it faults before any version validation can signal a restart — the process dies with no managed stack. Exactly the hazardBaseNodeStorage.GetChilddocuments in its own comment.Measured on
ChaosStressTests.Light_2T_50E_NoDelete: 6/6 pass on main, 4/5 abort with the guard, 4/4 pass with it removed. It also hung the nightly tier, which is how it surfaced.What the next attempt should do
Do not use that predicate here. The descent already follows a separator to choose each child, and that separator is the key's lower bound. Carrying it out of the descent answers the question with no neighbour read at all — cheaper than the reverted version, and safe by construction rather than by luck.
IXS-06is inrules/indexing.mdmarked[UNBUILT], carrying the evidence, the failed enforcement and the reason it failed, so the next attempt starts from the finding.nockawa commentedon Aug 10, 2026
Symptom 1 now has an exact line, a deterministic value, and a named mechanism
Work on branch
feature/739-olc-descent-authority, not yet pushed.The crash, caught twice with byte-identical numbers
Identical across separate runs and different iterations. Random heap garbage does not repeat — this is a specific stale field read from a specific place.
589824=0x90000= 9 << 16: a small plausible number sitting in the wrong 16 bits, i.e. a torn or wrongly-offset read.Two structural defects at one site
BTree.NodeWrapper.cs:561-570, the merge-with-right-sibling branch:R.Nextout of a node that is doomed and being recycled. The left-merge branch has the identical shape at line 551.R.Nextshould be snapshotted before the merge.IsValidcannot catch the result. It is_storage != null && ChunkId != 0— no range check. A garbage non-zero id passes line 566 and faults two lines later insideGetChunkLocation, which is why the crash surfaces atSetPreviousrather than where the bad value was read.Not fixed yet, deliberately. This issue records that a previous candidate fix here "tripled the
Add_*hang rate" and was reverted. Showing the mechanism before touching the merge path.Symptom 2 — not observed today
"A key survives its
Remove" did not reproduce in ~380,000 stress iterations across today's runs._rdNotRemovedand_rdWrongValueboth stayed at zero throughout, and the Remove-NotFound branch table (which prints only when non-zero) never appeared. Not declaring it fixed — PR #737 plus the IXS-07 descent fix (see #297) both plausibly bear on it, and the event was always rare — but there is currently no evidence of it.Fixed alongside: a NullReferenceException in
RemoveCorePessimisticDistinct defect, same family, found by the same runs. Both fast paths read the cached
_linkList/_reverseLinkListand go straight toPreDirtyForWriteandGetLatchwith no validity check. The field is not merely stale: the path that empties the tree writesRoot = _linkList = _reverseLinkList = default, andIsEmpty()at the top of the method is a TOCTOU. A defaultNodeWrappercarries a null_storage— which is precisely whyIsValidtests it — soGetLatchdereferences null.PreDirtyForWritereads onlyChunkId, which is why the crash lands on the lock and not the line above it.The OLC twins of both fast paths open with
if (!ll.IsValid) return Restart;and always have. These copies never got it.Fixed, with the pre-dirty and the lock paired into a single
SpinWriteLockAfterPreDirtyso a future caller cannot order them apart. Measured once in 26,848Remove_Disjointiterations. Say the word if you want it split into its own issue.On this issue's structural note
It observes that the pessimistic paths "are hand-duplicated copies of the OLC fast paths that have drifted". Re-measured: the duplication axis is not optimistic-vs-pessimistic, which sits at 0.22–0.35 similarity.
InsertIterative<->RemoveIterativeis 0.50 whole-method, and their Phase 1 descent loops were line-for-line identical apart fromargs.Comparervsargs.KeyComparer, the trace opcode, andreturnvsreturn false.Those two loops are now one
DescendRecordingPath, so the IXS-07 fix reaches every write path by construction instead of being added by hand three times. 101 lines deleted.Still not unified, and worth its own issue:
FindLeafis a fourth descent that does no version validation at all — reached from the range-scan cursors,RangeEnumerator,MovePessimisticandRemoveCorePessimistic.nockawa commentedon Aug 10, 2026
🔴 My proposed fix is REFUTED — and the failure decoded the garbage value
Attempted the fix described in the previous comment: snapshot the chain pointers before
MergeLeftin both merge branches, so nothing is re-read from the node the merge consumed.It does not fix this. Two 240 s stress runs, 53,805 iterations: the crash reproduces with byte-identical numbers, and merely moved to the
SetPreviousline that now consumes the pre-merge snapshot:So
right.GetNext(ref sibAccessor)already returned garbage before anything was merged. Read-after-consume was never the mechanism, and the two-accessor cache-view theory goes with it. Recording that so nobody re-tries it — that is now two ordering-shaped fixes this crash has shrugged off (this one, and the reverted candidate noted in the body that tripled theAdd_*rate).The change is being kept anyway — reading once before mutating is correct on its own terms and costs nothing — but it is not a fix for this issue and the code comment says so explicitly.
The value decodes, and it is not a chunk id
589824=0x00090000. AgainstIndex32Chunk.Control's documented layout — "State flags (LSW 16 bits), Position of the first Item aka Start (8 bits), stored Item Count (8 bits)" — that is:NodeStates.None— not evenIsLeaf)It is a
Controlword, belonging to an empty node whoseStarthas walked to 9. Not a torn id, not heap noise — a different field of a chunk, read whereNextChunkwas expected.Index32Chunkfield order isControl(0) ·OlcVersion(4) ·PrevChunk(8) ·NextChunk(12) ·LeftValue(16) ·HighKey(20). So a read intended for offset 12 is landing on offset 0, or on a chunk whose memory has been repurposed under it.That reframes the whole issue: this is an offset or lifetime defect, not an ordering one — which explains why every ordering-shaped fix has bounced off it. And it explains the determinism: the same wrong field of the same structurally-identical tree gives the same number every time. Random corruption does not repeat across runs; a systematic misread does.
Where the next attempt should start
rightis a node whose chunk has been freed and recycled by the epoch-deferred reclaim whilerelativesstill names it —Start=9, Count=0, flags=0is exactly what an emptied, torn-down node looks like, andflags=0means theIsLeafbit is gone, which a live leaf would never have.GetNextNode/SetPreviouscan be reached with aNodeWrapperbuilt from a stalerelativessnapshot, sinceNodeRelatives.Createresolves siblings lazily and caches them.IsValidcannot backstop either case:_storage != null && ChunkId != 0takes no accessor, so it cannot range-check. A bounds check would mean threading an accessor through every call site including hot ones — worth pricing, but it is a detector, not a fix.#739 #297 Restore the OLC descent's second parent validation, and sha…
nockawa commentedon Aug 31, 2026
Closing — no longer reproduces after #738's root-split fix
Both symptoms failed to reproduce on a 4-core reproduction of the CI runner (
DOTNET_PROCESSOR_COUNT=4, process affinity pinned to 4 logical CPUs, which is the configuration the nightly runs on):At the old rate, 34 consecutive clean runs has ~2.8% probability, so this is a real change rather than a quiet spell. Symptom 2 ("a key survives its
Remove") did not appear either — the third consecutive investigation in which it has not.Why the #738 fix plausibly covers this
#738 was a level-mixing root split: with an empty descent path, the pessimistic insert's Phase 4 built a new root over a leaf that had stopped being the root, attaching an internal subtree on one side and a leaf on the other. The resulting tree is unbalanced and carries leaves reachable only through the B-link chain. A merge running over a tree in that state reads chain pointers that do not correspond to the structure — which is the shape of this issue's crash.
That also retires the coupling recorded here: a candidate fix for symptom 1 "tripled the
Add_*hang rate", and it was reverted rather than shipped unexplained. The two were not sharing a window; both were feeding off the same corrupt state. TheAdd_*hang was #738.What was ruled out along the way
RemoveLeafmerging a neighbour its caller never locked.RemoveIterativewrite-locksleafPrev/leafNext, butRemoveLeafre-readsGetPrevious/GetNextfor itself, so nothing structurally guarantees they are the same node. Threaded the locked identities throughRemoveArgumentsand compared at both merge branches: 0 mismatches in 20 runs. Refuted; the probe was removed rather than left in.The instrument is staying
A forensic probe now sits on both leaf-merge branches. The bad id is dereferenced two calls after it is read, so by the time
GetChunkLocationthrows, the read that produced it is off the stack — which is why every trace on this issue points atSetPreviousand none at the cause. The probe records, per thread, the state of the node each chain pointer was read from: chunk id, the raw value in hex (so aControl-word shape is visible on sight), count, leaf-ness, obsolete bit and latch version.OnInvalidChunkIddumps that ring alongside the segment message. It is null-hooked in production and costs nothing until a test wires it.So if this recurs, the next capture answers the question this issue leaves open — offset error versus lifetime error — in one hit, rather than starting another hunt from the fault address.
Closing. If CI catches it again, that capture will carry evidence this issue never had, and it should be filed fresh against that evidence.