A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
fix(ecs): track system change queries across same-frame writes
yhh5bf655e02ed3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 764fc2a46..9e41c9c4b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,8 @@ published separately; it ships inside the editor.### Fixed+- **System change queries see additions and writes after earlier runs in the same frame.** Added and Changed filters use completed-system mutation sequences while explicit tick-based query instances keep their existing windows. Systems consume their own writebacks without retriggering themselves; compiled writers and asynchronous reads share the same boundaries. Stable queries skip candidate enumeration, and live sequence stamps reuse tick records and disappear with removed components.+- **Removal queries retain events across system runs in the same frame.** Removed component events use reader-owned sequence cursors, so removals after a system runs or after its last read remain available on its next run. Fresh readers start from registration, paused and async readers keep their claims, and fast readers skip retained history rather than repeatedly scanning a paused reader's backlog; explicit tick-based samplers keep their existing windows.- **Recreated UI components start a fresh visibility baseline.** Removing and reinserting a UINode no longer inherits its predecessor's shown/hidden state, including edits between frames or within one frame. Removed nodes leave the visibility cache; opted-in live component identities distinguish replacements without retaining removal history or adding resolved visibility reads on steady frames.diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex ac4b2139d..06b8ba4af 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -6795,6 +6795,7 @@ scanned: number## QueryInstance — class @public```+@internal resetChangeSequence: (sequence: number) => void@internal resetTick: (tick: number) => void@internal takeCost: () => QueryCost[Symbol.iterator]: () => Iterator<QueryResult<C>>@@ -10003,6 +10004,8 @@ tabIndex: number | undefined@internal advanceTick: () => void@internal advanceTopologyReader: (component: AnyComponentDef, readerId: number, lastRunTick: number) => void@internal advanceWriteReader: (component: AnyComponentDef, readerId: number, lastRunTick: number) => void+@internal anyAddedAfterSequence: (component: AnyComponentDef, after: number) => boolean+@internal anyChangedAfterSequence: (component: AnyComponentDef, after: number) => boolean@internal anyChangedSince: (component: AnyComponentDef, sinceTick: number) => boolean@internal applyEntityOrder: (entities: readonly Entity[]) => void@internal beginIteration: () => void@@ -10016,10 +10019,12 @@ tabIndex: number | undefined@internal disposeRemovedReader: (component: AnyComponentDef, readerId: number) => void@internal disposeTopologyReader: (component: AnyComponentDef, readerId: number) => void@internal disposeWriteReader: (component: AnyComponentDef, readerId: number) => void+@internal enableChangeSequenceTracking: (component: AnyComponentDef, added: boolean) => void@internal enableChangeTracking: (component: AnyComponentDef) => void@internal enableIncarnationTracking: (component: AnyComponentDef) => void@internal endIteration: () => void@internal ensureTransformsComposed: () => void+@internal getChangeSequence: () => number@internal getComponentIncarnation: (entity: Entity, component: AnyComponentDef) => number@internal getComponentTypesBatch: (entities: readonly Entity[]) => string[][]@internal getCppRegistry: () => CppRegistry | null@@ -10036,8 +10041,10 @@ tabIndex: number | undefined@internal hasCpp: boolean@internal hasPortableScriptAssetRefs: (component: AnyComponentDef) => boolean@internal invalidateTransformComposition: () => void+@internal isAddedAfterSequence: (entity: Entity, component: AnyComponentDef, after: number) => boolean@internal isAddedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean@internal isChangeTracked: (component: AnyComponentDef) => boolean+@internal isChangedAfterSequence: (entity: Entity, component: AnyComponentDef, after: number) => boolean@internal isChangedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean@internal isDestructionPending: (entity: Entity) => boolean@internal isIterating: () => booleandiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 62536ee21..e12de68cc 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -6998,6 +6998,7 @@ scanned: number## QueryInstance — class @public```+@internal resetChangeSequence: (sequence: number) => void@internal resetTick: (tick: number) => void@internal takeCost: () => QueryCost[Symbol.iterator]: () => Iterator<QueryResult<C>>@@ -10216,6 +10217,8 @@ tabIndex: number | undefined@internal advanceTick: () => void@internal advanceTopologyReader: (component: AnyComponentDef, readerId: number, lastRunTick: number) => void@internal advanceWriteReader: (component: AnyComponentDef, readerId: number, lastRunTick: number) => void+@internal anyAddedAfterSequence: (component: AnyComponentDef, after: number) => boolean+@internal anyChangedAfterSequence: (component: AnyComponentDef, after: number) => boolean@internal anyChangedSince: (component: AnyComponentDef, sinceTick: number) => boolean@internal applyEntityOrder: (entities: readonly Entity[]) => void@internal beginIteration: () => void@@ -10229,10 +10232,12 @@ tabIndex: number | undefined@internal disposeRemovedReader: (component: AnyComponentDef, readerId: number) => void@internal disposeTopologyReader: (component: AnyComponentDef, readerId: number) => void@internal disposeWriteReader: (component: AnyComponentDef, readerId: number) => void+@internal enableChangeSequenceTracking: (component: AnyComponentDef, added: boolean) => void@internal enableChangeTracking: (component: AnyComponentDef) => void@internal enableIncarnationTracking: (component: AnyComponentDef) => void@internal endIteration: () => void@internal ensureTransformsComposed: () => void+@internal getChangeSequence: () => number@internal getComponentIncarnation: (entity: Entity, component: AnyComponentDef) => number@internal getComponentTypesBatch: (entities: readonly Entity[]) => string[][]@internal getCppRegistry: () => CppRegistry | null@@ -10249,8 +10254,10 @@ tabIndex: number | undefined@internal hasCpp: boolean@internal hasPortableScriptAssetRefs: (component: AnyComponentDef) => boolean@internal invalidateTransformComposition: () => void+@internal isAddedAfterSequence: (entity: Entity, component: AnyComponentDef, after: number) => boolean@internal isAddedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean@internal isChangeTracked: (component: AnyComponentDef) => boolean+@internal isChangedAfterSequence: (entity: Entity, component: AnyComponentDef, after: number) => boolean@internal isChangedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean@internal isDestructionPending: (entity: Entity) => boolean@internal isIterating: () => booleandiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 64599ac5d..47f1007ad 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -6790,6 +6790,7 @@ scanned: number## QueryInstance — class @public```+@internal resetChangeSequence: (sequence: number) => void@internal resetTick: (tick: number) => void@internal takeCost: () => QueryCost[Symbol.iterator]: () => Iterator<QueryResult<C>>@@ -9998,6 +9999,8 @@ tabIndex: number | undefined@internal advanceTick: () => void@internal advanceTopologyReader: (component: AnyComponentDef, readerId: number, lastRunTick: number) => void@internal advanceWriteReader: (component: AnyComponentDef, readerId: number, lastRunTick: number) => void+@internal anyAddedAfterSequence: (component: AnyComponentDef, after: number) => boolean+@internal anyChangedAfterSequence: (component: AnyComponentDef, after: number) => boolean@internal anyChangedSince: (component: AnyComponentDef, sinceTick: number) => boolean@internal applyEntityOrder: (entities: readonly Entity[]) => void@internal beginIteration: () => void@@ -10011,10 +10014,12 @@ tabIndex: number | undefined@internal disposeRemovedReader: (component: AnyComponentDef, readerId: number) => void@internal disposeTopologyReader: (component: AnyComponentDef, readerId: number) => void@internal disposeWriteReader: (component: AnyComponentDef, readerId: number) => void+@internal enableChangeSequenceTracking: (component: AnyComponentDef, added: boolean) => void@internal enableChangeTracking: (component: AnyComponentDef) => void@internal enableIncarnationTracking: (component: AnyComponentDef) => void@internal endIteration: () => void@internal ensureTransformsComposed: () => void+@internal getChangeSequence: () => number@internal getComponentIncarnation: (entity: Entity, component: AnyComponentDef) => number@internal getComponentTypesBatch: (entities: readonly Entity[]) => string[][]@internal getCppRegistry: () => CppRegistry | null@@ -10031,8 +10036,10 @@ tabIndex: number | undefined@internal hasCpp: boolean@internal hasPortableScriptAssetRefs: (component: AnyComponentDef) => boolean@internal invalidateTransformComposition: () => void+@internal isAddedAfterSequence: (entity: Entity, component: AnyComponentDef, after: number) => boolean@internal isAddedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean@internal isChangeTracked: (component: AnyComponentDef) => boolean+@internal isChangedAfterSequence: (entity: Entity, component: AnyComponentDef, after: number) => boolean@internal isChangedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean@internal isDestructionPending: (entity: Entity) => boolean@internal isIterating: () => booleandiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex a9c4ad571..1fc1b83e4 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -7083,6 +7083,7 @@ scanned: number## QueryInstance — class @public```+@internal resetChangeSequence: (sequence: number) => void@internal resetTick: (tick: number) => void@internal takeCost: () => QueryCost[Symbol.iterator]: () => Iterator<QueryResult<C>>@@ -10297,6 +10298,8 @@ tabIndex: number | undefined@internal advanceTick: () => void@internal advanceTopologyReader: (component: AnyComponentDef, readerId: number, lastRunTick: number) => void@internal advanceWriteReader: (component: AnyComponentDef, readerId: number, lastRunTick: number) => void+@internal anyAddedAfterSequence: (component: AnyComponentDef, after: number) => boolean+@internal anyChangedAfterSequence: (component: AnyComponentDef, after: number) => boolean@internal anyChangedSince: (component: AnyComponentDef, sinceTick: number) => boolean@internal applyEntityOrder: (entities: readonly Entity[]) => void@internal beginIteration: () => void@@ -10310,10 +10313,12 @@ tabIndex: number | undefined@internal disposeRemovedReader: (component: AnyComponentDef, readerId: number) => void@internal disposeTopologyReader: (component: AnyComponentDef, readerId: number) => void@internal disposeWriteReader: (component: AnyComponentDef, readerId: number) => void+@internal enableChangeSequenceTracking: (component: AnyComponentDef, added: boolean) => void@internal enableChangeTracking: (component: AnyComponentDef) => void@internal enableIncarnationTracking: (component: AnyComponentDef) => void@internal endIteration: () => void@internal ensureTransformsComposed: () => void+@internal getChangeSequence: () => number@internal getComponentIncarnation: (entity: Entity, component: AnyComponentDef) => number@internal getComponentTypesBatch: (entities: readonly Entity[]) => string[][]@internal getCppRegistry: () => CppRegistry | null@@ -10330,8 +10335,10 @@ tabIndex: number | undefined@internal hasCpp: boolean@internal hasPortableScriptAssetRefs: (component: AnyComponentDef) => boolean@internal invalidateTransformComposition: () => void+@internal isAddedAfterSequence: (entity: Entity, component: AnyComponentDef, after: number) => boolean@internal isAddedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean@internal isChangeTracked: (component: AnyComponentDef) => boolean+@internal isChangedAfterSequence: (entity: Entity, component: AnyComponentDef, after: number) => boolean@internal isChangedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean@internal isDestructionPending: (entity: Entity) => boolean@internal isIterating: () => booleandiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 12802e5ff..17c2334af 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -6797,6 +6797,7 @@ scanned: number## QueryInstance — class @public```+@internal resetChangeSequence: (sequence: number) => void@internal resetTick: (tick: number) => void@internal takeCost: () => QueryCost[Symbol.iterator]: () => Iterator<QueryResult<C>>@@ -10029,6 +10030,8 @@ tabIndex: number | undefined@internal advanceTick: () => void@internal advanceTopologyReader: (component: AnyComponentDef, readerId: number, lastRunTick: number) => void@internal advanceWriteReader: (component: AnyComponentDef, readerId: number, lastRunTick: number) => void+@internal anyAddedAfterSequence: (component: AnyComponentDef, after: number) => boolean+@internal anyChangedAfterSequence: (component: AnyComponentDef, after: number) => boolean@internal anyChangedSince: (component: AnyComponentDef, sinceTick: number) => boolean@internal applyEntityOrder: (entities: readonly Entity[]) => void@internal beginIteration: () => void@@ -10042,10 +10045,12 @@ tabIndex: number | undefined@internal disposeRemovedReader: (component: AnyComponentDef, readerId: number) => void@internal disposeTopologyReader: (component: AnyComponentDef, readerId: number) => void@internal disposeWriteReader: (component: AnyComponentDef, readerId: number) => void+@internal enableChangeSequenceTracking: (component: AnyComponentDef, added: boolean) => void@internal enableChangeTracking: (component: AnyComponentDef) => void@internal enableIncarnationTracking: (component: AnyComponentDef) => void@internal endIteration: () => void@internal ensureTransformsComposed: () => void+@internal getChangeSequence: () => number@internal getComponentIncarnation: (entity: Entity, component: AnyComponentDef) => number@internal getComponentTypesBatch: (entities: readonly Entity[]) => string[][]@internal getCppRegistry: () => CppRegistry | null@@ -10062,8 +10067,10 @@ tabIndex: number | undefined@internal hasCpp: boolean@internal hasPortableScriptAssetRefs: (component: AnyComponentDef) => boolean@internal invalidateTransformComposition: () => void+@internal isAddedAfterSequence: (entity: Entity, component: AnyComponentDef, after: number) => boolean@internal isAddedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean@internal isChangeTracked: (component: AnyComponentDef) => boolean+@internal isChangedAfterSequence: (entity: Entity, component: AnyComponentDef, after: number) => boolean@internal isChangedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean@internal isDestructionPending: (entity: Entity) => boolean@internal isIterating: () => booleandiff --git a/sdk/src/ecs/ChangeTracker.ts b/sdk/src/ecs/ChangeTracker.tsindex 21d280d5b..dbda64fcb 100644--- a/sdk/src/ecs/ChangeTracker.ts+++ b/sdk/src/ecs/ChangeTracker.ts@@ -152,12 +152,23 @@ class ReaderOwnedJournal {}}+interface ChangeStamp { tick: number; sequence: number; }+type ChangeRow = number | ChangeStamp;++interface ComponentSequences {+ readonly rows: Map<Entity, ChangeRow>;+ latest: number;+}+export class ChangeTracker {private worldTick_ = 0;- private componentAddedTicks_ = new Map<symbol, Map<Entity, number>>();+ private componentAddedTicks_ = new Map<symbol, Map<Entity, ChangeRow>>();private componentIncarnations_ = new Map<symbol, Map<Entity, number>>();private nextIncarnation_ = 1;- private componentChangedTicks_ = new Map<symbol, Map<Entity, number>>();+ private componentChangedTicks_ = new Map<symbol, Map<Entity, ChangeRow>>();+ private componentAddedSequences_ = new Map<symbol, ComponentSequences>();+ private componentChangedSequences_ = new Map<symbol, ComponentSequences>();+ private changeSequence_ = 0;private readonly removals_ = new ReaderOwnedJournal(true);/** Membership moves, independent of ordinary change tracking. */private readonly topology_ = new ReaderOwnedJournal();@@ -186,6 +197,42 @@ export class ChangeTracker {this.trackedComponents_.add(component._id);}+ enableChangeSequenceTracking(component: AnyComponentDef, added: boolean): void {+ const sequences = added ? this.componentAddedSequences_ : this.componentChangedSequences_;+ if (sequences.has(component._id)) return;+ this.enableChangeTracking(component);+ const ticks = added ? this.componentAddedTicks_ : this.componentChangedTicks_;+ let rows = ticks.get(component._id);+ if (!rows) { rows = new Map(); ticks.set(component._id, rows); }+ const state: ComponentSequences = { rows, latest: -1 };+ sequences.set(component._id, state);+ // Share the tick map: opted-in rows gain a mutable stamp once, instead+ // of maintaining another entity index or allocating on each write.+ if (rows.size) {+ const sequence = ++this.changeSequence_;+ state.latest = sequence;+ for (const [entity, tick] of rows) rows.set(entity, { tick: tick as number, sequence });+ }+ }++ getChangeSequence(): number { return this.changeSequence_; }++ isAddedAfterSequence(entity: Entity, component: AnyComponentDef, after: number): boolean {+ return ((this.componentAddedSequences_.get(component._id)?.rows.get(entity) as ChangeStamp | undefined)?.sequence ?? -1) > after;+ }++ isChangedAfterSequence(entity: Entity, component: AnyComponentDef, after: number): boolean {+ return ((this.componentChangedSequences_.get(component._id)?.rows.get(entity) as ChangeStamp | undefined)?.sequence ?? -1) > after;+ }++ anyAddedAfterSequence(component: AnyComponentDef, after: number): boolean {+ return (this.componentAddedSequences_.get(component._id)?.latest ?? -1) > after;+ }++ anyChangedAfterSequence(component: AnyComponentDef, after: number): boolean {+ return (this.componentChangedSequences_.get(component._id)?.latest ?? -1) > after;+ }+enableIncarnationTracking(component: AnyComponentDef): void {if (!this.componentIncarnations_.has(component._id)) {this.componentIncarnations_.set(component._id, new Map());@@ -199,15 +246,15 @@ export class ChangeTracker {isAddedSince(entity: Entity, component: AnyComponentDef, sinceTick: number): boolean {const map = this.componentAddedTicks_.get(component._id);if (!map) return false;- const tick = map.get(entity);- return tick !== undefined && tick > sinceTick;+ const row = map.get(entity);+ return row !== undefined && (typeof row === 'number' ? row : row.tick) > sinceTick;}isChangedSince(entity: Entity, component: AnyComponentDef, sinceTick: number): boolean {const map = this.componentChangedTicks_.get(component._id);if (!map) return false;- const tick = map.get(entity);- return tick !== undefined && tick > sinceTick;+ const row = map.get(entity);+ return row !== undefined && (typeof row === 'number' ? row : row.tick) > sinceTick;}/** True if ANY entity changed `component` after `sinceTick`. O(1) — reads the@@ -343,6 +390,11 @@ export class ChangeTracker {this.topology_.record(component._id, entity, this.worldTick_);}if (!this.trackedComponents_.has(component._id)) return;+ const sequences = this.componentAddedSequences_.get(component._id);+ if (sequences) {+ this.recordSequence_(sequences, entity);+ return;+ }let map = this.componentAddedTicks_.get(component._id);if (!map) {map = new Map();@@ -368,6 +420,12 @@ export class ChangeTracker {this.writes_.record(component._id, entity, this.worldTick_);}if (!this.trackedComponents_.has(component._id)) return;+ const sequences = this.componentChangedSequences_.get(component._id);+ if (sequences) {+ this.recordSequence_(sequences, entity);+ this.componentLastChangedTick_.set(component._id, this.worldTick_);+ return;+ }let map = this.componentChangedTicks_.get(component._id);if (!map) {map = new Map();@@ -377,6 +435,14 @@ export class ChangeTracker {this.componentLastChangedTick_.set(component._id, this.worldTick_);}+ private recordSequence_(state: ComponentSequences, entity: Entity): void {+ const sequence = ++this.changeSequence_;+ state.latest = sequence;+ const row = state.rows.get(entity) as ChangeStamp | undefined;+ if (row) { row.tick = this.worldTick_; row.sequence = sequence; }+ else state.rows.set(entity, { tick: this.worldTick_, sequence });+ }+recordRemoved(component: AnyComponentDef, entity: Entity): void {this.recordRemovedById(component._id, entity);}@@ -417,18 +483,22 @@ export class ChangeTracker {* only while a `Removed` reader holds the component, and are pruned to the* lowest claim whenever one advances or goes away.*/- sizes(): { tracked: number; addedRows: number; changedRows: number; removedRows: number } {- const rowsIn = (maps: Map<symbol, Map<Entity, number>>): number => {+ sizes(): { tracked: number; addedRows: number; changedRows: number; removedRows: number; sequenceRows: number } {+ const rowsIn = (maps: Map<symbol, Map<Entity, ChangeRow>>): number => {let n = 0;for (const m of maps.values()) n += m.size;return n;};const removedRows = this.removals_.totalRows();+ let sequenceRows = 0;+ for (const state of this.componentAddedSequences_.values()) sequenceRows += state.rows.size;+ for (const state of this.componentChangedSequences_.values()) sequenceRows += state.rows.size;return {tracked: this.trackedComponents_.size,addedRows: rowsIn(this.componentAddedTicks_),changedRows: rowsIn(this.componentChangedTicks_),removedRows,+ sequenceRows,};}}diff --git a/sdk/src/ecs/query.ts b/sdk/src/ecs/query.tsindex 5224e587d..40aed6043 100644--- a/sdk/src/ecs/query.ts+++ b/sdk/src/ecs/query.ts@@ -10,6 +10,8 @@ import { AnyComponentDef, ComponentData, isBuiltinComponent } from './component'import type { World, QueryFilter } from './world';import { computeQueryCacheKey, queryDepIds } from './world';+const NO_CHANGE_CANDIDATES: readonly Entity[] = [];+// =============================================================================// Mutable Component Wrapper// =============================================================================@@ -404,6 +406,7 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Qu// precomputed like cacheKey_ so per-call query iteration allocates no array.private readonly depIds_: symbol[];private lastRunTick_: number;+ private lastChangeSequence_: number | null = null;private calls_ = 0;private scanned_ = 0;private filtered_ = 0;@@ -465,12 +468,36 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Quthis.lastRunTick_ = tick;}+ /** @internal System-owned queries use completed runs, not coarse frame ticks. */+ resetChangeSequence(sequence: number): void {+ if (!this.hasChangeFilters_()) return;+ if (this.lastChangeSequence_ === null) {+ for (const f of this.descriptor_._addedFilters) this.world_.enableChangeSequenceTracking(f.component, true);+ for (const f of this.descriptor_._changedFilters) this.world_.enableChangeSequenceTracking(f.component, false);+ }+ this.lastChangeSequence_ = sequence;+ }+/**- * The entity set before change filters — what the query cache can answer on- * its own. Every caller that asks "which entities match" goes through here,- * so none of them can disagree about the cache key or the dep set.+ * Every result reader uses this candidate set. A closed change window is+ * empty in O(1); otherwise the structural query cache supplies the entities+ * before their individual change filters are applied.*/private candidates_(): readonly Entity[] {+ if (this.lastChangeSequence_ !== null) {+ const after = this.lastChangeSequence_;+ let unchanged = false;+ for (const f of this.descriptor_._addedFilters) {+ if (!this.world_.anyAddedAfterSequence(f.component, after)) { unchanged = true; break; }+ }+ if (!unchanged) for (const f of this.descriptor_._changedFilters) {+ if (!this.world_.anyChangedAfterSequence(f.component, after)) { unchanged = true; break; }+ }+ if (unchanged) {+ if (this.world_.queryCostEnabled) this.calls_++;+ return NO_CHANGE_CANDIDATES;+ }+ }const entities = this.world_.queryEntities(this.allRequired_,this.descriptor_._with,@@ -507,11 +534,16 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Quconst { _addedFilters, _changedFilters } = this.descriptor_;if (_addedFilters.length === 0 && _changedFilters.length === 0) return true;const tick = this.lastRunTick_;+ const sequence = this.lastChangeSequence_;for (const f of _addedFilters) {- if (!this.world_.isAddedSince(entity, f.component, tick)) return this.rejected_();+ const added = sequence === null ? this.world_.isAddedSince(entity, f.component, tick)+ : this.world_.isAddedAfterSequence(entity, f.component, sequence);+ if (!added) return this.rejected_();}for (const f of _changedFilters) {- if (!this.world_.isChangedSince(entity, f.component, tick)) return this.rejected_();+ const changed = sequence === null ? this.world_.isChangedSince(entity, f.component, tick)+ : this.world_.isChangedAfterSequence(entity, f.component, sequence);+ if (!changed) return this.rejected_();}return true;}diff --git a/sdk/src/ecs/system.ts b/sdk/src/ecs/system.tsindex 82783c826..f6c0d6b5e 100644--- a/sdk/src/ecs/system.ts+++ b/sdk/src/ecs/system.ts@@ -404,6 +404,7 @@ export class SystemRunner {private readonly eventRegistry_: EventRegistry | null;private readonly argsCache_ = new Map<symbol, unknown[]>();private readonly systemTicks_ = new Map<symbol, number>();+ private readonly systemChangeSequences_ = new Map<symbol, number>();private readonly queryCache_ = new Map<symbol, QueryInstance<any>[]>();private readonly removedCache_ = new Map<symbol, RemovedQueryInstance<any>[]>();private currentLastRunTick_ = -1;@@ -461,6 +462,7 @@ export class SystemRunner {evict(systemId: symbol): void {this.argsCache_.delete(systemId);this.systemTicks_.delete(systemId);+ this.systemChangeSequences_.delete(systemId);this.queryCache_.delete(systemId);// Dropping the reference is not releasing the claim: a reader nothing// can reach still pins its component's removal history forever.@@ -472,6 +474,7 @@ export class SystemRunner {reset(): void {this.argsCache_.clear();this.systemTicks_.clear();+ this.systemChangeSequences_.clear();this.queryCache_.clear();for (const removeds of this.removedCache_.values()) {for (const removed of removeds) removed.dispose();@@ -491,6 +494,7 @@ export class SystemRunner {}this.currentLastRunTick_ = this.systemTicks_.get(system._id) ?? -1;+ const lastChangeSequence = this.systemChangeSequences_.get(system._id) ?? -1;// Published only once every param resolved. Building a system's first set// of query instances can throw — an unregistered component reaches@@ -513,11 +517,13 @@ export class SystemRunner {if (param._type === 'query') {if (firstRun) {const inst = new QueryInstance(this.world_, param, this.currentLastRunTick_);+ inst.resetChangeSequence(lastChangeSequence);queries.push(inst);args[i] = inst;} else {const inst = queries[qi];inst.resetTick(this.currentLastRunTick_);+ inst.resetChangeSequence(lastChangeSequence);args[i] = inst;}qi++;@@ -586,6 +592,7 @@ export class SystemRunner {this.timings_.set(name, (this.timings_.get(name) ?? 0) + (performance.now() - t0));}this.systemTicks_.set(system._id, this.world_.getWorldTick());+ this.systemChangeSequences_.set(system._id, this.world_.getChangeSequence());return true;}@@ -614,6 +621,9 @@ export class SystemRunner {removed.releaseThrough(ranAt);}this.systemTicks_.set(system._id, ranAt);+ // Closing at completion consumes this run's own writebacks too. Writes+ // after completion remain distinct even within the same world tick.+ this.systemChangeSequences_.set(system._id, this.world_.getChangeSequence());}private harvestQueryCost_(system: SystemDef): void {diff --git a/sdk/src/ecs/world.ts b/sdk/src/ecs/world.tsindex 2c8d6cbdb..d2ece2089 100644--- a/sdk/src/ecs/world.ts+++ b/sdk/src/ecs/world.ts@@ -1362,6 +1362,34 @@ export class World {this.changes_.enableChangeTracking(component);}+ /** @internal Opt a system query into precise change boundaries, separately from tick sampling. */+ enableChangeSequenceTracking(component: AnyComponentDef, added: boolean): void {+ this.changes_.enableChangeSequenceTracking(component, added);+ }++ /** @internal Latest opted-in component mutation sequence. */+ getChangeSequence(): number { return this.changes_.getChangeSequence(); }++ /** @internal Live additions after a completed system boundary. */+ isAddedAfterSequence(entity: Entity, component: AnyComponentDef, after: number): boolean {+ return this.changes_.isAddedAfterSequence(entity, component, after);+ }++ /** @internal Live changes after a completed system boundary. */+ isChangedAfterSequence(entity: Entity, component: AnyComponentDef, after: number): boolean {+ return this.changes_.isChangedAfterSequence(entity, component, after);+ }++ /** @internal O(1) empty-window checks before enumerating system query candidates. */+ anyAddedAfterSequence(component: AnyComponentDef, after: number): boolean {+ return this.changes_.anyAddedAfterSequence(component, after);+ }++ /** @internal O(1) empty-window checks before enumerating system query candidates. */+ anyChangedAfterSequence(component: AnyComponentDef, after: number): boolean {+ return this.changes_.anyChangedAfterSequence(component, after);+ }+/** @internal Opt in to live component identities, independent of frame ticks. */enableIncarnationTracking(component: AnyComponentDef): void {this.changes_.enableIncarnationTracking(component);diff --git a/sdk/tests/aot-dispatch.test.ts b/sdk/tests/aot-dispatch.test.tsindex d06564cf5..4ebee9f0c 100644--- a/sdk/tests/aot-dispatch.test.ts+++ b/sdk/tests/aot-dispatch.test.ts@@ -255,7 +255,7 @@ describe('the scheduler and its compiled twin', () => {w.runner.useAot(runtime);}for (let f = 0; f < 4; f++) {- w.world.advanceTick();+ if (f === 0) w.world.advanceTick();w.runner.run(w.system);w.runner.run(watcher);}@@ -267,6 +267,8 @@ describe('the scheduler and its compiled twin', () => {seen.push(...compiled);expect(interpreted.some((n) => n > 0), 'the watcher never saw a change either way').toBe(true);+ expect(interpreted.slice(1).every(n => n > 0), 'later writes in the same tick were missed')+ .toBe(true);expect(compiled).toEqual(interpreted);});diff --git a/sdk/tests/async-system.test.ts b/sdk/tests/async-system.test.tsindex 26a2cf938..1143546cc 100644--- a/sdk/tests/async-system.test.ts+++ b/sdk/tests/async-system.test.ts@@ -40,6 +40,7 @@ function createMockWorld() {suspendIteration: vi.fn(() => 0),resumeIteration: vi.fn(),getWorldTick: vi.fn(() => worldTick.value),+ getChangeSequence: vi.fn(() => 0),isAddedSince: vi.fn(() => false),isChangedSince: vi.fn(() => false),getRemovedEntitiesSince: vi.fn(() => []),diff --git a/sdk/tests/change-query-boundaries-wasm.test.ts b/sdk/tests/change-query-boundaries-wasm.test.tsnew file mode 100644index 000000000..7cda13a0e--- /dev/null+++ b/sdk/tests/change-query-boundaries-wasm.test.ts@@ -0,0 +1,72 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest';+import { App, flushPendingRegistrations } from '../src/app/app';+import { AppContext, setDefaultContext } from '../src/ecs/context';+import { Added, Changed, Mut, Query } from '../src/ecs/query';+import { defineSystem, Schedule } from '../src/ecs/system';+import { UINode, UIDisplay } from '../src/ui/core/ui-node';+import type { Entity } from '../src/types';+import type { CppRegistry, ESEngineModule } from '../src/wasm';+import { HAS_WASM, loadWasmModule } from './helpers/loadWasm';++describe.skipIf(!HAS_WASM)('builtin change query boundaries on real WASM', () => {+ let engine: ESEngineModule;+ let registry: CppRegistry;+ let app: App;+ beforeAll(async () => { engine = await loadWasmModule(); });+ beforeEach(() => {+ setDefaultContext(new AppContext());+ registry = new engine.Registry();+ app = App.new();+ app.connectCpp(registry, engine);+ });+ afterEach(() => {+ for (const entity of app.world.getAllEntities()) app.world.despawn(entity);+ expect(app.world.getStorageSizes().changes.sequenceRows).toBe(0);+ app.world.disconnectCpp();+ registry.delete();+ });+ it.each([Added, Changed])('sees a builtin insertion between frames through %s', async filter => {+ const batches: Entity[][] = [];+ app.addSystemToSchedule(Schedule.Update, defineSystem([Query(filter(UINode))], query => {+ const batch: Entity[] = [];+ query.forEach(entity => batch.push(entity));+ batches.push(batch);+ }));+ flushPendingRegistrations(app);+ await app.tick(1 / 60);+ const entity = app.world.spawn();+ app.world.insert(entity, UINode);+ await app.tick(1 / 60);+ await app.tick(1 / 60);+ expect(batches).toEqual([[], [entity], []]);+ });+ it('sees a late UI write on the next frame without retriggering its own Mut writeback', async () => {+ const batches: Entity[][] = [];+ app.addSystemToSchedule(Schedule.Update, defineSystem([Query(Mut(UINode), Changed(UINode))], query => {+ const batch: Entity[] = [];+ query.forEach((entity, node) => { batch.push(entity); node.display = UIDisplay.Flex; });+ batches.push(batch);+ }));+ let victim: Entity | undefined;+ app.addSystemToSchedule(Schedule.PostUpdate, defineSystem([], () => {+ if (victim !== undefined) {+ app.world.update(victim, UINode, node => { node.display = UIDisplay.None; });+ victim = undefined;+ }+ }));+ flushPendingRegistrations(app);+ await app.tick(1 / 60);+ const entity = app.world.spawn();+ app.world.insert(entity, UINode);+ await app.tick(1 / 60);+ victim = entity;+ await app.tick(1 / 60);+ await app.tick(1 / 60);+ await app.tick(1 / 60);+ expect(batches).toEqual([[], [entity], [], [entity], []]);+ expect(app.world.get(entity, UINode).display).toBe(UIDisplay.Flex);+ expect(app.world.getStorageSizes().changes.sequenceRows).toBe(1);+ });+});diff --git a/sdk/tests/change-query-boundaries.test.ts b/sdk/tests/change-query-boundaries.test.tsnew file mode 100644index 000000000..b6973dbb8--- /dev/null+++ b/sdk/tests/change-query-boundaries.test.ts@@ -0,0 +1,198 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { AppContext, setDefaultContext } from '../src/ecs/context';+import { defineComponent } from '../src/ecs/component';+import { World } from '../src/ecs/world';+import { ResourceStorage } from '../src/ecs/resource';+import { Added, Changed, Mut, Query, QueryInstance } from '../src/ecs/query';+import { defineSystem, SystemRunner } from '../src/ecs/system';+import type { Entity } from '../src/types';++const Marker = defineComponent('BoundaryMarker', { value: 0 });+describe('system change query boundaries', () => {+ let world: World;+ let runner: SystemRunner;+ beforeEach(() => {+ setDefaultContext(new AppContext());+ world = new World();+ runner = new SystemRunner(world, new ResourceStorage());+ });+ it.each([Added, Changed])('delivers %s between runs in one world tick once', filter => {+ const batches: Entity[][] = [];+ const reader = defineSystem([Query(filter(Marker))], query => {+ const batch: Entity[] = [];+ query.forEach(entity => batch.push(entity));+ batches.push(batch);+ });+ runner.run(reader);+ const entity = world.spawn();+ world.insert(entity, Marker);+ runner.run(reader);+ runner.run(reader);+ expect(batches).toEqual([[], [entity], []]);+ expect(world.getWorldTick()).toBe(0);+ });+ it('delivers a later systems write on the next run in the same tick', () => {+ const batches: Entity[][] = [];+ const reader = defineSystem([Query(Changed(Marker))], query => {+ const batch: Entity[] = [];+ query.forEach(entity => batch.push(entity));+ batches.push(batch);+ });+ runner.run(reader);+ const entity = world.spawn();+ world.insert(entity, Marker);+ runner.run(reader);+ const writer = defineSystem([], () => { world.update(entity, Marker, marker => { marker.value++; }); });+ runner.run(writer);+ runner.run(reader);+ runner.run(reader);+ expect(batches).toEqual([[], [entity], [entity], []]);+ });+ it('does not retrigger from the readers own Mut writeback', () => {+ const counts: number[] = [];+ const reader = defineSystem([Query(Mut(Marker), Changed(Marker))], query => {+ let count = 0;+ query.forEach((_entity, marker) => { marker.value++; count++; });+ counts.push(count);+ });+ runner.run(reader);+ const entity = world.spawn();+ world.insert(entity, Marker);+ runner.run(reader);+ runner.run(reader);+ expect(counts).toEqual([0, 1, 0]);+ expect(world.get(entity, Marker).value).toBe(1);+ });+ it('keeps the previous completed boundary while an async system is suspended', async () => {+ const batches: Entity[][] = [];+ let write: (() => void) | undefined;+ const reader = defineSystem([Query(Changed(Marker))], async query => {+ if (write) await Promise.resolve().then(write);+ const batch: Entity[] = [];+ query.forEach(entity => batch.push(entity));+ batches.push(batch);+ });+ await runner.run(reader);+ const entity = world.spawn();+ world.insert(entity, Marker);+ await runner.run(reader);+ write = () => { world.update(entity, Marker, marker => { marker.value++; }); };+ await runner.run(reader);+ write = undefined;+ await runner.run(reader);+ world.update(entity, Marker, marker => { marker.value++; });+ await runner.run(reader);+ expect(batches).toEqual([[], [entity], [entity], [], [entity]]);+ });+ it('keeps a paused reader independent of a fast readers completed boundary', () => {+ const fast: number[] = [], slow: number[] = [];+ const reader = (counts: number[]) => defineSystem([Query(Changed(Marker))], query => {+ let count = 0;+ query.forEach(() => { count++; });+ counts.push(count);+ });+ const fastReader = reader(fast), slowReader = reader(slow);+ runner.run(fastReader);+ runner.run(slowReader);+ const entity = world.spawn();+ world.insert(entity, Marker);+ runner.run(fastReader);+ runner.run(fastReader);+ world.update(entity, Marker, marker => { marker.value++; });+ runner.run(fastReader);+ runner.run(slowReader);+ runner.run(slowReader);+ expect(fast).toEqual([0, 1, 0, 1]);+ expect(slow).toEqual([0, 1, 0]);+ expect(world.getStorageSizes().changes.removedRows).toBe(0);+ });+ it('preserves explicit tick-based query instances without opting into sequence storage', () => {+ world.enableChangeTracking(Marker);+ const entity = world.spawn();+ world.insert(entity, Marker);+ const query = new QueryInstance(world, Query(Changed(Marker)), 0);+ let count = 0;+ query.forEach(() => { count++; });+ expect(count).toBe(0);+ world.advanceTick();+ world.update(entity, Marker, marker => { marker.value++; });+ query.forEach(() => { count++; });+ expect(count).toBe(1);+ expect(world.getStorageSizes().changes.sequenceRows).toBe(0);+ expect(world.getChangeSequence()).toBe(0);+ });+ it.each([Added, Changed])('does not enumerate stable %s queries for any read form', filter => {+ let armed = false;+ const reader = defineSystem([Query(filter(Marker))], query => {+ if (!armed) { query.forEach(() => {}); return; }+ expect(query.isEmpty()).toBe(true);+ expect(query.count()).toBe(0);+ expect(query.single()).toBeNull();+ expect(query.toArray()).toEqual([]);+ query.forEach(() => { throw new Error('stable query yielded a row'); });+ });+ runner.run(reader);+ const entity = world.spawn();+ world.insert(entity, Marker);+ runner.run(reader);+ const candidates = vi.spyOn(world, 'queryEntities');+ armed = true;+ runner.run(reader);+ expect(candidates).not.toHaveBeenCalled();+ candidates.mockRestore();+ });+ it.each([Added, Changed])('preserves tick sampling after existing %s records gain sequences', filter => {+ world.enableChangeTracking(Marker);+ const first = world.spawn();+ world.insert(first, Marker);+ const counts: number[] = [];+ const reader = defineSystem([Query(filter(Marker))], query => { counts.push(query.count()); });+ runner.run(reader);+ expect(counts).toEqual([1]);+ const manual = new QueryInstance(world, Query(filter(Marker)), 0);+ expect(manual.count()).toBe(0);+ world.advanceTick();+ if (filter === Added) {+ const next = world.spawn();+ world.insert(next, Marker);+ } else world.update(first, Marker, marker => { marker.value++; });+ expect(manual.count()).toBe(1);+ runner.run(reader);+ expect(counts).toEqual([1, 1]);+ });+ it.each([Added, Changed])('keeps %s sequence storage proportional to live components', filter => {+ const reader = defineSystem([Query(filter(Marker))], query => { query.forEach(() => {}); });+ runner.run(reader);+ const nodes = Array.from({ length: 128 }, () => {+ const entity = world.spawn();+ world.insert(entity, Marker);+ return entity;+ });+ for (let i = 0; i < 100; i++) {+ world.update(nodes[0], Marker, marker => { marker.value++; });+ runner.run(reader);+ }+ expect(world.getStorageSizes().changes.sequenceRows).toBe(nodes.length);+ for (const [i, entity] of nodes.entries()) {+ if (i % 2) world.despawn(entity);+ else world.remove(entity, Marker);+ }+ expect(world.getStorageSizes().changes.sequenceRows).toBe(0);+ expect(world.getStorageSizes().changes.removedRows).toBe(0);+ });+ it.each(['evict', 'reset'] as const)('starts a fresh query window after %s', operation => {+ const counts: number[] = [];+ const reader = defineSystem([Query(Changed(Marker))], query => { counts.push(query.count()); });+ runner.run(reader);+ const entity = world.spawn();+ world.insert(entity, Marker);+ runner.run(reader);+ runner.run(reader);+ if (operation === 'evict') runner.evict(reader._id);+ else runner.reset();+ runner.run(reader);+ expect(counts).toEqual([0, 1, 0, 1]);+ });+});diff --git a/sdk/tests/query-cost.test.ts b/sdk/tests/query-cost.test.tsindex 35cb9bf12..002da70fa 100644--- a/sdk/tests/query-cost.test.ts+++ b/sdk/tests/query-cost.test.ts@@ -52,13 +52,17 @@ describe('per-system query cost', () => {}, { name: 'Reactor' }));await app.tick(1 / 60);+ const entity = app.world.getEntitiesWithComponents([Position])[0];+ app.world.update(entity, Position, position => { position.x++; });await app.tick(1 / 60);const cost = costOf(app, 'Reactor')!;- // The filter is doing its job and the walk is still the whole set — the- // finding a Changed() query exists to make visible.+ // One changed row still requires checking the matching entity set.expect(cost.scanned).toBe(30);- expect(cost.filtered).toBe(30);+ expect(cost.filtered).toBe(29);+ await app.tick(1 / 60);+ // A closed change window performs no candidate scan at all.+ expect(costOf(app, 'Reactor')).toEqual({ calls: 1, scanned: 0, filtered: 0 });});it('shows nothing discarded when the changes are real', async () => {diff --git a/sdk/tests/system.test.ts b/sdk/tests/system.test.tsindex ec849d28d..2dd2280c6 100644--- a/sdk/tests/system.test.ts+++ b/sdk/tests/system.test.ts@@ -58,6 +58,12 @@ function createMockWorld() {endIteration: vi.fn(),resetIterationDepth: vi.fn(),getWorldTick: vi.fn(() => worldTick.value),+ getChangeSequence: vi.fn(() => 0),+ enableChangeSequenceTracking: vi.fn(),+ isAddedAfterSequence: vi.fn(() => false),+ isChangedAfterSequence: vi.fn(() => false),+ anyAddedAfterSequence: vi.fn(() => false),+ anyChangedAfterSequence: vi.fn(() => false),isAddedSince: vi.fn(() => false),isChangedSince: vi.fn(() => false),getRemovedEntitiesSince: vi.fn(() => []),diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 8405501da..febb88499 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';* the reader recognises anyway.*/export const NOTED = {+ 'fix(ecs): track system change queries across same-frame writes':+ { note: 'System change queries see additions and writes after earlier runs in the same frame.' },'fix(ecs): retain same-frame removals with sequence cursors':{ note: 'Removal queries retain events across system runs in the same frame.' },'fix(test): classify versioned navigation in the release corpus':