3D engine that AI agents drive
JavaScript 3d3d-engineagentic-aiai-agentsblenderclaude-codegame-enginegaussian-splattinggltfjavascriptmcpmcp-servermodel-context-protocolpath-tracerpath-tracingpbrrenderingthreejs-alternativewebgl2webgpu
Patch the shared prefix when the native triangle table changes length (#2180)
Nguyen Xuan An4b23a20dffb2
diff --git a/.github/workflows/cook-addon.yml b/.github/workflows/cook-addon.ymlindex ef03bd42..5df4a76f 100644--- a/.github/workflows/cook-addon.yml+++ b/.github/workflows/cook-addon.yml@@ -60,6 +60,7 @@ on:- 'scripts/render-file-native.mjs'- 'scripts/render-vite.config.mjs'- 'scripts/vite-site-pages.mjs'+ - 'src/agent-apply-report.js'- 'src/agent-bake-gpu.js'- 'src/agent-bake.js'- 'src/agent-clip-layers.js'@@ -85,6 +86,7 @@ on:- 'src/agent-scene-assets.js'- 'src/agent-scene-capabilities.js'- 'src/agent-scene-modules.js'+ - 'src/agent-scene.js'- 'src/agent-settle.js'- 'src/agent-terrain.js'- 'src/agent-texture-sequence.js'@@ -156,10 +158,11 @@ on:- 'src/impostor-shader.js'- 'src/irradiance-grid.js'- 'src/kernel-offload.js'+ - 'src/legacy-names.js'- 'src/light-bake-gpu.js'- 'src/light-bake.js'- - 'src/light-limits.js'- 'src/light-limit-advice.js'+ - 'src/light-limits.js'- 'src/light-link-bits.js'- 'src/light-linking.js'- 'src/light-modules.js'@@ -187,6 +190,7 @@ on:- 'src/material-patterns.js'- 'src/material-snippet.js'- 'src/material-texture-kit.js'+ - 'src/material-wear.js'- 'src/mesh-attribute-edits.js'- 'src/mesh-bevel.js'- 'src/mesh-bisect.js'@@ -265,6 +269,7 @@ on:- 'src/particle-emitter-mesh.js'- 'src/particle-sparks.js'- 'src/particles.js'+ - 'src/path-trace-terms.js'- 'src/path-tracer-blue-noise.js'- 'src/path-tracer-denoise.js'- 'src/path-tracer-gpu-pack.js'@@ -308,6 +313,7 @@ on:- 'src/rig-presets.js'- 'src/rig.js'- 'src/rotation-euler.js'+ - 'src/scene-graph.js'- 'src/sculpt-strokes.js'- 'src/seeded-random.js'- 'src/settle.js'diff --git a/changes/2180.md b/changes/2180.mdnew file mode 100644index 00000000..834b8bba--- /dev/null+++ b/changes/2180.md@@ -0,0 +1 @@+- A native video frame whose scene table changes length (a particle part under flush ranking) now sends the changes in the bytes it shares with the old table plus the new tail, instead of the whole table: on the particle clip a frame sends about 50 percent of the tables where it sent 76 percent; the video is the same bytes (#2180).diff --git a/docs/agent-render-jobs.md b/docs/agent-render-jobs.mdindex 6602c8b8..cf55a011 100644--- a/docs/agent-render-jobs.md+++ b/docs/agent-render-jobs.md@@ -248,7 +248,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), 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; a table that changed length sends the changes in the bytes it shares with the old one and the new tail), 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/native-export-delta.js b/scripts/native-export-delta.jsindex 54c15996..7bba7972 100644--- a/scripts/native-export-delta.js+++ b/scripts/native-export-delta.js@@ -3,7 +3,7 @@// The page packs the whole scene every frame, and almost all of the bytes come out the same: the static meshes, the lights, the// environment. The page keeps the tables of its last export, finds the byte ranges that differ and puts only those in the Blob// the job runner reads. The job runner holds the tables it got last time and patches them, so it ends with the same bytes a full-// export gives. This file is shared by the page (planning) and the job runner (patching); it touches no browser or Node API.+// export gives; a table of another length patches the bytes it shares with the old one, then appends or cuts (#2180). This file is shared by the page (planning) and the job runner (patching); it touches no browser or Node API./** Two changed words closer than this many bytes share one range, so a particle tail is a few ranges instead of thousands. */export const DELTA_GAP_BYTES = 1024;@@ -55,15 +55,36 @@ export function changedRanges(before, after) {return ranges.length > DELTA_MAXIMUM_RANGES ? null : ranges;}+/**+ * The ranges that turn `before` into `after` when the two tables have different lengths: the changes inside the bytes both hold+ * (the shared prefix), then everything past the old end when `after` is longer. A shorter `after` needs no more ranges, since the+ * applier cuts the old table to the new length. Returns null when the prefix changes in too many places.+ */+export function prefixPatchRanges(before, after) {+ const sharedBytes = Math.min(before.byteLength, after.byteLength);+ const ranges = changedRanges(before.subarray(0, sharedBytes), after.subarray(0, sharedBytes));+ if (ranges === null) return null;+ if (after.byteLength === sharedBytes) return ranges;+ const last = ranges[ranges.length - 1];+ if (last && last[0] + last[1] === sharedBytes) {+ last[1] = after.byteLength - last[0];+ } else {+ ranges.push([sharedBytes, after.byteLength - sharedBytes]);+ }+ return ranges;+}+/*** What to send of `tables` (name to Uint8Array) given the `previous` ones: name to a list of `[offset, length]` ranges. A table- * with no previous one, another length or too many changes is one range over all of it; an unchanged table is an empty list.+ * with no previous one or too many changes is one range over all of it; an unchanged table is an empty list. A table of another+ * length than before sends the changes in the bytes it shares with the old one, then the bytes past the old end (#2180).*/export function planExportDelta(previous, tables) {const ranges = {};for (const [name, bytes] of Object.entries(tables)) {const before = previous[name];- const changed = before && before.byteLength === bytes.byteLength ? changedRanges(before, bytes) : null;+ let changed = null;+ if (before) changed = before.byteLength === bytes.byteLength ? changedRanges(before, bytes) : prefixPatchRanges(before, bytes);ranges[name] = changed ?? [[0, bytes.byteLength]];}return ranges;@@ -98,6 +119,17 @@ function requireRangesInside(name, list, byteLength) {}}+// Whether the ranges (in order, not overlapping) between them cover every byte from `start` to the end of the table.+function coversFrom(list, start, end) {+ let covered = start;+ for (const [offset, length] of list) {+ if (offset + length <= covered) continue;+ if (offset > covered) return false;+ covered = offset + length;+ }+ return covered >= end;+}+/*** The full tables from the bytes a delta sent. `lengths` is the byte length of every table now, `ranges` what was sent, `sent` the* bytes of all ranges back to back, and `previous` the tables of the export the delta was made against. A table that changed gets a@@ -121,10 +153,14 @@ export function applyExportDelta({ previous, lengths, ranges, sent }) {cursor += byteLength;continue;}- if (before?.byteLength !== byteLength) {- throw new RangeError(`The native scene export sent only part of table "${name}", but the tables held here have ${before ? before.byteLength : 'no'} bytes for it, not ${byteLength}. Export the scene again without a baseline.`);+ if (!before) {+ throw new RangeError(`The native scene export sent only part of table "${name}", but the tables held here have no bytes for it. Export the scene again without a baseline.`);+ }+ if (before.byteLength < byteLength && !coversFrom(list, before.byteLength, byteLength)) {+ throw new RangeError(`The native scene export grew table "${name}" from ${before.byteLength} to ${byteLength} bytes but sent nothing for the bytes past the old end. Export the scene again without a baseline.`);}- const patched = before.slice();+ const patched = new Uint8Array(byteLength);+ patched.set(before.subarray(0, Math.min(before.byteLength, byteLength)));for (const [offset, length] of list) {patched.set(sent.subarray(cursor, cursor + length), offset);cursor += length;diff --git a/tests/native-export-delta.test.js b/tests/native-export-delta.test.jsindex 67b18bdf..10111399 100644--- a/tests/native-export-delta.test.js+++ b/tests/native-export-delta.test.js@@ -11,7 +11,7 @@ import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';import { collectExportBlob, createNativeTracerLocator, fetchNativeExport } from '../scripts/agent-native-trace.mjs';import {- DELTA_GAP_BYTES, DELTA_MAXIMUM_RANGES, applyExportDelta, changedRanges, deltaByteLength, deltaPieces, planExportDelta,+ DELTA_GAP_BYTES, DELTA_MAXIMUM_RANGES, applyExportDelta, changedRanges, deltaByteLength, deltaPieces, planExportDelta, prefixPatchRanges,} from '../scripts/native-export-delta.js';import { cookInstalled } from './support/cook.js';@@ -67,7 +67,7 @@ test('a delta rebuilds the same tables a full export gives, and leaves the previconst frozenPrevious = structuredClone(previous);const ranges = planExportDelta(previous, tables);assert.deepEqual(ranges.materials, []);- assert.deepEqual(ranges.lights, [[0, 130]], 'a table of another length goes whole');+ assert.deepEqual(ranges.lights, [[128, 2]], 'a longer table sends its new tail, not the whole table');assert.ok(deltaByteLength(ranges) < 3000, `only the changes cross, not ${deltaByteLength(ranges)} bytes`);const sent = concatenate(deltaPieces(tables, ranges));assert.equal(sent.byteLength, deltaByteLength(ranges));@@ -79,6 +79,55 @@ test('a delta rebuilds the same tables a full export gives, and leaves the previassert.deepEqual(previous, frozenPrevious);});+function roundTrip(previous, tables) {+ const ranges = planExportDelta(previous, tables);+ const lengths = Object.fromEntries(Object.entries(tables).map(([name, bytes]) => [name, bytes.byteLength]));+ const sent = concatenate(deltaPieces(tables, ranges));+ return { ranges, sent, rebuilt: applyExportDelta({ previous, lengths, ranges, sent }) };+}++test('a table that grows sends the changes in the shared prefix and the new tail, and rebuilds the full table', () => {+ const previous = { triangles: patternBytes(60000, 1) };+ const grown = new Uint8Array(60000 + 36);+ grown.set(withChanges(previous.triangles, [[7000, 1], [59990, 2]]));+ grown.set(patternBytes(36, 9), 60000);+ const { ranges, sent, rebuilt } = roundTrip(previous, { triangles: grown });+ assert.deepEqual(rebuilt.triangles, grown);+ assert.ok(sent.byteLength < 200, `a growing table sent ${sent.byteLength} of ${grown.byteLength} bytes`);+ assert.ok(ranges.triangles.length > 1 || ranges.triangles[0][1] < grown.byteLength, 'the table does not go whole');+ assert.equal(ranges.triangles.at(-1)[0] + ranges.triangles.at(-1)[1], grown.byteLength, 'the tail is sent');+});++test('a table that shrinks sends only the changes in the bytes it keeps, and rebuilds the full table', () => {+ const previous = { triangles: patternBytes(60000, 1) };+ const shrunk = withChanges(previous.triangles.subarray(0, 59904), [[100, 3], [40000, 4]]);+ const { ranges, sent, rebuilt } = roundTrip(previous, { triangles: shrunk });+ assert.deepEqual(rebuilt.triangles, shrunk);+ assert.equal(rebuilt.triangles.byteLength, 59904);+ assert.ok(sent.byteLength < 100, `a shrinking table sent ${sent.byteLength} of ${shrunk.byteLength} bytes`);+ assert.equal(previous.triangles.byteLength, 60000, 'the previous table is left alone');+ const onlyTruncated = roundTrip(previous, { triangles: previous.triangles.slice(0, 59904) });+ assert.deepEqual(onlyTruncated.ranges.triangles, []);+ assert.deepEqual(onlyTruncated.rebuilt.triangles, previous.triangles.slice(0, 59904));+});++test('a table that grows or shrinks keeps going whole when its shared prefix changes in too many places', () => {+ const stride = DELTA_GAP_BYTES + 8;+ const before = new Uint8Array((DELTA_MAXIMUM_RANGES + 5) * stride);+ const after = new Uint8Array(before.byteLength + 64);+ for (let index = 0; index < DELTA_MAXIMUM_RANGES + 5; index++) after[index * stride] = 1;+ assert.equal(prefixPatchRanges(before, after), null);+ assert.deepEqual(planExportDelta({ triangles: before }, { triangles: after }), { triangles: [[0, after.byteLength]] });+});++test('a growing table with the tail the delta lacks is refused, and an unchanged table that shrinks is cut', () => {+ const previous = { triangles: patternBytes(16, 1) };+ assert.throws(() => applyExportDelta({ previous, lengths: { triangles: 24 }, ranges: { triangles: [[0, 4]] }, sent: new Uint8Array(4) }), /grew table "triangles" from 16 to 24 bytes/);+ assert.throws(() => applyExportDelta({ previous, lengths: { triangles: 24 }, ranges: { triangles: [[0, 4], [20, 4]] }, sent: new Uint8Array(8) }), /grew table/);+ const cut = applyExportDelta({ previous, lengths: { triangles: 8 }, ranges: { triangles: [] }, sent: new Uint8Array(0) });+ assert.deepEqual(cut.triangles, previous.triangles.slice(0, 8));+});+test('applyExportDelta refuses ranges outside a table, a short blob and a table it does not hold', () => {const previous = { triangles: patternBytes(16, 1) };const lengths = { triangles: 16 };@@ -206,6 +255,43 @@ function particleRecipe() {environment: { setup: 'sunset' }, camera: { eye: [0, 3, 6], target: [0, 0.5, -1], fov: 50 } };}+// The tables of the particle clip's frames, packed the way the page exports them for the native tracer, without the tracer.+async function exportClipTables(recipe, frameTimes) {+ const [{ createAgentScene, loadAllAgentSceneModules }, { exportNativeSceneTables, splitExportForChunks }, { createCamera }, { buildTraceScene, resolveTexture },+ pack, { buildNativeInput }, { buildJobNativeInput, buildFlattenedJobNativeInput }, { pathTraceEnvironment }] = await Promise.all([+ import('../src/agent-scene.js'), import('../scripts/native-bake-page.js'), import('../src/path-tracer.js'), import('../src/path-tracer-scene.js'),+ import('../src/path-tracer-gpu-pack.js'), import('@codepawlhq/cook/pack-input'), import('@codepawlhq/cook/job-input'), import('../src/path-trace-terms.js'),+ ]);+ const gridVolumeInput = await import('@codepawlhq/cook/grid-volume-input').catch(() => ({}));+ await loadAllAgentSceneModules();+ const scene = createAgentScene(recipe, {}, {});+ const options = { width: 64, height: 64, bounces: 2, seed: 1, fireflyClamp: 20, noiseThreshold: 0, samples: 2 };+ return frameTimes.map(time => {+ scene.sampleMotion(time);+ const packed = exportNativeSceneTables({ parts: scene.parts, environment: pathTraceEnvironment(scene.environment), camera: createCamera(scene.camera, 64, 64), options,+ kernel: 'cycles', instancing: true, transport: 'chunks',+ modules: { buildTraceScene, resolveTexture, buildNativeInput, buildJobNativeInput, buildFlattenedJobNativeInput, pack, gridVolumeInput } });+ return splitExportForChunks(packed).tables;+ });+}++test('the frames of the particle clip with flush ranking on change table lengths, and the delta sends no more than the 60 percent a same-length frame needs',+ { skip: !cookInstalled && 'Cook is not installed' }, async () => {+ const frames = await exportClipTables(particleRecipe(), [1, 1 + 1 / 6, 1 + 2 / 6, 1 + 3 / 6, 1 + 4 / 6, 2]);+ let lengthChanges = 0;+ for (let frame = 1; frame < frames.length; frame++) {+ const previous = frames[frame - 1];+ const tables = frames[frame];+ for (const name of Object.keys(tables)) lengthChanges += previous[name].byteLength === tables[name].byteLength ? 0 : 1;+ const { ranges, sent, rebuilt } = roundTrip(previous, tables);+ assert.deepEqual(rebuilt, tables, `frame ${frame} patched is not the full export`);+ const total = Object.values(tables).reduce((sum, bytes) => sum + bytes.byteLength, 0);+ if (process.env.CRUCIBLE_PRINT_DELTA) console.log(`frame ${frame}: sent ${sent.byteLength} of ${total} bytes`, Object.fromEntries(Object.entries(tables).map(([name, bytes]) => [name, bytes.byteLength - previous[name].byteLength])));+ assert.ok(deltaByteLength(ranges) < total * 0.6, `frame ${frame} sent ${sent.byteLength} of ${total} bytes`);+ }+ assert.ok(lengthChanges > 0, 'the clip no longer changes a table length, so it does not pin the prefix patch');+ });+async function renderClip(workDirectory, label, deltaSwitch) {const transport = new StdioClientTransport({command: process.execPath,