Skip to content

Spatial cluster migration leaks ActiveChunkWriters — checkpoint gate never opens, WAL grows unbounded until the process dies #817

Closed

Description

@nockawa

This issue was originally filed as "the coverage gate has no liveness guarantee". That framing is SUPERSEDED — see Root cause below. The gate is correct; it is being lied to by a leaked counter. The original analysis (per-page recLSN refinement, the three correctness gaps in it, the rules/TLA+ impact) is preserved at the bottom because it remains valid as an assessment of that refinement — it is simply not the fix for this bug.

Symptom

WAL grows without bound until the process dies. No segment is ever recycled.

CHECKPT  running True   checkpoints 40   segments recycled 0   pages written 8866   consecutive gated cycles 40
WAL:     22 GB across 86 segments after ~4 min — perfectly linear, nothing reclaimed

A ~10 minute interactive run died with:

Typhon.Engine.WalBackPressureTimeoutException: WAL back-pressure timeout after 30010ms waiting for 130696 bytes
  at WalCommitBuffer.TryClaim (WalCommitBuffer.cs:497)
  at DurabilityLog.AppendFenceBlocks (DurabilityLog.cs:54)
  at DatabaseEngine.FinalizeArchetypeFence (DatabaseEngine.TickFence.cs:823)

Root cause — a leaked ActiveChunkWriters, in the migration path

The coverage gate at CheckpointManager.cs:462 skips any page whose ActiveChunkWriters != 0 (PagedMMF.cs:2081) and gates the whole cycle if even one page is skipped. That behaviour is correct. The defect is that ACW never returns to zero on pages touched by cluster migration.

Measured, with the workload quiescent — tick loop finished, no transaction open, nothing running:

skipped 458  repeated-from-previous-cycle 450  longest single-page streak 40
causes: ACW 24738   writer-held>100ms 0   stale-counter 0
QUIESCENT non-zero ACW: 458 of 458    139:acw=1  140:acw=2  162:acw=1  163:acw=4  164:acw=3  186:acw=11

Every skipped page still holds writer registrations with nothing running. Page 186 holds eleven. Counts accumulate over the run.

Supporting evidence:

  • Streak 40 of 40 cycles — no page ever came free across 40 cycles × 3 retry passes.
  • Skip cause is exclusively the ACW check. writer-held>100ms and stale-counter are both zero across every run, so the seqlock mechanisms are refuted.
  • Per-page increment/decrement trace on one page: 210 increments, 209 decrements — net 1, exactly matching its observed quiescent acw=1. The arithmetic closes.

Isolated to migration by A/B (identical config, only cell size changed so that one giant cell means zero migrations):

migrations/tick pages with quiescent ACW ≠ 0 consecutive gated cycles
cellSize=2000 24 45 of 45 12
cellSize=200000 0 0 of 0 0

Zero migrations ⇒ zero leak ⇒ the gate opens normally and the WAL reclaims.

Call stacks registering ACW on an affected page are all under the tick fence / migration machinery:

DatabaseEngine.ExecuteMigrations · ExecuteMigrationsSlice · ProcessArchetypeFence · WriteClusterTickFence
ArchetypeClusterState.ClaimSlotInCell · TryClaimSlotInCluster · AllocateNewCluster
ArchetypeClusterState.DrainPendingClusterFinalizations

⚠️ Do not read the per-signature net in that trace as a pairing. Increments originate in ChunkAccessor.MarkSlotDirty; decrements in CommitChanges / Dispose / ChangeSet.FlushDeferredEvictions. The stacks differ structurally, so a signature showing inc 11 dec 0 is not itself a leak — only the total is meaningful.

Where to look

ChunkAccessor increments ACW once per dirty slot (ChunkAccessor.cs:159, guarded by _dirtyFlags), and the three release paths each clear the matching bit:

Path Site
CommitChanges (also called from Dispose) ChunkAccessor.cs:281
EvictSlot, standalone ChunkAccessor.cs:522
EvictSlot, transaction — deferred ChunkAccessor.cs:509 → ChangeSet.cs:131

All four are balanced on inspection, so the leak is a migration path that dirties a slot through an accessor that is neither committed nor evicted — or one where the page's slot is re-pointed before the bit is cleared.

Impact

  • WAL grows at the full write rate forever; the database is otherwise healthy (data file 120 MB against 22 GB of log).
  • MarkReclaimable has only two call sites, both driven by CheckpointLSN, so there is no secondary path that recovers.
  • No ResourceOptions knob changes the outcome. Triggers are the timer (CheckpointIntervalMs, default 30 000), page-cache back-pressure (DatabaseEngine.cs:1137), ForceCheckpoint, BulkLoad and shutdown — more cycles against a gate held shut by a leaked counter simply yields more gated cycles.
  • 04-checkpoint.md:74 states WAL growth "is bounded by disk monitoring + backpressure". There is no disk monitoring, and the back-pressure is a 30 s timeout that terminates the process.

Repro

cd demo/SpaceBattle
dotnet run -c Release -- --autoTicks=2000 --initialShipsPerFaction=6000 --forceCheckpointEveryTicks=50

Reports CHECKPT / SKIPS lines including the quiescent ACW read. --cellSize=200000 makes it disappear; --acwTracePage=N buckets ACW increments and decrements for one page by call stack. ⚠️ Writes several GB of WAL; delete bin/Release/net10.0/SpaceBattle.typhon afterwards.

Diagnostics used are additive and behaviour-neutral: PagedMMF.ActiveChunkWritersOf / skip-cause counters / AcwTracePage, CheckpointManager.LastSkippedPages / RepeatSkippedPages / MaxConsecutiveSkipsForOnePage / SkipCauses.

Fix

Find and close the unbalanced increment in the migration path. That is the whole bug — with it fixed, the gate opens, segments recycle, and WAL growth is bounded.

Worth adding regardless, because this was invisible for so long:

  1. A liveness clause in CK-03 and an assertion or health signal when ConsecutiveGatedCycles exceeds a threshold. The engine already tracked the number; nothing surfaced it.
  2. A debug-mode check that ACW returns to zero for all pages at quiesce.
  3. Fix ADR-037, which documents a "WAL pressure (segments > 50 % consumed)" checkpoint trigger that is not implemented.

Superseded analysis — the per-page recLSN refinement

Retained because the assessment stands on its own merits, and because 04-checkpoint.md:75-77 specifies this refinement as future work gated on ConsecutiveGatedCycles telemetry. It would NOT have fixed this bug — min(recLSN) would freeze at the leaked pages' stamps and the WAL would still grow unbounded, just from a later start. Same for the hard-pass valve at 04-checkpoint.md:71-74, which spins waiting for ACW == 0 — a wait that never succeeds against a leak.

If the refinement is ever built, three correctness gaps in it are not addressed by the design doc:

  1. The stamp is not "the current LSN". PREPARE → APPEND → PUBLISH are separate and the chain lock is per-entity, so page-apply order ≠ LSN order: Tx A appends at 100 and stalls; Tx B appends at 200, publishes, dirties clean page P → recLSN(P) = 200; A then publishes into P. Trimming to 200 deletes A's record ⇒ committed data loss. ARIES is immune because the log record is generated under the same page latch as the update; Typhon deliberately is not. The correct stamp is a low-water of appended-but-unpublished LSNs, min(LastAppendedLsn + 1, min{lsn(T) : T appended, not published}) — a watermark that does not exist today.
  2. Mandatory clamp. min(recLSN) can exceed barrierLsn, pushing CheckpointLSN past DurableLsn and violating WP-01 and CK-02. Must be min(barrierLsn, minRecLsn).
  3. BulkManifest is not page-attributable. Recovery's orphan detection needs BulkBegin retained until BulkEnd is durable; a page-derived watermark needs an explicit floor min(safeLsn, oldestOpenBulkBeginLsn).

Scope it would carry: rules CK-02/03/04, CP-11, CP-05/06, WP-01/09, BL-02, REC-04, PS-01; re-modelling rules/tla/CheckpointProtocol.tla (S1) and re-validating its BreakCoverageGate mutant; and a conflict with 06-durability.md principle #6 ("zero Wal/Lsn/Fpi identifiers in Storage/") that the invariants CI job would not catch, since it greps only for RecordFormat.

Related doc drift found while investigating

Activity

  1. added theissue type on Aug 15, 2026
  2. updated Area Durability, Priority P0-Critical, Estimate L and Product Engine on Aug 15, 2026
  3. changed the title [-]Checkpoint coverage gate has no liveness guarantee — WAL grows unbounded until the process dies[/-] [+]Spatial cluster migration leaks ActiveChunkWriters — checkpoint gate never opens, WAL grows unbounded until the process dies[/+] on Aug 15, 2026
  4. nockawa commented on Aug 15, 2026

    @nockawa
    CollaboratorAuthor

    Root cause found and fixed — one missing using

    ArchetypeClusterState.DrainPendingClusterFinalizations (ArchetypeClusterState.cs:386) created two ChunkAccessors, dirtied pages through them, and never disposed either:

    var clusterAccessor   = hasCluster ? ClusterSegment.CreateChunkAccessor() : default;
    var transientAccessor = TransientSegment != null ? TransientSegment.CreateChunkAccessor() : default;
    
    for (int i = 0; i < count; i++)
    {
        byte* clusterBase = ... clusterAccessor.GetChunkAddress(chunkId, true);   // dirty: true
        ...
    }
    _drainedCount = 0;
    }   // no Dispose, no CommitChanges

    GetChunkAddress(chunkId, dirty: true) → MarkSlotDirty → IncrementActiveChunkWriters. The release is driven only by CommitChanges/Dispose, so every drained cluster leaked one ACW on its page, permanently. That is why counts accumulated (acw=11 on a page drained eleven times), why it was exclusively the migration path, and why zero migrations meant zero leak.

    Fix

    using var clusterAccessor   = hasCluster ? ClusterSegment.CreateChunkAccessor() : default;
    using var transientAccessor = TransientSegment != null ? TransientSegment.CreateChunkAccessor() : default;

    Disposing a default accessor is safe — Dispose returns immediately when _segment is null.

    How it was isolated

    An outstanding-increment ledger: push the call stack on every ACW increment for one page, pop on every decrement, and print whatever survives to a quiesced end of run. The bucket-by-stack table could not pair anything (increments originate in MarkSlotDirty, decrements in CommitChanges/Dispose/FlushDeferredEvictions — structurally different stacks), but the ledger names the site directly:

    LEAKED x1   ArchetypeClusterState.DrainPendingClusterFinalizations
                <- DatabaseEngine.FinalizeArchetypeFence
                <- DatabaseEngine.ProcessArchetypeFence
                <- WriteClusterTickFence <- WriteTickFenceCore <- WriteTickFence
    

    Verification — same workload, 40 checkpoints, 51 migrations/tick

    before after
    Segments recycled 0 11
    Consecutive gated cycles 40 0
    Pages skipped 458 0
    Quiescent non-zero ACW 458 of 458 0 of 0
    WAL after 2000 ticks 22 GB / 86 files 2.3 GB / 9 files

    WAL is bounded again — segments recycle and the file count stays flat instead of climbing linearly.

    Suite

    5287 passed / 1 failed / 16 skipped both with and without the fix, and the single failure is a different test each run (OverloadThrottleTests.SkippedSystem_SuccessorsStillExecute with the fix, TickFenceSingleVersion_…AcrossAHardCrash_… on the baseline). That is the known random-victim flake band, not a regression — the victim passes 5/5 in isolation. ClusterMigrationTests is 25/25 green.

    New rule + regression test

    Neither CP-11 nor CP-12 required that a registration is ever released — CP-11 constrains when ACW may be observed non-zero, CP-12 when the decrement may be deferred. The conservation invariant was simply absent, which is why 5 000+ tests walked past this. Added:

    CP-13: ActiveChunkWriters conservation [fatal][silent] (rules/durability.md)

    invariant every IncrementActiveChunkWriters is matched by exactly one DecrementActiveChunkWriters
    invariant no writer in flight → ∀ page: page.ACW == 0
    scope: ChunkAccessor.MarkSlotDirty, ChunkAccessor.CommitChanges, ChunkAccessor.Dispose,
           ChangeSet.FlushDeferredEvictions, ArchetypeClusterState.DrainPendingClusterFinalizations
    

    [VerifiesRule("CP-13")] ClusterMigrationTests.ClusterFinalization_ReleasesEveryActiveChunkWriter — spawns 24 entities in one cell, moves them all out so the source cluster empties and is drained, then asserts CountPagesWithActiveChunkWriters() == 0 with nothing in flight. Quiescence is the whole trick: while a workload is running, a leaked registration is indistinguishable from a busy page.

    Confirmed genuine — red without the fix (Expected: 0, But was: 1), green with it.

    Still open from the original report

  5. added a commit that references this issue on Aug 15, 2026
  6. moved this to Done in Typhonon Aug 15, 2026
  7. added a commit that references this issue on Aug 19, 2026
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

    P0-Critical

    Estimate

    L

    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