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(assets): a live asset replacement is a transaction per owning scope

esengine7fd0258f7169
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 46ea3312d..b67e81d60 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -766,6 +766,7 @@ ResourceDef<AssetsClass>
## AssetsData — type @beta
```
+@internal appScope: AssetScope
@internal releaseTextureLease: (lease: AssetRefLease<number>) => void
@internal releaseTyped: (type: string, ref: string) => void
@internal releaseTypedLease: (type: string, lease: AssetRefLease<unknown>) => void
@@ -6887,6 +6888,7 @@ ResourceDef<SceneManagerState>
## SceneManagerState — class @beta
```
+@internal assetScopeFor: (name: string) => AssetScope | null
bringToTop: (name: string) => void
getActive: () => string | null
getActiveScenes: () => string[]
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index d96d185e7..7d8b13b1a 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -766,6 +766,7 @@ ResourceDef<AssetsClass>
## AssetsData — type @beta
```
+@internal appScope: AssetScope
@internal releaseTextureLease: (lease: AssetRefLease<number>) => void
@internal releaseTyped: (type: string, ref: string) => void
@internal releaseTypedLease: (type: string, lease: AssetRefLease<unknown>) => void
@@ -7080,6 +7081,7 @@ ResourceDef<SceneManagerState>
## SceneManagerState — class @beta
```
+@internal assetScopeFor: (name: string) => AssetScope | null
bringToTop: (name: string) => void
getActive: () => string | null
getActiveScenes: () => string[]
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 1a35af215..b551a522e 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -761,6 +761,7 @@ ResourceDef<AssetsClass>
## AssetsData — type @beta
```
+@internal appScope: AssetScope
@internal releaseTextureLease: (lease: AssetRefLease<number>) => void
@internal releaseTyped: (type: string, ref: string) => void
@internal releaseTypedLease: (type: string, lease: AssetRefLease<unknown>) => void
@@ -6882,6 +6883,7 @@ ResourceDef<SceneManagerState>
## SceneManagerState — class @beta
```
+@internal assetScopeFor: (name: string) => AssetScope | null
bringToTop: (name: string) => void
getActive: () => string | null
getActiveScenes: () => string[]
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index b3509597c..66c08f352 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -761,6 +761,7 @@ ResourceDef<AssetsClass>
## AssetsData — type @beta
```
+@internal appScope: AssetScope
@internal releaseTextureLease: (lease: AssetRefLease<number>) => void
@internal releaseTyped: (type: string, ref: string) => void
@internal releaseTypedLease: (type: string, lease: AssetRefLease<unknown>) => void
@@ -7128,6 +7129,7 @@ ResourceDef<SceneManagerState>
## SceneManagerState — class @beta
```
+@internal assetScopeFor: (name: string) => AssetScope | null
bringToTop: (name: string) => void
getActive: () => string | null
getActiveScenes: () => string[]
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 843a3d9ac..88d0b3887 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -761,6 +761,7 @@ ResourceDef<AssetsClass>
## AssetsData — type @beta
```
+@internal appScope: AssetScope
@internal releaseTextureLease: (lease: AssetRefLease<number>) => void
@internal releaseTyped: (type: string, ref: string) => void
@internal releaseTypedLease: (type: string, lease: AssetRefLease<unknown>) => void
@@ -6889,6 +6890,7 @@ ResourceDef<SceneManagerState>
## SceneManagerState — class @beta
```
+@internal assetScopeFor: (name: string) => AssetScope | null
bringToTop: (name: string) => void
getActive: () => string | null
getActiveScenes: () => string[]
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.ts
index c21815fd7..b75570914 100644
--- a/sdk/src/asset/Assets.ts
+++ b/sdk/src/asset/Assets.ts
@@ -379,6 +379,7 @@ export class Assets {
private assetRegistry_: AssetRegistry | null = null;
private refCounter_: AssetRefCounter | null = null;
private invalidateListeners_ = new Set<InvalidateListener>();
+ private readonly appScope_ = new AssetScope();
/** `"<kind>:<handle>"` → resolved load path, recorded on every handle-yielding
* load. The REVERSE of resolution — inspectors and tooling that only hold a
* live World handle use it to name the asset (see {@link pathForHandle}). */
@@ -1678,7 +1679,23 @@ export class Assets {
};
}
+ /**
+ * What this Assets acquired for an owner the engine cannot name — a live
+ * binding on an entity no scene owns.
+ *
+ * Its life is this instance's, which is how long such an entity can live.
+ * Never a place to park an acquisition an owner exists for.
+ *
+ * @internal
+ */
+ get appScope(): AssetScope {
+ return this.appScope_;
+ }
+
releaseAll(): void {
+ // Through the normal door first, so what the app owned is disposed the
+ // way any other owner's is rather than by the wholesale drain below.
+ this.appScope_.releaseAll();
const rm = requireResourceManager();
this.resetEpoch_++;
this.abandoned_.clear();
diff --git a/sdk/src/asset/liveAssetRebind.ts b/sdk/src/asset/liveAssetRebind.ts
new file mode 100644
index 000000000..0cc725e37
--- /dev/null
+++ b/sdk/src/asset/liveAssetRebind.ts
@@ -0,0 +1,110 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file liveAssetRebind.ts
+ * @brief Replacing a live asset is a transaction, and its unit is the owning scope.
+ *
+ * @details Ownership is per scope: two scenes holding one texture hold two
+ * receipts. So a replacement that acquires ONCE and swaps the handle
+ * world-wide moves both owners onto an asset only one of them owes a
+ * release for — the other's receipt now names an era nothing on screen
+ * is using, and the new era has one holder where two are needed.
+ *
+ * Hence one acquisition per scope that migrates, and within a scope
+ * all of its bindings move or none do: a scope holding the new
+ * generation for some of its bindings and the old one for the rest
+ * owes two receipts for one replacement, and nothing afterwards can
+ * say which binding belongs to which.
+ *
+ * The coordinator owns nothing at rest. Every acquisition it makes
+ * ends up in an owner's scope or is given straight back.
+ */
+import type { World } from '../ecs/world';
+import type { Entity } from '../types';
+import type { AssetScope, AssetLease } from './AssetLease';
+import type { AssetFieldType } from '../scene/scene';
+import { findLiveAssetBindings, readLiveAssetBinding, writeLiveAssetBinding } from './liveAssetBindings';
+import { log } from '../util/logger';
+
+/** The scope that owns what an entity's asset fields hold. */
+export type OwnerScopeResolver = (entity: Entity) => AssetScope;
+
+/** One acquisition of the replacement, and how to read the value a bound field
+ * holds for a lease — a texture's handle, for the only kind rebound today. */
+export interface LiveAssetReplacement {
+ readonly lease: AssetLease;
+ readonly boundValue: (lease: AssetLease) => unknown;
+}
+
+/** Every scope owning at least one live binding of `oldValue` — one replacement
+ * acquisition is owed to each. */
+export function ownerScopesOf(
+ world: World, type: AssetFieldType, oldValue: unknown, ownerScopeOf: OwnerScopeResolver,
+): AssetScope[] {
+ const scopes: AssetScope[] = [];
+ for (const binding of findLiveAssetBindings(world, type, oldValue)) {
+ const scope = ownerScopeOf(binding.entity);
+ if (!scopes.includes(scope)) scopes.push(scope);
+ }
+ return scopes;
+}
+
+/**
+ * Move one scope onto the replacement: bindings and ownership together, all or
+ * none. Returns whether it migrated; when it did not, the replacement has been
+ * given back rather than kept by the coordinator.
+ */
+export function migrateScopeBindings(
+ world: World,
+ scope: AssetScope,
+ type: AssetFieldType,
+ oldValue: unknown,
+ replacement: LiveAssetReplacement,
+ ownerScopeOf: OwnerScopeResolver,
+): boolean {
+ const bindings = findLiveAssetBindings(world, type, oldValue)
+ .filter((binding) => ownerScopeOf(binding.entity) === scope);
+ const newValue = replacement.boundValue(replacement.lease);
+ if (bindings.length === 0 || newValue === undefined) {
+ replacement.lease.release();
+ return false;
+ }
+
+ // What this scope holds for the outgoing era, found BEFORE the replacement
+ // joins the scope — afterwards a search by value could match either.
+ const outgoing = scope.leases().find((lease) => replacement.boundValue(lease) === oldValue);
+
+ const previous = bindings.map((binding) => readLiveAssetBinding(world, binding));
+ let written = 0;
+ let failure: unknown = null;
+ for (; written < bindings.length; written++) {
+ try {
+ writeLiveAssetBinding(world, bindings[written], newValue);
+ } catch (e) {
+ failure = e;
+ break;
+ }
+ }
+ if (failure !== null) {
+ // Every binding, not only the ones whose write RETURNED: a write that
+ // threw may still have landed, and one left holding the replacement is
+ // the split ownership this is atomic to prevent.
+ for (let i = bindings.length - 1; i >= 0; i--) {
+ try {
+ writeLiveAssetBinding(world, bindings[i], previous[i]);
+ } catch {
+ // The binding is gone; there is nothing to put back into it.
+ }
+ }
+ replacement.lease.release();
+ log.warn('asset', 'live asset rebind rolled back — a binding could not be written', failure);
+ return false;
+ }
+
+ scope.add(replacement.lease);
+ if (outgoing) {
+ scope.forget(outgoing);
+ outgoing.release();
+ }
+ return true;
+}
diff --git a/sdk/src/hotUpdateRebind.ts b/sdk/src/hotUpdateRebind.ts
index bbc2e4b30..7a9785a14 100644
--- a/sdk/src/hotUpdateRebind.ts
+++ b/sdk/src/hotUpdateRebind.ts
@@ -3,30 +3,41 @@
/**
* @file hotUpdateRebind.ts
* @brief Built-in hot-update rebinder — makes a hot update transparent to game
- * code. When applyUpdate / invalidate drops an asset it reports the
- * value that was bound; this reloads the ref (now resolved to the fresh
- * content) and swaps old→new in every live component that declares a
- * field of that asset type, so a scene that references an asset by
- * @uuid updates on screen with ZERO game code.
+ * code. When applyUpdate / invalidate ends an asset's era this reloads
+ * the ref (now resolved to the fresh content) and moves every live
+ * binding of it onto the new one, so a scene that references an asset
+ * by @uuid updates on screen with ZERO game code.
*
- * Which fields those are comes from `component.assetFields` — see
- * liveAssetBindings.ts for why it cannot be a list kept here.
+ * It is a transaction coordinator, not an owner: which fields hold the
+ * asset comes from `component.assetFields` (liveAssetBindings.ts), and
+ * the replacement is acquired once per owning scope and handed to that
+ * scope (liveAssetRebind.ts). What it acquires and cannot place, it
+ * gives back.
*
* Registered once per App (initRuntime). State lives in this closure —
* per install, not module-global — so realms don't share queues.
*/
import type { App } from './app/app';
import { Schedule, defineSystem, GetWorld } from './ecs/system';
+import { SceneOwner } from './ecs/component';
+import { SceneManager } from './scene/sceneManager';
+import type { Entity } from './types';
import type { Assets } from './asset/Assets';
-import {
- componentsBindingAssetType, findLiveAssetBindings, writeLiveAssetBinding,
-} from './asset/liveAssetBindings';
+import type { AssetScope, AssetLease } from './asset/AssetLease';
+import type { TextureResult } from './asset/AssetLoader';
+import { componentsBindingAssetType } from './asset/liveAssetBindings';
+import { migrateScopeBindings, ownerScopesOf } from './asset/liveAssetRebind';
+import { log } from './util/logger';
+
+/** A texture lease as a bound field holds it. */
+const textureHandleOf = (lease: AssetLease): unknown =>
+ (lease.value as TextureResult | null)?.handle;
export function installHotUpdateRebind(app: App, assets: Assets): void {
- // Refs whose asset was invalidated (with the handle bound before the drop),
- // awaiting a reload; and resolved old→new handle swaps awaiting application.
+ // Refs whose asset era ended (with the handle bound before the drop),
+ // awaiting the reload; and replacements awaiting their owner's transaction.
const pending: Array<{ ref: string; oldHandle: number }> = [];
- const swaps: Array<{ oldHandle: number; newHandle: number }> = [];
+ const ready: Array<{ oldHandle: number; scope: AssetScope; lease: AssetLease }> = [];
assets.onInvalidate((event) => {
// Textures only for now, said by reading the kind rather than by the event
@@ -36,23 +47,42 @@ export function installHotUpdateRebind(app: App, assets: Assets): void {
if (oldHandle) pending.push({ ref: event.ref, oldHandle });
});
+ /**
+ * The scope that owes a release for what this entity's fields hold. An
+ * entity no scene owns is the app's: nothing else outlives it, and an
+ * acquisition with no owner is one nobody can give back.
+ */
+ const ownerScopeOf = (entity: Entity): AssetScope => {
+ const owner = app.world.tryGet(entity, SceneOwner);
+ const scene = owner?.scene && app.hasResource(SceneManager)
+ ? app.getResource(SceneManager).assetScopeFor(owner.scene)
+ : null;
+ return scene ?? assets.appScope;
+ };
+
app.addSystemToSchedule(Schedule.Update, defineSystem(
[GetWorld()],
(world) => {
- // Kick a reload for each newly-invalidated ref; the async result (the
- // new handle) lands in `swaps` a frame or two later.
+ // One acquisition per owning scope; the async results land in
+ // `ready` a frame or two later, each with the scope it is for.
while (pending.length > 0) {
const { ref, oldHandle } = pending.shift()!;
- void assets.loadTexture(ref).then((tex) => {
- if (tex.handle !== oldHandle) swaps.push({ oldHandle, newHandle: tex.handle });
- });
- }
- while (swaps.length > 0) {
- const { oldHandle, newHandle } = swaps.shift()!;
- for (const binding of findLiveAssetBindings(world, 'texture', oldHandle)) {
- writeLiveAssetBinding(world, binding, newHandle);
+ for (const scope of ownerScopesOf(world, 'texture', oldHandle, ownerScopeOf)) {
+ void assets.acquireTexture(ref).then(
+ (lease) => { ready.push({ oldHandle, scope, lease }); },
+ (e: unknown) => {
+ log.warn('asset', `hot-update rebind: reloading "${ref}" failed; its holders keep the asset they have`, e);
+ },
+ );
}
}
+ while (ready.length > 0) {
+ const { oldHandle, scope, lease } = ready.shift()!;
+ migrateScopeBindings(
+ world, scope, 'texture', oldHandle,
+ { lease, boundValue: textureHandleOf }, ownerScopeOf,
+ );
+ }
},
{
name: 'HotUpdateRebindSystem',
diff --git a/sdk/src/scene/sceneManager.ts b/sdk/src/scene/sceneManager.ts
index 5c163c076..943be4a40 100644
--- a/sdk/src/scene/sceneManager.ts
+++ b/sdk/src/scene/sceneManager.ts
@@ -652,6 +652,16 @@ export class SceneManagerState {
instance.loadedByType.clear();
}
+ /**
+ * What the named scene acquired, so an owner-aware operation (a live asset
+ * replacement) can put a receipt where this scene will give it back.
+ *
+ * @internal
+ */
+ assetScopeFor(name: string): AssetScope | null {
+ return this.scenes_.get(name)?.assetScope ?? null;
+ }
+
pause(name: string): void {
const instance = this.scenes_.get(name);
if (!instance || instance.status !== 'running') return;
diff --git a/sdk/tests/hot-update-rebind.test.ts b/sdk/tests/hot-update-rebind.test.ts
index b803fd26b..2d7c11e16 100644
--- a/sdk/tests/hot-update-rebind.test.ts
+++ b/sdk/tests/hot-update-rebind.test.ts
@@ -23,7 +23,13 @@ import type { CppRegistry } from '../src/wasm';
import type { Entity } from '../src/types';
import { ensureBuiltinComponentsRegistered } from '../src/ecs/component';
import { installHotUpdateRebind } from '../src/hotUpdateRebind';
+import { SceneManager, SceneManagerState, type SceneContext } from '../src/scene/sceneManager';
+import { AssetScope } from '../src/asset/AssetLease';
+import { Sprite, MeshRenderer, ParticleEmitter, TrailRenderer } from '../src/ecs/component';
+import { UIVisual } from '../src/ui/core/ui-visual';
import { findLiveAssetBindings } from '../src/asset/liveAssetBindings';
+import { migrateScopeBindings } from '../src/asset/liveAssetRebind';
+import type { AssetLease } from '../src/asset/AssetLease';
// ---------------------------------------------------------------------------
// The C++ side, modelled: a component store that add/get/has/remove really move.
@@ -204,3 +210,181 @@ describe('the hot-update rebinder reaches every declared texture field', () => {
expect(findLiveAssetBindings(world, 'texture', 7)).toHaveLength(1);
});
});
+
+describe('a replacement is a transaction per owning scope', () => {
+ beforeEach(() => { pool = createPoolFake(); });
+
+ /** An App with scenes, whose world's C++ side is the store above. */
+ function sceneApp(): { app: App; assets: Assets; manager: SceneManagerState } {
+ const app = App.new();
+ connectFakeCpp(app.world);
+ const assets = buildAssets();
+ const manager = new SceneManagerState(app);
+ app.insertResource(SceneManager, manager);
+ installHotUpdateRebind(app, assets);
+ return { app, assets, manager };
+ }
+
+ /** A scene that acquires `ref` for itself and binds it to `fields`. */
+ function sceneHolding(
+ app: App, assets: Assets, ref: string,
+ fields: Array<{ component: AnyComponentDef; field: string }>,
+ ) {
+ return async (ctx: SceneContext): Promise<void> => {
+ const scope = new AssetScope();
+ const lease = await assets.acquireTexture(ref);
+ scope.add(lease);
+ ctx.trackAssetScope(scope);
+ for (const { component, field } of fields) {
+ const entity = ctx.spawn();
+ app.world.insert(entity, component, { [field]: lease.value.handle } as never);
+ }
+ };
+ }
+
+ const boundValues = (app: App, component: AnyComponentDef, field: string): number[] =>
+ app.world.getEntitiesWithComponents([component])
+ .map((e) => (app.world.get(e, component) as Record<string, number>)[field]);
+
+ it('two scenes holding one texture get one acquisition EACH', async () => {
+ // The cardinality the world-wide swap got wrong: it acquired once and
+ // moved both owners onto it, so one of the two receipts named an era
+ // nothing was drawing and the era both were drawing had one holder.
+ const { app, assets, manager } = sceneApp();
+ const base = assets.sizes().refRows;
+
+ manager.register({ name: 'a', setup: sceneHolding(app, assets, 'hero.png', [{ component: Sprite, field: 'texture' }]) });
+ manager.register({ name: 'b', setup: sceneHolding(app, assets, 'hero.png', [{ component: TrailRenderer, field: 'texture' }]) });
+ await manager.loadAdditive('a');
+ await manager.loadAdditive('b');
+
+ const before = assets.getTexture('hero.png')!.handle;
+ expect(assets.sizes().refRows).toBe(base + 2); // two owners, one era
+
+ assets.invalidate('hero.png');
+ await settle(app);
+
+ const after = assets.getTexture('hero.png')!.handle;
+ expect(after).not.toBe(before);
+ expect(boundValues(app, Sprite, 'texture')).toEqual([after]);
+ expect(boundValues(app, TrailRenderer, 'texture')).toEqual([after]);
+ // Two owners still, of the new era: one acquisition each, and the era
+ // they left has no holders.
+ expect(assets.sizes().refRows).toBe(base + 2);
+
+ await manager.unload('a');
+ // B is still drawing it, and still owes exactly one release.
+ expect(assets.sizes().refRows).toBe(base + 1);
+ expect(boundValues(app, TrailRenderer, 'texture')).toEqual([after]);
+
+ await manager.unload('b');
+ expect(assets.sizes().refRows).toBe(base); // nothing stranded
+ });
+
+ it('one scene\'s four fields move together, and it owes ONE release', async () => {
+ // Per scope, not per binding: a scene left holding the new era for some
+ // of its fields and the old one for the rest owes two receipts for one
+ // replacement, and nothing afterwards can say which field is which.
+ const { app, assets, manager } = sceneApp();
+ const base = assets.sizes().refRows;
+ const fields = [
+ { component: Sprite, field: 'texture' },
+ { component: UIVisual, field: 'texture' },
+ { component: MeshRenderer, field: 'normalMap' },
+ { component: ParticleEmitter, field: 'texture' },
+ ];
+ manager.register({ name: 'level', setup: sceneHolding(app, assets, 'hero.png', fields) });
+ await manager.loadAdditive('level');
+
+ const before = assets.getTexture('hero.png')!.handle;
+ expect(assets.sizes().refRows).toBe(base + 1);
+
+ assets.invalidate('hero.png');
+ await settle(app);
+
+ const after = assets.getTexture('hero.png')!.handle;
+ expect(after).not.toBe(before);
+ for (const { component, field } of fields) {
+ expect(boundValues(app, component, field), `${component._name}.${field}`).toEqual([after]);
+ }
+ expect(assets.sizes().refRows).toBe(base + 1); // one owner, one receipt
+
+ await manager.unload('level');
+ expect(assets.sizes().refRows).toBe(base);
+ });
+
+ it('an entity no scene owns is the app\'s, not nobody\'s', async () => {
+ // The rebinder must not keep what it acquires, and an acquisition with
+ // no owner is one nobody can ever give back — the leak this had.
+ const { app, assets } = sceneApp();
+ const base = assets.sizes().refRows;
+
+ const lease = await assets.acquireTexture('hero.png');
+ const entity = app.world.spawn();
+ app.world.insert(entity, Sprite, { texture: lease.value.handle });
+
+ assets.invalidate('hero.png');
+ await settle(app);
+ const after = assets.getTexture('hero.png')!.handle;
+ expect(boundValues(app, Sprite, 'texture')).toEqual([after]);
+
+ lease.release(); // the game lets go of its own era
+ expect(assets.sizes().refRows).toBe(base + 1); // the app owns the replacement
+ assets.releaseAll();
+ expect(assets.sizes().refRows).toBe(base); // and gives it back at teardown
+ });
+});
+
+describe('a scope migrates all of its bindings or none', () => {
+ /** A world whose Nth write refuses — the failure the rollback exists for. */
+ function worldFailingWriteAt(nth: number): World {
+ const world = new World();
+ connectFakeCpp(world);
+ let writes = 0;
+ const set = world.set.bind(world);
+ world.set = ((entity: never, component: never, data: never) => {
+ if (++writes === nth) throw new Error('component store refused the write');
+ return set(entity, component, data);
+ }) as typeof world.set;
+ return world;
+ }
+
+ it('puts back every binding it had already written, and gives the replacement back', () => {
+ const scope = new AssetScope();
+ let released = 0;
+ const outgoing = {
+ key: 'texture:hero.png', generation: 1, value: { handle: 11 },
+ release: () => { released++; },
+ };
+ scope.add(outgoing as never);
+
+ const world = worldFailingWriteAt(3);
+ const Widget = defineComponent(
+ 'RollbackTestWidget', { icon: 0 },
+ { assetFields: [{ field: 'icon', type: 'texture' }] },
+ );
+ const entities = [world.spawn(), world.spawn(), world.spawn(), world.spawn()];
+ for (const e of entities) world.insert(e, Widget, { icon: 11 });
+
+ let replacementReleased = 0;
+ const replacement = {
+ lease: {
+ key: 'texture:hero.png', generation: 2, value: { handle: 22 },
+ release: () => { replacementReleased++; },
+ },
+ boundValue: (lease: AssetLease) => (lease.value as { handle: number }).handle,
+ };
+ const migrated = migrateScopeBindings(
+ world, scope, 'texture', 11, replacement as never, () => scope,
+ );
+
+ expect(migrated).toBe(false);
+ // Every binding still holds the era the scope still owns...
+ for (const e of entities) expect((world.get(e, Widget) as { icon: number }).icon).toBe(11);
+ expect(released).toBe(0);
+ // ...and the replacement was given back rather than kept by anyone.
+ expect(replacementReleased).toBe(1);
+ expect(scope.size).toBe(1);
+ expect(scope.leases()[0]).toBe(outgoing);
+ });
+});
diff --git a/tools/check-live-asset-rebind.mjs b/tools/check-live-asset-rebind.mjs
index b687845e1..238316dc1 100644
--- a/tools/check-live-asset-rebind.mjs
+++ b/tools/check-live-asset-rebind.mjs
@@ -17,7 +17,10 @@
*
* 1. No file on the rebind path names an asset-bearing component type.
* 2. The walk goes through the registry and reads `assetFields`.
- * 3. The runtime scene loader hands the scene its receipts, not its paths.
+ * 3. The rebind path acquires by receipt. A `load*` hands back no receipt, so
+ * what it takes out of the ledger is a row nobody can give back — that is
+ * the leak the rebinder had, one row per successful hot update.
+ * 4. The runtime scene loader hands the scene its receipts, not its paths.
*
* Run: node tools/check-live-asset-rebind.mjs (exit 1 on violation)
*/
@@ -30,6 +33,7 @@ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
/** The files that answer "which live fields hold this asset?". */
const REBIND_PATH = [
'sdk/src/asset/liveAssetBindings.ts',
+ 'sdk/src/asset/liveAssetRebind.ts',
'sdk/src/hotUpdateRebind.ts',
];
@@ -119,6 +123,15 @@ for (const fn of ['findLiveAssetBindings', 'componentsBindingAssetType']) {
}
}
+// A replacement is acquired, never merely loaded: `load*` hands back no receipt.
+for (const file of REBIND_PATH) {
+ const code = stripComments(readFileSync(path.join(ROOT, file), 'utf8'));
+ const call = /\bload(?:Texture|Material|Font|Audio|Typed|Prefab|Mesh)\s*\(/.exec(code);
+ if (call) {
+ findings.push(`${file}:${code.slice(0, call.index).split('\n').length} takes an asset out with a load*, which hands back no receipt — acquire it.`);
+ }
+}
+
// A caller holding receipts must not hand over paths: a path-addressed release
// after a hot update gives back the oldest era, and what the paths omit is
// never given back at all.