A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
fix(scene): roll back entities after publication failures
yhh5e193c907f41
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 62141d5fc..67334765c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -22,6 +22,8 @@ published separately; it ships inside the editor.### Fixed+- **Late scene-load errors roll back the new entities.** A failing final spawn-phase observer or asset-reference publication step now despawns the entities created by that load and releases their owned resources before returning the original error. Existing unrelated entities remain intact and a later load can retry normally.+- **Prepared prefab spawns reject failed parent attachments.** The synchronous spawn path rolls back its new hierarchy and entity-owned resources when its parent no longer accepts the root, matching asynchronous instantiation. Preparation resources remain available for later valid spawns, and live parents, position overrides and explicit unparented copies remain supported.- **Standalone scene and prefab spawns release their resources.** Loads without a scene collector transfer acquired resources to the entities that reference them, then release the preload receipts. Destroying or rolling back a spawned hierarchy retires those acquisitions. Prefab document reads also use scoped receipts, including nested sources, so repeated spawns no longer accumulate unowned references.diff --git a/sdk/src/scene/scene.ts b/sdk/src/scene/scene.tsindex 085906952..f1acbf7c7 100644--- a/sdk/src/scene/scene.ts+++ b/sdk/src/scene/scene.ts@@ -657,6 +657,7 @@ async function loadSceneAssetsAndSpawn(): Promise<Map<number, Entity>> {let ownership: PreparedSpawnOwnership | undefined;let releasePreload: (() => void) | undefined;+ let spawned: Map<number, Entity> | undefined;try {if (options?.assets) {const assets = options.assets;@@ -683,10 +684,19 @@ async function loadSceneAssetsAndSpawn(}}}- const entities = await timed('spawn', () => spawnAndLoadEntities(world, data, options?.externalEntities, options?.onPhase));+ const entities = await timed('spawn', () => {+ spawned = spawnAndLoadEntities(world, data, options?.externalEntities, options?.onPhase);+ return spawned;+ });ownership?.attach(world, entities);options?.assets?.trackSceneAssetReferences(data, entities);return entities;+ } catch (error) {+ if (spawned) for (const entity of spawned.values()) {+ try { if (world.valid(entity)) world.despawn(entity); }+ catch { /* A cleanup callback must not hide the original load failure. */ }+ }+ throw error;} finally {ownership?.release();releasePreload?.();diff --git a/sdk/tests/scene-publication-failure.test.ts b/sdk/tests/scene-publication-failure.test.tsnew file mode 100644index 000000000..9cd349845--- /dev/null+++ b/sdk/tests/scene-publication-failure.test.ts@@ -0,0 +1,46 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, expect, it, vi } from 'vitest';+import { World } from '../src/ecs/world';+import { loadSceneWithAssets, type SceneData } from '../src/scene/scene';+import { Assets } from '../src/asset/Assets';+import type { Backend } from '../src/asset/Backend';++vi.mock('../src/wasm/resourceManager', () => ({+ requireResourceManager: () => ({ releaseTexture: vi.fn(), invalidateTexturePath: () => false }),+ getResourceManager: () => null, evictTextureDimensions: vi.fn(),+}));++const scene: SceneData = { version: 4, name: 'publication', entities: [{ id: 1, name: 'new', parent: null,+ children: [], components: [{ type: 'MeshRenderer', data: { mesh: 'mesh.esmesh' } }],+}] };++describe('scene publication failures', () => {+ it('rolls back only this load when its final spawn-phase observer throws', async () => {+ const world = new World(), existing = world.spawn(), error = new Error('observer failed');+ await expect(loadSceneWithAssets(world, scene, { onPhase: phase => {+ if (phase === 'spawn') throw error;+ } })).rejects.toBe(error);+ expect(world.getAllEntities()).toEqual([existing]);+ });+ it('rolls back entities and their asset receipts when reference tracking throws', async () => {+ const world = new World(), existing = world.spawn(), error = new Error('tracking failed');+ const unloaded = vi.fn();+ const assets = Assets.create({ backend: {+ fetchBinary: async () => new ArrayBuffer(8), fetchText: async () => '{}', resolveUrl: (path: string) => path,+ } as Backend, module: { _malloc: () => 0, _free: () => {}, HEAPU8: new Uint8Array(16) } as never });+ assets.register<{ handle: number }>({ type: 'mesh', load: async () => ({ handle: 1 }), unload: unloaded } as never);+ const tracker = vi.spyOn(assets, 'trackSceneAssetReferences').mockImplementation(() => { throw error; });+ try {+ await expect(loadSceneWithAssets(world, scene, { assets })).rejects.toBe(error);+ expect(world.getAllEntities()).toEqual([existing]);+ expect(assets.sizes()).toMatchObject({ refRows: 0, trackedRefRows: 0, genericCached: 0 });+ expect(unloaded).toHaveBeenCalledOnce();+ tracker.mockRestore();+ const retry = await loadSceneWithAssets(world, scene, { assets });+ expect(retry.size).toBe(1);+ for (const entity of retry.values()) world.despawn(entity);+ expect(assets.sizes().refRows).toBe(0);+ } finally { tracker.mockRestore(); assets.releaseAll(); for (const entity of world.getAllEntities()) world.despawn(entity); }+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex f5efb08b1..bc9f43e7e 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';* the reader recognises anyway.*/export const NOTED = {+ 'fix(scene): roll back entities after publication failures':+ { note: 'Late scene-load errors roll back the new entities.' },'fix(prefab): roll back prepared spawns on parent rejection':{ note: 'Prepared prefab spawns reject failed parent attachments.' },'fix(asset): transfer standalone spawn resources to entity owners':