From 76fbd17cc767ca83245c5f1dd9f9b85a1586557f Mon Sep 17 00:00:00 2001 From: Kris Nye Date: Sun, 22 Nov 2026 09:32:16 -0800 Subject: [PATCH 1/2] ecs 0.6.0, ecs-persistence 0.2.0: save, restore and watch values a trait covers on any thread (#283) - World-thread commands, spawns and spawnTables give joined threads' data objects values, delivered by message and applied at the sync point through the move log. - spawnTables rewrites entity values in the resources it sets, and refuses only a resource a joined thread fills that isn't data. - Readonly systems' tables gather the values joined threads hold, merged by entity. - Readonly systems may filter on traits: changed: [trait] runs them once something declaring the trait changed, on any thread. - ecs-persistence: snapshot and spawn cover values on any thread; watch({ world, by }, onChange); guide chapter 5. --- ecs/packages/ecs-persistence/README.md | 18 ++++ ecs/packages/ecs-persistence/package.json | 2 +- .../ecs-persistence/src/guide/05-watching.md | 18 ++++ .../ecs-persistence/src/guide/05-watching.out | 5 + .../ecs-persistence/src/guide/05-watching.ts | 77 +++++++++++++++ .../ecs-persistence/src/guide/README.md | 1 + .../ecs-persistence/src/guide/guide.test.ts | 5 + ecs/packages/ecs-persistence/src/index.ts | 1 + .../ecs-persistence/src/persistence.test.ts | 68 +++++++++++++ ecs/packages/ecs-persistence/src/watch.ts | 25 +++++ ecs/packages/ecs/followups.md | 3 + ecs/packages/ecs/package.json | 2 +- .../ecs/src/implementation/world/batches.ts | 10 +- .../ecs/src/implementation/world/commands.ts | 17 ++-- .../ecs/src/implementation/world/join.ts | 68 ++++++++++++- .../ecs/src/implementation/world/joining.ts | 7 ++ .../ecs/src/implementation/world/mirror.ts | 74 +++++++++++++-- .../src/implementation/world/move-log.test.ts | 44 ++++++--- .../ecs/src/implementation/world/move-log.ts | 50 +++++++++- .../ecs/src/implementation/world/observer.ts | 69 +++++++++++++- .../ecs/src/implementation/world/register.ts | 8 +- .../implementation/world/remote-systems.ts | 1 + .../src/implementation/world/remote.test.ts | 78 +++++++++++++-- .../ecs/src/implementation/world/remote.ts | 25 ++++- .../ecs/src/implementation/world/runner.ts | 12 ++- .../ecs/src/implementation/world/sharing.ts | 47 ++++++++- .../ecs/src/implementation/world/state.ts | 6 ++ .../src/implementation/world/synchronize.ts | 5 +- .../src/implementation/world/tables-read.ts | 27 +++++- .../src/implementation/world/tables.test.ts | 28 ++++++ .../ecs/src/implementation/world/tables.ts | 37 ++++++-- .../world/thread-removed-systems.ts | 7 +- .../world/trait-changes.test.ts | 95 +++++++++++++++++++ .../src/implementation/world/trait-changes.ts | 69 ++++++++++++++ .../ecs/src/interface/system/check.ts | 11 +++ .../ecs/src/interface/system/commands.ts | 3 +- .../ecs/src/interface/system/create.ts | 17 +++- .../ecs/src/interface/system/declaration.ts | 11 ++- .../system/sync-systems.type-test.ts | 9 ++ ecs/packages/ecs/src/perftest/benchmarks.ts | 2 + ecs/packages/ecs/src/perftest/log.ts | 2 +- .../ecs/src/perftest/trait-changes.ts | 86 +++++++++++++++++ ecs/packages/ecs/threads.md | 31 +++++- 43 files changed, 1093 insertions(+), 88 deletions(-) create mode 100644 ecs/packages/ecs-persistence/src/guide/05-watching.md create mode 100644 ecs/packages/ecs-persistence/src/guide/05-watching.out create mode 100644 ecs/packages/ecs-persistence/src/guide/05-watching.ts create mode 100644 ecs/packages/ecs-persistence/src/watch.ts create mode 100644 ecs/packages/ecs/src/implementation/world/trait-changes.test.ts create mode 100644 ecs/packages/ecs/src/implementation/world/trait-changes.ts create mode 100644 ecs/packages/ecs/src/perftest/trait-changes.ts diff --git a/ecs/packages/ecs-persistence/README.md b/ecs/packages/ecs-persistence/README.md index b4fab3b42..767e0cbf4 100644 --- a/ecs/packages/ecs-persistence/README.md +++ b/ecs/packages/ecs-persistence/README.md @@ -80,6 +80,24 @@ const spawned = await spawn({ world: other, snapshot: loaded }); components left as they are. So an entity the application makes at startup, such as a camera, keeps a component that is a saved setting: `spawn({ world, snapshot: settings, match: [byCamera], update: true })`. +## Values on other threads + +A trait covers data wherever it lives: a resource or component declared `thread: "main"`, which views read beside +their elements, is saved as the world's own are. `snapshot` asks each joined thread for the values it holds, each as of +its own latest sync point, and `spawn` sets them on the thread that holds them, their entity values rewritten as the +rest are. + +## Saving as it changes + +```ts +const stop = watch({ world, by: session }, () => { due = true; }); +``` + +`watch({ world, by }, onChange)` calls `onChange` after each sync point at which something the trait covers changed, +on whichever thread holds it, and once after the first; it returns the function that stops it. It runs on the world's +thread. An application saving its session marks it due there, and saves when it chooses, so a burst of changes is one +save. + Each reports why it didn't happen as `{ failure }`, rather than throwing, and `result.failure !== undefined` tells which. A snapshot is opaque: only these functions read it. diff --git a/ecs/packages/ecs-persistence/package.json b/ecs/packages/ecs-persistence/package.json index 0d64b37ce..bc7458317 100644 --- a/ecs/packages/ecs-persistence/package.json +++ b/ecs/packages/ecs-persistence/package.json @@ -1,6 +1,6 @@ { "name": "@adobe/ecs-persistence", - "version": "0.1.3", + "version": "0.2.0", "description": "Saving, loading and copying the entities of @adobe/ecs worlds, as binary columns", "license": "MIT", "type": "module", diff --git a/ecs/packages/ecs-persistence/src/guide/05-watching.md b/ecs/packages/ecs-persistence/src/guide/05-watching.md new file mode 100644 index 000000000..03b71b183 --- /dev/null +++ b/ecs/packages/ecs-persistence/src/guide/05-watching.md @@ -0,0 +1,18 @@ +# Saving as it changes + +An editor keeps its work across reloads by saving a `session` as it changes, rather than on a timer. Some of what the +session covers lives on the page's thread: [`filter`](05-watching.ts#L22) is data the page's views read beside their +elements, so it's declared `thread: "page"`. The world here is on another thread than the page, joined to it as a +worker's world and its page are. + +- **Knowing when to save:** [`watch({ world, by: session }, onChange)`](05-watching.ts#L46) calls `onChange` after each + sync point at which something the trait covers changed, on whichever thread holds it: written, added, removed, + spawned or despawned. It calls it after the first sync point too, so the first is saved, and returns the function that stops it. A run changing nothing the session covers, `idle`, calls + nothing, so nothing is saved. Here `onChange` only marks the session due; the program saves when it chooses, so a + burst of changes is one save. +- **A value on the page's thread:** [`filterBoxes`](05-watching.ts#L28) writes the filter, and runs on the page's + thread, which holds it. `watch` sees that write as it sees the world's own. +- **Taking it:** [`snapshot({ world, by: session })`](05-watching.ts#L52) asks the page's thread for the filter and + merges it with what the world holds. Each thread gives its values as of its own latest sync point. +- **Putting it back:** [`spawn`](05-watching.ts#L72) sets the filter on the page's thread again, where the page reads + it. diff --git a/ecs/packages/ecs-persistence/src/guide/05-watching.out b/ecs/packages/ecs-persistence/src/guide/05-watching.out new file mode 100644 index 000000000..92b587365 --- /dev/null +++ b/ecs/packages/ecs-persistence/src/guide/05-watching.out @@ -0,0 +1,5 @@ +started: nothing to save +labeled: saved +idle: nothing to save +filtered on the page: saved +reloaded filter: shape: box diff --git a/ecs/packages/ecs-persistence/src/guide/05-watching.ts b/ecs/packages/ecs-persistence/src/guide/05-watching.ts new file mode 100644 index 000000000..3412a9fef --- /dev/null +++ b/ecs/packages/ecs-persistence/src/guide/05-watching.ts @@ -0,0 +1,77 @@ +// © 2026 Adobe. MIT License. See /LICENSE for details. +import { System, World } from "@adobe/ecs"; +import { decode, encode, snapshot, spawn, watch } from "../index.js"; + +/** Saved in the session, kept across reloads, under its name there. */ +const session = Symbol(); +const label = Symbol(); +const filter = Symbol(); + +declare module "@adobe/ecs" { + interface Threads { + page: true; + } + interface Traits { + readonly [session]: string; + } + interface Components { + [label]: { type: string; [session]: "label" }; + } + interface Resources { + // Data the page's views read beside their elements, so it lives on the page's thread. + [filter]: { type: ReadonlyMap | null; default: null; thread: "page"; [session]: "filter" }; + } +} + +const addLabel = System.create(({ commands }) => { commands.spawn([label])({ [label]: "box" }); }); +/** Runs on the page's thread, which holds the filter. */ +const filterBoxes = System.create({}, ({ resources }) => { resources[filter] = new Map([...resources[filter] ?? [], ["shape", "box"]]); }); +const idle = System.create({}, () => {}); +const readFilter = System.create({ readonly: true }, ({ resources }) => [...resources[filter] ?? []].map(([key, value]) => `${key}: ${value}`).join(", ")); + +/** A world on this thread, with the page's thread joined through a channel, as a worker's world and its page are. */ +const open = async (): Promise<{ readonly world: World; readonly page: World }> => { + const world = World.create(); + const { port1, port2 } = new MessageChannel(); + const shared = world.share(port1); + const page = await World.join(port2, { threads: ["page"] }); + await shared; + return { world, page }; +}; + +export const main = async (): Promise => { + const { world, page } = await open(); + let saved: Uint8Array = new Uint8Array(0); + let due = false; + const stop = watch({ world, by: session }, () => { due = true; }); + if (typeof stop !== "function") return console.log(stop.failure); + /** Saves the session once something it covers changed. */ + const save = async (after: string): Promise => { + if (!due) return console.log(`${after}: nothing to save`); + due = false; + const taken = await snapshot({ world, by: session }); + if (taken.failure !== undefined) return console.log(taken.failure); + saved = encode(taken); + console.log(`${after}: saved`); + }; + await save("started"); + await world.run(addLabel); + await save("labeled"); + await world.run(idle); + await save("idle"); + await world.run(filterBoxes); + await save("filtered on the page"); + stop(); + await page.dispose(); + await world.dispose(); + + // Reloaded: the filter goes back to the page's thread. + const reloaded = await open(); + const read = decode(saved, { by: session }); + if (read.failure !== undefined) return console.log(read.failure); + const spawned = await spawn({ world: reloaded.world, snapshot: read }); + if (spawned.failure !== undefined) return console.log(spawned.failure); + console.log("reloaded filter:", await reloaded.page.run(readFilter)); + await reloaded.page.dispose(); + await reloaded.world.dispose(); +}; diff --git a/ecs/packages/ecs-persistence/src/guide/README.md b/ecs/packages/ecs-persistence/src/guide/README.md index 291864601..ffbae5094 100644 --- a/ecs/packages/ecs-persistence/src/guide/README.md +++ b/ecs/packages/ecs-persistence/src/guide/README.md @@ -8,3 +8,4 @@ the ECS's own chapters. 2. [Copying between worlds](02-copying.md) 3. [Saving chunks](03-chunks.md) 4. [Documents and settings](04-settings.md) +5. [Saving as it changes](05-watching.md) diff --git a/ecs/packages/ecs-persistence/src/guide/guide.test.ts b/ecs/packages/ecs-persistence/src/guide/guide.test.ts index 83ef72b07..211e63146 100644 --- a/ecs/packages/ecs-persistence/src/guide/guide.test.ts +++ b/ecs/packages/ecs-persistence/src/guide/guide.test.ts @@ -7,6 +7,7 @@ const teaches: { readonly [chapter: number]: readonly string[] } = { 2: ["snapshot({ world, by: file, root", "dropped", "entities: false", "entities", "match: [byLabel]"], 3: ["shared: true", "where: { [chunk]: [2, 0] }", "despawnWhere", "match: [byTree]"], 4: ["snapshot({ world, by: file })", "snapshot({ world, by: settings })", "decode", "spawn", "match: [byCamera]", "update: true"], + 5: ["watch({ world, by: session }", "thread: \"page\"", "snapshot({ world, by: session })", "spawn"], }; /** @@ -23,6 +24,10 @@ const mutations: { readonly [chapter: number]: readonly (readonly [string, strin ["[tool]: { type: string; default: \"select\"; [settings]: \"tool\" }", "[tool]: { type: string; default: \"select\"; [settings]: \"tool\"; [file]: \"tool\" }"], [", update: true", ""], ], + 5: [ + ["() => { due = true; }", "() => {}"], + ["; [session]: \"filter\"", ""], + ], }; checkChapters({ folder: new URL(".", import.meta.url), teaches, mutations }); diff --git a/ecs/packages/ecs-persistence/src/index.ts b/ecs/packages/ecs-persistence/src/index.ts index 626a29406..e06030cb5 100644 --- a/ecs/packages/ecs-persistence/src/index.ts +++ b/ecs/packages/ecs-persistence/src/index.ts @@ -9,3 +9,4 @@ export { encode } from "./encode.js"; export type { Failure } from "./failure.js"; export { snapshot, type Snapshot } from "./snapshot.js"; export { spawn, type Spawned } from "./spawn.js"; +export { watch } from "./watch.js"; diff --git a/ecs/packages/ecs-persistence/src/persistence.test.ts b/ecs/packages/ecs-persistence/src/persistence.test.ts index fdb1b171a..79f4c787a 100644 --- a/ecs/packages/ecs-persistence/src/persistence.test.ts +++ b/ecs/packages/ecs-persistence/src/persistence.test.ts @@ -5,6 +5,7 @@ import { decode } from "./decode.js"; import { encode } from "./encode.js"; import { snapshot, type Snapshot } from "./snapshot.js"; import { spawn } from "./spawn.js"; +import { watch } from "./watch.js"; /** Saved in a document, under its name. */ const document = Symbol(); @@ -35,7 +36,12 @@ const unsaved = Symbol(); const tool = Symbol(); const zoom = Symbol(); const glow = Symbol(); +const filter = Symbol(); +const focused = Symbol(); declare module "@adobe/ecs" { + interface Threads { + persistenceTestPage: true; + } interface Traits { readonly [document]: string; readonly [settings]: string; @@ -68,6 +74,9 @@ declare module "@adobe/ecs" { // The user's own, never in a document; the zoom also in the document, under another name. [tool]: { type: string; default: "select"; [settings]: "tool" }; [zoom]: { type: number; default: 1; [settings]: "zoom"; [document]: "view zoom" }; + // Held by the page's thread, which views read it on; data, so it's saved wherever it is. + [filter]: { type: ReadonlyMap | null; default: null; thread: "persistenceTestPage"; [settings]: "filter" }; + [focused]: { type: Entity; [settings]: "focused" }; } } @@ -131,7 +140,66 @@ const decoded = (bytes: Uint8Array): Snapshot => { return result; }; +/** A world on this thread, with the page's thread joined to it through a channel. */ +const withPage = async (): Promise<{ readonly world: World; readonly page: World }> => { + const world = inline(); + const channel = new MessageChannel(); + const shared = world.share(channel.port1); + const page = await World.join(channel.port2, { threads: ["persistenceTestPage"] }); + await shared; + return { world, page }; +}; + +const filterGiven: { value: ReadonlyMap } = { value: new Map() }; +const setFilter = System.create(({ commands }) => { commands.spawnTables([], { resources: { [filter]: filterGiven.value } }); }); +const readFilter = System.create({ readonly: true }, ({ resources }) => resources[filter]); +const retool = System.create({}, ({ resources }) => { resources[tool] = `${resources[tool]}!`; }); +const addName = System.create(({ commands }) => { commands.spawn([name])({ [name]: "watched" }); }); +const idle = System.create({}, () => {}); + describe("persistence", () => { + it("saves and loads a value the page's thread holds, and watches it change", async () => { + const { world, page } = await withPage(); + const changes: string[] = []; + const stop = watch({ world, by: settings }, () => changes.push("changed")); + if (typeof stop !== "function") throw new Error(stop.failure); + await world.run(idle); + changes.length = 0; + await world.run(idle); + expect(changes).toEqual([]); + filterGiven.value = new Map([["kept", Entity.none]]); + await world.run(setFilter); + expect(changes).toEqual(["changed"]); + const saved = await taken({ world, by: settings }); + const bytes = encode(saved); + await page.dispose(); + await world.dispose(); + + const opened = await withPage(); + const read = decode(bytes, { by: settings }); + if ("failure" in read) throw new Error(read.failure); + const spawned = await spawn({ world: opened.world, snapshot: read }); + expect(spawned.failure).toBeUndefined(); + expect(await opened.page.run(readFilter)).toEqual(new Map([["kept", Entity.none]])); + await opened.page.dispose(); + await opened.world.dispose(); + }); + it("watches what a trait covers, calling once per sync point that changed it, until stopped", async () => { + await using world = inline(); + const changes: number[] = []; + const stop = watch({ world, by: document }, () => changes.push(changes.length)); + if (typeof stop !== "function") throw new Error(stop.failure); + await world.run(idle); + changes.length = 0; + await world.run(retool); + expect(changes).toEqual([]); + await world.run(addName); + expect(changes).toEqual([0]); + stop(); + await world.run(addName); + expect(changes).toEqual([0]); + expect(watch({ world, by: clashing }, () => {})).toEqual({ failure: `The trait names two components "vitals".` }); + }); it("saves and loads every kind of value and the resources its trait covers, each entity value naming the entity loaded for it, cycles and self references included", async () => { await using from = World.create({ [workers]: 0, [score]: 12, [motto]: "onward", [unsaved]: 3 }); await from.run(scene); diff --git a/ecs/packages/ecs-persistence/src/watch.ts b/ecs/packages/ecs-persistence/src/watch.ts new file mode 100644 index 000000000..5a0643419 --- /dev/null +++ b/ecs/packages/ecs-persistence/src/watch.ts @@ -0,0 +1,25 @@ +// © 2026 Adobe. MIT License. See /LICENSE for details. +import { System, type World } from "@adobe/ecs"; +import type { Failure } from "./failure.js"; +import { programOf, type NamingTrait } from "./program/program.js"; + +/** + * Calls `onChange` after each sync point at which a component or resource the trait `by` covers changed, on whichever + * thread holds it: written, added to or removed from an entity, or held by an entity spawned or despawned; and once + * after the first sync point, so a consumer saving snapshots saves the first. It's called on `world`'s thread after + * the sync point's readonly systems, at most once each, so a burst of changes is one call; a consumer that saves + * less often waits there. Returns the function that stops it. Fails, as data, for a trait it can't save by, or a + * `world` joined from another thread, which can't see what other threads hold. + */ +export const watch = (input: { readonly world: World; readonly by: NamingTrait }, onChange: () => void): (() => void) | Failure => { + const program = programOf(input.by); + if (typeof program === "string") return { failure: program }; + const notice = System.create({ readonly: true, changed: [input.by] }, () => onChange()); + try { + input.world.add(notice); + } + catch (error) { + return { failure: error instanceof Error ? error.message : String(error) }; + } + return () => input.world.remove(notice); +}; diff --git a/ecs/packages/ecs/followups.md b/ecs/packages/ecs/followups.md index 42ad6a121..7b41ce5a4 100644 --- a/ecs/packages/ecs/followups.md +++ b/ecs/packages/ecs/followups.md @@ -5,6 +5,9 @@ correctness, then optimization. Remove an item once it's decided or done. ## API changes +- **Trait filters on joined threads:** a readonly system's `changed: [trait]` runs only on the world's thread, which sees + every thread's stamps; a joined thread's own refuses it. Possible: the thread declares the trait's id with its + observer, and the world's posting check tests the trait as the world's own runner does. - **Instrumentation:** a later `World.create` options parameter may take instrumentation: timing, failure logs, debugging, and what no failure says, a tier that waited for a joined thread and commands that did nothing, which the implementation gathers only for its tests (`recorderOf`). Nothing until it's designed. diff --git a/ecs/packages/ecs/package.json b/ecs/packages/ecs/package.json index 9ac688b2b..572d552d7 100644 --- a/ecs/packages/ecs/package.json +++ b/ecs/packages/ecs/package.json @@ -1,6 +1,6 @@ { "name": "@adobe/ecs", - "version": "0.5.2", + "version": "0.6.0", "description": "Adobe ECS", "license": "MIT", "type": "module", diff --git a/ecs/packages/ecs/src/implementation/world/batches.ts b/ecs/packages/ecs/src/implementation/world/batches.ts index 78e56f33f..572ec650b 100644 --- a/ecs/packages/ecs/src/implementation/world/batches.ts +++ b/ecs/packages/ecs/src/implementation/world/batches.ts @@ -6,9 +6,9 @@ import { blockShift, chunkShift } from './kernel.js'; import { createBatch, type SpawnBatch } from './staging.js'; import { archetypeOf, type State } from './state.js'; import { gainsOf } from './structure.js'; -import { remoteError } from './remote.js'; +import { batchRemote } from './remote.js'; import { countChanged } from './layout-directory.js'; -import { logRange, logSet, startTag, tagOf } from './move-log.js'; +import { deliveredTag, logRange, logSet, startTag, tagOf } from './move-log.js'; import { writeDefault } from './synchronize.js'; import { writeString } from './strings.js'; import { cacheShared, internShared } from './shared.js'; @@ -26,7 +26,7 @@ export const batchOf = (state: State, ids: readonly number[], shared: readonly ( let batch = state.batchByKey.get(key); if (batch === undefined) { batch = createBatch(state.layouts, ids, shared); - for (const column of batch.columns) if (state.remote[column.id] !== undefined) column.remote = remoteError(state, column.id).message; + for (const column of batch.columns) if (state.remote[column.id] !== undefined) column.remote = batchRemote(state, column.id); state.batchByKey.set(key, batch); state.batches.push(batch); if (shared !== noShared) letGoWith(state, batch, key); @@ -123,7 +123,9 @@ const commitRows = (state: State, batch: SpawnBatch, first: number, n: number, t const log = storage.remote; const begin = log.starts[column.id]; for (let i = 0; i < n; i++) { - const tag = Math.max(startTag, tagOf(column.values[first + i], begin)); + const value = column.values[first + i]; + const given = tagOf(value, begin); + const tag = given >= 0 ? given : deliveredTag(log, value); storage.tags[start + i] = tag; if (tag !== startTag) logSet(log, target.id, start + i, column.id, tag, true); } diff --git a/ecs/packages/ecs/src/implementation/world/commands.ts b/ecs/packages/ecs/src/implementation/world/commands.ts index 57629fecf..9246fa626 100644 --- a/ecs/packages/ecs/src/implementation/world/commands.ts +++ b/ecs/packages/ecs/src/implementation/world/commands.ts @@ -10,6 +10,7 @@ import { despawnMatchOf, holdsCollection, isMatching, type DespawnMatch } from ' import { holdsValuesOf } from './where.js'; import { declarationOf, isWorldWritten, kindOf, labelOf, threadOfDeclaration, whyUnregistered } from '../../interface/registry/index.js'; import { matchesSchema } from '../../interface/registry/schemas.js'; +import { isDelivered } from './remote.js'; const collect = (state: State, buffer: CommandBuffer, key: Key, value: unknown): void => { if (value !== undefined) pushComponent(buffer, idOf(state, key), value); @@ -52,18 +53,18 @@ const addShared = (state: State, buffer: CommandBuffer, entity: number, shape: L }; /** - * Throws for a key of `resources` that isn't a resource, is one only the world writes or one living on another thread, - * or is given a value its schema doesn't take. + * Throws for a key of `resources` that isn't a resource, is one only the world writes, or one a joined thread fills + * that isn't data, or is given a value its schema doesn't take. */ -const checkResources = (resources: object): void => { +const checkResources = (state: State, resources: object): void => { for (const key of Object.getOwnPropertySymbols(resources)) { const fail = (message: string): never => { throw new Error(`commands.spawnTables: "${labelOf(key)}" ${message}.`); }; if (kindOf(key) !== "resource") fail(`isn't a registered resource: ${whyUnregistered(key)}`); if (isWorldWritten(key)) fail("is written only by the world"); const declaration = declarationOf(key); if (declaration === undefined) continue; - const thread = threadOfDeclaration(declaration); - if (thread !== null && thread !== "world") fail(`lives on thread "${thread}", not the world's`); + const id = idOf(state, key); + if (state.remote[id] !== undefined && !isDelivered(state, id)) fail(`lives on thread "${threadOfDeclaration(declaration) ?? "world"}", which a joined thread fills, and isn't data`); if (declaration.type !== undefined && !matchesSchema(declaration.type, Reflect.get(resources, key))) fail("is given a value its type doesn't take"); } }; @@ -176,10 +177,8 @@ export const createCommands = (state: State, target: { readonly buffer: CommandB const resources = options?.resources; const updates = options?.update === true ? target.buffer : null; if (resources === undefined) return spawnTables(state, tables, options?.existing, updates); - checkResources(resources); - const spawned = spawnTables(state, tables, options?.existing, updates); - queueResources(state, resources); - return spawned; + checkResources(state, resources); + return spawnTables(state, tables, options?.existing, updates, resources, remapped => queueResources(state, remapped)); }, remove: (entity: number, components: symbol | readonly symbol[]) => { const { buffer } = target; diff --git a/ecs/packages/ecs/src/implementation/world/join.ts b/ecs/packages/ecs/src/implementation/world/join.ts index 09fbd63eb..73ac36655 100644 --- a/ecs/packages/ecs/src/implementation/world/join.ts +++ b/ecs/packages/ecs/src/implementation/world/join.ts @@ -16,7 +16,7 @@ import { } from './joining.js'; import { currentBuffer, sharedMemoryAvailable } from './memory.js'; import { logRunWord } from './move-log.js'; -import { createMirror, nameComponent, rebuild, replay, type Mirror } from './mirror.js'; +import { createMirror, nameComponent, rebuild, receive, replay, resourceValueOf, waitStructure, type Mirror } from './mirror.js'; import { defaultOf } from './state.js'; import { createThreadSystems, type SystemSetup } from './thread-systems.js'; import { taskBlockWords } from './thread-tasks.js'; @@ -26,6 +26,9 @@ import type { Leaf } from '../../interface/system/leaf.js'; import { isObserver, scheduleOf } from '../../interface/registry/schedule.js'; import { releaseInput, transferablesOf } from './transfers.js'; +/** A gather the world asked for: the objects it wants by the world's numbers. */ +type GatherAsked = { readonly id: number; readonly components: readonly number[]; readonly resources: readonly number[] }; + /** The last of the numbers of runs of several observer systems. */ const nothing = (): undefined => undefined; @@ -325,6 +328,51 @@ export const joinWorld = (port: Parameters[0], options: { readon nameComponent(mirror, component, key, defaultOf); }; + /** Gathers the world asked for, answered once the mirror replayed the last published sync. */ + const gathers: GatherAsked[] = []; + /** Answers the gathers asked for, once the mirror is current; those left wait for a key, values or the structure epoch. */ + const answerGathers = (): void => { + if (gathers.length === 0) return; + const replayed = mirror; + if (replayed !== null) { + const state = replay(replayed); + if (state === "held") return; + if (state === "lapped") { + const rebuilt = rebuild(replayed); + if (rebuilt === "held") return; + if (rebuilt === "moved") { + void waitStructure(replayed).then(answerGathers); + return; + } + } + } + for (const asked of gathers.splice(0)) answerGather(replayed, asked); + }; + /** What the mirror holds of the objects a gather asked for, posted to the world, or why it can't be. */ + const answerGather = (replayed: Mirror | null, { id, components, resources }: GatherAsked): void => { + const columns = components.map(component => { + const entities: number[] = []; + const values: unknown[] = []; + for (const archetype of replayed?.archetypes ?? []) { + const column = archetype?.byComponent[component]; + if (archetype === null || archetype === undefined || column === undefined) continue; + for (let row = 0; row < archetype.count; row++) { + entities.push(archetype.entities[row]); + values.push(column.values[row]); + } + } + const gathered: readonly [number, Float64Array, readonly unknown[]] = [component, Float64Array.from(entities), values]; + return gathered; + }); + const values = resources.map((component): readonly [number, unknown] => [component, replayed === null ? null : resourceValueOf(replayed, component, replayed.starts.get(component))]); + try { + post({ protocol: protocolName, kind: "gathered", id, components: columns, resources: values }); + } + catch (error) { + post({ protocol: protocolName, kind: "gathered", id, error: `its values can't be posted to the world's thread: ${error instanceof Error ? error.message : String(error)}` }); + } + }; + /** Whether the last `process` finished a task, so the next of a tick's tasks may follow it closely. */ let tasked = false; const process = (): void => { @@ -493,11 +541,25 @@ export const joinWorld = (port: Parameters[0], options: { readon // Its key here, if this thread has one, for a component of a thread it claims. const key = message.id === null ? undefined : keyOfId(message.id); name(message.component, key !== undefined && ownObject(key, claims) ? key : null); + answerGathers(); // A task waiting for this component's key runs now, and posts of observer systems. systems?.process(); observer?.process(); return; } + case "gather": { + gathers.push({ id: message.id, components: message.components, resources: message.resources }); + return answerGathers(); + } + case "values": { + if (mirror !== null) receive(mirror, message.sync, message.first, message.values); + answerGathers(); + // What waited for them goes on: stops, a task, observer systems. + systems?.runStops(); + systems?.process(); + observer?.process(); + return; + } case "systems": { if (systems === null) setups.push(...message.systems); else systems.setup(message.systems); @@ -512,6 +574,7 @@ export const joinWorld = (port: Parameters[0], options: { readon case "sync systems": { if (systems === null) removedSetups.push(...message.syncSystems); else systems.setupRemovedSystems(message.syncSystems); + answerGathers(); // What waited for them goes on: stops, a task, observer systems. systems?.runStops(); systems?.process(); @@ -607,7 +670,8 @@ export const joinWorld = (port: Parameters[0], options: { readon return keyNumber(symbol); }); const present = (keys: readonly unknown[] | undefined): number[] => (keys ?? []).map(keyNumber); - const { components, resources, lookup } = leaf.declaration; + const { components, resources, lookup, changed } = leaf.declaration; + if (changed !== undefined) throw new Error(`Observer system "${label}" filters on traits' changes, so it runs only on the world's thread.`); const lookups: ObserverLookup[] = []; for (const name of Object.keys(lookup ?? {})) { const declared = lookup?.[name]; diff --git a/ecs/packages/ecs/src/implementation/world/joining.ts b/ecs/packages/ecs/src/implementation/world/joining.ts index 61643324e..ef61ff86a 100644 --- a/ecs/packages/ecs/src/implementation/world/joining.ts +++ b/ecs/packages/ecs/src/implementation/world/joining.ts @@ -1,5 +1,6 @@ // © 2026 Adobe. MIT License. See /LICENSE for details. import type { World } from '../../interface/world/world.js'; +import type { Gathered } from './move-log.js'; import type { WorkerError } from './protocol.js'; import type { Schema } from '../../interface/schema/schema.js'; import { layoutOf, viewsOf, type Layout, type Views } from '../../interface/registry/layout.js'; @@ -123,6 +124,8 @@ export type ToWorld = { readonly protocol: typeof protocolName } & ( | { readonly kind: "observer dropped"; readonly indexes: readonly number[] } /** A post it claimed and couldn't run yet, owed to a run: the world posts it again between runs. */ | { readonly kind: "observer again" } + /** What it holds of the objects gather `id` asked for, or why it couldn't give them. */ + | ({ readonly kind: "gathered"; readonly id: number } & Gathered) ); /** From the world's thread to a joined one. */ @@ -173,6 +176,10 @@ export type ToJoined = { readonly protocol: typeof protocolName } & ( | { readonly kind: "release"; readonly from: number; readonly sequence: number } /** A component whose objects the thread fills, by the world's number, with its id: null for one without. */ | { readonly kind: "component"; readonly component: number; readonly id: string | null } + /** Values the world's thread gives the thread's objects at sync `sync`, numbered from `first`, as its move log's tags name them. */ + | { readonly kind: "values"; readonly sync: number; readonly first: number; readonly values: readonly unknown[] } + /** Asks for the values it holds of its objects `components` and `resources`, by the world's numbers, as of a published sync. */ + | { readonly kind: "gather"; readonly id: number; readonly components: readonly number[]; readonly resources: readonly number[] } | { readonly kind: "refused"; readonly message: string } /** The name of the Web Lock the world's thread holds while it lives (`threadLock`), posted as it's shared and as it's asked to join. */ | { readonly kind: "thread lock"; readonly lock: string } diff --git a/ecs/packages/ecs/src/implementation/world/mirror.ts b/ecs/packages/ecs/src/implementation/world/mirror.ts index 4b2997bd9..a0fafe0ab 100644 --- a/ecs/packages/ecs/src/implementation/world/mirror.ts +++ b/ecs/packages/ecs/src/implementation/world/mirror.ts @@ -8,6 +8,7 @@ import { import { appendEntry, archetypeShift, entryWords, kindMask, logCapacityWord, logHeaderBytes, logLimitWord, logOffsetWord, logPublishedWord, logSyncWord, logVersionWord, logBoundWord, logBoundedWord, moveEntry, nullTag, ownTag, rangeEntry, setEntry, slotTags, startTag, swapEntry, syncEntry, + deliveredMask, deliveredTags, slotMask, } from './move-log.js'; import { coveringBuffer, currentBuffer, pageBytes, pagesWord } from './memory.js'; import { releaseValue } from './transfers.js'; @@ -78,6 +79,10 @@ export type Mirror = { /** The first staged slot not yet settled, by index into `staged`; the next slot's id. */ head: number; nextSlot: number; + /** Values the world's thread gave this thread's objects, by number, until a replay or rebuild through their sync. */ + readonly delivered: Map; + /** The number of the next value the world delivers. */ + received: number; /** Times it rebuilt, for tests. */ rebuilds: number; /** The archetype last found holding the resource entity, or -1. */ @@ -105,7 +110,7 @@ export const createMirror = (memory: WebAssembly.Memory, block: number, thread: memory, thread, block, buffer: memory.buffer, words: new Uint32Array(0), signed: new Int32Array(0), header: new Int32Array(0), ring: new Uint32Array(0), ringEntities: new Float64Array(0), version: -1, mask: 0, position: 0, through: 0, tick: 0, keys: new Map(), starts: new Map(), archetypes: [], scratch: new Uint32Array(1024), scratchEntities: new Float64Array(0), - staged: [], head: 0, nextSlot: 0, rebuilds: 0, resourceArchetype: -1, stagedTransfers: 0, runStops: null, + staged: [], head: 0, nextSlot: 0, delivered: new Map(), received: 0, rebuilds: 0, resourceArchetype: -1, stagedTransfers: 0, runStops: null, }; refresh(mirror); return mirror; @@ -210,17 +215,45 @@ const fill = (archetype: Mirrored, row: number, entity: number): void => { if (row >= archetype.count) archetype.count = row + 1; }; +/** Where a staged slot is in `staged`, by its distance from the head's: slots are numbered in order, wrapping. */ +const stagedAt = (mirror: Mirror, slot: number): number => { + const first = mirror.staged[mirror.head]?.slot ?? slot; + return mirror.head + ((slot - first) & slotMask); +}; + /** The value of a staged slot, taking it; the start where it was settled already. */ const take = (mirror: Mirror, slot: number, start: unknown): unknown => { - const at = mirror.head + ((slot - (mirror.staged[mirror.head]?.slot ?? slot)) | 0); + const at = stagedAt(mirror, slot); const staged = mirror.staged[at]; if (staged === undefined || staged.slot !== slot || !staged.live) return start; staged.live = false; return staged.value; }; -/** Settles staged slots whose sync applied without naming them: their commands dropped, so their values are released. */ +/** Whether the value the world delivers as `tag` arrived. */ +const isReceived = (mirror: Mirror, tag: number): boolean => (((tag - deliveredTags) - mirror.received) & deliveredMask) >= 0x40000000; + +/** Keeps values the world's thread delivered for sync `sync`, numbered from `first`, until a replay or rebuild takes them. */ +export const receive = (mirror: Mirror, sync: number, first: number, values: readonly unknown[]): void => { + for (let k = 0; k < values.length; k++) mirror.delivered.set((first + k) & deliveredMask, { value: values[k], sync: sync >>> 0 }); + mirror.received = (first + values.length) & deliveredMask; +}; + +/** A delivered value by its tag, taken; the start where it's gone, taken by a rebuild that read a later tag. */ +const takeDelivered = (mirror: Mirror, tag: number, start: unknown): unknown => { + const number = (tag - deliveredTags) & deliveredMask; + const found = mirror.delivered.get(number); + if (found === undefined) return start; + mirror.delivered.delete(number); + return found.value === undefined ? start : found.value; +}; + +/** + * Settles staged slots whose sync applied without naming them: their commands dropped, so their values are released; + * and drops delivered values of syncs applied, which a rebuild past them never read. + */ const settle = (mirror: Mirror): void => { + if (mirror.delivered.size > 0) for (const [number, { sync }] of mirror.delivered) if (((mirror.through - sync) | 0) >= 0) mirror.delivered.delete(number); const { staged } = mirror; let stagedTransfers = 0; for (let k = mirror.head; k < staged.length; k++) { @@ -251,7 +284,7 @@ const settle = (mirror: Mirror): void => { */ export const stage = (mirror: Mirror, entity: number, component: number, value: unknown, sync: number, transfer = false): number => { const slot = mirror.nextSlot; - mirror.nextSlot = (slot + 1) >>> 0; + mirror.nextSlot = (slot + 1) & slotMask; mirror.staged.push({ slot, entity, component, value, sync: sync >>> 0, transfer, live: true }); if (transfer) mirror.stagedTransfers++; return slot; @@ -325,7 +358,8 @@ const apply = (mirror: Mirror, count: number): number => { const to = archetypes[archetype]; const column = to === null || to === undefined ? undefined : to.byComponent[scratch[at + 2]]; const tag = scratch[at + 3]; - const value = tag === startTag ? column?.start : tag === nullTag ? null : take(mirror, (tag - slotTags) >>> 0, column?.start); + const value = tag === startTag ? column?.start : tag === nullTag ? null + : tag >= deliveredTags ? takeDelivered(mirror, tag, column?.start) : take(mirror, (tag - slotTags) >>> 0, column?.start); if (column !== undefined) column.values[scratch[at + 1]] = value; break; } @@ -366,6 +400,7 @@ const heldAt = (mirror: Mirror, count: number): number => { } if (archetypeOf(mirror, first >>> archetypeShift) === undefined) return syncStart; if (kind === moveEntry && archetypeOf(mirror, scratch[e * entryWords + 2]) === undefined) return syncStart; + if (kind === setEntry && scratch[e * entryWords + 3] >= deliveredTags && !isReceived(mirror, scratch[e * entryWords + 3])) return syncStart; } return count; }; @@ -510,8 +545,9 @@ export const rebuild = (mirror: Mirror): Rebuilt => { return previousValue(old, entity, component, start); })) return "held"; const archetypes: (Mirrored | null)[] = []; - /** Staged slots the rebuild takes, settled only once it's complete. */ + /** Staged slots and delivered values the rebuild takes, settled only once it's complete. */ const taken: number[] = []; + const takenDelivered: number[] = []; const tables = Atomics.load(words, tableLengthWord); for (let id = 0; id < tables; id++) { const record = recordOf(mirror, id); @@ -538,6 +574,23 @@ export const rebuild = (mirror: Mirror): Rebuilt => { if (tag === startTag) continue; const entity = archetype.entities[row]; if (tag === nullTag) column.values[row] = null; + else if (tag >= deliveredTags) { + if (!isReceived(mirror, tag)) return "held"; + const number = (tag - deliveredTags) & deliveredMask; + const found = mirror.delivered.get(number); + if (found !== undefined) { + column.values[row] = found.value === undefined ? column.start : found.value; + takenDelivered.push(number); + } + else { + // Taken by a replay before: the row holds it still. + if (!indexed) { + indexPrevious(old, entityLength); + indexed = true; + } + column.values[row] = previousValue(old, entity, column.component, column.start); + } + } else { // A value this thread's systems wrote is kept by entity, as one whose slot settled. const slot = (tag - slotTags) >>> 0; @@ -564,6 +617,7 @@ export const rebuild = (mirror: Mirror): Rebuilt => { const staged = stagedOf(mirror, slot); if (staged !== undefined) staged.live = false; } + for (const number of takenDelivered) mirror.delivered.delete(number); mirror.archetypes = archetypes; mirror.version = version; mirror.position = published; @@ -616,11 +670,17 @@ export const stagedValue = (mirror: Mirror, slot: number, settled: unknown): unk return staged === undefined ? settled : staged.value; }; +/** A delivered value by its tag while no sync applied it, else `settled`. */ +export const deliveredValue = (mirror: Mirror, tag: number, settled: unknown): unknown => { + const found = mirror.delivered.get((tag - deliveredTags) & deliveredMask); + return found === undefined ? settled : found.value; +}; + /** A live staged slot by its id. */ const stagedOf = (mirror: Mirror, slot: number): Staged | undefined => { const { staged, head } = mirror; if (head >= staged.length) return undefined; - const at = head + ((slot - staged[head].slot) | 0); + const at = stagedAt(mirror, slot); const entry = staged[at]; return entry !== undefined && entry.slot === slot && entry.live ? entry : undefined; }; diff --git a/ecs/packages/ecs/src/implementation/world/move-log.test.ts b/ecs/packages/ecs/src/implementation/world/move-log.test.ts index d56c64ae9..2e038733a 100644 --- a/ecs/packages/ecs/src/implementation/world/move-log.test.ts +++ b/ecs/packages/ecs/src/implementation/world/move-log.test.ts @@ -5,7 +5,7 @@ import { readCell } from "./cells.js"; import { createCommands } from "./commands.js"; import { asEntity, indexOf, locate as locateHere } from "./entities.js"; import { recordCount, structureWord, tableOffsetWord } from "./layout-directory.js"; -import { applying, cellOf, createMirror, nameComponent, rebuild, replay, stage, waitStructure, type Mirror } from "./mirror.js"; +import { applying, cellOf, createMirror, nameComponent, rebuild, receive, replay, stage, waitStructure, type Mirror } from "./mirror.js"; import { createMoveLog, logSyncWord, ownTag, slotValue, type MoveLog } from "./move-log.js"; import { claimThreads } from "./remote.js"; import { createState, defaultOf, idOf, startTicking, type State } from "./state.js"; @@ -58,18 +58,29 @@ const random = (seed: number) => { }; }; -/** A world whose "moveLogTest" objects a mirror on this thread fills, its log holding at least `minimum` entries. */ -const threaded = (minimum: number): { readonly state: State; readonly mirror: Mirror; readonly log: MoveLog } => { +/** Values the world's thread delivered, posted as messages are, which `arrive` hands the mirror. */ +type Delivery = { readonly sync: number; readonly first: number; readonly values: readonly unknown[] }; + +/** + * A world whose "moveLogTest" objects a mirror on this thread fills, its log holding at least `minimum` entries; the + * values it delivers wait in `deliveries` until `arrive`. + */ +const threaded = (minimum: number) => { const state = createState(true); let mirror: Mirror | null = null; - const log = createMoveLog(state.memory, 1, state.starts, component => { + const deliveries: Delivery[] = []; + const log: MoveLog = createMoveLog(state.memory, 1, state.starts, component => { const key = state.keys[component]; if (mirror !== null && typeof key === "symbol") nameComponent(mirror, component, key, defaultOf); - }, minimum); - mirror = createMirror(state.memory.memory, log.block, 1); + }, (sync, first, values) => { deliveries.push({ sync, first, values: structuredClone(values) }); }, () => Promise.resolve({ error: "no thread" }), minimum); + const made = createMirror(state.memory.memory, log.block, 1); + mirror = made; for (const key of [uid, amount, flag, own, ...remoteKeys]) idOf(state, key); claimThreads(state, log, ["moveLogTest"]); - return { state, mirror, log }; + const arrive = (): void => { + for (const { sync, first, values } of deliveries.splice(0)) receive(made, sync, first, values); + }; + return { state, mirror: made, log, deliveries, arrive }; }; const inline = (): State => { @@ -131,13 +142,13 @@ const worldCommands = (state: State) => { /** * Random spawns, despawns, adds and removes, single and list forms, from the world's thread, which give the thread's - * objects only their start or null; then the thread's own values for its objects, staged by the mirror, and world + * labels, data, values of their own, delivered, and its notes only their start or null; then the thread's own values for its objects, staged by the mirror, and world * commands after those, all applied as one sync point in both worlds. */ const property = (seed: number, minimum: number, steps: number): { readonly compared: number; readonly rebuilds: number } => { const next = random(seed); const pick = (list: readonly T[]): T => list[Math.floor(next() * list.length)]; - const { state: world, mirror } = threaded(minimum); + const { state: world, mirror, deliveries, arrive } = threaded(minimum); const reference = inline(); let nextUid = 1; let compared = 0; @@ -164,8 +175,9 @@ const property = (seed: number, minimum: number, steps: number): { readonly comp nextUid++; const form = Math.floor(next() * 4); const value = next() < 0.5 ? undefined : null; + const given = next() < 0.5 ? value : { text: `w${step}.${o}` }; both(commands => { - if (form === 0) commands.spawn([uid, label])({ [uid]: id, [label]: value }); + if (form === 0) commands.spawn([uid, label])({ [uid]: id, [label]: given }); else if (form === 1) commands.spawn([uid, amount, label, note])({ [uid]: id, [amount]: 1, [note]: value }); else if (form === 2) commands.spawn([uid, flag])({ [uid]: id }); else commands.spawn([uid, note, own])({ [uid]: id, [own]: "o" }); @@ -178,8 +190,9 @@ const property = (seed: number, minimum: number, steps: number): { readonly comp else if (choice < 0.55) { const entity = someone(); const form = Math.floor(next() * 4); + const given = next() < 0.5 ? none : { text: `a${step}.${o}` }; both(commands => { - if (form === 0) commands.add(entity, label, none); + if (form === 0) commands.add(entity, label, given); else if (form === 1) commands.add(entity, note, null); else if (form === 2) commands.add(entity, [amount, label], { [amount]: 2 }); else commands.add(entity, [flag, note, label], { [label]: null }); @@ -219,10 +232,17 @@ const property = (seed: number, minimum: number, steps: number): { readonly comp synchronize(state); } dead = [...dead, ...live.filter(entity => locateHere(reference.entities, entity) < 0)].slice(-20); + // Now and then the values delivered arrive after the thread tried to replay: it holds before their sync. + if (deliveries.length > 0 && next() < 0.3) { + const replayed = replay(mirror); + if (replayed !== "lapped") expect(replayed).toBe("held"); + } + arrive(); follow(mirror); compared += compare(reference, world, mirror); - // Every staged slot is settled once its sync point applied. + // Every staged slot and delivered value is settled once its sync point applied. expect(mirror.staged.slice(mirror.head).filter(entry => entry.live)).toEqual([]); + expect(mirror.delivered.size).toBe(0); } return { compared, rebuilds: mirror.rebuilds }; }; diff --git a/ecs/packages/ecs/src/implementation/world/move-log.ts b/ecs/packages/ecs/src/implementation/world/move-log.ts index 2d93c4457..a4899c005 100644 --- a/ecs/packages/ecs/src/implementation/world/move-log.ts +++ b/ecs/packages/ecs/src/implementation/world/move-log.ts @@ -52,13 +52,18 @@ export const swapEntry = 5; export const setEntry = 6; /** - * Tags: the component's start, `null`, a value the thread's systems wrote, which it keeps by entity, or a staged slot's - * value, by the slot's id plus `slotTags`. + * Tags: the component's start, `null`, a value the thread's systems wrote, which it keeps by entity, a staged slot's + * value, by the slot's id plus `slotTags`, or a value the world's thread gave, delivered to the thread by message, by its + * number plus `deliveredTags`. */ export const startTag = 0; export const nullTag = 1; export const ownTag = 2; export const slotTags = 3; +export const deliveredTags = 0x80000000; +/** Staged slots' ids wrap below `deliveredTags - slotTags`; delivered values' numbers wrap at 2^31. */ +export const slotMask = 0x3fffffff; +export const deliveredMask = 0x7fffffff; /** Entries a log holds at least. */ export const minimumEntries = 4096; @@ -102,8 +107,23 @@ export type MoveLog = { readonly minimum: number; /** Tells the thread a component it fills, once the world met it. */ readonly announce: (component: number) => void; + /** Values the current sync gives the thread's objects from the world's thread, the first numbered `delivered`. */ + readonly delivering: unknown[]; + delivered: number; + /** Posts the thread the values a sync gives its objects, numbered from `first`, before the sync is published. */ + readonly deliver: (sync: number, first: number, values: readonly unknown[]) => void; + /** Asks the thread for the values it holds of its objects `components` and `resources`, copies (`Gathered`). */ + readonly gather: (components: readonly number[], resources: readonly number[]) => Promise; }; +/** + * What a joined thread holds of its objects, copied: of each component, every entity holding it and its value, and + * each resource's value; or why it couldn't give them. + */ +export type Gathered = + | { readonly components: readonly (readonly [number, Float64Array, readonly unknown[]])[]; readonly resources: readonly (readonly [number, unknown])[]; readonly error?: undefined } + | { readonly error: string }; + const powerOfTwo = (entries: number): number => 2 ** Math.ceil(Math.log2(Math.max(entries, 1))); const placeRing = (log: MoveLog, capacity: number): void => { @@ -119,12 +139,16 @@ const placeRing = (log: MoveLog, capacity: number): void => { }; /** A log in shared memory for joined thread `thread`, its ring holding `minimum` entries at least. */ -export const createMoveLog = (memory: Memory, thread: number, starts: readonly unknown[], announce: (component: number) => void, minimum = minimumEntries): MoveLog => { +export const createMoveLog = ( + memory: Memory, thread: number, starts: readonly unknown[], announce: (component: number) => void, + deliver: MoveLog["deliver"], gather: MoveLog["gather"], minimum = minimumEntries, +): MoveLog => { const block = memory.allocate(logHeaderBytes); const header = new Int32Array(memory.memory.buffer, block, logHeaderBytes / 4).fill(0); const log: MoveLog = { thread, memory, header, block, ring: new Uint32Array(0), ringEntities: new Float64Array(0), mask: 0, position: 0, limit: 0, tick: -1, headed: false, starts, archetypes: [], minimum: powerOfTwo(minimum), announce, + delivering: [], delivered: 0, deliver, gather, }; placeRing(log, log.minimum); return log; @@ -201,9 +225,27 @@ export const logSwap = (log: MoveLog, archetype: number, last: number, row: numb export const logSet = (log: MoveLog, archetype: number, row: number, component: number, tag: number, added: boolean): void => entry(log, setEntry | (added ? addedFlag : 0) | (archetype << archetypeShift), row, component, tag); -/** At the end of a sync point: its entries, then the sync, published, each by a store the thread loads. */ +/** + * The tag of a value the world's thread gives the thread's object, delivered to it by message before its sync is + * published. + */ +export const deliveredTag = (log: MoveLog, value: unknown): number => { + const number = (log.delivered + log.delivering.length) & deliveredMask; + log.delivering.push(value); + return (deliveredTags + number) >>> 0; +}; + +/** + * At the end of a sync point: the values it delivers, posted, then its entries and the sync, published, each by a + * store the thread loads. + */ export const publishLog = (log: MoveLog): void => { if (log.tick < 0) return; + if (log.delivering.length > 0) { + const values = log.delivering.splice(0); + log.deliver(log.tick >>> 0, log.delivered, values); + log.delivered = (log.delivered + values.length) & deliveredMask; + } if (log.headed) Atomics.store(log.header, logPublishedWord, log.position); Atomics.store(log.header, logSyncWord, log.tick >>> 0); log.tick = -1; diff --git a/ecs/packages/ecs/src/implementation/world/observer.ts b/ecs/packages/ecs/src/implementation/world/observer.ts index 09e7c6db8..c2c20b19b 100644 --- a/ecs/packages/ecs/src/implementation/world/observer.ts +++ b/ecs/packages/ecs/src/implementation/world/observer.ts @@ -6,6 +6,9 @@ import { failureOf } from './failures.js'; import { refreshUses } from './indexes.js'; import type { Runner } from './runner.js'; import { joinedOf, type JoinedObserver } from './joined-observer.js'; +import type { Gathered, MoveLog } from './move-log.js'; +import { isDelivered } from './remote.js'; +import { idOf, type State } from './state.js'; /** * Runs observer systems after a sync point, on this thread: those of the run, `own`, then those added, `added`, each @@ -19,16 +22,60 @@ export const runObserver = (context: ExecuteContext, own: readonly Leaf[], added // Those on joined threads are posted there, which reads back and refreshes what they read itself. if (!ownPass.here && !addedPass.here) return context.state.indexFailures.length === 0 ? failures : runAll(context, own, added, ownPass, addedPass, failures); const waiting = ownPass.indexed || addedPass.indexed || context.state.gpu !== null ? prepare(context, ownPass, addedPass) : null; - if (waiting !== null) return finishAfter(waiting, context, own, added, ownPass, addedPass, failures); + const gathering = context.state.claimed && (ownPass.tabled || addedPass.tabled) ? gather(context.state, ownPass, addedPass) : null; + if (waiting !== null || gathering !== null) return finishAfter(Promise.all([waiting, gathering]), context, own, added, ownPass, addedPass, failures); return runAll(context, own, added, ownPass, addedPass, failures); }; +/** + * Asks each joined thread holding objects the tables of a pass's systems here read for them, kept in `state.gathered` + * while the pass runs; null when none of them is a joined thread's. + */ +const gather = (state: State, own: Pass, added: Pass): Promise | null => { + const asked = new Map; readonly resources: Set }>(); + const gathered: NonNullable = { components: new Map(), resources: new Map(), errors: new Map() }; + const ask = (key: symbol, resource: boolean): void => { + const id = idOf(state, key); + const log = state.remote[id]; + if (log === undefined) return; + if (!isDelivered(state, id)) { + gathered.errors.set(id, "it isn't data, which a copy carries"); + return; + } + let keys = asked.get(log); + if (keys === undefined) asked.set(log, keys = { components: new Set(), resources: new Set() }); + (resource ? keys.resources : keys.components).add(id); + }; + for (const { runners } of [own, added]) { + for (const { tables, joined } of runners) { + if (tables === null || joined !== null) continue; + for (const key of tables.components) ask(key, false); + for (const key of tables.resources ?? []) ask(key, true); + } + } + if (asked.size === 0 && gathered.errors.size === 0) return null; + state.gathered = gathered; + return Promise.all([...asked].map(async ([log, { components, resources }]) => { + const given = await log.gather([...components], [...resources]).catch((error: unknown): Gathered => ({ error: error instanceof Error ? error.message : String(error) })); + if (given.error !== undefined) { + for (const id of [...components, ...resources]) gathered.errors.set(id, given.error); + return; + } + for (const [id, entities, values] of given.components) { + const byEntity = new Map(); + for (let k = 0; k < entities.length; k++) byEntity.set(entities[k], values[k]); + gathered.components.set(id, byEntity); + } + for (const [id, value] of given.resources) gathered.resources.set(id, value); + })).then(() => undefined); +}; + /** * A list's runners, read again once one was replaced or removed, or for another list; whether any looks up through an * index, and whether any runs on this thread rather than a joined one. A runner removed since it was read reads as * removed, so a pass in progress skips it. */ -type Pass = { leaves: readonly Leaf[]; readonly runners: Runner[]; indexed: boolean; here: boolean; version: number; joined: readonly JoinedObserver[] | null }; +type Pass = { leaves: readonly Leaf[]; readonly runners: Runner[]; indexed: boolean; here: boolean; tabled: boolean; version: number; joined: readonly JoinedObserver[] | null }; /** * A context's passes: by list for runs' own observer systems, whose lists last as their schedules do; and one for those @@ -38,8 +85,8 @@ type Passes = { readonly own: WeakMap; readonly added: Pa const passes = new WeakMap(); const noLeaves: readonly Leaf[] = []; -const emptyPass: Pass = { leaves: noLeaves, runners: [], indexed: false, here: false, version: -1, joined: [] }; -const createPass = (leaves: readonly Leaf[]): Pass => ({ leaves, runners: [], indexed: false, here: false, version: -1, joined: null }); +const emptyPass: Pass = { leaves: noLeaves, runners: [], indexed: false, here: false, tabled: false, version: -1, joined: [] }; +const createPass = (leaves: readonly Leaf[]): Pass => ({ leaves, runners: [], indexed: false, here: false, tabled: false, version: -1, joined: null }); const passOf = (context: ExecuteContext, leaves: readonly Leaf[], added: boolean): Pass => { if (leaves.length === 0) return emptyPass; @@ -54,11 +101,13 @@ const passOf = (context: ExecuteContext, leaves: readonly Leaf[], added: boolean pass.leaves = leaves; pass.indexed = false; pass.here = false; + pass.tabled = false; pass.joined = null; for (let k = 0; k < leaves.length; k++) { const runner = runners[k] = context.runnerOf(leaves[k]); if (runner.indexes.length > 0) pass.indexed = true; if (runner.joined === null) pass.here = true; + if (runner.joined === null && runner.tables !== null) pass.tabled = true; } pass.version = runnersVersion; } @@ -93,12 +142,22 @@ const refreshAll = (context: ExecuteContext, own: Pass, added: Pass): Promise undefined); }; -const finishAfter = async (waiting: Promise, context: ExecuteContext, own: readonly Leaf[], added: readonly Leaf[], ownPass: Pass, addedPass: Pass, failures: Failure[] | null): Promise => { +const finishAfter = async (waiting: Promise, context: ExecuteContext, own: readonly Leaf[], added: readonly Leaf[], ownPass: Pass, addedPass: Pass, failures: Failure[] | null): Promise => { await waiting; return runAll(context, own, added, ownPass, addedPass, failures); }; const runAll = (context: ExecuteContext, own: readonly Leaf[], added: readonly Leaf[], ownPass: Pass, addedPass: Pass, failures: Failure[] | null): Failure[] | null => { + const { state } = context; + try { + return runEach(context, own, added, ownPass, addedPass, failures); + } + finally { + state.gathered = null; + } +}; + +const runEach = (context: ExecuteContext, own: readonly Leaf[], added: readonly Leaf[], ownPass: Pass, addedPass: Pass, failures: Failure[] | null): Failure[] | null => { const { state } = context; let failed = failures; if (state.indexFailures.length !== 0) (failed ??= []).push(...state.indexFailures.splice(0)); diff --git a/ecs/packages/ecs/src/implementation/world/register.ts b/ecs/packages/ecs/src/implementation/world/register.ts index 6349510a5..550517a1d 100644 --- a/ecs/packages/ecs/src/implementation/world/register.ts +++ b/ecs/packages/ecs/src/implementation/world/register.ts @@ -7,6 +7,7 @@ import { createRunner, releaseHoldings, removedRunner, stopHoldings, type Holdin import { isLeaf, reducedBy, scheduleOf, type Schedule } from '../../interface/registry/schedule.js'; import { idOf, observe, unobserve, type Key, type State } from './state.js'; import { orderKeysOf } from '../../interface/registry/index.js'; +import { declaredOf, declaresTrait } from '../../interface/registry/names.js'; import { entityWatchesOf, indexWatchesOf, lookupComponentsOf, orderComponentsOf } from './lookup-keys.js'; /** What a registration still has to do asynchronously: add resources, then load kernels; `rollback` undoes it if that fails. */ @@ -74,7 +75,12 @@ const keysOf = (leaf: Leaf): { readonly components: readonly Key[]; readonly res const { up } = leaf.declaration; if (up !== undefined) components.push(up.through, ...up.read ?? []); components.push(...orderComponentsOf(leaf.declaration)); - return { components, resources: [...resources?.read ?? [], ...resources?.write ?? [], ...resources?.changed ?? [], ...resources?.is ?? [], ...resources?.not ?? [], ...reducedBy(leaf)] }; + // Tables may read resources that don't place the system, as those of other threads, which aren't among its reads; + // and a trait filter watches the resources declaring its traits, which are in the world from then on, as read. + const tables = leaf.declaration.tables?.resources ?? []; + const { changed } = leaf.declaration; + const declaring = changed === undefined ? [] : [...declaredOf("resource").keys()].filter(key => declaresTrait(key, changed)); + return { components, resources: [...resources?.read ?? [], ...resources?.write ?? [], ...resources?.changed ?? [], ...resources?.is ?? [], ...resources?.not ?? [], ...reducedBy(leaf), ...tables, ...declaring] }; }; /** For a filtered `up` leaf: its parent reference and what it reads of its parent, whose changes also pass a row. */ diff --git a/ecs/packages/ecs/src/implementation/world/remote-systems.ts b/ecs/packages/ecs/src/implementation/world/remote-systems.ts index c04af06ce..f5e602ed7 100644 --- a/ecs/packages/ecs/src/implementation/world/remote-systems.ts +++ b/ecs/packages/ecs/src/implementation/world/remote-systems.ts @@ -611,6 +611,7 @@ export const createRemoteRunner = (state: State, leaf: Leaf, channel: TaskChanne holdings: { ...holdingNothing({ unplace: () => channel.unplace(index) }), indexes: lookups.holding }, remote, joined: null, + tables: null, lastRun: () => remote.lastRun, takeResult: () => { const { value } = remote.result; diff --git a/ecs/packages/ecs/src/implementation/world/remote.test.ts b/ecs/packages/ecs/src/implementation/world/remote.test.ts index f78894cba..823efea68 100644 --- a/ecs/packages/ecs/src/implementation/world/remote.test.ts +++ b/ecs/packages/ecs/src/implementation/world/remote.test.ts @@ -17,6 +17,9 @@ const widget = Symbol("remoteTest/widget"); const kept = Symbol("remoteTest/kept"); const guarded = Symbol("remoteTest/guarded"); const handle = Symbol("remoteTest/handle"); +const filter = Symbol("remoteTest/filter"); +const owner = Symbol("remoteTest/owner"); +const painter = Symbol("remoteTest/painter"); declare module "@adobe/ecs" { export interface Threads { remoteTest: true; @@ -30,6 +33,11 @@ declare module "@adobe/ecs" { [guarded]: { type: Widget | null; thread: "remoteTestRemoved" }; [handle]: { type: Widget | number | null; thread: "remoteTest" }; } + export interface Resources { + [filter]: { type: { readonly text: string; readonly owner: Entity } | null; thread: "remoteTest"; default: null }; + [owner]: { type: Entity }; + [painter]: { type: Widget | null; thread: "remoteTest"; default: null }; + } } /** A value that isn't data. */ type Widget = { readonly draw: () => string }; @@ -55,6 +63,9 @@ const dropCaptions = System.create({ components: { with: [caption] } }, (row, { const giveCaption = System.create({ components: { with: [point] } }, (row, { commands }) => { commands.add(row.entity, caption, { text: "a caption only the thread gives" }); }); +const giveWidget = System.create({ components: { with: [point] } }, (row, { commands }) => { + commands.add(row.entity, widget, { draw: () => "drawn" }); +}); const spawnCaptioned = System.create({}, ({ commands }) => { commands.spawn([point, caption])({ [point]: 1, [caption]: { text: "a caption only the thread gives" } }); }); @@ -74,6 +85,17 @@ const after = System.create({}, () => {}); /** Declared without a binding, so the build gives it no id. */ const [guard] = [System.removed({ components: { with: [guarded] } }, row => { void row[guarded]; })]; +const spawnTablesGiven: { resources: { readonly [key: symbol]: unknown } } = { resources: {} }; +const setResources = System.create(({ commands }) => { commands.spawnTables([], { resources: spawnTablesGiven.resources }); }); +/** Spawns one entity by a table, setting resources naming it. */ +const spawnNamed = System.create(({ commands }) => { + const { entities } = commands.spawnTables([{ count: 1, entities: new Float64Array([7]), columns: { [point]: { kind: "bytes", bytes: new Uint8Array(new Float64Array([9]).buffer), stride: 8 } } }], { resources: spawnTablesGiven.resources }); + return entities[0][0]; +}); + +const captionTables = System.create({ readonly: true, tables: { components: [caption, point], resources: [filter] } }, ({ tables }) => tables); +const widgetTables = System.create({ readonly: true, tables: { components: [widget] } }, ({ tables }) => tables); + /** A world shared with a thread on this one, which claims `threads`. */ const joined = async (): Promise<{ readonly world: CreatedWorld; readonly remote: World }> => { const world = createWorld({ [workers]: 0 }); @@ -108,16 +130,58 @@ const spawnOne = async (world: World, x: number): Promise => { describe("objects a joined thread fills", () => { // The cases of observers reading them are in `observe-joined-cases.test.ts`. - it("take from the world's thread only their start or null, in commands and spawns", async () => { + it("take data from the world's thread's commands and spawns, delivered at the sync point, and values that aren't only their start or null", async () => { + const { world, remote } = await joined(); + const entity = await spawnOne(world, 2); + expect((await runReported(world, giveCaption)).failures).toEqual([]); + const listed = Observe.entity(remote, entity, { required: [caption] }); + expect(await until(listed, value => value?.[caption]?.text === "a caption only the thread gives")).toEqual({ [caption]: { text: "a caption only the thread gives" } }); + expect((await runReported(world, spawnCaptioned)).failures).toEqual([]); + expect(await Observe.toPromise(Observe.count(world, { required: [caption] }))).toBe(2); + const message = '"remoteTest/widget" lives on thread "remoteTest", which a joined thread fills, and isn\'t data, so a command here gives it only its start or null.'; + expect((await runReported(world, giveWidget)).failures.map(failure => failure.message)).toEqual([message]); + expect(await Observe.toPromise(Observe.entity(remote, entity, { required: [widget] }))).toEqual({ [widget]: null }); + await remote.dispose(); + await world.dispose(); + }); + it("take resources a joined thread fills from commands.spawnTables, delivered with their entities rewritten, and not those that aren't data", async () => { const { world, remote } = await joined(); - await spawnOne(world, 2); - const message = '"remoteTest/caption" lives on thread "remoteTest", which a joined thread fills, so a command here gives it only its start or null.'; - expect((await runReported(world, giveCaption)).failures.map(failure => failure.message)).toEqual([message]); - expect((await runReported(world, spawnCaptioned)).failures.map(failure => failure.message)).toEqual([message]); - expect(await Observe.toPromise(Observe.count(world, { required: [caption] }))).toBe(1); + spawnTablesGiven.resources = { [filter]: { text: "found", owner: 7 }, [owner]: 7 }; + const entity = await world.run(spawnNamed); + expect(entity).not.toBe(7); + expect(await until(Observe.resource(remote, filter), value => value !== null)).toEqual({ text: "found", owner: entity }); + expect(await Observe.toPromise(Observe.resource(world, owner))).toBe(entity); + spawnTablesGiven.resources = { [painter]: { draw: () => "drawn" } }; + await expect(world.run(setResources)).rejects.toThrow('commands.spawnTables: "remoteTest/painter" lives on thread "remoteTest", which a joined thread fills, and isn\'t data.'); await remote.dispose(); await world.dispose(); }); + it("give tables their values on the thread, gathered by entity, and fail those that aren't data", async () => { + const { world, remote } = await joined(); + const first = await spawnOne(world, 1); + const second = await spawnOne(world, 2); + await world.run(giveCaption); + spawnTablesGiven.resources = { [filter]: { text: "gathered", owner: 0 } }; + await world.run(setResources); + const { archetypes, resources } = await world.run(captionTables); + const byEntity = new Map(); + for (const table of archetypes) { + const column = table.columns[caption]; + table.entities.forEach((entity, row) => byEntity.set(entity, column?.kind === "values" ? column.values[row] : undefined)); + } + expect(byEntity.get(first)).toEqual({ text: "a caption only the thread gives" }); + expect(byEntity.get(second)).toEqual({ text: "a caption only the thread gives" }); + expect(resources[filter]).toEqual({ text: "gathered", owner: 0 }); + await expect(world.run(widgetTables)).rejects.toThrow(/Tables can't read "remoteTest\/widget": a joined thread fills its objects, and gave none: it isn't data, which a copy carries/); + await remote.dispose(); + await world.dispose(); + }); + it("take resources of another thread from commands.spawnTables while no joined thread fills it", async () => { + await using world = createWorld({ [workers]: 0 }); + spawnTablesGiven.resources = { [filter]: { text: "here", owner: 0 } }; + await world.run(setResources); + expect(await Observe.toPromise(Observe.resource(world, filter))).toEqual({ text: "here", owner: 0 }); + }); it("take from a kernel only their start or null, its command giving another dropping and its system failing", async () => { const { world, remote } = await joined(); const entity = await spawnOne(world, 6); @@ -126,7 +190,7 @@ describe("objects a joined thread fills", () => { expect((await runReported(world, nullCaptionsKernel)).failures).toEqual([]); expect(await until(listed, value => value?.[caption] === null)).toEqual({ [caption]: null, [widget]: null }); const report = await runReported(world, numberHandlesKernel); - expect(report.failures.map(failure => [failure.name, failure.message])).toEqual([["numberHandlesKernel", '"remoteTest/handle" lives on thread "remoteTest", which a joined thread fills, so a command here gives it only its start or null.']]); + expect(report.failures.map(failure => [failure.name, failure.message])).toEqual([["numberHandlesKernel", '"remoteTest/handle" lives on thread "remoteTest", which a joined thread fills, and isn\'t data, so a command here gives it only its start or null.']]); expect(report.dropped).toBe(1); await remote.dispose(); await world.dispose(); diff --git a/ecs/packages/ecs/src/implementation/world/remote.ts b/ecs/packages/ecs/src/implementation/world/remote.ts index 14293a992..579ea1db4 100644 --- a/ecs/packages/ecs/src/implementation/world/remote.ts +++ b/ecs/packages/ecs/src/implementation/world/remote.ts @@ -15,6 +15,18 @@ const threadOfComponent = (state: State, id: number): string | null => { return declaration === undefined ? null : threadOfDeclaration(declaration); }; +/** + * Whether the world's thread may give a joined thread's object `id` a value of its own, delivered there: one of a type + * with a schema, so data a message carries, and not declared `transfer`, which moves only through a run's input. + */ +export const isDelivered = (state: State, id: number): boolean => { + const declaration = declarationOf(state.keys[id]); + return declaration?.type !== undefined && declaration.transfer !== true; +}; + +/** What a batch's column of a joined thread's object refuses from the world's thread: null when its values are delivered. */ +export const batchRemote = (state: State, id: number): string | null => isDelivered(state, id) ? null : remoteError(state, id).message; + /** Gives a component a joined thread fills to its log, in every archetype and batch holding it. */ const give = (state: State, id: number, log: MoveLog): void => { state.remote[id] = log; @@ -23,7 +35,7 @@ const give = (state: State, id: number, log: MoveLog): void => { const storage = archetype.storageById[id]; if (storage !== undefined) makeRemote(state.memory, archetype, storage, log); } - for (const batch of state.batches) for (const column of batch.columns) if (column.id === id) column.remote = remoteError(state, id).message; + for (const batch of state.batches) for (const column of batch.columns) if (column.id === id) column.remote = batchRemote(state, id); log.announce(id); }; @@ -85,12 +97,15 @@ export const releaseThreads = (state: State, log: MoveLog): void => { }; export const remoteError = (state: State, id: number): Error => - new Error(`"${labelOf(state.keys[id])}" lives on thread "${threadOfComponent(state, id) ?? "world"}", which a joined thread fills, so a command here gives it only its start or null.`); + new Error(isDelivered(state, id) + ? `"${labelOf(state.keys[id])}" lives on thread "${threadOfComponent(state, id) ?? "world"}", which a joined thread fills, so a command on another joined thread gives it only its start or null.` + : `"${labelOf(state.keys[id])}" lives on thread "${threadOfComponent(state, id) ?? "world"}", which a joined thread fills, and isn't data, so a command here gives it only its start or null.`); /** * For a system's commands, once a joined thread fills objects: the first error of a value another thread's object can't * take, with each such command dropped, by naming no entity, and each such staged spawn's value its start. Commands of - * the joined thread whose log is `own` give its own objects slots it staged. + * the joined thread whose log is `own` give its own objects slots it staged; the world's thread's, `own` null, give + * data, which is delivered. */ export const checkCommands = (state: State, buffer: CommandBuffer, own: MoveLog | null = null): Error | undefined => { let error: Error | undefined; @@ -102,7 +117,7 @@ export const checkCommands = (state: State, buffer: CommandBuffer, own: MoveLog const log = state.remote[id]; if (log === undefined) continue; const tag = tagOf(values[k], state.starts[id]); - if (tag >= 0 && (tag <= nullTag || log === own)) continue; + if (tag >= 0 ? tag <= nullTag || log === own : own === null && isDelivered(state, id)) continue; error ??= remoteError(state, id); entities[command] = 0; break; @@ -116,7 +131,7 @@ export const checkCommands = (state: State, buffer: CommandBuffer, own: MoveLog const begin = state.starts[column.id]; for (let row = start; row < end; row++) { const tag = tagOf(column.values[row], begin); - if (tag >= 0 && (tag <= nullTag || log === own)) continue; + if (tag >= 0 ? tag <= nullTag || log === own : own === null && isDelivered(state, column.id)) continue; error ??= remoteError(state, column.id); column.values[row] = begin; } diff --git a/ecs/packages/ecs/src/implementation/world/runner.ts b/ecs/packages/ecs/src/implementation/world/runner.ts index 2405d24fc..09fa04f7d 100644 --- a/ecs/packages/ecs/src/implementation/world/runner.ts +++ b/ecs/packages/ecs/src/implementation/world/runner.ts @@ -1,6 +1,8 @@ // © 2026 Adobe. MIT License. See /LICENSE for details. +import type { TablesDeclaration } from '../../interface/system/tables.js'; import type { Leaf } from '../../interface/system/leaf.js'; import { stampChanged, type Archetype } from './archetype.js'; +import { traitChanges } from './trait-changes.js'; import { groupCovers, groupHeld, groupOnWorkers, groupScalars, joinGroup, runGroup, type FusedGroup, type FusionRole } from './fusion.js'; import { kernelOf } from './attach-kernel.js'; import { readCell } from './cells.js'; @@ -116,6 +118,8 @@ export type Runner = { readonly remote: RemoteSystem | null; /** For an observer system on a joined thread, which runs it there after sync points (`joined-observer.ts`); else null. */ readonly joined: JoinedObserver | null; + /** What a readonly system's `tables` reads, whose objects joined threads hold are gathered before it runs; else null. */ + readonly tables: TablesDeclaration | null; /** The tick it last ran at, which a runner placing it elsewhere starts from. */ readonly lastRun: () => number; /** @@ -236,7 +240,9 @@ export const createRunner = (state: State, leaf: Leaf, since = 0): Runner => { /** The indexes whose entries changing passes every row, as a changed resource does: its lookups' with `changed: true`. */ const indexFilters = indexLookups.filters; const indexFiltered = indexFilters.length > 0; - const filtered = addedIds.length + changedIds.length + resourceChanged.length + indexFilters.length > 0; + /** For a trait filter, whether something declaring its traits changed since a tick; else null. */ + const traitsChanged = declaration.changed === undefined || declaration.changed.length === 0 ? null : traitChanges(state, declaration.changed); + const filtered = addedIds.length + changedIds.length + resourceChanged.length + indexFilters.length > 0 || traitsChanged !== null; /** Its `lastRun` while it runs, which its lookups' lists and rows compare with. */ const lookupSince: Since = { value: since }; let kernel: BoundKernel | null = null; @@ -1277,7 +1283,7 @@ export const createRunner = (state: State, leaf: Leaf, since = 0): Runner => { chunks[0] = ownedChunks[0]; try { // With points, resource and index filters pass an archetype's rows by its own point. - const resourcesChanged = !pointed && (indexesChanged || (resourceChanged.length > 0 && resourcesChangedSince(lastRun))); + const resourcesChanged = !pointed && (indexesChanged || (resourceChanged.length > 0 && resourcesChangedSince(lastRun)) || (traitsChanged !== null && traitsChanged(lastRun))); /** -1 passes every row. */ const since = !filtered || resourcesChanged ? -1 : lastRun; ranSince = since; @@ -1452,6 +1458,7 @@ export const createRunner = (state: State, leaf: Leaf, since = 0): Runner => { holdings, remote: null, joined: null, + tables: declaration.tables ?? null, lastRun: () => lastRun, takeResult: () => { const taken = result; @@ -1490,6 +1497,7 @@ export const removedRunner: Runner = { holdings: { ...holdingNothing(), removed: true, released: true }, remote: null, joined: null, + tables: null, lastRun: () => 0, takeResult: () => undefined, didRun: () => false, diff --git a/ecs/packages/ecs/src/implementation/world/sharing.ts b/ecs/packages/ecs/src/implementation/world/sharing.ts index 4b858d7ce..301217ec0 100644 --- a/ecs/packages/ecs/src/implementation/world/sharing.ts +++ b/ecs/packages/ecs/src/implementation/world/sharing.ts @@ -15,7 +15,7 @@ import { import { createObserverTarget, droppedObserver, endTarget, joinedRun, ranThere, type ObserverTarget } from './joined-observer.js'; import type { Leaf } from '../../interface/system/leaf.js'; import { Index } from '../../interface/indexes/index-type.js'; -import { createMoveLog, freeMoveLog, type MoveLog } from './move-log.js'; +import { createMoveLog, freeMoveLog, type Gathered, type MoveLog } from './move-log.js'; import { lineWords } from './protocol.js'; import { claimThreads, releaseThreads } from './remote.js'; import { createTaskChannel, type TaskChannel } from './remote-systems.js'; @@ -95,6 +95,8 @@ type Joined = { readonly proxies: Map; /** Settles what `share` returned: once it has joined, or failed to; null once settled. */ settle: { readonly resolve: () => void; readonly reject: (error: Error) => void } | null; + /** Gathers asked of it and not yet answered, by their ids. */ + readonly gathers: Map void>; }; const hasWaitAsync = (): boolean => typeof Atomics.waitAsync === "function"; @@ -318,6 +320,38 @@ export const createSharing = (host: SharingHost) => { post(thread, { protocol: protocolName, kind: "component", component, id: typeof key === "symbol" ? idOfKey(key) ?? null : null }); }; + /** + * Posts a thread the values a sync gives its objects from the world's thread. One a message can't carry, which its + * type said it could, is posted as undefined, so the object takes its start. + */ + const deliver = (thread: Joined, sync: number, first: number, values: readonly unknown[]): void => { + try { + post(thread, { protocol: protocolName, kind: "values", sync, first, values }); + } + catch { + const carried = values.map(value => { + try { + return structuredClone(value); + } + catch { + return undefined; + } + }); + post(thread, { protocol: protocolName, kind: "values", sync, first, values: carried }); + } + }; + + let gathers = 0; + /** Asks a thread for the values it holds of its objects, answered once it replayed the last published sync. */ + const gather = (thread: Joined, components: readonly number[], resources: readonly number[]): Promise => { + if (thread.status === "gone") return Promise.resolve({ error: "the thread is gone" }); + const id = ++gathers; + return new Promise(resolve => { + thread.gathers.set(id, resolve); + post(thread, { protocol: protocolName, kind: "gather", id, components, resources }); + }); + }; + /** * Its claims checked against those already made, and against systems and sync systems on them; its control words * placed, and its status `"joined"`; or refused. With claims, its objects become its own between runs, then it's @@ -379,7 +413,7 @@ export const createSharing = (host: SharingHost) => { // Systems registered since it asked to join are checked too. const crossing = host.crossing(threads, thread.imported); if (crossing !== null) return refuse(thread, crossing); - const log = createMoveLog(memory, thread.number, state.starts, component => announce(thread, component)); + const log = createMoveLog(memory, thread.number, state.starts, component => announce(thread, component), (sync, first, values) => deliver(thread, sync, first, values), (components, resources) => gather(thread, components, resources)); thread.log = log; claimThreads(state, log, threads); const tasks = createTaskChannel(state, log, message => post(thread, message), () => wake(thread), threads.join(`" and "`), number => { @@ -418,6 +452,8 @@ export const createSharing = (host: SharingHost) => { if (thread.status === "gone") return; const { control, log, tasks } = thread; thread.status = "gone"; + for (const answer of thread.gathers.values()) answer({ error: `the thread is gone` }); + thread.gathers.clear(); thread.settle?.reject(new Error(closed ? "The world is disposed." : "The thread was gone before it joined.")); thread.settle = null; threads.delete(thread); @@ -510,6 +546,11 @@ export const createSharing = (host: SharingHost) => { } return; } + case "gathered": { + const answer = thread.gathers.get(message.id); + thread.gathers.delete(message.id); + return answer?.(message); + } case "observer ran": { for (const [index, value, error] of message.results) { const placed = thread.observer?.placed[index]; @@ -540,7 +581,7 @@ export const createSharing = (host: SharingHost) => { const thread: Joined = { channel: threadChannel(port), status: "joining", claims: [], control: null, views: [], waits: true, names: new Map(), next: 1, completed: 0, finished: new Set(), inputs: new Map(), moved: new Map(), peers: new Set(), woken: false, - abort: new AbortController(), log: null, number: ++numbered, imported: new Set(), tasks: null, observer: null, proxies: new Map(), + abort: new AbortController(), log: null, number: ++numbered, imported: new Set(), tasks: null, observer: null, proxies: new Map(), gathers: new Map(), settle, }; threads.add(thread); diff --git a/ecs/packages/ecs/src/implementation/world/state.ts b/ecs/packages/ecs/src/implementation/world/state.ts index bf3733460..883760697 100644 --- a/ecs/packages/ecs/src/implementation/world/state.ts +++ b/ecs/packages/ecs/src/implementation/world/state.ts @@ -300,6 +300,11 @@ export type State = { readonly claims: Map; readonly logs: MoveLog[]; claimed: boolean; + /** + * While readonly systems run after a sync point, what joined threads hold of the objects their tables read: each + * component's values by entity, and each resource's value, by id. + */ + gathered: { readonly components: Map>; readonly resources: Map; readonly errors: Map } | null; /** The system without components whose body's value the run in progress resolves to; null for none, as in a tick. */ wanted: Leaf | null; /** While a sync system's failure is reported out of band, the sync systems each sync point ran, which then recover. */ @@ -433,6 +438,7 @@ export const createState = (shared?: boolean, wasm = true, simd = true, gpu = fa claims: new Map(), logs: [], claimed: false, + gathered: null, wanted: null, syncSystemsRan: null, ran: { systems: 0, main: false, gpu: false, joined: new Set() }, diff --git a/ecs/packages/ecs/src/implementation/world/synchronize.ts b/ecs/packages/ecs/src/implementation/world/synchronize.ts index 434064e53..1a95ae993 100644 --- a/ecs/packages/ecs/src/implementation/world/synchronize.ts +++ b/ecs/packages/ecs/src/implementation/world/synchronize.ts @@ -12,7 +12,7 @@ import { refreshDirectories } from './directories.js'; import { createArrivals, logArrival } from './arrivals.js'; import { noteEdge, noteEmptied, noteResourceLeft, reclaimEmptied } from './reclaim.js'; import { beginStructure, countChanged, endStructure, flushDirectory } from './layout-directory.js'; -import { beginLog, logAppend, logMove, logSet, logSwap, publishLog, startTag, tagOf } from './move-log.js'; +import { beginLog, deliveredTag, logAppend, logMove, logSet, logSwap, publishLog, startTag, tagOf } from './move-log.js'; import { record } from './journal.js'; import { indexOf, kill, locate, materialize, recycle, release, reserved, unreserve, type Reserved } from './entities.js'; import { activate } from './activate.js'; @@ -715,7 +715,8 @@ const copyBytes = (storage: Storage, row: number, bytes: Views, offset: number): /** A joined thread's object: its tag here, its value given there. */ const writeRemote = (storage: Storage, log: MoveLog, value: unknown, to: Archetype, toRow: number, from: Archetype | null, fresh: readonly number[] | undefined): void => { const id = storage.component; - const tag = tagOf(value, log.starts[id]); + const given = tagOf(value, log.starts[id]); + const tag = given >= 0 ? given : deliveredTag(log, value); storage.tags[toRow] = tag; logSet(log, to.id, toRow, id, tag, from === null || from.storageById[id] === undefined || (fresh !== undefined && fresh.includes(id))); }; diff --git a/ecs/packages/ecs/src/implementation/world/tables-read.ts b/ecs/packages/ecs/src/implementation/world/tables-read.ts index 025a0bdaf..5f76dc23a 100644 --- a/ecs/packages/ecs/src/implementation/world/tables-read.ts +++ b/ecs/packages/ecs/src/implementation/world/tables-read.ts @@ -10,15 +10,19 @@ import { holdsValuesOf } from './where.js'; // Reading tables, apart from spawning them: rows' contexts import it, and what spawning imports would make a cycle. +/** Why a table can't read a joined thread's object `id`: it gave no values, or said why. */ +const ungathered = (state: State, key: Key, id: number): Error => + new Error(`Tables can't read "${labelOf(key)}": a joined thread fills its objects${state.gathered?.errors.has(id) === true ? `, and gave none: ${state.gathered.errors.get(id)}` : ", and gave none"}.`); + /** What an archetype's storage of a component gives a table: a copy of its rows `0` to `count`. */ -const columnOf = (key: Key, storage: Storage, count: number): Table.Column => { +const columnOf = (state: State, key: Key, id: number, archetype: Archetype, storage: Storage, count: number): Table.Column => { const { layout } = storage; switch (layout.kind) { case "linear": return { kind: "bytes", bytes: storage.views.u8.slice(0, count * layout.stride), stride: layout.stride }; case "constant": return { kind: "value", value: layout.value }; case "object": - if (storage.remote !== null) throw new Error(`Tables can't read "${labelOf(key)}": a joined thread fills its objects.`); - return { kind: "values", values: storage.values.slice(0, count) }; + if (storage.remote === null) return { kind: "values", values: storage.values.slice(0, count) }; + return { kind: "values", values: gatheredColumn(state, key, id, archetype.entities, count) }; case "string": { const values: unknown[] = new Array(count); for (let row = 0; row < count; row++) values[row] = readCell(storage, row); @@ -27,6 +31,16 @@ const columnOf = (key: Key, storage: Storage, count: number): Table.Column => { } }; +/** A joined thread's values of its object `id` for each of `entities`, as it gave them; its start for one it didn't. */ +const gatheredColumn = (state: State, key: Key, id: number, entities: Float64Array, count: number): unknown[] => { + const byEntity = state.gathered?.components.get(id); + if (byEntity === undefined) throw ungathered(state, key, id); + const start = state.starts[id]; + const values: unknown[] = new Array(count); + for (let row = 0; row < count; row++) values[row] = byEntity.has(entities[row]) ? byEntity.get(entities[row]) : start; + return values; +}; + /** * A readonly system's `tables`, read by the function this returns, once per read: of each archetype matching `with`, * `not` and `where` and holding any of `components`, its entities and a copy of the column of each of them it holds; @@ -56,7 +70,7 @@ const readTables = (state: State, declaration: TablesDeclaration, requiring: rea for (const { key, id } of asked) { const storage = storageById[id]; if (storage === undefined) continue; - columns[key] = columnOf(key, storage, count); + columns[key] = columnOf(state, key, id, archetype, storage, count); held = true; } if (held) archetypes.push({ count, entities: archetype.entities.slice(0, count), columns }); @@ -64,7 +78,10 @@ const readTables = (state: State, declaration: TablesDeclaration, requiring: rea const resources: { [key: symbol]: unknown } = {}; for (const key of declaration.resources ?? []) { const cell = resourceCell(state, key); - resources[key] = readCell(cell.storage, cell.row); + const id = cell.storage.component; + if (cell.storage.remote === null) resources[key] = readCell(cell.storage, cell.row); + else if (state.gathered?.resources.has(id) === true) resources[key] = state.gathered.resources.get(id); + else throw ungathered(state, key, id); } return { archetypes, resources }; }; diff --git a/ecs/packages/ecs/src/implementation/world/tables.test.ts b/ecs/packages/ecs/src/implementation/world/tables.test.ts index 096db2c62..732dc3d83 100644 --- a/ecs/packages/ecs/src/implementation/world/tables.test.ts +++ b/ecs/packages/ecs/src/implementation/world/tables.test.ts @@ -19,6 +19,7 @@ const hidden = Symbol("tablesTest/hidden"); const buddy = Symbol("tablesTest/buddy"); const score = Symbol("tablesTest/score"); const title = Symbol("tablesTest/title"); +const focus = Symbol("tablesTest/focus"); declare module "@adobe/ecs" { interface Components { [position]: { type: Vec3 }; @@ -36,6 +37,7 @@ declare module "@adobe/ecs" { interface Resources { [score]: { type: number; default: 0 }; [title]: { type: string; default: "" }; + [focus]: { type: Entity }; } } @@ -64,6 +66,13 @@ const spawnTables = async (world: ReturnType, tables: readonly Ta return spawnedBy.spawned; }; +/** The rows of a table of labels whose entity `keep` takes. */ +const rowsWhere = (table: Table, keep: (entity: number) => boolean): Table => { + const rows = Array.from({ length: table.count }, (_, row) => row).filter(row => keep(table.entities[row])); + const column = table.columns[label]; + return { count: rows.length, entities: Float64Array.from(rows, row => table.entities[row]), columns: { [label]: { kind: "values", values: rows.map(row => column?.kind === "values" ? column.values[row] : undefined) } } }; +}; + /** Spawns `labels` in `world`, giving each label's entity. */ const spawnLabels = async (world: ReturnType, labels: readonly string[]): Promise> => { const made = new Map(); @@ -308,6 +317,25 @@ describe("tables", () => { expect(resources[title]).toBe("loaded"); }); + it("rewrite the entities in the resources they set as they rewrite their rows: each naming the one spawned for it, any other none", async () => { + await using from = inline(); + const made = await spawnLabels(from, ["kept", "outside"]); + const { archetypes } = await from.run(tablesOf([label])); + const kept = made.get("kept") ?? Entity.none; + const tables = archetypes.map(table => rowsWhere(table, entity => entity === kept)); + await using into = inline(); + await spawnLabels(into, ["first", "second", "third"]); + for (const [named, expected] of [[kept, "kept"], [made.get("outside") ?? Entity.none, null]] as const) { + given.resources = { [focus]: named }; + const spawned = await spawnTables(into, tables); + given.resources = undefined; + const { resources } = await into.run(tablesOf([label], [focus])); + if (expected === null) expect(resources[focus]).toBe(Entity.none); + else expect(resources[focus]).toBe(spawned.entities[0][0]); + expect(resources[focus]).not.toBe(named); + } + }); + it("refuse a resource only the world writes or a value its type doesn't take, spawning nothing", async () => { await using world = inline(); const table: Table = { count: 1, entities: new Float64Array([1]), columns: { [label]: { kind: "values", values: ["kept out"] } } }; diff --git a/ecs/packages/ecs/src/implementation/world/tables.ts b/ecs/packages/ecs/src/implementation/world/tables.ts index be84ef4b2..3c30fd1da 100644 --- a/ecs/packages/ecs/src/implementation/world/tables.ts +++ b/ecs/packages/ecs/src/implementation/world/tables.ts @@ -256,21 +256,42 @@ const checkExisting = (state: State, existing: ReadonlyMap): voi } }; +/** `resources`' values, each entity in them replaced by `remap`'s: the object given when none may hold one. */ +const remapResources = (resources: object, remap: Remap | null): object => { + const keys = Object.getOwnPropertySymbols(resources); + if (remap === null || !keys.some(key => holdsEntityOf(key))) return resources; + const remapped: { [key: symbol]: unknown } = {}; + for (const key of keys) { + const schema = declarationOf(key)?.type; + const value: unknown = Reflect.get(resources, key); + remapped[key] = schema !== undefined && holdsEntity(schema) ? remapValue(schema, value, remap) : value; + } + return remapped; +}; + +/** Whether a key's values may hold an entity. */ +const holdsEntityOf = (key: Key): boolean => { + const schema = declarationOf(key)?.type; + return schema !== undefined && holdsEntity(schema); +}; + /** * Spawns an entity for each row of `tables` into the batches of their components, as references would leave them had * the entities outside the tables despawned: a row owned, directly or through others, by an entity outside them isn't * spawned; a weak reference to one is removed; and any other entity value naming one is `Entity.none`. Every entity * value naming an entity spawned names the one spawned for it. A row whose entity `existing` maps isn't spawned: the - * entity it maps to stands for it, as it does for an entity outside the tables that `existing` maps. + * entity it maps to stands for it, as it does for an entity outside the tables that `existing` maps. `resources`, their + * entity values rewritten the same way, go to `set`. */ -export const spawnTables = (state: State, tables: readonly Table[], existing: ReadonlyMap = new Map(), updates: CommandBuffer | null = null): Table.Spawned => { +export const spawnTables = ( + state: State, tables: readonly Table[], existing: ReadonlyMap = new Map(), updates: CommandBuffer | null = null, + resources: object | null = null, set: (resources: object) => void = () => {}, +): Table.Spawned => { const plans = tables.map(table => planOf(state, table)); checkExisting(state, existing); - // Entities are mapped only where a value of the tables may hold one, or a row is one that exists. - const remapping = existing.size > 0 || plans.some(({ keys }) => keys.some(key => { - const schema = declarationOf(key)?.type; - return schema !== undefined && holdsEntity(schema); - })); + // Entities are mapped only where a value of the tables or resources may hold one, or a row is one that exists. + const remapping = existing.size > 0 || plans.some(({ keys }) => keys.some(holdsEntityOf)) + || (resources !== null && Object.getOwnPropertySymbols(resources).some(holdsEntityOf)); const none: ReadonlySet = new Set(); if (!remapping) { const entities = plans.map(({ table }) => { @@ -279,6 +300,7 @@ export const spawnTables = (state: State, tables: readonly Table[], existing: Re return spawned; }); plans.forEach((plan, t) => spawnRows(state, plan, null, none, entities[t], null)); + if (resources !== null) set(resources); return { entities, dropped: 0 }; } const places = placesOf(plans); @@ -409,5 +431,6 @@ export const spawnTables = (state: State, tables: readonly Table[], existing: Re } for (const { removed, rows } of groups.values()) spawnRows(state, plan, rows, removed, Float64Array.from(rows, row => entities[t][row]), remap); }); + if (resources !== null) set(remapResources(resources, remap)); return { entities, dropped: droppedCount }; }; diff --git a/ecs/packages/ecs/src/implementation/world/thread-removed-systems.ts b/ecs/packages/ecs/src/implementation/world/thread-removed-systems.ts index 13a3991c7..5b65b5129 100644 --- a/ecs/packages/ecs/src/implementation/world/thread-removed-systems.ts +++ b/ecs/packages/ecs/src/implementation/world/thread-removed-systems.ts @@ -5,8 +5,8 @@ import { objectLayout, viewsOf, type Layout } from '../../interface/registry/lay import { writeOf } from './archetype.js'; import { emptyViews } from './arrays.js'; import { readCell } from './cells.js'; -import { logRanThroughWord, logStopsWord, nullTag, ownTag, slotTags, startTag } from './move-log.js'; -import { resourceValueOf, stagedValue, type Mirror, type Previously } from './mirror.js'; +import { deliveredTags, logRanThroughWord, logStopsWord, nullTag, ownTag, slotTags, startTag } from './move-log.js'; +import { deliveredValue, resourceValueOf, stagedValue, type Mirror, type Previously } from './mirror.js'; import type { WorkerError } from './protocol.js'; import { rowBinderOf, type Row, type RowArchetype, type RowHost, type RowStorage } from './rows.js'; import { @@ -249,7 +249,8 @@ export const createThreadRemovedSystems = (host: Thread return column === undefined ? start : column.values[row]; } const previous = old(entity, component, start); - return tag === ownTag ? previous : stagedValue(mirror, (tag - slotTags) >>> 0, previous); + if (tag === ownTag) return previous; + return tag >= deliveredTags ? deliveredValue(mirror, tag, previous) : stagedValue(mirror, (tag - slotTags) >>> 0, previous); }; /** Whether every removed system a block names was set up here, as null for one this thread never imported. */ diff --git a/ecs/packages/ecs/src/implementation/world/trait-changes.test.ts b/ecs/packages/ecs/src/implementation/world/trait-changes.test.ts new file mode 100644 index 000000000..a7f1c186a --- /dev/null +++ b/ecs/packages/ecs/src/implementation/world/trait-changes.test.ts @@ -0,0 +1,95 @@ +// © 2026 Adobe. MIT License. See /LICENSE for details. +import { describe, expect, it } from "vitest"; +import { Entity } from "../../index.js"; +import { workers } from "../../interface/resources/workers.js"; +import { System } from "../../interface/system/system.js"; +import { createWorld, join } from "./create.js"; + +// Readonly systems filtering on a trait's changes: run once something declaring it changed, on any thread. + +const saved = Symbol("traitChangesTest/saved"); +const size = Symbol("traitChangesTest/size"); +const tint = Symbol("traitChangesTest/tint"); +const other = Symbol("traitChangesTest/other"); +const title = Symbol("traitChangesTest/title"); +const view = Symbol("traitChangesTest/view"); +declare module "@adobe/ecs" { + export interface Threads { + traitChangesTest: true; + } + export interface Traits { + readonly [saved]: N extends unknown ? true : never; + } + export interface Components { + [size]: { type: number; [saved]: true }; + [tint]: { type: number; [saved]: true }; + [other]: { type: number }; + } + export interface Resources { + [title]: { type: string; default: ""; [saved]: true }; + [view]: { type: { readonly zoom: number } | null; default: null; thread: "traitChangesTest"; [saved]: true }; + } +} + +const ran = { count: 0 }; +const notice = System.create({ readonly: true, changed: [saved] }, () => { ran.count++; }); + +const input: { entity: Entity } = { entity: Entity.none }; +const spawnSized = System.create(({ commands }) => { input.entity = commands.spawn([size, other])({ [size]: 1, [other]: 1 }); }); +const writeOther = System.create({ components: { with: [other] } }, row => { row[other] = row[other] + 1; }); +const writeSize = System.create({ components: { with: [size] } }, row => { row[size] = row[size] + 1; }); +const addTint = System.create(({ commands }) => { commands.add(input.entity, tint, 3); }); +const removeTint = System.create(({ commands }) => { commands.remove(input.entity, tint); }); +const despawn = System.create(({ commands }) => { commands.despawn(input.entity); }); +const retitle = System.create({}, ({ resources }) => { resources[title] = `${resources[title]}!`; }); +const setView = System.create(({ commands }) => { commands.spawnTables([], { resources: { [view]: { zoom: 2 } } }); }); +const idle = System.create({}, () => {}); +/** Writes only its own thread's object, so it runs there as a tail, after the sync point. */ +const zoomIn = System.create({}, ({ resources }) => { resources[view] = { zoom: (resources[view]?.zoom ?? 1) * 2 }; }); + +/** How many times the notice ran over a run of `system`. */ +const runsOver = async (world: { run: (system: System) => Promise }, system: System): Promise => { + const before = ran.count; + await world.run(system); + return ran.count - before; +}; + +describe("a readonly system filtering on a trait's changes", () => { + it("runs once a component or resource declaring the trait was written, added, removed, spawned or despawned", async () => { + await using world = createWorld({ [workers]: 0 }); + world.add(notice); + await world.run(spawnSized); + await world.run(idle); + expect(await runsOver(world, idle)).toBe(0); + expect(await runsOver(world, writeOther)).toBe(0); + expect(await runsOver(world, writeSize)).toBe(1); + expect(await runsOver(world, addTint)).toBe(1); + expect(await runsOver(world, idle)).toBe(0); + expect(await runsOver(world, removeTint)).toBe(1); + expect(await runsOver(world, retitle)).toBe(1); + expect(await runsOver(world, despawn)).toBe(1); + expect(await runsOver(world, idle)).toBe(0); + }); + it("runs once a resource declaring the trait that a joined thread fills was given a value", async () => { + await using world = createWorld({ [workers]: 0 }); + const channel = new MessageChannel(); + const shared = world.share(channel.port1); + const remote = await join(channel.port2, { threads: ["traitChangesTest"] }); + await shared; + world.add(notice); + await world.run(idle); + expect(await runsOver(world, idle)).toBe(0); + expect(await runsOver(world, setView)).toBe(1); + expect(await runsOver(world, idle)).toBe(0); + // Written there by a tail, which ends after the run's readonly systems ran: a later run sees it. + expect(await runsOver(world, zoomIn) + await runsOver(world, idle)).toBe(1); + expect(await runsOver(world, idle)).toBe(0); + // A joined thread's own runs where it is, which can't see a trait's keys on other threads. + await expect(remote.run(notice)).rejects.toThrow('Observer system "notice" filters on traits\' changes, so it runs only on the world\'s thread.'); + await remote.dispose(); + }); + it("is refused naming what isn't a trait", () => { + // @ts-expect-error a key isn't a trait + expect(() => System.create({ readonly: true, changed: [size] }, () => {})).toThrow(/"traitChangesTest\/size", which isn't a registered trait/); + }); +}); diff --git a/ecs/packages/ecs/src/implementation/world/trait-changes.ts b/ecs/packages/ecs/src/implementation/world/trait-changes.ts new file mode 100644 index 000000000..33bb00ec6 --- /dev/null +++ b/ecs/packages/ecs/src/implementation/world/trait-changes.ts @@ -0,0 +1,69 @@ +// © 2026 Adobe. MIT License. See /LICENSE for details. +import { declaresTrait } from '../../interface/registry/names.js'; +import { indexOf } from './entities.js'; +import { chunkShift } from './kernel.js'; +import type { State } from './state.js'; + +/** + * Whether a component or resource declaring one of `traits` changed since a tick, on any thread: written, by its + * stamps, which joined threads' systems write in shared memory too; added, by its added stamps; or gone from an entity, + * by fewer rows holding it than when it was last asked. The world's keys declaring them are found as it meets them, and + * their ticks start, with kernels' stamps, at the next run. + */ +export const traitChanges = (state: State, traits: readonly symbol[]): ((since: number) => boolean) => { + const ids: number[] = []; + /** By id among `ids`, the rows holding it when last asked, -1 before. */ + const counts: number[] = []; + let tested = 0; + const follow = (): void => { + for (const { keys } = state; tested < keys.length; tested++) { + if (!declaresTrait(keys[tested], traits)) continue; + ids.push(tested); + counts.push(-1); + if (!state.observed.has(tested)) state.watchesPending.push(tested); + } + }; + const resourceChanged = (id: number, since: number): boolean => { + if (state.resourceEntity < 0) return false; + const index = indexOf(state.resourceEntity); + const storage = state.archetypes[state.entities.archetype[index]]?.storageById[id]; + return storage !== undefined && storage.ticked && storage.changed[state.entities.row[index]] > since; + }; + /** Whether a storage's rows were stamped added or changed after `since`. */ + const stamped = (id: number, since: number): { changed: boolean; rows: number } => { + let rows = 0; + let changed = false; + const { archetypes } = state; + for (let k = 0; k < archetypes.length; k++) { + const archetype = archetypes[k]; + const storage = archetype.storageById[id]; + if (storage === undefined || archetype.resource || archetype.count === 0) continue; + rows += archetype.count; + if (changed || !storage.ticked) continue; + if (storage.columnChanged > since) { + changed = true; + continue; + } + const { chunkAdded, chunkChanged } = storage; + for (let chunk = 0, last = (archetype.count - 1) >> chunkShift; chunk <= last && !changed; chunk++) { + if (chunkChanged[chunk] > since || chunkAdded[chunk] > since) changed = true; + } + } + return { changed, rows }; + }; + return since => { + follow(); + let changed = false; + for (let k = 0; k < ids.length; k++) { + const id = ids[k]; + if (state.resources.has(id)) { + if (!changed && resourceChanged(id, since)) changed = true; + continue; + } + const found = stamped(id, since); + if (found.changed || found.rows !== counts[k]) changed = true; + counts[k] = found.rows; + } + return changed; + }; +}; diff --git a/ecs/packages/ecs/src/interface/system/check.ts b/ecs/packages/ecs/src/interface/system/check.ts index 538829811..cebdb59f8 100644 --- a/ecs/packages/ecs/src/interface/system/check.ts +++ b/ecs/packages/ecs/src/interface/system/check.ts @@ -191,6 +191,16 @@ const checkTables = (leaf: Leaf): void => { if (tables.where !== undefined) checkWhereValues(`System "${name}"`, "tables' where", "tables", tables.where, false); }; +/** Throws for `changed` on a system that isn't readonly or has components, or naming what isn't a registered trait. */ +const checkTraitFilter = (leaf: Leaf): void => { + const { name, declaration } = leaf; + const { changed } = declaration; + if (changed === undefined) return; + if (declaration.readonly !== true) throw new Error(`System "${name}" filters on traits' changes, which only a readonly system does.`); + if (declaration.components !== undefined) throw new Error(`System "${name}" filters on traits' changes, so it has no components.`); + for (const key of changed) if (kindOf(key) !== "trait") throw new Error(`System "${name}" filters on the changes of "${labelOf(key)}", which isn't a registered trait: ${whyUnregistered(key)}.`); +}; + /** * Throws for a leaf that names a component or resource that isn't registered as one, lists a key in both `read` and * `write`, writes a reference, has a lookup reading a component it writes, uses object components and resources of different threads, declares what a readonly system can't, or whose @@ -218,6 +228,7 @@ export const checkLeaf = (leaf: Leaf): void => { } checkTarget(leaf); checkTables(leaf); + checkTraitFilter(leaf); threadOf(declaration, "System", name); requireRegistered("System", name, "component", components?.has); requireRegistered("System", name, "component", components?.not); diff --git a/ecs/packages/ecs/src/interface/system/commands.ts b/ecs/packages/ecs/src/interface/system/commands.ts index dee2fca73..4caff1f66 100644 --- a/ecs/packages/ecs/src/interface/system/commands.ts +++ b/ecs/packages/ecs/src/interface/system/commands.ts @@ -101,7 +101,8 @@ export type Commands = { * other components as they are. Its entity values are rewritten as a spawned row's are, but a reference naming an * entity that isn't there, weak or owner, is left out, so the entity's own stands. * - `resources` sets each resource it names, by key, at the sync point, as commands apply, each value checked - * against its resource's schema; not one only the world writes, nor one living on another thread. + * against its resource's schema, its entity values rewritten as the rows' are; one a joined thread fills is + * copied there. Not one only the world writes, nor one a joined thread fills that isn't data. */ spawnTables(tables: readonly Table[], options?: { readonly resources?: { readonly [key: symbol]: unknown }; diff --git a/ecs/packages/ecs/src/interface/system/create.ts b/ecs/packages/ecs/src/interface/system/create.ts index 1db78c93b..ed29e5c1b 100644 --- a/ecs/packages/ecs/src/interface/system/create.ts +++ b/ecs/packages/ecs/src/interface/system/create.ts @@ -4,6 +4,8 @@ import type { Index } from '../indexes/index-type.js'; import type { Condition } from '../resource/condition.js'; import { takeIdOfDeclaration } from '../registry/ids.js'; import { nameOf } from '../registry/items.js'; +import { threadOfDeclaration } from '../registry/declarations.js'; +import { declarationOf } from '../registry/names.js'; import { claimSystem } from '../registry/program.js'; import type { Body, Context } from './body.js'; import { checkComposite, checkLeaf, inputSchemaOf } from './check.js'; @@ -106,6 +108,11 @@ type Validate = ? (D extends { readonly readonly: true } ? {} : { readonly tables?: { readonly "error: tables are read by a readonly system": true } }) & (Property extends undefined ? {} : { readonly tables?: { readonly "error: a system reading tables has no components": true } }) : {}) + // A trait filter runs a readonly system without components once. + & (D extends { readonly changed: object } + ? (D extends { readonly readonly: true } ? {} : { readonly changed?: { readonly "error: a trait filter is a readonly system's": true } }) + & (Property extends undefined ? {} : { readonly changed?: { readonly "error: a system filtering on traits has no components": true } }) + : {}) & (D extends { readonly target: string } ? Targeted : {}) & (D extends { readonly target: string } ? Property extends undefined ? { readonly target?: { readonly "error: a system on one entity runs on its row, so it needs components": true } } : {} : {}) & (D extends { readonly before: object } | { readonly after: object } | { readonly during: object } ? Ordered : {}) @@ -208,8 +215,14 @@ const resolve = (what: string, declared: Declaration, access: ReturnType { + const found = declarationOf(key); + const thread = found === undefined ? null : threadOfDeclaration(found); + return thread === null || thread === "world"; + }); + for (const key of [...whereReads, ...tableReads]) if (!uses.read.includes(key) && !uses.write.includes(key) && !conditions.includes(key)) uses.read.push(key); const resolved: Resolved = { ...rest, ...components === undefined ? {} : { components: componentLists(components, components.whole === true ? null : access.components, reading, whereReads) }, diff --git a/ecs/packages/ecs/src/interface/system/declaration.ts b/ecs/packages/ecs/src/interface/system/declaration.ts index 94c22ae7f..1b7a1fc8f 100644 --- a/ecs/packages/ecs/src/interface/system/declaration.ts +++ b/ecs/packages/ecs/src/interface/system/declaration.ts @@ -5,6 +5,7 @@ import type { ComponentAccess, ComponentLists, ResourceAccess, ResourceLists, Sy import type { Shader } from './render.js'; import type { System } from './system.js'; import type { TablesDeclaration } from './tables.js'; +import type { OwnTrait } from './sync-system-declaration.js'; /** * A system never declares its thread: it runs on the one its object components and resources live on, those it @@ -73,9 +74,17 @@ export type Declaration = { readonly readonly?: true; /** * For a readonly system without components: gives its context `tables`, copies of whole archetypes' columns, as - * `TablesDeclaration` says, read on the world's thread. Its components and resources count as what it reads. + * `TablesDeclaration` says, read on the world's thread, with copies of the values joined threads hold of their + * objects, which each gives as of its last replayed sync point; one that isn't data fails the system. Its components + * and resources count as what it reads, but objects of other threads, which don't place it. */ readonly tables?: TablesDeclaration; + /** + * For a readonly system without components: runs only once a component or resource declaring one of these traits + * of your own changed since it last ran, on any thread: written, added to or removed from an entity, or held by an + * entity spawned or despawned. It doesn't place the system. + */ + readonly changed?: readonly OwnTrait[]; }; /** A declaration as the world takes it: the build's inferred reads, writes and reductions joined with what it declares. */ diff --git a/ecs/packages/ecs/src/interface/system/sync-systems.type-test.ts b/ecs/packages/ecs/src/interface/system/sync-systems.type-test.ts index 45f0b462f..6b2432c2a 100644 --- a/ecs/packages/ecs/src/interface/system/sync-systems.type-test.ts +++ b/ecs/packages/ecs/src/interface/system/sync-systems.type-test.ts @@ -144,3 +144,12 @@ System.changes({ watch: [source], before: [tick] }, () => {}); System.create({ after: [other] }, () => {}); // @ts-expect-error nor a composite with a changes system System.create({ systems: [tick], before: [unnamedChanges] }); + +// A readonly system without components may run only once something declaring a trait of your own changed. +System.create({ readonly: true, changed: [inDocument] }, () => {}); +// @ts-expect-error only traits of your own: a key isn't one +System.create({ readonly: true, changed: [kept] }, () => {}); +// @ts-expect-error a trait filter is a readonly system's +System.create({ changed: [inDocument] }, () => {}); +// @ts-expect-error a trait filter runs a system without components once +System.create({ readonly: true, changed: [inDocument], components: { with: [kept] } }, () => {}); diff --git a/ecs/packages/ecs/src/perftest/benchmarks.ts b/ecs/packages/ecs/src/perftest/benchmarks.ts index d02592109..b0824c308 100644 --- a/ecs/packages/ecs/src/perftest/benchmarks.ts +++ b/ecs/packages/ecs/src/perftest/benchmarks.ts @@ -37,6 +37,7 @@ import { invariantBenchmarks } from "./invariants.js"; import { journalBenchmarks } from "./journal.js"; import { tableBenchmarks } from "./tables.js"; import { chainedBenchmarks } from "./chained.js"; +import { traitChangesBenchmarks } from "./trait-changes.js"; import { transientBenchmarks } from "./transients.js"; /** A world whose kernels run on this thread, which the benchmarks without a placement measure; `workers` ones use the pool. */ @@ -765,5 +766,6 @@ export const benchmarks: readonly Benchmark[] = [ ...journalBenchmarks, ...tableBenchmarks, ...chainedBenchmarks, + ...traitChangesBenchmarks, ...transientBenchmarks, ]; diff --git a/ecs/packages/ecs/src/perftest/log.ts b/ecs/packages/ecs/src/perftest/log.ts index 37ab2d3d0..ae69c0e21 100644 --- a/ecs/packages/ecs/src/perftest/log.ts +++ b/ecs/packages/ecs/src/perftest/log.ts @@ -42,7 +42,7 @@ const joinedWorld = (count: number): { readonly state: State; readonly mirror: M const log = createMoveLog(state.memory, 1, state.starts, component => { const key = state.keys[component]; if (mirror !== null && typeof key === "symbol") nameComponent(mirror, component, key, defaultOf); - }); + }, () => {}, () => Promise.resolve({ error: "no thread" })); mirror = createMirror(state.memory.memory, log.block, 1); for (const key of [serial, label, moved]) idOf(state, key); claimThreads(state, log, ["logBenchmark"]); diff --git a/ecs/packages/ecs/src/perftest/trait-changes.ts b/ecs/packages/ecs/src/perftest/trait-changes.ts new file mode 100644 index 000000000..3c6e405f4 --- /dev/null +++ b/ecs/packages/ecs/src/perftest/trait-changes.ts @@ -0,0 +1,86 @@ +// © 2026 Adobe. MIT License. See /LICENSE for details. +import { workers } from "../interface/resources/workers.js"; +import { System } from "../interface/system/system.js"; +import { createWorld } from "../implementation/index.js"; +import type { Benchmark } from "./benchmark.js"; +import { fastest } from "./suite.js"; + +// A readonly system filtering on a trait's changes, over 100K entities in 10 archetypes holding a component declaring +// the trait: what it costs a run that changes nothing the trait covers, and one that writes a row of it. + +const saved = Symbol("traitChanges/saved"); +const size = Symbol("traitChanges/size"); +const kind = Symbol("traitChanges/kind"); +const other = Symbol("traitChanges/other"); +declare module "@adobe/ecs" { + export interface Traits { + readonly [saved]: N extends unknown ? true : never; + } + export interface Components { + [size]: { type: number; [saved]: true }; + [kind]: { type: number; shared: true }; + [other]: { type: number }; + } +} + +const entities = 100_000; +const archetypes = 10; +/** Runs in each timed sample. */ +const runs = 100; + +const spawnAll = System.create(({ commands }) => { + for (let a = 0; a < archetypes; a++) { + const spawn = commands.spawn([size, kind, other], { [kind]: a }); + for (let k = 0; k < entities / archetypes; k++) spawn({ [size]: k, [other]: k }); + } +}); +let noticed = 0; +const notice = System.create({ readonly: true, changed: [saved] }, () => { noticed++; }); +const touchOther = System.create({}, () => {}); +let row = 0; +const writeOne = System.create({ components: { with: [size] } }, entry => { + if (row++ === 0) entry[size] = entry[size] + 1; +}); + +const timed = (system: System, expected: number) => async (): Promise => { + const world = createWorld({ [workers]: 0 }); + try { + await world.run(spawnAll); + world.add(notice); + await world.run(touchOther); + return await fastest(async () => { + noticed = 0; + for (let k = 0; k < runs; k++) { + row = 0; + await world.run(system); + } + if (noticed !== expected) throw new Error(`trait changes: noticed ${noticed} of ${runs} runs, not ${expected}`); + }); + } + finally { + await world.dispose(); + } +}; + +const runBest = { bytes: 64, basis: "A run reads at least one cache line of its system's state." }; + +export const traitChangesBenchmarks: readonly Benchmark[] = [ + { + name: "trait notice quiet 100K", + operation: "A run changing nothing, with a readonly system filtering on a trait 100K entities in 10 archetypes hold: the filter's check of their stamps and counts.", + per: "runs", + n: runs, + typical: [1, 1], + best: runBest, + run: timed(touchOther, 0), + }, + { + name: "trait notice written 100K", + operation: "A run writing one row of a component declaring the trait, which the readonly system filtering on it notices.", + per: "runs", + n: runs, + typical: [1, 1], + best: runBest, + run: timed(writeOne, runs), + }, +]; diff --git a/ecs/packages/ecs/threads.md b/ecs/packages/ecs/threads.md index 4a33aeb0c..75f333a86 100644 --- a/ecs/packages/ecs/threads.md +++ b/ecs/packages/ecs/threads.md @@ -129,9 +129,11 @@ All derived from declarations and, for terminal systems, the plugin's analysis o one on another thread than the world's, which a joined thread may fill, has no `commands` in its context, writes no resources and declares no `lookup`, and `System.changes` watches and reads only the world's thread's values, in types and at creation; `before`/`after` across threads is an error at creation. -- **Values for another thread's objects:** a command issued on one thread may give an object component of another - thread only its start or `null`, as tags the owning thread resolves, and a command issued on a joined thread gives a - string only its start. Any other value fails the command: a spawn's when +- **Values for another thread's objects:** a command issued on the world's thread may give an object of another + thread data, a value of a type with a schema, not declared `transfer`, which is delivered (see Delivered values); a + command issued on a joined thread may give another thread's object only its start or `null`, as tags the owning + thread resolves, and a string only its start; and no command gives one that isn't data anything else. Any other + value fails the command: a spawn's when it's issued, an add's when its system's commands are queued on the world's thread, or when it's issued on a joined one, where it drops and its system fails, so the issuing paths check nothing while no joined thread fills objects. A `transfer` value reaches its own thread through a run's input instead (see Transfers). @@ -426,6 +428,29 @@ array while it's there, else, and for a value its systems wrote, the thread's ow Tags make it exact: a start or `null` given after a slot or a write wins, as it did. A thread keeps an entity column per archetype it holds objects of (8 bytes a row, updated by replay). +### Delivered values + +Data the world's thread gives a joined thread's object, by a command, a spawn or `commands.spawnTables`, its resources +included, goes there by message (`move-log.ts`, `mirror.ts`). As apply writes it, the log numbers it and its row's tag +is the number plus `deliveredTags`, above every staged slot's, whose ids wrap below them; the log's `set` entry carries +that tag. Before it publishes the sync, the world posts the sync's values in one `values` message, numbered from the +first. The thread keeps them by number: replay holds before a sync whose `set` names one that hasn't arrived, as it +holds for a key not yet named, and the message, once it arrives, runs what waited; a rebuild reading such a tag holds +too. Replay and rebuild take each value as they apply it, and drop those of syncs applied that a rebuild past them +never read. A value a message can't carry, though its type said it could, goes as undefined, and its object takes its +start. The world never waits for delivery. + +### Gathered tables + +A readonly system's `tables` on the world's thread reads the objects joined threads hold by asking them +(`observer.ts`, `tables-read.ts`, `join.ts`): before a pass's systems run, the world posts each thread holding objects +its systems' tables read a `gather` of those components and resources, and runs the pass once every thread answered. +A thread answers once its mirror is current, holding as replay does, with every entity holding each component and +its value, and each resource's value, structured-cloned; the world merges them by entity, a row the thread didn't give +taking its start. Each thread's values are as of the newest sync it replayed, not one moment across threads. An +object that isn't data isn't asked for, and a thread that's gone or whose values can't be posted gives none: a table +reading either fails its system, naming why. Objects of other threads don't place a system reading tables. + ### Systems on other threads A system whose thread a joined thread claims is placed there (`remote-systems.ts`): the world's runner for it stands in From 1a98407afec6e23daac5a66b55cf5a6f14cadd68 Mon Sep 17 00:00:00 2001 From: Kris Nye Date: Sun, 22 Nov 2026 11:06:28 -0800 Subject: [PATCH 2/2] ecs: state in its agent context that the core is minimal and performance-first --- ecs/packages/ecs/CLAUDE.md | 8 ++++++++ ecs/packages/ecs/src/interface/CLAUDE.md | 2 ++ 2 files changed, 10 insertions(+) diff --git a/ecs/packages/ecs/CLAUDE.md b/ecs/packages/ecs/CLAUDE.md index eb7ef42ce..15436c5c8 100644 --- a/ecs/packages/ecs/CLAUDE.md +++ b/ecs/packages/ecs/CLAUDE.md @@ -1,5 +1,13 @@ # ecs +## The core is minimal and fast + +`@adobe/ecs` is a deliberately minimal core whose first requirement is performance. Add to it only what can't be built +on its public API, by a library or the application, or what the core does significantly faster, shown by a benchmark. +Everything else, such as policies, conveniences, scheduling choices like debouncing and saving, and integrations, goes +in a library (`ecs-persistence`, `ecs-gpu`) or the application. When a feature seems to need the core, first find the +smallest primitive that lets it live outside, and propose that. + ## Interface and implementation are separate The ECS has two parts: diff --git a/ecs/packages/ecs/src/interface/CLAUDE.md b/ecs/packages/ecs/src/interface/CLAUDE.md index a2d18ff49..3bf93d449 100644 --- a/ecs/packages/ecs/src/interface/CLAUDE.md +++ b/ecs/packages/ecs/src/interface/CLAUDE.md @@ -23,6 +23,8 @@ own. That includes: When work seems to need a change here, first find a way to keep it out: +- Build it outside the core, in a library or the application, on the public API, unless the core alone can do it or + does it significantly faster (`../../CLAUDE.md`, "The core is minimal and fast"). - Infer the type the implementation needs (`Parameters<…>`, `ReturnType<…>`, indexed access) instead of exporting a name for it. - Keep protocol state, progress and bookkeeping in the implementation's own storage, not in components or resources