Skip to content

3D engine that AI agents drive

Say why scene_create closes older scenes (#2287)

Nguyen Xuan An012029750416
diff --git a/changes/2287.md b/changes/2287.md
new file mode 100644
index 00000000..ead356ed
--- /dev/null
+++ b/changes/2287.md
@@ -0,0 +1 @@
+- `scene_create` now says why it closed older scenes (`evictionReason`: the 4-scene cap or the 96 MiB geometry cap, with the sizes), and a later call with that ID repeats the reason (#2287)
diff --git a/docs/mcp.md b/docs/mcp.md
index eaf7865b..d7fb0d40 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -173,7 +173,7 @@ Inspect or export the recipe before retrying. Context loss still permits recipe
`sessionId` is the scene ID: `scene_create` and `scene_create_asset` return it, and every scene tool takes it. It is optional: a call that leaves it out means the last used scene. An ID that names no open scene (an invented one, one from a disposed scene, or one that was evicted) is rejected with the open IDs in the message, because acting on a scene the caller did not name could edit the wrong one.
-One server keeps up to 4 scenes open, within 96 MiB of resident geometry together. Creating a scene past either cap closes the least recently used scene, and the create result lists it under `evictedSessions`; a later call with that ID fails with an `evicted` error. Save a scene with `scene_export_recipe` before it can be evicted. Only one scene holds the preview renderer at a time, so a call on another scene rebuilds it first; that costs a moment, so finish a batch of calls on one scene before switching.
+One server keeps up to 4 scenes open, within 96 MiB of resident geometry together. The 96 MiB counts the geometry every open scene holds (including its revision history and checkpoints) plus the new one, so a few large scenes (terrain, vegetation, imported models) can fill it before the fourth scene opens; small scenes reach 4. Creating a scene past either cap closes the least recently used scenes until both hold, and the create result lists them under `evictedSessions` with `evictionReason`, which names the cap that was exceeded and the MiB involved; a later call with that ID fails with an `evicted` error that repeats the reason. Save a scene with `scene_export_recipe` before it can be evicted. Only one scene holds the preview renderer at a time, so a call on another scene rebuilds it first; that costs a moment, so finish a batch of calls on one scene before switching.
Each scene keeps up to 16 checkpoints. `scene_checkpoint` returns `checkpointId`; past the limit the oldest checkpoint is evicted and the result lists it under `evictedCheckpointIds`. A `checkpointId` belongs to the scene that returned it. A render job stays tied to the scene it was submitted for. While a job runs the preview renderer is leased, so `scene_create`, edits and disposal wait for it, as before.
diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.js
index 3f5462fc..dece41e2 100644
--- a/scripts/agent-preview-browser.js
+++ b/scripts/agent-preview-browser.js
@@ -46,7 +46,7 @@ import { parseRadianceHdr } from '../src/hdri.js';
import { parseCube } from '../src/view-transform.js';
import { weightTracksFromGltfAnimation } from '../src/export-skeleton.js';
import { clipFromGltfAnimation } from '../src/skeleton-pose.js';
-import { sessionProblem, SCENE_STORE_LIMITS } from '../src/agent-errors.js';
+import { sessionProblem, planSceneEviction } from '../src/agent-errors.js';
import { AGENT_SCENE_DEFAULT_LIMITS, MEMORY_CEILING_MIB } from '../src/agent-scene-capabilities.js';
import { describeApplication } from '../src/agent-apply-report.js';
import { framingProblems, placementProblems, textureProblems, exposureProblems, lumaShares } from '../src/frame-checks.js';
@@ -62,11 +62,13 @@ const records = new Map();
let leasedRecord = null;
const EVICTED_SESSIONS_KEPT = 32;
const evictedSessions = [];
+// Why each remembered evicted scene was closed, so a later call with its ID can say it.
+const evictionReasons = {};
let canvas = document.querySelector('canvas');
function sessionError(sessionId) {
const openSessionIds = [...records.keys()];
- return new Error(sessionProblem(sessionId, openSessionIds.at(-1), { openSessionIds, evictedSessionIds: evictedSessions }));
+ return new Error(sessionProblem(sessionId, openSessionIds.at(-1), { openSessionIds, evictedSessionIds: evictedSessions, evictionReasons }));
}
function lookupSession(sessionId) {
@@ -125,26 +127,19 @@ function residentBytesOf(record) {
return record.scene.inspect().residentGeometryBytes ?? 0;
}
-// Close the least recently used scenes until `incoming` more scenes of `incomingBytes` fit, and name them to the caller.
+// Close the least recently used scenes until the new scene fits both caps, and name them and the cap to the caller.
function evictForNewScene(incomingBytes) {
- const evicted = [];
- let bytes = incomingBytes;
- const sizes = new Map();
- for (const record of records.values()) {
- const size = residentBytesOf(record);
- sizes.set(record, size);
- bytes += size;
+ const openScenes = [...records.values()].map(record => ({ sessionId: record.sessionId, bytes: residentBytesOf(record) }));
+ const { sessionIds, reason } = planSceneEviction(openScenes, incomingBytes);
+ for (const sessionId of sessionIds) {
+ releaseRecord(records.get(sessionId));
+ evictedSessions.push(sessionId);
+ evictionReasons[sessionId] = reason;
}
- for (const record of [...records.values()]) {
- const overCount = records.size + 1 > SCENE_STORE_LIMITS.maxOpenScenes;
- if (!overCount && bytes <= SCENE_STORE_LIMITS.maxOpenSceneBytes) break;
- bytes -= sizes.get(record);
- releaseRecord(record);
- evicted.push(record.sessionId);
- evictedSessions.push(record.sessionId);
+ for (const forgottenId of evictedSessions.splice(0, Math.max(0, evictedSessions.length - EVICTED_SESSIONS_KEPT))) {
+ delete evictionReasons[forgottenId];
}
- evictedSessions.splice(0, Math.max(0, evictedSessions.length - EVICTED_SESSIONS_KEPT));
- return evicted;
+ return { evicted: sessionIds, reason };
}
function bytesFromBase64(data) {
@@ -645,9 +640,9 @@ function createPreview(scene, { sessionId, memoryBudgetMiB, backend, transparent
if (backend === 'gpu' && /swiftshader|llvmpipe|software/i.test(result.render.graphics)) {
throw new Error('Hardware GPU rendering was requested, but the browser selected a software renderer.');
}
- const evicted = evictForNewScene(result.inspection.residentGeometryBytes ?? 0);
+ const { evicted, reason } = evictForNewScene(result.inspection.residentGeometryBytes ?? 0);
records.set(sessionId, record);
- return evicted.length ? { ...result, evictedSessions: evicted } : result;
+ return evicted.length ? { ...result, evictedSessions: evicted, evictionReason: reason } : result;
} catch (error) {
renderer?.dispose();
// A throwing constructor may already own GPU objects without returning an instance.
diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjs
index 355094b9..3c51ada9 100644
--- a/scripts/agent-runtime.mjs
+++ b/scripts/agent-runtime.mjs
@@ -194,6 +194,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
let streamedSequencesUsed = false;
// Scenes the page closed to stay under the scene cap, so a later call with one of them gets a clear error.
const evictedSessionIds = [];
+ const evictionReasons = {};
// Scenes that have a bake, so an edit that rebakes gets the longer deadline.
const bakedSessionIds = new Set();
let queuedCalls = 0;
@@ -805,7 +806,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
function requireSession(sessionId) {
if (!openSessionIds.has(sessionId)) {
- throw new Error(sessionProblem(sessionId, lastUsedSessionId(), { openSessionIds: [...openSessionIds], evictedSessionIds }));
+ throw new Error(sessionProblem(sessionId, lastUsedSessionId(), { openSessionIds: [...openSessionIds], evictedSessionIds, evictionReasons }));
}
// Re-insert so the Set order stays least to most recently used.
openSessionIds.delete(sessionId);
@@ -817,8 +818,11 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
for (const evictedSessionId of result.evictedSessions ?? []) {
forgetSession(evictedSessionId);
evictedSessionIds.push(evictedSessionId);
+ if (result.evictionReason) evictionReasons[evictedSessionId] = result.evictionReason;
+ }
+ for (const forgottenId of evictedSessionIds.splice(0, Math.max(0, evictedSessionIds.length - MAXIMUM_REMEMBERED_EVICTIONS))) {
+ delete evictionReasons[forgottenId];
}
- evictedSessionIds.splice(0, Math.max(0, evictedSessionIds.length - MAXIMUM_REMEMBERED_EVICTIONS));
openSessionIds.add(sessionId);
if (hasBake) bakedSessionIds.add(sessionId);
}
diff --git a/src/agent-errors.js b/src/agent-errors.js
index 77ab616c..db300725 100644
--- a/src/agent-errors.js
+++ b/src/agent-errors.js
@@ -5,10 +5,11 @@
* `openSessionIds` lists the open scenes from least to most recently used; `evictedSessionIds` lists scenes the server
* closed to stay under its scene cap.
*/
-export function sessionProblem(requestedSessionId, activeSessionId, { openSessionIds = [], evictedSessionIds = [] } = {}) {
+export function sessionProblem(requestedSessionId, activeSessionId, { openSessionIds = [], evictedSessionIds = [], evictionReasons = {} } = {}) {
if (evictedSessionIds.includes(requestedSessionId)) {
const open = openSessionIds.length ? ` Open scenes: ${openSessionIds.join(', ')}.` : '';
- return `sessionId ${requestedSessionId} was evicted: the server keeps a limited number of open scenes and closes the least recently used one when a new scene is created.${open} Pass the sessionId of an open scene, or call scene_create again (scene_export_recipe saves a scene before it is evicted).`;
+ const reason = evictionReasons[requestedSessionId] ?? 'the server keeps a limited number of open scenes and closes the least recently used one when a new scene is created';
+ return `sessionId ${requestedSessionId} was evicted: ${reason}.${open} Pass the sessionId of an open scene, or call scene_create again (scene_export_recipe saves a scene before it is evicted).`;
}
if (!activeSessionId) {
return 'No scene is active: it was never created, was disposed, or scene_create failed. Call scene_create or scene_create_asset first, then pass the sessionId it returns.';
@@ -22,6 +23,42 @@ export function sessionProblem(requestedSessionId, activeSessionId, { openSessio
/** How many scenes one server keeps open, and the resident geometry bytes they may hold together. */
export const SCENE_STORE_LIMITS = Object.freeze({ maxOpenScenes: 4, maxOpenSceneBytes: 96 * 1024 * 1024 });
+function mebibytes(bytes) {
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`;
+}
+
+/**
+ * Which open scenes a new scene closes, and why. `openScenes` lists `{ sessionId, bytes }` from least to most recently used and
+ * `incomingBytes` is the new scene's resident geometry. Scenes close oldest first until both caps hold, so a scene is only closed
+ * for a cap that is really exceeded: the scene count, or the resident geometry the open scenes hold together with the new one.
+ * The reason names that cap and the numbers, because "up to 4 scenes" is easy to read as a promise a few large scenes cannot keep.
+ */
+export function planSceneEviction(openScenes, incomingBytes, limits = SCENE_STORE_LIMITS) {
+ let remainingCount = openScenes.length;
+ let remainingBytes = incomingBytes + openScenes.reduce((total, scene) => total + scene.bytes, 0);
+ const startingBytes = remainingBytes;
+ const sessionIds = [];
+ let closedForCount = false;
+ let closedForBytes = false;
+ for (const scene of openScenes) {
+ const overCount = remainingCount + 1 > limits.maxOpenScenes;
+ const overBytes = remainingBytes > limits.maxOpenSceneBytes;
+ if (!overCount && !overBytes) break;
+ closedForCount ||= overCount;
+ closedForBytes ||= overBytes;
+ remainingCount -= 1;
+ remainingBytes -= scene.bytes;
+ sessionIds.push(scene.sessionId);
+ }
+ if (!sessionIds.length) return { sessionIds, reason: null };
+ const reasons = [];
+ if (closedForCount) reasons.push(`the server keeps at most ${limits.maxOpenScenes} open scenes`);
+ if (closedForBytes) {
+ reasons.push(`the open scenes and the new one held ${mebibytes(startingBytes)} of resident geometry, over the ${mebibytes(limits.maxOpenSceneBytes)} cap (the new scene alone is ${mebibytes(incomingBytes)})`);
+ }
+ return { sessionIds, reason: `closed the least recently used scene${sessionIds.length > 1 ? 's' : ''} because ${reasons.join(' and ')}` };
+}
+
/** A request made against an old revision: names both revisions, so the caller retries with the current one instead of guessing. */
export function staleRevisionMessage(subject, expectedRevision, currentRevision) {
return `Stale revision for ${subject}: expectedRevision ${expectedRevision} is not the current revision ${currentRevision}. Pass expectedRevision ${currentRevision}; a failed scene_apply leaves the revision unchanged, and scene_inspect returns the current one.`;
diff --git a/tests/scene-eviction.test.js b/tests/scene-eviction.test.js
new file mode 100644
index 00000000..e1b271be
--- /dev/null
+++ b/tests/scene-eviction.test.js
@@ -0,0 +1,47 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { planSceneEviction, sessionProblem, SCENE_STORE_LIMITS } from '../src/agent-errors.js';
+
+const MIB = 1024 * 1024;
+
+function scenes(sizesInMiB) {
+ return sizesInMiB.map((size, index) => ({ sessionId: `scene-${index}`, bytes: size * MIB }));
+}
+
+test('small scenes stay open up to the scene cap and nothing is closed', () => {
+ const plan = planSceneEviction(scenes([1, 1, 1]), MIB);
+ assert.deepEqual(plan.sessionIds, []);
+ assert.equal(plan.reason, null);
+});
+
+test('a fifth scene closes only the least recently used one and names the scene cap', () => {
+ const plan = planSceneEviction(scenes([1, 1, 1, 1]), MIB);
+ assert.deepEqual(plan.sessionIds, ['scene-0']);
+ assert.match(plan.reason, /because the server keeps at most 4 open scenes$/);
+});
+
+test('large scenes close for the memory cap and the reason gives the numbers', () => {
+ const plan = planSceneEviction(scenes([40, 40]), 30 * MIB);
+ assert.deepEqual(plan.sessionIds, ['scene-0']);
+ assert.match(plan.reason, /110\.0 MiB of resident geometry, over the 96\.0 MiB cap \(the new scene alone is 30\.0 MiB\)/);
+ assert.doesNotMatch(plan.reason, /at most 4 open scenes/);
+});
+
+test('scenes close oldest first until the memory cap holds and both caps can apply together', () => {
+ const plan = planSceneEviction(scenes([10, 50, 10, 10]), 40 * MIB);
+ assert.deepEqual(plan.sessionIds, ['scene-0', 'scene-1']);
+ assert.match(plan.reason, /scenes because the server keeps at most 4 open scenes and the open scenes/);
+});
+
+test('the default limits are the documented four scenes and 96 MiB', () => {
+ assert.equal(SCENE_STORE_LIMITS.maxOpenScenes, 4);
+ assert.equal(SCENE_STORE_LIMITS.maxOpenSceneBytes, 96 * MIB);
+});
+
+test('a later call with an evicted ID repeats the reason it was closed for', () => {
+ const reason = 'closed the least recently used scene because the server keeps at most 4 open scenes';
+ const message = sessionProblem('old', 'b', { openSessionIds: ['a', 'b'], evictedSessionIds: ['old'], evictionReasons: { old: reason } });
+ assert.match(message, /sessionId old was evicted: closed the least recently used scene because the server keeps at most 4 open scenes\./);
+ const withoutReason = sessionProblem('old', 'b', { openSessionIds: ['a', 'b'], evictedSessionIds: ['old'] });
+ assert.match(withoutReason, /sessionId old was evicted: the server keeps a limited number/);
+});
diff --git a/tests/support/preview-harness.mjs b/tests/support/preview-harness.mjs
index d7192c76..c966a74a 100644
--- a/tests/support/preview-harness.mjs
+++ b/tests/support/preview-harness.mjs
@@ -13,7 +13,7 @@ import { hasPatternTextures } from '../../scripts/agent-preview-textures.js';
import { rasterOptionsFor } from '../../scripts/agent-render-quality.mjs';
import { assetCopyKey, recipeAssetNeeds } from '../../src/agent-scene-assets.js';
import { BRANCH_LIMITS, createBranchStore, printableLabel } from '../../src/agent-branches.js';
-import { sessionProblem, SCENE_STORE_LIMITS } from '../../src/agent-errors.js';
+import { sessionProblem, planSceneEviction, SCENE_STORE_LIMITS } from '../../src/agent-errors.js';
import { imageLimitProblem } from '../../src/image-header.js';
import { sampleMotionAtZeroForGround } from '../../scripts/motion-ground-sample.js';
import { TEXTURE_SEQUENCE_LIMITS } from '../../src/texture-sequence-limits.js';
@@ -89,7 +89,7 @@ export function previewHarness({ createImageBitmap = async () => { throw new Err
// The harness loads Manifold from node_modules directly, so the preview's served-file loader is ignored.
setManifoldModuleLoader: () => {},
needsPhysics, loadPhysicsEngine, physicsEngineLoaded, setPhysicsModuleLoader: () => {},
- describeMarks, validateMarks, sceneQueryFor, partMaterialsFor, summarizeWalkMap, walkOptionsFor, createQueryOnlyCache, parseGltf, hasPatternTextures, rasterOptionsFor, Uint8Array, atob, sessionProblem, SCENE_STORE_LIMITS, AGENT_SCENE_DEFAULT_LIMITS, MEMORY_CEILING_MIB, imageLimitProblem, sampleMotionAtZeroForGround, TEXTURE_SEQUENCE_LIMITS, Blob, createImageBitmap, describeApplication, framingProblems, placementProblems, textureProblems, exposureProblems, lumaShares, assetCopyKey, recipeAssetNeeds, agentAssetDecodeOptions, withCatalogLimitAdvice,
+ describeMarks, validateMarks, sceneQueryFor, partMaterialsFor, summarizeWalkMap, walkOptionsFor, createQueryOnlyCache, parseGltf, hasPatternTextures, rasterOptionsFor, Uint8Array, atob, sessionProblem, planSceneEviction, SCENE_STORE_LIMITS, AGENT_SCENE_DEFAULT_LIMITS, MEMORY_CEILING_MIB, imageLimitProblem, sampleMotionAtZeroForGround, TEXTURE_SEQUENCE_LIMITS, Blob, createImageBitmap, describeApplication, framingProblems, placementProblems, textureProblems, exposureProblems, lumaShares, assetCopyKey, recipeAssetNeeds, agentAssetDecodeOptions, withCatalogLimitAdvice,
applyProjection, applyCameraFields, mat4, fitAgentShadow, resolveAgentShadow, agentEnvironmentMap, BRANCH_LIMITS,
// Line art needs a real renderer with render passes, so the fault-injected one gets a no-op install.
agentSceneModule: name => (name === 'lineArt' ? { installLineArt: renderer => renderer } : name === 'userPass' ? { ...agentSceneModule(name), installUserPasses: renderer => renderer } : agentSceneModule(name)), agentSceneModuleLoaded, createBranchStore, printableLabel,