Skip to content

Recovery silently drops SV value updates for pre-existing entities (no ApplySlotToExisting) — TickFence does not deliver its documented ≤1-tick window #569

Closed

Description

@nockawa

Summary

Crash recovery silently drops every SingleVersion component value update for any entity that already existed at the last checkpoint. The engine writes, fsyncs and retains those WAL records every tick, then throws them away on replay.

This contradicts the documented ≤1-tick loss window for DurabilityDiscipline.TickFence.

Evidence

RecoveryDriver.cs:218-237 — the aggregation loop:

foreach (var (entityIdRaw, agg) in entities)
{
    // No Spawn in the window → the record targets a pre-existing (checkpointed) entity
    // already loaded into the EntityMap.
    if (!agg.HasSpawn)
    {
        if (agg.HasDestroy)            { applier.ApplyDestroyToExisting(entityIdRaw, agg.DestroyTsn); }
        else if (agg.HasEnabledChange) { applier.ApplySetEnabledBitsToExisting(entityIdRaw, agg.EnabledBits); }

        continue;   // ← the aggregated Slot payloads are DROPPED
    }
    …
}

RecoveryApplier has ApplyDestroyToExisting and ApplySetEnabledBitsToExisting but no ApplySlotToExisting. The comment at :223-224 states the omission is known and deferred:

"Base-entity Destroy wins over any enabled change (net not-alive); otherwise apply a base-entity enabled-bits change in place. A base-entity value update (AddCompRev to the existing chain) is a later increment."

Impact

  • Scope: every entity that existed at the last checkpoint. In a steady-state simulation — spawn once, mutate forever — that is effectively all of them after the first checkpoint.
  • Actual durability delivered: the checkpoint interval (ResourceOptions.CheckpointIntervalMs, 30 s default), not ≤1 tick.
  • Not silent data corruption — the checkpoint still persists the cluster pages, so the values are durable at checkpoint granularity. What is lost is freshness, up to 30 s of it, and the guarantee that was advertised.

What promises the thing that is not delivered

Source Claim
claude/overview/02-execution.md:571 ≤ 1 tick loss window for TickFence
claude/adr/057-committed-durability-discipline.md:13-15 "its durability is TickFence: values are batched into a WAL record at the tick boundary, so a crash can lose up to one tick of writes (≤1-tick loss)"
Typhon.Schema.Definition/DurabilityDiscipline.cs:22-26 "durability batched at the tick fence (≤1-tick loss)" — the XML doc users read in IntelliSense

No test covers it

claude/scratch/robustness-assessment-2026-07-06-findings.md:229 rates this high and notes "No test/KnownIssue covers it." Two independent design documents say it deserves its own issue:

Two ways to close it

A. Implement ApplySlotToExisting — make the promise true. Recovery applies the aggregated slot payload to the existing entity's cluster slot (and, for Versioned, the revision chain). The per-slot latest-wins aggregation (RecoveryDriver.cs:53) already produces exactly the value to apply; what is missing is the applier method and the cluster-slot write path for a non-spawning entity.

B. Stop emitting — make the promise honest, per archetype. That is the ClusterDurability.Checkpoint proposal, filed separately.

These are alternatives, not complements, and choosing between them is the actual decision. Doing neither is the only option that leaves the engine in its current state: paying full price for a guarantee it does not deliver.

Acceptance criteria (for option A)

  • RecoveryApplier.ApplySlotToExisting(entityId, slot, payload, lsn) — cluster and flat paths
  • RecoveryDriver routes the !agg.HasSpawn case's aggregated slot payloads to it
  • Test: pre-existing entity mutated in the WAL window, hard crash before checkpoint → recovers with last-tick values, not checkpoint values
  • Test: interaction with DurabilityDiscipline.Commit records for the same slot — last-writer-wins by LSN (CM-03)
  • Test: the post-Columnar FenceBlock WAL record — cut tick-fence emission cost and volume #559 FenceBlock expansion path feeds this correctly (recovery expands a block into per-(entity, slot) aggregation)
  • DifferentialRecoveryOracleTests / WalCrashSweepTests gates do not regress

If option B is chosen instead, this issue closes as "won't fix — superseded by declared per-archetype durability", and the documentation above must be corrected in the same change.

Related

Activity

  1. added theissue type on Jul 27, 2026
  2. updated Priority P1-High, Estimate M, Product Engine and Area Durability on Jul 27, 2026
  3. added a commit that references this issue on Jul 27, 2026
  4. moved this to Todo in Typhonon Aug 6, 2026
  5. nockawa commented on Aug 7, 2026

    @nockawa
    CollaboratorAuthor

    ✅ Reproduced by a running test — and this is the single biggest data-loss risk in the engine today

    Confirmed on epic-411 @ 7e382da3. The issue was until now argued from code reading; there is now a deterministic red test that takes 124 ms.

    The test

    The trick is that it is not a new test — it is Bug2_Update_Reopen_WithCheckpoint (LifecycleDurabilityBugTests.cs:161) with exactly one line moved. Bug2 checkpoints after both the spawn and the update, so both records land below CheckpointLSN and the reopen is served from checkpointed pages — WAL replay of the update is never exercised. Moving the checkpoint to sit between them is the steady-state shape of every long-running database:

    spawn(A=1) → commit → uow.Flush()           // Immediate — ACKED
    dbe.ForceCheckpoint(); WaitForCheckpoint()  // ← the ONLY difference: spawn now BELOW CheckpointLSN
    update(A=777) → commit → uow.Flush()        // Immediate — ACKED, alone in the WAL window
    dbe.SimulateHardCrash()
    reopen → read A

    The result

    Failed Bug3_UpdateAfterCheckpoint_SurvivesHardCrash(True) [124 ms]
      an Immediate-ACKED update to an already-checkpointed entity must survive a hard crash;
      got 1 (the pre-checkpoint spawn value — the update was silently discarded)
      Assert.That(a, Is.EqualTo(777))
      Expected: 777
      But was:  1
    

    hardCrash=False passes — a clean shutdown persists engine state. So the control holds and this is unambiguously the recovery path, not the write path.

    Test added on branch epic-411 as LifecycleDurabilityBugTests.Bug3_UpdateAfterCheckpoint_SurvivesHardCrash, parameterised [Values] bool hardCrash so the control ships with it.

    Two things worth escalating

    1. It is not Versioned-specific. The title says "SV value updates"; this repro uses CompABArch on the ordinary OpenMut(...).Write(...) path. The discard is in RecoveryDriver's per-entity aggregation (:243-259 — agg.Slots is populated at :215-222 and never read when !agg.HasSpawn), which is upstream of storage mode. Worth re-checking whether the title under-scopes it.

    2. It is not a child of Epic #411. #411's five children are #389, #400, #396, #402, #184. On the current plan, this would not have been looked at before declaring the WAL alpha-ready — while it is strictly more dangerous than any of the five: [fatal] + [silent], needs no concurrency, no collections, no allocation failure and no timing luck. Only run long enough to checkpoint, update an existing entity, lose power.

    Recommend making it a child of #411 and treating it as the epic's top blocker.

    Why nothing caught it

    claude/rules/durability.md:136-142 already states the reason exactly: "every recovery workload puts a spawn and its updates in the SAME window, so nothing crosses the checkpoint frontier on one entity and no test catches it." That is a structural blind spot in RecoveryWorkloads, not an oversight in any one test — which is why a single moved ForceCheckpoint exposes it instantly. Suggest adding a cross-checkpoint-frontier axis to the sweep so the whole class is covered, not just this instance.

    🤖 #411 reassessment — claude/research/Durability/epic-411-reassessment/03-experiment-results.md §E1.

  6. nockawa commented on Aug 7, 2026

    @nockawa
    CollaboratorAuthor

    Fixed under #705 — Option A, on branch feature/705-detector-harnesses

    Option A implemented. RecoveryApplier.ApplySlotToExisting(entityIdRaw, slots) for the cluster and flat paths, routed from RecoveryDriver's !agg.HasSpawn branch — the aggregation at :53 already produced exactly the right value, so the only thing missing was somewhere to put it.

    Each storage home is updated through the same primitive the live write path uses, so recovery produces the shape a normal write would: ComponentRevisionManager.AddCompRev appends to the existing chain for Versioned (the chain ROOT is unchanged, so the EntityMap record needs no rewrite), SingleVersion content is overwritten in place, and a cluster entity's SoA HEAD is written at the slot its ClusterEntityRecord already names. Appending rather than re-rooting matters: Phase-4 SCRUB collapses each chain to its highest-TSN committed element and frees the rest, so an appended revision is reclaimed correctly where a fresh root would orphan the old chain's chunks.

    Two corrections to this issue's framing

    1. It is not SingleVersion-specific. The branch that dropped the payloads keys on "no Spawn in this window", not on storage mode — so flat Versioned archetypes lost their updates identically. All three shapes (flat non-indexed, flat unique-indexed, cluster SV) reproduced it, and all three are now green. The title understates the scope.

    2. test-strategy.md §7 called this "~20 lines". It is ~150 across two storage homes plus the driver routing. This issue's own four-item acceptance list was the accurate estimate; the design doc's was not.

    Evidence — red before fix

    The defect was inexpressible before #705's interface change: every existing workload built its entities in a List<EntityId> local inside Execute, so RecoverWithMidCheckpoint's two windows always touched disjoint entity sets. CrossFrontierUpdateWorkload(shape, existingAliveSet) takes the previous phase's alive-set and spawns nothing. On the unfixed engine, all 8 entities recovered with their spawn values:

    Entity(Key=1, Arch=1) slot 0 (CompA): value bytes differ —
      expected [F5-01-00-00-00-00-FA-43-...]   (the window's update)
      got      [01-00-00-00-00-00-00-00-...]   (the checkpointed spawn)
    

    Acceptance criteria

    • RecoveryApplier.ApplySlotToExisting — cluster and flat paths
    • RecoveryDriver routes the !agg.HasSpawn case's aggregated slot payloads to it
    • Test: pre-existing entity mutated in the WAL window, hard crash → recovers with last-tick values (CrossFrontierUpdate_RecoversTheWindowValue_NotTheCheckpointedOne, 3 shapes)
    • Test: last-writer-wins by LSN for two writes to the same slot in one window (CrossFrontierUpdate_TwoWritesInOneWindow_RecoversTheLastOne, [VerifiesRule("CM-03")])
    • DifferentialRecoveryOracleTests / WalCrashSweepTests do not regress — full suite 5,003 passed / 0 failed

    Not closing: the work is on a branch, unmerged.

    🤖 Claude Code · https://claude.ai/code/session_01MuoGAeaJVpnqz6qcoxQ8Df

  7. added a commit that references this issue on Aug 8, 2026
  8. nockawa commented on Aug 8, 2026

    @nockawa
    CollaboratorAuthor

    Audit: the fix is merged, but the issue is not complete — 2 of 6 items remain

    Verified against origin/main @ 2dd0a176 (PR #714), not against the PR description.

    Done (ticked above):

    Item Evidence
    ApplySlotToExisting, cluster and flat RecoveryApplier.cs:288 dispatches to ApplySlotToExistingCluster (:371) when a cluster accessor is present, and falls through to the locations[] / revision-chain branch otherwise. Both paths present.
    RecoveryDriver routes !agg.HasSpawn RecoveryDriver.cs:269.
    Last-tick values, not checkpoint values CrossFrontierUpdate_RecoversTheWindowValue_NotTheCheckpointedOne, all three shapes, green.
    Gates do not regress Full suite 5020 passed / 0 failed / 15 skipped.

    Still open:

    • Commit-discipline interaction for the same slot (CM-03). CrossFrontierUpdate_TwoWritesInOneWindow_RecoversTheLastOne proves last-writer-wins across two separately-committed transactions and carries [VerifiesRule("CM-03")], but its writes go through ShapeOps.Begin — I could not confirm it ever puts a DurabilityDiscipline.Commit record and a tick-fence record on the same slot, which is what this item asks for. The mixed case is the one where LSN ordering could actually diverge between the two producers.
    • The post-Columnar FenceBlock WAL record — cut tick-fence emission cost and volume #559 FenceBlock expansion path. No reference to FenceBlock anywhere in test/Typhon.Engine.Tests/Durability/CrashRecovery/. This item looks simply unwritten.

    Neither gap invalidates the fix; both are coverage the issue asked for and did not get. Leaving open rather than closing on a green suite that does not exercise them.

  9. nockawa commented on Aug 8, 2026

    @nockawa
    CollaboratorAuthor

    Closing. Option A shipped earlier; PR #719 closes the two remaining acceptance criteria.

    CM-03 (last-writer-wins for two updates to the same slot in one window) — already covered. CrossFrontierUpdate_TwoWritesInOneWindow_RecoversTheLastOne carries [VerifiesRule("CM-03")] and is green across all three storage homes.

    The FenceBlock criterion was the interesting one: it could not be checked as the code stood. RecoveryDriver expands a columnar block into exactly the per-(entity, slot) shape the per-entity Slot records produced — deliberately, so recovery semantics are identical — which means every existing assertion passes the same whichever format carried the value. A test claiming to cover the block path would have been indistinguishable from one that never saw a block.

    RecoveryDriver.Result.FenceBlockRecordsExpanded makes the difference observable, and CrossFrontierUpdate_ArrivesThroughTheColumnarFenceBlockPath asserts on it. ClusterSv only, and deliberately not through PostRecoveryShapes: the flat homes emit no blocks, so running them would assert zero and fail for behaviour that is correct.

    Measured: checkpointLsn=16 scanned=25 applied=8 maxLsn=25 fenceBlockExpanded=8 — every applied record reached the applier through the block path, not one of them as a Slot record.

    Option B (ClusterDurability.Checkpoint, #568) remains a separate design question about whether the promise is worth its cost. It is no longer a question about whether the promise is kept.

  10. moved this from Todo to In Progress in Typhonon Aug 8, 2026
  11. moved this from In Progress to Done in Typhonon Aug 8, 2026
  12. added a commit that references this issue on Aug 9, 2026
    438b9f9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Fields

    Priority

    P1-High

    Estimate

    M

    Area

    Durability

    Start date

    None yet

    Target date

    None yet

    Bug status

    None yet

    Product

    Engine

    Projects

    • Status
      Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions