Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Hold one native session per sequence job and report each frame's route (#896)

Nguyen Xuan An844415715195
diff --git a/bench/cycles-parity/sequence-timing.mjs b/bench/cycles-parity/sequence-timing.mjs
new file mode 100644
index 00000000..9f8d78bc
--- /dev/null
+++ b/bench/cycles-parity/sequence-timing.mjs
@@ -0,0 +1,126 @@
+// Times a bounded sequence of frames (24 by default) on an exported scene, one mode per process so the cold compile of one mode never
+// warms the other: "session" renders the frames through a native sequence (the route a stills or video job takes), "oneshot" renders each with
+// traceNative. Prints one SEQUENCE_TIMING line of JSON with the per-frame phase seconds, the route of each frame, the wall seconds of the
+// whole sequence and the SHA-256 of every frame, so the two modes can be compared byte for byte.
+// node bench/cycles-parity/sequence-timing.mjs <sceneJsonPath> --mode session|oneshot [--variant camera|object-light] [--frames 24]
+// [--samples 16] [--width 480] [--height 270] [--seed 1] [--instancing]
+// Variants: "camera" orbits the camera; "object-light" also moves the part named "block" and swings the first point light's intensity.
+// --instancing builds the scene with shared geometry, so a moved part is an instance transform (an update) instead of new triangles.
+import { createHash } from 'node:crypto';
+import { readFile } from 'node:fs/promises';
+import { resolve } from 'node:path';
+import { createCamera } from '../../src/path-tracer.js';
+import * as packModule from '../../src/path-tracer-gpu-pack.js';
+import { buildTraceScene } from '../../src/path-tracer-scene.js';
+import * as renderNative from '../../packages/render-native/index.mjs';
+import { createNativeSequence } from '../../scripts/agent-native-sequence.mjs';
+import { applyCookOnlyFields } from './cook-only-fields.mjs';
+import { buildTraceSceneWithManyLights } from './trace-scene-many-lights.mjs';
+import { reconstructTraceSceneSource } from './scene-bridge.mjs';
+
+const PHASE_NAMES = ['setupSeconds', 'compileSeconds', 'uploadSeconds', 'accelerationBuildSeconds', 'tracedSeconds'];
+const MOVING_PART_NAME = 'block';
+const ORBIT_RADIANS = Math.PI / 6;
+
+function readFlag(argumentList, flagName, fallbackValue) {
+ const flagIndex = argumentList.indexOf(flagName);
+ return flagIndex === -1 ? fallbackValue : argumentList[flagIndex + 1];
+}
+
+function sha256Of(values) {
+ return createHash('sha256').update(Buffer.from(values.buffer, values.byteOffset, values.byteLength)).digest('hex');
+}
+
+function orbitedCamera(camera, frameIndex, frameCount) {
+ const angle = ORBIT_RADIANS * frameIndex / Math.max(1, frameCount - 1);
+ const [targetX, , targetZ] = camera.target;
+ const offsetX = camera.eye[0] - targetX;
+ const offsetZ = camera.eye[2] - targetZ;
+ const eye = [targetX + offsetX * Math.cos(angle) - offsetZ * Math.sin(angle), camera.eye[1], targetZ + offsetX * Math.sin(angle) + offsetZ * Math.cos(angle)];
+ return { ...camera, eye };
+}
+
+function frameScene(source, variant, frameIndex, frameCount) {
+ if (variant === 'camera') return { parts: source.parts, environment: source.environment };
+ const phase = frameIndex / Math.max(1, frameCount - 1);
+ const parts = source.parts.map(part => {
+ if (part.name !== MOVING_PART_NAME) return part;
+ const matrix = new Float32Array(part.matrix);
+ matrix[12] += 0.6 * Math.sin(phase * Math.PI * 2);
+ return { ...part, matrix };
+ });
+ const pointLights = source.environment.pointLights.map((light, index) => (index === 0 ? { ...light, intensity: light.intensity * (0.5 + phase) } : light));
+ return { parts, environment: { ...source.environment, pointLights } };
+}
+
+function buildInputs(source, settings) {
+ const { variant, frameCount, width, height, instancing, renderOptions } = settings;
+ const inputs = [];
+ for (let frameIndex = 0; frameIndex < frameCount; frameIndex++) {
+ const { parts, environment } = frameScene(source, variant, frameIndex, frameCount);
+ const traceScene = instancing
+ ? applyCookOnlyFields(buildTraceScene(parts, environment, { instancing }), parts, environment)
+ : buildTraceSceneWithManyLights(parts, environment);
+ const camera = createCamera(orbitedCamera(source.camera, frameIndex, frameCount), width, height);
+ inputs.push(renderNative.buildNativeInputV2(traceScene, camera, { ...renderOptions, parts }, packModule));
+ }
+ return inputs;
+}
+
+function summarizeFrame(traced, route, wallSeconds) {
+ const frame = { rgbaSha256: sha256Of(traced.rgba), wallSeconds: Number(wallSeconds.toFixed(6)), path: route?.path ?? 'one-shot' };
+ for (const phaseName of PHASE_NAMES) frame[phaseName] = Number((traced[phaseName] ?? 0).toFixed(6));
+ if (route?.reason) frame.reason = route.reason;
+ if (route?.changedTables) frame.changedTables = route.changedTables;
+ return frame;
+}
+
+function averageOfWarmFrames(frames, fieldName) {
+ const warmFrames = frames.slice(1);
+ const total = warmFrames.reduce((sum, frame) => sum + frame[fieldName], 0);
+ return Number((total / Math.max(1, warmFrames.length)).toFixed(6));
+}
+
+function runSequence(inputs, mode, traceOptions) {
+ const sequence = mode === 'session' ? createNativeSequence({ tracer: renderNative }) : null;
+ const frames = [];
+ const sequenceStarted = performance.now();
+ try {
+ for (const input of inputs) {
+ const frameStarted = performance.now();
+ const { traced, route } = sequence ? sequence.trace(input, traceOptions) : { traced: renderNative.traceNative(input, traceOptions) };
+ frames.push(summarizeFrame(traced, route, (performance.now() - frameStarted) / 1000));
+ }
+ } finally {
+ sequence?.close();
+ }
+ return { frames, totalSeconds: Number(((performance.now() - sequenceStarted) / 1000).toFixed(6)) };
+}
+
+async function run() {
+ const argumentList = process.argv.slice(2);
+ const mode = readFlag(argumentList, '--mode', null);
+ if (!argumentList[0] || argumentList[0].startsWith('--') || !['session', 'oneshot'].includes(mode)) {
+ throw new RangeError('Usage: node bench/cycles-parity/sequence-timing.mjs <sceneJsonPath> --mode session|oneshot [--variant camera|object-light] [--frames 24] [--samples 16] [--width 480] [--height 270] [--seed 1] [--instancing]');
+ }
+ const variant = readFlag(argumentList, '--variant', 'camera');
+ if (!['camera', 'object-light'].includes(variant)) throw new RangeError(`--variant must be camera or object-light; got "${variant}".`);
+ const frameCount = Number(readFlag(argumentList, '--frames', 24));
+ const width = Number(readFlag(argumentList, '--width', 480));
+ const height = Number(readFlag(argumentList, '--height', 270));
+ const samples = Number(readFlag(argumentList, '--samples', 16));
+ const seed = Number(readFlag(argumentList, '--seed', 1));
+ const instancing = argumentList.includes('--instancing');
+ const description = JSON.parse(await readFile(resolve(argumentList[0]), 'utf8'));
+ const source = await reconstructTraceSceneSource(description);
+ const renderOptions = { width, height, samples, bounces: 8, seed };
+ const inputs = buildInputs(source, { variant, frameCount, width, height, instancing, renderOptions });
+ const { frames, totalSeconds } = runSequence(inputs, mode, { ...renderOptions, kernel: 'cycles' });
+ const paths = {};
+ for (const frame of frames) paths[frame.path] = (paths[frame.path] ?? 0) + 1;
+ const summary = { scene: description.id, mode, variant, instancing, frameCount, width, height, samples, seed, totalSeconds, paths,
+ coldFrame: frames[0], warmAverage: Object.fromEntries([...PHASE_NAMES, 'wallSeconds'].map(name => [name, averageOfWarmFrames(frames, name)])), frames };
+ console.log(`SEQUENCE_TIMING ${JSON.stringify(summary)}`);
+}
+
+await run();
diff --git a/changes/896-session-jobs.md b/changes/896-session-jobs.md
new file mode 100644
index 00000000..86b57d19
--- /dev/null
+++ b/changes/896-session-jobs.md
@@ -0,0 +1 @@
+- Native render jobs with several frames keep one persistent session, so a camera move builds nothing after frame 1 and each frame's report names the route it took (#896)
diff --git a/docs/agent-render-jobs.md b/docs/agent-render-jobs.md
index 2ee94f4b..8d5e55a8 100644
--- a/docs/agent-render-jobs.md
+++ b/docs/agent-render-jobs.md
@@ -185,7 +185,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/67js-render-native` 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/67js-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`. 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 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. 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), or `native`, which traces on hardware ray queries (Vulkan) through the optional `@codepawlhq/67js-render-native` 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/67js-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`. 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 or instance transforms are sent to the session; a frame whose counts, geometry, 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`, `pipelineReused` and `accelerationReused`); a single-frame job and `JS67_NATIVE_KERNEL=legacy` trace one-shot and carry no `nativeSession`. The session is closed when the job ends or fails, and every frame equals the one-shot render byte for byte. 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. 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.
## Controller API
diff --git a/docs/cycles-parity.md b/docs/cycles-parity.md
index 867d655a..111d2354 100644
--- a/docs/cycles-parity.md
+++ b/docs/cycles-parity.md
@@ -904,6 +904,25 @@ Measured on one NVIDIA A10 (480 x 270, 32 samples, `bench/cycles-parity/session-
One-shot `traceNative` images (both kernels) and S1 session frames hash the same as origin/main built in the same container.
+## Sequence jobs through a persistent session (#896, slice S3)
+
+A stills or video job with `renderer.backend: "native"` and more than one frame holds one native session for the whole job. Frame 1 creates it; each later frame is decided by comparing its FORMAT-v2 tables with the ones the session holds: the same tables (a camera move) render with the frame's own `kernelParams`; changed `materials`, lights or instance transforms go through `session.update`; changed counts, geometry, textures or environment close the session and create a new one for that frame. A failed update (which closes the session by design), a failed render or a package without sessions falls to a new session or a one-shot trace for that frame and the job carries on. `metrics.pathTracer.nativeSession` names the route of each frame (`path`: `new-session`, `reused`, `updated` or `one-shot`, with `reason`, `changedTables`, `pipelineReused`, `accelerationReused`, `frameIndex`). Every frame equals the one-shot render of the same input byte for byte (`tests/native-sequence.test.js`, and the SHA-256 of all 24 frames in each run below).
+
+Measured on one NVIDIA RTX 4090 (Vast instance, 24 frames, 480 x 270, 16 samples, `bench/cycles-parity/sequence-timing.mjs`, one process per mode so the cold compile of one mode never warms the other; medians of three runs; milliseconds) `[measured]`:
+
+| Sequence | Mode | Frame 1 setup / compile / upload / accel / trace | Frame 2-24 mean setup / compile / upload / accel / trace | Sequence total (s) | Routes |
+| --- | --- | --- | --- | --- | --- |
+| `lit-interior`, camera orbit | session | 300 / 33 / 0.5 / 1.0 / 24 | 0 / 1.8 / 0.1 / 0 / 19 | 1.03 | 1 new, 23 reused |
+| | one-shot | 324 / 32 / 0.5 / 1.7 / 25 | 0 / 1.9 / 0.3 / 0.9 / 18 | 0.98 | |
+| `lit-interior`, block moves and key light swings (flattened) | session | 296 / 33 / 0.5 / 1.2 / 26 | 0 / 1.9 / 0.2 / 0.8 / 21 | 1.02 | 24 new (triangles differ) |
+| | one-shot | 304 / 33 / 0.5 / 1.4 / 27 | 0 / 1.9 / 0.3 / 1.0 / 21 | 1.02 | |
+| same, instanced (`buildTraceScene` `instancing: true`) | session | 295 / 33 / 0.5 / 0.9 / 21 | 0 / 1.8 / 0.0 / 0 / 13 | 0.88 | 1 new, 23 updated |
+| | one-shot | 233 / 34 / 0.5 / 0.8 / 20 | 0 / 1.8 / 0.2 / 0.5 / 13 | 0.75 | |
+| `many-lights-500` (3,646 triangles, 350 lights), camera orbit | session | 302 / 33 / 0.7 / 2.7 / 70 | 0 / 1.9 / 0.1 / 0 / 19 | 1.00 | 1 new, 23 reused |
+| | one-shot | 286 / 33 / 0.7 / 2.6 / 66 | 0 / 1.8 / 0.3 / 2.0 / 18 | 1.32 (one run 7.5 s, two near 1.0) | |
+
+What the numbers say `[inferred]`: a session removes the acceleration build and most of the upload from frame 2 on (camera-only: 0 ms against 0.9 to 2.0 ms of build, 0.1 against 0.3 ms of upload), and `pipelineReused` and `accelerationReused` are true on every later frame. Compile does not read zero: the 1.8 ms is the lookup of the process-wide compiled-kernel cache, which a one-shot trace also hits from its second frame, so a one-shot sequence in a warm process already skips the 33 ms compile and the 240 to 320 ms device start. These scenes hold about 3,000 triangles, so the saving is 1 to 3 ms of a 18 to 25 ms frame and the sequence totals sit within run-to-run noise (the instanced rows show the spread: 0.73 to 1.04 s for the same work). A session pays when the scene is large enough for the build and upload to matter; a bench at that size is not recorded here. A moving object in the flattened scene changes the `triangles` table, so every frame there is a new session (as costly as a one-shot trace); only a scene packed with shared geometry turns a moved object into an instance-transform update.
+
## Reproducible Commands
Run from the repository root in PowerShell. Set `$env:BLENDER_BIN` if Blender 5.3 is installed outside `C:\Program Files\Blender Foundation\Blender 5.3\blender.exe`, and pass an untracked `<out-dir>` (such as `artifacts/cycles-parity`) so binary `.exr` and `.npy` files stay out of Git:
diff --git a/packages/render-native/README.md b/packages/render-native/README.md
index 7cdbf7ac..49d32381 100644
--- a/packages/render-native/README.md
+++ b/packages/render-native/README.md
@@ -72,6 +72,8 @@ A frame may change these words of the 320 byte block: the camera, lens, aperture
A frame is byte-identical to the `traceNative` render of the same input and options: `traceNative` runs a session that renders once. `render` after `close()` throws, and so does a frame on a session whose device was lost; the error says to create a new session. A plain frame clears the film and starts at sample 0.
+A render job of many frames (`scripts/agent-native-sequence.mjs`) keeps one session for its frames: the same tables render with the frame's `kernelParams`, changed values go through `update`, and a refused or failed update, or a render the session cannot do, falls back to a new session or a one-shot trace for that frame. The job report names the route of each frame.
+
### Progressive film
`render({ samples: 16, accumulate: true, targetSamples: 64 })` adds its samples to the film instead of starting an image, so one image can grow over several calls and be read at any point:
diff --git a/scripts/agent-native-sequence.mjs b/scripts/agent-native-sequence.mjs
new file mode 100644
index 00000000..cede5705
--- /dev/null
+++ b/scripts/agent-native-sequence.mjs
@@ -0,0 +1,110 @@
+// One native session per sequence job (issue 896): the first frame of a stills or video job creates a session on the Cycles kernel,
+// and each later frame renders through it. A frame whose scene differs only in the camera reuses the uploaded scene, the compiled
+// kernel and the acceleration structures; one whose materials, lights or instance transforms changed sends those tables; one the
+// session cannot take (other counts, geometry, textures or environment) gets a new session. Every frame equals the one-shot
+// `traceNative` render of the same input byte for byte, and its route says which of these happened.
+import { isNativeTimeLimitError } from './agent-native-trace.mjs';
+
+const SESSION_OPTIONS = { kernel: 'cycles' };
+const FIRST_FRAME_REASON = 'first frame of the sequence';
+const REQUIRED_TRACER_FUNCTIONS = ['createNativeSession', 'planNativeSessionUpdate', 'prepareCyclesInput'];
+
+/**
+ * @param {{ tracer: object }} options `tracer` is the loaded render-native package.
+ * @returns {{ trace(input: object, traceOptions: object): { traced: object, route: object }, close(): void }}
+ * `trace` takes a v1 table set or a FORMAT-v2 input and the `traceNative` options of the frame, and returns the traced
+ * planes with the route the frame took: `path` is "new-session", "reused", "updated" or "one-shot", `reason` says why a
+ * session was created or skipped, and the session's own reuse flags and update report ride along.
+ */
+export function createNativeSequence({ tracer }) {
+ if (tracer === null || typeof tracer !== 'object') {
+ throw new TypeError('createNativeSequence: pass `tracer`, the loaded @codepawlhq/67js-render-native package.');
+ }
+ let session = null;
+ let heldInput = null;
+ let closed = false;
+
+ function closeSession() {
+ const closingSession = session;
+ session = null;
+ heldInput = null;
+ try {
+ closingSession?.close();
+ } catch {
+ // The session is gone either way; the next frame creates a new one.
+ }
+ }
+
+ function missingSessionSupport() {
+ const missing = REQUIRED_TRACER_FUNCTIONS.filter(name => typeof tracer[name] !== 'function');
+ return missing.length === 0 ? null : `the installed render-native package has no ${missing.join(' or ')}`;
+ }
+
+ function traceOnce(input, traceOptions, reason) {
+ return { traced: tracer.traceNative(input, traceOptions), route: { path: 'one-shot', reason } };
+ }
+
+ // Returns null when the open session now holds `nextInput`, otherwise the reason it was closed.
+ function bringSessionUpToDate(nextInput, route) {
+ let changedTables;
+ try {
+ changedTables = Object.keys(tracer.planNativeSessionUpdate(heldInput, nextInput));
+ } catch (error) {
+ closeSession();
+ return error.message;
+ }
+ if (changedTables.length === 0) {
+ route.path = 'reused';
+ return null;
+ }
+ try {
+ const report = session.update(nextInput);
+ heldInput = nextInput;
+ Object.assign(route, { path: 'updated', changedTables, accelerationRebuilt: report.accelerationRebuilt, kernelRespecialized: report.kernelRespecialized,
+ updateSeconds: report.updateSeconds });
+ return null;
+ } catch (error) {
+ // A failed update closes the session by design, so the frame goes to a new one.
+ closeSession();
+ return `the session update failed (${error.message})`;
+ }
+ }
+
+ function createSession(nextInput, route, reason) {
+ session = tracer.createNativeSession(nextInput, SESSION_OPTIONS);
+ heldInput = nextInput;
+ Object.assign(route, { path: 'new-session', reason });
+ }
+
+ return {
+ trace(input, traceOptions) {
+ if (closed) throw new Error('createNativeSequence: this sequence is closed. Create a new one for the next job.');
+ const unsupported = missingSessionSupport();
+ if (unsupported) return traceOnce(input, traceOptions, unsupported);
+ const nextInput = tracer.prepareCyclesInput(input, traceOptions);
+ const route = {};
+ const reasonForNewSession = session ? bringSessionUpToDate(nextInput, route) : FIRST_FRAME_REASON;
+ if (reasonForNewSession !== null) {
+ try {
+ createSession(nextInput, route, reasonForNewSession);
+ } catch (error) {
+ closeSession();
+ return traceOnce(input, traceOptions, `${reasonForNewSession}; creating a session failed (${error.message})`);
+ }
+ }
+ try {
+ const traced = session.render({ ...traceOptions, kernelParams: nextInput.kernelParams });
+ Object.assign(route, { pipelineReused: traced.pipelineReused, accelerationReused: traced.accelerationReused, frameIndex: traced.frameIndex });
+ return { traced, route };
+ } catch (error) {
+ closeSession();
+ if (isNativeTimeLimitError(error)) throw error;
+ return traceOnce(input, traceOptions, `the session render failed (${error.message})`);
+ }
+ },
+ close() {
+ closed = true;
+ closeSession();
+ },
+ };
+}
diff --git a/scripts/agent-native-trace.mjs b/scripts/agent-native-trace.mjs
index 4e4b3adc..c92dc960 100644
--- a/scripts/agent-native-trace.mjs
+++ b/scripts/agent-native-trace.mjs
@@ -159,12 +159,17 @@ export async function denoiseFrameWithOidn({ tracer, denoiser, width, height, co
/**
* Traces one frame the page exported and returns the PNG (base64) with the job report. `denoise` is "none", "wavelet",
* "atrous" (the tracer's GPU filter, which is also where a missing or failing OIDN lands) or "oidn"; `denoiser` is the
- * loaded OIDN package for "oidn". Throws when the tracer cannot run, so the caller can fall back.
+ * loaded OIDN package for "oidn". `sequence` (from createNativeSequence) renders a cycles kernel frame through the job's
+ * persistent session and adds `report.nativeSession`, the route the frame took. Throws when the tracer cannot run, so the
+ * caller can fall back.
*/
-export async function traceFrameNative({ tracer, exported, width, height, samples, bounces, seed, denoise, denoiser, maxSeconds, noiseThreshold = 0, kernel = chooseNativeKernel() }) {
+export async function traceFrameNative({ tracer, exported, width, height, samples, bounces, seed, denoise, denoiser, maxSeconds, noiseThreshold = 0, kernel = chooseNativeKernel(), sequence }) {
const started = performance.now();
const filtersInTrace = denoise === 'atrous' && kernel === 'cycles';
- const traced = tracer.traceNative(decodeTables(exported), { width, height, samples, maxSeconds, kernel, noiseThreshold, ...(filtersInTrace ? { denoise: 'atrous' } : {}) });
+ const traceOptions = { width, height, samples, maxSeconds, kernel, noiseThreshold, ...(filtersInTrace ? { denoise: 'atrous' } : {}) };
+ const { traced, route } = sequence && kernel === 'cycles'
+ ? sequence.trace(decodeTables(exported), traceOptions)
+ : { traced: tracer.traceNative(decodeTables(exported), traceOptions) };
const tracedSeconds = (performance.now() - started) / 1000;
const pixelCount = width * height;
const features = { color: withoutAlpha(traced.rgba, pixelCount), albedo: traced.albedo, normal: traced.normal,
@@ -173,7 +178,8 @@ export async function traceFrameNative({ tracer, exported, width, height, sample
const report = { width, height, samples, bounces, seed, denoised: false, denoiser: 'none', threads: 1, backend: 'native',
gpu: traced.adapter, nativeBackend: traced.backend, nativeFeatures: traced.features, setupSeconds: traced.setupSeconds, compileSeconds: traced.compileSeconds,
uploadSeconds: traced.uploadSeconds, accelerationBuildSeconds: traced.accelerationBuildSeconds,
- kernel, averageSamples: traced.averageSamples ?? samples, noiseThreshold, triangles: exported.triangles, tracedSeconds, ignored: exported.ignored };
+ kernel, averageSamples: traced.averageSamples ?? samples, noiseThreshold, triangles: exported.triangles, tracedSeconds, ignored: exported.ignored,
+ ...(route ? { nativeSession: route } : {}) };
let linear = features.color;
const denoiseStarted = performance.now();
if (denoise === 'oidn') {
diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjs
index f20b7b5e..3059eed4 100644
--- a/scripts/agent-runtime.mjs
+++ b/scripts/agent-runtime.mjs
@@ -15,6 +15,7 @@ import { MATERIAL_SNIPPET_CAPABILITIES } from '../src/material-snippet.js';
import { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, RENDER_PASS_NAMES, RENDER_PASS_DEPTH_RANGE, VIDEO_ENCODERS, MAXIMUM_VIDEO_SECONDS, MAXIMUM_JOB_SIDE, MAXIMUM_JOB_PIXELS, MAXIMUM_MEMORY_MIB, BAKE_WORKER_MAXIMUM_SECONDS } from '../src/agent-scene-capabilities.js';
import { PATH_TRACER_CAPABILITIES } from '../src/path-tracer-capabilities.js';
import { chooseDenoiser, finishWithOidn } from './agent-path-trace-denoise.mjs';
+import { createNativeSequence } from './agent-native-sequence.mjs';
import { chooseTraceBackend, createNativeTracerLocator, isNativeTimeLimitError, traceFrameNative, traceTexelsNative } from './agent-native-trace.mjs';
import { createAgentAssetCatalog } from './agent-asset-catalog.mjs';
import { geometryOnlyGlb } from './agent-query-asset.mjs';
@@ -463,6 +464,8 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
let jobPage;
let encoder;
let frameReceiver;
+ // A stills or video job of native frames renders them all through one session; it is closed when the job ends.
+ let nativeSequence;
let pageEncodes = false;
let suspended = false;
const started = performance.now();
@@ -566,12 +569,14 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
if (trace.backend === 'native') {
try {
const exported = await jobPage.evaluate(input => window.__agentPreview.exportNativeScene(input), { ...frameInput, options: { width, height, bounces: tracerOptions.bounces, seed: tracerOptions.seed, fireflyClamp: 20, noiseThreshold: tracerOptions.noiseThreshold } });
- traced = await traceFrameNative({ tracer: trace.tracer, exported, width, height, samples: tracerOptions.samples, bounces: tracerOptions.bounces,
+ if (settings.frameCount > 1) nativeSequence ??= createNativeSequence({ tracer: trace.tracer });
+ traced = await traceFrameNative({ tracer: trace.tracer, sequence: nativeSequence, exported, width, height, samples: tracerOptions.samples, bounces: tracerOptions.bounces,
seed: tracerOptions.seed, denoise: choice.denoise === true ? 'wavelet' : choice.denoise === false ? 'none' : choice.denoise, denoiser: choice.denoiser,
maxSeconds: tracerOptions.maxSeconds, noiseThreshold: tracerOptions.noiseThreshold });
} catch (error) {
// Past maxSeconds the job fails as it does on every backend; falling back would only run it twice as long.
if (isNativeTimeLimitError(error)) throw error;
+ nativeSequence?.close();
nativeTracerLocator.markUnusable(error.message);
backendNote = (await nativeTracerLocator.find()).reason;
traceOptions.backend = backend === 'cpu' ? 'cpu' : 'gpu';
@@ -726,6 +731,7 @@ export function createAgentRuntime({ kernelWorkers = true, backend = 'gpu', brow
return { artifacts, metrics };
} finally {
signal.removeEventListener('abort', abort);
+ nativeSequence?.close();
activeFrameReceiver = undefined;
frameReceiver?.close();
try { await encoder?.close(); }
diff --git a/tests/native-sequence.test.js b/tests/native-sequence.test.js
new file mode 100644
index 00000000..efb99e6d
--- /dev/null
+++ b/tests/native-sequence.test.js
@@ -0,0 +1,257 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import * as renderNative from '../packages/render-native/index.mjs';
+import { createNativeSequence } from '../scripts/agent-native-sequence.mjs';
+import { traceFrameNative } from '../scripts/agent-native-trace.mjs';
+import { createCamera } from '../src/path-tracer.js';
+
+const addonIsBuilt = renderNative.findNativeAddon() !== null;
+const skipWithoutAddon = addonIsBuilt ? false : 'the native addon is not built';
+const TRACE_OPTIONS = { width: 4, height: 4, samples: 2, maxSeconds: 5, kernel: 'cycles' };
+
+// ---- The frame loop's decisions, with a stand-in for the package ----
+
+function inputWith({ materialByte = 1, instanceCount = 1, camera = 0, geometryByte = 0 } = {}) {
+ return {
+ schemaVersion: 2,
+ kernelParams: new Uint8Array([camera]),
+ instanceCount,
+ instances: new Uint8Array(instanceCount * 160),
+ materialCount: 1,
+ materials: new Uint8Array([materialByte]),
+ triangleCount: 1,
+ triangles: new Uint8Array([geometryByte]),
+ };
+}
+
+function fakeTracer({ failUpdate = false, failRender = null, failCreate = false, withSessions = true } = {}) {
+ const events = [];
+ const tracer = {
+ events,
+ prepareCyclesInput: input => input,
+ planNativeSessionUpdate: renderNative.planNativeSessionUpdate,
+ traceNative(input, options) {
+ events.push(['one-shot', options.kernel]);
+ return { rgba: new Float32Array(4), oneShot: true };
+ },
+ };
+ if (withSessions) {
+ let sessionNumber = 0;
+ tracer.createNativeSession = input => {
+ if (failCreate) throw new Error('no adapter');
+ sessionNumber += 1;
+ const id = sessionNumber;
+ let frames = 0;
+ events.push(['create', id]);
+ return {
+ update(next) {
+ events.push(['update', id]);
+ if (failUpdate) throw new Error('the card failed part way');
+ return { accelerationRebuilt: false, kernelRespecialized: false, updateSeconds: 0.5, input: next };
+ },
+ render(frameOptions) {
+ events.push(['render', id, Array.from(frameOptions.kernelParams)]);
+ if (failRender) throw failRender;
+ frames += 1;
+ return { rgba: new Float32Array(4), pipelineReused: frames > 1, accelerationReused: frames > 1, frameIndex: frames - 1 };
+ },
+ close() {
+ events.push(['close', id]);
+ },
+ };
+ };
+ }
+ return tracer;
+}
+
+test('the first frame creates a session and a camera-only frame reuses it with its own kernel parameters', () => {
+ const tracer = fakeTracer();
+ const sequence = createNativeSequence({ tracer });
+ const first = sequence.trace(inputWith({ camera: 1 }), TRACE_OPTIONS);
+ assert.equal(first.route.path, 'new-session');
+ assert.equal(first.route.reason, 'first frame of the sequence');
+ const second = sequence.trace(inputWith({ camera: 2 }), TRACE_OPTIONS);
+ assert.deepEqual(second.route, { path: 'reused', pipelineReused: true, accelerationReused: true, frameIndex: 1 });
+ assert.deepEqual(tracer.events, [['create', 1], ['render', 1, [1]], ['render', 1, [2]]]);
+});
+
+test('a frame with other materials sends the changed tables through update and keeps the session', () => {
+ const tracer = fakeTracer();
+ const sequence = createNativeSequence({ tracer });
+ sequence.trace(inputWith(), TRACE_OPTIONS);
+ const { route } = sequence.trace(inputWith({ materialByte: 9 }), TRACE_OPTIONS);
+ assert.equal(route.path, 'updated');
+ assert.deepEqual(route.changedTables, ['materials']);
+ assert.equal(route.accelerationRebuilt, false);
+ assert.equal(route.updateSeconds, 0.5);
+ assert.deepEqual(tracer.events.map(event => event[0]), ['create', 'render', 'update', 'render']);
+});
+
+test('a frame the session cannot take closes it and starts a new one, saying what changed', () => {
+ const tracer = fakeTracer();
+ const sequence = createNativeSequence({ tracer });
+ sequence.trace(inputWith(), TRACE_OPTIONS);
+ const counted = sequence.trace(inputWith({ instanceCount: 2 }), TRACE_OPTIONS);
+ assert.equal(counted.route.path, 'new-session');
+ assert.match(counted.route.reason, /`instanceCount` changes from 1 to 2/);
+ const geometry = sequence.trace(inputWith({ instanceCount: 2, geometryByte: 5 }), TRACE_OPTIONS);
+ assert.equal(geometry.route.path, 'new-session');
+ assert.match(geometry.route.reason, /`triangles` differs/);
+ assert.deepEqual(tracer.events.filter(event => event[0] !== 'render'), [['create', 1], ['close', 1], ['create', 2], ['close', 2], ['create', 3]]);
+});
+
+test('a failed update, which closes the session by design, falls to a new session for that frame', () => {
+ const tracer = fakeTracer({ failUpdate: true });
+ const sequence = createNativeSequence({ tracer });
+ sequence.trace(inputWith(), TRACE_OPTIONS);
+ const { route } = sequence.trace(inputWith({ materialByte: 9 }), TRACE_OPTIONS);
+ assert.equal(route.path, 'new-session');
+ assert.match(route.reason, /the session update failed \(the card failed part way\)/);
+ assert.deepEqual(tracer.events.map(event => event[0]), ['create', 'render', 'update', 'close', 'create', 'render']);
+ const next = sequence.trace(inputWith({ materialByte: 9, camera: 3 }), TRACE_OPTIONS);
+ assert.equal(next.route.path, 'reused', 'the new session carries the sequence on');
+});
+
+test('a package without sessions, or a card that cannot make one, traces each frame one-shot and says why', () => {
+ const old = createNativeSequence({ tracer: fakeTracer({ withSessions: false }) });
+ const oldFrame = old.trace(inputWith(), TRACE_OPTIONS);
+ assert.equal(oldFrame.route.path, 'one-shot');
+ assert.match(oldFrame.route.reason, /no createNativeSession/);
+ assert.equal(oldFrame.traced.oneShot, true);
+
+ const refusing = createNativeSequence({ tracer: fakeTracer({ failCreate: true }) });
+ const refusedFrame = refusing.trace(inputWith(), TRACE_OPTIONS);
+ assert.equal(refusedFrame.route.path, 'one-shot');
+ assert.match(refusedFrame.route.reason, /first frame of the sequence; creating a session failed \(no adapter\)/);
+});
+
+test('a render that fails falls back one-shot and the next frame starts a new session, but a time limit passes through', () => {
+ const failing = fakeTracer({ failRender: new Error('device lost') });
+ const sequence = createNativeSequence({ tracer: failing });
+ const frame = sequence.trace(inputWith(), TRACE_OPTIONS);
+ assert.equal(frame.route.path, 'one-shot');
+ assert.match(frame.route.reason, /the session render failed \(device lost\)/);
+ assert.deepEqual(failing.events.map(event => event[0]), ['create', 'render', 'close', 'one-shot']);
+
+ const slow = fakeTracer({ failRender: new Error('the trace passed its time limit') });
+ assert.throws(() => createNativeSequence({ tracer: slow }).trace(inputWith(), TRACE_OPTIONS), /time limit/);
+ assert.deepEqual(slow.events.map(event => event[0]), ['create', 'render', 'close']);
+});
+
+test('closing frees the session and a closed sequence refuses a frame', () => {
+ const tracer = fakeTracer();
+ const sequence = createNativeSequence({ tracer });
+ sequence.trace(inputWith(), TRACE_OPTIONS);
+ sequence.close();
+ sequence.close();
+ assert.deepEqual(tracer.events.filter(event => event[0] === 'close'), [['close', 1]]);
+ assert.throws(() => sequence.trace(inputWith(), TRACE_OPTIONS), /sequence is closed/);
+ assert.throws(() => createNativeSequence({}), { name: 'TypeError', message: /pass `tracer`/ });
+});
+
+const emptyExport = {
+ triangleCount: 0, triangles: 0, ignored: [],
+ tables: Object.fromEntries(['triangles', 'materials', 'lights', 'atlas', 'environmentColors', 'environmentTables', 'parameters'].map(name => [name, ''])),
+};
+
+test('traceFrameNative reports the route of a sequence frame, and a single frame carries none', async () => {
+ const pixels = 16;
+ const plane = (count) => new Float32Array(pixels * count);
+ const traced = { rgba: plane(4), albedo: plane(3), normal: plane(3), depth: plane(1), variance: plane(1), adapter: 'test', backend: 'test' };
+ const tracer = { traceNative: () => traced };
+ const route = { path: 'reused', frameIndex: 3 };
+ const sequenceCalls = [];
+ const sequence = { trace: (input, options) => { sequenceCalls.push(options.kernel); return { traced, route }; } };
+ const common = { tracer, exported: emptyExport, width: 4, height: 4, samples: 2, denoise: 'none' };
+
+ const viaSequence = await traceFrameNative({ ...common, sequence, kernel: 'cycles' });
+ assert.deepEqual(viaSequence.report.nativeSession, route);
+ assert.deepEqual(sequenceCalls, ['cycles']);
+
+ const single = await traceFrameNative({ ...common, kernel: 'cycles' });
+ assert.equal('nativeSession' in single.report, false);
+ const legacy = await traceFrameNative({ ...common, sequence, kernel: 'legacy' });
+ assert.equal('nativeSession' in legacy.report, false, 'the legacy kernel has no sessions');
+ assert.deepEqual(sequenceCalls, ['cycles']);
+});
+
+// ---- Identity against the one-shot render: needs the built addon and a Vulkan ray query adapter ----
+
+const UNIT_QUAD = {
+ positions: new Float32Array([-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0]),
+ normals: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1]),
+ uvs: new Float32Array([0, 1, 1, 1, 1, 0, 0, 0]),
+ colors: new Float32Array(12).fill(1),
+ indices: new Uint32Array([0, 1, 2, 0, 2, 3]),
+};
+const IMAGE_OPTIONS = { width: 24, height: 16, samples: 16, bounces: 3, seed: 11 };
+const RESULT_PLANES = ['rgba', 'albedo', 'normal', 'depth', 'variance'];
+
+function horizontalQuadMatrix(scale, height, facesUp) {
+ const upOrDown = facesUp ? 1 : -1;
+ return [scale, 0, 0, 0, 0, 0, -upOrDown * scale, 0, 0, upOrDown * scale, 0, 0, 0, height, 0, 1];
+}
+
+function frameOf({ eye = [0, 2.2, 6], floorColor = [0.6, 0.6, 0.6], lampEmission = 5, lampHeight = 2, extraQuad = false }) {
+ const scene = {
+ materials: [{ color: floorColor, roughness: 0.8 }, { color: [1, 0.95, 0.9], emission: lampEmission, roughness: 1 }],
+ instances: [
+ { geometry: UNIT_QUAD, matrix: horizontalQuadMatrix(8, 0, true), materialIndex: 0 },
+ { geometry: UNIT_QUAD, matrix: horizontalQuadMatrix(2, 3, false), materialOverride: 1 },
+ { geometry: UNIT_QUAD, matrix: horizontalQuadMatrix(1, lampHeight, false), materialOverride: 1 },
+ ],
+ };
+ if (extraQuad) scene.instances.push({ geometry: UNIT_QUAD, matrix: horizontalQuadMatrix(1, 1, true), materialIndex: 0 });
+ const camera = createCamera({ eye, target: [0, 0.5, 0], fov: 45 }, IMAGE_OPTIONS.width, IMAGE_OPTIONS.height);
+ return renderNative.buildNativeInputV2(scene, camera, IMAGE_OPTIONS);
+}
+
+function sameBytes(first, second) {
+ return RESULT_PLANES.every(plane => Buffer.from(first[plane].buffer, first[plane].byteOffset, first[plane].byteLength)
+ .equals(Buffer.from(second[plane].buffer, second[plane].byteOffset, second[plane].byteLength)));
+}
+
+// Renders every frame through one sequence and one-shot, requires the same bytes, and returns the routes.
+function paths(frameSpecs) {
+ const options = { ...IMAGE_OPTIONS, kernel: 'cycles' };
+ const sequence = createNativeSequence({ tracer: renderNative });
+ try {
+ return frameSpecs.map((spec, index) => {
+ const input = frameOf(spec);
+ const { traced, route } = sequence.trace(input, options);
+ assert.ok(sameBytes(traced, renderNative.traceNative(input, options)), `frame ${index} differs from the one-shot render`);
+ return { route, traced };
+ });
+ } finally {
+ sequence.close();
+ }
+}
+
+test('a camera orbit through a session equals one-shot frames and builds nothing after frame 1', { skip: skipWithoutAddon }, () => {
+ const frames = paths([{ eye: [0, 2.2, 6] }, { eye: [1.5, 2.2, 5.5] }, { eye: [3, 2.2, 4.5] }]);
+ assert.deepEqual(frames.map(frame => frame.route.path), ['new-session', 'reused', 'reused']);
+ for (const { traced, route } of frames.slice(1)) {
+ assert.equal(route.pipelineReused, true, 'the kernel is held, not compiled again');
+ assert.equal(route.accelerationReused, true);
+ assert.equal(traced.setupSeconds, 0);
+ assert.equal(traced.accelerationBuildSeconds, 0);
+ }
+});
+
+test('a material, a light and a transform sequence equal one-shot frames and update in place', { skip: skipWithoutAddon }, () => {
+ const frames = paths([
+ { },
+ { floorColor: [0.2, 0.5, 0.8], eye: [1, 2.2, 6] },
+ { floorColor: [0.2, 0.5, 0.8], lampEmission: 9 },
+ { floorColor: [0.2, 0.5, 0.8], lampEmission: 9, lampHeight: 2.4 },
+ ]);
+ assert.deepEqual(frames.map(frame => frame.route.path), ['new-session', 'updated', 'updated', 'updated']);
+ assert.deepEqual(frames[1].route.changedTables, ['materials']);
+ assert.equal(frames[3].route.accelerationRebuilt, true);
+});
+
+test('a sequence that changes its instance count mid-way falls back to a new session and carries on identically', { skip: skipWithoutAddon }, () => {
+ const frames = paths([{ }, { eye: [1, 2.2, 6] }, { extraQuad: true }, { extraQuad: true, eye: [2, 2.2, 5] }]);
+ assert.deepEqual(frames.map(frame => frame.route.path), ['new-session', 'reused', 'new-session', 'reused']);
+ assert.match(frames[2].route.reason, /instanceCount/);
+});