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 release gives back the acquisition it names, not the oldest one

esengine08ffc85fa7b3
diff --git a/sdk/src/asset/AssetLease.ts b/sdk/src/asset/AssetLease.ts
new file mode 100644
index 000000000..1089fc369
--- /dev/null
+++ b/sdk/src/asset/AssetLease.ts
@@ -0,0 +1,64 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file AssetLease.ts
+ * @brief The receipt for one acquisition, and a scope that holds several.
+ *
+ * @details A path answers "which asset do I want?". A lease answers "which
+ * instance do I actually hold?" — and only the second one can be given
+ * back correctly once `invalidate()` has made two generations of the
+ * same path live at the same time.
+ */
+
+/** One acquisition, and the right to end it. */
+export interface AssetLease<T = unknown> {
+ readonly key: string;
+ /** Ledger-minted, so two eras never merge even if their values compare equal. */
+ readonly generation: number;
+ readonly value: T;
+ /** Give this one acquisition back. Calling twice is a no-op, not a double free. */
+ release(): void;
+}
+
+/**
+ * @brief Everything one owner acquired, released together.
+ *
+ * @details What a scene, a group or a document owns. It holds receipts rather
+ * than paths, so unloading releases what was actually acquired — not
+ * what the manifest says the owner would acquire if it loaded today.
+ * An acquisition that failed produced no lease, so there is nothing to
+ * release and nothing to guess about.
+ */
+export class AssetScope {
+ private leases_: AssetLease[] = [];
+
+ add<T>(lease: AssetLease<T>): AssetLease<T> {
+ this.leases_.push(lease as AssetLease);
+ return lease;
+ }
+
+ /** Hand back everything, in reverse acquisition order. */
+ releaseAll(): void {
+ // Reverse: a dependent acquired after what it depends on goes first.
+ for (let i = this.leases_.length - 1; i >= 0; i--) this.leases_[i].release();
+ this.leases_ = [];
+ }
+
+ /** Stop tracking one lease without releasing it — for an ownership transfer. */
+ forget(lease: AssetLease): boolean {
+ const i = this.leases_.indexOf(lease);
+ if (i < 0) return false;
+ this.leases_.splice(i, 1);
+ return true;
+ }
+
+ /** How many acquisitions this scope still owes. Diagnostics and tests. */
+ get size(): number {
+ return this.leases_.length;
+ }
+
+ /** @internal The receipts themselves — for a census, never to release behind the scope. */
+ leases(): readonly AssetLease[] {
+ return this.leases_;
+ }
+}
diff --git a/sdk/src/asset/AssetRefLedger.ts b/sdk/src/asset/AssetRefLedger.ts
index 0fdbe3a9f..d7316d755 100644
--- a/sdk/src/asset/AssetRefLedger.ts
+++ b/sdk/src/asset/AssetRefLedger.ts
@@ -2,13 +2,19 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
* @file AssetRefLedger.ts
- * @brief Who still holds an asset, per generation.
+ * @brief Who still holds an asset, per generation, with a receipt per acquire.
*
* @details A cache key is not an identity. `invalidate()` mints a new
* generation of the same key while the previous one still has holders,
- * so a ledger with one slot per key attributes their release to the
- * replacement — and the resource they were actually handed is left
- * with nobody able to free it.
+ * so a key-addressed release cannot know which one the caller was
+ * handed — it can only guess, and guessing frees somebody else's
+ * asset while leaving the caller's with nobody able to free it.
+ *
+ * So an acquire hands back a LEASE: the receipt for that one
+ * acquisition. Releasing means giving the receipt back, not naming a
+ * path and hoping. The generation id is minted here rather than taken
+ * from the value, because a loader may hand out an `===` equal value
+ * for a later generation and two eras must never merge.
*
* One implementation, because there were two: textures kept handles
* and generic assets kept loader entries, and only the texture one had
@@ -16,61 +22,112 @@
* business; the accounting is not.
*/
+/** The receipt for one acquisition. Give it back to release exactly that one. */
+export interface AssetRefLease<T> {
+ readonly key: string;
+ /** Ledger-minted. Distinguishes eras even when their values compare equal. */
+ readonly generation: number;
+ readonly value: T;
+}
+
+interface LeaseImpl<T> extends AssetRefLease<T> {
+ /** A receipt spends once; giving it back twice must not drop a stranger's reference. */
+ spent: boolean;
+}
+
/** One generation: the value its holders were given, and how many hold it. */
export interface AssetRefGeneration<T> {
+ readonly id: number;
readonly value: T;
count: number;
+ /** Superseded by invalidate(): still held, but no new holder joins it. */
+ superseded: boolean;
}
export class AssetRefLedger<T> {
private byKey_ = new Map<string, Array<AssetRefGeneration<T>>>();
+ private nextId_ = 1;
- /** Record one more holder of `value` under `key`. */
- acquire(key: string, value: T): void {
+ /**
+ * Record one more holder of `value` under `key` and hand back its receipt.
+ *
+ * Joins the key's current generation when it is holding the same value —
+ * that is a cache hit, and both holders really do share one asset. A
+ * superseded generation is never joined: its era is over.
+ */
+ acquire(key: string, value: T): AssetRefLease<T> {
let generations = this.byKey_.get(key);
if (!generations) {
generations = [];
this.byKey_.set(key, generations);
}
- const existing = generations.find((g) => g.value === value);
- if (existing) existing.count++;
- else generations.push({ value, count: 1 });
+ const current = generations[generations.length - 1];
+ let generation: AssetRefGeneration<T>;
+ if (current && !current.superseded && current.value === value) {
+ current.count++;
+ generation = current;
+ } else {
+ generation = { id: this.nextId_++, value, count: 1, superseded: false };
+ generations.push(generation);
+ }
+ const lease: LeaseImpl<T> = { key, generation: generation.id, value, spent: false };
+ return lease;
}
/**
- * Drop one reference from the OLDEST generation of `key`; `exhausted` says
- * the caller now owns the disposal. Oldest first so a superseded generation
- * drains as its holders let go — they are indistinguishable through a
- * key-addressed API, and a release naming the old value never comes.
+ * The key's current generation is over: its holders keep what they have and
+ * still owe a release, but the next acquire starts a new era rather than
+ * joining theirs. Called when the cache entry is invalidated.
*/
- release(key: string): { value: T; exhausted: boolean } | undefined {
+ supersede(key: string): void {
const generations = this.byKey_.get(key);
- if (!generations || generations.length === 0) return undefined;
+ const current = generations?.[generations.length - 1];
+ if (current) current.superseded = true;
+ }
- const oldest = generations[0];
- oldest.count--;
- if (oldest.count > 0) return { value: oldest.value, exhausted: false };
+ /**
+ * Give back one receipt; `exhausted` says the caller now owns the disposal.
+ *
+ * A receipt the ledger no longer knows is a no-op rather than an error:
+ * a wholesale {@link drain} already took that reference, and taking it
+ * again is the double free.
+ */
+ release(lease: AssetRefLease<T>): { value: T; exhausted: boolean } | undefined {
+ const impl = lease as LeaseImpl<T>;
+ if (impl.spent) return undefined;
+ const generations = this.byKey_.get(lease.key);
+ const index = generations?.findIndex((g) => g.id === lease.generation) ?? -1;
+ if (!generations || index < 0) return undefined;
- generations.shift();
- if (generations.length === 0) this.byKey_.delete(key);
- return { value: oldest.value, exhausted: true };
+ impl.spent = true;
+ const generation = generations[index];
+ if (--generation.count > 0) return { value: generation.value, exhausted: false };
+
+ generations.splice(index, 1);
+ if (generations.length === 0) this.byKey_.delete(lease.key);
+ return { value: generation.value, exhausted: true };
}
/**
- * Drop one reference to a SPECIFIC value, naming what it means rather than
- * taking the oldest. A no-op when the ledger no longer knows it — someone
- * else already took that reference, and taking it again is the double free.
+ * Drop one reference to `key` without a receipt, oldest generation first.
+ *
+ * The compatibility door for callers that only ever knew a path. It is
+ * exact while a key has ONE generation, which is every key that was never
+ * invalidated; `ambiguous` says it had to guess, so a caller that can carry
+ * a lease is asked to. See {@link release}.
*/
- releaseValue(key: string, value: T): boolean {
+ releaseOldest(key: string): { value: T; exhausted: boolean; ambiguous: boolean } | undefined {
const generations = this.byKey_.get(key);
- const index = generations?.findIndex((g) => g.value === value) ?? -1;
- if (!generations || index < 0) return false;
+ if (!generations || generations.length === 0) return undefined;
+ const ambiguous = generations.length > 1;
- const generation = generations[index];
- if (--generation.count > 0) return false;
- generations.splice(index, 1);
+ const oldest = generations[0];
+ oldest.count--;
+ if (oldest.count > 0) return { value: oldest.value, exhausted: false, ambiguous };
+
+ generations.shift();
if (generations.length === 0) this.byKey_.delete(key);
- return true;
+ return { value: oldest.value, exhausted: true, ambiguous };
}
/** Every live value, and forget them all. For a wholesale teardown. */
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.ts
index 480ee2c6b..eebc0d0a5 100644
--- a/sdk/src/asset/Assets.ts
+++ b/sdk/src/asset/Assets.ts
@@ -18,7 +18,8 @@ import type { CppResourceManager } from '../wasm';
import { requireResourceManager, getResourceManager, evictTextureDimensions } from '../wasm/resourceManager';
import type { TextureImportSettings, TextureImportSettingsResolver } from './loaders/TextureLoader';
import { TextureLoader, textureResidencyKey } from './loaders/TextureLoader';
-import { AssetRefLedger } from './AssetRefLedger';
+import { AssetRefLedger, type AssetRefLease } from './AssetRefLedger';
+import type { AssetLease } from './AssetLease';
import { SpineAssetLoader } from './loaders/SpineAssetLoader';
import { MaterialAssetLoader } from './loaders/MaterialAssetLoader';
import { MeshAssetLoader } from './loaders/MeshAssetLoader';
@@ -265,6 +266,21 @@ export type AssetRefResolver = (ref: string) => string | null;
* renaming or moving the file breaks nothing. Not hand-written; the realm's
* resolver turns it back into the path above before any fetch.
*/
+/**
+ * A path-addressed release had more than one generation to choose from, so it
+ * took the oldest and may have freed somebody else's asset. Reported once per
+ * key: the caller that can carry a lease should, and one that cannot needs to
+ * hear it once, not every frame.
+ */
+const ambiguousWarned_ = new Set<string>();
+function warnAmbiguousRelease_(key: string): void {
+ if (ambiguousWarned_.has(key)) return;
+ ambiguousWarned_.add(key);
+ log.warn('asset',
+ `release("${key}") had more than one live generation and released the oldest — `
+ + 'which may not be the one the caller holds. Release it by its lease instead.');
+}
+
export class Assets {
readonly backend: Backend;
readonly catalog: Catalog;
@@ -443,6 +459,12 @@ export class Assets {
}
private async loadTextureVariant_(ref: string, flip: boolean): Promise<TextureResult> {
+ return (await this.acquireTextureVariant_(ref, flip)).result;
+ }
+
+ private async acquireTextureVariant_(
+ ref: string, flip: boolean,
+ ): Promise<{ result: TextureResult; lease: AssetRefLease<number> }> {
const path = this.resolveLoadPath_(ref);
const cacheKey = this.textureCacheKey_(path, flip);
const settings = this.textureImportResolver_?.(ref);
@@ -471,7 +493,7 @@ export class Assets {
`Assets were released while "${ref}" was loading; its texture has no owner. Load it again.`,
);
}
- this.textureRefs_.acquire(cacheKey, result.handle);
+ const lease = this.textureRefs_.acquire(cacheKey, result.handle);
this.recordHandlePath_('texture', result.handle, path);
// The 9-slice border belongs to the IMAGE, so it rides its import
// settings and is stamped onto the handle here — the one place every
@@ -482,7 +504,7 @@ export class Assets {
const b = settings.sliceBorder;
requireResourceManager().setTextureMetadata(result.handle, b.left, b.right, b.top, b.bottom);
}
- return result;
+ return { result, lease };
}
/**
@@ -559,7 +581,11 @@ export class Assets {
}
async loadAnimClip(ref: string): Promise<AnimClipResult> {
- const result = await this.loadTyped<AnimClipResult>('anim-clip', ref);
+ return (await this.acquireAnimClip_(ref)).value;
+ }
+
+ private async acquireAnimClip_(ref: string): Promise<AssetLease<AnimClipResult>> {
+ const { value: result, lease } = await this.acquireTyped_<AnimClipResult>('anim-clip', ref);
// The loader registers the clip under its RESOLVED load path (an absolute
// URL in realms whose ref resolver returns fetchable URLs, e.g. the play
// realm), but SpriteAnimator/Animator reference clips by the SERIALIZED
@@ -572,7 +598,10 @@ export class Assets {
const clip = anim.getClip(result.clipId);
if (clip && !anim.getClip(ref)) anim.aliasClip(ref, clip);
}
- return result;
+ return {
+ key: lease.key, generation: lease.generation, value: result,
+ release: () => this.releaseTypedLease('anim-clip', lease),
+ };
}
async loadTilemap(ref: string): Promise<TilemapResult> {
@@ -1143,27 +1172,27 @@ export class Assets {
// with hundreds of assets doesn't saturate the network or tie up
// image decoders all at once.
const tasks: Array<() => Promise<void>> = [];
- const pushHandleLoad = (
- paths: Set<string>, loader: (p: string) => Promise<{ handle: number }>,
- handles: Map<string, number>, label: string,
+ /**
+ * One task per path. The receipt is recorded only when the acquire
+ * SUCCEEDED — a failed load owns nothing, so there is nothing for the
+ * scene to give back and nothing to guess about at unload.
+ */
+ const pushAcquire = <T>(
+ paths: Set<string>,
+ acquire: (p: string) => Promise<AssetLease<T>>,
+ label: string,
+ handles?: Map<string, number>,
): void => {
for (const path of paths) {
tasks.push(() =>
- loader(path).then(r => { handles.set(path, r.handle); }).catch(e => {
- log.warn('asset', `Failed to load ${label}: ${path}`, e);
- handles.set(path, 0);
- recordFailure(path, label, e);
- }),
- );
- }
- };
- const pushFireAndForget = (
- paths: Set<string>, loader: (p: string) => Promise<unknown>, label: string,
- ): void => {
- for (const path of paths) {
- tasks.push(() =>
- loader(path).then(() => {}).catch(e => {
+ acquire(path).then(lease => {
+ releaseCallbacks.push(() => lease.release());
+ if (handles) {
+ handles.set(path, (lease.value as { handle?: number } | null)?.handle ?? 0);
+ }
+ }).catch(e => {
log.warn('asset', `Failed to load ${label}: ${path}`, e);
+ handles?.set(path, 0);
recordFailure(path, label, e);
}),
);
@@ -1176,18 +1205,19 @@ export class Assets {
// which is the resolver's documented contract. Resolution happens inside
// loadTexture anyway, so the bytes fetched are identical either way —
// feeding it the resolved path only strips the lookup of its key.
- pushHandleLoad(
+ pushAcquire(
texturePaths,
- p => this.loadTexture(discovered.rawFor.get(p) ?? p),
- textureHandles,
+ p => this.acquireTexture(discovered.rawFor.get(p) ?? p),
'texture',
+ textureHandles,
);
- pushHandleLoad(materialPaths, p => this.loadMaterial(p), materialHandles, 'material');
- pushHandleLoad(fontPaths, p => this.loadFont(p), fontHandles, 'font');
- pushHandleLoad(meshPaths, p => this.loadTyped<{ handle: number }>('mesh', p), meshHandles, 'mesh');
- pushHandleLoad(environmentPaths,
- p => this.loadTyped<{ handle: number }>('environment', p),
- environmentHandles, 'environment');
+ pushAcquire(materialPaths, p => this.acquireTyped<MaterialResult>('material', p),
+ 'material', materialHandles);
+ pushAcquire(fontPaths, p => this.acquireTyped<FontResult>('font', p), 'font', fontHandles);
+ pushAcquire(meshPaths, p => this.acquireTyped<{ handle: number }>('mesh', p),
+ 'mesh', meshHandles);
+ pushAcquire(environmentPaths, p => this.acquireTyped<{ handle: number }>('environment', p),
+ 'environment', environmentHandles);
// The runtime scene loader owns spine as a two-phase load+apply through the
// SpineManager (skeletons must bind to spawned entities); it opts out here so
// spine page textures / virtual-FS writes aren't done twice.
@@ -1201,17 +1231,17 @@ export class Assets {
);
}
}
- pushFireAndForget(animClipPaths, p => this.loadAnimClip(p), 'anim-clip');
- pushFireAndForget(tilemapPaths, p => this.loadTilemap(p), 'tilemap');
- pushFireAndForget(tilesetPaths, p => this.loadTileset(p), 'tileset');
- pushFireAndForget(timelinePaths, p => this.loadTimeline(p), 'timeline');
- pushFireAndForget(audioPaths, p => this.loadAudio(p), 'audio');
+ pushAcquire(animClipPaths, p => this.acquireAnimClip_(p), 'anim-clip');
+ pushAcquire(tilemapPaths, p => this.acquireTyped('tilemap', p), 'tilemap');
+ pushAcquire(tilesetPaths, p => this.acquireTyped('tileset', p), 'tileset');
+ pushAcquire(timelinePaths, p => this.acquireTyped('timeline', p), 'timeline');
+ pushAcquire(audioPaths, p => this.acquireTyped('audio', p), 'audio');
// FSM/BT loaders register the parsed definition into the shared AI store
// under the asset path, so a StateMachineAgent/BehaviorTreeAgent whose
// fsm/bt is that path resolves once the scene finishes preloading.
- pushFireAndForget(fsmPaths, p => this.loadTyped('statemachine', p), 'statemachine');
- pushFireAndForget(btPaths, p => this.loadTyped('behaviortree', p), 'behaviortree');
- pushFireAndForget(animatorPaths, p => this.loadTyped('animatorcontroller', p), 'animatorcontroller');
+ pushAcquire(fsmPaths, p => this.acquireTyped('statemachine', p), 'statemachine');
+ pushAcquire(btPaths, p => this.acquireTyped('behaviortree', p), 'behaviortree');
+ pushAcquire(animatorPaths, p => this.acquireTyped('animatorcontroller', p), 'animatorcontroller');
const totalCount = tasks.length;
onProgress?.(0, totalCount);
@@ -1311,6 +1341,34 @@ export class Assets {
}
}
+ // =========================================================================
+ // Acquire — the same loads, but handing back an ownership receipt
+ // =========================================================================
+
+ /**
+ * Load a texture and get the receipt for THIS acquisition.
+ *
+ * The difference from {@link loadTexture} is who can be released correctly
+ * afterwards: a path names an asset, a lease names the instance this caller
+ * was handed. After `invalidate()` those are no longer the same thing.
+ */
+ async acquireTexture(ref: string): Promise<AssetLease<TextureResult>> {
+ const { result, lease } = await this.acquireTextureVariant_(ref, true);
+ return {
+ key: lease.key, generation: lease.generation, value: result,
+ release: () => this.releaseTextureLease(lease),
+ };
+ }
+
+ /** {@link acquireTexture} for everything that goes through a typed loader. */
+ async acquireTyped<T>(type: string, ref: string): Promise<AssetLease<T>> {
+ const { value, lease } = await this.acquireTyped_<T>(type, ref);
+ return {
+ key: lease.key, generation: lease.generation, value,
+ release: () => this.releaseTypedLease(type, lease),
+ };
+ }
+
// =========================================================================
// Release
// =========================================================================
@@ -1319,23 +1377,34 @@ export class Assets {
const path = this.resolveLoadPath_(ref);
for (const flip of [true, false]) {
const key = this.textureCacheKey_(path, flip);
- const dropped = this.textureRefs_.release(key);
- if (!dropped?.exhausted) continue;
-
- // Last SDK reference: drop our one C++ ref. The pool decides what
- // that means — free immediately (no budget), or retain as an
- // evictable cache entry that the next load revives by key.
- requireResourceManager().releaseTexture(dropped.value);
- evictTextureDimensions(dropped.value);
- // Only when it is still the cached value: a superseded handle left
- // the cache when its generation ended, and the entry there now
- // belongs to a generation with holders of its own.
- if (this.textureCache_.get(key)?.handle === dropped.value) {
- this.textureCache_.delete(key);
- }
+ const dropped = this.textureRefs_.releaseOldest(key);
+ if (!dropped) continue;
+ if (dropped.ambiguous) warnAmbiguousRelease_(key);
+ if (dropped.exhausted) this.disposeTexture_(key, dropped.value);
}
}
+ /**
+ * Give back one texture acquisition by its receipt — exact even when
+ * `invalidate()` left two generations of the same path live.
+ */
+ releaseTextureLease(lease: AssetRefLease<number>): void {
+ const dropped = this.textureRefs_.release(lease);
+ if (dropped?.exhausted) this.disposeTexture_(lease.key, dropped.value);
+ }
+
+ /** The last SDK reference to a texture handle is gone: let the C++ pool decide. */
+ private disposeTexture_(key: string, handle: number): void {
+ // The pool decides what that means — free immediately (no budget), or
+ // retain as an evictable cache entry that the next load revives by key.
+ requireResourceManager().releaseTexture(handle);
+ evictTextureDimensions(handle);
+ // Only when it is still the cached value: a superseded handle left the
+ // cache when its generation ended, and the entry there now belongs to a
+ // generation with holders of its own.
+ if (this.textureCache_.get(key)?.handle === handle) this.textureCache_.delete(key);
+ }
+
releaseFont(ref: string): void {
this.releaseTyped('font', ref);
}
@@ -1400,12 +1469,28 @@ export class Assets {
// invalidate() is out of the cache while its holders still owe a
// release, and returning here left their asset unreachable.
const key = `${type}:${path}`;
- const dropped = this.genericRefs_.release(key);
+ const dropped = this.genericRefs_.releaseOldest(key);
+ if (!dropped) return;
+ if (dropped.ambiguous) warnAmbiguousRelease_(key);
+ if (dropped.exhausted) this.disposeGeneric_(type, path, dropped.value);
+ }
+
+ /**
+ * Give back one typed acquisition by its receipt — exact even when
+ * `invalidate()` left two generations of the same path live.
+ */
+ releaseTypedLease(type: string, lease: AssetRefLease<unknown>): void {
+ const dropped = this.genericRefs_.release(lease);
if (!dropped?.exhausted) return;
+ const path = lease.key.slice(type.length + 1);
+ this.disposeGeneric_(type, path, dropped.value);
+ }
- this.loaders_.get(type)?.unload(dropped.value, this.getLoadContext_());
+ /** The last reference to a typed asset is gone: hand it to its loader. */
+ private disposeGeneric_(type: string, path: string, value: unknown): void {
+ this.loaders_.get(type)?.unload(value, this.getLoadContext_());
const cache = this.genericCache_.get(type);
- if (cache && cache.get(path) === dropped.value) cache.delete(path);
+ if (cache && cache.get(path) === value) cache.delete(path);
}
/**
@@ -1442,7 +1527,10 @@ export class Assets {
if (this.textureCache_.invalidate(key)) hit = true;
// The ledger is NOT dropped: holders of the outgoing generation
// still owe a release, and forgetting them is what stranded their
- // texture with nobody able to free it.
+ // texture with nobody able to free it. Its era ends here, though —
+ // the next acquire opens a generation of its own even if the pool
+ // hands back a numerically equal handle.
+ this.textureRefs_.supersede(key);
if (typeof rm?.invalidateTexturePath === 'function') {
if (rm.invalidateTexturePath(key)) hit = true;
}
@@ -1451,7 +1539,9 @@ export class Assets {
// Generic caches: material / font / anim-clip / tilemap / timeline / audio / prefab.
for (const [type, cache] of this.genericCache_.entries()) {
if (cache.invalidate(path)) hit = true;
- // The ledger stays: the outgoing generation's holders still owe a release.
+ // The ledger stays: the outgoing generation's holders still owe a
+ // release. Its era is closed so the next acquire cannot join it.
+ this.genericRefs_.supersede(`${type}:${path}`);
}
// Loader-owned residency (e.g. the AudioAPI warm cache) can outlive
@@ -1734,6 +1824,12 @@ export class Assets {
}
private async loadTyped<T>(type: string, ref: string): Promise<T> {
+ return (await this.acquireTyped_<T>(type, ref)).value;
+ }
+
+ private async acquireTyped_<T>(
+ type: string, ref: string,
+ ): Promise<{ value: T; lease: AssetRefLease<unknown> }> {
const loader = this.loaders_.get(type) as AssetLoader<T> | undefined;
if (!loader) {
throw new Error(`No loader registered for type: ${type}`);
@@ -1749,10 +1845,10 @@ export class Assets {
const result = await (cache.getOrLoad(path, () =>
loader.load(path, this.getLoadContext_()),
) as Promise<T>);
- this.genericRefs_.acquire(`${type}:${path}`, result);
+ const lease = this.genericRefs_.acquire(`${type}:${path}`, result);
const handle = (result as { handle?: unknown } | null)?.handle;
if (typeof handle === 'number' && handle !== 0) this.recordHandlePath_(type, handle, path);
- return result;
+ return { value: result, lease };
}
private getLoadContext_(): LoadContext {
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index f1dde27de..9882489f4 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -125,6 +125,7 @@ export {
BUILTIN_MESH_TEMPLATES, builtinMeshTemplate, isBuiltinMeshRef,
type BuiltinMeshTemplate,
} from './asset/builtinMeshes';
+export { AssetScope, type AssetLease } from './asset/AssetLease';
export { createCanvasTexture, type CanvasTexture } from './asset/canvasTexture';
export type { GlImageSource } from './asset/glTextureUpload';
diff --git a/sdk/tests/asset-generation-ownership.test.ts b/sdk/tests/asset-generation-ownership.test.ts
new file mode 100644
index 000000000..74ac057bf
--- /dev/null
+++ b/sdk/tests/asset-generation-ownership.test.ts
@@ -0,0 +1,126 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file asset-generation-ownership.test.ts
+ * @brief A release gives back the acquisition it names, not the oldest one
+ * sharing its path.
+ *
+ * @details `invalidate()` leaves two generations of one path live at once: the
+ * holders of the outgoing one still owe a release. A path-addressed
+ * release cannot tell them apart, so it took the oldest — freeing an
+ * asset its holder was still using, and stranding the newer one with
+ * nobody able to free it. These pin the receipt-based path instead.
+ */
+import { describe, it, expect, vi } from 'vitest';
+import { Assets } from '../src/asset/Assets';
+import { AssetRefLedger } from '../src/asset/AssetRefLedger';
+import { AssetScope } from '../src/asset/AssetLease';
+import type { Backend } from '../src/asset/Backend';
+
+vi.mock('../src/wasm/resourceManager', () => ({
+ requireResourceManager: () => ({ releaseTexture: vi.fn(), invalidateTexturePath: vi.fn(() => false) }),
+ getResourceManager: () => null,
+ evictTextureDimensions: vi.fn(),
+}));
+
+/** A generic asset whose every generation is a distinguishable object. */
+function makeAssets(unloaded: string[]) {
+ let n = 0;
+ const assets = Assets.create({
+ backend: {
+ fetchBinary: vi.fn(async () => new ArrayBuffer(8)),
+ fetchText: vi.fn(async () => '{}'),
+ resolveUrl: (p: string) => `http://test/${p}`,
+ } as unknown as Backend,
+ module: { _malloc: vi.fn(() => 0), _free: vi.fn(), HEAPU8: new Uint8Array(16), GL: null, FS: null } as never,
+ });
+ assets.register<{ id: string }>({
+ type: 'font',
+ load: async () => ({ id: `gen${++n}` }),
+ unload: (v: { id: string }) => { unloaded.push(v.id); },
+ } as never);
+ return assets;
+}
+
+describe('asset ownership is generation-exact', () => {
+ it('a holder of the new generation does not free the old one', async () => {
+ const unloaded: string[] = [];
+ const assets = makeAssets(unloaded);
+ const base = assets.sizes().refRows;
+
+ const a = await assets.acquireTyped<{ id: string }>('font', 'f.ttf');
+ assets.invalidate('f.ttf'); // A keeps gen1, still owes a release
+ const b = await assets.acquireTyped<{ id: string }>('font', 'f.ttf');
+ expect(a.value.id).toBe('gen1');
+ expect(b.value.id).toBe('gen2');
+ expect(a.generation).not.toBe(b.generation);
+
+ b.release(); // B lets go of gen2
+ expect(unloaded).toEqual(['gen2']); // ...and gen1 is untouched
+ expect(unloaded).not.toContain(a.value.id);
+
+ a.release(); // A lets go of gen1
+ expect(unloaded).toEqual(['gen2', 'gen1']);
+ expect(assets.sizes().refRows).toBe(base); // the ledger balances
+ });
+
+ it('two holders of ONE generation still share it', async () => {
+ const unloaded: string[] = [];
+ const assets = makeAssets(unloaded);
+ const a = await assets.acquireTyped<{ id: string }>('font', 'f.ttf');
+ const b = await assets.acquireTyped<{ id: string }>('font', 'f.ttf');
+ expect(a.generation).toBe(b.generation); // a cache hit is one era
+
+ a.release();
+ expect(unloaded).toEqual([]); // still pinned by B
+ b.release();
+ expect(unloaded).toEqual(['gen1']);
+ });
+
+ it('giving the same receipt back twice is a no-op, not a double free', async () => {
+ const unloaded: string[] = [];
+ const assets = makeAssets(unloaded);
+ const a = await assets.acquireTyped<{ id: string }>('font', 'f.ttf');
+ const b = await assets.acquireTyped<{ id: string }>('font', 'f.ttf');
+
+ a.release();
+ a.release(); // the bug this prevents
+ expect(unloaded).toEqual([]); // B's reference survives
+ b.release();
+ expect(unloaded).toEqual(['gen1']);
+ });
+
+ it('an era closed by invalidate is never rejoined, even by an equal value', () => {
+ // The ledger mints the generation id, so a loader handing back an `===`
+ // equal value after invalidate cannot merge two eras.
+ const ledger = new AssetRefLedger<string>();
+ const first = ledger.acquire('k', 'SAME');
+ ledger.supersede('k');
+ const second = ledger.acquire('k', 'SAME');
+ expect(second.generation).not.toBe(first.generation);
+
+ expect(ledger.release(second)?.exhausted).toBe(true);
+ expect(ledger.generations('k').map((g) => g.id)).toEqual([first.generation]);
+ expect(ledger.release(first)?.exhausted).toBe(true);
+ expect(ledger.rows).toBe(0);
+ });
+
+ it('a scope releases what it actually acquired', async () => {
+ const unloaded: string[] = [];
+ const assets = makeAssets(unloaded);
+ const base = assets.sizes().refRows;
+ const scope = new AssetScope();
+
+ scope.add(await assets.acquireTyped('font', 'a.ttf'));
+ scope.add(await assets.acquireTyped('font', 'b.ttf'));
+ assets.invalidate('a.ttf');
+ scope.add(await assets.acquireTyped('font', 'a.ttf')); // a second era of a.ttf
+ expect(scope.size).toBe(3);
+
+ scope.releaseAll();
+ expect(unloaded.sort()).toEqual(['gen1', 'gen2', 'gen3']);
+ expect(assets.sizes().refRows).toBe(base);
+ scope.releaseAll(); // idempotent
+ expect(unloaded).toHaveLength(3);
+ });
+});