Skip to content

armgit / kiln

Public Imported from GitHub
0

Build and revise procedural 3D assets with your coding agent. Local MCP server, CLI and TypeScript engine with rendered review, editable source and GLB export.

Pay three repeated large-asset costs once: atlas validation, shared topology, cold-start cache identity (#343)

Matthew Kissinger47364c0ebd6e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 91f5a26e..e0c13b3d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,18 @@ does not publish a package.
## Unreleased
+- Three repeated costs on large assets are paid once. Measured on the 2,635,224-triangle cathedral, whose
+ 1,707 meshes share 184 geometries:
+ - The open-surface penetration rule measures each shared geometry's topology once per pass. The
+ pass goes from 3.9 s to 0.5 s and an in-process cold build from 23 s to 20 s. The evidence is
+ byte-identical.
+ - An unchanged atlas provenance table is validated once rather than by every reader. Loading the
+ review scene goes from 1.4 s to 1.1 s. An entry answers only while the table's canonical JSON is
+ unchanged, so an edit in place is validated again.
+ - A host that found no render service at startup now knows the capture identity before its first
+ render. That first capture is cached like any other: its repeat is a hit, where before it rendered
+ again (4.9 s instead of about 2 s for the default grid). The identity follows the port's own
+ connection, so the start it makes is the one the first request would make.
- `KILN_EVALUATOR_TIMEOUT_MS` now works above 60,000, as documented. Only the host read it: the worker
kept its own 60-second timer, so a build that yielded to the event loop after that failed with
`DEADLINE_EXCEEDED` at any limit, usually once the abandoned build had run to its end. The worker now
diff --git a/src/__tests__/atlas-table-memo.test.ts b/src/__tests__/atlas-table-memo.test.ts
new file mode 100644
index 00000000..966e72d8
--- /dev/null
+++ b/src/__tests__/atlas-table-memo.test.ts
@@ -0,0 +1,91 @@
+import { expect, test } from 'bun:test';
+import * as THREE from 'three';
+import { Document } from '@gltf-transform/core';
+import { textureAtlas, remapUVToAtlas } from '../texture-atlas';
+import {
+ atlasDocumentTable,
+ collectAtlasProvenance,
+ createAtlasTableMemo,
+ validateAtlasProvenanceTable,
+} from '../atlas-provenance';
+
+// Loading a GLB validated the same scene table twice (import validation, then the review scene),
+// and every export validated it again after the provenance refresh. The memo keeps one
+// validation per unchanged table without ever answering for a table it has not seen.
+
+test('the memo validates an unchanged table once and hands out independent copies', () => {
+ let calls = 0;
+ const memo = createAtlasTableMemo((raw) => {
+ calls++;
+ return structuredClone(raw) as never;
+ });
+ const raw = { version: 1, atlases: [{ id: 'a' }] };
+ const first = memo(raw);
+ const second = memo(raw);
+ expect(calls).toBe(1);
+ expect(second).toEqual(first);
+ expect(second).not.toBe(first);
+ (first as unknown as { atlases: unknown[] }).atlases.push('mutated by a caller');
+ expect(memo(raw)).toEqual(second);
+});
+
+test('the memo validates again after an in-place edit, for another object, and after a failure', () => {
+ let calls = 0;
+ const memo = createAtlasTableMemo((raw) => {
+ calls++;
+ if ((raw as { bad?: boolean }).bad) throw new Error('invalid table');
+ return structuredClone(raw) as never;
+ });
+ const raw: Record<string, unknown> = { version: 1, atlases: [] };
+ memo(raw);
+ raw['atlases'] = [{ id: 'b' }];
+ expect(memo(raw) as unknown).toEqual({ version: 1, atlases: [{ id: 'b' }] });
+ expect(calls).toBe(2);
+ memo({ version: 1, atlases: [{ id: 'b' }] });
+ expect(calls).toBe(3);
+ raw['bad'] = true;
+ expect(() => memo(raw)).toThrow('invalid table');
+ expect(() => memo(raw)).toThrow('invalid table');
+ expect(calls).toBe(5);
+});
+
+test('a document table edited in place after validation is validated again, never reused', async () => {
+ const texture = await textureAtlas({
+ schemaVersion: 1,
+ width: 128,
+ height: 128,
+ usage: 'albedo',
+ regions: [
+ {
+ name: 'face',
+ content: { x: 4, y: 4, width: 4, height: 4 },
+ source: {
+ kind: 'procedural',
+ spec: {
+ schemaVersion: 3,
+ width: 4,
+ height: 4,
+ background: [255, 12, 34, 255],
+ operations: [],
+ },
+ },
+ },
+ ],
+ });
+ const geometry = remapUVToAtlas(new THREE.PlaneGeometry(), texture, 'face', {
+ inputOrigin: 'bottom-left',
+ mode: 'texel-center',
+ });
+ const root = new THREE.Group().add(
+ new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({ map: texture })),
+ );
+ const table = collectAtlasProvenance(root).table!;
+ const doc = new Document();
+ doc.getRoot().setDefaultScene(doc.createScene().setExtras({ kilnAtlasProvenance: table }));
+ const first = atlasDocumentTable(doc)!;
+ expect(first).toEqual(validateAtlasProvenanceTable(table));
+ expect(atlasDocumentTable(doc)).toEqual(first);
+ // The same extras object, now carrying a key the closed table must reject.
+ (table as unknown as Record<string, unknown>)['extra'] = true;
+ expect(() => atlasDocumentTable(doc)).toThrow();
+});
diff --git a/src/__tests__/cli-capture-cache.test.ts b/src/__tests__/cli-capture-cache.test.ts
index 044eae5f..db01aa71 100644
--- a/src/__tests__/cli-capture-cache.test.ts
+++ b/src/__tests__/cli-capture-cache.test.ts
@@ -69,6 +69,85 @@ test('local service identity enables default host GPU reuse and invalidates on r
server.stop(true);
}
});
+test('a renderer the first capture has to start still caches that capture', async () => {
+ // A cold session used to have no capture identity until the first request had started the
+ // service, so that request bypassed the cache and its repeat rendered again.
+ let renders = 0,
+ starts = 0;
+ const server = Bun.serve({
+ port: 0,
+ fetch: async (request) => {
+ if (new URL(request.url).pathname === '/health')
+ return Response.json(
+ fakeRenderHealth({
+ ok: true,
+ rendererId: 'gpu:test',
+ captureIdentity: {
+ version: 'kiln.capture-producer.v1',
+ fingerprint: `sha256:${'b'.repeat(64)}`,
+ instanceId: 'cold-start',
+ },
+ }),
+ );
+ renders++;
+ const body = (await request.json()) as {
+ glb_base64: string;
+ cameras: unknown[];
+ width: number;
+ height: number;
+ };
+ return Response.json({
+ ok: true,
+ rendererId: 'gpu:test',
+ cameras: body.cameras,
+ width: body.width,
+ height: body.height,
+ views: [Buffer.from(encodePng(new Uint8Array(512 * 512 * 3), 512, 512)).toString('base64')],
+ fidelity: {
+ version: 'kiln.render-fidelity.v1',
+ producer: 'kiln-render-service',
+ delivered: 'full-material',
+ materialFaithful: true,
+ degraded: false,
+ inputGlbSha256:
+ 'sha256:' +
+ createHash('sha256').update(Buffer.from(body.glb_base64, 'base64')).digest('hex'),
+ rendererId: 'gpu:test',
+ },
+ });
+ },
+ });
+ const nobody = Bun.serve({ port: 0, fetch: () => new Response(null) });
+ const unusedPort = nobody.port;
+ nobody.stop(true);
+ const previousPort = process.env.KILN_RENDER_SERVICE_PORT;
+ const previousUrl = process.env.KILN_RENDER_PORT_URL;
+ try {
+ delete process.env.KILN_RENDER_PORT_URL;
+ process.env.KILN_RENDER_SERVICE_PORT = String(unusedPort);
+ const context = await buildRenderPort('auto', undefined, {
+ start: async () => {
+ starts++;
+ return server.url.toString();
+ },
+ });
+ expect(starts).toBe(0);
+ const inspect = createKilnProgramToolRegistry(context).find((d) => d.name === 'kiln_inspect')!;
+ const code =
+ "const meta={name:'box',category:'prop'};function build(){const r=createRoot('Root');createPart('Body',boxGeo(1,1,1),gameMaterial('#888888'),{parent:r});return r;}";
+ expect(await inspect.run({ code })).toMatchObject({ ok: true });
+ expect(await inspect.run({ code })).toMatchObject({ ok: true });
+ expect(renders).toBe(1);
+ expect(starts).toBe(1);
+ } finally {
+ if (previousPort === undefined) delete process.env.KILN_RENDER_SERVICE_PORT;
+ else process.env.KILN_RENDER_SERVICE_PORT = previousPort;
+ if (previousUrl === undefined) delete process.env.KILN_RENDER_PORT_URL;
+ else process.env.KILN_RENDER_PORT_URL = previousUrl;
+ server.stop(true);
+ }
+});
+
test('CPU mode does not probe a renderer; unknown or unreachable identity disables reuse', async () => {
const { probeCaptureIdentity } = await import('../cli-render-mode');
let requests = 0;
diff --git a/src/atlas-provenance.ts b/src/atlas-provenance.ts
index d1e30d6c..0df79e4c 100644
--- a/src/atlas-provenance.ts
+++ b/src/atlas-provenance.ts
@@ -324,9 +324,35 @@ function rawDocumentTable(doc: Document): unknown {
const scene = doc.getRoot().getDefaultScene() ?? doc.getRoot().listScenes()[0];
return scene ? field(scene.getExtras(), 'kilnAtlasProvenance') : undefined;
}
+/**
+ * One validation per unchanged table. An entry is keyed by the extras object and answers only
+ * while that object's canonical JSON is the one validated; the fingerprint runs the validator's
+ * own preflight first, so a table it would reject (accessors included) always reaches `validate`.
+ * Failures are never kept, and every caller receives its own copy.
+ */
+export function createAtlasTableMemo(
+ validate: (raw: unknown) => AtlasProvenanceTableV1,
+): (raw: unknown) => AtlasProvenanceTableV1 {
+ const validated = new WeakMap<object, { json: string; table: AtlasProvenanceTableV1 }>();
+ return (raw) => {
+ if (raw === null || typeof raw !== 'object') return validate(raw);
+ let json: string;
+ try {
+ json = canonicalAtlasMetadataJsonV1(raw);
+ } catch {
+ return validate(raw);
+ }
+ const hit = validated.get(raw);
+ if (hit?.json === json) return structuredClone(hit.table);
+ const table = validate(raw);
+ validated.set(raw, { json, table: structuredClone(table) });
+ return table;
+ };
+}
+const documentTable = createAtlasTableMemo(validateAtlasProvenanceTable);
export function atlasDocumentTable(doc: Document): AtlasProvenanceTableV1 | undefined {
const raw = rawDocumentTable(doc);
- return raw === undefined ? undefined : validateAtlasProvenanceTable(raw);
+ return raw === undefined ? undefined : documentTable(raw);
}
export function atlasMaterialUses(doc: Document): { texture: GltfTexture; info: TextureInfo }[] {
const uses: { texture: GltfTexture; info: TextureInfo }[] = [];
diff --git a/src/cli-render-mode.ts b/src/cli-render-mode.ts
index 5d079d58..d29658df 100644
--- a/src/cli-render-mode.ts
+++ b/src/cli-render-mode.ts
@@ -37,13 +37,19 @@ export function resolveRenderMode(value?: string): RenderMode {
export const GPU_REQUIRED_NEXT_STEP =
'A GPU renderer is required by KILN_RENDER=gpu (CLI --render gpu). Set KILN_RENDER=auto (--render auto) to continue with CPU geometry views, or KILN_RENDER_PORT_URL (--render-port) for a renderer on another device; after repairing the local service call kiln_renderer { action: "reprobe" } (CLI: kiln service reprobe)';
+/** A lazily started port that can also say where its next request goes. */
+export interface LazyRenderPort extends PbrRenderPort {
+ /** The URL the next request uses, starting the service exactly as that request would. */
+ resolveUrl(): Promise<string>;
+}
+
/** Failed starts are cached. Only an explicitly refused socket permits a new local start. */
export function makeLazyRenderPort(
start: () => Promise<string>,
token?: string,
sourceFingerprint?: string,
initialUrl?: string,
-): PbrRenderPort {
+): LazyRenderPort {
let resolving: Promise<{ url: string; port: PbrRenderPort }> | undefined = initialUrl
? Promise.resolve({
url: initialUrl,
@@ -62,7 +68,7 @@ export function makeLazyRenderPort(
);
},
));
- return async (req, execution) => {
+ const render: PbrRenderPort = async (req, execution) => {
execution?.signal?.throwIfAborted();
const pending = resolve();
const { url, port } = await pending;
@@ -87,6 +93,7 @@ export function makeLazyRenderPort(
return (await resolve()).port(req, execution);
}
};
+ return Object.assign(render, { resolveUrl: async () => (await resolve()).url });
}
/** What actually got selected, for honest CLI reporting. */
@@ -204,20 +211,15 @@ export async function buildRenderPort(
if (explicitUrl)
return attach(explicitUrl, `GPU service (explicit remote ${explicitUrl})`, remoteToken);
const attachLocal = (initialUrl?: string, label = 'GPU service (local, started on demand)') => {
- let resolvedUrl = initialUrl;
const start = options?.start ?? (() => startLocalRenderService(dir, startupEnvironment));
- context.viewRenderPort = makeLazyRenderPort(
- async () => {
- resolvedUrl = await start();
- return resolvedUrl;
- },
- localToken,
- source,
- initialUrl,
- );
+ const port = makeLazyRenderPort(start, localToken, source, initialUrl);
+ context.viewRenderPort = port;
context.viewRenderTimeoutMs = CLI_VIEW_RENDER_TIMEOUT_MS;
- context.captureCacheIdentity = () =>
- resolvedUrl ? probeCaptureIdentity(resolvedUrl, localToken, source) : undefined;
+ // The identity follows the port's own connection. On a cold session that means the start
+ // the first request would make next, so even that request is cached. A failed start stays
+ // the port's cached failure, and an unknown identity still bypasses the cache.
+ context.captureCacheIdentity = async () =>
+ probeCaptureIdentity(await port.resolveUrl(), localToken, source);
selected.set(context, label);
return context;
};
diff --git a/src/qa/open-surface-penetration.test.ts b/src/qa/open-surface-penetration.test.ts
index 221a9175..74176c67 100644
--- a/src/qa/open-surface-penetration.test.ts
+++ b/src/qa/open-surface-penetration.test.ts
@@ -8,8 +8,9 @@
* geometry. Every one has a fixture here beside the true positives.
*/
-import { describe, expect, test } from 'bun:test';
+import { describe, expect, spyOn, test } from 'bun:test';
import * as THREE from 'three';
+import * as geometryModule from '../geometry';
import {
analyzeOpenSurfacePenetration,
inspectOpenSurfacePenetration,
@@ -245,6 +246,36 @@ describe('determinism and wiring', () => {
expect(first.penetrations.map((pair) => pair.solid)).toEqual(['Mesh_CurvedWall']);
});
+ test('a geometry shared by many meshes is measured once, with the same evidence', () => {
+ // The 2.6M-triangle cathedral places 1,707 meshes over 184 geometries; topology belongs to
+ // the geometry, so each placement measuring it again was pure repetition.
+ const wall = new THREE.BoxGeometry(2, 1.4, 0.12);
+ const sheet = new THREE.PlaneGeometry(1.4, 1.4, 8, 8);
+ const place = (geometry: THREE.BufferGeometry, name: string, x: number) => {
+ const mesh = new THREE.Mesh(geometry);
+ mesh.name = name;
+ mesh.position.set(x, 0.7, 0.4);
+ return mesh;
+ };
+ const build = (shared: boolean) =>
+ sceneOf(
+ ...[0, 3, 6].flatMap((x, i) => [
+ place(shared ? wall : wall.clone(), `Mesh_Wall_${i}`, x),
+ place(shared ? sheet : sheet.clone(), `Mesh_Throw_${i}`, x),
+ ]),
+ );
+ const separate = analyzeOpenSurfacePenetration(build(false));
+ const measured = spyOn(geometryModule, 'geometryDiagnostics');
+ try {
+ const sharedEvidence = analyzeOpenSurfacePenetration(build(true));
+ expect(measured).toHaveBeenCalledTimes(2);
+ expect(JSON.stringify(sharedEvidence)).toBe(JSON.stringify(separate));
+ expect(sharedEvidence.penetrations).toHaveLength(3);
+ } finally {
+ measured.mockRestore();
+ }
+ });
+
test('the rule takes its own measurement from the scene', () => {
const findings = OPEN_SURFACE_PENETRATION_QA_RULE.evaluate({
intent: createAssetIntentV1({ category: 'prop' }),
diff --git a/src/qa/open-surface-penetration.ts b/src/qa/open-surface-penetration.ts
index 995c5ca7..8e6912b8 100644
--- a/src/qa/open-surface-penetration.ts
+++ b/src/qa/open-surface-penetration.ts
@@ -241,6 +241,12 @@ function collectParts(
skipped: OpenSurfacePenetrationEvidenceV1['skipped'],
): AnalyzedPart[] {
const parts: AnalyzedPart[] = [];
+ // Topology belongs to the geometry, not the placement: a geometry shared by many meshes is
+ // measured once per pass, and a failure is reported for every mesh that uses it.
+ const topology = new Map<
+ THREE.BufferGeometry,
+ { diagnostics: ReturnType<typeof geometryDiagnostics> } | { error: unknown }
+ >();
root.updateWorldMatrix(true, true);
root.traverseVisible((node) => {
const mesh = node as THREE.Mesh;
@@ -284,16 +290,24 @@ function collectParts(
skipped.push({ part: name, reason: 'non-finite transformed bounds cannot be measured' });
return;
}
- let diagnostics: ReturnType<typeof geometryDiagnostics>;
- try {
- diagnostics = geometryDiagnostics(mesh.geometry);
- } catch (error) {
+ let measured = topology.get(mesh.geometry);
+ if (!measured) {
+ try {
+ measured = { diagnostics: geometryDiagnostics(mesh.geometry) };
+ } catch (error) {
+ measured = { error };
+ }
+ topology.set(mesh.geometry, measured);
+ }
+ if ('error' in measured) {
+ const { error } = measured;
skipped.push({
part: name,
reason: `topology could not be analyzed (${error instanceof Error ? error.message : String(error)})`,
});
return;
}
+ const { diagnostics } = measured;
// A watertight, orientable shell is a solid a ray can be counted against.
// Anything else — a sheet, a card, a shell with a hole — is an open surface.
const closed =