Skip to content

A pull View held by user code is frozen until someone calls Refresh, while the incremental variant of the same call is live #722

Closed

Description

@nockawa

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() live — registered with 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 inside Refresh (EcsView.cs:268, :272).
  • PopulateInitialOr is called from exactly one place, EcsQuery.cs:791 — view construction.
  • RefreshFull / RefreshFullOr / RefreshPull are the remaining sites and are all reached through Refresh.

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. Refresh still dispatches to RefreshPull (EcsView.cs:228), which still calls _query.Execute() and set-differences.
  • BIND-04 in rules/runtime-scheduling.md has no occupancy clauses; its note still 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_ConvergesWithOneCreatedAfter is 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_ConvergesWithOneCreatedAfter un-ignored and green — asserts convergence after one refresh, and asserts the delta path was taken rather than the re-query
  • BIND-04 in rules/runtime-scheduling.md updated — its note naming direction 1 as unbuilt is retired, replaced by enforce clauses covering the delta source and the per-entity visibility probe
  • ArchetypeClusterState.cs:588's reference to the non-existent EcsView.ScanArchetypeOccupancy resolved
  • Membership is live for an unfiltered pull view without the caller calling Refresh — withdrawn. Requires a view to hold a transaction, which ADR-042 forbids; and its justification (the WhereField comparison 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

🤖 Split out during bug-bash round three.

Activity

  1. self-assigned this
    on Aug 8, 2026
  2. updated Area Query, Estimate L, Product Engine and Priority P2-Medium on Aug 8, 2026
  3. added theissue type on Aug 8, 2026
  4. added a commit that references this issue on Aug 8, 2026
  5. reopened this on Aug 8, 2026
  6. moved this to Todo in Typhonon Aug 8, 2026
  7. nockawa commented on Aug 12, 2026

    @nockawa
    CollaboratorAuthor

    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:

    RefreshPull = 398 568 us / tick
      ├─ Execute()  (the O(N) rescan)  =   3 189 us   (0.8 %)
      └─ the membership diff           = 395 344 us  (99.2 %)
    

    The re-query is not the problem. The diff is, and only because of #791 — HashUtils.FastHash64 multiplies by the golden ratio and HashMap masks the low bits, so all 50 000 EntityIds of one archetype land in 2 buckets of 131 072 and _entityIds.TryAdd walks 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.TryCountViaOccupancy already exploits exactly this for Count() 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: 782 ulong at 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:

    • Slot reuse inside one tick (destroy A in slot 5, spawn B into slot 5) makes a pure XOR blind to an identity swap. The per-cluster ClusterMaxBornTsn / ClusterAnyDied summaries already exist — compare the 64 entity-key longs only for clusters whose summary moved, so cost stays proportional to changed clusters, not total.
    • Applicability is unchanged from direction 1. A membership channel is exact only for the unfiltered case; .Where(lambda) and spatial pull views keep the per-tick re-query either way. That gating must be explicit and probe-forced in tests (à la QueryPathProbe.ForcedCount), or a mis-selected fast path is silently wrong results rather than slow ones.

    ClusterAwareView in claude/design/Ecs/EntityClusters/08-query-view.md already specifies the storage end of this (_clusterMembership + _clusterMatchBits, ~200 bytes vs ~2 MB at 100 k). Full cluster-native view storage also means replacing PartitionEntityView with ClusterRangePartition and reworking Contains(pk) — bigger than this issue needs. The increment that closes #722 and #790 keeps HashMap<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

  8. moved this from Todo to In Progress in Typhonon Aug 12, 2026
  9. added 2 commits that reference this issue on Aug 13, 2026
  10. nockawa commented on Aug 13, 2026

    @nockawa
    CollaboratorAuthor

    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. ClusterAnyDied was 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. ClusterMaxDiedTsn replaces 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 ReleaseSlot clears 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 fold VisibilityUnknown. 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 as CLUSTERVIS-01 / CLUSTERVIS-02, which nothing had stated.

    Not in #795 — the O(changed) refresh, and ViewCreatedBeforeTheSpawns_ConvergesWithOneCreatedAfter stays [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/DiedTSN check.

  11. added a commit that references this issue on Aug 24, 2026
  12. nockawa commented on Aug 24, 2026

    @nockawa
    CollaboratorAuthor

    Done, in #867. Every remaining acceptance item is satisfied, with one honest caveat on the third.

    • O(changed), not O(N) — an archetype-only view now subscribes to a per-archetype membership channel and gates on a structural epoch. Measured at 50 000 entities: ~3 100 µs → 0.25 µs idle, ~2 000 µs → 19–27 µs at 50 changes/tick.
    • O(1) parallel prepare preserved — RefreshSystemInputViewsAtTickStart still drives all three pull shapes (BIND-04 keys on IsPullMode deliberately); a membership view's refresh there takes the epoch gate.
    • ViewCreatedBeforeTheSpawns_ConvergesWithOneCreatedAfter un-ignored and green — ⚠️ but not asserting what this box says. It asserts convergence after one refresh, and that the refresh re-queried. It is the second refresh that asserts the channel. That is deliberate, and it is the more important finding: the seed is taken at the creating transaction's fixed TSN with that transaction's uncommitted spawns folded in, so it corresponds to no committed instant. Review reproduced three permanent-corruption consequences of trusting it — including a commit lost for the life of the view, verbatim MEMB-01's on_violation. So the first refresh always resynchronises, and the test now pins both halves: it heals, then the channel takes over.
    • BIND-04 updated — the note declaring 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).
    • ScanArchetypeOccupancy reference resolved — repointed at EcsQuery.TryCountViaOccupancy, with the zero-caller IsClusterFullyVisibleAt overload 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.

  13. moved this from In Progress to Done in Typhonon Aug 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

Fields

Priority

P1-High

Estimate

L

Area

Query

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