Repository navigation
Description
Problem
ComponentCollection<T> (CC) buffer content is not crash-safe. After a crash in the window commit → WAL-durable → (before next checkpoint), the component row's _bufferId is recovered but the buffer it points at is not — leaving a dangling reference and a divergent RefCounter. This is orthogonal to #387: #387 makes CC survive a clean close→reopen; it does nothing for crash recovery.
This was found while assessing #387 — by reading the WAL chunk types + the replay path, not by inference.
Root cause (evidence)
Typhon's redo model is "logical replay of component ops re-derives everything downstream" (it's why indexes need no redo records — replay re-inserts them; and why content/revision chunks survive — their bytes are the WAL payload). CC silently falls outside this guarantee.
- The WAL has exactly six chunk types (
Durability/internals/WalChunkHeader.cs:10):Transaction,FullPageImage,TickFence,ClusterTickFence,BulkBegin/End. None carries CC buffer content. Every component-touching record carries the component row (ComponentStorageSize/PerEntityPayloadbytes) — which holds the_bufferIdbut never the CC elements. WalReplayHelper.ReplayCreate/Update(Durability/internals/WalReplayHelper.cs:132/:184) reconstruct the component row + revision chain by writing the WAL payload into freshly-allocated chunks. They never touch the VSBS segment that backs CC.- CC buffer content + the
RefCounter(in theVariableSizedBufferRootHeader) reach disk only via checkpoint (data-page pipeline). FPI provides only the before-image (revert-to-checkpoint-start), never forward redo.
A ComponentCollection<T> field is a pointer (_bufferId) into a separately-durable segment. Pointers in a redo log are only safe when the pointee shares the same redo timeline. CC's pointee lives on the checkpoint timeline, while _bufferId lives on the WAL-redo timeline. Mismatched timelines = the hole.
Crash scenario
tx adds element to CC buffer B (VSBS pages dirtied in cache), sets component _bufferId = B, commits
WAL flush (FUA) → Transaction/TickFence/ClusterTickFence record durable (carries the row incl. _bufferId = B)
[CRASH] ← before the next checkpoint
Recovery Phase 5: replay rewrites the component row with _bufferId = B (and allocates fresh content/rev chunks)
but buffer B's content = state at the LAST checkpoint. If B was allocated after that checkpoint,
B does not exist on disk → _bufferId = B dangles; RefCounter reverts and diverges from references.
Result on reopen: dangling _bufferId, wrong RefCounter → use-after-free / leak / AddElement's own RefCounter <= 0 tripwire (VariableSizedBufferSegment.cs:269) firing.
Why this is CC-specific (and not the revision chain)
The revision chain stores a ComponentChunkId, which looks similar — but it is safe because that chunk's content is the WAL payload and replay rewrites it. CC's content is not in any payload, so replay has nothing to reconstruct it from.
Scope / relationship to #387
- Out of ComponentCollection: cross-reopen persistence (persist + reload VSBS segments) #387. ComponentCollection: cross-reopen persistence (persist + reload VSBS segments) #387 ships clean-shutdown persistence (persist + reload VSBS roots, restore
HasCollectionson the load ctor, reopen regression tests). Its AC "user CC data survives close→reopen … correct refcount" must be read as clean reopen only; crash-safety is tracked here. - This issue should be considered a prerequisite for declaring CC durable/shippable on an ACID engine.
- Likely gated behind ComponentCollection: cross-reopen persistence (persist + reload VSBS segments) #387 (no point hardening crash recovery for a feature that doesn't yet survive clean reopen).
Proposed approaches (not final)
- Dedicated CC WAL chunk type — log CC buffer deltas (Add/Remove/Clear/Clone/AddRef/Release) or a per-commit buffer snapshot, replayed forward against the VSBS. Mirrors how the UoW registry earns durability via its own WAL records. Cleanest semantically; most work.
- Physical after-image redo of dirtied VSBS pages — capture after-images (not just FPI before-images) of dirtied component-collection pages into the WAL at commit, so replay restores them. Physical redo scoped to one segment kind.
- Checkpoint-ordering bind — guarantee the
_bufferIdwrite is never WAL-durable ahead of its buffer content being checkpointed. Likely defeats the perf model (WAL is the fast path, checkpoint is async) — listed for completeness, probably rejected.
Approaches 1 or 2 are the realistic paths.
Acceptance criteria
- A crash test (kill/abort after WAL flush, before checkpoint) that writes CC data, recovers, and asserts: elements intact,
_bufferIdresolves to a live buffer,RefCounterconsistent with references — for Versioned and SingleVersion, on clustered and non-clustered archetypes. - No dangling
_bufferId, noRefCounterdivergence, no buffer leak after crash recovery. - Mid-window crash + recovery + subsequent mutate (overwrite/destroy) leaves CC buffer lifecycle correct (no use-after-free, no leak).
- A
claude/rules/durability.mdinvariant pinning "CC buffer content is recoverable to the same frontier as the_bufferIdthat references it." - Verify BulkLoad's CC path (writes pages direct to
.bin, fsync via checkpoint, advances CheckpointLSN) is unaffected — i.e. the hole is the normal interactive/tick commit path only.
References
claude/overview/06-durability.md— two-pipeline model (WAL redo vs checkpoint), 6-phase recovery, FPI = before-image only.claude/archive/ComponentCollection.md, design sketch item 5 in ComponentCollection: cross-reopen persistence (persist + reload VSBS segments) #387.- REC-04 (recovery replays from CheckpointLSN); FPI torn-page repair runs before replay.
Metadata
Metadata
Assignees
Labels
Type
Fields
Priority
Estimate
Area
Start date
Target date
Bug status
Product
Projects
- StatusShow more project fieldsDone
Activity
nockawa commentedon Aug 7, 2026
Proven by running code — and it is worse than this issue describes
Branch
epic-411@7e382da3. New fixture:test/Typhon.Engine.Tests/Durability/CrashRecovery/CcDurabilityProbeTests.cs. All outputs verbatim.First: the evidence in the issue body is stale.
WalReplayHelper.csno longer exists (cited at:132/:184); FPI was retired in increment D so "exactly six chunk types" is now five; recovery isRecoveryDriver+RecoveryApplier. The conclusion holds — the mechanism description needs rewriting.1.
CollectionDeltais never emitted — proven by counting, not grepWorkload: one SV (Commit-discipline) spawn with a 5-element collection, one Versioned spawn with a 5-element collection, plus a post-spawn append to an existing collection — the canonical delta case. Immediate durability,
uow.Flush(), then scan the WAL with the recovery read path (WalSegmentReader+RecordCodec.TryReadRecord):Controls are non-trivial (
Slot=3,Lifecycle=2), so the scanner works and the transactions really reached the log. D3 is unimplemented, exactly asclaude/rules/durability.md:200-201says.2. 🔴 Raw
bufferIds leak into the WAL — proven byte-for-byte (LOG-06 violated)First 4 bytes are the scalar
A=0x11223344; the trailing 4 are the collection field — the live handle. All four productionAddSlotsites (Transaction.cs:2411, :2446, :2457,DatabaseEngine.TickFence.cs:197) omit the optionalhandleRangesargument, soHandleRangeCount == 0andRecordCodec.ZeroHandleRanges(:556) iterates an empty span. The zeroing code is correct and never runs.3. Crash outcome — silent loss, escalating to wrong data
Outcome (a) silent data loss: entity alive, scalar intact, handle restored verbatim, collection empty. No throw, no diagnostic — the database looks healthy and answers queries.
It escalates to (b) wrong elements after any post-recovery collection allocation:
The VSBS free-list restarts empty (its pages died with the data file), so the next allocation hands back a handle a live recovered entity still holds. Refcount 1 on a two-owner buffer is the shape of a free-under-a-live-holder — use-after-free is not demonstrated, only its mechanism; I did not drive a destroy-then-access to a fault.
4. 🔴 The differential oracle false-greens on collections — demonstrated
RecoveryShadowModel.Diff()returned zero diffs while the collection went 5 → 0 elements.CaptureValues(RecoveryShadowModel.cs:73) snapshotser.ReadRaw(s), which for a collection field is the 4-bytebufferId— faithfully round-tripped, hence a clean diff.Anyone adding a collection workload to the T-5 oracle will "prove" #389 fixed on a database that lost every collection. The oracle must dereference collection fields before it is allowed to speak about this issue. Please treat that as a prerequisite of the fix, not a follow-up.
What I got wrong, recorded so nobody re-derives it
My first aliasing framing was refuted: the post-recovery spawn and the recovered entity turned out to be the same
EntityId(Key=1, raw 65537), so it was entity overwrite, not buffer aliasing. Rebuilding the experiment to allocate on a local value with noSpawnremoved entity identity from the question, and the aliasing then held. The overwrite itself was a separate real bug — filed as #697 (post-recoverySpawnre-issues a just-recoveredEntityId).Recommended split
bufferIdzeroing on its own, now. A few lines; converts memory-unsafety into honest emptiness. Worth doing even if the redo work slips.CollectionDeltaemit + apply. Note the apply side is bigger than a switch case:RecoveryDriver'sRectype (:36-48) has noFieldId, and:166discards non-Slotpayloads, so it structurally cannot carry a delta today.Not established: the Versioned crash path (experiments B/C/C2 ran SV/Commit-discipline; A shows Versioned also emits nothing and
:2446also omitshandleRanges, so the same defect is expected) and the tick-fence path (DatabaseEngine.TickFence.cs:197— noFenceBlockrecords appeared in any scan).🤖
claude/research/Durability/epic-411-reassessment/05-collections-and-changeset.md.#739 Revert the descent lower-bound guard — it crashes the test host …
#765 S0 Complete the known-red allowlist from what the tier actually …
nockawa commentedon Aug 10, 2026
Unblocked, reclassified, and starting
Reclassified: Type
Feature→ Bug, labelbugadded, Bug status → ConfirmedIt was typed
Feature, which is how a data-loss defect stays invisible: the backlog filters on Type, so a crash-safety hole filed as a feature request never appears in a bug view.ComponentCollection<T>ships today; a user who crashes in the commit → checkpoint window loses collection contents. That is a bug by any user-facing reading, whatever the shippability framing.Confirmed because it reproduces deterministically, every run:
The oracle's own message names this issue by shape: "A collection that recovers EMPTY behind an intact buffer descriptor is #389's exact shape — the raw-bytes comparison cannot see it."
Unblocked
The body says "likely gated behind #387 (no point hardening crash recovery for a feature that doesn't yet survive clean reopen)". #387 is closed — clean close→reopen persistence shipped. The gate is lifted.
Priority — flagging, not changing
Left at P1-High. There is a real argument for P0: silent data loss, 100 % within the crash window, on an engine whose headline claim is ACID. The argument against is that this is pre-GA work under #411 (WAL v2 → GA) and CC has never been declared crash-safe. That is a call for @nockawa rather than one to make unilaterally.
Worth stating plainly either way: the merge gate is green while this is live, because
PayloadAxes_SurviveACrashis correctly quarantined. The quarantine is doing its job; the consequence is that the board shows no red for deterministic data loss. That is the same shape that let #297 sit for 160 days.Quarantine audit (done alongside)
Every issue referenced by
QUARANTINE.md— #389, #400, #406, #410, #552, #696 — is open. No test is excluded from the gate for a bug that has since been fixed, which was the failure mode worth checking for.Next
Reading
claude/design/Durability/MinimalWal/before proposing anything, to establish whether an existing increment already covers CC redo or whether this needs its own design decision between the body's approaches 1 (dedicated CC WAL chunk type) and 2 (physical after-image redo of dirtied VSBS pages).nockawa commentedon Aug 10, 2026
Accepted implementation plan — Option B, full-content emission at commit
Branch
feature/389-cc-crash-safety(worktreebug-bash). Plan derived fromtodo.mdat the worktree root, itself written from a five-agent sweep over the WAL / ECS / VSBS / test / design surfaces. Scope: all phases 0–6, run autonomously.The decision
In
BuildCommitBatch, for every component already emitted as aSlotrecord whose table hasHasCollections, emit the collection's entire current content asClearfollowed byAppend × N.This is a deliberate deviation from the frozen D3 design, which assumed per-operation deltas journalled at mutation time. D3's per-mutation journalling is unimplementable against the actual API: the accessor holds none of
entityId/slot/fieldId, is never given theTransaction, and therefit binds may legally point at a stack local before the entity exists. Full-content emission also dissolvesEnsureBase(03-recovery.md:143-145), which is likewise unimplementable — once the handle is zeroed for LOG-06 there is no reverse index from a buffer back to its owning row. Under Option B the fold always hasbaseDiscarded = true, soEnsureBaseis never called.Cost — whole-collection emission on every commit touching a collection-bearing component — is accepted for v1 as correct-by-construction, optimisable later behind a per-field dirty flag. Not pre-optimised.
Refuted and not to be re-attempted (recorded in
todo.md§3): (A) journal deltas at mutation time; (B) adding aCollectionDeltacase toRecoveryDriver's switch alone — the record is already stripped ofFieldId/Index/elements at scan; (C) physical after-image redo of dirtied VSBS pages.Phases and acceptance criteria
PayloadAxes_SurviveACrashfails naming the collection divergence, not a byte-compare · 0.2 a mutation test proves the oracle reacts to a dropped element[VerifiesRule("LOG-06")]test driving a real commit asserts nobufferIdin the emitted bytes · 1.2 collections recover honestly empty rather than danglingSetprimitivebufferId == 0· 2.2 RefCounter conserved, no orphaned chunks · 2.3 idempotent in content and refcount (AP-12)Bucket = 1already) · 3.3 collection-free components emit byte-identical batches · 3.4 build theoffsetInComponentStorage → FieldIdmap (does not exist today)RemoveAt/UpdateAt⇒ loud failure · 4.3FoldFlushruns after every Slot apply for the same entity (load-bearing; the design never states it) · 4.4 idempotence by actually applying twiceCollectionDurabilityTestsper08-test-plan.mdrow A1.7 · 5.2 un-quarantinePayloadAxes_SurviveACrash— that test going green is the acceptance criterion · 5.3 Versioned + SingleVersion × clustered + non-clustered · 5.4 un-filterComponentCollectionMatrixTests'ReopenKindaxis if it passesDC-01intorules/durability.md· 6.2 AP-12's collections clause UNBUILT note · 6.3 Option B's deviation into03-recovery.md§5 · 6.4 ADR-056's crash-safety exclusion annotated superseded · 6.5 close the06-durability.mdvs04-data.md/ADR-056 contradictionDeviations from
todo.md, declared up frontD1 — Phase 0 was already built.
ICollectionProjector,RecoveryShadowModel.DiffCollectionsandAssertCollectionsAreObservableare all present on this branch, andPayloadPayloadWorkloadimplements the projector. Verified empirically rather than assumed: on the unmodified engine,PayloadAxes_SurviveACrashfails with 8 mismatches of the formcollection field 0: 0 element(s), expected N— AC 0.1 exactly. AC 0.2 isCollectionOracle_DroppedElement_IsDetected, green. Phase 0 is therefore verification, not construction.D2 — the
Setprimitive must be type-erased.todo.md§4 Phase 2 says buildSeton "VSBS or the accessor". Both call sites —BuildCommitBatch(read, for emit) andRecoveryApplier(write, forFoldFlush) — hold onlyVariableSizedBufferSegmentBase<PersistentStore>, because that is the value type ofComponentTable.ComponentCollectionVSBSByOffset. ASet<T>on the generic subclass is unreachable from both. So the raw primitives go on the base class and work in bytes atElementSizestride; a typed forwarder on the generic subclass is kept for tests and ergonomics.Out of scope, decided — do not widen
[fatal], silent handle re-issue onto live objects — its own issue.SaveInSystemSchema/PersistSchemaChanges/PersistNewArchetypesbuild accessors outside any transaction. To be stated explicitly in the rule text so the next reader does not read it as an oversight.Also to file, per
todo.md§8: rollback may not undo collection appends — an atomicity violation on the happy path, no crash required. Code-derived, not measured; one test settles it before filing.nockawa commentedon Aug 11, 2026
Implementation complete — acceptance criteria and evidence
Branch
feature/389-cc-crash-safety, six commits, not pushed pending review.DifferentialRecoveryOracleTests.PayloadAxes_SurviveACrashis green and un-quarantined. That test going green is this issue's acceptance criterion. ItsQUARANTINE.mdrow is deleted.This issue's own acceptance criteria
_bufferIdresolves to a live buffer,RefCounterconsistent — Versioned and SingleVersion, clustered and non-clusteredCollectionDurabilityTests.Collections_SurviveAHardCrash(both homes) ·AxisArchetypesTests.EveryDurableCollectionCell_KeepsItsElementsAcrossAReopen(16 cells, storage shape × clean/crash) ·PayloadAxes_SurviveACrash_bufferId, noRefCounterdivergence, no buffer leakCommit_WithCollections_PutsNoBufferIdOnTheWire[VerifiesRule("LOG-06")], withLog06Verifier_RejectsABufferIdOnTheWire[RuleMutant]proving it can fail. Leak:VsbsSetElementsTests.Set_RepeatedlyOverOneCollection_LeaksNoChunksReapplyingTheWindow_ConvergesInContentAndRefcountre-applies the same window and requires content and refcounts unchanged_bufferIdreferencing it"DC-01ratified intorules/durability.md, plus AP-12's collections clause flipped from🔵 UNBUILTto builtSuppressWalSerializationUoW appends nothing, so it emits noCollectionDeltaeither. Full suite green covers the bulk fixturesPhase ACs
All met except one, which I did the opposite of, deliberately:
AC 5.4 — not done as written. The plan said to lift
ComponentCollectionMatrixTests'ReopenKindfilter. It must not be lifted. That fixture's bodies never reopen anything, so removing the narrowing generates duplicate in-session cases whose names advertise a reopen that never happens — #704's trap 2 verbatim. The reopen harness lives inAxisArchetypesTests, so the collection reopen axis went there instead (16 cells, green). Recorded in both fixtures so it is not re-derived.AC 0.1/0.2 were already built and were verified rather than constructed: on the unmodified engine
PayloadAxes_SurviveACrashfailed with 8 mismatches of the formcollection field 0: 0 element(s), expected N— naming the collection divergence, exactly as specified.Three things the plan did not anticipate
1. A fifth LOG-06 leak site. The plan enumerated four
AddSlotsites. The columnar tick-fence path (#559) bulk-copies component columns straight out of the cluster page and had no handle zeroing at all. Not merely hygiene: the fence's Slot expansion is the latest value recovery sees for an entity, so an unzeroed handle would be written back into the recovered row and dangle. It also needs its ownCollectionDeltabatch, for the reason below.2. Zeroing the handle makes emission mandatory, not opportunistic. Once the payload's handle is zero, applying a Slot record sets the recovered row's handle to zero — so a Slot with no fold behind it empties the collection, including content that was already checkpointed and would previously have survived untouched. Every emitter that writes a Slot for a collection-bearing table must emit content, or the fix trades a dangling reference for silent loss.
3. A pre-existing chunk leak, found by writing the "no orphaned chunks" test.
BufferReleaseandDeleteBufferboth walked the chunk chain fromrh.FirstStoredChunkId— which is the append cursor (the tail), not the head. The head is the root chunk, whereVariableSizedBufferAccessorstarts reading. Releasing a multi-chunk buffer freed the tail and orphaned everything between; a single-chunk buffer has root == tail, which is why it survived. Both paths now walk from the root and drain the free-chunk chain too. Red before the fix, green after.Deliberate deviations from the frozen design
D3's mutation-time journalling is unimplementable against this API: the accessor holds neither entity id, slot nor field id, is never given the
Transaction, and therefit binds may legally point at a stack local before the entity exists — that being the documented idiom for filling a collection beforeSpawn. Option B (full content at commit) has every fact in hand at theAddSlotline.EnsureBaseis dead by construction and must stay that way.03-recovery.md:143-145cannot be implemented: once LOG-06 zeroes the handle there is no route from a record back to its buffer — reachable only through the row's inline_bufferId, no reverse index, no owner back-pointer on the buffer root. Complete emission meansClearalways precedes the element ops, so the base is never consulted.FoldFlushmust run AFTER the Slot apply, which the design never states. Load-bearing twice: a Slot apply overwrites the whole value, so an earlier flush is clobbered; and since the payload's handle is zeroed, the flush is what gives the collection back its buffer. Now recorded in AP-12.Follow-ups
DC-01is now ratified (its body said otherwise) and RB-06's audit row retargeted from ComponentCollection: crash-safety — CC buffer mutations are not WAL-redo-logged (dangling _bufferId after mid-window crash) #389 to VSBS buffer free-list is not restored at recovery — live collection handles can be re-issued to a second owner #770, since leaving it would have read as fixed.todo.md§8 item 2 (rollback may not undo collection appends) — REFUTED, not filed.RolledBackAppend_DoesNotSurviveshows the append is correctly undone; the Versioned COW path already handles it. Test kept as the record.Verification
Full suite 5150 passed / 0 failed (quarantine excluded) on the final run. Three earlier runs each produced one failure, a different test each time —
WaitContextTests.HighFrequency_ShouldStop_Consistent,Transient_SpawnDestroy_Throughput, and the quarantined #400 Linearizability set — every one green in isolation and none touching collections or durability. That is #720's documented random-victim flake, baselined rather than assumed.check-rule-scopes✅ ·audit-rule-coverage✅ (0 blocking) ·check-doc-links✅#389 ComponentCollection crash-safety: log the content, stop logging …
#774 Merge main
nockawa commentedon Aug 11, 2026
Closing — the last AC now has a test, not an argument
PR #773 merged as
32de4c89and carried every acceptance criterion except the last, which was answered by reasoning: "BL-01 holds — aSuppressWalSerializationUoW appends nothing, so it emits noCollectionDeltaeither." The reasoning is correct, and it was the only AC with nothing executable behind it — the same shape as the LOG-06 verifier this issue's own investigation retired in #703. It has one now.The argument, verified structurally
All three emitters live in
Transaction.BuildCommitBatch(Transaction.cs:2425,:2466,:2482). That method has exactly one caller —AppendToWal:2524— and the gate is one line above it at:2516:So a bulk UoW cannot reach an emitter. BL-01 holds through this change by construction.
A fact the AC's wording assumes away
A bulk session cannot put an element in a collection at all.
ComponentCollectionAccessoris obtainable only fromTransaction.CreateComponentCollectionAccessor<T>, andBulkLoadSessionexposes no transaction — its surface isSpawn/OpenMut/Update<T>/Destroy/CompleteBulkLoad. The only bulk-reachable shape is a collection-bearing component with a null handle. "BulkLoad's CC path" as the body describes it — pages written direct to.bin, fsynced by checkpoint — carries component rows, never collection content.That makes the interesting case the composition, not the bulk path alone: a row that arrived on the checkpoint timeline whose elements arrive later on the WAL timeline. That is precisely what this change made fragile — a Slot applied over an already-checkpointed row now zeroes the handle, so the fold behind it is the only thing that puts the content back.
Two tests, in
CollectionDurabilityTestsBulkLoad_WithCollections_PutsNothingOnTheWireCollectionDeltas are required to be present — without it the assertion holds equally on a scan that read nothing, which is a live failure mode here (the reader drain-gapBulkLoadRecoveryTestsdocuments).BulkSpawned_ThenFilled_CollectionsSurviveAHardCrashCompleteBulkLoad→ ordinary commit fills the collections →SimulateHardCrash→ reopen → elements intact, both storage homes.Falsified before being trusted: skipping the fill in the second test fails it (
Failed: 1), so the assertion observes recovered elements rather than passing on an empty collection. Fixture: 14/14 green, ~0.9 s.Suite
Category!=Quarantine(the merge gate's filter): 5238 passed, 1 failed —Transient_SpawnDestroy_Throughput, green on its own, and one of the three victims #773's own verification named. Unfiltered runs 3× with the change and 3× on unmodifiedmainare indistinguishable: the same two quarantined #400 tests every run plus a rotating victim. One earlier run put ~10 victims inAxisArchetypesTests, which did not reproduce in 3 further runs and does not reproduce onmaineither — #720's band, baselined rather than assumed.Unrelated observation, filed nowhere
Bulk-load →
CompleteBulkLoad→SimulateHardCrash→ reopen recovers all 16 entities, and open-time verification reports 1 non-fatal finding, verdictDataLoss, reproducibly. Collections are not involved — it reproduces with empty ones. It is plausibly the bounded page-leakBulkLoadRecoveryTests' remarks describe as deferred (Phase 3b, explicit page-free), now visible because #729's verifier ships. Not investigated, not filed — flagging it because "verdict DataLoss on a clean reopen" is a bad thing to leave undescribed.#389 Verify the BulkLoad collection path with tests, not an argument
#787 #788 #799 #800 #812 #813 Six doc-drift findings, verified agains…