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.

fix(scene): loadAdditive committed a scene that had already been unloaded

esengine0434846d1823
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0e45dcf7a..8101a1494 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -37,6 +37,16 @@ published separately; it ships inside the editor.
### Fixed
+- **An additive scene unloaded during its own `setup()` came back as a ghost.**
+ `setup()` is user code and may await for as long as it likes; an `unload()`
+ during it tears the scene down completely — entities, systems, assets, its slot
+ in the registry. `load()` re-checked the slot afterwards and aborted, but
+ `loadAdditive()` went straight on to set `running`, add to the additive set and
+ push to the draw order, resurrecting a scene that no longer existed and leaving
+ whatever `setup()` spawned after the teardown in the world under it, owned by
+ nobody. The check now lives in `loadSceneData_`, which both paths await: it
+ returns only if the load still owns the slot, so neither caller has to remember.
+
- **A hot reload could leave an asset loading three times, or fail the reload with
the old file's error.** `AsyncCache.invalidate()` aborts the in-flight load and
drops its pending record, and hot reload asks for the same key again right away,
diff --git a/sdk/src/scene/sceneManager.ts b/sdk/src/scene/sceneManager.ts
index 92fb1a2ac..ff9632d0d 100644
--- a/sdk/src/scene/sceneManager.ts
+++ b/sdk/src/scene/sceneManager.ts
@@ -317,11 +317,6 @@ export class SceneManagerState {
await this.loadSceneData_(instance, name, config, sceneData, onProgress);
- // A user setup() can await; an unload during it invalidates this load.
- // loadSceneData_ already despawned any spawned entities on its own token
- // check, so abort before committing status/activeScene to a dead scene.
- if (this.scenes_.get(name) !== instance) throw new SceneLoadCancelled(name);
-
instance.status = 'running';
this.activeScene_ = name;
this.loadOrder_.push(name);
@@ -492,6 +487,13 @@ export class SceneManagerState {
}
}
+ /**
+ * Populate a scene: entities, assets, systems, setup().
+ *
+ * Returning means this load still owns the scene slot. Every await inside is a
+ * window for a concurrent unload to take it; checking that here rather than
+ * per caller is what the additive path was missing.
+ */
private async loadSceneData_(
instance: SceneInstance,
name: string,
@@ -564,6 +566,10 @@ export class SceneManagerState {
const ctx = this.contexts_.get(name)!;
if (config.setup) {
await config.setup(ctx);
+ // setup() is user code and can await for as long as it likes. An
+ // unload during it means everything above — and everything setup
+ // itself spawned — belongs to a scene that no longer exists.
+ if (this.scenes_.get(name) !== instance) throw new SceneLoadCancelled(name);
}
}
diff --git a/sdk/tests/sceneManager-race.test.ts b/sdk/tests/sceneManager-race.test.ts
new file mode 100644
index 000000000..a292db050
--- /dev/null
+++ b/sdk/tests/sceneManager-race.test.ts
@@ -0,0 +1,212 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file sceneManager-race.test.ts
+ * @brief A load that no longer owns its scene slot must not commit anything.
+ *
+ * setup() is user code and may await for as long as it likes; an
+ * unload() during it tears the scene down completely. load() re-checked
+ * the slot afterwards and aborted, but loadAdditive() went straight on
+ * to set `running`, add to `additiveScenes_` and push to `loadOrder_` —
+ * resurrecting a scene that had already been unloaded, with whatever
+ * setup() spawned after the teardown left in the world under it.
+ *
+ * The interleaving is driven by hand: setup blocks on a deferred
+ * promise, the test unloads while it is blocked, then releases it.
+ */
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('../src/scene/scene', () => ({
+ loadSceneWithAssets: vi.fn().mockResolvedValue(new Map()),
+}));
+
+vi.mock('../src/render/customDraw', () => ({
+ registerDrawCallback: vi.fn(),
+ unregisterDrawCallback: vi.fn(),
+}));
+
+vi.mock('../src/postprocess', () => ({
+ PostProcess: { bind: vi.fn(), unbind: vi.fn() },
+ PostProcessStack: vi.fn(),
+}));
+
+vi.mock('../src/render/material', () => ({
+ Material: { release: vi.fn(), createShader: vi.fn() },
+ defineResource: vi.fn(),
+}));
+
+vi.mock('../src/render/draw', () => ({
+ Draw: { setLayer: vi.fn(), setDepth: vi.fn(), rect: vi.fn() },
+}));
+
+vi.mock('../src/ecs/resource', () => ({
+ defineResource: vi.fn((_init: unknown, name?: string) => ({
+ _id: Symbol(name ?? 'Resource'), _name: name ?? 'Resource', _default: _init,
+ })),
+}));
+
+vi.mock('../src/ecs/component', () => ({
+ SceneOwner: Symbol('SceneOwner'),
+ Disabled: { _id: Symbol('Disabled'), _name: 'Disabled', _builtin: false, _default: {} },
+ renderableComponents: () => [],
+ defineBuiltin: (name: string) => Symbol(name),
+ defineTag: (name: string) => ({ _id: Symbol(name), _name: name, _builtin: false, _default: {} }),
+}));
+
+vi.mock('../src/asset/AssetPlugin', () => ({ Assets: Symbol('Assets') }));
+
+vi.mock('../src/defaults', () => ({
+ RuntimeConfig: {
+ sceneTransitionDuration: 0.5,
+ sceneTransitionColor: { r: 0, g: 0, b: 0, a: 1 },
+ },
+}));
+
+import { SceneManagerState, SceneLoadCancelled } from '../src/scene/sceneManager';
+
+interface Deferred {
+ promise: Promise<void>;
+ resolve: () => void;
+}
+
+function deferred(): Deferred {
+ let resolve!: () => void;
+ const promise = new Promise<void>((res) => { resolve = res; });
+ return { promise, resolve };
+}
+
+function createMockApp() {
+ const alive = new Set<number>();
+ let next = 1;
+ const world = {
+ spawn: vi.fn(() => { const e = next++; alive.add(e); return e; }),
+ despawn: vi.fn((e: number) => { alive.delete(e); }),
+ valid: vi.fn((e: number) => alive.has(e)),
+ has: vi.fn(() => false),
+ get: vi.fn(() => undefined),
+ insert: vi.fn(),
+ set: vi.fn(),
+ remove: vi.fn(),
+ };
+ return {
+ world,
+ hasResource: vi.fn(() => false),
+ getResource: vi.fn(() => undefined),
+ addSystemToSchedule: vi.fn(),
+ removeSystem: vi.fn(),
+ _alive: alive,
+ };
+}
+
+describe('a load unloaded mid-setup commits nothing', () => {
+ let app: ReturnType<typeof createMockApp>;
+ let manager: SceneManagerState;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ app = createMockApp();
+ manager = new SceneManagerState(app as any);
+ });
+
+ /**
+ * Registers `name` with a setup() that blocks until `gate` opens. `reached`
+ * settles once setup is actually running — without waiting for it the unload
+ * lands in the earlier asset-load window instead, which the code has always
+ * checked, and the test would pass while proving nothing.
+ */
+ function registerBlockingScene(name: string, onSetup?: (ctx: any) => void): { gate: Deferred; reached: Deferred } {
+ const gate = deferred();
+ const reached = deferred();
+ manager.register({
+ name,
+ data: { version: '1.0', name, entities: [] } as any,
+ setup: async (ctx: any) => {
+ reached.resolve();
+ await gate.promise;
+ onSetup?.(ctx);
+ },
+ });
+ return { gate, reached };
+ }
+
+ it('loadAdditive: unload during setup leaves no trace of the scene', async () => {
+ const { gate, reached } = registerBlockingScene('ui');
+
+ const loading = manager.loadAdditive('ui');
+ const rejected = expect(loading).rejects.toBeInstanceOf(SceneLoadCancelled);
+
+ await reached.promise;
+ await manager.unload('ui');
+ gate.resolve();
+ await rejected;
+
+ expect(manager.isLoaded('ui')).toBe(false);
+ expect(manager.getLoadOrder()).not.toContain('ui');
+ expect(manager.getActiveScenes()).not.toContain('ui');
+ expect(manager.getSceneStatus('ui')).toBeNull();
+ expect(manager.getScene('ui')).toBeNull();
+ });
+
+ it('load: unload during setup leaves no trace either', async () => {
+ const { gate, reached } = registerBlockingScene('main');
+
+ const loading = manager.load('main');
+ const rejected = expect(loading).rejects.toBeInstanceOf(SceneLoadCancelled);
+
+ await reached.promise;
+ await manager.unload('main');
+ gate.resolve();
+ await rejected;
+
+ expect(manager.isLoaded('main')).toBe(false);
+ expect(manager.getLoadOrder()).not.toContain('main');
+ expect(manager.getActive()).toBeNull();
+ });
+
+ it('loadAdditive: entities setup spawned after the teardown are not left behind', async () => {
+ let spawned: number | null = null;
+ const { gate, reached } = registerBlockingScene('ui', (ctx) => { spawned = ctx.spawn(); });
+
+ const loading = manager.loadAdditive('ui');
+ const rejected = expect(loading).rejects.toBeInstanceOf(SceneLoadCancelled);
+
+ await reached.promise;
+ await manager.unload('ui');
+ gate.resolve();
+ await rejected;
+
+ expect(spawned).not.toBeNull();
+ // unload() had already run: nothing else will ever come back for this one.
+ expect(app._alive.has(spawned!)).toBe(false);
+ });
+
+ it('a load nobody interrupted still commits', async () => {
+ const { gate, reached } = registerBlockingScene('ui');
+ const loading = manager.loadAdditive('ui');
+ await reached.promise;
+ gate.resolve();
+ await loading;
+
+ expect(manager.isLoaded('ui')).toBe(true);
+ expect(manager.getLoadOrder()).toContain('ui');
+ expect(manager.getSceneStatus('ui')).toBe('running');
+ });
+
+ it('the slot is free for a fresh load after the cancelled one', async () => {
+ const { gate, reached } = registerBlockingScene('ui');
+ const loading = manager.loadAdditive('ui');
+ const rejected = expect(loading).rejects.toBeInstanceOf(SceneLoadCancelled);
+ await reached.promise;
+ await manager.unload('ui');
+ gate.resolve();
+ await rejected;
+
+ // Re-register without the gate so the retry completes on its own.
+ manager.register({
+ name: 'ui',
+ data: { version: '1.0', name: 'ui', entities: [] } as any,
+ });
+ await manager.loadAdditive('ui');
+ expect(manager.getSceneStatus('ui')).toBe('running');
+ });
+});