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(assets): one reference ledger, so the fix reaches every asset kind

esenginef021f81da63a
diff --git a/sdk/src/asset/AssetRefLedger.ts b/sdk/src/asset/AssetRefLedger.ts
new file mode 100644
index 000000000..db9f2401c
--- /dev/null
+++ b/sdk/src/asset/AssetRefLedger.ts
@@ -0,0 +1,100 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file AssetRefLedger.ts
+ * @brief Who still holds an asset, per generation.
+ *
+ * @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.
+ *
+ * One implementation, because there were two: textures kept handles
+ * and generic assets kept loader entries, and only the texture one had
+ * been taught about generations. The kind of resource is the caller's
+ * business; the accounting is not.
+ */
+
+/** One generation: the value its holders were given, and how many hold it. */
+export interface AssetRefGeneration<T> {
+ readonly value: T;
+ count: number;
+}
+
+export class AssetRefLedger<T> {
+ private byKey_ = new Map<string, Array<AssetRefGeneration<T>>>();
+
+ /** Record one more holder of `value` under `key`. */
+ acquire(key: string, value: T): void {
+ 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 });
+ }
+
+ /**
+ * 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.
+ */
+ release(key: string): { value: T; exhausted: boolean } | undefined {
+ const generations = this.byKey_.get(key);
+ if (!generations || generations.length === 0) return undefined;
+
+ const oldest = generations[0];
+ oldest.count--;
+ if (oldest.count > 0) return { value: oldest.value, exhausted: false };
+
+ generations.shift();
+ if (generations.length === 0) this.byKey_.delete(key);
+ return { value: oldest.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.
+ */
+ releaseValue(key: string, value: T): boolean {
+ const generations = this.byKey_.get(key);
+ const index = generations?.findIndex((g) => g.value === value) ?? -1;
+ if (!generations || index < 0) return false;
+
+ const generation = generations[index];
+ if (--generation.count > 0) return false;
+ generations.splice(index, 1);
+ if (generations.length === 0) this.byKey_.delete(key);
+ return true;
+ }
+
+ /** Every live value, and forget them all. For a wholesale teardown. */
+ drain(): Array<{ key: string; value: T }> {
+ const out: Array<{ key: string; value: T }> = [];
+ for (const [key, generations] of this.byKey_) {
+ for (const generation of generations) out.push({ key, value: generation.value });
+ }
+ this.byKey_.clear();
+ return out;
+ }
+
+ /** Keys with at least one live reference. */
+ get size(): number {
+ return this.byKey_.size;
+ }
+
+ /** @internal Live generations of one key, oldest first — diagnostics and tests. */
+ generations(key: string): readonly AssetRefGeneration<T>[] {
+ return this.byKey_.get(key) ?? [];
+ }
+
+ /** @internal The whole ledger, for the resource census. */
+ entries(): ReadonlyMap<string, readonly AssetRefGeneration<T>[]> {
+ return this.byKey_;
+ }
+}
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.ts
index c91490081..0be6a6b29 100644
--- a/sdk/src/asset/Assets.ts
+++ b/sdk/src/asset/Assets.ts
@@ -18,6 +18,7 @@ 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 { SpineAssetLoader } from './loaders/SpineAssetLoader';
import { MaterialAssetLoader } from './loaders/MaterialAssetLoader';
import { FontAssetLoader } from './loaders/FontAssetLoader';
@@ -235,14 +236,8 @@ export class Assets {
// owner; release its GL handle so it doesn't leak VRAM.
requireResourceManager().releaseTexture(result.handle);
});
- /**
- * Live texture references per cache key, oldest generation first.
- *
- * Carries the HANDLE, not just a count: invalidate() mints a new generation
- * while the previous still has holders, and one slot per key attributed
- * their release to the replacement — a texture stranded per hot reload.
- */
- private textureRefs_ = new Map<string, Array<{ handle: number; count: number }>>();
+ /** Live texture references per cache key. See {@link AssetRefLedger}. */
+ private textureRefs_ = new AssetRefLedger<number>();
/**
* Bumped by releaseAll(). A load in flight across one has no owner left: the
@@ -259,7 +254,7 @@ export class Assets {
* Same contract as textures: every load*() increments, every release*()
* decrements, and the loader's unload runs only at zero — so an asset
* shared by two scenes survives the first scene's unload. */
- private genericRefCounts_ = new Map<string, number>();
+ private genericRefs_ = new AssetRefLedger<unknown>();
private loadContext_: LoadContext | null = null;
private assetRefResolver_: AssetRefResolver | null = null;
private assetRegistry_: AssetRegistry | null = null;
@@ -342,7 +337,7 @@ export class Assets {
`Assets were released while "${ref}" was loading; its texture has no owner. Load it again.`,
);
}
- this.acquireTextureRef_(cacheKey, result.handle);
+ 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
@@ -1190,45 +1185,22 @@ export class Assets {
// Release
// =========================================================================
- /** Record one more holder of `handle` under `cacheKey`. */
- private acquireTextureRef_(cacheKey: string, handle: number): void {
- let generations = this.textureRefs_.get(cacheKey);
- if (!generations) {
- generations = [];
- this.textureRefs_.set(cacheKey, generations);
- }
- const existing = generations.find((g) => g.handle === handle);
- if (existing) existing.count++;
- else generations.push({ handle, count: 1 });
- }
-
releaseTexture(ref: string): void {
const path = this.resolveLoadPath_(ref);
for (const flip of [true, false]) {
const key = this.textureCacheKey_(path, flip);
- const generations = this.textureRefs_.get(key);
- if (!generations || generations.length === 0) continue;
-
- // Oldest first, so a superseded generation drains as its holders let
- // go. Holders are indistinguishable through a ref-keyed API, and a
- // release naming the old handle never comes.
- const oldest = generations[0];
- oldest.count--;
- if (oldest.count > 0) continue;
-
- generations.shift();
- if (generations.length === 0) this.textureRefs_.delete(key);
+ 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.
- const rm = requireResourceManager();
- rm.releaseTexture(oldest.handle);
- evictTextureDimensions(oldest.handle);
+ 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 === oldest.handle) {
+ if (this.textureCache_.get(key)?.handle === dropped.value) {
this.textureCache_.delete(key);
}
}
@@ -1273,22 +1245,16 @@ export class Assets {
private releaseTyped(type: string, ref: string): void {
const path = this.resolveLoadPath_(ref);
- const cache = this.genericCache_.get(type);
- if (!cache) return;
- const entry = cache.get(path);
- if (!entry) return;
-
+ // NOT gated on a live cache entry: a generation superseded by
+ // 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 count = this.genericRefCounts_.get(key);
- if (count === undefined) return;
- if (count > 1) {
- this.genericRefCounts_.set(key, count - 1);
- return;
- }
- const loader = this.loaders_.get(type);
- loader?.unload(entry, this.getLoadContext_());
- cache.delete(path);
- this.genericRefCounts_.delete(key);
+ const dropped = this.genericRefs_.release(key);
+ if (!dropped?.exhausted) return;
+
+ this.loaders_.get(type)?.unload(dropped.value, this.getLoadContext_());
+ const cache = this.genericCache_.get(type);
+ if (cache && cache.get(path) === dropped.value) cache.delete(path);
}
/**
@@ -1334,7 +1300,7 @@ 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;
- if (this.genericRefCounts_.delete(`${type}:${path}`)) hit = true;
+ // The ledger stays: the outgoing generation's holders still owe a release.
}
// Loader-owned residency (e.g. the AudioAPI warm cache) can outlive
@@ -1413,7 +1379,7 @@ export class Assets {
return {
textureCached: tex.cached,
pendingLoads: pending,
- refCounts: this.textureRefs_.size + this.genericRefCounts_.size,
+ refCounts: this.textureRefs_.size + this.genericRefs_.size,
genericCaches: this.genericCache_.size,
genericCached,
handlePaths: this.handleToPath_.size,
@@ -1436,16 +1402,12 @@ export class Assets {
this.textureCache_.clearAll();
// Superseded generations are not in the cache and would otherwise
// survive a releaseAll that claims to have let go of everything.
- for (const generations of this.textureRefs_.values()) {
- for (const generation of generations) {
- if (!seen.has(generation.handle)) {
- seen.add(generation.handle);
- rm.releaseTexture(generation.handle);
- evictTextureDimensions(generation.handle);
- }
- }
+ for (const { value } of this.textureRefs_.drain()) {
+ if (seen.has(value)) continue;
+ seen.add(value);
+ rm.releaseTexture(value);
+ evictTextureDimensions(value);
}
- this.textureRefs_.clear();
this.spineLoader_.releaseAll();
this.materialLoader_?.releaseAll();
@@ -1454,7 +1416,9 @@ export class Assets {
cache.clearAll();
}
this.genericCache_.clear();
- this.genericRefCounts_.clear();
+ for (const { key, value } of this.genericRefs_.drain()) {
+ this.loaders_.get(key.slice(0, key.indexOf(':')))?.unload(value, this.getLoadContext_());
+ }
this.handleToPath_.clear();
}
@@ -1621,8 +1585,7 @@ export class Assets {
const result = await (cache.getOrLoad(path, () =>
loader.load(path, this.getLoadContext_()),
) as Promise<T>);
- const key = `${type}:${path}`;
- this.genericRefCounts_.set(key, (this.genericRefCounts_.get(key) ?? 0) + 1);
+ 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;
diff --git a/sdk/tests/assets-invalidate-event.test.ts b/sdk/tests/assets-invalidate-event.test.ts
index 47d316915..653c053fc 100644
--- a/sdk/tests/assets-invalidate-event.test.ts
+++ b/sdk/tests/assets-invalidate-event.test.ts
@@ -42,11 +42,11 @@ describe('Assets.onInvalidate', () => {
const internal = assets as unknown as {
textureCache_: { cache_: Map<string, unknown> };
textureCacheKey_: (path: string, flip: boolean) => string;
- textureRefs_: Map<string, Array<{ handle: number; count: number }>>;
+ textureRefs_: { acquire(key: string, handle: number): void };
};
const key = internal.textureCacheKey_('tex/hot.png', false);
internal.textureCache_.cache_.set(key, { handle: 42 });
- internal.textureRefs_.set(key, [{ handle: 42, count: 1 }]);
+ internal.textureRefs_.acquire(key, 42);
const listener = vi.fn();
assets.onInvalidate(listener);
@@ -63,11 +63,11 @@ describe('Assets.onInvalidate', () => {
const internal = assets as unknown as {
textureCache_: { cache_: Map<string, unknown> };
textureCacheKey_: (path: string, flip: boolean) => string;
- textureRefs_: Map<string, Array<{ handle: number; count: number }>>;
+ textureRefs_: { acquire(key: string, handle: number): void };
};
const key = internal.textureCacheKey_('tex/hot.png', false);
internal.textureCache_.cache_.set(key, { handle: 42 });
- internal.textureRefs_.set(key, [{ handle: 42, count: 1 }]);
+ internal.textureRefs_.acquire(key, 42);
const listener = vi.fn();
const unsubscribe = assets.onInvalidate(listener);
@@ -79,7 +79,7 @@ describe('Assets.onInvalidate', () => {
// Re-populate cache and invalidate again — listener should NOT fire.
internal.textureCache_.cache_.set(key, { handle: 43 });
- internal.textureRefs_.set(key, [{ handle: 43, count: 1 }]);
+ internal.textureRefs_.acquire(key, 43);
assets.invalidate('tex/hot.png');
expect(listener).toHaveBeenCalledTimes(1);
});
@@ -89,11 +89,11 @@ describe('Assets.onInvalidate', () => {
const internal = assets as unknown as {
textureCache_: { cache_: Map<string, unknown> };
textureCacheKey_: (path: string, flip: boolean) => string;
- textureRefs_: Map<string, Array<{ handle: number; count: number }>>;
+ textureRefs_: { acquire(key: string, handle: number): void };
};
const key = internal.textureCacheKey_('tex/hot.png', false);
internal.textureCache_.cache_.set(key, { handle: 42 });
- internal.textureRefs_.set(key, [{ handle: 42, count: 1 }]);
+ internal.textureRefs_.acquire(key, 42);
const bad = vi.fn(() => { throw new Error('listener failed'); });
const good = vi.fn();
@@ -110,11 +110,11 @@ describe('Assets.onInvalidate', () => {
const internal = assets as unknown as {
textureCache_: { cache_: Map<string, unknown> };
textureCacheKey_: (path: string, flip: boolean) => string;
- textureRefs_: Map<string, Array<{ handle: number; count: number }>>;
+ textureRefs_: { acquire(key: string, handle: number): void };
};
const key = internal.textureCacheKey_('tex/a.png', false);
internal.textureCache_.cache_.set(key, { handle: 1 });
- internal.textureRefs_.set(key, [{ handle: 1, count: 1 }]);
+ internal.textureRefs_.acquire(key, 1);
const a = vi.fn();
const b = vi.fn();
diff --git a/sdk/tests/torture/asset-lifecycle.test.ts b/sdk/tests/torture/asset-lifecycle.test.ts
index dd34e6f7e..0db7e0730 100644
--- a/sdk/tests/torture/asset-lifecycle.test.ts
+++ b/sdk/tests/torture/asset-lifecycle.test.ts
@@ -116,10 +116,10 @@ function checkInvariants(model: Model, real: Real): void {
for (const [key, generations] of textureRefs(assets)) {
for (const generation of generations) {
if (generation.count < 0) {
- throw new Error(`refCount(${key}, handle ${generation.handle}) = ${generation.count} — a release outran its acquire`);
+ throw new Error(`refCount(${key}, handle ${generation.value}) = ${generation.count} — a release outran its acquire`);
}
if (generation.count === 0) {
- throw new Error(`refCount(${key}, handle ${generation.handle}) = 0 is recorded rather than removed — a generation nothing can drain`);
+ throw new Error(`refCount(${key}, handle ${generation.value}) = 0 is recorded rather than removed — a generation nothing can drain`);
}
}
if (generations.length === 0) {
@@ -207,7 +207,7 @@ function checkFullTeardown(model: Model, real: Real): void {
if (refs.size > 0) {
throw new Error(
'refcount ledger is not empty after full teardown: '
- + [...refs].map(([k, g]) => `${k}=[${g.map((x) => `h${x.handle}x${x.count}`).join(',')}]`).join(', '),
+ + [...refs].map(([k, g]) => `${k}=[${g.map((x) => `h${x.value}x${x.count}`).join(',')}]`).join(', '),
);
}
}
diff --git a/sdk/tests/torture/assetHarness.ts b/sdk/tests/torture/assetHarness.ts
index ce7f260cf..c6da11d4a 100644
--- a/sdk/tests/torture/assetHarness.ts
+++ b/sdk/tests/torture/assetHarness.ts
@@ -191,7 +191,7 @@ export type Scheduler = fc.Scheduler;
/** One live generation of a texture: the handle its holders were given, and how many. */
export interface TextureGeneration {
- handle: number;
+ readonly value: number;
count: number;
}
@@ -201,5 +201,92 @@ export interface TextureGeneration {
* through a public accessor would test the accessor. Nothing else reaches in.
*/
export function textureRefs(assets: Assets): ReadonlyMap<string, readonly TextureGeneration[]> {
- return (assets as unknown as { textureRefs_: Map<string, TextureGeneration[]> }).textureRefs_;
+ return (assets as unknown as {
+ textureRefs_: { entries(): ReadonlyMap<string, readonly TextureGeneration[]> };
+ }).textureRefs_.entries();
+}
+
+// =============================================================================
+// Generic assets — the other half of the ledger
+// =============================================================================
+
+/** What a generic (non-texture) loader did, as the test can see it. */
+export interface FakeGenericLoader {
+ /** load() invocations, in order. */
+ readonly loads: string[];
+ /** Entries handed to unload(). One appearing twice is a double free. */
+ readonly unloaded: unknown[];
+ /** Entries produced and not yet unloaded. */
+ live(): unknown[];
+}
+
+export interface GenericHarness {
+ readonly assets: Assets;
+ readonly loader: FakeGenericLoader;
+ failNext(path: string): void;
+ dispose(): void;
+}
+
+/**
+ * A tilemap loader whose settling the caller owns, standing in for every
+ * non-texture kind. They all share one code path (loadTyped/releaseTyped) and
+ * now one ledger, so proving the contract on one proves it for audio,
+ * materials, fonts, clips and prefabs too.
+ */
+export function makeGenericHarness(
+ scheduleLoad: (path: string) => Promise<unknown>,
+): GenericHarness {
+ initResourceManager({
+ releaseTexture: () => {},
+ getTextureDimensions: () => null,
+ setTextureMetadata: () => {},
+ } as never);
+
+ const backend = {
+ fetchBinary: async () => new ArrayBuffer(8),
+ fetchText: async () => '{}',
+ resolveUrl: (p: string) => `http://torture/${p}`,
+ } as unknown as Backend;
+ const assets = Assets.create({ backend, module: mockModule });
+
+ const loads: string[] = [];
+ const unloaded: unknown[] = [];
+ const produced: unknown[] = [];
+ const failing = new Set<string>();
+ let nextId = 1;
+
+ assets.register({
+ type: 'tilemap',
+ extensions: ['.estilemap'],
+ async load(path: string): Promise<unknown> {
+ loads.push(path);
+ const shouldFail = failing.delete(path);
+ await scheduleLoad(path);
+ if (shouldFail) throw new Error(`torture: generic load failed for ${path}`);
+ const entry = { id: nextId++, path };
+ produced.push(entry);
+ return entry;
+ },
+ unload(asset: unknown): void {
+ unloaded.push(asset);
+ },
+ } as never);
+
+ return {
+ assets,
+ loader: {
+ loads,
+ unloaded,
+ live: () => produced.filter((e) => !unloaded.includes(e)),
+ },
+ failNext: (path) => failing.add(path),
+ dispose: () => shutdownResourceManager(),
+ };
+}
+
+/** The generic half of the reference ledger, for the same reason as textureRefs. */
+export function genericRefs(assets: Assets): ReadonlyMap<string, readonly { value: unknown; count: number }[]> {
+ return (assets as unknown as {
+ genericRefs_: { entries(): ReadonlyMap<string, readonly { value: unknown; count: number }[]> };
+ }).genericRefs_.entries();
}
diff --git a/sdk/tests/torture/generic-asset-lifecycle.test.ts b/sdk/tests/torture/generic-asset-lifecycle.test.ts
new file mode 100644
index 000000000..8d5f6b3a3
--- /dev/null
+++ b/sdk/tests/torture/generic-asset-lifecycle.test.ts
@@ -0,0 +1,195 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The same torture, on the half that is not textures.
+ *
+ * Audio, materials, fonts, clips, timelines, tilemaps and prefabs share one
+ * code path and, since the ledger was unified, one set of rules. They also
+ * shared the bug: releaseTyped returned early when the cache had no entry, so a
+ * generation superseded by invalidate() left its loaded asset unreachable and
+ * unload() was never called. Textures got that fixed first; this is the proof
+ * the other seven kinds got it too, rather than the assurance that they did.
+ */
+import { describe, it, expect } from 'vitest';
+import fc from 'fast-check';
+import { makeGenericHarness, genericRefs, type GenericHarness } from './assetHarness';
+
+const KEYS = ['maps/a.estilemap', 'maps/b.estilemap'] as const;
+const RUNS = Number(process.env.TORTURE_RUNS ?? 200);
+const SEED = process.env.TORTURE_SEED ? Number(process.env.TORTURE_SEED) : undefined;
+
+interface Model {
+ held: Map<string, number>;
+ joinable: Map<string, number>;
+ scheduler: fc.Scheduler;
+}
+
+interface Real {
+ harness: GenericHarness;
+ settled: Promise<unknown>[];
+}
+
+const freshModel = (scheduler: fc.Scheduler): Model => ({
+ held: new Map(KEYS.map((k) => [k, 0])),
+ joinable: new Map(KEYS.map((k) => [k, 0])),
+ scheduler,
+});
+
+const bump = (m: Map<string, number>, k: string, by = 1): void => m.set(k, (m.get(k) ?? 0) + by) && undefined;
+
+function checkInvariants(real: Real): void {
+ const { assets, loader } = real.harness;
+
+ // No entry may be unloaded twice — the loader would double-free whatever it
+ // owns (an audio buffer, a material's bound textures).
+ const seen = new Set<unknown>();
+ for (const entry of loader.unloaded) {
+ if (seen.has(entry)) throw new Error(`an asset was unloaded twice: ${JSON.stringify(entry)}`);
+ seen.add(entry);
+ }
+
+ for (const [key, generations] of genericRefs(assets)) {
+ if (generations.length === 0) throw new Error(`${key} keeps an empty generation list`);
+ for (const generation of generations) {
+ if (generation.count <= 0) {
+ throw new Error(`refCount(${key}) = ${generation.count} — a release outran its acquire`);
+ }
+ if (loader.unloaded.includes(generation.value)) {
+ throw new Error(`${key} still references an asset that was already unloaded`);
+ }
+ }
+ }
+}
+
+/** Everything loaded must be unloaded once every reference is given back. */
+function checkFullTeardown(model: Model, real: Real): void {
+ const { assets, loader } = real.harness;
+ for (const [key, count] of model.held) {
+ for (let i = 0; i < count; i++) assets.releaseTilemap(key);
+ model.held.set(key, 0);
+ }
+ const live = loader.live();
+ if (live.length > 0) {
+ throw new Error(
+ `${live.length} asset(s) never unloaded after every reference was dropped: `
+ + `${live.map((e) => JSON.stringify(e)).join(', ')} (loaded ${loader.loads.length})`,
+ );
+ }
+ const refs = genericRefs(assets);
+ if (refs.size > 0) throw new Error(`ledger not empty after teardown: ${[...refs.keys()].join(', ')}`);
+}
+
+type Cmd = fc.AsyncCommand<Model, Real>;
+
+class Load implements Cmd {
+ constructor(readonly key: string) {}
+ check = (): boolean => true;
+ async run(model: Model, real: Real): Promise<void> {
+ bump(model.joinable, this.key);
+ real.settled.push(real.harness.assets.loadTilemap(this.key).then(
+ () => { bump(model.held, this.key); bump(model.joinable, this.key, -1); },
+ () => { bump(model.joinable, this.key, -1); },
+ ));
+ checkInvariants(real);
+ }
+ toString = (): string => `load(${this.key})`;
+}
+
+class Release implements Cmd {
+ constructor(readonly key: string) {}
+ check = (model: Model): boolean => (model.held.get(this.key) ?? 0) > 0;
+ async run(model: Model, real: Real): Promise<void> {
+ real.harness.assets.releaseTilemap(this.key);
+ bump(model.held, this.key, -1);
+ checkInvariants(real);
+ }
+ toString = (): string => `release(${this.key})`;
+}
+
+class Invalidate implements Cmd {
+ constructor(readonly key: string) {}
+ check = (): boolean => true;
+ async run(model: Model, real: Real): Promise<void> {
+ real.harness.assets.invalidate(this.key);
+ model.joinable.set(this.key, 0);
+ checkInvariants(real);
+ }
+ toString = (): string => `invalidate(${this.key})`;
+}
+
+class FailNext implements Cmd {
+ constructor(readonly key: string) {}
+ check = (): boolean => true;
+ async run(model: Model, real: Real): Promise<void> {
+ real.harness.failNext(this.key);
+ checkInvariants(real);
+ }
+ toString = (): string => `failNext(${this.key})`;
+}
+
+class SettleOne implements Cmd {
+ check = (model: Model): boolean => model.scheduler.count() > 0;
+ async run(model: Model, real: Real): Promise<void> {
+ await model.scheduler.waitOne();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ checkInvariants(real);
+ }
+ toString = (): string => 'settleOne()';
+}
+
+describe('generic asset lifecycle under generated interleavings', () => {
+ it('unloads everything it loaded, whatever the order', async () => {
+ const key = fc.constantFrom(...KEYS);
+ await fc.assert(
+ fc.asyncProperty(
+ fc.scheduler(),
+ fc.commands(
+ [
+ key.map((k) => new Load(k)),
+ key.map((k) => new Release(k)),
+ key.map((k) => new Invalidate(k)),
+ key.map((k) => new FailNext(k)),
+ fc.constant(new SettleOne()),
+ ],
+ { maxCommands: 24 },
+ ),
+ async (scheduler, commands) => {
+ const harness = makeGenericHarness(scheduler.scheduleFunction(async (p: string) => p));
+ const real: Real = { harness, settled: [] };
+ const model = freshModel(scheduler);
+ try {
+ await fc.asyncModelRun(() => ({ model, real }), commands);
+ await scheduler.waitAll();
+ await Promise.all(real.settled);
+ checkFullTeardown(model, real);
+ } finally {
+ harness.dispose();
+ }
+ },
+ ),
+ { numRuns: RUNS, seed: SEED, verbose: true },
+ );
+ }, 300_000);
+});
+
+describe('generic assets: the texture bug, one layer over', () => {
+ it('unloads an asset whose load was superseded by invalidate', async () => {
+ // The exact shape that stranded a texture, on the path every non-texture
+ // kind takes. It failed here until the ledger was unified.
+ let open!: () => void;
+ const harness = makeGenericHarness(() => new Promise<unknown>((r) => { open = () => r(null); }));
+ try {
+ const load = harness.assets.loadTilemap(KEYS[0]);
+ harness.assets.invalidate(KEYS[0]);
+ open();
+ await load;
+
+ harness.assets.releaseTilemap(KEYS[0]);
+
+ expect(harness.loader.live(), 'the superseded asset was never unloaded').toEqual([]);
+ expect([...genericRefs(harness.assets).keys()], 'an orphan ledger row survived').toEqual([]);
+ } finally {
+ harness.dispose();
+ }
+ });
+});