Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions ecs/packages/ecs-persistence/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
2 changes: 1 addition & 1 deletion ecs/packages/ecs-persistence/package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
18 changes: 18 additions & 0 deletions ecs/packages/ecs-persistence/src/guide/05-watching.md
Original file line number Diff line number Diff line change
@@ -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.
5 changes: 5 additions & 0 deletions ecs/packages/ecs-persistence/src/guide/05-watching.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
started: nothing to save
labeled: saved
idle: nothing to save
filtered on the page: saved
reloaded filter: shape: box
77 changes: 77 additions & 0 deletions ecs/packages/ecs-persistence/src/guide/05-watching.ts
Original file line number Diff line number Diff line change
@@ -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<N> {
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<string, string> | 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<void> => {
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<void> => {
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();
};
1 change: 1 addition & 0 deletions ecs/packages/ecs-persistence/src/guide/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
5 changes: 5 additions & 0 deletions ecs/packages/ecs-persistence/src/guide/guide.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"],
};

/**
Expand All @@ -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 });
1 change: 1 addition & 0 deletions ecs/packages/ecs-persistence/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
68 changes: 68 additions & 0 deletions ecs/packages/ecs-persistence/src/persistence.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down Expand Up @@ -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<N> {
readonly [document]: string;
readonly [settings]: string;
Expand Down Expand Up @@ -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<string, Entity> | null; default: null; thread: "persistenceTestPage"; [settings]: "filter" };
[focused]: { type: Entity; [settings]: "focused" };
}
}

Expand Down Expand Up @@ -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<string, Entity> } = { 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);
Expand Down
25 changes: 25 additions & 0 deletions ecs/packages/ecs-persistence/src/watch.ts
Original file line number Diff line number Diff line change
@@ -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);
};
8 changes: 8 additions & 0 deletions ecs/packages/ecs/CLAUDE.md
Original file line number Diff line number Diff line change
@@ -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:
Expand Down
3 changes: 3 additions & 0 deletions ecs/packages/ecs/followups.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion ecs/packages/ecs/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@adobe/ecs",
"version": "0.5.2",
"version": "0.6.0",
"description": "Adobe ECS",
"license": "MIT",
"type": "module",
Expand Down
10 changes: 6 additions & 4 deletions ecs/packages/ecs/src/implementation/world/batches.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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);
Expand Down Expand Up @@ -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);
}
Expand Down
Loading