Skip to content

OLC B+Tree: merge/unlink writes a garbage chunk id, and a key can survive its Remove #739

Closed

Description

@nockawa

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.
  • removeReturnedFalse is set: Remove reported 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

Activity

  1. self-assigned this
    on Aug 9, 2026
  2. updated Product Engine, Area Indexes, Estimate M, Priority P1-High and Bug status Confirmed on Aug 9, 2026
  3. added theissue type on Aug 9, 2026
  4. moved this to Todo in Typhonon Aug 9, 2026
  5. nockawa commented on Aug 9, 2026

    @nockawa
    CollaboratorAuthor

    Reproduced with a stable signature — and it is Remove_Disjoint, not Remove_Merges

    Six 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:

    scenario iterations failures
    Add_Splits 6,001 6
    Add_Disjoint 13,129 2
    Remove_Disjoint 16,931 3
    Remove_Merges 15,977 1
    Remove_Mixed 16,085 0

    Failure kinds across all six runs: 8 DEADLINE (#738), 2 chunk-id exceptions (this issue), and 0 missing keys.

    The chunk id is not garbage

    System.InvalidOperationException: ChunkBasedSegment.GetChunkLocation:
      Computed page index 19027 >= segment length 50.
      ChunkId=589824, rootChunkCount=0, otherChunkCount=31, Capacity=1519
        at NodeWrapper.SetPrevious(NodeWrapper, ChunkAccessor`1&)   BTree.NodeWrapper.cs:92
        at NodeWrapper.RemoveLeaf(RemoveArguments&, NodeRelatives&, ChunkAccessor`1&)  BTree.NodeWrapper.cs:559
        at BTree`2.RemoveIterative(RemoveArguments&, ChunkAccessor`1&, Boolean&)       BTree.Remove.cs:716
    

    Two independent runs produced the identical ChunkId=589824 and the identical page index 19027. A corrupted pointer or a use-after-free would vary. 589824 is 0x90000 — 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 0x90000 here, 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:

    merge = true;
    MergeLeft(GetNext(ref accessor), ref sibAccessor);                       // victim merged into this
    SetNext(GetNext(ref accessor).GetNext(ref sibAccessor), ref accessor);   // relink
    if (GetNext(ref accessor).IsValid)
    {
        var n = GetNext(ref accessor);
        n.SetPrevious(this, ref sibAccessor);                                // ← throws
    }

    The accessor split reads correctly on inspection — GetNext(ref accessor) reads this node's own field, and the sibling's field is then read through sibAccessor — so the fault is not obviously the accessor convention. Left un-diagnosed rather than half-diagnosed.

    Note on symptom 2

    Remove_Merges recorded 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

    OLC_STRESS_SECONDS=30 dotnet test test/Typhon.Engine.Tests/Typhon.Engine.Tests.csproj \
      -c Release --filter "FullyQualifiedName~OlcBTreeRaceStressTests" --blame-crash

    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.

  6. moved this from Todo to In Progress in Typhonon Aug 9, 2026
  7. added a commit that references this issue on Aug 10, 2026
  8. moved this from In Progress to Todo in Typhonon Aug 10, 2026
  9. added 2 commits that reference this issue on Aug 10, 2026
  10. nockawa commented on Aug 10, 2026

    @nockawa
    CollaboratorAuthor

    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 OptimisticDescendToLeaf tests 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 and key <= leaf.lastKey is 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. EntryCount and 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 TryGet instead of Remove. They should be closed together.

    Why the fix was reverted

    Calling KeyBelowLeafLowerBound before 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 its HighKey. 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 hazard BaseNodeStorage.GetChild documents 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-06 is in rules/indexing.md marked [UNBUILT], carrying the evidence, the failed enforcement and the reason it failed, so the next attempt starts from the finding.

  11. nockawa commented on Aug 10, 2026

    @nockawa
    CollaboratorAuthor

    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

    ChunkBasedSegment.GetChunkLocation: Computed page index 19027 >= segment length 50.
    ChunkId=589824, rootChunkCount=0, otherChunkCount=31, Capacity=1519
       at NodeWrapper.SetPrevious          BTree.NodeWrapper.cs:92
       at NodeWrapper.RemoveLeaf           BTree.NodeWrapper.cs:569
       at BTree.RemoveIterative            BTree.Remove.cs:703
       at BTree.RemoveCorePessimistic      BTree.Remove.cs:465
    
    run A (iter 14,060) run B (iter 34,166)
    ChunkId 589824 589824
    page index 19027 19027
    chunk count 31 31

    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:

    MergeLeft(GetNext(ref accessor), ref sibAccessor);                        // 564: merge R into `this`
    SetNext(GetNext(ref accessor).GetNext(ref sibAccessor), ref accessor);    // 565: read R.Next — AFTER R was consumed
    if (GetNext(ref accessor).IsValid)                                        // 566: IsValid does NOT range-check
    {
        var n = GetNext(ref accessor);
        n.SetPrevious(this, ref sibAccessor);                                 // 569: faults here
    }
    1. Read-after-consume. Line 564 merges R away; line 565 then goes back and reads R.Next out of a node that is doomed and being recycled. The left-merge branch has the identical shape at line 551. R.Next should be snapshotted before the merge.
    2. IsValid cannot 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 inside GetChunkLocation, which is why the crash surfaces at SetPrevious rather 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. _rdNotRemoved and _rdWrongValue both 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 RemoveCorePessimistic

    Distinct defect, same family, found by the same runs. Both fast paths read the cached _linkList / _reverseLinkList and go straight to PreDirtyForWrite and GetLatch with no validity check. The field is not merely stale: the path that empties the tree writes Root = _linkList = _reverseLinkList = default, and IsEmpty() at the top of the method is a TOCTOU. A default NodeWrapper carries a null _storage — which is precisely why IsValid tests it — so GetLatch dereferences null. PreDirtyForWrite reads only ChunkId, 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 SpinWriteLockAfterPreDirty so a future caller cannot order them apart. Measured once in 26,848 Remove_Disjoint iterations. 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 <-> RemoveIterative is 0.50 whole-method, and their Phase 1 descent loops were line-for-line identical apart from args.Comparer vs args.KeyComparer, the trace opcode, and return vs return 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: FindLeaf is a fourth descent that does no version validation at all — reached from the range-scan cursors, RangeEnumerator, MovePessimistic and RemoveCorePessimistic.

  12. nockawa commented on Aug 10, 2026

    @nockawa
    CollaboratorAuthor

    🔴 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 MergeLeft in 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 SetPrevious line that now consumes the pre-merge snapshot:

    ChunkId=589824, page index 19027, otherChunkCount=31   (identical to before)
       at NodeWrapper.SetPrevious   BTree.NodeWrapper.cs:92
       at NodeWrapper.RemoveLeaf    BTree.NodeWrapper.cs:585   <- consumes the value read BEFORE the merge
    

    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 the Add_* 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. Against Index32Chunk.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:

    field value
    flags 0 (NodeStates.None — not even IsLeaf)
    Start 9
    Count 0

    It is a Control word, belonging to an empty node whose Start has walked to 9. Not a torn id, not heap noise — a different field of a chunk, read where NextChunk was expected.

    Index32Chunk field order is Control(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

    1. Whether right is a node whose chunk has been freed and recycled by the epoch-deferred reclaim while relatives still names it — Start=9, Count=0, flags=0 is exactly what an emptied, torn-down node looks like, and flags=0 means the IsLeaf bit is gone, which a live leaf would never have.
    2. Whether GetNextNode / SetPrevious can be reached with a NodeWrapper built from a stale relatives snapshot, since NodeRelatives.Create resolves siblings lazily and caches them.
    3. IsValid cannot backstop either case: _storage != null && ChunkId != 0 takes 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.
  13. added a commit that references this issue on Aug 10, 2026
  14. nockawa commented on Aug 31, 2026

    @nockawa
    CollaboratorAuthor

    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):

    rate
    before the #738 fix ~1 chunk-id crash in 10 runs
    after the fix, first batch 1 in 10
    after the fix, since 0 in 34 runs / 190,770 iterations

    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. The Add_* hang was #738.

    What was ruled out along the way

    • RemoveLeaf merging a neighbour its caller never locked. RemoveIterative write-locks leafPrev/leafNext, but RemoveLeaf re-reads GetPrevious/GetNext for itself, so nothing structurally guarantees they are the same node. Threaded the locked identities through RemoveArguments and compared at both merge branches: 0 mismatches in 20 runs. Refuted; the probe was removed rather than left in.
    • Read-after-consume was already tried and already documented at the site as not being the mechanism. Not re-attempted.

    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 GetChunkLocation throws, the read that produced it is off the stack — which is why every trace on this issue points at SetPrevious and 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 a Control-word shape is visible on sight), count, leaf-ness, obsolete bit and latch version. OnInvalidChunkId dumps 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.

  15. changed
    Bug status
    toon Aug 31, 2026
  16. moved this from Todo to Done in Typhonon Aug 31, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Fields

Priority

P1-High

Estimate

M

Area

Indexes

Start date

None yet

Target date

None yet

Bug status

Fixed

Product

Engine

Projects

  • Status
    Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions