Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

refactor(scheduler): symmetric runBefore/runAfter edges + full-path cycle reports

esengine394f9f0c3e04
diff --git a/sdk/src/app.ts b/sdk/src/app.ts
index 03d8919d6..30322ca47 100644
--- a/sdk/src/app.ts
+++ b/sdk/src/app.ts
@@ -712,53 +712,57 @@ export class App {
return out;
};
- for (const entry of systems) {
- if (entry.runBefore) {
- for (const targetName of entry.runBefore) {
- for (const targetIndex of resolveTargets(targetName)) {
- const targetEntry = systems[targetIndex];
- if (!targetEntry.runAfter) {
- targetEntry.runAfter = [];
- }
- if (!targetEntry.runAfter.includes(entry.system._name)) {
- targetEntry.runAfter.push(entry.system._name);
- }
- }
+ // Build a local dependency graph: `adj[i]` lists indices that must run
+ // *before* system `i`. Both runBefore and runAfter feed into the same
+ // structure — runBefore is translated symmetrically into
+ // "target depends on me" without mutating the caller's SystemEntry
+ // objects (the old path appended to target.runAfter, leaving duplicated
+ // edges across repeat sorts).
+ const adj: number[][] = systems.map(() => []);
+ const addEdge = (from: number, to: number) => {
+ if (from === to) return;
+ const list = adj[to];
+ if (!list.includes(from)) list.push(from);
+ };
+
+ for (let i = 0; i < systems.length; i++) {
+ const e = systems[i];
+ if (e.runAfter) {
+ for (const depName of e.runAfter) {
+ for (const j of resolveTargets(depName)) addEdge(j, i);
+ }
+ }
+ if (e.runBefore) {
+ for (const targetName of e.runBefore) {
+ for (const j of resolveTargets(targetName)) addEdge(i, j);
}
}
}
+ // DFS topological sort with path-aware cycle reporting.
+ // color: 0 = unvisited, 1 = in the current DFS stack (GRAY), 2 = done.
+ const GRAY = 1, BLACK = 2;
+ const color = new Uint8Array(systems.length);
+ const stack: number[] = [];
const sorted: SystemEntry[] = [];
- const visited = new Set<number>();
- const visiting = new Set<number>();
const visit = (index: number): void => {
- if (visited.has(index)) return;
- if (visiting.has(index)) {
- const name = systems[index].system._name;
- throw new Error(`Circular dependency detected involving system "${name}"`);
- }
-
- visiting.add(index);
- const entry = systems[index];
-
- if (entry.runAfter) {
- for (const depName of entry.runAfter) {
- for (const depIndex of resolveTargets(depName)) {
- visit(depIndex);
- }
- }
+ if (color[index] === BLACK) return;
+ if (color[index] === GRAY) {
+ const cycleStart = stack.indexOf(index);
+ const path = stack.slice(cycleStart).map(i => systems[i].system._name);
+ path.push(systems[index].system._name);
+ throw new Error(`Circular system dependency: ${path.join(' → ')}`);
}
-
- visiting.delete(index);
- visited.add(index);
- sorted.push(entry);
+ color[index] = GRAY;
+ stack.push(index);
+ for (const dep of adj[index]) visit(dep);
+ stack.pop();
+ color[index] = BLACK;
+ sorted.push(systems[index]);
};
- for (let i = 0; i < systems.length; i++) {
- visit(i);
- }
-
+ for (let i = 0; i < systems.length; i++) visit(i);
return sorted;
}
diff --git a/sdk/tests/scheduler-cycles.test.ts b/sdk/tests/scheduler-cycles.test.ts
new file mode 100644
index 000000000..8fd37c909
--- /dev/null
+++ b/sdk/tests/scheduler-cycles.test.ts
@@ -0,0 +1,89 @@
+/**
+ * @file scheduler-cycles.test.ts
+ * @brief Cycle detection quality + re-sort idempotence after sortSystems.
+ */
+import { describe, expect, it } from 'vitest';
+import { App } from '../src/app';
+import { Schedule, defineSystem } from '../src/system';
+
+function trackedSystem(name: string, trace: string[]) {
+ return defineSystem([], () => { trace.push(name); }, { name });
+}
+
+describe('sortSystems cycle detection', () => {
+ async function runUpdate(app: App) {
+ (app as any).runner_ = { run: (sys: any) => sys._fn() };
+ await (app as any).runSchedule(Schedule.Update);
+ }
+
+ it('reports the full cycle path, not just one member', async () => {
+ const app = App.new();
+ const trace: string[] = [];
+ app.addSystemToSchedule(Schedule.Update, trackedSystem('A', trace), { runAfter: ['C'] });
+ app.addSystemToSchedule(Schedule.Update, trackedSystem('B', trace), { runAfter: ['A'] });
+ app.addSystemToSchedule(Schedule.Update, trackedSystem('C', trace), { runAfter: ['B'] });
+
+ let caught: Error | null = null;
+ try { await runUpdate(app); } catch (e) { caught = e as Error; }
+ expect(caught).not.toBeNull();
+ expect(caught!.message).toMatch(/Circular system dependency:/);
+ // DFS may traverse in either direction; either rotation is acceptable
+ // so long as all three systems appear with a self-closing edge.
+ expect(caught!.message).toContain('A');
+ expect(caught!.message).toContain('B');
+ expect(caught!.message).toContain('C');
+ // The first node must repeat at the end, closing the loop.
+ const path = caught!.message.split('Circular system dependency: ')[1].split(' → ');
+ expect(path[0]).toBe(path[path.length - 1]);
+ expect(path).toHaveLength(4);
+ });
+
+ it('catches cycles introduced through runBefore (asymmetry regression)', async () => {
+ const app = App.new();
+ const trace: string[] = [];
+ app.addSystemToSchedule(Schedule.Update, trackedSystem('A', trace), { runBefore: ['B'] });
+ app.addSystemToSchedule(Schedule.Update, trackedSystem('B', trace), { runBefore: ['A'] });
+
+ await expect(runUpdate(app)).rejects.toThrow(/A → B → A|B → A → B/);
+ });
+
+ it('produces the same order on two consecutive sorts of the same schedule', async () => {
+ const app = App.new();
+ const trace: string[] = [];
+ app.addSystemToSchedule(Schedule.Update, trackedSystem('A', trace), { runBefore: ['B'] });
+ app.addSystemToSchedule(Schedule.Update, trackedSystem('B', trace), { runAfter: ['A'] });
+ app.addSystemToSchedule(Schedule.Update, trackedSystem('C', trace), { runAfter: ['B'] });
+
+ (app as any).runner_ = { run: (sys: any) => sys._fn() };
+ await (app as any).runSchedule(Schedule.Update);
+ await (app as any).runSchedule(Schedule.Update);
+
+ // Two runs → same order twice → A,B,C,A,B,C (no edge duplication
+ // artifacts that would skew a second sort).
+ expect(trace).toEqual(['A', 'B', 'C', 'A', 'B', 'C']);
+ });
+
+ it('does not mutate registered SystemEntry objects across sorts', async () => {
+ const app = App.new();
+ const trace: string[] = [];
+ app.addSystemToSchedule(Schedule.Update, trackedSystem('A', trace), { runBefore: ['B'] });
+ app.addSystemToSchedule(Schedule.Update, trackedSystem('B', trace));
+
+ const entries = (app as any).systems_.get(Schedule.Update) as Array<{
+ system: { _name: string };
+ runBefore?: string[];
+ runAfter?: string[];
+ }>;
+ const entryB = entries.find(e => e.system._name === 'B')!;
+ const runAfterBeforeSort = entryB.runAfter;
+
+ (app as any).runner_ = { run: (sys: any) => sys._fn() };
+ await (app as any).runSchedule(Schedule.Update);
+ await (app as any).runSchedule(Schedule.Update);
+
+ // B's runAfter must be unchanged after multiple sorts. Previously the
+ // scheduler pushed 'A' onto B.runAfter as a side effect of resolving
+ // A.runBefore, leaving duplicated edges in persistent state.
+ expect(entryB.runAfter).toBe(runAfterBeforeSort);
+ });
+});
diff --git a/sdk/tests/system-ordering.test.ts b/sdk/tests/system-ordering.test.ts
index 376c0c55f..63c58f2cb 100644
--- a/sdk/tests/system-ordering.test.ts
+++ b/sdk/tests/system-ordering.test.ts
@@ -124,7 +124,8 @@ describe('System Dependency Ordering', () => {
(app as any).runner_ = { run: (sys: any) => sys._fn() };
- await expect((app as any).runSchedule(Schedule.Update)).rejects.toThrow('Circular dependency');
+ await expect((app as any).runSchedule(Schedule.Update))
+ .rejects.toThrow(/Circular system dependency: SystemA → SystemB → SystemA/);
});
});