Repository navigation
#389 ComponentCollection crash-safety: log the content, stop logging the handle - #773
Merged
Merged
Conversation
All four production AddSlot sites omitted CommitBatchBuilder's optional handleRanges argument, so RecordCodec.ZeroHandleRanges iterated an empty span on every commit. The zeroing code was correct and had never once executed — raw bufferIds travelled in every Slot payload, byte for byte. There was a fifth leak nobody had enumerated. The columnar tick-fence path (#559) bulk-copies component columns straight out of the cluster page into the WAL claim, so a collection handle survives that copy exactly as the scalar beside it does, and it had no zeroing at all. That one is not merely hygiene: the fence's Slot expansion is the LATEST value recovery sees for an entity, so an unzeroed handle is written back into the recovered row and dangles. WriteFenceBlocks now takes the packed ranges and clears them per entity per column. ComponentCollectionVSBSByOffset is replaced by ComponentTable.CollectionFields, an array of CollectionFieldInfo carrying offset, handle size, FieldId and VSBS together, plus the CollectionHandleRanges the codec consumes. #389 needs the FieldId next, and a dictionary with two parallel structures beside it is how the three drift apart. ArchetypeClusterState's ClusterCollectionField was an exact subset of the new struct and is deleted — the cluster now shares the table's descriptor rather than copying it, which is sound because a cluster slot carries no component overhead and the offsets already coincide. LOG-06 goes back to covered. It was retired to NOT COVERED on 2026-08-07 (#703) because both fixtures claiming it build their own wire bytes and round-trip them, so neither could observe the emitter — they were green in the same build as a red production probe. The new verifier drives a live commit and reads the bytes back off the on-disk WAL through the engine's own reader, and it fails if a run inspected only one of the two emitters. Both halves were falsified against the real path before being trusted: disabling the per-entity zeroing surfaces "bufferId 3 at payload offset 0" at LSN 17, disabling the columnar zeroing surfaces the same at LSN 33 marked (fence block). This is not yet a fix for #389. It converts silent corruption into visible absence: collections now recover honestly empty instead of pointing at a buffer that may since have been handed to someone else. The content redo follows.
Recovery's fold-flush has to write a collection's final content in one shot, and nothing could do that. The whole mutation surface of a ComponentCollection was Add; the VSBS itself offered AddElement, AddElements (bulk APPEND, sole caller CloneBuffer) and DeleteElement. So SetElementsRaw is built here from AllocateBuffer + fill + BufferRelease of the old id. The primitives are type-erased, on the base class, working in bytes at ElementSize stride. That is not a stylistic choice: both call sites — the commit emitter reading a collection to log it, and RecoveryApplier replacing one — hold a VariableSizedBufferSegmentBase<PersistentStore> and nothing more, because that is the element type of ComponentTable.CollectionFields and a ComponentTable is not generic over its fields' element types. A Set<T> on the generic subclass would have been unreachable from both. Typed forwarders remain for callers that do have T. Allocate-then-release rather than truncate-in-place buys three things at once. A copy-on-write-shared buffer is never written through, so a snapshot-isolation violation is unreachable by construction instead of by a check. Set(x) twice equals Set(x) once in content and refcount, which is AP-12 (only the buffer id differs, and AP-13 tolerates exactly that). And an empty Set returns the null handle, matching the live shape where a collection never appended to has _bufferId == 0 — otherwise every empty collection would leak an allocation on every recovery. Writing the "no orphaned chunks" acceptance test turned up a real pre-existing bug. BufferRelease and DeleteBuffer both walked the chunk chain from rh.FirstStoredChunkId, and that field is not the head: AddElement assigns it the chunk it just appended into, so it is the append cursor, the TAIL. The head is the root chunk, which is where VariableSizedBufferAccessor starts reading. Releasing a multi-chunk buffer therefore freed the tail and orphaned everything between. A single-chunk buffer has root == tail, which is why it survived — invisible until a collection outgrows one chunk, and then it leaks silently rather than failing. Both paths now walk from the root, and also drain the free-chunk chain, which NextChunk parks empty chunks on and which was leaked for the same reason. Set_RepeatedlyOverOneCollection_LeaksNoChunks is red before that fix and green after; the other seven cases cover set-to-empty, smaller, larger, over-a-COW-shared-buffer and on the null handle, each asserting refcount conservation.
CommitBatchBuilder.AddCollectionDelta had zero production callers. The record kind, its codec, its wire layout and its property tests all existed; nothing had ever written one. Every Slot record for a collection-bearing table now carries the collection's entire content behind it, as Clear followed by Append per element. Full content rather than per-operation deltas is a deliberate deviation from the frozen D3 design, and it is the only shape the API admits. ComponentCollectionAccessor knows none of the entity id, the slot or the field id, is never handed the Transaction, and the ref it binds may legally point at a stack local before the entity exists — that last one is the documented idiom for filling a collection before Spawn, so mutation-time journalling cannot even name what it would be journalling. At commit every one of those facts is already in hand at the AddSlot line. It also dissolves EnsureBase, which 03-recovery.md §5 calls for and which cannot be written: once the handle is zeroed for LOG-06 a buffer is unreachable, because a collection is reached only through the row's inline _bufferId, there is no reverse index, and the buffer root has no owner back-pointer. Complete emission means the fold always has baseDiscarded set, so EnsureBase is never called. The emission is mandatory at every site, not opportunistic, and that is a consequence of the previous commit rather than of this one. Zeroing the handle means applying a Slot record sets the recovered row's handle to zero, so a Slot with no fold behind it empties the collection — including one whose content was already checkpointed and would have survived untouched before. All five emitters are wired: the three in BuildCommitBatch, the per-entity tick fence, and the columnar cluster fence, which gets its own CollectionDelta batch alongside its FenceBlock records. Fence records are individually committed, so ordering between the two batches is by LSN and the fold converges either way. LOG-07 needed no work — AddCollectionDelta already buckets as 1, the same bucket as AddSlot, so a delta cannot precede a Spawn by construction. Verified against the emitted bytes rather than assumed, since this is the first caller that bucketing scheme has ever had. Six tests: the fold over a real commit reproduces the model for both flat-Versioned and cluster-SingleVersion, the fence emits content of its own, deltas follow their spawn, and a collection-free component emits not one CollectionDelta — the common case does not pay for the rare one. The fold in the test is a re-implementation of the driver's, not a call into it, so the two can disagree. Recovery still ignores these records. Apply follows.
…ash is green The apply side was not merely unimplemented, it was unimplementable as sketched. RecoveryDriver.Rec carried no FieldId and no Index, and copied Payload only for Slot records, so a CollectionDelta was gutted at SCAN — one line above the switch whose comment deferred the apply. Adding a case to that switch, the obvious move, could never have worked. Rec now carries the fields and the element bytes. The fold is per (EntityId, slot, FieldId) and runs in LSN order, per 03-recovery.md §5. All five ops are implemented although Option B emits only Clear and Append: the record format defines them, the fold is where they are cheap, and an out-of-range RemoveAt or UpdateAt fails loudly per §9.e rather than clamping — clamping would write a collection that never existed, which is this issue's own failure mode. Those branches are unreachable from any emitter, so they are driven directly by a test; an unreachable loud-failure path nobody has seen fire is indistinguishable from one that silently guesses. EnsureBase is absent by construction, not by omission. The design has the fold read a collection's pre-window content on demand, and that cannot be written: once LOG-06 zeroes the handle there is no route from a record back to its buffer — a collection is reachable only through its row's inline _bufferId, there is no reverse index, and the buffer root has no owner back-pointer. Because every emission is complete, Clear always precedes the element ops and the base is never consulted. FoldFlush runs AFTER the entity's Slot apply, and the design never says so. It is load-bearing twice over: a Slot apply overwrites the whole component value, so a flush that ran first would be clobbered; and since the payload's handle is zeroed, the apply leaves the row pointing at nothing, so the flush is also what gives the collection back its buffer. The handle is written into every home the value has — the content chunk, and for a cluster entity the SoA slot plus, when Versioned, the head revision's chunk, because SCRUB collapses the chain to its highest-TSN element and would otherwise reinstate a stale handle over the cache. Releasing the previous buffer is asymmetric on purpose. SingleVersion storage is rewritten in place, so the old handle dies with the copy and is captured beforehand and released. A Versioned apply appends a NEW revision, leaving the prior one and its buffer referenced until SCRUB frees the content chunk, which releases the buffer with it — releasing here as well would double-decrement. The oracle needed one change to stay honest. RecoveryShadowModel compares raw component bytes, and its own class doc already said that comparison is "wrong in both directions" for a collection field. Only one direction could happen before: an intact descriptor over an emptied buffer. Now that recovery REBUILDS the buffer the other direction is live — the recovered handle is a fresh allocation and legitimately differs — so the handle bytes are masked and the elements are compared by the projector, which is the check that can actually answer the question. AP-13 says placements chosen at apply may differ from pre-crash; this is that. AP-12 is verified by actually applying the window twice, which rules/durability.md notes none of the four existing AP-12 verifiers do. It replays RecoveryDriver.Run over a snapshot of the segments taken at crash time — the live WAL is recycled by CK-04 once the first recovery seals, so without the snapshot the re-run silently has nothing to replay, and the test says so rather than passing. PayloadAxes_SurviveACrash is un-quarantined and its QUARANTINE.md row deleted. That test going green IS the acceptance criterion for #389. On AC 5.4 I did the opposite of what the plan asked, deliberately. It called for lifting ComponentCollectionMatrixTests' ReopenKind filter; that fixture's bodies never reopen anything, so lifting it would have generated duplicate in-session cases whose names advertise a reopen that never happens — #704's trap 2 verbatim. The reopen harness lives in AxisArchetypesTests, so the collection reopen axis went there: 16 cells across storage shape x clean/crash, green. Full suite: 5148 passed. Three runs produced three different single failures — WaitContextTests.HighFrequency_ShouldStop_Consistent, Transient_SpawnDestroy_Throughput, and the quarantined #400 Linearizability set — each green in isolation and none touching collections or durability. That is #720's documented random-victim flake.
… already durable DC-01 lands in rules/durability.md beside AP-13, with the text durable-state-architecture.md drafted plus a scope naming the handle-zeroing paths and a verified naming falsifiable tests. It is the law all three defects in that document share: a reference whose durability timeline differs from its referent's cannot have both survive an arbitrary crash. #389 satisfies it the log-reconstructible way — zero the handle out of the log, emit the referent's content behind the record that names it. RB-06 (the VSBS free-list restarting empty) is the same law, still open, and deliberately out of scope. The rule is ratified WITH its first implementation rather than ahead of it, which is what makes its scope: line checkable at all — check-rule-scopes.py resolves every scope symbol against real code, so a rule ratified as a preamble could not have passed the gate it exists to feed. AP-12's collections clause goes from UNBUILT to built, and gains the note the design never carried: the fold flush must run AFTER the entity's Slot apply. That ordering is load-bearing in two directions and nothing else in the corpus says so. The doc corrections are the uncomfortable part. overview/06-durability.md tabulated CollectionDelta as "folded-then-Set (D3)" and 04-data.md called the crash-safety gap a "caveat", while ADR-056 listed it as a known hole — three documents, two of them wrong, for months. rules/durability.md was the one that had it right. Both overviews now say so explicitly instead of being quietly patched, because the shape is worth remembering: the machine-checked document was correct and the two prose ones both said the reassuring thing. 04-data.md's crash-safety section is rewritten rather than edited. "A crash can lose that write" understated it: the collection read back EMPTY behind an intact handle, with no throw and no diagnostic, and escalated to another entity's elements once the free-list re-issued the handle. It also now records that a recovered bufferId is a fresh allocation by AP-13, so nobody re-files that as a defect, and that schema-catalog collections stay checkpoint-bounded by decision. ADR-056 is immutable, so its crash-safety consequence is struck through with the supersession noted rather than rewritten. MinimalWal/README.md:37 had claimed that supersession one-directionally since it was written; the ADR now knows about it. 03-recovery.md §5 records the D3 deviation in full, including why per-mutation journalling cannot be written against this API and why EnsureBase — which the pseudo-code below the note still calls — is dead by construction and must stay that way.
…nter Seven added lines exceeded the 160-column standard; wrapped. Two of them were in the LOG-06 verifier's own doc comment, which is the one place a reader goes to understand why that test is shaped the way it is. RecoveryApplier's file header still said "Destroy / SetEnabledBits / collections follow in later increments". All three are wired; the header now says so and names the ordering constraint the fold flush carries. RB-06's audit row in rules/durability.md pointed at #389 for the VSBS free-list not being restored at recovery. #389 does not fix that and never claimed to — it is #770 — and leaving the pointer on an issue about to close would have read as fixed. Retargeted, with the reason recorded in the row rather than only in the commit. Also settles todo.md §8 item 2 and does NOT file it: RolledBackAppend_DoesNotSurvive shows a rolled-back append to an already-committed collection is correctly undone. The concern was code-derived — ComponentCollectionAccessor.Add writes into VSBS pages at call time and neither it nor ChunkAccessor.CommitChanges has an undo — but the Versioned copy-on-write path already handles it: the append lands on the new revision's cloned buffer and the rollback discards that revision. The existing SvCc_Rollback_FreesCollection covers a rolled-back SPAWN, a different question. Test kept as the record so nobody re-derives the suspicion. Full suite green: 5150 passed, 0 failed, quarantine excluded. check-rule-scopes, audit-rule-coverage (0 blocking) and check-doc-links all pass.
nockawa
added a commit
that referenced
this pull request
Aug 11, 2026
The only conflict was QUARANTINE.md, where #773 removed the #389 row because it fixed #389, and this branch had added its own row immediately above it. Resolved by keeping the new row and taking main's deletion; the [Category("Quarantine")] attribute on PayloadAxes_SurviveACrash is gone from the source too, so the register and the code agree. Engine suite after the merge: 5237 passed, 0 failed, 20 skipped under the gate's filter — up from 5200 because main added tests and the un-quarantined #389 test now runs. Suppression lint clean, rule-coverage audit 0 blocking.
5 tasks done
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Addresses #389. Docs half: Log2n-io/Typhon-Claude#81.
DifferentialRecoveryOracleTests.PayloadAxes_SurviveACrashis green and un-quarantined, and itsQUARANTINE.mdrow is deleted. That test going green is #389's acceptance criterion.The defect
ComponentCollection<T>was never brought under the commit protocol at all. The issue title says buffer mutations are not WAL-redo-logged; that is true and understates it.CommitBatchBuilder.AddCollectionDeltahad zero production callers. The record kind, its wire layout, its codec and its property tests all existed; nothing had ever written one.RecoveryDriver.Reccarried noFieldId, noIndex, and copiedPayloadonly forSlotrecords — so aCollectionDeltawas gutted at scan, one line above the switch whose comment deferred the apply. Adding a case to that switch, the obvious move, could never have worked.AddSlotsites omitted the optionalhandleRangesargument, soRecordCodec.ZeroHandleRangesiterated an empty span on every commit. The zeroing code was correct and had never once executed — rawbufferIds travelled in every Slot payload, byte for byte.Outcome after a crash: the collection reads back empty behind an intact handle — no throw, no diagnostic — escalating to another entity's elements once the VSBS free-list re-issues that handle.
The approach — option B, full content at commit
Every emitter that writes a
Slotrecord for a component whose tableHasCollectionsnow also logs that collection's entire current content, asClear+Append × N. Recovery folds those per(EntityId, slot, FieldId)and writes the result back via a newSetElementsRawprimitive, after the entity's Slot apply.This is a deliberate deviation from the frozen D3 design, and it is the only shape the API admits.
ComponentCollectionAccessorholds none of the entity id, the slot or the field id, is never handed theTransaction, and therefit binds may legally point at a stack local before the entity exists — that being the documented idiom for filling a collection beforeSpawn. There is no moment during mutation at which a delta could name what it belongs to. At commit, every one of those facts is already in hand at theAddSlotline.It also dissolves
EnsureBase(03-recovery.md:143-145), which is likewise unimplementable: once LOG-06 zeroes the handle there is no route from a record back to its buffer — a collection is reachable only through its row's inline_bufferId, there is no reverse index, and the buffer root carries no owner back-pointer. Complete emission meansClearalways precedes the element ops, so the base is never consulted.Cost — whole-collection emission on every commit touching a collection-bearing component — is accepted for v1 as correct-by-construction and is optimisable later behind a per-field dirty flag. Deliberately not pre-optimised.
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 into the WAL claim 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 is written back into the recovered row and dangles.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 must emit content, or the change trades a dangling reference for silent loss. This is why the cluster fence gets its own
CollectionDeltabatch alongside itsFenceBlockrecords.3. A pre-existing chunk leak, found by writing the "no orphaned chunks" test.
BufferReleaseandDeleteBufferboth walked the chunk chain fromrh.FirstStoredChunkId— but that field is the append cursor (the tail), not the head; the head is the root chunk, which is 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 unnoticed — invisible until a collection outgrows one chunk, and then it leaks silently rather than failing. Both paths now walk from the root and also drain the free-chunk chain, whichNextChunkparks empty chunks on and which leaked for the same reason.Notable design points for review
ComponentCollectionVSBSByOffset→ComponentTable.CollectionFields. ComponentCollection: crash-safety — CC buffer mutations are not WAL-redo-logged (dangling _bufferId after mid-window crash) #389 needs two more facts per field — theFieldIdaCollectionDeltacarries, and the packed byte range the codec zeroes — and carrying those in structures parallel to a dictionary is how the three drift apart.ArchetypeClusterState.ClusterCollectionFieldwas an exact subset and is deleted; the cluster now shares the table's descriptor rather than copying it, which is sound because a cluster slot carries no component overhead so the offsets already coincide.Setprimitive is type-erased, on the base class, working in bytes atElementSizestride. Not stylistic: both call sites holdVariableSizedBufferSegmentBase<PersistentStore>and nothing more, because that is the element type ofCollectionFieldsand aComponentTableis not generic over its fields' element types. ASet<T>on the generic subclass would have been unreachable from both. Typed forwarders remain.Setreturns the null handle, matching the live shape where a never-appended collection has_bufferId == 0.FoldFlushruns after the Slot apply, and the design never says so. Load-bearing twice: a Slot apply overwrites the whole component 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.RecoveryShadowModelcompares raw component bytes, and its own class doc already said that comparison is "wrong in both directions" for a collection field. Only one direction could happen before. Now that recovery rebuilds the buffer, the other is live — the recovered handle is a fresh allocation and legitimately differs — so the handle bytes are masked and the elements are compared by the projector, which is the check that can answer the question. AP-13 permits exactly this.Rules
DC-01ratified intorules/durability.md— no dangling durable reference, the law all three ofdurable-state-architecture.md's defects share. Ratified with its first implementation rather than as a preamble, which is what makes itsscope:line checkable at all:check-rule-scopes.pyresolves every scope symbol against real code.NOT COVEREDon 2026-08-07 (F1 — Make green mean green: un-suppression, shard integrity, and verifiers that can fail #703) because both fixtures claiming it hand-build their wire bytes and so cannot observe the emitter. The new verifier drives a live commit and reads the bytes back off the on-disk WAL, and fails if a run inspected only one of the two emitters. Both halves were falsified against the real path before being trusted — disabling the per-entity zeroing surfacesbufferId 3 at payload offset 0; disabling the columnar zeroing surfaces the same, marked(fence block).🔵 UNBUILTto built, and gains the flush-ordering note.Tests
New:
CollectionDurabilityTests(11),VsbsSetElementsTests(8),WalScanner(reads real WAL segments through the engine's own reader),AxisArchetypesTests.EveryDurableCollectionCell_KeepsItsElementsAcrossAReopen(16 cells, storage shape × clean/crash).AP-12 is verified by actually applying the window twice, which
rules/durability.mdnotes none of the four existing AP-12 verifiers do. It replaysRecoveryDriver.Runover a snapshot of the segments taken at crash time — CK-04 recycles the live WAL once the first recovery seals, so without the snapshot a "re-run" silently replays nothing and passes vacuously; the test asserts it did not.One AC deliberately not done as written. AC 5.4 asked 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). The reopen harness lives inAxisArchetypesTests, so the collection reopen axis went there. Recorded in both fixtures.Also settled, and NOT filed:
todo.md§8 item 2 (rollback may not undo collection appends) is refuted —RolledBackAppend_DoesNotSurviveshows the Versioned COW path already handles it. Test kept as the record so the suspicion is not re-derived.Verification
Rebased onto
mainafter #750 (12eaa446).rules/durability.mdauto-merged (itsIR-01and thisDC-01both survive);coverage/rule-coverage.mdis generated and was regenerated rather than hand-resolved.Typhon.Engine.TestsTyphon.Workbench.TestsTyphon.Shell.TestsTyphon.Client.TestsTyphon.Samples.Swg.Testscheck-rule-scopes✅ (191 scope lines resolve) ·audit-rule-coverage✅ (0 blocking) ·check-doc-links✅Pre-rebase, three full runs each produced one failure, a different test each time —
WaitContextTests.HighFrequency_ShouldStop_Consistent,Transient_SpawnDestroy_Throughput, and the quarantined #400 Linearizability set — each green in isolation and none touching collections or durability. That is #720's documented random-victim flake, baselined rather than assumed.