Skip to content

Concurrent cluster walk vs structural mutation: worker threads can read a freed chunk (destroy) or throw IndexOutOfRange (spawn) #582

Closed

Description

@nockawa

Found by the 2026-07-27 claude/rules/ audit. I wrote a candidate rule (CLUSTERWALK-01) for this and explicitly asked a reviewing agent to refute it as an over-stated invariant. It could not — it confirmed reachability and found the severity is higher than I stated, plus a second failure face.

The race

ActiveClusterIds / ActiveClusterCount are read live, per chunk, on worker threads — while another worker can structurally mutate them inside Commit().

Readers (src/Typhon.Engine/Runtime/public/TyphonRuntime.cs): ExecuteChunkWithAccessor:1507,1512 and :1564,1569; ExecuteChunkWithTransaction:1724,1729. These feed ctx.ClusterIds / StartClusterIndex / EndClusterIndex.

Mutator: Transaction.Destroy + Commit → FlushEcsPendingOperations → FlushPendingDestroys (Transactions/public/Transaction.ECS.cs:1297,2219) → ReleaseSlot (Ecs/internals/ArchetypeClusterState.cs:2493,2544) → RemoveFromActiveList:2406, which does a non-atomic swap-with-last then a separate decrement (:2424-2425).

Nothing excludes the overlap. Destroys commit in a worker's finally via SystemEndCallback (Runtime/public/DagScheduler.cs:1199,1643), concurrent with other systems still running. FlushPendingDestroys takes only EpochGuard.Enter (Transaction.ECS.cs:2226) — reclamation deferral, not mutual exclusion. Systems in sibling DAGs on one track have no ordering at all.

Face 1 — destroy: read of a freed chunk [fatal][silent]

Precondition (narrower than a plain destroy): the destroy drains the cluster's last occupant — clusterDrained (:2509) with deferFinalize == false (:2517-2533).

With a walker holding a captured count N, swap-with-last leaves the former tail duplicated at index i and still present at N-1: one cluster is visited twice, the destroyed one skipped. Worse, that cluster's chunk is FreeChunk'd two lines later (:2531-2532) — so the walk can touch a freed and possibly recycled chunk. Use-after-free, not merely a miscount.

Face 2 — spawn: IndexOutOfRangeException [fatal], loud

TyphonRuntime.cs:1193-1194 (inside OnParallelQueryPrepare:1105, which the file itself documents at :1818 as running on multiple worker threads) loads array first, count second. A concurrent AddToActiveList resize (ArchetypeClusterState.cs:2389-2393) swaps the array reference → old array + new count → out-of-range. The three chunk-read sites happen to load count-first and are safe against resize.

Why the scheduler cannot prevent it

SystemAccessDescriptor has no vocabulary for "structurally mutates archetype A". A system that reads a component to pick victims and then calls tx.Destroy declares only Reads<T>; the walker declares Reads/ReadsFresh<T>. Reads × Reads derives no edge, and AC-01/AC-02 raise nothing. Both declarations are entirely legal and the build is silent.

Supporting notes

  • ClusterSetVersion (:561) is a plain non-atomic int used only as a rebuild-staleness hint (TierClusterIndex.cs:142), and it is incremented after the mutation (:2434). It is not a seqlock, so no reader could version-gate soundly even if it tried.
  • ReleaseSlot's own doc comment says "Caller owns the writer mutex for this ArchetypeClusterState when deferFinalize = false" — FlushPendingDestroys demonstrably does not. Either the comment is wrong or a lock is missing.
  • Zero Volatile in either TyphonRuntime.cs or ArchetypeClusterState.cs, so per CLAUDE.md's arm64 discipline the read side is not a valid lock-free protocol on a weak model regardless of load order.

Historical note

The AntHill decomposition hit this and resolved it by removing every entity destroy (respawn-as-larva) rather than by fencing — i.e. the hazard was avoided, not fixed.

Fix directions

  1. Defer structural mutation to the fence (as migration and AABB refresh already are), or
  2. give the walk a real protocol (versioned/epoch-gated snapshot of the active list), or
  3. give SystemAccessDescriptor a "structurally mutates archetype" declaration so the deriver can order it.

Rule CLUSTERWALK-01 in claude/rules/ecs.md records the invariant; it needs updating per the above (drain-only precondition, freed-chunk severity, spawn face, drop the mutex claim).

Activity

  1. added theissue type on Jul 27, 2026
  2. updated Priority P0-Critical, Estimate L and Product Engine on Jul 30, 2026
  3. nockawa commented on Jul 31, 2026

    @nockawa
    CollaboratorAuthor

    Analysis complete — moved out of the bug-bash branch into a dedicated initiative

    Design doc: claude/design/Ecs/EntityClusters/12-structural-mutation-safety.md

    Five parallel analyses (deferral integration, adversarial refutation, publication-protocol audit, performance, rules/docs conformance). Every load-bearing claim below was re-verified against the tree before being recorded.

    The planned fix does not work

    claude/design/Runtime/09-tick-pipelining.md finding N8 states "D's core is a parameter flip plus a drain call, not new machinery", and :281 says "Destroy just needs the flag flipped." That is wrong. Passing deferFinalize: true from Transaction.Destroy is a no-op at best and a permanent leak in practice:

    # Blocker
    B1 PrepareArchetypeFence zeroes _drainedCount at its top (TickFence.cs:477) — after every user-stage commit already recorded into it. Drains discarded.
    B2 FinalizeArchetypeFence early-returns before the drain when FenceBranchPath == 0 (:730-733 vs :744) — and a destroy never marks the cluster dirty, so a destroy-only tick on a non-spatial archetype produces exactly that state. Pure-Transient archetypes: unreachable by construction (:513).
    B3 No TyphonRuntime ⇒ no fence, ever. Leak for the process lifetime.
    B4 deferFinalize is overloaded — it also means "this is a MOVE, not a destroy" and gates SV ComponentCollection release (ArchetypeClusterState.cs:2515). Flipping it on destroy leaks a VSBS buffer on every destroy.
    B5 RecordClusterDrain's grow fallback loses entries (:344 re-reads the field outside the lock). Dead today only because pre-sizing bounds it by PendingMigrationCount, which has nothing to do with destroys.

    B1 and B2 must land together — fixing B1 alone lets stale chunkIds survive across ticks, and since the allocator takes the lowest clear bit, the drain would then free a live cluster. Leak → corruption.

    Deferral is still right, for reasons stronger than the original argument

    • ADR-035 precedent — MVCC content chunks already defer reclamation until MinTSN passes DiedTSN. Cluster chunks are the outlier that frees synchronously.
    • The window is already documented and tolerated — ClusterRef.cs:504-508 states the enumerator filters OccupancyBits == 0 precisely because empty clusters exist during the deferred-drain window. The fix widens an existing documented window rather than inventing one.
    • No documented visibility guarantee breaks — occupancy bits, DiedTSN and EntityMap all stay immediate. Only reclamation moves.
    • Zero hot-path cost, structurally — count and array are captured once per chunk dispatch, never per iteration. It also reduces cross-worker contention versus today's inline path.

    The SystemAccessDescriptor alternative is disqualified on correctness: DAG edges are between systems, but the destroy runs in Commit() inside the per-chunk finally on every worker for chunks of the same system. A system destroying entities it iterates races itself.

    Face 2 is a separate, independently-fixable defect — and worse than described

    ActiveClusterIds[ActiveClusterCount++] = chunkId stores the count before the element (C# evaluation order), verified by JitDisasm. A count-first reader sees n+1 then reads Ids[n] as 0 or a stale id; chunk ids start at 1, so 0 → GetChunkAddress(0). This fires on x64 — program order, not memory model. The release belongs on the count (the linearization point), not the array; on arm64 stlr is one-way and a later plain store may float above it.

    There are four array-first readers, not two — including ClusterRef.cs:554/556, the public ArchetypeAccessor.GetClusterEnumerator().

    The one real cost, and its mitigation

    RemoveFromActiveList is O(ActiveClusterCount), run per drain on the serial fence: +2.5 ms at 1000 drains × 4546 clusters, against a fence already ~960 µs on one worker with 27 idle. Batching the eviction (sort ids, single pass) is 41–300× and improves today's code too. Fold it in.

    Decisions owed before implementation

    1. Are off-tick Destroy + Commit legal? Nothing gates structural mutation to the tick window (_tickInProgress exists but the ECS layer never reads it). If legal, this promotes a documented soft assumption into a hard correctness dependency for entity lifecycle.
    2. doc/feature-set/Spatial/spatial-coherent-clustering.md:79 says an emptied cluster is "deallocated immediately" — user-facing, would become false.
    3. The no-runtime path — keep the immediate path when no runtime is bound (principled: no runtime ⇒ no parallel dispatch ⇒ no hazard), or defer unconditionally and rewrite the four tests that assert the current contract.

    Why it survived

    CLUSTERWALK-01 is verified: NOT COVERED, and no benchmark covers cluster iteration under concurrent structural churn. ParallelFenceTests.cs:550 documents a prior real IndexOutOfRange from this exact class. Write the regression test first.

    Also found — filed separately

    Four adjacent defects and a doc-accuracy task, listed in §10 and §9 of the design doc. claude/rules/spatial.md MD-02 is already stale pre-fix, and 10-fence-parallelisation.md:121 marks this state "Already solved" — which is why the fence-parallelisation review didn't catch it.

    Estimate confirmed L. Not a bug-fix; needs the ADR, the rules rewrite (three replacement rules drafted), ~13 doc updates, and changes across the commit path, the fence, and the public enumerator.

  4. added a commit that references this issue on Jul 31, 2026
  5. moved this to Todo in Typhonon Jul 31, 2026
  6. nockawa commented on Aug 5, 2026

    @nockawa
    CollaboratorAuthor

    New reader, and the widest one: StatisticsRebuilder on a background thread

    Found by the #629 pre-merge review (finding M3) and added to claude/rules/ecs.md CLUSTERWALK-01's scope: line. Filing it here rather than fixing it, since it is the same race this issue already tracks.

    Reader: Querying/internals/StatisticsRebuilder.cs:118-127 — RebuildClusterAll walks for (int c = 0; c < clusterState.ActiveClusterCount; c += interval) and dereferences clusterState.ActiveClusterIds[c] through a ChunkAccessor, re-reading ActiveClusterCount in the loop condition. Reached from Querying/internals/StatisticsWorker.cs:154-172, which also reads ActiveClusterCount at :159 to compute liveEntities.

    What makes it different from every reader currently listed. The three TyphonRuntime sites are DAG workers — a tick phase bounds when they can overlap a destroy, even if nothing orders them against one. This one runs on the Typhon-Statistics background thread (StatisticsWorker.cs:82-89, IsBackground = true, BelowNormal), woken by a timer. No tick phase bounds it, so it can be mid-walk during any commit on any thread. It is also on by default (StatisticsOptions.cs:31).

    Genuinely new on this branch — RebuildClusterAll was added in cf476099. It is not a pre-existing site that went unnoticed.

    Blast radius is narrower than the worker-thread sites, though, which is why the review ranked it MEDIUM and not with the P0 faces above:

    • the throw is swallowed (StatisticsWorker.cs:174-177), so the visible cost is stale statistics rather than a crash;
    • a garbage sample produces a bad plan, not wrong rows;
    • EpochGuard keeps the pages mapped, so the freed-chunk read of Face 1 cannot fault here.

    Not fixed in this sprint, deliberately. The two options the review gave were "add it to #582's list" or "snapshot (ids, count) under _finalizeLock before the walk". The snapshot is ~5 lines and would close this reader specifically, but it would also be the fourth different ad-hoc protocol over the same list — this issue's own fix directions (defer to the fence / give the walk a real epoch-gated snapshot / teach SystemAccessDescriptor about structural mutation) all supersede it. Recording it so the eventual fix covers this reader too.

    Two sibling findings from the same review were fixed rather than filed, both in the scaffolding around the same cluster state:

    • M4 — MutationsSinceRebuild measured 52 bytes from ActiveClusterCount; since objects are 8-byte aligned rather than 64, that put them in one cache line for 2 of the 8 possible alignments, per instance. Now padded, and the increment is hoisted out of the per-field loop.
    • M5 — ZoneMapArray's three arrays plus capacity were published with no lock and no ordering. Reachable on x64, not just arm64: Array.Resize(ref _mins, …) re-reads the field, so two growers could leave the arrays at different lengths. Now one immutable snapshot under a shared/exclusive latch.
  7. nockawa commented on Aug 8, 2026

    @nockawa
    CollaboratorAuthor

    Face 2 fixed in PR #719. Face 1 is not fixed and not claimed — this issue should stay open for it.

    Face 2

    Three sites in TyphonRuntime loaded cs.ActiveClusterIds and then cs.ActiveClusterCount — the dormancy promote, the checkerboard promote, and the non-tier chunk partition. Worth adding to the issue's analysis: this needs no reordering to fault, so it is not only an arm64 concern. Read the length-16 array, let a concurrent spawn resize and bump the count to 17, read 17, index 16 of the old array. Plain interleaving, reachable on x64.

    All five read sites now go through one ReadActiveClusterList helper that acquires count then array and clamps. Concentrating it is the point: the two sites that already loaded count first were right by accident, and nothing stopped the next one from being written either way. AddToActiveList releases the grown array before the count, which is the half the acquire pairs with.

    The tests construct the interleaving rather than racing for it. A 40 000-add spin — about twelve resizes — landed inside the two-instruction window zero times in three runs, so a stress test here would have asserted that a safe order is safe and nothing more. Four deterministic cases run in 4 ms, and one of them positively demonstrates the removed order producing count > ids.Length rather than merely asserting the new one does not.

    Face 1 — still open

    RemoveFromActiveList's swap-with-last against a walker holding a captured count can still show one cluster twice, skip the destroyed one, and let the walk touch a chunk that is FreeChunk'd two lines later. Ordering does not touch that; it needs a real snapshot or epoch protocol, which is one of the three fix directions this issue already lists. Said so in the code comments and the test remarks so the commit is not misread as closing this.

  8. moved this from Todo to In Progress in Typhonon Aug 8, 2026
  9. added a commit that references this issue on Aug 8, 2026
  10. 13 remaining items

  11. moved this from Todo to In Progress in Typhonon Oct 5, 2026
  12. nockawa commented on Oct 5, 2026

    @nockawa
    CollaboratorAuthor

    Bug bash 2026-10-05 — Needs Loïc's call

    Still live on main: yes, at cca609b0. A destroy that drains a cluster still finalizes inline on the committing thread (ArchetypeClusterState.cs:10053-10058): RemoveFromActiveList (an unlatched swap-with-last, :9910), followed by FreeChunk. Nothing guards it and nothing is quarantined.

    Repro: two new tests in ClusterWalkDestroyTests (uncommitted in the bug-582 worktree).

    • ADestroyCommittedDuringADispatch_DoesNotShowTheWalkAClusterTwice(false/true) is deterministic and fails 10/10 runs on 4 CPUs, on both the accessor path and the per-chunk-Transaction path. It runs with one worker. Chunk 0 empties the first cluster of chunk 1's range and commits, either through a side transaction (EW-01 compliant) or through ctx.Transaction. Chunk 1 then walks its Prepare-given range with the documented GetClusterEnumerator(ctx.ClusterIds, Start, End) idiom and visits the tail cluster twice: tick 0's walk met cluster(s) [36] twice after a destroy drained cluster 19. That overload doesn't clamp (ClusterRef.cs:1378).
    • ConcurrentDestroysThatDrainClusters_LeaveTheActiveListExact is a new face that needs no walker and no runtime. Two user threads each commit their own transactions, and every destroy drains a cluster. It fails 4/10 runs on 4 CPUs. Two failure modes appeared:
      • A freed id stays in the list: holds 290 entries, expected 289; stale: [444].
      • A live cluster is dropped: stale: [363], missing: [362]. That cluster's entities become invisible to every active-list walk, and its chunk is never freed.

    Root cause: the inline finalize assumes a single-threaded caller per archetype. Both :81 ("removal happens only from serial contexts") and :10053 say so, and the engine breaks that assumption in two ways:

    Two removers interleave inside RemoveFromActiveList's read-modify-write. Evidence: serializing removers alone (below) takes the stress test from 4/10 red to 0/10, while the walker test stays 10/10 red.

    Evidence against D1/D3 in the design doc:

    • D1: concurrent structural mutation can't be declared illegal without breaking a tested contract and the runtime's own per-chunk commits. Deferral therefore has to be unconditional.
    • D3: the premise "no runtime ⇒ no concurrency ⇒ no hazard" is false. The stress test uses no runtime. A runtime-less host needs its own reclamation point. WriteTickFence is the natural candidate, since EW-01 host_mode already makes its quiescence a caller obligation.

    Options:

    • A — stopgap, bounded: run the inline finalize under _finalizeLock (FinalizeDrainedClusterLatched, uncommitted in the worktree). It closes remover-vs-remover and remover-vs-latched-appender corruption. It does NOT fix walkers, or a claim that CASes into a cluster between its last-bit clear and its free (inferred, not reproduced). It adds no rule change, but the latch banner has to list the new acquisition site.
    • B — the real fix: §5.1 fence deferral, now unconditional per the evidence above, plus D2 (the user-facing "deallocated immediately" text).
    • C — interim guidance: systems destroy through ctx.Commands (ENG-01 step 2: the write side — ctx.Commands, per-worker buffers, key blocks and write-time validation #1099). Those commands are applied serially before the fence (TyphonRuntime.cs:3104) and avoid every face.

    Recommendation: A now as a separate commit (it fixes silent list corruption that exists today, with or without a runtime), then B. The two new tests become B's acceptance criteria #1 and #8.

    Open:

    • The _finalizeLock banner's "exhaustive" acquisition list is stale. At least 9 sites are missing, including ClaimSlotInFreshCluster, AllocateClusterInCell, AddClusterToPerCellIndex, IsClusterIndexed, WidenClusterInPerCellIndex and the three realm-spatial methods.
    • No overlap with the In-Progress branches.
  13. moved this from Todo to In Progress in Typhonon Oct 12, 2026
  14. nockawa commented on Oct 12, 2026

    @nockawa
    CollaboratorAuthor

    Bug bash 2026-10-12 (round 2): writer race fixed on bug/582-cluster-walk-structural-race @ 51f9389. Face 1 still needs Loïc's call.

    • Rebased on main @ f83ec31. Main's [doc-drift] Documentation fixes 2026-10-03 #1109 (ctx.Commands) does not touch the direct-destroy path, so both faces are still live.
    • Fixed (writer vs writer). A destroy's commit that drains a cluster now finalizes it under _finalizeLock (FinalizeDrainedClusterLatched). ConcurrentDestroysThatDrainClusters_LeaveTheActiveListExact failed 7/10 on 4 CPUs without it and passes 0/10 with it. The latch banner and the stale "serial context" comments are corrected.
    • Face 1 (a walker against a removal) is unchanged. ADestroyCommittedDuringADispatch_DoesNotShowTheWalkAClusterTwice is deterministic and still red. It is quarantined against this issue as the acceptance test for the fence deferral, which is still your decision (D1–D3).
    • Gate: green.
  15. moved this from In Progress to Todo in Typhonon Oct 12, 2026
  16. added a commit that references this issue on Oct 12, 2026
  17. nockawa commented on Oct 13, 2026

    @nockawa
    CollaboratorAuthor

    Face 1 — fence-deferred cluster finalize: decisions and acceptance criteria (2026-10-13)

    Decided: D1 off-tick structural mutation is legal, so deferral is unconditional. D2 "an emptied cluster is deallocated immediately" becomes "at the next fence". D3 no immediate path without a runtime; runtime-less hosts reclaim at WriteTickFence. A spawn may refill a drained cluster before the fence: Finalize seals it with a CAS (occupancy 0 → reads as full) and keeps it if the CAS loses.

    Branch: feature/582-deferred-cluster-finalize.

    • AC1 A destroy that drains a cluster no longer evicts or frees on the committing thread; it clears the bit and records the cluster for the fence (persistent and transient)
    • AC2 ADestroyCommittedDuringADispatch_DoesNotShowTheWalkAClusterTwice (both variants) passes and leaves quarantine
    • AC3 ConcurrentDestroysThatDrainClusters_LeaveTheActiveListExact stays green: the active list is exact once fenced
    • AC4 The fence finalizes drained clusters (cell detach, batched eviction O(N + D log D), chunk free) at the runtime fence and at WriteTickFence, pure-Transient archetypes included
    • AC5 Seal: a cluster refilled before the fence is kept; a spawn racing the seal never lands in a freed cluster
    • AC6 The spawn claim path gains no per-claim check
    • AC7 Tests asserting immediate eviction are rewritten to fence semantics
    • AC8 ADR (D1/D2/D3), CLUSTERWALK rule updates with verifying tests, user-facing doc corrected
    • AC9 Perf: fence cost at 1 000 drains / ~4 500 active clusters measured; commit-path destroy does not regress
    • AC10 pre-push.sh green; /code-review findings fixed
  18. moved this from Todo to In Progress in Typhonon Oct 13, 2026
  19. changed
    Bug status
    toon Oct 13, 2026
  20. added a commit that references this issue on Oct 13, 2026
  21. moved this from In Progress to Done in Typhonon Oct 13, 2026
  22. changed
    Bug status
    toon Oct 13, 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

    Runtime

    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