Description
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-atomicintused 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 thisArchetypeClusterStatewhendeferFinalize = false" —FlushPendingDestroysdemonstrably does not. Either the comment is wrong or a lock is missing.- Zero
Volatilein eitherTyphonRuntime.csorArchetypeClusterState.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
- Defer structural mutation to the fence (as migration and AABB refresh already are), or
- give the walk a real protocol (versioned/epoch-gated snapshot of the active list), or
- give
SystemAccessDescriptora "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).
Metadata
Metadata
Assignees
Labels
Type
Fields
Priority
Estimate
Area
Start date
Target date
Bug status
Product
Projects
- StatusShow more project fieldsDone
Activity
nockawa commentedon Jul 31, 2026
Analysis complete — moved out of the bug-bash branch into a dedicated initiative
Design doc:
claude/design/Ecs/EntityClusters/12-structural-mutation-safety.mdFive 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.mdfinding N8 states "D's core is a parameter flip plus a drain call, not new machinery", and:281says "Destroy just needs the flag flipped." That is wrong. PassingdeferFinalize: truefromTransaction.Destroyis a no-op at best and a permanent leak in practice:PrepareArchetypeFencezeroes_drainedCountat its top (TickFence.cs:477) — after every user-stage commit already recorded into it. Drains discarded.FinalizeArchetypeFenceearly-returns before the drain whenFenceBranchPath == 0(:730-733vs: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).TyphonRuntime⇒ no fence, ever. Leak for the process lifetime.deferFinalizeis overloaded — it also means "this is a MOVE, not a destroy" and gates SVComponentCollectionrelease (ArchetypeClusterState.cs:2515). Flipping it on destroy leaks a VSBS buffer on every destroy.RecordClusterDrain's grow fallback loses entries (:344re-reads the field outside the lock). Dead today only because pre-sizing bounds it byPendingMigrationCount, 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
MinTSNpassesDiedTSN. Cluster chunks are the outlier that frees synchronously.ClusterRef.cs:504-508states the enumerator filtersOccupancyBits == 0precisely because empty clusters exist during the deferred-drain window. The fix widens an existing documented window rather than inventing one.DiedTSNandEntityMapall stay immediate. Only reclamation moves.The
SystemAccessDescriptoralternative is disqualified on correctness: DAG edges are between systems, but the destroy runs inCommit()inside the per-chunkfinallyon 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++] = chunkIdstores the count before the element (C# evaluation order), verified by JitDisasm. A count-first reader seesn+1then readsIds[n]as0or a stale id; chunk ids start at 1, so0→GetChunkAddress(0). This fires on x64 — program order, not memory model. The release belongs on the count (the linearization point), not the array; on arm64stlris 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 publicArchetypeAccessor.GetClusterEnumerator().The one real cost, and its mitigation
RemoveFromActiveListisO(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
Destroy+Commitlegal? Nothing gates structural mutation to the tick window (_tickInProgressexists but the ECS layer never reads it). If legal, this promotes a documented soft assumption into a hard correctness dependency for entity lifecycle.doc/feature-set/Spatial/spatial-coherent-clustering.md:79says an emptied cluster is "deallocated immediately" — user-facing, would become false.Why it survived
CLUSTERWALK-01isverified: NOT COVERED, and no benchmark covers cluster iteration under concurrent structural churn.ParallelFenceTests.cs:550documents a prior realIndexOutOfRangefrom 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.mdMD-02 is already stale pre-fix, and10-fence-parallelisation.md:121marks 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.
#582 #623 Bug bash: 17 correctness fixes across durability, spatial, …
nockawa commentedon Aug 5, 2026
New reader, and the widest one:
StatisticsRebuilderon a background threadFound by the #629 pre-merge review (finding M3) and added to
claude/rules/ecs.mdCLUSTERWALK-01'sscope: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—RebuildClusterAllwalksfor (int c = 0; c < clusterState.ActiveClusterCount; c += interval)and dereferencesclusterState.ActiveClusterIds[c]through aChunkAccessor, re-readingActiveClusterCountin the loop condition. Reached fromQuerying/internals/StatisticsWorker.cs:154-172, which also readsActiveClusterCountat:159to computeliveEntities.What makes it different from every reader currently listed. The three
TyphonRuntimesites are DAG workers — a tick phase bounds when they can overlap a destroy, even if nothing orders them against one. This one runs on theTyphon-Statisticsbackground 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 —
RebuildClusterAllwas added incf476099. 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:
StatisticsWorker.cs:174-177), so the visible cost is stale statistics rather than a crash;EpochGuardkeeps 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_finalizeLockbefore 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 / teachSystemAccessDescriptorabout 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:
MutationsSinceRebuildmeasured 52 bytes fromActiveClusterCount; 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.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.nockawa commentedon Aug 8, 2026
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
TyphonRuntimeloadedcs.ActiveClusterIdsand thencs.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
ReadActiveClusterListhelper 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.AddToActiveListreleases 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.Lengthrather 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 isFreeChunk'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.#582 Stop AddToActiveList caching the array it appends to — a regress…
13 remaining items
nockawa commentedon Oct 5, 2026
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 byFreeChunk. Nothing guards it and nothing is quarantined.Repro: two new tests in
ClusterWalkDestroyTests(uncommitted in thebug-582worktree).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 throughctx.Transaction. Chunk 1 then walks its Prepare-given range with the documentedGetClusterEnumerator(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_LeaveTheActiveListExactis 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:holds 290 entries, expected 289; stale: [444].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:10053say so, and the engine breaks that assumption in two ways:EcsConcurrencyTests.ParallelSpawnAndDestroy_NoCorruption.TyphonRuntime.cs:2722,CreateConcurrentTransaction).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:
WriteTickFenceis the natural candidate, since EW-01host_modealready makes its quiescence a caller obligation.Options:
_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.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:
_finalizeLockbanner's "exhaustive" acquisition list is stale. At least 9 sites are missing, includingClaimSlotInFreshCluster,AllocateClusterInCell,AddClusterToPerCellIndex,IsClusterIndexed,WidenClusterInPerCellIndexand the three realm-spatial methods.nockawa commentedon Oct 12, 2026
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.ctx.Commands) does not touch the direct-destroy path, so both faces are still live._finalizeLock(FinalizeDrainedClusterLatched).ConcurrentDestroysThatDrainClusters_LeaveTheActiveListExactfailed 7/10 on 4 CPUs without it and passes 0/10 with it. The latch banner and the stale "serial context" comments are corrected.ADestroyCommittedDuringADispatch_DoesNotShowTheWalkAClusterTwiceis 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).#1163 #978 #1164 #946 #1056 #1006 #1165 #1166 #841 #1168 Bug bash rou…
nockawa commentedon Oct 13, 2026
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.ADestroyCommittedDuringADispatch_DoesNotShowTheWalkAClusterTwice(both variants) passes and leaves quarantineConcurrentDestroysThatDrainClusters_LeaveTheActiveListExactstays green: the active list is exact once fencedWriteTickFence, pure-Transient archetypes includedpre-push.shgreen;/code-reviewfindings fixed#582 An emptied cluster is reclaimed at the tick fence, never inside …