Repository navigation
Description
Split out of #718, which closed with direction 2 (PR #721). That fixed the P0 half — the runtime now re-queries every pull-mode system input once per tick, so a system does see entities spawned while it is running. This issue is the half that fix does not reach.
⚠️ The premise below was measured and is wrong. See the correction after the table.
The residual (as originally filed)
EcsQuery.ToView() has two modes and they behave differently at the same call site:
| built as | membership after a later spawn |
|---|---|
Query<T>().WhereField(...).ToView() |
ViewRegistry, receives spawn/destroy deltas |
Query<T>().ToView() |
frozen at construction until someone calls Refresh(tx) |
Nothing in the API distinguishes them, and the unfiltered form is the one that reads as "all entities of this archetype". Adding a WhereField — a narrowing — is what switches you onto the live path.
For a View passed to a system this no longer matters (BIND-04). For a View a user holds and reads directly, it still does.
Correction: there is no asymmetry in liveness
EcsView.Refresh is the only thing that mutates _entityIds, on either path. Verified by enumerating every mutation site in EcsView.cs and every caller:
ProcessEntry/ProcessEntryOr— the delta appliers — are called from exactly one place, the ring-buffer drain insideRefresh(EcsView.cs:268,:272).PopulateInitialOris called from exactly one place,EcsQuery.cs:791— view construction.RefreshFull/RefreshFullOr/RefreshPullare the remaining sites and are all reached throughRefresh.
So a WhereField view's publisher queues spawn/destroy deltas into its ring buffer, but nothing applies them until someone refreshes. Its Count is exactly as frozen as the unfiltered one's. The two views differ in what a refresh costs, never in whether they self-update.
That is not an oversight: "views never self-refresh" is a documented core invariant (ADR-042, claude/design/Querying/ViewSystem/01-overview.md). A view holds no transaction, so it has no snapshot to refresh against; giving it one would pin the TransactionChain and block MVCC GC for as long as the view lives. The original acceptance criterion "membership is live without the caller calling Refresh" therefore asked for something the engine deliberately forbids, on the strength of a comparison that does not hold.
The real defect: cost. Prototyped, measured, NOT merged.
The residual asymmetry is cost, and it is severe. The unfiltered pull refresh re-queries the whole archetype and set-differences the result — O(N) per refresh, allocating the full set each time (EcsView.RefreshPull, EcsView.cs:300). That is still what main does today.
A prototype replaced it with a per-cluster occupancy-word diff against a per-view snapshot, applying only changed bits. Measured at N = 50 000: 398 568 µs → 23.5 µs per refresh, 2.4 MB → 536 B.
It was not shipped. Review found correctness defects that trace to #582 — the occupancy path reads ActiveClusterIds / ActiveClusterCount and per-cluster occupancy words live on worker threads while other workers structurally mutate them, and that data has no publication protocol and no reclamation quiescence. Fixing it inside the view is not possible; #582 is a prerequisite, and it is Designed with its branch not started (claude/design/Ecs/EntityClusters/12-structural-mutation-safety.md).
Correction to this issue's own record (2026-08-22)
The acceptance list below previously carried five checked boxes describing the prototype as landed. It is not in the tree. Verified on main:
EcsView.TryRefreshViaOccupancy— does not exist.Refreshstill dispatches toRefreshPull(EcsView.cs:228), which still calls_query.Execute()and set-differences.BIND-04inrules/runtime-scheduling.mdhas no occupancy clauses; itsnotestill reads that direction 1 "needs a design, because ViewRegistry is keyed per indexed FIELD and an unfiltered query has no field to register under."ViewCreatedBeforeTheSpawns_ConvergesWithOneCreatedAfteris still[Ignore("#722 …")](SystemInputViewLivenessTests.cs:104).
PR #795 merged carrying this issue's number, but delivered the cluster visibility-summary latch fix (#668) — not the occupancy refresh. Boxes unchecked accordingly.
There is one piece of orphaned drift from the prototype: ArchetypeClusterState.cs:588 cites EcsView.ScanArchetypeOccupancy, a method that exists nowhere in the tree.
Acceptance
- An unfiltered pull view's refresh is O(changed), not O(N) — no full re-query, no full-set allocation per refresh
- The O(1) parallel prepare is preserved (no per-tick full re-query for system inputs)
-
ViewCreatedBeforeTheSpawns_ConvergesWithOneCreatedAfterun-ignored and green — asserts convergence after one refresh, and asserts the delta path was taken rather than the re-query -
BIND-04inrules/runtime-scheduling.mdupdated — itsnotenaming direction 1 as unbuilt is retired, replaced byenforceclauses covering the delta source and the per-entity visibility probe -
ArchetypeClusterState.cs:588's reference to the non-existentEcsView.ScanArchetypeOccupancyresolved -
Membership is live for an unfiltered pull view without the caller calling— withdrawn. Requires a view to hold a transaction, which ADR-042 forbids; and its justification (theRefreshWhereFieldcomparison above) does not hold. No caller ever asked for it.
Blocked on #582 for the occupancy-word approach specifically. The transaction-level changeset (Transaction.PendingSpawns / PendingDestroys) is an alternative delta source that is populated regardless of indexing and carries no concurrent-walk hazard; which source wins is the subject of the #790 design.
Related
- A system's input View built from Query<T>().ToView() is frozen at creation — no system ever processes an entity spawned later #718 — the parent; direction 2 shipped in PR Bug bash round three: four fixes, two reframings and one answered question #721
- [Feature]: Incremental views for all-archetype membership queries without field predicates #790 — the user-facing cost report; the design for the membership channel lives there
- Concurrent cluster walk vs structural mutation: worker threads can read a freed chunk (destroy) or throw IndexOutOfRange (spawn) #582 — concurrent cluster walk vs structural mutation; prerequisite for the occupancy approach
BIND-04inrules/runtime-scheduling.md- SchedulerSystemArchetype touch rollup never emits — its two gates are mutually exclusive for cluster-native parallel systems #631 — the telemetry symptom that led to A system's input View built from Query<T>().ToView() is frozen at creation — no system ever processes an entity spawned later #718
🤖 Split out during bug-bash round three.
Activity
#722 Repoint the quarantined view test at an open issue (#723)
Stop the PR title closing issues, keep it moving the board
Stop the PR title closing issues, keep it moving the board (#726)
nockawa commentedon Aug 12, 2026
Raised P2 → P1, and the direction in the issue body needs revising. Both because of #790, which is this issue arriving from the outside as a performance complaint, and because of what measuring it turned up.
The cost of direction 2 is not what we thought
This issue and #718 both record direction 2's price as "an O(N) re-query per tick", and treat that as the honest cost of correctness. Measured, one unfiltered view over 50 000 entities:
The re-query is not the problem. The diff is, and only because of #791 —
HashUtils.FastHash64multiplies by the golden ratio andHashMapmasks the low bits, so all 50 000EntityIds of one archetype land in 2 buckets of 131 072 and_entityIds.TryAddwalks a 25 000-long probe chain. One instruction takes the refresh to 2 235 us (178x).That reorders the work: #791 lands first, and this issue is then measured against a 2.2 ms baseline rather than a 398 ms one.
Direction 1 as written is probably the wrong endpoint
The body proposes a lifecycle-level notification channel: subscribe by archetype, publish on spawn / destroy / enable, drain per tick. It works, but it keeps the per-entity
HashMap<long>and only removes the 0.8 % term.Since #629 every archetype is cluster-backed and each cluster header carries a 64-bit occupancy word. For an unfiltered query, membership is the union of those words —
EcsQuery.TryCountViaOccupancyalready exploits exactly this forCount()at 66-93x, behind a visibility gate (IsClusterFullyVisibleAt) that is bail-conservative and ablation-tested. Deltas then become an XOR of this tick's occupancy words against last tick's snapshot: 782ulongat 50 000 entities, no per-entity work, no set rebuild, no allocation. It removes the diff and the scan, and it needs no new publisher plumbing on the spawn/destroy paths at all.Two things to design against rather than discover:
ClusterMaxBornTsn/ClusterAnyDiedsummaries already exist — compare the 64 entity-key longs only for clusters whose summary moved, so cost stays proportional to changed clusters, not total..Where(lambda)and spatial pull views keep the per-tick re-query either way. That gating must be explicit and probe-forced in tests (à laQueryPathProbe.ForcedCount), or a mis-selected fast path is silently wrong results rather than slow ones.ClusterAwareViewinclaude/design/Ecs/EntityClusters/08-query-view.mdalready specifies the storage end of this (_clusterMembership+_clusterMatchBits, ~200 bytes vs ~2 MB at 100 k). Full cluster-native view storage also means replacingPartitionEntityViewwithClusterRangePartitionand reworkingContains(pk)— bigger than this issue needs. The increment that closes #722 and #790 keepsHashMap<long>as the membership set and only changes how the refresh computes the delta: occupancy XOR instead of full re-query plus set difference. Downstream consumers are untouched.Related
RefreshFull's pull branch; same code, folded into the same change#722 Record EnsureClusterVisibilityCapacity in the latch-acquisition …
#722 #668 The cluster visibility summary latched permanently, and its…
nockawa commentedon Aug 13, 2026
PR #795 delivers half of this and deliberately leaves the other half. This issue stays open until the second half lands.
Shipping in #795 — the died watermark.
ClusterAnyDiedwas a sticky "has anything ever died in this cluster" bit. That question can only be un-asked by a full rescan, so it was never cleared and a churning archetype latched onto the per-entity probe permanently.ClusterMaxDiedTsnreplaces it: what a reader needs is not whether something died but whether every death is already visible to it, which is a maximum rather than a boolean, and a maximum recovers on its own as snapshots pass the last death. This is the option-B decision taken during design.That change turned out to have a sharp edge worth recording. A sticky bit denies the gate forever, which is safe by being useless; a recovering watermark can grant, and is only correct because
ReleaseSlotclears the occupancy bit at destroy commit. Two callers never held that — WAL replay (cleanup deferred to the orphan sweep) and cluster migration (sets a destination bit, releases only the source) — so both now foldVisibilityUnknown. Without that,Count()over-counts a tombstone permanently after any recovery replaying a below-frontier destroy. #795 also fixes the publication ordering the gate depends on, and writes both invariants down asCLUSTERVIS-01/CLUSTERVIS-02, which nothing had stated.Not in #795 — the O(changed) refresh, and
ViewCreatedBeforeTheSpawns_ConvergesWithOneCreatedAfterstays[Ignore]d against this issue, correctly.The prototype works — 398 568 µs → 23.5 µs per refresh at 50 000 entities, 2.4 MB → 536 B — but three review rounds found ~22 correctness defects concentrated in it, and successive fixes kept producing new ones. The cause is not carelessness: it rests on two engine facts that do not hold. The active-cluster list is not safely walkable (
CLUSTERWALK-01/ #582, open, and explicitly recorded as needing "a snapshot or epoch protocol"), and a set occupancy bit does not imply a live, committed, fully-written entity.The direction being pursued instead: make the delta available only under the tick fence's exclusion guarantee, and have every other caller take the re-query. That removes the whole "is the bitmap lying to me right now" class rather than defending against it site by site. It gives up nothing this issue asked for — the remaining acceptance item was withdrawn on ADR-042 grounds above, and #790's filer feeds his view to a system, which the runtime refreshes for him.
Note this leaves ~13 of the 22 findings untouched, since those were single-threaded logic errors rather than races. Quiescence makes the bitmap trustworthy; it does not make it sufficient, and an old reader still needs the per-entity
BornTSN/DiedTSNcheck.#790 #722 #864 Incremental refresh for unfiltered views, and a dispos…
nockawa commentedon Aug 24, 2026
Done, in #867. Every remaining acceptance item is satisfied, with one honest caveat on the third.
RefreshSystemInputViewsAtTickStartstill drives all three pull shapes (BIND-04keys onIsPullModedeliberately); a membership view's refresh there takes the epoch gate.ViewCreatedBeforeTheSpawns_ConvergesWithOneCreatedAfterun-ignored and green —MEMB-01'son_violation. So the first refresh always resynchronises, and the test now pins both halves: it heals, then the channel takes over.BIND-04updated — thenotedeclaring direction 1 unbuilt is retired; it now records that only the archetype-only shape has a channel and why the other two keep the honest O(N).ScanArchetypeOccupancyreference resolved — repointed atEcsQuery.TryCountViaOccupancy, with the zero-callerIsClusterFullyVisibleAtoverload deleted alongside it.The withdrawn item stays withdrawn: a view still holds no transaction, so membership is not live without a
Refresh. What was actually wrong was the cost of that refresh, which is what this fixes.