3D engine that AI agents drive
JavaScript 3d3d-engineagentic-aiai-agentsblenderclaude-codegame-enginegaussian-splattinggltfjavascriptmcpmcp-servermodel-context-protocolpath-tracerpath-tracingpbrrenderingthreejs-alternativewebgl2webgpu
Refuse render jobs that can never run at submit (#2097)
Nguyen Xuan An5927390fe857
diff --git a/changes/2097.md b/changes/2097.mdnew file mode 100644index 00000000..2f1c0d46--- /dev/null+++ b/changes/2097.md@@ -0,0 +1 @@+- `scene_render_submit` now refuses a `gpu` path tracer backend on a `--backend cpu` runtime and an ID matte naming a part or material the scene lacks, at submit with the names to pass, instead of queuing a job that fails later (#2097)diff --git a/docs/agent-render-jobs.md b/docs/agent-render-jobs.mdindex 0b75712c..2e80fca1 100644--- a/docs/agent-render-jobs.md+++ b/docs/agent-render-jobs.md@@ -167,7 +167,7 @@ A seek to any frame gives the same pixels: a job samples each frame from its tim{ "kind": "image", "width": 1280, "height": 720, "mattes": [{ "object": "hero" }, { "material": "stone" }] }```-Each entry names exactly one `object` (a part name from `metrics.objectNames`) or one `material` (a name from `metrics.cryptomatte.materials`), up to 8 entries and 120 characters a name. An object matte is read from the exact 24-bit object ID, so a part that other parts overlap still gets its own clean edge. A material matte is read from the `cryptomatte` pass, whose hash has 255 values: two materials can share one, and then `metrics.mattes[n].sharedWith` lists the other names and the matte holds both. A name the scene does not have fails the job with the list of names it does have.+Each entry names exactly one `object` (a part name from `metrics.objectNames`) or one `material` (a name from `metrics.cryptomatte.materials`), up to 8 entries and 120 characters a name. An object matte is read from the exact 24-bit object ID, so a part that other parts overlap still gets its own clean edge. A material matte is read from the `cryptomatte` pass, whose hash has 255 values: two materials can share one, and then `metrics.mattes[n].sharedWith` lists the other names and the matte holds both. A name the scene does not have is refused by `scene_render_submit` with the list of names it does have, and no job is queued.`metrics.mattes` holds `{ object, partIds, coveragePixels }` or `{ material, sharedWith?, coveragePixels }` for each entry, from the last frame. Mattes are 8-bit PNG: they need `format` png, no `multilayer` and no `renderer`, and they cost about one extra pass each in the job estimate.### Combining pass pixels@@ -214,7 +214,7 @@ An `image`, `stills` or `video` job can ask for the offline [path tracer](https:"renderer": { "type": "pathTracer", "backend": "gpu", "samples": 64, "bounces": 8, "denoise": true, "seed": 0, "maxSeconds": 120 } }```-Every field after `type` is optional. `backend` is `cpu` (the default, byte-identical on SwiftShader smokes), `gpu`, which traces in a WebGL2 shader and needs a runtime started on the GPU backend (a `--backend cpu` runtime refuses it), or `native`, which traces on hardware ray queries (Vulkan) through the optional `@codepawlhq/cook` package. A native job exports the scene from the job page, traces it in the job runner with the Cycles-matching kernel (`JS67_NATIVE_KERNEL=legacy` keeps the older one), then denoises (OIDN runs on a device kept alive between frames when the OIDN library is installed, so only the first frame pays for the device and the filter commit; `metrics.pathTracer.oidnMode` says `in-process` or `cli`) and writes the PNG as the other backends do: `denoise: true` means OIDN with the albedo and normal guides when `@codepawlhq/crucible-denoise-oidn` and its binary are installed, else (or when OIDN fails) the GPU a-trous filter of the native tracer with a note in `metrics.pathTracer.denoiserNote` (`denoiser: "atrous"`; it is biased, it smooths; `denoise: "wavelet"` asks for the CPU filter). The report carries `kernel` and `averageSamples`. The Cycles-matching kernel takes up to 4,000,000 unique triangles (copies of a shared mesh count once, and the scene may hold four times that with every copy counted); the job reads the scene from its page as one Blob over the DevTools stream (about half the time of returning it as base64, and no single message bounds it); from the second frame of a `stills` or `video` job the page sends only the table bytes that changed since the frame before (a scene with moving particles sends the particles, not the static meshes), the job rebuilds the same tables from them, and `metrics.pathTracer.exportSentBytes` says how many bytes crossed (`JS67_NATIVE_EXPORT_DELTA=off` reads every table whole); the `cpu` backend and the older kernel keep 400,000, and the `gpu` backend takes what the page's WebGL2 context holds, up to 2,000,000 (see [path-tracer.md](https://github.com/codepawl/crucible/blob/main/docs/path-tracer.md)). A larger scene is refused with an error that names the limit. On the Cycles-matching kernel the job sends each material whole (FORMAT-v2 tables, instanced or not): blend opacity (`alphaMode: "blend"` with `opacity` below 1), sheen, `specular` and `specularColor`, anisotropy, iridescence, attenuation, and the clearcoat, transmission, sheen, anisotropy and coat normal maps all reach the kernel, and `metrics.pathTracer.ignored` lists only what it does not shade (the legacy kernel keeps the v1 tables and the old notes). A scene whose materials cannot be exported whole is traced from the v1 tables for that frame with the reason in `materialsReason`; the native tracer stays usable. It never fails for lack of the package: without it, without its built binary or without a Vulkan ray query adapter the job runs on `gpu` (`cpu` on a cpu runtime) and `metrics.pathTracer.backendNote` says why; `metrics.pathTracer.backend` always names what ran. The look up costs one import and is cached per process. Native traces volume fog and subsurface scattering with the same walk as the WebGPU megakernel, honours `maxSeconds`, and honours `noiseThreshold` on the GPU (after 16 samples, and then every 8, a converged pixel draws no more; `report.averageSamples` is the mean a pixel drew). The `gpu` fallback ignores `noiseThreshold`. The report in `metrics.pathTracer` names the `backend` that ran, the `gpu`, `gpuCompileSeconds` and `gpuKernelCompiles`. A `stills` or `video` job traces every frame with the same options: the kernel compiles once per job page and each frame reuses it, so a film shows `gpuKernelCompiles: 1`. A native `stills` or `video` job (the Cycles-matching kernel) also keeps one native session for the whole job: a frame that only moves the camera reuses the uploaded scene, the compiled kernel and the acceleration structures; changed materials, lights, instance transforms or triangles (the table may change length) are sent to the session, which rebuilds only the changed meshes' acceleration structures; a frame whose record counts, placed meshes, emissive meshes, textures or environment changed gets a new session, and a failed session update or render falls back to a new session or a one-shot trace for that frame. `metrics.pathTracer.nativeSession` says which one each frame took (`path` is `new-session`, `reused`, `updated` or `one-shot`, with `reason`, `changedTables`, `changedMeshes` (after a triangles update), `pipelineReused` and `accelerationReused`); `metrics.nativeSessionRoutes` lists the `path` of every frame. A job reuses the session only when the tables the page exports are equal to the previous frame's apart from the camera (`reused`), or differ in material values, lights, instance transforms or triangles (`updated`). Geometry that moves with the time, such as particle systems (sparks, swaying hair) or a moved node in a scene exported as flattened triangles, goes through `updated` and costs one BLAS build per changed mesh plus the TLAS. A changed emissive mesh, other record counts or another set of placed meshes gives that frame a new session, which costs what a one-shot trace costs and is byte-identical to it; `reason` names the first table that differed. A single-frame job and `JS67_NATIVE_KERNEL=legacy` trace one-shot and carry no `nativeSession`; `JS67_NATIVE_SESSIONS=off` in the server's environment traces every frame one-shot (default on). The session is closed when the job ends or fails, and every frame of a stills job equals the one-shot render byte for byte. A native video also blends its frames over time, so the noise the denoiser leaves does not shimmer from frame to frame: each pixel finds where its surface point was in the frame before (from the first-hit distance and the two cameras) and the filtered light is averaged with what was gathered there. A pixel whose surface was hidden, off screen, another surface or seen from a direction more than about 6 degrees away in the frame before starts again, so a cut to another view starts again too, and the whole image starts again at a new shot of a `timeline` and on any frame whose scene, light or render settings changed (its route is not `reused`), so a video with moving parts or lights, or a dip through black, gets no blending on those frames. Each frame of such a video traces with its own seed (`seed` plus the frame number), and `metrics.pathTracer.temporal` reports `historyShare` (the share of pixels that found their history, from the last frame) with `restarted` saying why an image started again. The blend assumes a still scene under a moving camera: light that depends on the view (a sharp reflection, a highlight, the view through glass) trails the camera by a few frames, and an orthographic camera is not blended. `JS67_NATIVE_TEMPORAL=off` in the server's environment turns the blending off, which makes every video frame equal its one-shot render again. A video of traced frames goes through the ffmpeg encoder (the browser H.264 encoder has no drawn frame to read), `maxSeconds` limits each frame, and the job deadline is `maxSeconds` times the frame count plus 60 seconds, up to the job ceiling. Limits: `samples` 1 to 1024, `bounces` 1 to 16, `seed` 0 to 2147483647, `maxSeconds` 1 to 600 (the job's deadline is `maxSeconds` plus 60 seconds; a 1920 by 1080 still of a 180,000 triangle room at 64 samples took 246 s, so give a large still `maxSeconds` 600). `passes` are refused with it, because the tracer has no object ID, depth or normal pass; part findings (framing, floating, intersecting, textures, z-fighting) still reach `metrics.diagnostics` from the first frame, with a `findings-unavailable` entry saying that exposure findings are not available on a traced job (see [mcp.md](mcp.md)). The tracer loads in the job page on demand, uses eight threads at below-normal priority, stops pixels that have converged (`report.averageSamples`), and writes `render.png`; `scene_render_result` metrics carry `pathTracer` with the samples, threads, seconds and what the scene asked for that was not drawn. The same recipe and seed give the same PNG on the cpu and gpu backends; the native Cycles-matching kernel is not always byte-identical between runs (on the demo room at 960 by 540 and 256 samples two jobs differed in a few bytes; a 480 by 270 job with OIDN did not). A job that passes `maxSeconds` fails and writes no image.+Every field after `type` is optional. `backend` is `cpu` (the default, byte-identical on SwiftShader smokes), `gpu`, which traces in a WebGL2 shader and needs a runtime started on the GPU backend (a `--backend cpu` runtime refuses it at `scene_render_submit`, before the job is queued), or `native`, which traces on hardware ray queries (Vulkan) through the optional `@codepawlhq/cook` package. A native job exports the scene from the job page, traces it in the job runner with the Cycles-matching kernel (`JS67_NATIVE_KERNEL=legacy` keeps the older one), then denoises (OIDN runs on a device kept alive between frames when the OIDN library is installed, so only the first frame pays for the device and the filter commit; `metrics.pathTracer.oidnMode` says `in-process` or `cli`) and writes the PNG as the other backends do: `denoise: true` means OIDN with the albedo and normal guides when `@codepawlhq/crucible-denoise-oidn` and its binary are installed, else (or when OIDN fails) the GPU a-trous filter of the native tracer with a note in `metrics.pathTracer.denoiserNote` (`denoiser: "atrous"`; it is biased, it smooths; `denoise: "wavelet"` asks for the CPU filter). The report carries `kernel` and `averageSamples`. The Cycles-matching kernel takes up to 4,000,000 unique triangles (copies of a shared mesh count once, and the scene may hold four times that with every copy counted); the job reads the scene from its page as one Blob over the DevTools stream (about half the time of returning it as base64, and no single message bounds it); from the second frame of a `stills` or `video` job the page sends only the table bytes that changed since the frame before (a scene with moving particles sends the particles, not the static meshes), the job rebuilds the same tables from them, and `metrics.pathTracer.exportSentBytes` says how many bytes crossed (`JS67_NATIVE_EXPORT_DELTA=off` reads every table whole); the `cpu` backend and the older kernel keep 400,000, and the `gpu` backend takes what the page's WebGL2 context holds, up to 2,000,000 (see [path-tracer.md](https://github.com/codepawl/crucible/blob/main/docs/path-tracer.md)). A larger scene is refused with an error that names the limit. On the Cycles-matching kernel the job sends each material whole (FORMAT-v2 tables, instanced or not): blend opacity (`alphaMode: "blend"` with `opacity` below 1), sheen, `specular` and `specularColor`, anisotropy, iridescence, attenuation, and the clearcoat, transmission, sheen, anisotropy and coat normal maps all reach the kernel, and `metrics.pathTracer.ignored` lists only what it does not shade (the legacy kernel keeps the v1 tables and the old notes). A scene whose materials cannot be exported whole is traced from the v1 tables for that frame with the reason in `materialsReason`; the native tracer stays usable. It never fails for lack of the package: without it, without its built binary or without a Vulkan ray query adapter the job runs on `gpu` (`cpu` on a cpu runtime) and `metrics.pathTracer.backendNote` says why; `metrics.pathTracer.backend` always names what ran. The look up costs one import and is cached per process. Native traces volume fog and subsurface scattering with the same walk as the WebGPU megakernel, honours `maxSeconds`, and honours `noiseThreshold` on the GPU (after 16 samples, and then every 8, a converged pixel draws no more; `report.averageSamples` is the mean a pixel drew). The `gpu` fallback ignores `noiseThreshold`. The report in `metrics.pathTracer` names the `backend` that ran, the `gpu`, `gpuCompileSeconds` and `gpuKernelCompiles`. A `stills` or `video` job traces every frame with the same options: the kernel compiles once per job page and each frame reuses it, so a film shows `gpuKernelCompiles: 1`. A native `stills` or `video` job (the Cycles-matching kernel) also keeps one native session for the whole job: a frame that only moves the camera reuses the uploaded scene, the compiled kernel and the acceleration structures; changed materials, lights, instance transforms or triangles (the table may change length) are sent to the session, which rebuilds only the changed meshes' acceleration structures; a frame whose record counts, placed meshes, emissive meshes, textures or environment changed gets a new session, and a failed session update or render falls back to a new session or a one-shot trace for that frame. `metrics.pathTracer.nativeSession` says which one each frame took (`path` is `new-session`, `reused`, `updated` or `one-shot`, with `reason`, `changedTables`, `changedMeshes` (after a triangles update), `pipelineReused` and `accelerationReused`); `metrics.nativeSessionRoutes` lists the `path` of every frame. A job reuses the session only when the tables the page exports are equal to the previous frame's apart from the camera (`reused`), or differ in material values, lights, instance transforms or triangles (`updated`). Geometry that moves with the time, such as particle systems (sparks, swaying hair) or a moved node in a scene exported as flattened triangles, goes through `updated` and costs one BLAS build per changed mesh plus the TLAS. A changed emissive mesh, other record counts or another set of placed meshes gives that frame a new session, which costs what a one-shot trace costs and is byte-identical to it; `reason` names the first table that differed. A single-frame job and `JS67_NATIVE_KERNEL=legacy` trace one-shot and carry no `nativeSession`; `JS67_NATIVE_SESSIONS=off` in the server's environment traces every frame one-shot (default on). The session is closed when the job ends or fails, and every frame of a stills job equals the one-shot render byte for byte. A native video also blends its frames over time, so the noise the denoiser leaves does not shimmer from frame to frame: each pixel finds where its surface point was in the frame before (from the first-hit distance and the two cameras) and the filtered light is averaged with what was gathered there. A pixel whose surface was hidden, off screen, another surface or seen from a direction more than about 6 degrees away in the frame before starts again, so a cut to another view starts again too, and the whole image starts again at a new shot of a `timeline` and on any frame whose scene, light or render settings changed (its route is not `reused`), so a video with moving parts or lights, or a dip through black, gets no blending on those frames. Each frame of such a video traces with its own seed (`seed` plus the frame number), and `metrics.pathTracer.temporal` reports `historyShare` (the share of pixels that found their history, from the last frame) with `restarted` saying why an image started again. The blend assumes a still scene under a moving camera: light that depends on the view (a sharp reflection, a highlight, the view through glass) trails the camera by a few frames, and an orthographic camera is not blended. `JS67_NATIVE_TEMPORAL=off` in the server's environment turns the blending off, which makes every video frame equal its one-shot render again. A video of traced frames goes through the ffmpeg encoder (the browser H.264 encoder has no drawn frame to read), `maxSeconds` limits each frame, and the job deadline is `maxSeconds` times the frame count plus 60 seconds, up to the job ceiling. Limits: `samples` 1 to 1024, `bounces` 1 to 16, `seed` 0 to 2147483647, `maxSeconds` 1 to 600 (the job's deadline is `maxSeconds` plus 60 seconds; a 1920 by 1080 still of a 180,000 triangle room at 64 samples took 246 s, so give a large still `maxSeconds` 600). `passes` are refused with it, because the tracer has no object ID, depth or normal pass; part findings (framing, floating, intersecting, textures, z-fighting) still reach `metrics.diagnostics` from the first frame, with a `findings-unavailable` entry saying that exposure findings are not available on a traced job (see [mcp.md](mcp.md)). The tracer loads in the job page on demand, uses eight threads at below-normal priority, stops pixels that have converged (`report.averageSamples`), and writes `render.png`; `scene_render_result` metrics carry `pathTracer` with the samples, threads, seconds and what the scene asked for that was not drawn. The same recipe and seed give the same PNG on the cpu and gpu backends; the native Cycles-matching kernel is not always byte-identical between runs (on the demo room at 960 by 540 and 256 samples two jobs differed in a few bytes; a 480 by 270 job with OIDN did not). A job that passes `maxSeconds` fails and writes no image.A native frame that compiled its kernel says so in `metrics.pathTracer`: `compileSeconds` is the compile, `gpuTraceSeconds` the trace; a compile over one second adds `kernelCompileNote`. The first trace of each scene variant (a scene with no emitter is its own variant) compiles; later frames of the job reuse it. Details: [path-tracer.md](https://github.com/codepawl/crucible/blob/main/docs/path-tracer.md).diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.jsindex c8cbbdcb..015af96a 100644--- a/scripts/agent-preview-browser.js+++ b/scripts/agent-preview-browser.js@@ -991,6 +991,11 @@ window.__agentPreview = {return { sourceRevision: record.scene.revision, recipe: record.scene.exportRecipe(),clips: record.asset?.animations.map(clip => ({ duration: clip.duration })) ?? [] };},+ // The part and material names an ID matte can name, read from the loaded scene so a job submit can refuse a name no frame will contain.+ matteTargets({ sessionId }) {+ const { passSupport } = requireSession(sessionId).renderer;+ return { objectNames: passSupport.objectNames(), materialNames: Object.keys(passSupport.cryptomatteManifest().materials) };+ },suspend({ sessionId }) {const record = lookupSession(sessionId);if (leasedRecord) throw new Error('Scene renderer is already suspended.');diff --git a/scripts/agent-render-jobs.mjs b/scripts/agent-render-jobs.mjsindex ae1f4fc2..2d323719 100644--- a/scripts/agent-render-jobs.mjs+++ b/scripts/agent-render-jobs.mjs@@ -305,7 +305,12 @@ function passesFrom(passes, kind) {const MAXIMUM_MATTES = 8;const MAXIMUM_MATTE_NAME_LENGTH = 120;-/** The ID mattes of a job: each names one object (part) or one material, and writes one gray PNG per frame. */+/** Refuses a path tracer backend this runtime cannot provide. The runner calls it for each frame and submit calls it first, so a doomed job is never queued. */+export function requireTracerBackendAvailable(renderer, runtimeBackend) {+ if (renderer?.backend === 'gpu' && runtimeBackend === 'cpu') throw new Error('renderer.backend "gpu" needs a runtime on the GPU backend, and this one runs on SwiftShader.');+}++/** The ID mattes of a job:each names one object (part) or one material, and writes one gray PNG per frame. */function mattesFrom(input) {const { mattes, kind, renderer, format, multilayer } = input;if (kind === 'video') throw new RangeError('mattes need kind image or stills; a video holds the lit image only.');diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjsindex 3327fc21..e0798955 100644--- a/scripts/agent-runtime.mjs+++ b/scripts/agent-runtime.mjs@@ -39,12 +39,12 @@ import { TEXTURE_SEQUENCE_CAPABILITIES, TEXTURE_SEQUENCE_LIMITS } from '../src/timport { writeWebBuild } from './web-export.mjs';import { gameAssetIds } from '../src/game-assets.js';import { resolveJobRoot } from './agent-job-root.mjs';-import { createAgentRenderJobs, EXPORT_DIRECTORY_NAME, HIGH_PRECISION_FRAME_FACTOR, RENDER_HISTORY_FILE, normalizeJobSettings, frameByteLimitFor, oversizeFrameBudgetError } from './agent-render-jobs.mjs';+import { createAgentRenderJobs, EXPORT_DIRECTORY_NAME, HIGH_PRECISION_FRAME_FACTOR, RENDER_HISTORY_FILE, normalizeJobSettings, frameByteLimitFor, oversizeFrameBudgetError, requireTracerBackendAvailable } from './agent-render-jobs.mjs';import { RENDER_QUALITY_NOTE, applyQuality, tierReport } from './agent-render-quality.mjs';import { RENDER_BUDGET_NOTE, chooseBudgetSettings, parseBudget } from './agent-render-budget.mjs';import { RENDER_ESTIMATE_NOTE, estimateRenderJob, historyWithJob, parseHistory, pathTraceTriangleProblem, renderReport, sceneSizeFrom } from './agent-render-estimate.mjs';import { objectIdMetrics } from './agent-object-id-metrics.mjs';-import { renderJobMattes } from './job-mattes.mjs';+import { renderJobMattes, requireMatteTargets } from './job-mattes.mjs';import { encodeRenderOutput, encodeMultilayerExr } from './render-output-encoders.mjs';import { createFrameEncoder } from './frame-encoder.mjs';import { DEFAULT_PAGE_ENCODER_QUANTIZER, createFrameReceiver, startVideoEncoderInPage } from './gpu-frame-reader.mjs';@@ -930,7 +930,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', browif (streamedJob && frameInput.motionTime !== undefined) await supplyStreamedFrames(jobPage, jobId, frameInput.motionTime);if (settings.renderer) {const { type, ...tracerOptions } = settings.renderer;- if (settings.renderer.backend === 'gpu' && backend === 'cpu') throw new Error('renderer.backend "gpu" needs a runtime on the GPU backend, and this one runs on SwiftShader.');+ requireTracerBackendAvailable(settings.renderer, backend);nativeTracerLocator ??= createNativeTracerLocator();const trace = await chooseTraceBackend({ requested: settings.renderer.backend, runtimeBackend: backend, locator: nativeTracerLocator });// Only a job that really traces on native defaults to OIDN; the cpu, gpu and webgpu defaults do not change.@@ -1663,6 +1663,8 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow}const triangleProblem = pathTraceTriangleProblem(size, jobSettings?.renderer, { canChooseBackend: backend !== 'cpu', picksRenderer: settings?.budget !== undefined || settings?.quality !== undefined });if (triangleProblem) throw new RangeError(triangleProblem);+ requireTracerBackendAvailable(jobSettings?.renderer, backend);+ if (jobSettings?.mattes) requireMatteTargets({ mattes: jobSettings.mattes, ...(await invoke('matteTargets', { sessionId })) });const estimate = estimateOf(jobSettings);estimateForNextJob = estimate;try {diff --git a/scripts/job-mattes.mjs b/scripts/job-mattes.mjsindex 06442317..e59f73f9 100644--- a/scripts/job-mattes.mjs+++ b/scripts/job-mattes.mjs@@ -33,22 +33,45 @@ function coverageOf(mask) {return covered;}-function objectMatte({ target, index, objectPass }) {+/** The object IDs (1 is the first name) of the parts called `target`; throws the matte error when the scene has none. */+function objectIdsOf({ target, index, objectNames }) {const ids = [];- objectPass.info.objectNames.forEach((name, position) => { if (name === target) ids.push(position + 1); });+ objectNames.forEach((name, position) => { if (name === target) ids.push(position + 1); });if (ids.length === 0) {- throw new Error(`mattes[${index}]: no part named "${target}" in this scene. Pass one of: ${nameList(objectPass.info.objectNames)}.`);+ throw new Error(`mattes[${index}]: no part named "${target}" in this scene. Pass one of: ${nameList(objectNames)}.`);}- const mask = objectIdMatte({ pixels: objectPass.bytes, width: objectPass.width, height: objectPass.height, ids });- return { mask, metric: { object: target, partIds: ids } };+ return ids;}-function materialMatte({ target, index, cryptomattePass }) {- const { materials } = cryptomattePass.info.cryptomatte;+function requireMaterialEntry({ target, index, materials }) {const entry = materials[target];if (!entry) {throw new Error(`mattes[${index}]: no material named "${target}" in this scene. Pass one of: ${nameList(Object.keys(materials))}.`);}+ return entry;+}++/**+ * Checks every matte of a job against the scene before anything renders: `objectNames` lists the parts in object ID order and+ * `materialNames` the materials. Throws the error the job would end with, so a matte that can never be drawn is refused at submit.+ */+export function requireMatteTargets({ mattes, objectNames, materialNames }) {+ const materials = Object.fromEntries(materialNames.map(name => [name, true]));+ mattes.forEach((matte, index) => {+ if (matte.object !== undefined) objectIdsOf({ target: matte.object, index, objectNames });+ else requireMaterialEntry({ target: matte.material, index, materials });+ });+}++function objectMatte({ target, index, objectPass }) {+ const ids = objectIdsOf({ target, index, objectNames: objectPass.info.objectNames });+ const mask = objectIdMatte({ pixels: objectPass.bytes, width: objectPass.width, height: objectPass.height, ids });+ return { mask, metric: { object: target, partIds: ids } };+}++function materialMatte({ target, index, cryptomattePass }) {+ const { materials } = cryptomattePass.info.cryptomatte;+ const entry = requireMaterialEntry({ target, index, materials });const mask = cryptomatteMatte({ pixels: cryptomattePass.bytes, width: cryptomattePass.width, height: cryptomattePass.height, channel: 'material', value: entry.value });const sharedWith = Object.entries(materials).filter(([name, other]) => name !== target && cryptomatteByte(other.value) === cryptomatteByte(entry.value))diff --git a/scripts/smoke-path-tracer.mjs b/scripts/smoke-path-tracer.mjsindex a1bd49df..f885c41f 100644--- a/scripts/smoke-path-tracer.mjs+++ b/scripts/smoke-path-tracer.mjs@@ -106,10 +106,10 @@ try {assert.match(refused.content[0].text, message);}- // A SwiftShader runtime keeps the CPU tracer: a job that asks for the GPU backend fails instead of drawing something else.+ // A SwiftShader runtime keeps the CPU tracer: a submit that asks for the GPU backend is refused instead of drawing something else.const gpuOnSwiftShader = await submit(sessionId, { ...base, renderer: { ...tracer, backend: 'gpu' } });- assert.equal(gpuOnSwiftShader.isError, undefined, gpuOnSwiftShader.content?.[0]?.text);- assert.equal((await finished(gpuOnSwiftShader.structuredContent.jobId)).state, 'failed', 'backend gpu must fail on a cpu runtime.');+ assert.equal(gpuOnSwiftShader.isError, true, 'backend gpu must be refused at submit on a cpu runtime.');+ assert.match(gpuOnSwiftShader.content[0].text, /renderer\.backend "gpu" needs a runtime on the GPU backend/);const slow = await submit(sessionId, { kind: 'image', width: 512, height: 512, renderer: { type: 'pathTracer', samples: 1024, maxSeconds: 1 } });assert.equal(slow.isError, undefined, slow.content?.[0]?.text);diff --git a/tests/mcp-render-submit-refusals.test.js b/tests/mcp-render-submit-refusals.test.jsnew file mode 100644index 00000000..e31b63c5--- /dev/null+++ b/tests/mcp-render-submit-refusals.test.js@@ -0,0 +1,81 @@+// scene_render_submit refuses a job that can never run, at submit and through the real MCP server on the CPU backend (SwiftShader):+// a gpu path tracer backend on that runtime, and an ID matte naming a part or material the scene does not have. No job record is made.+import test, { after, before } from 'node:test';+import assert from 'node:assert/strict';+import { mkdtemp, readdir, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import { join, resolve } from 'node:path';+import { setTimeout as delay } from 'node:timers/promises';+import { Client } from '@modelcontextprotocol/client';+import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';++const FRAME = { kind: 'image', width: 64, height: 64 };+const recipe = {+ format: 'crucible.scene', schemaVersion: 1,+ geometries: [{ id: 'box', type: 'box' }],+ materials: [{ id: 'w', color: [0.7, 0.7, 0.7] }],+ nodes: [{ id: 'box', geometry: 'box', material: 'w' }],+ camera: { eye: [3, 2, 3], target: [0, 0, 0], fov: 40 },+};++let directory;+let client;+let sessionId;++before(async () => {+ directory = await mkdtemp(join(tmpdir(), 'crucible-submit-refusals-'));+ const transport = new StdioClientTransport({ command: process.execPath,+ args: [resolve('bin/crucible-mcp.mjs'), '--backend', 'cpu', '--memory', '96', '--jobs', join(directory, 'jobs')], cwd: directory, stderr: 'pipe' });+ client = new Client({ name: 'crucible-submit-refusals-test', version: '1' });+ await client.connect(transport, { timeout: 240000 });+ sessionId = (await client.callTool({ name: 'scene_create', arguments: { recipe } }, { timeout: 120000 })).structuredContent.sessionId;+});++after(async () => {+ await client?.close();+ await rm(directory, { recursive: true, force: true });+});++function submit(settings) {+ return client.callTool({ name: 'scene_render_submit', arguments: { sessionId, expectedRevision: 0, settings: { ...FRAME, ...settings } } }, { timeout: 120000 });+}++async function jobFolders() {+ // The job store folder exists only once a job is stored.+ const names = await readdir(join(directory, 'jobs')).catch(() => []);+ return names.filter(name => /^[0-9a-f-]{36}$/.test(name));+}++async function refused(settings, expectedMessage) {+ const before = await jobFolders();+ const result = await submit(settings);+ assert.equal(result.isError, true, 'the submit is refused');+ assert.match(result.content[0].text, expectedMessage);+ assert.deepEqual(await jobFolders(), before, 'no job record is created');+}++test('a gpu path tracer backend is refused at submit on a cpu runtime', { timeout: 180000 }, async () => {+ await refused({ renderer: { type: 'pathTracer', backend: 'gpu', samples: 1 } },+ /renderer\.backend "gpu" needs a runtime on the GPU backend, and this one runs on SwiftShader\./);+});++test('a matte naming a part the scene lacks is refused at submit with the part names', { timeout: 180000 }, async () => {+ await refused({ mattes: [{ object: 'nope' }] }, /mattes\[0\]: no part named "nope" in this scene\. Pass one of: box/);+});++test('a matte naming a material the scene lacks is refused at submit with the material names', { timeout: 180000 }, async () => {+ await refused({ mattes: [{ object: 'box' }, { material: 'nope' }] }, /mattes\[1\]: no material named "nope" in this scene\. Pass one of: .*w/);+});++test('mattes naming real parts and materials still queue and render', { timeout: 180000 }, async () => {+ const result = await submit({ mattes: [{ object: 'box' }, { material: 'w' }] });+ assert.equal(result.isError, undefined, result.content?.[0]?.text);+ const { jobId } = result.structuredContent;+ let record;+ for (let poll = 0; poll < 300; poll++) {+ record = (await client.callTool({ name: 'scene_render_status', arguments: { jobId } })).structuredContent;+ if (['completed', 'failed', 'cancelled'].includes(record.state)) break;+ await delay(200);+ }+ assert.equal(record.state, 'completed', record.error);+});