Skip to content

3D engine that AI agents drive

Dispose every system when one dispose throws (#2617)

abu-tahir-0101ee6b37d5d
diff --git a/changes/2617.md b/changes/2617.md
new file mode 100644
index 00000000..08212117
--- /dev/null
+++ b/changes/2617.md
@@ -0,0 +1 @@
+- `runtime.dispose()` disposes every system and then reports the first failure, instead of leaving the rest undisposed (#2617)
diff --git a/src/runtime.js b/src/runtime.js
index 44dbe1c7..c8fef553 100644
--- a/src/runtime.js
+++ b/src/runtime.js
@@ -326,14 +326,23 @@ export function createRuntime(target, options = {}) {
};
},
- // Stops the loop and disposes every system in reverse order. The runtime cannot start again.
+ // Stops the loop and disposes every system in reverse order. Every dispose hook runs so one failure cannot keep the others
+ // from releasing their resources; the first failure is thrown after the list is cleared. The runtime cannot start again.
dispose() {
if (disposed) return;
stopLoop();
governor.dispose();
disposed = true;
- for (const system of [...systems].reverse()) disposeSystem(system);
+ let failure = null;
+ for (const system of [...systems].reverse()) {
+ try {
+ disposeSystem(system);
+ } catch (error) {
+ failure ??= { error };
+ }
+ }
systems.length = 0;
+ if (failure) throw failure.error;
},
};
diff --git a/tests/runtime.test.js b/tests/runtime.test.js
index fd735203..558d4382 100644
--- a/tests/runtime.test.js
+++ b/tests/runtime.test.js
@@ -129,6 +129,23 @@ test('systems run in order and dispose in reverse', () => {
assert.deepEqual(log.slice(-2), ['second:dispose', 'first:dispose']);
});
+test('dispose runs every system even when one throws, then reports the failure (#2617)', () => {
+ const log = [];
+ const systems = [recorder('first', log), recorder('second', log), recorder('third', log)];
+ systems[1].dispose = () => {
+ log.push('second:dispose');
+ throw new Error('second dispose failed');
+ };
+ const harness = createHarness({ systems });
+ harness.runtime.start();
+ assert.throws(() => harness.runtime.dispose(), /second dispose failed/);
+ assert.deepEqual(log.filter(line => line.endsWith(':dispose')), ['third:dispose', 'second:dispose', 'first:dispose']);
+ assert.deepEqual(harness.runtime.systems, []);
+ assert.equal(harness.hasPendingFrame(), false);
+ harness.runtime.dispose();
+ assert.equal(log.filter(line => line.endsWith(':dispose')).length, 3, 'a second dispose does nothing');
+});
+
test('systems can be left out, inserted, swapped and removed', () => {
const log = [];
const harness = createHarness({ mode: 'variable', systems: [{ name: 'game', update: () => log.push('game') }] });