From 9c50b64226101498e3f1a2e5a0d6c44fb0634b91 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 24 Oct 2026 20:26:54 +0200 Subject: [PATCH 01/36] Tests first: the FBX export's behavioural tests and the stub Blender they run against Red on the daemon at c5cf445: fbx jobs, the refusal ladder, export containment, kill on lease loss and SIGTERM, the minted seed, motion_job.v1, the artifact read route and rest-fbx. test_bvh_to_fbx.py runs the converter in real Blender (VILI_BLENDER). This commit does not pass its own tests. Co-Authored-By: Claude Opus 5.5 --- scripts/fixtures/stub-blender.mjs | 38 ++++ scripts/fixtures/stub-worker.mjs | 29 ++- scripts/test-vili-daemon.mjs | 367 +++++++++++++++++++++++++++++- scripts/test_bvh_to_fbx.py | 141 ++++++++++++ 4 files changed, 571 insertions(+), 4 deletions(-) create mode 100755 scripts/fixtures/stub-blender.mjs create mode 100644 scripts/test_bvh_to_fbx.py diff --git a/scripts/fixtures/stub-blender.mjs b/scripts/fixtures/stub-blender.mjs new file mode 100755 index 0000000..2062ce9 --- /dev/null +++ b/scripts/fixtures/stub-blender.mjs @@ -0,0 +1,38 @@ +#!/usr/bin/env node +// Stands in for Blender in the daemon's tests. Every start appends a JSON line {pid, pgid, priority, argv, env} to starts.log beside +// this file (the test gives each daemon its own copy, so the log is per test). `--version` answers like Blender, +// unless the copy is named blender-broken. An export (`... -- `) acts on the clip name: +// fail* prints a line to stderr, exits 1 silent* exits 0 with no result line +// hang* a grandchild, then never exits slow* runs 6 s, then behaves +// other writes "FBX-STUB:" + the BVH's bytes to and prints the VILI-FBX result line +import { appendFileSync, readFileSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { spawn } from "node:child_process"; + +const here = path.dirname(process.argv[1]); +const log = path.join(here, "starts.log"); +const argv = process.argv.slice(2); +const pgid = Number(readFileSync("/proc/self/stat", "utf8").split(") ")[1].split(" ")[2]); +appendFileSync(log, `${JSON.stringify({ pid: process.pid, pgid, priority: os.getPriority(), argv, env: process.env })}\n`); + +if (argv.includes("--version")) { + if (path.basename(process.argv[1]).includes("broken")) process.exit(1); + console.log("Blender 0.0.0 (stub)"); + console.log("\tbuild date: never"); + process.exit(0); +} + +const [bvh, fbx, clip] = argv.slice(argv.indexOf("--") + 1); +console.error(`stub-blender-stderr ${clip}`); +if (clip.startsWith("fail")) process.exit(1); +if (clip.startsWith("silent")) process.exit(0); +if (clip.startsWith("hang")) { + spawn(process.execPath, ["-e", `require('fs').appendFileSync(${JSON.stringify(log)}, 'grandchild ' + process.pid + '\n'); setInterval(() => {}, 1000)`], { stdio: "ignore" }); + process.on("SIGTERM", () => {}); + setInterval(() => {}, 1000); +} else { + if (clip.startsWith("slow")) await new Promise((resolve) => setTimeout(resolve, 6000)); + writeFileSync(fbx, Buffer.concat([Buffer.from("FBX-STUB:"), readFileSync(bvh)])); + console.log(`VILI-FBX ${JSON.stringify({ bones: 78, frames: [1, 60], fps: 30 })}`); +} diff --git a/scripts/fixtures/stub-worker.mjs b/scripts/fixtures/stub-worker.mjs index 3cf1831..265662d 100644 --- a/scripts/fixtures/stub-worker.mjs +++ b/scripts/fixtures/stub-worker.mjs @@ -1,12 +1,12 @@ // Stands in for kimodo-resident-worker.py in the daemon's tests. It binds port 0, prints the ready line the // daemon waits for, and answers /health and /generate with what the daemon gave it. The --model value picks a // misbehaviour: crash-before-ready, hang-before-ready, sick, slow-health, stubborn, fail-generate, -// refuse-generate, drop-generate, slow-generate, writer (appends to .writes every 50 ms, never answers, ignores SIGTERM), slow-to-stop (no answer; prints a line and exits 1.5 s after SIGTERM), chatty (prints a line the moment it is healthy), encoder (a grandchild, then no answer), graceful (exits 0.5 s after SIGTERM), die-after-ready. Any other value is just the model the worker serves. +// refuse-generate, drop-generate, slow-generate, writer (appends to .writes every 50 ms, never answers, ignores SIGTERM), slow-to-stop (no answer; prints a line and exits 1.5 s after SIGTERM), chatty (prints a line the moment it is healthy), encoder (a grandchild, then no answer), graceful (exits 0.5 s after SIGTERM), die-after-ready, bvh-outside (lists a BVH outside the job's directory), bvh-link (lists a symlink as its BVH). A request with bvh writes .bvh (motion/motion_NN.bvh for several samples) and lists it. Any other value is just the model the worker serves. import http from "node:http"; import os from "node:os"; import path from "node:path"; import { spawn } from "node:child_process"; -import { appendFileSync, writeFileSync } from "node:fs"; +import { appendFileSync, mkdirSync, symlinkSync, writeFileSync } from "node:fs"; const argv = process.argv.slice(2); const flag = (name) => { @@ -81,8 +81,33 @@ if (model === "hang-before-ready") { spawn(process.execPath, ["-e", `process.on('SIGTERM', () => {}); require('fs').appendFileSync(${JSON.stringify(spawnLog)}, 'grandchild ' + process.pid + '\\n'); setInterval(() => {}, 1000)`], { stdio: "ignore" }); return; } + let files; + if (payload.bvh) { + const outside = path.join(path.dirname(payload.output), "..", "outside.bvh"); + if (model === "bvh-outside") { + writeFileSync(outside, "BVH-OUTSIDE\n"); + files = [outside]; + } else if (model === "bvh-link") { + writeFileSync(outside, "BVH-OUTSIDE\n"); + symlinkSync(outside, `${payload.output}.bvh`); + files = [`${payload.output}.bvh`]; + } else if (payload.numSamples > 1) { + mkdirSync(payload.output, { recursive: true }); + files = Array.from({ length: payload.numSamples }, (_, index) => path.join(payload.output, `motion_${String(index).padStart(2, "0")}.bvh`)); + for (const [index, file] of files.entries()) writeFileSync(file, `BVH-STUB sample ${index}\n`); + } else { + writeFileSync(`${payload.output}.npz`, "NPZ-STUB\n"); + writeFileSync(`${payload.output}.bvh`, "BVH-STUB\n"); + files = [`${payload.output}.npz`, `${payload.output}.bvh`]; + } + } send(200, { ok: true, + files, + seed: payload.seed, + metaSeed: payload.meta?.seed, + bvh: payload.bvh, + bvhStandardTpose: payload.bvhStandardTpose, model: model || "stub-model", pid: process.pid, requests, diff --git a/scripts/test-vili-daemon.mjs b/scripts/test-vili-daemon.mjs index 8b1d9c3..23e7a34 100644 --- a/scripts/test-vili-daemon.mjs +++ b/scripts/test-vili-daemon.mjs @@ -2,7 +2,8 @@ // Runs the real daemon against scripts/fixtures/stub-worker.mjs as its --python/--worker-entry. import assert from "node:assert/strict"; import { spawn } from "node:child_process"; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs"; +import { createHash } from "node:crypto"; +import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs"; import http from "node:http"; import net from "node:net"; import os from "node:os"; @@ -14,6 +15,8 @@ import { decode, encode } from "@msgpack/msgpack"; const here = path.dirname(fileURLToPath(import.meta.url)); const daemonPath = path.join(here, "vili-daemon.mjs"); const stubPath = path.join(here, "fixtures", "stub-worker.mjs"); +const stubBlenderPath = path.join(here, "fixtures", "stub-blender.mjs"); +const exportScriptPath = path.join(here, "bvh-to-fbx.py"); const fakeIdunnEntry = path.join(here, "fixtures", "fake-idunn-entry.mjs"); const THREADS = 5; @@ -44,6 +47,7 @@ function isAlive(pid) { async function startDaemon({ omit = [], viaEnv = false, threads = String(THREADS), python = process.execPath, nested = false, host = "127.0.0.1", relativeModels = false, extraArgs = [], root: givenRoot = null, entry = daemonPath, extraEnv = {}, hold = entry === daemonPath, + blender = "stub", } = {}) { const root = givenRoot ?? mkdtempSync(path.join(os.tmpdir(), "vili-test-")); const stateRoot = nested ? path.join(root, "a", "b", "state") : root; @@ -59,6 +63,15 @@ async function startDaemon({ "python-env": "test-env", }; if (threads !== null) settings.threads = threads; + // Blender is a copy of the stub in a directory of its own (the stub logs its starts beside itself): "stub" is + // ready, "broken" fails its version probe, "missing" is a path with nothing there, null is unconfigured. + const blenderDir = mkdtempSync(path.join(os.tmpdir(), "vili-blender-")); + const blenderPath = blender === null ? null : path.join(blenderDir, { stub: "blender", broken: "blender-broken", missing: "absent" }[blender]); + if (blender === "stub" || blender === "broken") { + copyFileSync(stubBlenderPath, blenderPath); + chmodSync(blenderPath, 0o755); + } + if (blenderPath) settings.blender = blenderPath; for (const name of omit) delete settings[name]; const env = { ...process.env, LEAK_CHECK: "leaked", LANG: "xx_TEST.UTF-8", ...extraEnv }; for (const name of Object.keys(env)) if (name.startsWith("VILI_")) delete env[name]; @@ -80,10 +93,17 @@ async function startDaemon({ const log = path.join(stateRoot, "embeddings", "stub-spawns.log"); return existsSync(log) ? readFileSync(log, "utf8").split("\n").filter(Boolean) : []; }; + const startsLog = path.join(blenderDir, "starts.log"); + const startLines = () => (existsSync(startsLog) ? readFileSync(startsLog, "utf8").split("\n").filter(Boolean) : []); return { root, stateRoot, modelsRoot, + blenderDir, + blenderPath, + // every start of the stub Blender, the version probe included + starts: () => startLines().filter((line) => line.startsWith("{")).map((line) => JSON.parse(line)), + blenderGrandchildren: () => startLines().filter((line) => line.startsWith("grandchild ")).map((line) => Number(line.split(" ")[1])), proc, boundHost: listening[1], port: Number(port), @@ -101,6 +121,7 @@ async function startDaemon({ // a daemon that did not stop on SIGTERM must not outlive the test and hold the run open if (proc.exitCode === null && proc.signalCode === null) proc.kill("SIGKILL"); rmSync(root, { recursive: true, force: true }); + rmSync(blenderDir, { recursive: true, force: true }); } }, }; @@ -251,7 +272,7 @@ test("a job is a record on disk", async () => { const answer = await generate(daemon, { prompt: "a person waves", duration: 2, constraints: [{ type: "root2d" }] }); assert.equal(answer.status, 200); const job = answer.body; - assert.equal(job.schema, "gamecult.vili.motion_job.v0"); + assert.equal(job.schema, "gamecult.vili.motion_job.v1"); assert.equal(job.request.schema, "gamecult.vili.motion_request.v0"); assert.equal(job.prompt, "a person waves"); assert.equal(job.model, "stub-model"); @@ -264,6 +285,14 @@ test("a job is a record on disk", async () => { assert.equal(job.worker.constraints, path.join(job.artifactDir, "constraints.json")); assert.deepEqual(JSON.parse(readFileSync(job.worker.constraints, "utf8")), [{ type: "root2d" }]); assert.deepEqual(JSON.parse(readFileSync(path.join(daemon.stateRoot, "jobs", `${job.jobId}.json`), "utf8")), job); + assert.ok(Number.isInteger(job.seed) && job.seed >= 0 && job.seed < 2 ** 31, "no seed was sent, so one was minted"); + assert.deepEqual(job.files.map((file) => file.name), ["constraints.json", "meta.json", "request.json"]); + for (const file of job.files) { + const bytes = readFileSync(path.join(job.artifactDir, file.name)); + assert.equal(file.bytes, bytes.length); + assert.equal(file.sha256, createHash("sha256").update(bytes).digest("hex")); + } + assert.equal(job.export, undefined, "a job that asked for no FBX has no export block"); const batch = await generate(daemon, { texts: ["a", "b"], durations: [1, 1] }); assert.equal(batch.status, 200); assert.equal(batch.body.prompt, null); @@ -810,6 +839,7 @@ test("before the lease nothing is written, spawned or accepted", async () => { assert.equal(answer.status, 503); assert.equal(answer.body.code, "write-lease-pending"); assert.deepEqual(daemon.spawns(), []); + assert.deepEqual(daemon.starts(), [], "no Blender before the lease, the version probe included"); assert.equal(existsSync(daemon.stateRoot), false, "the state root must not exist before the lease"); assert.deepEqual(daemon.health(), []); } finally { @@ -1143,6 +1173,7 @@ test("the entry derives the daemon's host, port, interpreter and environment ide assert.equal(derived.VILI_DAEMON_PORT, "18861"); assert.equal(derived.GAMECULT_IDUNN_CANDIDATE_BIND, "http://127.0.0.1:18861", "cultnet-ts compares the bind to the Expected route's endpoint, which carries the scheme Idunn's bare host:port lacks"); assert.equal(derived.VILI_PYTHON, path.join(release, "python", "bin", "python3.12")); + assert.equal(derived.VILI_BLENDER, path.join(release, "blender", "blender")); assert.equal(derived.VILI_PYTHON_ENV, `locks-sha256:${createHash("sha256").update("build lock bytes\nruntime lock bytes\n").digest("hex")}`); } } finally { @@ -1289,3 +1320,335 @@ test("a worker's output line after the first is not logged once the lease is gon await daemon.stop(); } }); + +// ---- FBX export: the daemon converts each BVH the worker lists, through the sealed Blender, under the write gate. + +const sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex"); +const exportRequest = (extra = {}) => ({ prompt: "a person waves", duration: 2, fbx: true, ...extra }); +const exportStarts = (daemon) => daemon.starts().filter((start) => start.argv.includes("--")); +const jobFiles = (daemon) => readdirSync(path.join(daemon.stateRoot, "jobs")); +const getArtifact = (daemon, urlPath) => request(daemon.port, "GET", urlPath); + +test("an fbx job exports every listed BVH", async () => { + const daemon = await startDaemon(); + try { + assert.equal((await backendOf(daemon)).blender, "Blender 0.0.0 (stub)"); + const answer = await generate(daemon, exportRequest({ clipName: "wave_01", seed: 7 })); + assert.equal(answer.status, 200); + const job = answer.body; + assert.equal(job.schema, "gamecult.vili.motion_job.v1"); + assert.equal(job.ok, true); + assert.equal(job.worker.bvh, true, "fbx implies the BVH"); + assert.equal(job.worker.bvhStandardTpose, true, "fbx implies the standard T-pose"); + assert.equal(job.request.bvh, true); + assert.equal(job.request.bvhStandardTpose, true); + assert.deepEqual(job.export.clips, [{ file: "motion.fbx", clipName: "wave_01", bones: 78, frames: [1, 60], fps: 30 }]); + assert.equal(job.export.blender, "Blender 0.0.0 (stub)"); + assert.equal(job.export.script, `sha256:${sha256(readFileSync(exportScriptPath))}`); + assert.equal(job.export.settings, "standard-tpose soma77 metres hashseed0 time1970"); + const fbx = readFileSync(path.join(job.artifactDir, "motion.fbx")); + assert.equal(fbx.toString(), "FBX-STUB:BVH-STUB\n"); + assert.deepEqual(job.files.map((file) => file.name), ["meta.json", "motion.bvh", "motion.fbx", "motion.npz", "request.json"]); + assert.equal(job.files.find((file) => file.name === "motion.fbx").sha256, sha256(fbx)); + assert.equal(job.files.find((file) => file.name === "motion.fbx").bytes, fbx.length); + assert.deepEqual(JSON.parse(readFileSync(path.join(daemon.stateRoot, "jobs", `${job.jobId}.json`), "utf8")), job); + const request_ = JSON.parse(readFileSync(path.join(job.artifactDir, "request.json"), "utf8")); + assert.equal(request_.fbx, undefined, "the worker is told nothing of FBX"); + assert.equal(request_.clipName, undefined); + + const [probe, run] = daemon.starts(); + assert.deepEqual(probe.argv, ["-b", "--factory-startup", "--version"]); + assert.deepEqual(run.argv, [ + "-b", "--factory-startup", "--python-use-system-env", "--python-exit-code", "1", "--python", exportScriptPath, + "--", path.join(job.artifactDir, "motion.bvh"), path.join(job.artifactDir, "motion.fbx"), "wave_01", + ]); + assert.deepEqual(run.env, { + PATH: process.env.PATH, + LANG: "xx_TEST.UTF-8", + HOME: "/nonexistent", + PYTHONHASHSEED: "0", + PYTHONNOUSERSITE: "1", + LD_LIBRARY_PATH: path.join(daemon.blenderDir, "lib"), + }, "the export environment is these six and nothing else (no VILI_*, no LEAK_CHECK)"); + assert.equal(run.priority, 10); + assert.equal(run.pgid, run.pid, "Blender leads its own process group"); + const log = readFileSync(path.join(daemon.stateRoot, "logs", "export.log"), "utf8"); + assert.match(log, /stub-blender-stderr wave_01/); + + const named = await generate(daemon, exportRequest()); + assert.equal(named.body.export.clips[0].clipName, named.body.jobId, "the clip is named after the job by default"); + const several = await generate(daemon, exportRequest({ clipName: "pair", numSamples: 2 })); + assert.equal(several.status, 200); + assert.deepEqual(several.body.export.clips.map((clip) => [clip.file, clip.clipName]), [ + ["motion/motion_00.fbx", "pair_00"], + ["motion/motion_01.fbx", "pair_01"], + ]); + } finally { + await daemon.stop(); + } +}); + +test("fbx refusals happen before anything is written or spawned", async () => { + const daemon = await startDaemon(); + try { + for (const bad of [ + { bvhStandardTpose: false }, + { bvh_standard_tpose: "false" }, + { clipName: "a b canary" }, + { clipName: "x".repeat(65) }, + { clipName: "" }, + { clipName: 5 }, + ]) { + const answer = await generate(daemon, exportRequest(bad)); + assert.equal(answer.status, 400, JSON.stringify(bad)); + assert.ok(!answer.raw.includes("canary"), "the refusal repeated the input"); + } + assert.equal(existsSync(path.join(daemon.stateRoot, "artifacts")), false, "no artifact directory was made"); + assert.deepEqual(jobFiles(daemon), []); + assert.deepEqual(daemon.spawns(), [], "no worker was started"); + assert.equal(exportStarts(daemon).length, 0); + assert.equal((await generate(daemon, exportRequest({ clipName: "x".repeat(64) }))).status, 200, "64 characters is the limit"); + } finally { + await daemon.stop(); + } + for (const blender of [null, "broken", "missing"]) { + const unready = await startDaemon({ blender }); + try { + assert.equal((await backendOf(unready)).blender, blender === null ? "unconfigured" : "unavailable"); + const answer = await generate(unready, exportRequest()); + assert.equal(answer.status, 503); + assert.equal(answer.body.code, "blender-unavailable"); + assert.deepEqual(unready.spawns(), [], "no worker was started"); + assert.equal(existsSync(path.join(unready.stateRoot, "artifacts")), false, "no artifact directory was made"); + assert.deepEqual(jobFiles(unready), []); + assert.equal(exportStarts(unready).length, 0); + assert.equal((await generate(unready)).status, 200, "a job that asks for no FBX needs no Blender"); + } finally { + await unready.stop(); + } + } +}); + +test("the BVH is never given to Blender unless it is a regular file inside the job's directory", async () => { + const daemon = await startDaemon(); + try { + for (const model of ["bvh-outside", "bvh-link"]) { + const answer = await generate(daemon, exportRequest({ model, clipName: "canary_clip" })); + assert.equal(answer.status, 502, model); + assert.equal(answer.body.ok, false); + assert.equal(answer.body.error, "fbx-export-refused"); + assert.equal(answer.body.export.clips.length, 0); + assert.ok(existsSync(path.join(daemon.stateRoot, "jobs", `${answer.body.jobId}.json`)), "the failed job is still a record"); + } + assert.equal(exportStarts(daemon).length, 0, "Blender was never started for either"); + assert.ok(!(daemon.stdout() + daemon.stderr()).includes("canary")); + } finally { + await daemon.stop(); + } +}); + +test("a failing or hung Blender fails the job, leaks nothing, and leaves nothing running", async () => { + const daemon = await startDaemon(); + try { + const failed = await generate(daemon, exportRequest({ clipName: "fail_canary" })); + assert.equal(failed.status, 502); + assert.equal(failed.body.ok, false); + assert.equal(failed.body.error, "fbx-export-failed (exit 1)"); + assert.ok(!failed.raw.includes("stub-blender-stderr"), "Blender's output is not in the answer"); + assert.ok(!failed.body.error.includes("canary") && !(daemon.stdout() + daemon.stderr()).includes("canary")); + assert.match(readFileSync(path.join(daemon.stateRoot, "logs", "export.log"), "utf8"), /stub-blender-stderr fail_canary/); + assert.ok(existsSync(path.join(daemon.stateRoot, "jobs", `${failed.body.jobId}.json`))); + + const silent = await generate(daemon, exportRequest({ clipName: "silent" })); + assert.equal(silent.body.error, "fbx-export-failed (no result)"); + + const before = daemon.starts().length; + const hung = await generate(daemon, exportRequest({ clipName: "hang", exportTimeoutMs: 700 })); + assert.equal(hung.status, 502); + assert.equal(hung.body.error, "fbx-export-failed (signal SIGKILL)"); + const [run] = daemon.starts().slice(before); + await until(() => daemon.blenderGrandchildren().length === 1, "the hung Blender's grandchild"); + await until(() => !isAlive(run.pid) && !isAlive(daemon.blenderGrandchildren()[0]), "the hung export's group to be dead"); + assert.equal(hung.body.files.some((file) => file.name.endsWith(".fbx")), false); + } finally { + await daemon.stop(); + } +}); + +test("SIGTERM during an export stops its group, writes nothing more, and exits 0", async () => { + const daemon = await startDaemon(); + try { + const pending = generate(daemon, exportRequest({ clipName: "slow" })); + pending.catch(() => {}); + const run = await until(() => exportStarts(daemon)[0], "the export to start"); + daemon.proc.kill("SIGTERM"); + await until(() => !isAlive(run.pid), "the export to be stopped", 5); + await until(() => daemon.proc.exitCode !== null, "the daemon to exit"); + assert.equal(daemon.proc.exitCode, 0); + assert.deepEqual(jobFiles(daemon), [], "no record after the signal"); + const [artifacts] = [path.join(daemon.stateRoot, "artifacts")]; + for (const job of readdirSync(artifacts)) assert.equal(existsSync(path.join(artifacts, job, "motion.fbx")), false); + } finally { + await daemon.stop(); + } +}); + +test("losing the lease kills a running export within a second and records nothing", async () => { + const daemon = await idunnDaemon({ leased: true }); + try { + await until(() => existsSync(path.join(daemon.stateRoot, "vili.service.cc")), "the service store", 10); + assert.equal(daemon.starts().length, 1, "the version probe ran once the lease was held"); + const pending = generate(daemon, exportRequest({ clipName: "slow" })); + const run = await until(() => exportStarts(daemon)[0], "the export to start"); + rmSync(daemon.lease); + const lost = Date.now(); + await until(() => !isAlive(run.pid), "the export to be dead", 2); + assert.ok(Date.now() - lost < 1500, "the export outlived the lease by more than a second"); + assert.equal((await pending).status, 503); + assert.deepEqual(jobFiles(daemon), []); + assert.equal(existsSync(path.join(daemon.stateRoot, "artifacts", readdirSync(path.join(daemon.stateRoot, "artifacts"))[0], "motion.fbx")), false); + } finally { + await daemon.stop(); + } +}); + +test("the seed is minted when absent and recorded for every job", async () => { + const daemon = await startDaemon(); + try { + for (const extra of [{}, { fbx: false }]) { + const job = (await generate(daemon, exportRequest(extra))).body; + assert.ok(Number.isInteger(job.seed) && job.seed >= 0 && job.seed < 2 ** 31); + assert.equal(job.request.seed, job.seed); + assert.equal(job.worker.seed, job.seed, "the worker was given the minted seed"); + assert.equal(job.worker.metaSeed, job.seed); + assert.equal(JSON.parse(readFileSync(path.join(job.artifactDir, "meta.json"), "utf8")).seed, job.seed); + } + const given = (await generate(daemon, exportRequest({ seed: 7 }))).body; + assert.equal(given.seed, 7); + assert.equal(given.worker.seed, 7); + assert.equal(given.worker.metaSeed, 7); + assert.equal(JSON.parse(readFileSync(path.join(given.artifactDir, "meta.json"), "utf8")).seed, 7); + const zero = (await generate(daemon, exportRequest({ seed: 0 }))).body; + assert.equal(zero.seed, 0, "0 is a seed"); + } finally { + await daemon.stop(); + } +}); + +test("the artifact read route serves only a job's own FBX and BVH files", async () => { + const daemon = await startDaemon(); + try { + const job = (await generate(daemon, exportRequest({ clipName: "walk", numSamples: 1 }))).body; + const base = `/motion/artifacts/${job.jobId}`; + const served = await getArtifact(daemon, `${base}/motion.fbx`); + assert.equal(served.status, 200); + assert.equal(served.headers["content-type"], "application/octet-stream"); + assert.equal(served.raw, "FBX-STUB:BVH-STUB\n"); + assert.equal((await getArtifact(daemon, `${base}/motion.bvh`)).raw, "BVH-STUB\n"); + + const refused = [ + `${base}/meta.json`, + `${base}/request.json`, + `${base}/motion.npz`, + `${base}/..%2fmeta.json`, + `${base}/%2e%2e/${job.jobId}/meta.json`, + `${base}/../../jobs/${job.jobId}.json`, + `${base}/motion/motion_00.fbx`, + `/motion/artifacts/vili-123/motion.fbx`, + `/motion/artifacts/vili-canary-canary/motion.fbx`, + `/motion/artifacts/vili-9999999999999/motion.fbx`, + `/motion/artifacts/${job.jobId}`, + `/motion/artifacts/${job.jobId}/`, + ]; + for (const url of refused) { + const answer = await getArtifact(daemon, url); + assert.equal(answer.status, 404, url); + assert.equal(answer.raw, "not found\n", "a refusal echoes nothing"); + } + assert.equal((await request(daemon.port, "POST", `${base}/motion.fbx`, { body: "{}", headers: { "content-type": "application/json" } })).status, 404); + + // a symlink planted in the artifact directory, as the file or as a directory above it, is never followed + const outside = path.join(daemon.root, "outside.bin"); + writeFileSync(outside, "SECRET"); + rmSync(path.join(job.artifactDir, "motion.bvh")); + symlinkSync(outside, path.join(job.artifactDir, "motion.bvh")); + assert.equal((await getArtifact(daemon, `${base}/motion.bvh`)).status, 404); + mkdirSync(path.join(daemon.root, "elsewhere")); + writeFileSync(path.join(daemon.root, "elsewhere", "motion_00.fbx"), "SECRET"); + symlinkSync(path.join(daemon.root, "elsewhere"), path.join(job.artifactDir, "motion")); + const through = await getArtifact(daemon, `${base}/motion/motion_00.fbx`); + assert.equal(through.status, 404); + assert.ok(!through.raw.includes("SECRET")); + } finally { + await daemon.stop(); + } +}); + +test("rest-fbx is a job whose FBX is readable", async () => { + const pyRoot = mkdtempSync(path.join(os.tmpdir(), "vili-py-")); + const python = path.join(pyRoot, "bin", "python3.12"); + mkdirSync(path.dirname(python), { recursive: true }); + symlinkSync(process.execPath, python); + const skeletons = path.join(pyRoot, "lib", "python3.12", "site-packages", "kimodo", "assets", "skeletons", "somaskel77"); + mkdirSync(skeletons, { recursive: true }); + writeFileSync(path.join(skeletons, "somaskel77_standard_tpose.bvh"), "REST-BVH\n"); + const daemon = await startDaemon({ python }); + try { + const answer = await request(daemon.port, "POST", "/motion/rest-fbx", { body: "{}", headers: { "content-type": "application/json" } }); + assert.equal(answer.status, 200); + const job = answer.body; + assert.match(job.jobId, /^rest-[0-9]{13}$/); + assert.equal(job.schema, "gamecult.vili.motion_job.v1"); + assert.deepEqual(job.export.clips, [{ file: "SOMA77_Rest.fbx", clipName: "SOMA77_Rest", bones: 78, frames: [1, 60], fps: 30 }]); + assert.deepEqual(job.files.map((file) => file.name), ["SOMA77_Rest.bvh", "SOMA77_Rest.fbx"]); + assert.deepEqual(JSON.parse(readFileSync(path.join(daemon.stateRoot, "jobs", `${job.jobId}.json`), "utf8")), job); + const served = await getArtifact(daemon, `/motion/artifacts/${job.jobId}/SOMA77_Rest.fbx`); + assert.equal(served.status, 200); + assert.equal(served.raw, "FBX-STUB:REST-BVH\n"); + assert.deepEqual(daemon.spawns(), [], "no worker is needed for a rest pose"); + const cross = await request(daemon.port, "POST", "/motion/rest-fbx", { body: "{}", headers: { "content-type": "text/plain" } }); + assert.equal(cross.status, 403); + } finally { + await daemon.stop(); + rmSync(pyRoot, { recursive: true, force: true }); + } + + const bare = await startDaemon(); + try { + const missing = await request(bare.port, "POST", "/motion/rest-fbx", { body: "{}", headers: { "content-type": "application/json" } }); + assert.equal(missing.status, 503); + assert.equal(missing.body.code, "rest-skeleton-missing"); + } finally { + await bare.stop(); + } + const unready = await startDaemon({ blender: null }); + try { + const refused = await request(unready.port, "POST", "/motion/rest-fbx", { body: "{}", headers: { "content-type": "application/json" } }); + assert.equal(refused.status, 503); + assert.equal(refused.body.code, "blender-unavailable"); + assert.equal(existsSync(path.join(unready.stateRoot, "artifacts")), false); + } finally { + await unready.stop(); + } + const waiting = await idunnDaemon(); + try { + const early = await request(waiting.port, "POST", "/motion/rest-fbx", { body: "{}", headers: { "content-type": "application/json" } }); + assert.equal(early.status, 503); + assert.equal(early.body.code, "write-lease-pending"); + assert.deepEqual(waiting.starts(), []); + } finally { + await waiting.stop(); + } +}); + +test("operator state and the command boundary name the export", async () => { + const daemon = await startDaemon(); + try { + const state = await operatorState(daemon); + assert.equal(state.routes.artifacts, "/motion/artifacts/{jobId}/{name}"); + assert.equal(state.routes.restFbx, "/motion/rest-fbx"); + assert.ok(state.authority.owns.includes("clip export to FBX")); + } finally { + await daemon.stop(); + } +}); diff --git a/scripts/test_bvh_to_fbx.py b/scripts/test_bvh_to_fbx.py new file mode 100644 index 0000000..fb46aeb --- /dev/null +++ b/scripts/test_bvh_to_fbx.py @@ -0,0 +1,141 @@ +"""Runs scripts/bvh-to-fbx.py in the real Blender the daemon runs (VILI_BLENDER), with the environment the daemon +builds for it (scripts/vili-daemon.mjs exportEnv). The recipe's test-worker step runs this against the unpacked +blender tree; there is no skip: without VILI_BLENDER it errors. + + VILI_BLENDER= python3.12 -m unittest scripts/test_bvh_to_fbx.py +""" +import importlib.util +import json +import os +import pathlib +import re +import subprocess +import tempfile +import unittest + +BLENDER = os.environ["VILI_BLENDER"] +SCRIPT = pathlib.Path(__file__).resolve().with_name("bvh-to-fbx.py") + +# Reads an FBX back into a factory scene and reports what the avatar cut will see. +INSPECT = r''' +import bpy, json, sys +fbx = sys.argv[sys.argv.index("--") + 1] +bpy.ops.wm.read_factory_settings(use_empty=True) +bpy.ops.import_scene.fbx(filepath=fbx) +scene = bpy.context.scene +arm = next(o for o in scene.objects if o.type == "ARMATURE") +out = { + "bones": [b.name for b in arm.data.bones], + "scale": list(arm.scale), + "hips_rest": arm.data.bones["Hips"].head_local.z * arm.scale.z, +} +action = arm.animation_data.action if arm.animation_data else None +if action is not None: + first, last = (int(f) for f in action.frame_range) + def world(name, frame): + scene.frame_set(frame) + return (arm.matrix_world @ arm.pose.bones[name].matrix).translation.copy() + out["hips_travel"] = (world("Hips", last) - world("Hips", first)).length + out["root_wander"] = max((world("Root", f) - world("Root", first)).length for f in range(first, last + 1)) +print("INSPECT " + json.dumps(out)) +''' + + +def export_env(): + env = { + "HOME": "/nonexistent", + "PYTHONHASHSEED": "0", + "PYTHONNOUSERSITE": "1", + "LD_LIBRARY_PATH": os.path.join(os.path.dirname(BLENDER), "lib"), + } + for name in ("PATH", "LANG"): + if name in os.environ: + env[name] = os.environ[name] + return env + + +def blender(*argv, env=None): + return subprocess.run( + [BLENDER, "-b", "--factory-startup", "--python-use-system-env", "--python-exit-code", "1", *argv], + env=export_env() if env is None else env, capture_output=True, text=True, timeout=600, + ) + + +def convert(bvh, fbx, clip, env=None): + return blender("--python", str(SCRIPT), "--", str(bvh), str(fbx), clip, env=env) + + +def rest_bvh(): + spec = importlib.util.find_spec("kimodo") + return pathlib.Path(spec.submodule_search_locations[0]) / "assets" / "skeletons" / "somaskel77" / "somaskel77_standard_tpose.bvh" + + +class BvhToFbx(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.tmp = tempfile.TemporaryDirectory() + cls.dir = pathlib.Path(cls.tmp.name) + cls.rest = rest_bvh() + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def inspect(self, fbx): + script = self.dir / "inspect.py" + script.write_text(INSPECT) + run = blender("--python", str(script), "--", str(fbx)) + self.assertEqual(run.returncode, 0, run.stderr[-2000:]) + line = next(line for line in run.stdout.splitlines() if line.startswith("INSPECT ")) + return json.loads(line[len("INSPECT "):]) + + def test_rest_pose_keeps_the_bvh_joint_names_and_height(self): + fbx = self.dir / "rest.fbx" + run = convert(self.rest, fbx, "SOMA77_Rest") + self.assertEqual(run.returncode, 0, run.stderr[-2000:]) + result = json.loads(next(l for l in run.stdout.splitlines() if l.startswith("VILI-FBX "))[len("VILI-FBX "):]) + self.assertEqual(result["bones"], 78) + joints = re.findall(r"^\s*(?:ROOT|JOINT)\s+(\S+)", self.rest.read_text(), re.M) + seen = self.inspect(fbx) + self.assertEqual(len(joints), 78) + self.assertEqual(sorted(seen["bones"]), sorted(joints)) + self.assertFalse(any("mixamorig" in name for name in seen["bones"])) + for axis in seen["scale"]: + self.assertAlmostEqual(axis, 1.0, places=4) + self.assertAlmostEqual(seen["hips_rest"], 1.0, delta=0.01) + + def test_two_exports_of_one_bvh_are_byte_identical(self): + first, second = self.dir / "a.fbx", self.dir / "b.fbx" + for target in (first, second): + self.assertEqual(convert(self.rest, target, "twin").returncode, 0) + self.assertEqual(first.read_bytes(), second.read_bytes()) + + def test_without_a_fixed_hash_seed_the_script_exits_3(self): + env = export_env() + del env["PYTHONHASHSEED"] + target = self.dir / "unseeded.fbx" + self.assertEqual(convert(self.rest, target, "unseeded", env=env).returncode, 3) + self.assertFalse(target.exists()) + + def test_hips_travel_is_kept_and_root_stays_put(self): + text = self.rest.read_text() + header = text[:text.index("MOTION")] + channels = sum(int(n) for n in re.findall(r"CHANNELS\s+(\d+)", header)) + frames = 31 + rows = [] + for frame in range(frames): + row = ["0"] * channels + row[8] = repr(100.0 * frame / (frames - 1)) # Hips Zposition, centimetres: one metre over the clip + rows.append(" ".join(row)) + bvh = self.dir / "walk.bvh" + bvh.write_text(f"{header}MOTION\nFrames: {frames}\nFrame Time: 0.0333333\n" + "\n".join(rows) + "\n") + fbx = self.dir / "walk.fbx" + run = convert(bvh, fbx, "walk") + self.assertEqual(run.returncode, 0, run.stderr[-2000:]) + seen = self.inspect(fbx) + self.assertAlmostEqual(seen["hips_travel"], 1.0, delta=0.001) + self.assertLess(seen["root_wander"], 1e-4) + + +if __name__ == "__main__": + unittest.main() From 742de6314df261540fb0c6d718bf4265a899982f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 24 Oct 2026 20:29:41 +0200 Subject: [PATCH 02/36] Vili exports each clip as FBX through the sealed Blender, in the daemon, under the write gate fbx and clipName on /motion/generate; scripts/bvh-to-fbx.py converts one BVH (SOMA77 names, standard T-pose, metres, travel on Hips) with a fixed hash seed and time so one BVH on one host body gives one set of bytes. The daemon runs it per listed BVH (regular file inside the job's artifact directory only), in its own process group, killed with the worker on lease loss and stopped on SIGTERM. The seed is minted when absent and every job records motion_job.v1 (seed, file sha256, export). GET /motion/artifacts and POST /motion/rest-fbx. The duplicated bvh/bvhStandardTpose derivations are one plan. The entry points the daemon at the release's blender. Co-Authored-By: Claude Opus 5.5 --- scripts/bvh-to-fbx.py | 52 ++++++ scripts/idunn-entry.mjs | 3 +- scripts/vili-daemon.mjs | 356 +++++++++++++++++++++++++++++++++++++--- 3 files changed, 385 insertions(+), 26 deletions(-) create mode 100644 scripts/bvh-to-fbx.py diff --git a/scripts/bvh-to-fbx.py b/scripts/bvh-to-fbx.py new file mode 100644 index 0000000..313add1 --- /dev/null +++ b/scripts/bvh-to-fbx.py @@ -0,0 +1,52 @@ +# Converts one Kimodo standard-T-pose BVH to one FBX. Blender converts formats and nothing else: no retarget, no +# rename, no key reduction, no resample, no in-place bake. Run by the daemon (scripts/vili-daemon.mjs exportClip): +# blender -b --factory-startup --python-use-system-env --python-exit-code 1 --python bvh-to-fbx.py -- +# with PYTHONHASHSEED=0 in the environment. The settings are Blender API parameters, cross-checked against the +# 'unity' preset of wifimetas/kimodo-mcp blender_export.py (Apache-2.0, 83b5361); no code is copied. +import datetime +import json +import sys +import types + +import bpy + +# io_scene_fbx hashes strings for UUIDs (fbx_utils.py) and stamps the file with now() (export_fbx_bin.py): a fixed +# hash seed and a fixed time make one BVH on one host body give one set of FBX bytes. +if sys.flags.hash_randomization != 0: + sys.exit(3) + +bvh, fbx, clip = sys.argv[sys.argv.index("--") + 1:] + +bpy.ops.wm.read_factory_settings(use_empty=True) +scene = bpy.context.scene +scene.unit_settings.system = "METRIC" +scene.unit_settings.scale_length = 1.0 + +import io_scene_fbx.export_fbx_bin as fbx_bin # after the factory reset, which the pin must outlive + +if not hasattr(fbx_bin, "datetime"): + raise RuntimeError("io_scene_fbx.export_fbx_bin no longer stamps with datetime: the pin must move") +fixed_time = datetime.datetime(1970, 1, 1) +fbx_bin.datetime = types.SimpleNamespace(datetime=types.SimpleNamespace(now=lambda: fixed_time)) + +bpy.ops.import_anim.bvh( + filepath=bvh, global_scale=0.01, axis_forward="-Z", axis_up="Y", rotate_mode="NATIVE", + use_fps_scale=False, update_scene_fps=True, frame_start=1, +) +armature = bpy.context.view_layer.objects.active +action = armature.animation_data.action +# The FBX take takes the scene's name. +armature.name = armature.data.name = action.name = scene.name = clip +first, last = (int(frame) for frame in action.frame_range) +scene.frame_start, scene.frame_end = first, last + +bpy.ops.object.select_all(action="DESELECT") +armature.select_set(True) +bpy.ops.export_scene.fbx( + filepath=fbx, use_selection=True, object_types={"ARMATURE"}, apply_unit_scale=True, + apply_scale_options="FBX_SCALE_ALL", axis_forward="-Z", axis_up="Y", add_leaf_bones=False, + primary_bone_axis="Y", secondary_bone_axis="X", armature_nodetype="NULL", bake_anim=True, + bake_anim_use_all_bones=True, bake_anim_use_nla_strips=False, bake_anim_use_all_actions=False, + bake_anim_force_startend_keying=True, bake_anim_step=1.0, bake_anim_simplify_factor=0.0, +) +print("VILI-FBX " + json.dumps({"bones": len(armature.data.bones), "frames": [first, last], "fps": scene.render.fps})) diff --git a/scripts/idunn-entry.mjs b/scripts/idunn-entry.mjs index 9fb062c..75883a0 100644 --- a/scripts/idunn-entry.mjs +++ b/scripts/idunn-entry.mjs @@ -104,7 +104,7 @@ function parseEntryArgs(argv) { } // What the daemon reads from its environment, derived from Idunn's bind and the sealed release's own layout: -// the interpreter sits beside the vili tree, and the environment's identity is the hash of the two lock files. +// the interpreter and Blender sit beside the vili tree, and the environment's identity is the hash of the two lock files. export function daemonEnvironment(bind, entryDir) { const { host, port } = splitBind(bind); const locks = ["requirements-build.lock", "requirements.lock"].map((name) => @@ -115,6 +115,7 @@ export function daemonEnvironment(bind, entryDir) { VILI_DAEMON_HOST: host, VILI_DAEMON_PORT: port, VILI_PYTHON: path.resolve(entryDir, "..", "..", "python", "bin", "python3.12"), + VILI_BLENDER: path.resolve(entryDir, "..", "..", "blender", "blender"), VILI_PYTHON_ENV: `locks-sha256:${createHash("sha256").update(Buffer.concat(locks)).digest("hex")}`, }; } diff --git a/scripts/vili-daemon.mjs b/scripts/vili-daemon.mjs index e7977ae..3e7042e 100644 --- a/scripts/vili-daemon.mjs +++ b/scripts/vili-daemon.mjs @@ -1,9 +1,9 @@ #!/usr/bin/env node import http from "node:http"; import os from "node:os"; -import { createHash } from "node:crypto"; -import { closeSync, openSync, readdirSync, readFileSync, realpathSync, unlinkSync, writeFileSync, writeSync } from "node:fs"; -import { mkdir, writeFile } from "node:fs/promises"; +import { createHash, randomInt } from "node:crypto"; +import { closeSync, lstatSync, openSync, readdirSync, readFileSync, realpathSync, unlinkSync, writeFileSync, writeSync } from "node:fs"; +import { copyFile, mkdir, readFile, writeFile } from "node:fs/promises"; import path from "node:path"; import readline from "node:readline"; import net from "node:net"; @@ -74,6 +74,7 @@ const viliDocumentRegistry = defineDocumentRegistry( ); const MAX_THREADS = 16; +const CLIP_NAME = /^[A-Za-z0-9_-]{1,64}$/; // The state root's one identity: symlinks resolved as far as the path exists. The hand-run lock's name, reclaim's // marker and the worker's environment all derive from args.stateRoot, so two spellings of one root are one root. @@ -98,6 +99,7 @@ function parseArgs(argv) { threads: env.VILI_THREADS || "8", kimodoCommit: env.VILI_KIMODO_COMMIT || "", pythonEnv: env.VILI_PYTHON_ENV || "", + blender: env.VILI_BLENDER || "", }; for (let index = 0; index < argv.length; index += 1) { @@ -111,6 +113,7 @@ function parseArgs(argv) { else if (arg === "--threads") args.threads = argv[++index]; else if (arg === "--kimodo-commit") args.kimodoCommit = argv[++index]; else if (arg === "--python-env") args.pythonEnv = argv[++index]; + else if (arg === "--blender") args.blender = argv[++index]; } if (!/^[0-9]{1,2}$/.test(String(args.threads)) || Number(args.threads) < 1 || Number(args.threads) > MAX_THREADS) { console.error(`threads must be an integer from 1 to ${MAX_THREADS}`); @@ -119,16 +122,27 @@ function parseArgs(argv) { args.threads = Number(args.threads); args.stateRoot = canonicalPath(args.stateRoot); if (args.modelsRoot) args.modelsRoot = path.resolve(args.modelsRoot); + if (args.blender) args.blender = path.resolve(args.blender); return args; } const args = parseArgs(process.argv.slice(2)); const startedAt = new Date().toISOString(); +// The rest pose Kimodo ships, in the worker interpreter's own tree (/lib/python3.12/site-packages), once. +const restBvh = path.isAbsolute(args.python) + ? path.join(path.dirname(path.dirname(args.python)), "lib", "python3.12", "site-packages", "kimodo", "assets", "skeletons", "somaskel77", "somaskel77_standard_tpose.bvh") + : null; + // The worker child. Display state only: nothing reads `worker` to decide anything but ensureWorker. const worker = { state: "stopped", proc: null, pid: null, port: null, servedModels: [], lastError: null }; let starting = null; +// Blender, probed once after the lease. Display and admission state: it decides only whether an fbx request is +// refused early. `version` is the first line of `blender --version`, or null (unconfigured, or the probe failed). +const blender = { version: null }; +const blenderReady = () => blender.version !== null; + function firstDefined(...values) { return values.find((value) => value !== undefined && value !== null); } @@ -175,6 +189,7 @@ function backendStatus() { kimodoCommit: args.kimodoCommit || null, modelsRoot: args.modelsRoot || null, lastError: worker.lastError, + blender: blender.version ?? (args.blender ? "unavailable" : "unconfigured"), }; } @@ -192,6 +207,7 @@ function operatorState() { "animation job intake", "worker process lifecycle", "motion artifact references", + "clip export to FBX", ], doesNotOwn: [ "Persona speech generation", @@ -204,6 +220,8 @@ function operatorState() { health: "/health", operatorState: "/operator-state", generate: "/motion/generate", + artifacts: "/motion/artifacts/{jobId}/{name}", + restFbx: "/motion/rest-fbx", }, }; } @@ -225,8 +243,20 @@ function commandBoundary() { "worker process lifecycle", "timeout handling", "motion artifact references", + "clip export", ], }, + restFbx: { + method: "POST", + path: "/motion/rest-fbx", + owns: ["the rest-pose FBX job"], + }, + artifacts: { + method: "GET", + path: "/motion/artifacts/{jobId}/{name}", + owns: ["read-only artifact bytes"], + doesNotOwn: ["any path outside the job's artifact directory"], + }, liveness: { method: "GET", path: "/health", @@ -294,6 +324,21 @@ function childEnv() { return env; } +// The whole Blender environment, in one place: nothing else from process.env reaches it. The libraries the sealed +// release carries sit in blender/lib; PYTHONHASHSEED=0 is half of byte-reproducible export (scripts/bvh-to-fbx.py). +function exportEnv() { + const env = { + HOME: "/nonexistent", + PYTHONHASHSEED: "0", + PYTHONNOUSERSITE: "1", + LD_LIBRARY_PATH: path.join(path.dirname(args.blender), "lib"), + }; + for (const name of ["PATH", "LANG"]) { + if (process.env[name] !== undefined) env[name] = process.env[name]; + } + return env; +} + function workerUnconfigured() { return !args.modelsRoot || !args.kimodoCommit || !args.pythonEnv; } @@ -407,17 +452,187 @@ export function handRunRuntime(stateRoot) { }; } -// A requested stop gives the worker its grace (SIGTERM, then SIGKILL); a lost writer gets SIGKILL at once. -async function stopWorker(signals = ["SIGTERM", "SIGKILL"]) { +// A requested stop gives a process group its grace (SIGTERM, then SIGKILL); a lost writer gets SIGKILL at once. The +// worker and the exports are stopped by this one path. +async function stopGroups(procs, signals) { + for (const signal of signals) { + for (const proc of procs) if (proc.pid !== undefined) killGroup(proc.pid, signal); + const gone = await Promise.all(procs.map((proc) => waitForExit(proc, signal === "SIGTERM" ? 10000 : 5000))); + if (gone.every(Boolean)) break; + } +} + +const STOP_SIGNALS = ["SIGTERM", "SIGKILL"]; + +async function stopWorker(signals = STOP_SIGNALS) { const proc = worker.proc; if (!proc || proc.pid === undefined) return; worker.state = "stopped"; - for (const signal of signals) { - killGroup(proc.pid, signal); - if (await waitForExit(proc, signal === "SIGTERM" ? 10000 : 5000)) break; + await stopGroups([proc], signals); +} + +// Blender's process groups in flight. A finished export removes itself; a model switch (ensureWorker) leaves them alone. +const exportGroups = new Set(); +const stopExports = (signals = STOP_SIGNALS) => stopGroups([...exportGroups], signals); + +function isRegularFile(file) { + try { + return lstatSync(file).isFile(); + } catch { + return false; } } +// A regular file (no symlink, in the file or any directory above it) strictly inside `directory`, which is canonical. +function regularFileInside(file, directory) { + const relative = path.relative(directory, file); + if (!relative || path.isAbsolute(relative) || relative.split(path.sep)[0] === "..") return false; + try { + return lstatSync(file).isFile() && realpathSync(file) === file; + } catch { + return false; + } +} + +const exportScript = path.join(__dirname, "bvh-to-fbx.py"); +const EXPORT_SETTINGS = "standard-tpose soma77 metres hashseed0 time1970"; +const EXPORT_TIMEOUT_MS = 120000; +let exportScriptDigest = null; +const scriptDigest = () => (exportScriptDigest ??= `sha256:${createHash("sha256").update(readFileSync(exportScript)).digest("hex")}`); + +// Runs the sealed Blender in its own process group, niced, under the write gate. Both streams go to +// logs/export.log line by line through mayWrite(), and only there. Resolves { code, signal, first, result }: the +// exit, the first stdout line and the last `VILI-FBX ` line's payload. It rejects only with LeaseLost. +async function runBlender(argv, timeoutMs) { + guard(); + await mkdir(path.join(args.stateRoot, "logs"), { recursive: true }); + guard(); // synchronous with the log open and the spawn below: no await between them + const sink = openSync(path.join(args.stateRoot, "logs", "export.log"), "a"); + const proc = spawn(args.blender, argv, { + cwd: __dirname, + env: exportEnv(), + stdio: ["ignore", "pipe", "pipe"], + shell: false, + detached: true, + }); + exportGroups.add(proc); + const seen = { first: null, result: null }; + let sinkOpen = true; + for (const [stream, isStdout] of [[proc.stdout, true], [proc.stderr, false]]) { + if (!stream) continue; + readline.createInterface({ input: stream }).on("line", (line) => { + if (isStdout) { + seen.first ??= line; + if (line.startsWith("VILI-FBX ")) seen.result = line.slice("VILI-FBX ".length); + } + if (sinkOpen && mayWrite()) writeSync(sink, `${line}\n`); + }); + } + const finished = new Promise((resolve) => { + proc.once("error", () => resolve({ code: null, signal: null })); + proc.once("close", (code, signal) => resolve({ code, signal })); + }); + proc.once("exit", () => { + exportGroups.delete(proc); + if (proc.pid !== undefined) killGroup(proc.pid, "SIGKILL"); // whatever Blender left running + }); + try { + os.setPriority(proc.pid, 10); + } catch { + if (proc.pid !== undefined) killGroup(proc.pid, "SIGKILL"); + } + const timer = setTimeout(() => { + if (proc.pid !== undefined) killGroup(proc.pid, "SIGKILL"); + }, timeoutMs); + const exit = await finished; + clearTimeout(timer); + exportGroups.delete(proc); + sinkOpen = false; + closeSync(sink); + return { ...exit, ...seen }; +} + +// Blender answers once at start: `blender --version`, 15 s. Ready only when it exits 0 and names itself. +async function probeBlender() { + if (!args.blender) return; + const run = await runBlender(["-b", "--factory-startup", "--version"], 15000); + guard(); + blender.version = run.code === 0 && run.first?.startsWith("Blender ") ? run.first : null; +} + +// One BVH to one FBX beside it. The FBX counts only if Blender exits 0, prints its result line and the file exists. +// A failure names the exit or the signal and never Blender's output. +async function exportClip(bvh, fbx, clipName, timeoutMs) { + const run = await runBlender([ + "-b", "--factory-startup", "--python-use-system-env", "--python-exit-code", "1", + "--python", exportScript, "--", bvh, fbx, clipName, + ], timeoutMs); + guard(); // the writer may have been lost while Blender ran + let info = null; + if (run.code === 0 && run.result !== null) { + try { + const parsed = JSON.parse(run.result); + if (Number.isInteger(parsed.bones) && Array.isArray(parsed.frames) && parsed.frames.length === 2 + && parsed.frames.every(Number.isInteger) && Number.isFinite(parsed.fps)) info = parsed; + } catch { + // not the result line + } + } + if (info && isRegularFile(fbx)) return { clip: { file: fbx, clipName, bones: info.bones, frames: info.frames, fps: info.fps } }; + const how = run.code === 0 ? "no result" : run.code !== null ? `exit ${run.code}` : `signal ${run.signal ?? "none"}`; + return { error: `fbx-export-failed (${how})` }; +} + +// Every BVH the worker listed becomes an FBX, or the job fails. A listed BVH must be a regular file inside the job's +// artifact directory, and all are checked before Blender starts for any. Sample N of several is _NN. +async function exportListed(listed, artifactDir, clipName, timeoutMs) { + const bvhs = []; + for (const file of Array.isArray(listed) ? listed : []) { + if (typeof file !== "string" || !file.endsWith(".bvh")) continue; + const full = path.resolve(artifactDir, file); + if (!regularFileInside(full, artifactDir)) return { clips: [], error: "fbx-export-refused" }; + bvhs.push(full); + } + if (bvhs.length === 0) return { clips: [], error: "fbx-export-failed (no bvh)" }; + bvhs.sort(); + const clips = []; + for (const [index, bvh] of bvhs.entries()) { + const name = bvhs.length === 1 ? clipName : `${clipName}_${String(index).padStart(2, "0")}`; + const done = await exportClip(bvh, `${bvh.slice(0, -".bvh".length)}.fbx`, name, timeoutMs); + if (done.error) return { clips, error: done.error }; + clips.push({ ...done.clip, file: path.relative(artifactDir, done.clip.file).split(path.sep).join("/") }); + } + return { clips, error: null }; +} + +// Every regular file under the artifact directory, named relative to it, sorted. +async function artifactFiles(directory) { + const files = []; + const walk = async (relative) => { + for (const entry of readdirSync(path.join(directory, relative), { withFileTypes: true })) { + const name = path.join(relative, entry.name); + if (entry.isDirectory()) await walk(name); + else if (entry.isFile()) { + const bytes = await readFile(path.join(directory, name)); + files.push({ name: name.split(path.sep).join("/"), bytes: bytes.length, sha256: createHash("sha256").update(bytes).digest("hex") }); + } + } + }; + await walk(""); + return files.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); +} + +// The one job record, for a generate job and a rest job alike: what the job was, which files it left and, for an +// export, the exact Blender and script that made them. +async function writeJobRecord(job, exported) { + guard(); + const record = { schema: "gamecult.vili.motion_job.v1", ...job, files: await artifactFiles(job.artifactDir) }; + if (exported) record.export = { blender: blender.version, script: scriptDigest(), settings: EXPORT_SETTINGS, clips: exported.clips }; + guard(); + await writeFile(path.join(args.stateRoot, "jobs", `${job.jobId}.json`), JSON.stringify(record, null, 2)); + return record; +} + async function startWorker(model, timeoutMs) { guard(); await mkdir(path.join(args.stateRoot, "logs"), { recursive: true }); @@ -524,9 +739,9 @@ async function readRequestBody(request) { return raw ? JSON.parse(raw) : {}; } -async function generateMotion(request, response) { +async function underLease(response, run) { try { - await generate(request, response); + await run(); } catch (error) { if (!(error instanceof LeaseLost)) throw error; json(response, 503, { ok: false, code: stopping ? "stopping" : runtime.refusal() }); @@ -562,7 +777,25 @@ async function generate(request, response) { return; } + // One export plan: fbx implies the BVH and its standard T-pose, which the FBX is made from. + const fbx = boolValue(body.fbx); + const askedTpose = firstDefined(body.bvhStandardTpose, body.bvh_standard_tpose); + if (fbx && ((askedTpose !== undefined && !boolValue(askedTpose)) + || (body.clipName !== undefined && !(typeof body.clipName === "string" && CLIP_NAME.test(body.clipName))))) { + json(response, 400, { ok: false, error: "Invalid fbx request." }); + return; + } + if (fbx && !blenderReady()) { + json(response, 503, { ok: false, code: "blender-unavailable" }); + return; + } + const plan = { + bvh: fbx || boolValue(body.bvh), + bvhStandardTpose: fbx || boolValue(askedTpose), + }; + const jobId = `vili-${Date.now()}`; + const clipName = fbx ? (body.clipName ?? jobId) : undefined; const artifactDir = path.join(args.stateRoot, "artifacts", jobId); guard(); await mkdir(artifactDir, { recursive: true }); @@ -574,7 +807,8 @@ async function generate(request, response) { bodyMeta.diffusion_steps, 20, ))); - const seed = body.seed === undefined ? null : Number(body.seed); + const askedSeed = Number(firstDefined(body.seed, bodyMeta.seed)); + const seed = Number.isFinite(askedSeed) ? askedSeed : randomInt(0, 2 ** 31); const numSamples = Math.max(1, Number(firstDefined( body.numSamples, body.num_samples, @@ -591,7 +825,7 @@ async function generate(request, response) { }; meta.num_samples = Math.max(1, Number(firstDefined(body.numSamples, body.num_samples, meta.num_samples, 1))); meta.diffusion_steps = diffusionSteps; - if (Number.isFinite(seed)) meta.seed = seed; + meta.seed = seed; if (body.cfg) meta.cfg = body.cfg; const constraintsPath = (() => { if (typeof body.constraints === "string") return body.constraints; @@ -615,12 +849,13 @@ async function generate(request, response) { diffusion_steps: diffusionSteps, numTransitionFrames: firstDefined(body.numTransitionFrames, body.num_transition_frames), constraints: constraintsPath, - seed: Number.isFinite(seed) ? seed : undefined, + seed, + fbx: fbx || undefined, + clipName, cfg: body.cfg, cfgType: firstDefined(body.cfgType, body.cfg_type), cfgWeight: firstDefined(body.cfgWeight, body.cfg_weight), - bvh: boolValue(body.bvh), - bvhStandardTpose: boolValue(firstDefined(body.bvhStandardTpose, body.bvh_standard_tpose)), + ...plan, noPostprocess: boolValue(firstDefined(body.noPostprocess, body.no_postprocess)), saveExampleDir: boolValue(firstDefined(body.saveExampleDir, body.save_example_dir)), inputFolder: firstDefined(body.inputFolder, body.input_folder), @@ -645,12 +880,11 @@ async function generate(request, response) { numSamples, numTransitionFrames: firstDefined(body.numTransitionFrames, body.num_transition_frames), constraints: constraintsPath, - seed: Number.isFinite(seed) ? seed : undefined, + seed, cfg: body.cfg, cfgType: firstDefined(body.cfgType, body.cfg_type), cfgWeight: firstDefined(body.cfgWeight, body.cfg_weight), - bvh: boolValue(body.bvh), - bvhStandardTpose: boolValue(firstDefined(body.bvhStandardTpose, body.bvh_standard_tpose)), + ...plan, noPostprocess: boolValue(firstDefined(body.noPostprocess, body.no_postprocess)), saveExampleDir: boolValue(firstDefined(body.saveExampleDir, body.save_example_dir)), output: path.join(artifactDir, "motion"), @@ -670,9 +904,15 @@ async function generate(request, response) { result = { ok: false, error: `the worker request failed (${error?.name || "Error"})`, body: null }; } + let exported = null; + if (fbx && result.ok) { + const timeoutMs = Math.min(EXPORT_TIMEOUT_MS, Math.max(1, Number(firstDefined(body.exportTimeoutMs, EXPORT_TIMEOUT_MS)) || EXPORT_TIMEOUT_MS)); + exported = await exportListed(result.body?.files, artifactDir, clipName, timeoutMs); + if (exported.error) result = { ok: false, error: exported.error, body: result.body }; + } + guard(); // the writer may have been lost while the job ran - const job = { - schema: "gamecult.vili.motion_job.v0", + const job = await writeJobRecord({ jobId, createdAt: new Date().toISOString(), prompt: prompt || null, @@ -685,11 +925,69 @@ async function generate(request, response) { ok: result.ok, error: result.error, worker: result.body, - }; - await writeFile(path.join(args.stateRoot, "jobs", `${jobId}.json`), JSON.stringify(job, null, 2)); + }, exported); json(response, result.ok ? 200 : 502, job); } +// The release's own rest pose, exported as the avatar cut's source: a job like any other, made from Kimodo's +// standard-T-pose BVH that the worker interpreter's site-packages carries. +async function restFbx(response) { + guard(); + if (!blenderReady()) { + json(response, 503, { ok: false, code: "blender-unavailable" }); + return; + } + if (!restBvh || !isRegularFile(restBvh)) { + json(response, 503, { ok: false, code: "rest-skeleton-missing" }); + return; + } + const jobId = `rest-${Date.now()}`; + const artifactDir = path.join(args.stateRoot, "artifacts", jobId); + guard(); + await mkdir(artifactDir, { recursive: true }); + guard(); + await copyFile(restBvh, path.join(artifactDir, "SOMA77_Rest.bvh")); + const exported = await exportListed([path.join(artifactDir, "SOMA77_Rest.bvh")], artifactDir, "SOMA77_Rest", EXPORT_TIMEOUT_MS); + guard(); + const job = await writeJobRecord({ + jobId, + createdAt: new Date().toISOString(), + prompt: null, + model: null, + request: null, + durationSeconds: null, + diffusionSteps: null, + seed: null, + artifactDir, + ok: !exported.error, + error: exported.error, + worker: null, + }, exported); + json(response, job.ok ? 200 : 502, job); +} + +// Reads only: a job's own FBX and BVH files, by exact name, regular files inside the job's artifact directory. +const ARTIFACT_ROUTE = /^\/motion\/artifacts\/((?:vili|rest)-[0-9]{13})\/(motion\.fbx|motion\.bvh|SOMA77_Rest\.fbx|motion\/motion_[0-9]{2}\.(?:fbx|bvh))$/; + +async function serveArtifact(response, jobId, name) { + const directory = path.join(args.stateRoot, "artifacts", jobId); + const file = path.join(directory, name); + let bytes = null; + if (regularFileInside(file, directory)) { + try { + bytes = await readFile(file); + } catch { + // gone between the check and the read + } + } + if (bytes === null) { + text(response, 404, "not found\n"); + return; + } + response.writeHead(200, { "content-type": "application/octet-stream", "cache-control": "no-store" }); + response.end(bytes); +} + const SNAPSHOT_BODY_MAX = 64 * 1024; // Idunn's route challenge: a msgpack POST from the host, answered from local authority. A browser page can send @@ -732,6 +1030,11 @@ async function handleRequest(request, response) { await answerRouteChallenge(request, response); return; } + const artifact = request.method === "GET" ? ARTIFACT_ROUTE.exec(url.pathname) : null; + if (artifact) { + await serveArtifact(response, artifact[1], artifact[2]); + return; + } if (request.method === "POST" && refuseCrossSite(request, response)) return; if (url.pathname === "/" || url.pathname === "/health") { @@ -739,7 +1042,9 @@ async function handleRequest(request, response) { } else if (url.pathname === "/operator-state") { json(response, 200, operatorState()); } else if (url.pathname === "/motion/generate" && request.method === "POST") { - await generateMotion(request, response); + await underLease(response, () => generate(request, response)); + } else if (url.pathname === "/motion/rest-fbx" && request.method === "POST") { + await underLease(response, () => restFbx(response)); } else { text(response, 404, "not found\n"); } @@ -792,7 +1097,7 @@ export async function serve(rt) { server.close(); server.closeIdleConnections(); clearInterval(tick); - await stopWorker(); + await Promise.all([stopWorker(), stopExports()]); runtime.release(); process.exit(0); }; @@ -805,13 +1110,14 @@ export async function serve(rt) { if (lost) return; lost = true; clearInterval(tick); - stopWorker(["SIGKILL"]).finally(() => runtime.reportHealth?.("degraded")); + Promise.all([stopWorker(["SIGKILL"]), stopExports(["SIGKILL"])]).finally(() => runtime.reportHealth?.("degraded")); }; runtime.watch(onLost); // held() reports a loss through this the moment any gate sees it try { guard(); await mkdir(path.join(args.stateRoot, "jobs"), { recursive: true }); await persistSurfaces(); + await probeBlender(); } catch (error) { if (error instanceof LeaseLost) return; // lost while opening the state root: onLost has run, and nothing is active throw error; From 0c34679bdc4333de82b24a0fa3abdcfe16140f94 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 24 Oct 2026 20:29:41 +0200 Subject: [PATCH 03/36] Recipe: Blender 5.2.2 and its nine Debian libraries are sealed in the release Ten sha256-pinned external inputs, unpack-blender and unpack-blender-libs steps, the blender artifact (blender 0555), VILI_BLENDER for test_bvh_to_fbx.py, jobs slot schema motion_job.v1. Co-Authored-By: Claude Opus 5.5 --- deployment/idunn/recipe.toml | 119 ++++++++++++++++++++++++++++++-- deployment/idunn/unpack-debs.py | 76 ++++++++++++++++++++ 2 files changed, 190 insertions(+), 5 deletions(-) create mode 100644 deployment/idunn/unpack-debs.py diff --git a/deployment/idunn/recipe.toml b/deployment/idunn/recipe.toml index 304ad29..c4ffef2 100644 --- a/deployment/idunn/recipe.toml +++ b/deployment/idunn/recipe.toml @@ -3,7 +3,7 @@ target = "vili" source_stamp_environment = "VILI_BUILD_COMMIT" required_gitlinks = ["vendor/CultLib", "vendor/kimodo", "vendor/SOMA-X"] -# The one external input: a relocatable CPython. The locked site-packages are installed into this tree itself: a copied +# External inputs: a relocatable CPython, then Blender and the libraries it loads. The locked site-packages are installed into this tree itself: a copied # environment would carry an absolute interpreter link and a recorded build path, and the seal refuses both. [[external_inputs]] id = "cpython" @@ -12,6 +12,83 @@ sha256 = "5ff9f0602ce964a529ed1e8555d3abab6341926d724402ba9a15e9e877191124" runner = "python-build" destination = "release/cpython.tar.gz" +# Blender 5.2.2 LTS, unpacked beside the interpreter. The tree is sealed whole; the daemon runs it with +# LD_LIBRARY_PATH=blender/lib (scripts/vili-daemon.mjs exportEnv). +[[external_inputs]] +id = "blender" +url = "https://download.blender.org/release/Blender5.2/blender-5.2.2-linux-x64.tar.xz" +sha256 = "84098912789dc450e95697c4184fb8a90acbe5111c2ba4aede3fecb57806a168" +runner = "python-build" +destination = "release/blender.tar.xz" + +# The nine Debian bookworm packages whose shared libraries Blender loads and its tree does not carry (the Blender +# tarball's loader reaches libGL and the X client libraries). Their usr/lib/x86_64-linux-gnu/*.so* go into blender/lib; +# nothing is installed on the host (motion-pipeline:ruling:blender-libs-bundled-in-release). One snapshot.debian.org +# timestamp, so the bytes are immutable; each sha256 is the package's own. + +[[external_inputs]] +id = "deb-libxrender1" +url = "https://snapshot.debian.org/archive/debian/20260301T000000Z/pool/main/libx/libxrender/libxrender1_0.9.10-1.1_amd64.deb" +sha256 = "b2a6d160578f359220101947c8d67059b44704a251e688de1d0b744fefedfd1a" +runner = "python-build" +destination = "release/deb-libxrender1.deb" + +[[external_inputs]] +id = "deb-libxfixes3" +url = "https://snapshot.debian.org/archive/debian/20260301T000000Z/pool/main/libx/libxfixes/libxfixes3_6.0.0-2_amd64.deb" +sha256 = "1cd616396ff2ecae77e6e8b5b7695d414f0146de2d147837a2a02165f99e1a2c" +runner = "python-build" +destination = "release/deb-libxfixes3.deb" + +[[external_inputs]] +id = "deb-libxi6" +url = "https://snapshot.debian.org/archive/debian/20260301T000000Z/pool/main/libx/libxi/libxi6_1.8-1+b1_amd64.deb" +sha256 = "6c2fb5f241b311788990122c6e693915867cd8ed9d6da2e3524aec7ed3cdb4c0" +runner = "python-build" +destination = "release/deb-libxi6.deb" + +[[external_inputs]] +id = "deb-libxkbcommon0" +url = "https://snapshot.debian.org/archive/debian/20260301T000000Z/pool/main/libx/libxkbcommon/libxkbcommon0_1.5.0-1_amd64.deb" +sha256 = "e3fe045b9a33a101de1c5a912a4a10928db055c3f68930f47eccbb44d7c7d54e" +runner = "python-build" +destination = "release/deb-libxkbcommon0.deb" + +[[external_inputs]] +id = "deb-libsm6" +url = "https://snapshot.debian.org/archive/debian/20260301T000000Z/pool/main/libs/libsm/libsm6_1.2.3-1_amd64.deb" +sha256 = "22a420890489023346f30fecef14ea900a0788e7bf959ef826aabb83944fccfb" +runner = "python-build" +destination = "release/deb-libsm6.deb" + +[[external_inputs]] +id = "deb-libice6" +url = "https://snapshot.debian.org/archive/debian/20260301T000000Z/pool/main/libi/libice/libice6_1.0.10-1_amd64.deb" +sha256 = "452796e565c9d42386bd59990000ae9c37d85e142e00ee2b14df0787e2bbf970" +runner = "python-build" +destination = "release/deb-libice6.deb" + +[[external_inputs]] +id = "deb-libgl1" +url = "https://snapshot.debian.org/archive/debian/20260301T000000Z/pool/main/libg/libglvnd/libgl1_1.6.0-1_amd64.deb" +sha256 = "6f89b1702c48e9a2437bb3c1ffac8e1ab2d828fc28b3d14b2eecd4cc19b2c790" +runner = "python-build" +destination = "release/deb-libgl1.deb" + +[[external_inputs]] +id = "deb-libglx0" +url = "https://snapshot.debian.org/archive/debian/20260301T000000Z/pool/main/libg/libglvnd/libglx0_1.6.0-1_amd64.deb" +sha256 = "95f568df73dedf43ae66834a75502112e0d4f3ad7124f3dbfa790b739383b896" +runner = "python-build" +destination = "release/deb-libglx0.deb" + +[[external_inputs]] +id = "deb-libglvnd0" +url = "https://snapshot.debian.org/archive/debian/20260301T000000Z/pool/main/libg/libglvnd/libglvnd0_1.6.0-1_amd64.deb" +sha256 = "b6da5b153dd62d8b5e5fbe25242db1fc05c068707c365db49abda8c2427c75f8" +runner = "python-build" +destination = "release/deb-libglvnd0.deb" + # ---- node-build: the daemon, the Idunn entry and its dependencies [[steps]] @@ -67,6 +144,30 @@ phase = "prepare" runner = "python-build" argv = ["tar", "-xzf", "release/cpython.tar.gz", "-C", "release"] +[[steps]] +id = "unpack-blender" +phase = "prepare" +runner = "python-build" +argv = ["tar", "-xJf", "release/blender.tar.xz", "-C", "release", "--transform", "s,^blender-5.2.2-linux-x64,blender,"] + +[[steps]] +id = "unpack-blender-libs" +phase = "prepare" +runner = "python-build" +required_environment = ["PATH"] +argv = [ + "python3.12", "deployment/idunn/unpack-debs.py", "release/blender/lib", + "release/deb-libxrender1.deb", + "release/deb-libxfixes3.deb", + "release/deb-libxi6.deb", + "release/deb-libxkbcommon0.deb", + "release/deb-libsm6.deb", + "release/deb-libice6.deb", + "release/deb-libgl1.deb", + "release/deb-libglx0.deb", + "release/deb-libglvnd0.deb", +] + [[steps]] id = "install-build-tools" phase = "prepare" @@ -93,7 +194,7 @@ id = "test-worker" phase = "test" runner = "python-build" working_directory = "." -required_environment = ["HOME", "TMPDIR", "PYTHONPATH", "PATH"] +required_environment = ["HOME", "TMPDIR", "PYTHONPATH", "PATH", "VILI_BLENDER"] argv = ["python3.12", "-m", "unittest", "discover", "-s", "scripts", "-p", "test_*.py"] # Every module the worker and the encoder child import at top level, kimodo.scripts.generate included. @@ -114,7 +215,7 @@ runner = "python-build" required_environment = ["PATH"] argv = ["python3.12", "-m", "compileall", "-q", "-j", "4", "--invalidation-mode", "unchecked-hash", "release/python/lib/python3.12"] -# ---- the sealed release: node, vili, python +# ---- the sealed release: node, vili, python, blender [[artifacts]] id = "node" @@ -139,9 +240,17 @@ source = "release/python" destination = "python" executable_members = ["bin/python3.12"] +[[artifacts]] +id = "blender" +source_kind = "runner-output" +runner = "python-build" +source = "release/blender" +destination = "blender" +executable_members = ["blender"] + [service] executable_artifact = "node" -required_adjacent_artifacts = ["vili", "python"] +required_adjacent_artifacts = ["vili", "python", "blender"] arguments = [ { kind = "literal", value = "vili/scripts/idunn-entry.mjs" }, { kind = "literal", value = "--state-root" }, @@ -187,7 +296,7 @@ startup = "create-or-open-after-write-lease" id = "jobs" relative_path = "jobs" kind = "external-directory" -schema = "gamecult.vili.motion_job.v0" +schema = "gamecult.vili.motion_job.v1" writer = "process-bound-single-writer" recovery = "preserve" startup = "create-or-open-after-write-lease" diff --git a/deployment/idunn/unpack-debs.py b/deployment/idunn/unpack-debs.py new file mode 100644 index 0000000..cf197fc --- /dev/null +++ b/deployment/idunn/unpack-debs.py @@ -0,0 +1,76 @@ +"""Unpacks the shared libraries of Debian packages into one directory (the recipe's unpack-blender-libs step): + + python3.12 deployment/idunn/unpack-debs.py ... + +Only usr/lib/x86_64-linux-gnu/*.so* is taken, flat: regular files and relative symlinks. Nothing else in a package +is read out, nothing is overwritten, and a package that yields no library is an error. Standard library only: the +step runs before any package is installed. +""" +import fnmatch +import io +import os +import pathlib +import sys +import tarfile + +LIBRARY_DIRECTORY = "usr/lib/x86_64-linux-gnu" + + +def data_archive(deb): + """The data.tar.* member of a .deb, an ar archive.""" + raw = deb.read_bytes() + if raw[:8] != b"!\n": + raise SystemExit("not an ar archive: " + deb.name) + position = 8 + while position + 60 <= len(raw): + header = raw[position:position + 60] + name = header[:16].decode("ascii").strip().rstrip("/") + size = int(header[48:58].decode("ascii").strip()) + position += 60 + if name.startswith("data.tar"): + return raw[position:position + size] + position += size + (size & 1) + raise SystemExit("no data archive in " + deb.name) + + +def unpack(deb, destination): + taken = [] + with tarfile.open(fileobj=io.BytesIO(data_archive(deb)), mode="r:*") as archive: + for member in archive: + directory, _, name = member.name.lstrip("./").rpartition("/") + if directory != LIBRARY_DIRECTORY or not fnmatch.fnmatch(name, "*.so*"): + continue + target = destination / name + if os.path.lexists(target): + raise SystemExit("already present: " + name) + if member.isreg(): + target.write_bytes(archive.extractfile(member).read()) + target.chmod(0o644) + elif member.issym(): + if "/" in member.linkname or member.linkname in ("", ".", ".."): + raise SystemExit("not a sibling link: " + name) + os.symlink(member.linkname, target) + else: + raise SystemExit("unexpected member type: " + name) + taken.append(name) + if not taken: + raise SystemExit("no library in " + deb.name) + return taken + + +def main(argv): + if len(argv) < 2: + raise SystemExit("usage: unpack-debs.py ...") + destination = pathlib.Path(argv[0]) + if not destination.is_dir(): + raise SystemExit("destination is not a directory") + total = 0 + for deb in argv[1:]: + taken = unpack(pathlib.Path(deb), destination) + total += len(taken) + print(f"{pathlib.Path(deb).name}: {len(taken)} libraries") + print(f"unpacked {total} libraries") + + +if __name__ == "__main__": + main(sys.argv[1:]) From 89ddb8dab03fceec6349fdeac949e725ed82fda6 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 24 Oct 2026 20:29:42 +0200 Subject: [PATCH 04/36] README: Vili is live on Yggdrasil; FBX export, the read route, rest-fbx and the v1 job record Co-Authored-By: Claude Opus 5.5 --- README.md | 44 ++++++++++++++++++++++++++++++++++++++------ 1 file changed, 38 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 5639475..da2ab50 100644 --- a/README.md +++ b/README.md @@ -4,15 +4,15 @@ Vili is the GameCult Persona animation daemon. It owns the bridge from Persona performance intent to body-motion generation. Its backend is Kimodo, run by Vili's own daemon as a CPU-only Python process tree on -Linux. It is built to run on Yggdrasil as an Idunn target (planned, not live; see Front Door). +Linux. It runs on Yggdrasil as an Idunn target (see Front Door). ## Front Door -- **Value:** a supervised path from a text prompt to generated body motion. The daemon spawns one resident Kimodo worker, caps its threads, and returns motion artifacts (`motion.npz`, optional BVH) for a job. +- **Value:** a supervised path from a text prompt to generated body motion. The daemon spawns one resident Kimodo worker, caps its threads, and returns motion artifacts (`motion.npz`, BVH, and FBX for Unity) for a job. - **Problem:** Personas and games need generated motion, but cold per-request model loads cost minutes. One daemon owns job identity, worker lifecycle, the thread budget and artifact references, so callers touch no model state. - **Entry points:** `scripts/vili-daemon.mjs` (the daemon; `npm start`, `npm test`), `scripts/idunn-entry.mjs` (the process Idunn runs), `deployment/idunn/recipe.toml` (the sealed release), `scripts/kimodo-resident-worker.py` (the worker it spawns), `scripts/kimodo-text-encode.py` (the one-shot encoder child), `POST /motion/generate` (see Motion Generation), `docs/verse-service-contract.md` and `docs/motion-pipeline-target.md`. -- **Live:** the process tree below, run by hand for development and tests: `POST /motion/generate`, `GET /health`, `GET /operator-state`, and the CultCache service store. It produces `motion.npz` and optional BVH on the SOMA skeleton; there is no FBX export. -- **Planned:** the Idunn target `vili` on Yggdrasil at `http://10.77.0.1:8824` over WireGuard, with its provisioning runbook in `gamecult-ops`; neither exists until the first `idunn up` lands. FBX export and a text-prompt-to-Unity-clip path with no hand steps (`docs/motion-pipeline-target.md`). +- **Live:** the Idunn target `vili` on Yggdrasil at `http://10.77.0.1:8824` (WireGuard only), CPU only: `POST /motion/generate` (add `"fbx": true` for a Unity-ready FBX per clip), `POST /motion/rest-fbx` (the avatar's rest pose), `GET /motion/artifacts/{jobId}/{name}` (the FBX and BVH bytes), `GET /health`, `GET /operator-state`, and the CultCache service store. FBX export is `scripts/bvh-to-fbx.py` in the release's own Blender 5.2.2; see FBX Export. +- **Planned:** worker intake closed to local callers only, publication to Odin, and a Thing 2 operator surface. The text-prompt-to-Unity-clip path with no hand steps is `docs/motion-pipeline-target.md`. ## Authority @@ -128,12 +128,13 @@ Supported request fields: - `numTransitionFrames` / `num_transition_frames` - `constraints` as an object/list, or `constraints`, `constraintsPath`, or `constraints_path` as a path on the worker host -- `seed` +- `seed` (absent: the daemon mints one, and every job records the seed it used) - `cfg`, `cfgType` / `cfg_type`, `cfgWeight` / `cfg_weight` - `bvh`, `bvhStandardTpose` / `bvh_standard_tpose` +- `fbx` and `clipName` (see FBX Export) - `noPostprocess` / `no_postprocess` - `saveExampleDir` / `save_example_dir` -- `timeoutMs`, `workerTimeoutMs` +- `timeoutMs`, `workerTimeoutMs`, `exportTimeoutMs` (at most 120000) Vili intentionally does not accept an arbitrary Kimodo output path. Generated artifacts are written under `.vili/artifacts/{jobId}/` and referenced from the @@ -141,6 +142,37 @@ job record. `Kimodo-SOMA-RP-v1.1` produces NPZ and optional BVH output, `Kimodo-SMPLX-RP-v1.1` also exports AMASS NPZ, and `Kimodo-G1-RP-v1.1` also exports CSV when that model is resident. +## FBX Export + +`"fbx": true` makes the job's BVH an FBX for Unity, beside it: `motion.fbx`, or `motion/motion_NN.fbx` for several +samples. It implies `bvh` and `bvhStandardTpose`; an explicit `bvhStandardTpose: false` is a 400. `clipName` +(`^[A-Za-z0-9_-]{1,64}$`, default the job id; sample N of several is `_NN`) names the armature, the action +and the FBX take. With Blender not ready (`backend.blender` is `unconfigured` or `unavailable`, not a +`Blender 5.2.2 LTS ...` line) an `fbx` request is a 503 `blender-unavailable` and nothing is written. + +The worker never runs Blender. After it answers, the daemon runs the release's Blender +(`blender -b --factory-startup --python-use-system-env --python scripts/bvh-to-fbx.py`) on each BVH it listed, and +only on a regular file inside the job's artifact directory; the FBX path is the BVH's, so it is derived from the +job id. Blender converts and nothing else: the SOMA77 joint names are Kimodo's, the pose is the standard T-pose in +metres, and the clip's travel stays on `Hips` (Root is static), so Unity derives root motion or bakes it into the +pose as the caller chooses. Blender runs under the write gate in its own process group at nice 10, with +`HOME=/nonexistent`, `PYTHONHASHSEED=0` and `LD_LIBRARY_PATH=/lib` as its whole environment, a 120 s +timeout, and its output in `/logs/export.log`. It is killed with the worker on lease loss and stopped on +SIGTERM. A failed export fails the job (`fbx-export-refused` or `fbx-export-failed (...)`, 502) and the answer never +carries Blender's output. + +One BVH gives the same FBX bytes on one host body (a fixed hash seed and a fixed time stamp); FBX bytes differ +between glibc versions in the last float digits, so the BVH is the cross-body reproducibility unit. + +`POST /motion/rest-fbx` exports Kimodo's own standard-T-pose rest skeleton as `SOMA77_Rest.fbx` in a `rest-` job, +the source for the avatar. `GET /motion/artifacts/{jobId}/{name}` serves `motion.fbx`, `motion.bvh`, +`SOMA77_Rest.fbx` and `motion/motion_NN.fbx|bvh` of a job as bytes, read-only; anything else is a 404. + +A job is a `gamecult.vili.motion_job.v1` record in `/jobs/{jobId}.json` and the generate answer: the request, +the `seed` used, `files` (`name`, `bytes`, `sha256` for every file in the artifact directory), the worker's answer, +and for an export `export` (`blender` version line, `script` sha256, `settings`, and per clip `file`, `clipName`, +`bones`, `frames`, `fps`). + ## Current Runtime State Kimodo's 8B text encoder (LLM2Vec, Llama 3) never lives in the worker. The From f38f420df1fe9f3a6ca28c56c8bc393a56cb08fe Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 24 Oct 2026 20:33:13 +0200 Subject: [PATCH 05/36] The version probe writes nothing to the state root; existing tests learn the new backend and routes Co-Authored-By: Claude Opus 5.5 --- scripts/test-vili-daemon.mjs | 9 +++++---- scripts/vili-daemon.mjs | 22 +++++++++++++--------- 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/scripts/test-vili-daemon.mjs b/scripts/test-vili-daemon.mjs index 23e7a34..063a806 100644 --- a/scripts/test-vili-daemon.mjs +++ b/scripts/test-vili-daemon.mjs @@ -230,7 +230,7 @@ test("every flag has an environment twin, and the thread cap defaults to 8", asy assert.equal(answer.body.worker.env.OMP_NUM_THREADS, "16"); assert.deepEqual(await backendOf(viaEnv), { state: "ready", pid: answer.body.worker.pid, port: (await backendOf(viaEnv)).port, threads: 16, pythonEnv: "test-env", - kimodoCommit: "abc1234", modelsRoot: viaEnv.modelsRoot, lastError: null, + kimodoCommit: "abc1234", modelsRoot: viaEnv.modelsRoot, lastError: null, blender: "Blender 0.0.0 (stub)", }); } finally { await viaEnv.stop(); @@ -701,7 +701,7 @@ test("health, operator state and the unknown", async () => { assert.equal(unknown.raw, "not found\n"); const state = await operatorState(daemon); assert.equal(state.host, os.hostname()); - assert.deepEqual(Object.keys(state.routes), ["health", "operatorState", "generate"]); + assert.deepEqual(Object.keys(state.routes), ["health", "operatorState", "generate", "artifacts", "restFbx"]); } finally { await daemon.stop(); } @@ -1463,7 +1463,7 @@ test("a failing or hung Blender fails the job, leaks nothing, and leaves nothing assert.equal(silent.body.error, "fbx-export-failed (no result)"); const before = daemon.starts().length; - const hung = await generate(daemon, exportRequest({ clipName: "hang", exportTimeoutMs: 700 })); + const hung = await generate(daemon, exportRequest({ clipName: "hang", exportTimeoutMs: 2500 })); assert.equal(hung.status, 502); assert.equal(hung.body.error, "fbx-export-failed (signal SIGKILL)"); const [run] = daemon.starts().slice(before); @@ -1497,7 +1497,8 @@ test("losing the lease kills a running export within a second and records nothin const daemon = await idunnDaemon({ leased: true }); try { await until(() => existsSync(path.join(daemon.stateRoot, "vili.service.cc")), "the service store", 10); - assert.equal(daemon.starts().length, 1, "the version probe ran once the lease was held"); + await until(() => daemon.starts().length === 1, "the version probe, run once the lease was held"); + assert.equal(existsSync(path.join(daemon.stateRoot, "logs")), false, "the probe writes nothing to the state root"); const pending = generate(daemon, exportRequest({ clipName: "slow" })); const run = await until(() => exportStarts(daemon)[0], "the export to start"); rmSync(daemon.lease); diff --git a/scripts/vili-daemon.mjs b/scripts/vili-daemon.mjs index 3e7042e..d5b4f01 100644 --- a/scripts/vili-daemon.mjs +++ b/scripts/vili-daemon.mjs @@ -501,13 +501,17 @@ let exportScriptDigest = null; const scriptDigest = () => (exportScriptDigest ??= `sha256:${createHash("sha256").update(readFileSync(exportScript)).digest("hex")}`); // Runs the sealed Blender in its own process group, niced, under the write gate. Both streams go to -// logs/export.log line by line through mayWrite(), and only there. Resolves { code, signal, first, result }: the -// exit, the first stdout line and the last `VILI-FBX ` line's payload. It rejects only with LeaseLost. -async function runBlender(argv, timeoutMs) { +// logs/export.log line by line through mayWrite(), and only there; the version probe is not logged, so it writes +// nothing to the state root. Resolves { code, signal, first, result }: the exit, the first stdout line and the last +// `VILI-FBX ` line's payload. It rejects only with LeaseLost. +async function runBlender(argv, timeoutMs, logged = true) { guard(); - await mkdir(path.join(args.stateRoot, "logs"), { recursive: true }); - guard(); // synchronous with the log open and the spawn below: no await between them - const sink = openSync(path.join(args.stateRoot, "logs", "export.log"), "a"); + let sink = null; + if (logged) { + await mkdir(path.join(args.stateRoot, "logs"), { recursive: true }); + guard(); // synchronous with the log open and the spawn below: no await between them + sink = openSync(path.join(args.stateRoot, "logs", "export.log"), "a"); + } const proc = spawn(args.blender, argv, { cwd: __dirname, env: exportEnv(), @@ -517,7 +521,7 @@ async function runBlender(argv, timeoutMs) { }); exportGroups.add(proc); const seen = { first: null, result: null }; - let sinkOpen = true; + let sinkOpen = sink !== null; for (const [stream, isStdout] of [[proc.stdout, true], [proc.stderr, false]]) { if (!stream) continue; readline.createInterface({ input: stream }).on("line", (line) => { @@ -547,15 +551,15 @@ async function runBlender(argv, timeoutMs) { const exit = await finished; clearTimeout(timer); exportGroups.delete(proc); + if (sink !== null) closeSync(sink); sinkOpen = false; - closeSync(sink); return { ...exit, ...seen }; } // Blender answers once at start: `blender --version`, 15 s. Ready only when it exits 0 and names itself. async function probeBlender() { if (!args.blender) return; - const run = await runBlender(["-b", "--factory-startup", "--version"], 15000); + const run = await runBlender(["-b", "--factory-startup", "--version"], 15000, false); guard(); blender.version = run.code === 0 && run.first?.startsWith("Blender ") ? run.first : null; } From bfbcd7a1ee469431971472f13e7d46bd5a8c6a93 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 24 Oct 2026 20:49:15 +0200 Subject: [PATCH 06/36] stub-blender: the hung export's grandchild logs its pid Co-Authored-By: Claude Opus 5.5 --- scripts/fixtures/stub-blender.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/fixtures/stub-blender.mjs b/scripts/fixtures/stub-blender.mjs index 2062ce9..0fb6ac8 100755 --- a/scripts/fixtures/stub-blender.mjs +++ b/scripts/fixtures/stub-blender.mjs @@ -28,7 +28,7 @@ console.error(`stub-blender-stderr ${clip}`); if (clip.startsWith("fail")) process.exit(1); if (clip.startsWith("silent")) process.exit(0); if (clip.startsWith("hang")) { - spawn(process.execPath, ["-e", `require('fs').appendFileSync(${JSON.stringify(log)}, 'grandchild ' + process.pid + '\n'); setInterval(() => {}, 1000)`], { stdio: "ignore" }); + spawn(process.execPath, ["-e", `require('fs').appendFileSync(${JSON.stringify(log)}, 'grandchild ' + process.pid + '\\n'); setInterval(() => {}, 1000)`], { stdio: "ignore" }); process.on("SIGTERM", () => {}); setInterval(() => {}, 1000); } else { From c6c79bfdefd1585dbc5d9f892264dfb8a10b1199 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 24 Oct 2026 20:49:37 +0200 Subject: [PATCH 07/36] test_bvh_to_fbx: report the frame range and Hips travel by frame when travel is off Co-Authored-By: Claude Opus 5.5 --- scripts/test_bvh_to_fbx.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/scripts/test_bvh_to_fbx.py b/scripts/test_bvh_to_fbx.py index fb46aeb..195bc5a 100644 --- a/scripts/test_bvh_to_fbx.py +++ b/scripts/test_bvh_to_fbx.py @@ -35,6 +35,8 @@ if action is not None: def world(name, frame): scene.frame_set(frame) return (arm.matrix_world @ arm.pose.bones[name].matrix).translation.copy() + out["frame_range"] = [first, last] + out["hips_by_frame"] = {f: round((world("Hips", f) - world("Hips", first)).length, 4) for f in (first, first + 1, last - 1, last, last + 1)} out["hips_travel"] = (world("Hips", last) - world("Hips", first)).length out["root_wander"] = max((world("Root", f) - world("Root", first)).length for f in range(first, last + 1)) print("INSPECT " + json.dumps(out)) @@ -133,7 +135,7 @@ class BvhToFbx(unittest.TestCase): run = convert(bvh, fbx, "walk") self.assertEqual(run.returncode, 0, run.stderr[-2000:]) seen = self.inspect(fbx) - self.assertAlmostEqual(seen["hips_travel"], 1.0, delta=0.001) + self.assertAlmostEqual(seen["hips_travel"], 1.0, delta=0.001, msg=json.dumps(seen)) self.assertLess(seen["root_wander"], 1e-4) From 13ca0df73159d5848486061a6d72c192c9442c5a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 24 Oct 2026 20:51:16 +0200 Subject: [PATCH 08/36] test_bvh_to_fbx: read Hips travel past the importer's late take end Co-Authored-By: Claude Opus 5.5 --- scripts/test_bvh_to_fbx.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/scripts/test_bvh_to_fbx.py b/scripts/test_bvh_to_fbx.py index 195bc5a..a297d46 100644 --- a/scripts/test_bvh_to_fbx.py +++ b/scripts/test_bvh_to_fbx.py @@ -35,10 +35,10 @@ if action is not None: def world(name, frame): scene.frame_set(frame) return (arm.matrix_world @ arm.pose.bones[name].matrix).translation.copy() - out["frame_range"] = [first, last] - out["hips_by_frame"] = {f: round((world("Hips", f) - world("Hips", first)).length, 4) for f in (first, first + 1, last - 1, last, last + 1)} - out["hips_travel"] = (world("Hips", last) - world("Hips", first)).length - out["root_wander"] = max((world("Root", f) - world("Root", first)).length for f in range(first, last + 1)) + # The importer starts the take a frame late, so its range ends before the last key: read two frames past it. + frames = range(first, last + 3) + out["hips_travel"] = max((world("Hips", f) - world("Hips", first)).length for f in frames) + out["root_wander"] = max((world("Root", f) - world("Root", first)).length for f in frames) print("INSPECT " + json.dumps(out)) ''' From d4375d458f8b3db8c0e5c08eee200e2611298981 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 24 Oct 2026 20:54:48 +0200 Subject: [PATCH 09/36] Tests: say why a job ended before its export; minted seeds differ Co-Authored-By: Claude Opus 5.5 --- scripts/test-vili-daemon.mjs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/scripts/test-vili-daemon.mjs b/scripts/test-vili-daemon.mjs index 063a806..32e73fe 100644 --- a/scripts/test-vili-daemon.mjs +++ b/scripts/test-vili-daemon.mjs @@ -1500,7 +1500,9 @@ test("losing the lease kills a running export within a second and records nothin await until(() => daemon.starts().length === 1, "the version probe, run once the lease was held"); assert.equal(existsSync(path.join(daemon.stateRoot, "logs")), false, "the probe writes nothing to the state root"); const pending = generate(daemon, exportRequest({ clipName: "slow" })); - const run = await until(() => exportStarts(daemon)[0], "the export to start"); + const ended = pending.then((answer) => { throw new Error(`the job ended before its export started: ${answer.status} ${answer.raw.slice(0, 300)}`); }); + ended.catch(() => {}); + const run = await Promise.race([until(() => exportStarts(daemon)[0], "the export to start"), ended]); rmSync(daemon.lease); const lost = Date.now(); await until(() => !isAlive(run.pid), "the export to be dead", 2); @@ -1529,6 +1531,9 @@ test("the seed is minted when absent and recorded for every job", async () => { assert.equal(given.worker.seed, 7); assert.equal(given.worker.metaSeed, 7); assert.equal(JSON.parse(readFileSync(path.join(given.artifactDir, "meta.json"), "utf8")).seed, 7); + const minted = new Set(); + for (let count = 0; count < 3; count += 1) minted.add((await generate(daemon, exportRequest())).body.seed); + assert.ok(minted.size > 1, "minted seeds differ from job to job"); const zero = (await generate(daemon, exportRequest({ seed: 0 }))).body; assert.equal(zero.seed, 0, "0 is a seed"); } finally { From c109f436b86b407628120d12cec0cb61061f1edb Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 24 Oct 2026 21:00:22 +0200 Subject: [PATCH 10/36] Tests: malformed result, missing FBX, a grandchild left behind, clip order independent of the worker's listing Co-Authored-By: Claude Opus 5.5 --- scripts/fixtures/stub-blender.mjs | 41 ++++++++++++++++++++++--------- scripts/fixtures/stub-worker.mjs | 1 + scripts/test-vili-daemon.mjs | 13 ++++++++-- 3 files changed, 42 insertions(+), 13 deletions(-) diff --git a/scripts/fixtures/stub-blender.mjs b/scripts/fixtures/stub-blender.mjs index 0fb6ac8..53e33ab 100755 --- a/scripts/fixtures/stub-blender.mjs +++ b/scripts/fixtures/stub-blender.mjs @@ -1,11 +1,14 @@ #!/usr/bin/env node -// Stands in for Blender in the daemon's tests. Every start appends a JSON line {pid, pgid, priority, argv, env} to starts.log beside -// this file (the test gives each daemon its own copy, so the log is per test). `--version` answers like Blender, -// unless the copy is named blender-broken. An export (`... -- `) acts on the clip name: -// fail* prints a line to stderr, exits 1 silent* exits 0 with no result line -// hang* a grandchild, then never exits slow* runs 6 s, then behaves -// other writes "FBX-STUB:" + the BVH's bytes to and prints the VILI-FBX result line -import { appendFileSync, readFileSync, writeFileSync } from "node:fs"; +// Stands in for Blender in the daemon's tests. Every start appends a JSON line {pid, pgid, priority, argv, env} to +// starts.log beside this file (the test gives each daemon its own copy, so the log is per test). `--version` answers +// like Blender, unless the copy is named blender-broken, which names itself and exits 1. An export +// (`... -- `) acts on the clip name: +// fail* prints a line to stderr, exits 1 silent* exits 0 with no result line +// garbage* exits 0 with a malformed result line nofile* exits 0 with a result line and no FBX +// hang* a grandchild, then never exits slow* runs 6 s, then behaves +// orphan* behaves, but leaves a grandchild running when it exits +// other writes "FBX-STUB:" + the BVH's bytes to and prints the VILI-FBX result line +import { appendFileSync, existsSync, readFileSync, writeFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; import { spawn } from "node:child_process"; @@ -17,22 +20,38 @@ const pgid = Number(readFileSync("/proc/self/stat", "utf8").split(") ")[1].split appendFileSync(log, `${JSON.stringify({ pid: process.pid, pgid, priority: os.getPriority(), argv, env: process.env })}\n`); if (argv.includes("--version")) { - if (path.basename(process.argv[1]).includes("broken")) process.exit(1); console.log("Blender 0.0.0 (stub)"); console.log("\tbuild date: never"); - process.exit(0); + process.exit(path.basename(process.argv[1]).includes("broken") ? 1 : 0); } +const result = `VILI-FBX ${JSON.stringify({ bones: 78, frames: [1, 60], fps: 30 })}`; +const grandchildren = () => (existsSync(log) ? readFileSync(log, "utf8").split("\n").filter((line) => line.startsWith("grandchild ")).length : 0); +const spawnGrandchild = () => spawn(process.execPath, ["-e", `require('fs').appendFileSync(${JSON.stringify(log)}, 'grandchild ' + process.pid + '\\n'); setInterval(() => {}, 1000)`], { stdio: "ignore" }); + const [bvh, fbx, clip] = argv.slice(argv.indexOf("--") + 1); console.error(`stub-blender-stderr ${clip}`); if (clip.startsWith("fail")) process.exit(1); if (clip.startsWith("silent")) process.exit(0); +if (clip.startsWith("garbage")) { + console.log('VILI-FBX {"bones":"many","frames":[1],"fps":30}'); + process.exit(0); +} +if (clip.startsWith("nofile")) { + console.log(result); + process.exit(0); +} if (clip.startsWith("hang")) { - spawn(process.execPath, ["-e", `require('fs').appendFileSync(${JSON.stringify(log)}, 'grandchild ' + process.pid + '\\n'); setInterval(() => {}, 1000)`], { stdio: "ignore" }); + spawnGrandchild(); process.on("SIGTERM", () => {}); setInterval(() => {}, 1000); } else { if (clip.startsWith("slow")) await new Promise((resolve) => setTimeout(resolve, 6000)); + if (clip.startsWith("orphan")) { + const before = grandchildren(); + spawnGrandchild(); + for (let waited = 0; grandchildren() === before && waited < 3000; waited += 25) await new Promise((resolve) => setTimeout(resolve, 25)); + } writeFileSync(fbx, Buffer.concat([Buffer.from("FBX-STUB:"), readFileSync(bvh)])); - console.log(`VILI-FBX ${JSON.stringify({ bones: 78, frames: [1, 60], fps: 30 })}`); + console.log(result); } diff --git a/scripts/fixtures/stub-worker.mjs b/scripts/fixtures/stub-worker.mjs index 265662d..680b6b4 100644 --- a/scripts/fixtures/stub-worker.mjs +++ b/scripts/fixtures/stub-worker.mjs @@ -95,6 +95,7 @@ if (model === "hang-before-ready") { mkdirSync(payload.output, { recursive: true }); files = Array.from({ length: payload.numSamples }, (_, index) => path.join(payload.output, `motion_${String(index).padStart(2, "0")}.bvh`)); for (const [index, file] of files.entries()) writeFileSync(file, `BVH-STUB sample ${index}\n`); + files.reverse(); // the worker's listing order is not the daemon's clip order } else { writeFileSync(`${payload.output}.npz`, "NPZ-STUB\n"); writeFileSync(`${payload.output}.bvh`, "BVH-STUB\n"); diff --git a/scripts/test-vili-daemon.mjs b/scripts/test-vili-daemon.mjs index 32e73fe..93f95ac 100644 --- a/scripts/test-vili-daemon.mjs +++ b/scripts/test-vili-daemon.mjs @@ -1459,8 +1459,17 @@ test("a failing or hung Blender fails the job, leaks nothing, and leaves nothing assert.match(readFileSync(path.join(daemon.stateRoot, "logs", "export.log"), "utf8"), /stub-blender-stderr fail_canary/); assert.ok(existsSync(path.join(daemon.stateRoot, "jobs", `${failed.body.jobId}.json`))); - const silent = await generate(daemon, exportRequest({ clipName: "silent" })); - assert.equal(silent.body.error, "fbx-export-failed (no result)"); + for (const clip of ["silent", "garbage", "nofile"]) { + const odd = await generate(daemon, exportRequest({ clipName: clip })); + assert.equal(odd.status, 502, clip); + assert.equal(odd.body.error, "fbx-export-failed (no result)", clip); + } + + const known = new Set(daemon.blenderGrandchildren()); + const orphaned = await generate(daemon, exportRequest({ clipName: "orphan" })); + assert.equal(orphaned.status, 200, "an export that exits 0 is a good export"); + const left = await until(() => daemon.blenderGrandchildren().filter((pid) => !known.has(pid))[0], "the orphan's grandchild"); + await until(() => !isAlive(left), "what Blender left running to be killed with its group"); const before = daemon.starts().length; const hung = await generate(daemon, exportRequest({ clipName: "hang", exportTimeoutMs: 2500 })); From ae7c8a1e52062d128501d12b664a402708de7f97 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 24 Oct 2026 21:06:40 +0200 Subject: [PATCH 11/36] stub-blender: the orphan's grandchild does not keep the stub alive Co-Authored-By: Claude Opus 5.5 --- scripts/fixtures/stub-blender.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/fixtures/stub-blender.mjs b/scripts/fixtures/stub-blender.mjs index 53e33ab..a951240 100755 --- a/scripts/fixtures/stub-blender.mjs +++ b/scripts/fixtures/stub-blender.mjs @@ -49,7 +49,7 @@ if (clip.startsWith("hang")) { if (clip.startsWith("slow")) await new Promise((resolve) => setTimeout(resolve, 6000)); if (clip.startsWith("orphan")) { const before = grandchildren(); - spawnGrandchild(); + spawnGrandchild().unref(); // a live child would keep this process, and so the export, alive for (let waited = 0; grandchildren() === before && waited < 3000; waited += 25) await new Promise((resolve) => setTimeout(resolve, 25)); } writeFileSync(fbx, Buffer.concat([Buffer.from("FBX-STUB:"), readFileSync(bvh)])); From 2688e69fbe121f2080397a23521df8c5046d7bee Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 24 Oct 2026 21:07:27 +0200 Subject: [PATCH 12/36] test_bvh_to_fbx: pin the result line, the frame range and the take name Co-Authored-By: Claude Opus 5.5 --- scripts/test_bvh_to_fbx.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/scripts/test_bvh_to_fbx.py b/scripts/test_bvh_to_fbx.py index a297d46..beb775b 100644 --- a/scripts/test_bvh_to_fbx.py +++ b/scripts/test_bvh_to_fbx.py @@ -28,9 +28,11 @@ out = { "bones": [b.name for b in arm.data.bones], "scale": list(arm.scale), "hips_rest": arm.data.bones["Hips"].head_local.z * arm.scale.z, + "scene": scene.name, } action = arm.animation_data.action if arm.animation_data else None if action is not None: + out["action"] = action.name first, last = (int(f) for f in action.frame_range) def world(name, frame): scene.frame_set(frame) @@ -67,6 +69,11 @@ def convert(bvh, fbx, clip, env=None): return blender("--python", str(SCRIPT), "--", str(bvh), str(fbx), clip, env=env) +def result(run): + line = next(line for line in run.stdout.splitlines() if line.startswith("VILI-FBX ")) + return json.loads(line[len("VILI-FBX "):]) + + def rest_bvh(): spec = importlib.util.find_spec("kimodo") return pathlib.Path(spec.submodule_search_locations[0]) / "assets" / "skeletons" / "somaskel77" / "somaskel77_standard_tpose.bvh" @@ -95,8 +102,7 @@ class BvhToFbx(unittest.TestCase): fbx = self.dir / "rest.fbx" run = convert(self.rest, fbx, "SOMA77_Rest") self.assertEqual(run.returncode, 0, run.stderr[-2000:]) - result = json.loads(next(l for l in run.stdout.splitlines() if l.startswith("VILI-FBX "))[len("VILI-FBX "):]) - self.assertEqual(result["bones"], 78) + self.assertEqual(result(run), {"bones": 78, "frames": [1, 1], "fps": 30}) joints = re.findall(r"^\s*(?:ROOT|JOINT)\s+(\S+)", self.rest.read_text(), re.M) seen = self.inspect(fbx) self.assertEqual(len(joints), 78) @@ -134,7 +140,9 @@ class BvhToFbx(unittest.TestCase): fbx = self.dir / "walk.fbx" run = convert(bvh, fbx, "walk") self.assertEqual(run.returncode, 0, run.stderr[-2000:]) + self.assertEqual(result(run), {"bones": 78, "frames": [1, frames], "fps": 30}) seen = self.inspect(fbx) + self.assertIn("walk", seen["action"], "the clip name reaches the FBX take") self.assertAlmostEqual(seen["hips_travel"], 1.0, delta=0.001, msg=json.dumps(seen)) self.assertLess(seen["root_wander"], 1e-4) From f7fba1c115f91b6f518b97ea7d22a6d7e88db615 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 24 Oct 2026 21:07:57 +0200 Subject: [PATCH 13/36] bvh-to-fbx.py: the header names no in-place bake, matching the negative grep Co-Authored-By: Claude Opus 5.5 --- scripts/bvh-to-fbx.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/bvh-to-fbx.py b/scripts/bvh-to-fbx.py index 313add1..c15b5a5 100644 --- a/scripts/bvh-to-fbx.py +++ b/scripts/bvh-to-fbx.py @@ -1,5 +1,5 @@ # Converts one Kimodo standard-T-pose BVH to one FBX. Blender converts formats and nothing else: no retarget, no -# rename, no key reduction, no resample, no in-place bake. Run by the daemon (scripts/vili-daemon.mjs exportClip): +# rename, no key reduction, no resample, no root-motion bake. Run by the daemon (scripts/vili-daemon.mjs exportClip): # blender -b --factory-startup --python-use-system-env --python-exit-code 1 --python bvh-to-fbx.py -- # with PYTHONHASHSEED=0 in the environment. The settings are Blender API parameters, cross-checked against the # 'unity' preset of wifimetas/kimodo-mcp blender_export.py (Apache-2.0, 83b5361); no code is copied. From 8479465cd17027afd01cef929fe41d6eb0bb8b5c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 24 Oct 2026 21:08:28 +0200 Subject: [PATCH 14/36] Recipe: the Blender input has its own id; idunn validate refuses an input id that collides with an artifact id Co-Authored-By: Claude Opus 5.5 --- deployment/idunn/recipe.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deployment/idunn/recipe.toml b/deployment/idunn/recipe.toml index c4ffef2..c5df686 100644 --- a/deployment/idunn/recipe.toml +++ b/deployment/idunn/recipe.toml @@ -15,7 +15,7 @@ destination = "release/cpython.tar.gz" # Blender 5.2.2 LTS, unpacked beside the interpreter. The tree is sealed whole; the daemon runs it with # LD_LIBRARY_PATH=blender/lib (scripts/vili-daemon.mjs exportEnv). [[external_inputs]] -id = "blender" +id = "blender-linux-x64" url = "https://download.blender.org/release/Blender5.2/blender-5.2.2-linux-x64.tar.xz" sha256 = "84098912789dc450e95697c4184fb8a90acbe5111c2ba4aede3fecb57806a168" runner = "python-build" From f99d95b4c604127363f5fa766103a5214496f1ee Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 24 Oct 2026 21:08:45 +0200 Subject: [PATCH 15/36] Test: the hung export's grandchild is the one that is new since the orphan's Co-Authored-By: Claude Opus 5.5 --- scripts/test-vili-daemon.mjs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/scripts/test-vili-daemon.mjs b/scripts/test-vili-daemon.mjs index 93f95ac..c63aa06 100644 --- a/scripts/test-vili-daemon.mjs +++ b/scripts/test-vili-daemon.mjs @@ -1472,12 +1472,13 @@ test("a failing or hung Blender fails the job, leaks nothing, and leaves nothing await until(() => !isAlive(left), "what Blender left running to be killed with its group"); const before = daemon.starts().length; + known.add(left); const hung = await generate(daemon, exportRequest({ clipName: "hang", exportTimeoutMs: 2500 })); assert.equal(hung.status, 502); assert.equal(hung.body.error, "fbx-export-failed (signal SIGKILL)"); const [run] = daemon.starts().slice(before); - await until(() => daemon.blenderGrandchildren().length === 1, "the hung Blender's grandchild"); - await until(() => !isAlive(run.pid) && !isAlive(daemon.blenderGrandchildren()[0]), "the hung export's group to be dead"); + const stuck = await until(() => daemon.blenderGrandchildren().filter((pid) => !known.has(pid))[0], "the hung Blender's grandchild"); + await until(() => !isAlive(run.pid) && !isAlive(stuck), "the hung export's group to be dead"); assert.equal(hung.body.files.some((file) => file.name.endsWith(".fbx")), false); } finally { await daemon.stop(); From 62c0217d1faaa83608589c4692154f72e3620b07 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 24 Oct 2026 21:13:39 +0200 Subject: [PATCH 16/36] test_bvh_to_fbx: a clip's timing, pose against Blender's native reading, the unit factor and every key Co-Authored-By: Claude Opus 5.5 --- scripts/test_bvh_to_fbx.py | 57 ++++++++++++++++++++++++++++++-------- 1 file changed, 45 insertions(+), 12 deletions(-) diff --git a/scripts/test_bvh_to_fbx.py b/scripts/test_bvh_to_fbx.py index beb775b..6f51063 100644 --- a/scripts/test_bvh_to_fbx.py +++ b/scripts/test_bvh_to_fbx.py @@ -9,6 +9,7 @@ import json import os import pathlib import re +import struct import subprocess import tempfile import unittest @@ -16,31 +17,45 @@ import unittest BLENDER = os.environ["VILI_BLENDER"] SCRIPT = pathlib.Path(__file__).resolve().with_name("bvh-to-fbx.py") -# Reads an FBX back into a factory scene and reports what the avatar cut will see. +# Reads an FBX back into a factory scene and reports what the avatar cut will see. With a BVH as its second +# argument it also imports that BVH the way Blender itself does (native Euler order), as the reference pose. INSPECT = r''' import bpy, json, sys -fbx = sys.argv[sys.argv.index("--") + 1] +argv = sys.argv[sys.argv.index("--") + 1:] +fbx = argv[0] bpy.ops.wm.read_factory_settings(use_empty=True) bpy.ops.import_scene.fbx(filepath=fbx) scene = bpy.context.scene arm = next(o for o in scene.objects if o.type == "ARMATURE") + +def world(name, frame): + scene.frame_set(frame) + return (arm.matrix_world @ arm.pose.bones[name].matrix).translation.copy() + out = { "bones": [b.name for b in arm.data.bones], "scale": list(arm.scale), "hips_rest": arm.data.bones["Hips"].head_local.z * arm.scale.z, - "scene": scene.name, } action = arm.animation_data.action if arm.animation_data else None if action is not None: out["action"] = action.name first, last = (int(f) for f in action.frame_range) - def world(name, frame): - scene.frame_set(frame) - return (arm.matrix_world @ arm.pose.bones[name].matrix).translation.copy() - # The importer starts the take a frame late, so its range ends before the last key: read two frames past it. + out["frame_range"] = [first, last] + # The importer starts the take a frame late: sample i is at frame first + 1 + i, and the range ends before the + # last key. Read two frames past it. frames = range(first, last + 3) out["hips_travel"] = max((world("Hips", f) - world("Hips", first)).length for f in frames) + out["hips_mid"] = (world("Hips", first + 1 + 15) - world("Hips", first)).length out["root_wander"] = max((world("Root", f) - world("Root", first)).length for f in frames) + out["head_from_hips"] = list(world("Head", first + 1 + 15) - world("Hips", first + 1 + 15)) + if len(argv) > 1: + bpy.ops.wm.read_factory_settings(use_empty=True) + bpy.ops.import_anim.bvh(filepath=argv[1], global_scale=0.01, axis_forward="-Z", axis_up="Y", rotate_mode="NATIVE", + use_fps_scale=False, update_scene_fps=True, frame_start=1) + scene = bpy.context.scene + arm = bpy.context.view_layer.objects.active + out["reference_head_from_hips"] = list(world("Head", 1 + 15) - world("Hips", 1 + 15)) print("INSPECT " + json.dumps(out)) ''' @@ -74,6 +89,17 @@ def result(run): return json.loads(line[len("VILI-FBX "):]) +def unit_scale_factor(fbx): + """GlobalSettings' UnitScaleFactor from a binary FBX: the property is four strings, then a double.""" + raw = pathlib.Path(fbx).read_bytes() + position = raw.index(b"UnitScaleFactor") + len(b"UnitScaleFactor") + for _ in range(3): # type "double", label "Number", flags "" + assert raw[position:position + 1] == b"S" + position += 5 + struct.unpack(" Date: Sat, 24 Oct 2026 21:17:07 +0200 Subject: [PATCH 17/36] Export: the redundant guard after Blender is gone; tests for a lying exit code, a malformed result with an FBX, output after SIGTERM, and a hung request Co-Authored-By: Claude Opus 5.5 --- scripts/fixtures/stub-blender.mjs | 16 ++++++++++++---- scripts/test-vili-daemon.mjs | 26 +++++++++++++++++++++++++- scripts/vili-daemon.mjs | 1 - 3 files changed, 37 insertions(+), 6 deletions(-) diff --git a/scripts/fixtures/stub-blender.mjs b/scripts/fixtures/stub-blender.mjs index a951240..a330321 100755 --- a/scripts/fixtures/stub-blender.mjs +++ b/scripts/fixtures/stub-blender.mjs @@ -4,8 +4,9 @@ // like Blender, unless the copy is named blender-broken, which names itself and exits 1. An export // (`... -- `) acts on the clip name: // fail* prints a line to stderr, exits 1 silent* exits 0 with no result line -// garbage* exits 0 with a malformed result line nofile* exits 0 with a result line and no FBX -// hang* a grandchild, then never exits slow* runs 6 s, then behaves +// garbage* an FBX, then a malformed result line nofile* exits 0 with a result line and no FBX +// lies* an FBX and a result line, exits 3 slow* runs 6 s, then behaves +// hang* a grandchild, then never exits; after SIGTERM it prints a line every 100 ms // orphan* behaves, but leaves a grandchild running when it exits // other writes "FBX-STUB:" + the BVH's bytes to and prints the VILI-FBX result line import { appendFileSync, existsSync, readFileSync, writeFileSync } from "node:fs"; @@ -33,17 +34,24 @@ const [bvh, fbx, clip] = argv.slice(argv.indexOf("--") + 1); console.error(`stub-blender-stderr ${clip}`); if (clip.startsWith("fail")) process.exit(1); if (clip.startsWith("silent")) process.exit(0); +const writeFbx = () => writeFileSync(fbx, Buffer.concat([Buffer.from("FBX-STUB:"), readFileSync(bvh)])); if (clip.startsWith("garbage")) { + writeFbx(); console.log('VILI-FBX {"bones":"many","frames":[1],"fps":30}'); process.exit(0); } +if (clip.startsWith("lies")) { + writeFbx(); + console.log(result); + process.exit(3); +} if (clip.startsWith("nofile")) { console.log(result); process.exit(0); } if (clip.startsWith("hang")) { spawnGrandchild(); - process.on("SIGTERM", () => {}); + process.on("SIGTERM", () => setInterval(() => console.error("after-sigterm-line"), 100)); setInterval(() => {}, 1000); } else { if (clip.startsWith("slow")) await new Promise((resolve) => setTimeout(resolve, 6000)); @@ -52,6 +60,6 @@ if (clip.startsWith("hang")) { spawnGrandchild().unref(); // a live child would keep this process, and so the export, alive for (let waited = 0; grandchildren() === before && waited < 3000; waited += 25) await new Promise((resolve) => setTimeout(resolve, 25)); } - writeFileSync(fbx, Buffer.concat([Buffer.from("FBX-STUB:"), readFileSync(bvh)])); + writeFbx(); console.log(result); } diff --git a/scripts/test-vili-daemon.mjs b/scripts/test-vili-daemon.mjs index c63aa06..f7c68f0 100644 --- a/scripts/test-vili-daemon.mjs +++ b/scripts/test-vili-daemon.mjs @@ -1464,6 +1464,9 @@ test("a failing or hung Blender fails the job, leaks nothing, and leaves nothing assert.equal(odd.status, 502, clip); assert.equal(odd.body.error, "fbx-export-failed (no result)", clip); } + const lied = await generate(daemon, exportRequest({ clipName: "lies" })); + assert.equal(lied.status, 502, "an export that exits non-zero is no export, whatever it printed"); + assert.equal(lied.body.error, "fbx-export-failed (exit 3)"); const known = new Set(daemon.blenderGrandchildren()); const orphaned = await generate(daemon, exportRequest({ clipName: "orphan" })); @@ -1473,7 +1476,10 @@ test("a failing or hung Blender fails the job, leaks nothing, and leaves nothing const before = daemon.starts().length; known.add(left); - const hung = await generate(daemon, exportRequest({ clipName: "hang", exportTimeoutMs: 2500 })); + const hung = await Promise.race([ + generate(daemon, exportRequest({ clipName: "hang", exportTimeoutMs: 2500 })), + new Promise((_, reject) => setTimeout(() => reject(new Error("the hung export was never stopped")), 20000)), + ]); assert.equal(hung.status, 502); assert.equal(hung.body.error, "fbx-export-failed (signal SIGKILL)"); const [run] = daemon.starts().slice(before); @@ -1503,6 +1509,24 @@ test("SIGTERM during an export stops its group, writes nothing more, and exits 0 } }); +test("what a stopping export still prints is not logged, and it is killed when it ignores SIGTERM", async () => { + const daemon = await startDaemon(); + try { + const pending = generate(daemon, exportRequest({ clipName: "hang", exportTimeoutMs: 60000 })); + pending.catch(() => {}); + const run = await until(() => exportStarts(daemon)[0], "the export to start"); + daemon.proc.kill("SIGTERM"); + await until(() => daemon.proc.exitCode !== null, "the daemon to exit", 30); + assert.equal(daemon.proc.exitCode, 0); + await until(() => !isAlive(run.pid), "the export that ignored SIGTERM to be killed"); + const log = readFileSync(path.join(daemon.stateRoot, "logs", "export.log"), "utf8"); + assert.match(log, /stub-blender-stderr hang/); + assert.ok(!log.includes("after-sigterm-line"), "a line printed after the signal reached the log"); + } finally { + await daemon.stop(); + } +}); + test("losing the lease kills a running export within a second and records nothing", async () => { const daemon = await idunnDaemon({ leased: true }); try { diff --git a/scripts/vili-daemon.mjs b/scripts/vili-daemon.mjs index d5b4f01..d8994df 100644 --- a/scripts/vili-daemon.mjs +++ b/scripts/vili-daemon.mjs @@ -571,7 +571,6 @@ async function exportClip(bvh, fbx, clipName, timeoutMs) { "-b", "--factory-startup", "--python-use-system-env", "--python-exit-code", "1", "--python", exportScript, "--", bvh, fbx, clipName, ], timeoutMs); - guard(); // the writer may have been lost while Blender ran let info = null; if (run.code === 0 && run.result !== null) { try { From f344cef3b9d0176c10bfac75da4a5ba13a2a6318 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 24 Oct 2026 21:20:52 +0200 Subject: [PATCH 18/36] Tests for unpack-debs.py: only libraries, flat, sibling links, no overwrite Co-Authored-By: Claude Opus 5.5 --- scripts/test_unpack_debs.py | 115 ++++++++++++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 scripts/test_unpack_debs.py diff --git a/scripts/test_unpack_debs.py b/scripts/test_unpack_debs.py new file mode 100644 index 0000000..f0cc945 --- /dev/null +++ b/scripts/test_unpack_debs.py @@ -0,0 +1,115 @@ +"""deployment/idunn/unpack-debs.py takes a Debian package's shared libraries and nothing else.""" +import importlib.util +import io +import pathlib +import tarfile +import tempfile +import unittest + +SOURCE = pathlib.Path(__file__).resolve().parents[1] / "deployment" / "idunn" / "unpack-debs.py" +spec = importlib.util.spec_from_file_location("unpack_debs", SOURCE) +unpack_debs = importlib.util.module_from_spec(spec) +spec.loader.exec_module(unpack_debs) + +LIB = "./usr/lib/x86_64-linux-gnu/" + + +def deb(path, members, compression="xz", marker=b"2.0\n"): + """A .deb: an ar archive of a debian-binary marker and a data tarball holding `members` (name, kind, payload).""" + data = io.BytesIO() + with tarfile.open(fileobj=data, mode=f"w:{compression}") as archive: + for name, kind, payload in members: + info = tarfile.TarInfo(name) + if kind == "file": + info.size = len(payload) + archive.addfile(info, io.BytesIO(payload)) + elif kind in ("symlink", "hardlink"): + info.type = tarfile.SYMTYPE if kind == "symlink" else tarfile.LNKTYPE + info.linkname = payload + archive.addfile(info) + else: + info.type = tarfile.DIRTYPE + archive.addfile(info) + body = data.getvalue() + + def member(name, content): + header = f"{name + '/':<16}{0:<12}{0:<6}{0:<6}{'100644':<8}{len(content):<10}`\n".encode("ascii") + return header + content + (b"\n" if len(content) % 2 else b"") + + path.write_bytes(b"!\n" + member("debian-binary", marker) + member(f"data.tar.{compression}", body)) + + +class UnpackDebs(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.dir = pathlib.Path(self.tmp.name) + self.out = self.dir / "lib" + self.out.mkdir() + + def tearDown(self): + self.tmp.cleanup() + + def test_takes_only_shared_libraries_flat_and_keeps_sibling_links(self): + package = self.dir / "a.deb" + deb(package, [ + (LIB, "dir", b""), + (LIB + "libfoo.so.1.2", "file", b"ELF"), + (LIB + "libfoo.so.1", "symlink", "libfoo.so.1.2"), + (LIB + "libfoo.a", "file", b"static"), + (LIB + "pkgconfig/foo.pc", "file", b"pc"), + ("./usr/share/doc/foo/copyright", "file", b"text"), + ("./etc/foo.so.conf", "file", b"conf"), + ]) + self.assertEqual(sorted(unpack_debs.unpack(package, self.out)), ["libfoo.so.1", "libfoo.so.1.2"]) + self.assertEqual(sorted(entry.name for entry in self.out.iterdir()), ["libfoo.so.1", "libfoo.so.1.2"]) + self.assertEqual((self.out / "libfoo.so.1.2").read_bytes(), b"ELF") + self.assertEqual((self.out / "libfoo.so.1").readlink().as_posix(), "libfoo.so.1.2") + self.assertEqual((self.out / "libfoo.so.1.2").stat().st_mode & 0o777, 0o644) + + def test_a_gzip_data_archive_is_read_too(self): + package = self.dir / "g.deb" + deb(package, [(LIB + "libbar.so.0", "file", b"ELF")], compression="gz") + self.assertEqual(unpack_debs.unpack(package, self.out), ["libbar.so.0"]) + + def test_refuses_to_overwrite(self): + (self.out / "libfoo.so.1").write_bytes(b"already here") + package = self.dir / "a.deb" + deb(package, [(LIB + "libfoo.so.1", "file", b"ELF")]) + with self.assertRaises(SystemExit): + unpack_debs.unpack(package, self.out) + self.assertEqual((self.out / "libfoo.so.1").read_bytes(), b"already here") + + def test_refuses_a_link_that_leaves_the_directory(self): + for target in ("/etc/passwd", "../../etc/passwd", "sub/libfoo.so.1", ".."): + package = self.dir / "l.deb" + deb(package, [(LIB + "libfoo.so.1", "symlink", target)]) + with self.assertRaises(SystemExit, msg=target): + unpack_debs.unpack(package, self.out) + self.assertEqual(list(self.out.iterdir()), [], target) + + def test_a_package_with_no_library_is_an_error(self): + package = self.dir / "n.deb" + deb(package, [("./usr/share/doc/foo/copyright", "file", b"text")]) + with self.assertRaises(SystemExit): + unpack_debs.unpack(package, self.out) + + def test_an_odd_sized_member_before_the_data_is_padded_over(self): + package = self.dir / "o.deb" + deb(package, [(LIB + "libodd.so.0", "file", b"ELF")], marker=b"2.0 x") + self.assertEqual(unpack_debs.unpack(package, self.out), ["libodd.so.0"]) + + def test_refuses_a_member_that_is_neither_a_file_nor_a_symlink(self): + package = self.dir / "h.deb" + deb(package, [(LIB + "libhard.so.0", "hardlink", "libother.so.0")]) + with self.assertRaises(SystemExit): + unpack_debs.unpack(package, self.out) + + def test_not_an_ar_archive_is_an_error(self): + package = self.dir / "x.deb" + package.write_bytes(b"PK\x03\x04 not a deb") + with self.assertRaises(SystemExit): + unpack_debs.unpack(package, self.out) + + +if __name__ == "__main__": + unittest.main() From 1328b5514ca51e3bf31fb2e57384a2408b5170ac Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 24 Oct 2026 21:22:48 +0200 Subject: [PATCH 19/36] Test: a planted directory that is not a job id's serves nothing Co-Authored-By: Claude Opus 5.5 --- scripts/test-vili-daemon.mjs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/scripts/test-vili-daemon.mjs b/scripts/test-vili-daemon.mjs index f7c68f0..60019ad 100644 --- a/scripts/test-vili-daemon.mjs +++ b/scripts/test-vili-daemon.mjs @@ -1586,6 +1586,9 @@ test("the artifact read route serves only a job's own FBX and BVH files", async assert.equal(served.raw, "FBX-STUB:BVH-STUB\n"); assert.equal((await getArtifact(daemon, `${base}/motion.bvh`)).raw, "BVH-STUB\n"); + // a directory that is not a job's own (its id is not vili-<13 digits>) serves nothing even with a file in it + mkdirSync(path.join(daemon.stateRoot, "artifacts", "vili-123"), { recursive: true }); + writeFileSync(path.join(daemon.stateRoot, "artifacts", "vili-123", "motion.fbx"), "PLANTED"); const refused = [ `${base}/meta.json`, `${base}/request.json`, From 3d80c7f0b5b2cf8cc9c40283c9964409d7e8415a Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 24 Oct 2026 21:25:51 +0200 Subject: [PATCH 20/36] Test: wait for the version probe's answer, not its start, before asking for an export Co-Authored-By: Claude Opus 5.5 --- scripts/test-vili-daemon.mjs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/test-vili-daemon.mjs b/scripts/test-vili-daemon.mjs index 60019ad..5e42edf 100644 --- a/scripts/test-vili-daemon.mjs +++ b/scripts/test-vili-daemon.mjs @@ -1531,7 +1531,8 @@ test("losing the lease kills a running export within a second and records nothin const daemon = await idunnDaemon({ leased: true }); try { await until(() => existsSync(path.join(daemon.stateRoot, "vili.service.cc")), "the service store", 10); - await until(() => daemon.starts().length === 1, "the version probe, run once the lease was held"); + await until(async () => (await backendOf(daemon)).blender === "Blender 0.0.0 (stub)", "the version probe, run once the lease was held"); + assert.equal(daemon.starts().length, 1); assert.equal(existsSync(path.join(daemon.stateRoot, "logs")), false, "the probe writes nothing to the state root"); const pending = generate(daemon, exportRequest({ clipName: "slow" })); const ended = pending.then((answer) => { throw new Error(`the job ended before its export started: ${answer.status} ${answer.raw.slice(0, 300)}`); }); From 385a7e5733ef27b07917487f568e67666afd2c32 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 24 Oct 2026 21:32:26 +0200 Subject: [PATCH 21/36] Test: the signal comes after the export's first line is logged Co-Authored-By: Claude Opus 5.5 --- scripts/test-vili-daemon.mjs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/scripts/test-vili-daemon.mjs b/scripts/test-vili-daemon.mjs index 5e42edf..14560a0 100644 --- a/scripts/test-vili-daemon.mjs +++ b/scripts/test-vili-daemon.mjs @@ -1515,6 +1515,8 @@ test("what a stopping export still prints is not logged, and it is killed when i const pending = generate(daemon, exportRequest({ clipName: "hang", exportTimeoutMs: 60000 })); pending.catch(() => {}); const run = await until(() => exportStarts(daemon)[0], "the export to start"); + const logFile = path.join(daemon.stateRoot, "logs", "export.log"); + await until(() => existsSync(logFile) && readFileSync(logFile, "utf8").includes("stub-blender-stderr hang"), "the export's first line to be logged"); daemon.proc.kill("SIGTERM"); await until(() => daemon.proc.exitCode !== null, "the daemon to exit", 30); assert.equal(daemon.proc.exitCode, 0); From a9413d4444cd2a7162cb72678cb6a39cf8a1133c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 24 Oct 2026 23:04:36 +0200 Subject: [PATCH 22/36] Test: Soul s1 findings as behavioural tests, red at the h1 head (job ids, seed, link swap) or pinning gates (lease, LD_LIBRARY_PATH, record links, header time, key loss) Co-Authored-By: Claude Opus 5.5 --- scripts/fixtures/stub-worker.mjs | 10 +- scripts/test-vili-daemon.mjs | 170 +++++++++++++++++++++++++++++-- scripts/test_bvh_to_fbx.py | 43 ++++++++ 3 files changed, 215 insertions(+), 8 deletions(-) diff --git a/scripts/fixtures/stub-worker.mjs b/scripts/fixtures/stub-worker.mjs index 680b6b4..6439144 100644 --- a/scripts/fixtures/stub-worker.mjs +++ b/scripts/fixtures/stub-worker.mjs @@ -1,7 +1,7 @@ // Stands in for kimodo-resident-worker.py in the daemon's tests. It binds port 0, prints the ready line the // daemon waits for, and answers /health and /generate with what the daemon gave it. The --model value picks a // misbehaviour: crash-before-ready, hang-before-ready, sick, slow-health, stubborn, fail-generate, -// refuse-generate, drop-generate, slow-generate, writer (appends to .writes every 50 ms, never answers, ignores SIGTERM), slow-to-stop (no answer; prints a line and exits 1.5 s after SIGTERM), chatty (prints a line the moment it is healthy), encoder (a grandchild, then no answer), graceful (exits 0.5 s after SIGTERM), die-after-ready, bvh-outside (lists a BVH outside the job's directory), bvh-link (lists a symlink as its BVH). A request with bvh writes .bvh (motion/motion_NN.bvh for several samples) and lists it. Any other value is just the model the worker serves. +// refuse-generate, drop-generate, slow-generate, writer (appends to .writes every 50 ms, never answers, ignores SIGTERM), slow-to-stop (no answer; prints a line and exits 1.5 s after SIGTERM), chatty (prints a line the moment it is healthy), encoder (a grandchild, then no answer), graceful (exits 0.5 s after SIGTERM), die-after-ready, bvh-outside (lists a BVH outside the job's directory), bvh-link (lists a symlink as its BVH), plant-link (a normal answer with a file symlink and a directory symlink planted beside the BVH). A request with bvh writes .bvh (motion/motion_NN.bvh for several samples) and lists it. Any other value is just the model the worker serves. import http from "node:http"; import os from "node:os"; import path from "node:path"; @@ -102,6 +102,13 @@ if (model === "hang-before-ready") { files = [`${payload.output}.npz`, `${payload.output}.bvh`]; } } + if (model === "plant-link") { + const outside = path.join(path.dirname(payload.output), "..", "outside.bvh"); + writeFileSync(outside, "BVH-OUTSIDE +"); + symlinkSync(outside, `${payload.output}.link`); + symlinkSync(path.dirname(outside), `${payload.output}-linkdir`); + } send(200, { ok: true, files, @@ -134,6 +141,7 @@ if (model === "hang-before-ready") { LANG: process.env.LANG, LEAK_CHECK: process.env.LEAK_CHECK, }, + envKeys: Object.keys(process.env).sort(), argv, }); } else { diff --git a/scripts/test-vili-daemon.mjs b/scripts/test-vili-daemon.mjs index 14560a0..31a8429 100644 --- a/scripts/test-vili-daemon.mjs +++ b/scripts/test-vili-daemon.mjs @@ -3,7 +3,7 @@ import assert from "node:assert/strict"; import { spawn } from "node:child_process"; import { createHash } from "node:crypto"; -import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs"; +import { chmodSync, copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs"; import http from "node:http"; import net from "node:net"; import os from "node:os"; @@ -818,13 +818,13 @@ for (let trial = 1; trial <= 10; trial += 1) { } }); } -const idunnDaemon = async ({ leased = false, extraEnv = {}, loseWhenExists = null } = {}) => { +const idunnDaemon = async ({ leased = false, extraEnv = {}, loseWhenExists = null, python = undefined } = {}) => { const root = mkdtempSync(path.join(os.tmpdir(), "vili-test-")); const lease = path.join(root, "lease"); const healthLog = path.join(root, "health.log"); if (leased) writeFileSync(lease, ""); const daemon = await startDaemon({ - root, nested: true, entry: fakeIdunnEntry, extraEnv: { + root, nested: true, entry: fakeIdunnEntry, ...(python ? { python } : {}), extraEnv: { FAKE_IDUNN_LEASE: lease, FAKE_IDUNN_HEALTH_LOG: healthLog, ...extraEnv, ...(loseWhenExists ? { FAKE_IDUNN_STATE_ROOT: path.join(root, "a", "b", "state"), FAKE_IDUNN_LOSE_WHEN_EXISTS: loseWhenExists } : {}), }, @@ -1174,6 +1174,8 @@ test("the entry derives the daemon's host, port, interpreter and environment ide assert.equal(derived.GAMECULT_IDUNN_CANDIDATE_BIND, "http://127.0.0.1:18861", "cultnet-ts compares the bind to the Expected route's endpoint, which carries the scheme Idunn's bare host:port lacks"); assert.equal(derived.VILI_PYTHON, path.join(release, "python", "bin", "python3.12")); assert.equal(derived.VILI_BLENDER, path.join(release, "blender", "blender")); + assert.deepEqual(Object.keys(derived).sort(), ["GAMECULT_IDUNN_CANDIDATE_BIND", "VILI_BLENDER", "VILI_DAEMON_HOST", "VILI_DAEMON_PORT", "VILI_PYTHON", "VILI_PYTHON_ENV"], + "the entry sets exactly these: no LD_LIBRARY_PATH for the whole unit"); assert.equal(derived.VILI_PYTHON_ENV, `locks-sha256:${createHash("sha256").update("build lock bytes\nruntime lock bytes\n").digest("hex")}`); } } finally { @@ -1630,14 +1632,20 @@ test("the artifact read route serves only a job's own FBX and BVH files", async } }); -test("rest-fbx is a job whose FBX is readable", async () => { - const pyRoot = mkdtempSync(path.join(os.tmpdir(), "vili-py-")); - const python = path.join(pyRoot, "bin", "python3.12"); +// A worker interpreter whose site-packages carry Kimodo's rest skeleton, as the release's does: the stub worker runs on node. +function restPython() { + const root = mkdtempSync(path.join(os.tmpdir(), "vili-py-")); + const python = path.join(root, "bin", "python3.12"); mkdirSync(path.dirname(python), { recursive: true }); symlinkSync(process.execPath, python); - const skeletons = path.join(pyRoot, "lib", "python3.12", "site-packages", "kimodo", "assets", "skeletons", "somaskel77"); + const skeletons = path.join(root, "lib", "python3.12", "site-packages", "kimodo", "assets", "skeletons", "somaskel77"); mkdirSync(skeletons, { recursive: true }); writeFileSync(path.join(skeletons, "somaskel77_standard_tpose.bvh"), "REST-BVH\n"); + return { root, python }; +} + +test("rest-fbx is a job whose FBX is readable", async () => { + const { root: pyRoot, python } = restPython(); const daemon = await startDaemon({ python }); try { const answer = await request(daemon.port, "POST", "/motion/rest-fbx", { body: "{}", headers: { "content-type": "application/json" } }); @@ -1698,3 +1706,151 @@ test("operator state and the command boundary name the export", async () => { await daemon.stop(); } }); + +// ---- Findings of Soul's pass s1 on the FBX export (motion-pipeline:verdict:cut-vili-fbx-export.s1). + +const readJson = (file) => JSON.parse(readFileSync(file, "utf8")); +const restRequest = (daemon) => request(daemon.port, "POST", "/motion/rest-fbx", { body: "{}", headers: { "content-type": "application/json" } }); + +test("concurrent generate and rest-fbx requests never share a job id, a directory, a record or a file", async () => { + const rest = restPython(); + const daemon = await startDaemon({ python: rest.python }); + try { + const answers = []; + for (let round = 0; round < 10; round += 1) { + answers.push(...await Promise.all([ + generate(daemon, exportRequest({ clipName: `a${round}` })), + generate(daemon, exportRequest({ clipName: `b${round}` })), + restRequest(daemon), + restRequest(daemon), + ])); + } + assert.equal(answers.length, 40); + for (const answer of answers) { + assert.equal(answer.status, 200, answer.raw.slice(0, 300)); + assert.equal(answer.body.ok, true); + } + const ids = answers.map((answer) => answer.body.jobId); + assert.equal(new Set(ids).size, 40, "every job has its own id"); + assert.equal(new Set(answers.map((answer) => answer.body.artifactDir)).size, 40, "and its own directory"); + assert.deepEqual(readdirSync(path.join(daemon.stateRoot, "artifacts")).sort(), [...ids].sort()); + assert.deepEqual(readdirSync(path.join(daemon.stateRoot, "jobs")).sort(), ids.map((id) => `${id}.json`).sort(), "and its own record"); + for (const { body } of answers) { + assert.deepEqual(readJson(path.join(daemon.stateRoot, "jobs", `${body.jobId}.json`)), body, "the record is the job's own answer"); + assert.equal(body.export.clips.length, 1); + } + const names = answers.filter((answer) => answer.body.jobId.startsWith("vili-")).map((answer) => answer.body.export.clips[0].clipName).sort(); + assert.deepEqual(names, Array.from({ length: 10 }, (_, round) => [`a${round}`, `b${round}`]).flat().sort(), "each generate job exported its own clip"); + const first = answers[0].body.jobId; + assert.equal((await getArtifact(daemon, `/motion/artifacts/${first}/motion.fbx`)).status, 200, "the read route serves the minted ids"); + } finally { + await daemon.stop(); + rmSync(rest.root, { recursive: true, force: true }); + } +}); + +test("a seed that is not an integer from 0 to 2^31 is refused before anything is written, without echoing it", async () => { + const daemon = await startDaemon(); + try { + const bad = [7.9, "7", "canary", [], [3], true, -1, 2 ** 31, 1e21, { canary: 1 }]; + for (const seed of bad) { + for (const payload of [exportRequest({ seed }), exportRequest({ meta: { seed } })]) { + const answer = await generate(daemon, payload); + assert.equal(answer.status, 400, JSON.stringify(payload)); + assert.ok(!answer.raw.includes("canary"), "the refusal repeated the input"); + assert.ok(!answer.raw.includes("7.9"), "the refusal repeated the input"); + } + } + assert.equal(existsSync(path.join(daemon.stateRoot, "artifacts")), false, "nothing was written"); + assert.deepEqual(daemon.spawns(), [], "no worker was started"); + assert.equal(exportStarts(daemon).length, 0); + for (const seed of [0, 2 ** 31 - 1]) { + const job = (await generate(daemon, exportRequest({ seed }))).body; + assert.equal(job.seed, seed); + assert.equal(job.worker.seed, seed, "the seed recorded is the seed the worker was given"); + } + } finally { + await daemon.stop(); + } +}); + +test("a BVH or FBX path swapped for a symlink after the job was checked is never followed", async () => { + for (const swap of ["bvh", "fbx", "both"]) { + const daemon = await startDaemon(); + try { + const outside = path.join(daemon.root, "outside-secret"); + const victim = path.join(daemon.root, "victim"); + writeFileSync(outside, "SECRET"); + writeFileSync(victim, "VICTIM"); + // sample 0 ("slow_00") exports for six seconds; the swap lands while it does, before sample 1 is touched + const pending = generate(daemon, exportRequest({ clipName: "slow", numSamples: 2 })); + await until(() => exportStarts(daemon).length === 1, "the first export to start"); + const [job] = readdirSync(path.join(daemon.stateRoot, "artifacts")); + const motion = path.join(daemon.stateRoot, "artifacts", job, "motion"); + if (swap !== "fbx") { + rmSync(path.join(motion, "motion_01.bvh")); + symlinkSync(outside, path.join(motion, "motion_01.bvh")); + } + if (swap !== "bvh") symlinkSync(victim, path.join(motion, "motion_01.fbx")); + const answer = await pending; + assert.equal(answer.status, 502, swap); + assert.equal(answer.body.ok, false); + assert.equal(readFileSync(victim, "utf8"), "VICTIM", `${swap}: nothing was written through the planted link`); + assert.equal(readFileSync(outside, "utf8"), "SECRET"); + for (const name of readdirSync(motion)) { + if (name.endsWith(".fbx") && !lstatSync(path.join(motion, name)).isSymbolicLink()) { + assert.ok(!readFileSync(path.join(motion, name), "utf8").includes("SECRET"), `${swap}: ${name} holds bytes read through the planted link`); + } + } + assert.ok(!answer.raw.includes("SECRET") && !answer.raw.includes("VICTIM")); + } finally { + await daemon.stop(); + } + } +}); + +test("the worker's environment is its named keys, and LD_LIBRARY_PATH reaches Blender only", async () => { + const daemon = await startDaemon({ extraEnv: { LD_LIBRARY_PATH: "/canary-lib" } }); + try { + const job = (await generate(daemon, exportRequest({ clipName: "wave" }))).body; + assert.equal(job.ok, true); + const named = ["HF_HOME", "HF_HUB_OFFLINE", "TRANSFORMERS_OFFLINE", "VILI_EMBEDDINGS_DIR", "VILI_THREADS", "OMP_NUM_THREADS", "MKL_NUM_THREADS", + "PYTHONPATH", "PYTHONDONTWRITEBYTECODE", "PYTHONUNBUFFERED", "VILI_KIMODO_COMMIT", "VILI_PYTHON_ENV"]; + const forwarded = ["PATH", "HOME", "LANG"].filter((name) => process.env[name] !== undefined || name === "LANG"); + assert.deepEqual(job.worker.envKeys, [...named, ...forwarded].sort(), "the worker gets exactly these keys, LD_LIBRARY_PATH not among them"); + const run = daemon.starts().find((start) => start.argv.includes("--")); + assert.equal(run.env.LD_LIBRARY_PATH, path.join(daemon.blenderDir, "lib"), "Blender gets the release's libraries, not the host's"); + } finally { + await daemon.stop(); + } +}); + +test("the lease goes between rest-fbx's directory and its copy: nothing is copied, nothing is exported", async () => { + const rest = restPython(); + const daemon = await idunnDaemon({ leased: true, loseWhenExists: "artifacts/*", python: rest.python }); + try { + await until(() => existsSync(path.join(daemon.stateRoot, "vili.service.cc")), "the service store", 10); + const answer = await restRequest(daemon); + assert.equal(answer.status, 503); + assert.equal(answer.body.code, "write-lease-lost"); + for (const job of readdirSync(path.join(daemon.stateRoot, "artifacts"))) { + assert.deepEqual(readdirSync(path.join(daemon.stateRoot, "artifacts", job)), [], "the job's directory is empty"); + } + assert.equal(exportStarts(daemon).length, 0); + } finally { + await daemon.stop(); + rmSync(rest.root, { recursive: true, force: true }); + } +}); + +test("the job record lists regular files only: a planted symlink, to a file or to a directory, is not listed", async () => { + const daemon = await startDaemon(); + try { + const job = (await generate(daemon, exportRequest({ model: "plant-link", clipName: "plant" }))).body; + assert.equal(job.ok, true); + assert.equal(readdirSync(job.artifactDir).filter((name) => name.includes("link")).length, 2, "both symlinks are in the job directory"); + assert.deepEqual(job.files.map((file) => file.name), ["meta.json", "motion.bvh", "motion.fbx", "motion.npz", "request.json"]); + } finally { + await daemon.stop(); + } +}); diff --git a/scripts/test_bvh_to_fbx.py b/scripts/test_bvh_to_fbx.py index 6f51063..b8ea8e5 100644 --- a/scripts/test_bvh_to_fbx.py +++ b/scripts/test_bvh_to_fbx.py @@ -47,6 +47,7 @@ if action is not None: frames = range(first, last + 3) out["hips_travel"] = max((world("Hips", f) - world("Hips", first)).length for f in frames) out["hips_mid"] = (world("Hips", first + 1 + 15) - world("Hips", first)).length + out["hips_curve"] = [list(world("Hips", first + 1 + i)) for i in range(31)] out["root_wander"] = max((world("Root", f) - world("Root", first)).length for f in frames) out["head_from_hips"] = list(world("Head", first + 1 + 15) - world("Hips", first + 1 + 15)) if len(argv) > 1: @@ -56,6 +57,7 @@ if action is not None: scene = bpy.context.scene arm = bpy.context.view_layer.objects.active out["reference_head_from_hips"] = list(world("Head", 1 + 15) - world("Hips", 1 + 15)) + out["reference_hips_curve"] = [list(world("Hips", 1 + i)) for i in range(31)] print("INSPECT " + json.dumps(out)) ''' @@ -100,6 +102,35 @@ def unit_scale_factor(fbx): return struct.unpack(" Date: Sat, 24 Oct 2026 23:15:55 +0200 Subject: [PATCH 23/36] Test: the plant-link stub writes its file with a newline escape, not a newline Co-Authored-By: Claude Opus 5.5 --- scripts/fixtures/stub-worker.mjs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/scripts/fixtures/stub-worker.mjs b/scripts/fixtures/stub-worker.mjs index 6439144..cfa1bb9 100644 --- a/scripts/fixtures/stub-worker.mjs +++ b/scripts/fixtures/stub-worker.mjs @@ -104,8 +104,7 @@ if (model === "hang-before-ready") { } if (model === "plant-link") { const outside = path.join(path.dirname(payload.output), "..", "outside.bvh"); - writeFileSync(outside, "BVH-OUTSIDE -"); + writeFileSync(outside, "BVH-OUTSIDE\n"); symlinkSync(outside, `${payload.output}.link`); symlinkSync(path.dirname(outside), `${payload.output}-linkdir`); } From 3574efe92e8e1cccc9d85670af57935a951867b9 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 24 Oct 2026 23:19:02 +0200 Subject: [PATCH 24/36] Test: the rest-fbx lease test waits for the Blender probe, so the lease is what stops it Co-Authored-By: Claude Opus 5.5 --- scripts/test-vili-daemon.mjs | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/test-vili-daemon.mjs b/scripts/test-vili-daemon.mjs index 31a8429..422aa84 100644 --- a/scripts/test-vili-daemon.mjs +++ b/scripts/test-vili-daemon.mjs @@ -1830,6 +1830,7 @@ test("the lease goes between rest-fbx's directory and its copy: nothing is copie const daemon = await idunnDaemon({ leased: true, loseWhenExists: "artifacts/*", python: rest.python }); try { await until(() => existsSync(path.join(daemon.stateRoot, "vili.service.cc")), "the service store", 10); + await until(async () => /^Blender /.test((await backendOf(daemon)).blender), "the Blender probe"); const answer = await restRequest(daemon); assert.equal(answer.status, 503); assert.equal(answer.body.code, "write-lease-lost"); From ea7ce34d90f8f031471ea1a3c81e1ea5e252c7d9 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 24 Oct 2026 23:19:16 +0200 Subject: [PATCH 25/36] Fix: job ids from one source with an exclusive mkdir, an integer seed at the door, Blender handed a private copy and its FBX created exclusively (Soul s1: job-id-collision, seed-recorded-not-used, bvh-swap-after-check) Co-Authored-By: Claude Opus 5.5 --- scripts/test-vili-daemon.mjs | 14 +++- scripts/vili-daemon.mjs | 145 +++++++++++++++++++++++++---------- 2 files changed, 115 insertions(+), 44 deletions(-) diff --git a/scripts/test-vili-daemon.mjs b/scripts/test-vili-daemon.mjs index 422aa84..f6b050b 100644 --- a/scripts/test-vili-daemon.mjs +++ b/scripts/test-vili-daemon.mjs @@ -1360,10 +1360,16 @@ test("an fbx job exports every listed BVH", async () => { const [probe, run] = daemon.starts(); assert.deepEqual(probe.argv, ["-b", "--factory-startup", "--version"]); - assert.deepEqual(run.argv, [ - "-b", "--factory-startup", "--python-use-system-env", "--python-exit-code", "1", "--python", exportScriptPath, - "--", path.join(job.artifactDir, "motion.bvh"), path.join(job.artifactDir, "motion.fbx"), "wave_01", + assert.deepEqual(run.argv.slice(0, 8), [ + "-b", "--factory-startup", "--python-use-system-env", "--python-exit-code", "1", "--python", exportScriptPath, "--", ]); + // Blender reads a private copy and writes a private FBX, in a directory made for this export alone: it is never + // handed a path in the job's directory, and the directory is gone once the export is over. + const [privateBvh, privateFbx, claimed] = run.argv.slice(8); + assert.match(path.relative(daemon.stateRoot, privateBvh), /^work\/export-[A-Za-z0-9]{6}\/in\.bvh$/); + assert.equal(privateFbx, path.join(path.dirname(privateBvh), "out.fbx")); + assert.equal(claimed, "wave_01"); + assert.deepEqual(readdirSync(path.join(daemon.stateRoot, "work")), []); assert.deepEqual(run.env, { PATH: process.env.PATH, LANG: "xx_TEST.UTF-8", @@ -1651,7 +1657,7 @@ test("rest-fbx is a job whose FBX is readable", async () => { const answer = await request(daemon.port, "POST", "/motion/rest-fbx", { body: "{}", headers: { "content-type": "application/json" } }); assert.equal(answer.status, 200); const job = answer.body; - assert.match(job.jobId, /^rest-[0-9]{13}$/); + assert.match(job.jobId, /^rest-[0-9]{13}-[0-9a-f]{8}$/); assert.equal(job.schema, "gamecult.vili.motion_job.v1"); assert.deepEqual(job.export.clips, [{ file: "SOMA77_Rest.fbx", clipName: "SOMA77_Rest", bones: 78, frames: [1, 60], fps: 30 }]); assert.deepEqual(job.files.map((file) => file.name), ["SOMA77_Rest.bvh", "SOMA77_Rest.fbx"]); diff --git a/scripts/vili-daemon.mjs b/scripts/vili-daemon.mjs index d8994df..ba781f6 100644 --- a/scripts/vili-daemon.mjs +++ b/scripts/vili-daemon.mjs @@ -1,9 +1,9 @@ #!/usr/bin/env node import http from "node:http"; import os from "node:os"; -import { createHash, randomInt } from "node:crypto"; -import { closeSync, lstatSync, openSync, readdirSync, readFileSync, realpathSync, unlinkSync, writeFileSync, writeSync } from "node:fs"; -import { copyFile, mkdir, readFile, writeFile } from "node:fs/promises"; +import { createHash, randomBytes, randomInt } from "node:crypto"; +import { closeSync, constants, lstatSync, openSync, readdirSync, readFileSync, realpathSync, unlinkSync, writeFileSync, writeSync } from "node:fs"; +import { copyFile, mkdir, mkdtemp, open, readFile, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import readline from "node:readline"; import net from "node:net"; @@ -564,44 +564,88 @@ async function probeBlender() { blender.version = run.code === 0 && run.first?.startsWith("Blender ") ? run.first : null; } -// One BVH to one FBX beside it. The FBX counts only if Blender exits 0, prints its result line and the file exists. -// A failure names the exit or the signal and never Blender's output. -async function exportClip(bvh, fbx, clipName, timeoutMs) { - const run = await runBlender([ - "-b", "--factory-startup", "--python-use-system-env", "--python-exit-code", "1", - "--python", exportScript, "--", bvh, fbx, clipName, - ], timeoutMs); - let info = null; - if (run.code === 0 && run.result !== null) { - try { - const parsed = JSON.parse(run.result); - if (Number.isInteger(parsed.bones) && Array.isArray(parsed.frames) && parsed.frames.length === 2 - && parsed.frames.every(Number.isInteger) && Number.isFinite(parsed.fps)) info = parsed; - } catch { - // not the result line - } +// The bytes of a regular file strictly inside `directory`, or null. The file is opened without following a symlink +// and the open file is the one checked, so a path swapped after the check cannot redirect the read. +async function readInside(file, directory) { + let handle = null; + try { + handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW); + const opened = await handle.stat(); + if (!opened.isFile() || !regularFileInside(file, directory)) return null; + const named = lstatSync(file); + if (named.dev !== opened.dev || named.ino !== opened.ino) return null; + return await handle.readFile(); + } catch { + return null; + } finally { + await handle?.close(); + } +} + +// One BVH to one FBX beside it. Blender never sees a path in the job's artifact directory: it reads a private copy of +// the BVH and writes a private FBX in a directory made for this export alone, and the FBX is then created beside the +// BVH exclusively, so nothing planted at either path is read, written through or replaced. The FBX counts only if +// Blender exits 0, prints its result line and its file exists. A failure names the exit or the signal and never +// Blender's output. +async function exportClip(bvh, fbx, clipName, timeoutMs, artifactDir) { + const input = await readInside(bvh, artifactDir); + if (input === null) return { error: "fbx-export-refused" }; + guard(); + await mkdir(path.join(args.stateRoot, "work"), { recursive: true }); + guard(); + const work = await mkdtemp(path.join(args.stateRoot, "work", "export-")); + try { + const privateBvh = path.join(work, "in.bvh"); + const privateFbx = path.join(work, "out.fbx"); + guard(); + await writeFile(privateBvh, input, { flag: "wx" }); + const run = await runBlender([ + "-b", "--factory-startup", "--python-use-system-env", "--python-exit-code", "1", + "--python", exportScript, "--", privateBvh, privateFbx, clipName, + ], timeoutMs); + let info = null; + if (run.code === 0 && run.result !== null) { + try { + const parsed = JSON.parse(run.result); + if (Number.isInteger(parsed.bones) && Array.isArray(parsed.frames) && parsed.frames.length === 2 + && parsed.frames.every(Number.isInteger) && Number.isFinite(parsed.fps)) info = parsed; + } catch { + // not the result line + } + } + const made = info ? await readInside(privateFbx, work) : null; + if (made !== null) { + guard(); + try { + await writeFile(fbx, made, { flag: "wx" }); + return { clip: { file: fbx, clipName, bones: info.bones, frames: info.frames, fps: info.fps } }; + } catch (error) { + if (error instanceof LeaseLost) throw error; + return { error: "fbx-export-refused" }; + } + } + const how = run.code === 0 ? "no result" : run.code !== null ? `exit ${run.code}` : `signal ${run.signal ?? "none"}`; + return { error: `fbx-export-failed (${how})` }; + } finally { + if (mayWrite()) await rm(work, { recursive: true, force: true }); } - if (info && isRegularFile(fbx)) return { clip: { file: fbx, clipName, bones: info.bones, frames: info.frames, fps: info.fps } }; - const how = run.code === 0 ? "no result" : run.code !== null ? `exit ${run.code}` : `signal ${run.signal ?? "none"}`; - return { error: `fbx-export-failed (${how})` }; } // Every BVH the worker listed becomes an FBX, or the job fails. A listed BVH must be a regular file inside the job's -// artifact directory, and all are checked before Blender starts for any. Sample N of several is _NN. +// artifact directory, and that is decided when its export begins (exportClip), never earlier. Sample N of several is +// _NN. async function exportListed(listed, artifactDir, clipName, timeoutMs) { const bvhs = []; for (const file of Array.isArray(listed) ? listed : []) { if (typeof file !== "string" || !file.endsWith(".bvh")) continue; - const full = path.resolve(artifactDir, file); - if (!regularFileInside(full, artifactDir)) return { clips: [], error: "fbx-export-refused" }; - bvhs.push(full); + bvhs.push(path.resolve(artifactDir, file)); } if (bvhs.length === 0) return { clips: [], error: "fbx-export-failed (no bvh)" }; bvhs.sort(); const clips = []; for (const [index, bvh] of bvhs.entries()) { const name = bvhs.length === 1 ? clipName : `${clipName}_${String(index).padStart(2, "0")}`; - const done = await exportClip(bvh, `${bvh.slice(0, -".bvh".length)}.fbx`, name, timeoutMs); + const done = await exportClip(bvh, `${bvh.slice(0, -".bvh".length)}.fbx`, name, timeoutMs, artifactDir); if (done.error) return { clips, error: done.error }; clips.push({ ...done.clip, file: path.relative(artifactDir, done.clip.file).split(path.sep).join("/") }); } @@ -751,6 +795,28 @@ async function underLease(response, run) { } } +// A seed is an integer Kimodo can take: the worker seeds with int(seed), so the daemon records exactly what it sends. +const SEED_LIMIT = 2 ** 31; + +// The one source of job ids, for a generate job and a rest job alike: the clock for order, random bits for +// uniqueness, and an exclusive mkdir that decides, so two jobs never share a directory, a record or a file. +async function newJobDir(prefix) { + guard(); + await mkdir(path.join(args.stateRoot, "artifacts"), { recursive: true }); + for (let attempt = 0; attempt < 8; attempt += 1) { + const jobId = `${prefix}-${Date.now()}-${randomBytes(4).toString("hex")}`; + const artifactDir = path.join(args.stateRoot, "artifacts", jobId); + guard(); + try { + await mkdir(artifactDir); + return { jobId, artifactDir }; + } catch (error) { + if (error.code !== "EEXIST") throw error; + } + } + throw new Error("no free job id"); +} + async function generate(request, response) { guard(); if (workerUnconfigured()) { @@ -797,21 +863,23 @@ async function generate(request, response) { bvhStandardTpose: fbx || boolValue(askedTpose), }; - const jobId = `vili-${Date.now()}`; - const clipName = fbx ? (body.clipName ?? jobId) : undefined; - const artifactDir = path.join(args.stateRoot, "artifacts", jobId); - guard(); - await mkdir(artifactDir, { recursive: true }); - const duration = firstDefined(body.durationSeconds, body.duration, 4); const bodyMeta = typeof body.meta === "object" && body.meta ? body.meta : {}; + const askedSeed = firstDefined(body.seed, bodyMeta.seed); + if (askedSeed !== undefined && !(Number.isInteger(askedSeed) && askedSeed >= 0 && askedSeed < SEED_LIMIT)) { + json(response, 400, { ok: false, error: "Invalid seed." }); + return; + } + + const { jobId, artifactDir } = await newJobDir("vili"); + const clipName = fbx ? (body.clipName ?? jobId) : undefined; + const duration = firstDefined(body.durationSeconds, body.duration, 4); const diffusionSteps = Math.max(1, Number(firstDefined( body.diffusionSteps, body.diffusion_steps, bodyMeta.diffusion_steps, 20, ))); - const askedSeed = Number(firstDefined(body.seed, bodyMeta.seed)); - const seed = Number.isFinite(askedSeed) ? askedSeed : randomInt(0, 2 ** 31); + const seed = askedSeed ?? randomInt(0, SEED_LIMIT); const numSamples = Math.max(1, Number(firstDefined( body.numSamples, body.num_samples, @@ -944,10 +1012,7 @@ async function restFbx(response) { json(response, 503, { ok: false, code: "rest-skeleton-missing" }); return; } - const jobId = `rest-${Date.now()}`; - const artifactDir = path.join(args.stateRoot, "artifacts", jobId); - guard(); - await mkdir(artifactDir, { recursive: true }); + const { jobId, artifactDir } = await newJobDir("rest"); guard(); await copyFile(restBvh, path.join(artifactDir, "SOMA77_Rest.bvh")); const exported = await exportListed([path.join(artifactDir, "SOMA77_Rest.bvh")], artifactDir, "SOMA77_Rest", EXPORT_TIMEOUT_MS); @@ -970,7 +1035,7 @@ async function restFbx(response) { } // Reads only: a job's own FBX and BVH files, by exact name, regular files inside the job's artifact directory. -const ARTIFACT_ROUTE = /^\/motion\/artifacts\/((?:vili|rest)-[0-9]{13})\/(motion\.fbx|motion\.bvh|SOMA77_Rest\.fbx|motion\/motion_[0-9]{2}\.(?:fbx|bvh))$/; +const ARTIFACT_ROUTE = /^\/motion\/artifacts\/((?:vili|rest)-[0-9]{13}-[0-9a-f]{8})\/(motion\.fbx|motion\.bvh|SOMA77_Rest\.fbx|motion\/motion_[0-9]{2}\.(?:fbx|bvh))$/; async function serveArtifact(response, jobId, name) { const directory = path.join(args.stateRoot, "artifacts", jobId); From b015658962559ba81a581295cf4dd5f14d83309d Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 24 Oct 2026 23:19:17 +0200 Subject: [PATCH 26/36] README: the FBX routes are planned until the next idunn up; the seed and the export's file handling as built (Soul s1: front-door-claims-fbx-live) Co-Authored-By: Claude Opus 5.5 --- README.md | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index da2ab50..85eb3ee 100644 --- a/README.md +++ b/README.md @@ -8,11 +8,11 @@ Linux. It runs on Yggdrasil as an Idunn target (see Front Door). ## Front Door -- **Value:** a supervised path from a text prompt to generated body motion. The daemon spawns one resident Kimodo worker, caps its threads, and returns motion artifacts (`motion.npz`, BVH, and FBX for Unity) for a job. +- **Value:** a supervised path from a text prompt to generated body motion. The daemon spawns one resident Kimodo worker, caps its threads, and returns motion artifacts (`motion.npz` and BVH; FBX for Unity is planned, see below) for a job. - **Problem:** Personas and games need generated motion, but cold per-request model loads cost minutes. One daemon owns job identity, worker lifecycle, the thread budget and artifact references, so callers touch no model state. - **Entry points:** `scripts/vili-daemon.mjs` (the daemon; `npm start`, `npm test`), `scripts/idunn-entry.mjs` (the process Idunn runs), `deployment/idunn/recipe.toml` (the sealed release), `scripts/kimodo-resident-worker.py` (the worker it spawns), `scripts/kimodo-text-encode.py` (the one-shot encoder child), `POST /motion/generate` (see Motion Generation), `docs/verse-service-contract.md` and `docs/motion-pipeline-target.md`. -- **Live:** the Idunn target `vili` on Yggdrasil at `http://10.77.0.1:8824` (WireGuard only), CPU only: `POST /motion/generate` (add `"fbx": true` for a Unity-ready FBX per clip), `POST /motion/rest-fbx` (the avatar's rest pose), `GET /motion/artifacts/{jobId}/{name}` (the FBX and BVH bytes), `GET /health`, `GET /operator-state`, and the CultCache service store. FBX export is `scripts/bvh-to-fbx.py` in the release's own Blender 5.2.2; see FBX Export. -- **Planned:** worker intake closed to local callers only, publication to Odin, and a Thing 2 operator surface. The text-prompt-to-Unity-clip path with no hand steps is `docs/motion-pipeline-target.md`. +- **Live:** the Idunn target `vili` on Yggdrasil at `http://10.77.0.1:8824` (WireGuard only), CPU only, running the revision deployed before the FBX export: `POST /motion/generate` (`motion.npz` and optional BVH on the SOMA skeleton; no FBX), `GET /health`, `GET /operator-state`, and the CultCache service store. +- **Planned:** FBX export, which is in this tree and not yet deployed: `"fbx": true` on `POST /motion/generate` (a Unity-ready FBX per clip), `POST /motion/rest-fbx` (the avatar's rest pose) and `GET /motion/artifacts/{jobId}/{name}` (the FBX and BVH bytes), from `scripts/bvh-to-fbx.py` in the release's own Blender 5.2.2 (see FBX Export). They answer only after the next `idunn up`. Also planned: worker intake closed to local callers only, publication to Odin, and a Thing 2 operator surface. The text-prompt-to-Unity-clip path with no hand steps is `docs/motion-pipeline-target.md`. ## Authority @@ -128,7 +128,7 @@ Supported request fields: - `numTransitionFrames` / `num_transition_frames` - `constraints` as an object/list, or `constraints`, `constraintsPath`, or `constraints_path` as a path on the worker host -- `seed` (absent: the daemon mints one, and every job records the seed it used) +- `seed` (an integer from 0 to 2^31 - 1, anything else is a 400; absent: the daemon mints one; the job records the seed the worker was given) - `cfg`, `cfgType` / `cfg_type`, `cfgWeight` / `cfg_weight` - `bvh`, `bvhStandardTpose` / `bvh_standard_tpose` - `fbx` and `clipName` (see FBX Export) @@ -144,6 +144,8 @@ exports CSV when that model is resident. ## FBX Export +Planned until the next deploy: the live unit does not have these routes or the `fbx` field yet. + `"fbx": true` makes the job's BVH an FBX for Unity, beside it: `motion.fbx`, or `motion/motion_NN.fbx` for several samples. It implies `bvh` and `bvhStandardTpose`; an explicit `bvhStandardTpose: false` is a 400. `clipName` (`^[A-Za-z0-9_-]{1,64}$`, default the job id; sample N of several is `_NN`) names the armature, the action @@ -151,9 +153,12 @@ and the FBX take. With Blender not ready (`backend.blender` is `unconfigured` or `Blender 5.2.2 LTS ...` line) an `fbx` request is a 503 `blender-unavailable` and nothing is written. The worker never runs Blender. After it answers, the daemon runs the release's Blender -(`blender -b --factory-startup --python-use-system-env --python scripts/bvh-to-fbx.py`) on each BVH it listed, and -only on a regular file inside the job's artifact directory; the FBX path is the BVH's, so it is derived from the -job id. Blender converts and nothing else: the SOMA77 joint names are Kimodo's, the pose is the standard T-pose in +(`blender -b --factory-startup --python-use-system-env --python scripts/bvh-to-fbx.py`) on each BVH it listed. +The BVH must be a regular file inside the job's artifact directory, opened without following a symlink; Blender is +handed a private copy of it and writes a private FBX in a directory made for that export (`/work/`), and the +daemon creates the FBX beside the BVH exclusively, so a path planted in the job directory is never read, written +through or replaced. The FBX path is the BVH's, derived from the job id, which is the clock plus random bits and is +taken by an exclusive mkdir. Blender converts and nothing else: the SOMA77 joint names are Kimodo's, the pose is the standard T-pose in metres, and the clip's travel stays on `Hips` (Root is static), so Unity derives root motion or bakes it into the pose as the caller chooses. Blender runs under the write gate in its own process group at nice 10, with `HOME=/nonexistent`, `PYTHONHASHSEED=0` and `LD_LIBRARY_PATH=/lib` as its whole environment, a 120 s From 32eb3e4c87529be565c5cda3d408389ac42b3f1f Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 24 Oct 2026 23:23:22 +0200 Subject: [PATCH 27/36] Test: a directory above the BVH swapped for a symlink is refused too Co-Authored-By: Claude Opus 5.5 --- scripts/test-vili-daemon.mjs | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/scripts/test-vili-daemon.mjs b/scripts/test-vili-daemon.mjs index f6b050b..0dce8fd 100644 --- a/scripts/test-vili-daemon.mjs +++ b/scripts/test-vili-daemon.mjs @@ -3,7 +3,7 @@ import assert from "node:assert/strict"; import { spawn } from "node:child_process"; import { createHash } from "node:crypto"; -import { chmodSync, copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs"; +import { chmodSync, copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, statSync, symlinkSync, writeFileSync } from "node:fs"; import http from "node:http"; import net from "node:net"; import os from "node:os"; @@ -1781,7 +1781,7 @@ test("a seed that is not an integer from 0 to 2^31 is refused before anything is }); test("a BVH or FBX path swapped for a symlink after the job was checked is never followed", async () => { - for (const swap of ["bvh", "fbx", "both"]) { + for (const swap of ["bvh", "fbx", "both", "directory"]) { const daemon = await startDaemon(); try { const outside = path.join(daemon.root, "outside-secret"); @@ -1793,17 +1793,25 @@ test("a BVH or FBX path swapped for a symlink after the job was checked is never await until(() => exportStarts(daemon).length === 1, "the first export to start"); const [job] = readdirSync(path.join(daemon.stateRoot, "artifacts")); const motion = path.join(daemon.stateRoot, "artifacts", job, "motion"); - if (swap !== "fbx") { + const elsewhere = path.join(daemon.root, "elsewhere"); + if (swap === "directory") { + // the directory itself is replaced by a link to one that holds a regular file of the right name + mkdirSync(elsewhere); + writeFileSync(path.join(elsewhere, "motion_01.bvh"), "SECRET"); + renameSync(motion, `${motion}-moved`); + symlinkSync(elsewhere, motion); + } + if (swap === "bvh" || swap === "both") { rmSync(path.join(motion, "motion_01.bvh")); symlinkSync(outside, path.join(motion, "motion_01.bvh")); } - if (swap !== "bvh") symlinkSync(victim, path.join(motion, "motion_01.fbx")); + if (swap === "fbx" || swap === "both") symlinkSync(victim, path.join(motion, "motion_01.fbx")); const answer = await pending; assert.equal(answer.status, 502, swap); assert.equal(answer.body.ok, false); assert.equal(readFileSync(victim, "utf8"), "VICTIM", `${swap}: nothing was written through the planted link`); assert.equal(readFileSync(outside, "utf8"), "SECRET"); - for (const name of readdirSync(motion)) { + for (const name of readdirSync(swap === "directory" ? elsewhere : motion)) { if (name.endsWith(".fbx") && !lstatSync(path.join(motion, name)).isSymbolicLink()) { assert.ok(!readFileSync(path.join(motion, name), "utf8").includes("SECRET"), `${swap}: ${name} holds bytes read through the planted link`); } From 2f5e48f1dba5a597e63a60692061d667a3245c74 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 25 Oct 2026 00:41:11 +0200 Subject: [PATCH 28/36] Test: the sealed Blender loads no host library outside the libc family (container job, red until the X libraries are bundled) Co-Authored-By: Claude Opus 5.5 --- scripts/verify-blender-selfcontained.sh | 99 +++++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100755 scripts/verify-blender-selfcontained.sh diff --git a/scripts/verify-blender-selfcontained.sh b/scripts/verify-blender-selfcontained.sh new file mode 100755 index 0000000..ff247fa --- /dev/null +++ b/scripts/verify-blender-selfcontained.sh @@ -0,0 +1,99 @@ +#!/usr/bin/env bash +# The sealed Blender carries every library it loads except the libc family. Run in a container with no X or GL +# library on it (it needs docker, so it is not in the recipe's test step, whose runner image has X libraries): +# +# ygg-verify.sh debian:bookworm-slim 'bash scripts/verify-blender-selfcontained.sh' +# +# It downloads the recipe's Blender and Debian inputs (url and sha256 from deployment/idunn/recipe.toml), unpacks them +# with the recipe's own unpack-blender and unpack-blender-libs argv, then asserts: ldd reports nothing missing; every +# shared object the process maps during a real export, run with the daemon's export environment +# (scripts/vili-daemon.mjs exportEnv), is inside the release tree or is libc, libm, libdl, libpthread, librt, libutil, +# libresolv, the dynamic loader, libgcc_s, libstdc++ or libuuid1. Any other host library fails. +set -euo pipefail +cd "$(dirname "$0")/.." +export DEBIAN_FRONTEND=noninteractive +apt-get update -qq >/dev/null +apt-get install -y -qq --no-install-recommends curl ca-certificates xz-utils python3 >/dev/null + +# The test means nothing if the host can supply what the release should carry. +host=$(find / -xdev \( -name 'libX11*' -o -name 'libxcb*' -o -name 'libXext*' -o -name 'libXau*' -o -name 'libXdmcp*' \ + -o -name 'libbsd*' -o -name 'libmd.so*' -o -name 'libGL*' -o -name 'libXi.*' -o -name 'libxkbcommon*' \) 2>/dev/null | head -5) +if [ -n "$host" ]; then echo "FAIL: the container carries X or GL libraries: $host"; exit 2; fi + +mkdir -p release +python3 - <<'PY' +import hashlib, subprocess, tomllib +recipe = tomllib.load(open("deployment/idunn/recipe.toml", "rb")) +for item in recipe["external_inputs"]: + if item["id"] != "blender-linux-x64" and not item["id"].startswith("deb-"): + continue + subprocess.run(["curl", "-sSfL", "--retry", "3", "--max-time", "900", "-o", item["destination"], item["url"]], check=True) + assert hashlib.sha256(open(item["destination"], "rb").read()).hexdigest() == item["sha256"], item["id"] + print("verified", item["id"]) +steps = {s["id"]: s["argv"] for s in recipe["steps"]} +for step in ("unpack-blender", "unpack-blender-libs"): + argv = ["python3" if a == "python3.12" else a for a in steps[step]] + subprocess.run(argv, check=True) + print("ran", step) +PY + +blender=$PWD/release/blender/blender +lib=$PWD/release/blender/lib +echo "libraries in blender/lib: $(ls "$lib" | wc -l)" + +echo "-- ldd" +LD_LIBRARY_PATH=$lib ldd "$blender" > ldd.txt +if grep "not found" ldd.txt; then echo "FAIL: ldd reports missing libraries"; exit 1; fi + +echo "-- a real export with the daemon's export environment" +cat > t.bvh <<'BVH' +HIERARCHY +ROOT Hips +{ + OFFSET 0 0 0 + CHANNELS 6 Xposition Yposition Zposition Zrotation Yrotation Xrotation + JOINT Spine + { + OFFSET 0 10 0 + CHANNELS 3 Zrotation Yrotation Xrotation + End Site + { + OFFSET 0 10 0 + } + } +} +MOTION +Frames: 3 +Frame Time: 0.0333333 +0 100 0 0 0 0 0 0 0 +0 101 0 0 0 0 5 0 0 +0 102 0 0 0 0 10 0 0 +BVH +# The daemon's argv and environment exactly (HOME, PYTHONHASHSEED, PYTHONNOUSERSITE, LD_LIBRARY_PATH, PATH, LANG). +daemon_env() { env -i PATH="$PATH" LANG=C HOME=/nonexistent PYTHONHASHSEED=0 PYTHONNOUSERSITE=1 LD_LIBRARY_PATH="$lib" "$@"; } +daemon_env "$blender" -b --factory-startup --python-use-system-env --python-exit-code 1 --python scripts/bvh-to-fbx.py -- \ + "$PWD/t.bvh" "$PWD/plain.fbx" proof | tee export.txt +grep -q '^VILI-FBX ' export.txt || { echo "FAIL: no VILI-FBX line"; exit 1; } +test -s plain.fbx || { echo "FAIL: no FBX written"; exit 1; } + +# The same export again inside a wrapper that records what the process mapped when it finished: the loader's own +# account, dlopen included. The FBX must be byte-identical to the plain run. +cat > mapped.py <<'PY' +import runpy, sys +try: + runpy.run_path("scripts/bvh-to-fbx.py", run_name="__main__") +finally: + seen = sorted({l.split(None, 5)[5].strip() for l in open("/proc/self/maps") if len(l.split(None, 5)) == 6 and l.split(None, 5)[5].startswith("/")}) + open(sys.argv[sys.argv.index("--") + 1] + ".maps", "w").write("\n".join(seen) + "\n") +PY +daemon_env "$blender" -b --factory-startup --python-use-system-env --python-exit-code 1 --python mapped.py -- \ + "$PWD/t.bvh" "$PWD/mapped.fbx" proof >/dev/null +cmp plain.fbx mapped.fbx || { echo "FAIL: wrapped export differs"; exit 1; } + +echo "-- shared objects mapped from outside the release" +outside=$(grep -E '\.so(\.|$)|/ld-linux' mapped.fbx.maps | grep -v "^$PWD/release/" || true) +echo "$outside" +bad=$(echo "$outside" | grep -v -E '^$|/(libc|libm|libdl|libpthread|librt|libutil|libresolv|libgcc_s|libstdc\+\+|libuuid)\.so[.0-9]*$|/ld-linux-x86-64\.so\.[0-9]+$|/libc-[0-9.]+\.so$|/libm-[0-9.]+\.so$' || true) +if [ -n "$bad" ]; then echo "FAIL: host libraries outside the allowlist:"; echo "$bad"; exit 1; fi +test -n "$(grep -c "^$PWD/release/blender/lib/libX11" mapped.fbx.maps | grep -v '^0$')" || { echo "FAIL: libX11 was not loaded from the release"; exit 1; } +echo "SELFCONTAINED-OK" From ae4743052226f577adb8c18c8cbbdbf6cc36bfbf Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 25 Oct 2026 00:41:43 +0200 Subject: [PATCH 29/36] Test: the container precheck exempts libmd (dpkg needs it, so the slim image has it); the test demands the release's copy is the one mapped Co-Authored-By: Claude Opus 5.5 --- scripts/verify-blender-selfcontained.sh | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/scripts/verify-blender-selfcontained.sh b/scripts/verify-blender-selfcontained.sh index ff247fa..07fe7da 100755 --- a/scripts/verify-blender-selfcontained.sh +++ b/scripts/verify-blender-selfcontained.sh @@ -15,9 +15,10 @@ export DEBIAN_FRONTEND=noninteractive apt-get update -qq >/dev/null apt-get install -y -qq --no-install-recommends curl ca-certificates xz-utils python3 >/dev/null -# The test means nothing if the host can supply what the release should carry. +# The test means nothing if the host can supply what the release should carry. (libmd.so.0 is exempt: dpkg needs it, +# so even the slim image has it; the mapped-library allowlist below still demands that Blender load the release's copy.) host=$(find / -xdev \( -name 'libX11*' -o -name 'libxcb*' -o -name 'libXext*' -o -name 'libXau*' -o -name 'libXdmcp*' \ - -o -name 'libbsd*' -o -name 'libmd.so*' -o -name 'libGL*' -o -name 'libXi.*' -o -name 'libxkbcommon*' \) 2>/dev/null | head -5) + -o -name 'libbsd*' -o -name 'libGL*' -o -name 'libXi.*' -o -name 'libxkbcommon*' \) 2>/dev/null | head -5) if [ -n "$host" ]; then echo "FAIL: the container carries X or GL libraries: $host"; exit 2; fi mkdir -p release @@ -95,5 +96,7 @@ outside=$(grep -E '\.so(\.|$)|/ld-linux' mapped.fbx.maps | grep -v "^$PWD/releas echo "$outside" bad=$(echo "$outside" | grep -v -E '^$|/(libc|libm|libdl|libpthread|librt|libutil|libresolv|libgcc_s|libstdc\+\+|libuuid)\.so[.0-9]*$|/ld-linux-x86-64\.so\.[0-9]+$|/libc-[0-9.]+\.so$|/libm-[0-9.]+\.so$' || true) if [ -n "$bad" ]; then echo "FAIL: host libraries outside the allowlist:"; echo "$bad"; exit 1; fi -test -n "$(grep -c "^$PWD/release/blender/lib/libX11" mapped.fbx.maps | grep -v '^0$')" || { echo "FAIL: libX11 was not loaded from the release"; exit 1; } +for name in libX11 libmd; do + grep -q "^$PWD/release/blender/lib/$name\." mapped.fbx.maps || { echo "FAIL: $name was not loaded from the release"; exit 1; } +done echo "SELFCONTAINED-OK" From 2891f016bf11a1e0b3d29e30ad46d58424fd6721 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 25 Oct 2026 00:42:32 +0200 Subject: [PATCH 30/36] Fix: the sealed Blender carries libx11-6, libxext6, libxcb1, libxau6, libxdmcp6, libbsd0 and libmd0 too (Soul s1 blender-uses-host-x-libs) Seven sha256-pinned bookworm inputs from the recipe's snapshot, unpacked by the one unpack-blender-libs step. Co-Authored-By: Claude Opus 5.5 --- deployment/idunn/recipe.toml | 65 ++++++++++++++++++++++++++++++++++-- 1 file changed, 62 insertions(+), 3 deletions(-) diff --git a/deployment/idunn/recipe.toml b/deployment/idunn/recipe.toml index c5df686..9fed140 100644 --- a/deployment/idunn/recipe.toml +++ b/deployment/idunn/recipe.toml @@ -21,9 +21,12 @@ sha256 = "84098912789dc450e95697c4184fb8a90acbe5111c2ba4aede3fecb57806a168" runner = "python-build" destination = "release/blender.tar.xz" -# The nine Debian bookworm packages whose shared libraries Blender loads and its tree does not carry (the Blender -# tarball's loader reaches libGL and the X client libraries). Their usr/lib/x86_64-linux-gnu/*.so* go into blender/lib; -# nothing is installed on the host (motion-pipeline:ruling:blender-libs-bundled-in-release). One snapshot.debian.org +# The sixteen Debian bookworm packages whose shared libraries Blender loads and its tree does not carry: libGL and the +# X client libraries it reaches (libx11-6, libxext6, libxcb1, libxau6, libxdmcp6, libbsd0 and libmd0 are the transitive +# ones a host only has when something like xauth installed them). Their usr/lib/x86_64-linux-gnu/*.so* go into +# blender/lib; nothing is installed on the host and the host supplies only the libc family, libgcc_s, libstdc++ and +# libuuid1 (motion-pipeline:ruling:blender-libs-bundled-in-release, motion-pipeline:ruling:blender-x-libs-bundled-in-release; +# proved by scripts/verify-blender-selfcontained.sh). One snapshot.debian.org # timestamp, so the bytes are immutable; each sha256 is the package's own. [[external_inputs]] @@ -89,6 +92,55 @@ sha256 = "b6da5b153dd62d8b5e5fbe25242db1fc05c068707c365db49abda8c2427c75f8" runner = "python-build" destination = "release/deb-libglvnd0.deb" +[[external_inputs]] +id = "deb-libx11-6" +url = "https://snapshot.debian.org/archive/debian/20260301T000000Z/pool/main/libx/libx11/libx11-6_1.8.4-2+deb12u2_amd64.deb" +sha256 = "d88c973e79fd9b65838d77624142952757e47a6eb1a58602acf0911cf35989f4" +runner = "python-build" +destination = "release/deb-libx11-6.deb" + +[[external_inputs]] +id = "deb-libxext6" +url = "https://snapshot.debian.org/archive/debian/20260301T000000Z/pool/main/libx/libxext/libxext6_1.3.4-1+b1_amd64.deb" +sha256 = "504b7be9d7df4f6f4519e8dd4d6f9d03a9fb911a78530fa23a692fba3058cba6" +runner = "python-build" +destination = "release/deb-libxext6.deb" + +[[external_inputs]] +id = "deb-libxcb1" +url = "https://snapshot.debian.org/archive/debian/20260301T000000Z/pool/main/libx/libxcb/libxcb1_1.15-1_amd64.deb" +sha256 = "fdc61332a3892168f3cc9cfa1fe9cf11a91dc3e0acacbc47cbc50ebaa234cc71" +runner = "python-build" +destination = "release/deb-libxcb1.deb" + +[[external_inputs]] +id = "deb-libxau6" +url = "https://snapshot.debian.org/archive/debian/20260301T000000Z/pool/main/libx/libxau/libxau6_1.0.9-1_amd64.deb" +sha256 = "679db1c4579ec7c61079adeaae8528adeb2e4bf5465baa6c56233b995d714750" +runner = "python-build" +destination = "release/deb-libxau6.deb" + +[[external_inputs]] +id = "deb-libxdmcp6" +url = "https://snapshot.debian.org/archive/debian/20260301T000000Z/pool/main/libx/libxdmcp/libxdmcp6_1.1.2-3_amd64.deb" +sha256 = "ecb8536f5fb34543b55bb9dc5f5b14c9dbb4150a7bddb3f2287b7cab6e9d25ef" +runner = "python-build" +destination = "release/deb-libxdmcp6.deb" + +[[external_inputs]] +id = "deb-libbsd0" +url = "https://snapshot.debian.org/archive/debian/20260301T000000Z/pool/main/libb/libbsd/libbsd0_0.11.7-2_amd64.deb" +sha256 = "bb31cc8b40f962a85b2cec970f7f79cc704a1ae4bad24257a822055404b2c60b" +runner = "python-build" +destination = "release/deb-libbsd0.deb" + +[[external_inputs]] +id = "deb-libmd0" +url = "https://snapshot.debian.org/archive/debian/20260301T000000Z/pool/main/libm/libmd/libmd0_1.0.4-2_amd64.deb" +sha256 = "03539fd30c509e27101d13a56e52eda9062bdf1aefe337c07ab56def25a13eab" +runner = "python-build" +destination = "release/deb-libmd0.deb" + # ---- node-build: the daemon, the Idunn entry and its dependencies [[steps]] @@ -166,6 +218,13 @@ argv = [ "release/deb-libgl1.deb", "release/deb-libglx0.deb", "release/deb-libglvnd0.deb", + "release/deb-libx11-6.deb", + "release/deb-libxext6.deb", + "release/deb-libxcb1.deb", + "release/deb-libxau6.deb", + "release/deb-libxdmcp6.deb", + "release/deb-libbsd0.deb", + "release/deb-libmd0.deb", ] [[steps]] From 113dcaa745db25de44263f011b5cbf4373ce0ef2 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 25 Oct 2026 00:43:23 +0200 Subject: [PATCH 31/36] Test: the mapped-library record is written beside the FBX it names Co-Authored-By: Claude Opus 5.5 --- scripts/verify-blender-selfcontained.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/verify-blender-selfcontained.sh b/scripts/verify-blender-selfcontained.sh index 07fe7da..b8eb2a2 100755 --- a/scripts/verify-blender-selfcontained.sh +++ b/scripts/verify-blender-selfcontained.sh @@ -85,7 +85,7 @@ try: runpy.run_path("scripts/bvh-to-fbx.py", run_name="__main__") finally: seen = sorted({l.split(None, 5)[5].strip() for l in open("/proc/self/maps") if len(l.split(None, 5)) == 6 and l.split(None, 5)[5].startswith("/")}) - open(sys.argv[sys.argv.index("--") + 1] + ".maps", "w").write("\n".join(seen) + "\n") + open(sys.argv[sys.argv.index("--") + 2] + ".maps", "w").write("\n".join(seen) + "\n") PY daemon_env "$blender" -b --factory-startup --python-use-system-env --python-exit-code 1 --python mapped.py -- \ "$PWD/t.bvh" "$PWD/mapped.fbx" proof >/dev/null From 19d894c5a781b3c2e49b9ab251f4b854451095f8 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 25 Oct 2026 01:40:54 +0200 Subject: [PATCH 32/36] Test: Soul s2 findings as behavioural tests (id suffix burst, FIFO listed as BVH, work slot and sweep) Co-Authored-By: Claude Opus 5.5 --- scripts/fixtures/stub-worker.mjs | 7 +- scripts/test-vili-daemon.mjs | 107 +++++++++++++++++++++++++++++++ 2 files changed, 112 insertions(+), 2 deletions(-) diff --git a/scripts/fixtures/stub-worker.mjs b/scripts/fixtures/stub-worker.mjs index cfa1bb9..1ad2ccc 100644 --- a/scripts/fixtures/stub-worker.mjs +++ b/scripts/fixtures/stub-worker.mjs @@ -1,11 +1,11 @@ // Stands in for kimodo-resident-worker.py in the daemon's tests. It binds port 0, prints the ready line the // daemon waits for, and answers /health and /generate with what the daemon gave it. The --model value picks a // misbehaviour: crash-before-ready, hang-before-ready, sick, slow-health, stubborn, fail-generate, -// refuse-generate, drop-generate, slow-generate, writer (appends to .writes every 50 ms, never answers, ignores SIGTERM), slow-to-stop (no answer; prints a line and exits 1.5 s after SIGTERM), chatty (prints a line the moment it is healthy), encoder (a grandchild, then no answer), graceful (exits 0.5 s after SIGTERM), die-after-ready, bvh-outside (lists a BVH outside the job's directory), bvh-link (lists a symlink as its BVH), plant-link (a normal answer with a file symlink and a directory symlink planted beside the BVH). A request with bvh writes .bvh (motion/motion_NN.bvh for several samples) and lists it. Any other value is just the model the worker serves. +// refuse-generate, drop-generate, slow-generate, writer (appends to .writes every 50 ms, never answers, ignores SIGTERM), slow-to-stop (no answer; prints a line and exits 1.5 s after SIGTERM), chatty (prints a line the moment it is healthy), encoder (a grandchild, then no answer), graceful (exits 0.5 s after SIGTERM), die-after-ready, bvh-outside (lists a BVH outside the job's directory), bvh-link (lists a symlink as its BVH), bvh-fifo (lists a FIFO as its BVH), plant-link (a normal answer with a file symlink and a directory symlink planted beside the BVH). A request with bvh writes .bvh (motion/motion_NN.bvh for several samples) and lists it. Any other value is just the model the worker serves. import http from "node:http"; import os from "node:os"; import path from "node:path"; -import { spawn } from "node:child_process"; +import { execFileSync, spawn } from "node:child_process"; import { appendFileSync, mkdirSync, symlinkSync, writeFileSync } from "node:fs"; const argv = process.argv.slice(2); @@ -87,6 +87,9 @@ if (model === "hang-before-ready") { if (model === "bvh-outside") { writeFileSync(outside, "BVH-OUTSIDE\n"); files = [outside]; + } else if (model === "bvh-fifo") { + execFileSync("mkfifo", [`${payload.output}.bvh`]); + files = [`${payload.output}.bvh`]; } else if (model === "bvh-link") { writeFileSync(outside, "BVH-OUTSIDE\n"); symlinkSync(outside, `${payload.output}.bvh`); diff --git a/scripts/test-vili-daemon.mjs b/scripts/test-vili-daemon.mjs index 0dce8fd..d964f48 100644 --- a/scripts/test-vili-daemon.mjs +++ b/scripts/test-vili-daemon.mjs @@ -1869,3 +1869,110 @@ test("the job record lists regular files only: a planted symlink, to a file or t await daemon.stop(); } }); + +// Soul s2: the job id's random suffix is what carries a burst. The clock alone repeats inside one millisecond, and +// the exclusive mkdir's few retries are spent there, so a constant suffix fails a burst and passes every small test. +test("four hundred simultaneous generates each get their own job id, directory and record", async () => { + const daemon = await startDaemon(); + try { + const answers = await Promise.all(Array.from({ length: 400 }, () => generate(daemon))); + assert.deepEqual([...new Set(answers.map((answer) => answer.status))], [200]); + const ids = answers.map((answer) => answer.body.jobId); + for (const id of ids) assert.match(id, /^vili-\d{13}-[0-9a-f]{8}$/); + assert.equal(new Set(ids).size, 400, "no two jobs share an id"); + assert.equal(readdirSync(path.join(daemon.stateRoot, "artifacts")).length, 400); + assert.equal(jobFiles(daemon).length, 400); + } finally { + await daemon.stop(); + } +}); + +// Soul s2: opening a path that blocks (a FIFO with no writer) must not wait. The open is non-blocking and the check +// is made on the open descriptor, so the listed node is refused at once and the filesystem threads stay free. +test("a listed BVH that is a FIFO is refused promptly and other file work proceeds", async () => { + const daemon = await startDaemon(); + const within = (promise, ms, what) => Promise.race([ + promise, + new Promise((_, reject) => setTimeout(() => reject(new Error(`${what} did not settle in ${ms} ms`)), ms)), + ]); + try { + // more than libuv's four filesystem threads: a blocking open per request would starve all of them + const answers = await within(Promise.all(Array.from({ length: 6 }, () => + generate(daemon, exportRequest({ model: "bvh-fifo", clipName: "canary-fifo-clip" })))), 8000, "the FIFO jobs"); + for (const answer of answers) { + assert.equal(answer.status, 502); + assert.equal(answer.body.ok, false); + assert.ok(!answer.raw.includes("canary-fifo-clip"), "the refusal does not echo the clip name"); + } + assert.equal(exportStarts(daemon).length, 0, "no Blender for a node that is not a regular file"); + const other = await within(generate(daemon, exportRequest({ clipName: "after" })), 8000, "an ordinary job"); + assert.equal(other.status, 200); + assert.ok(!daemon.stdout().includes("canary-fifo-clip") && !daemon.stderr().includes("canary-fifo-clip")); + } finally { + await daemon.stop(); + } +}); + +// Soul s2: work/ is a declared state slot, and a daemon that holds the state root sweeps the export directories a +// killed daemon left, those and nothing else. +test("the recipe declares the work directory as a state slot", () => { + const recipe = readFileSync(path.join(here, "..", "deployment", "idunn", "recipe.toml"), "utf8"); + assert.match(recipe, /\[\[state\.slots\]\]\nid = "work"\nrelative_path = "work"\nkind = "external-directory"/); +}); + +test("a restarted daemon sweeps the export directories a killed one left, and touches nothing else", async () => { + const first = await startDaemon(); + let second = null; + try { + const pending = generate(first, exportRequest({ clipName: "slow" })).catch(() => null); + await until(() => exportStarts(first).length === 1, "the export to start"); + const work = path.join(first.stateRoot, "work"); + const [stale] = readdirSync(work); + assert.match(stale, /^export-[A-Za-z0-9]{6}$/); + first.proc.kill("SIGKILL"); + await until(() => first.proc.signalCode !== null, "the daemon to die"); + await pending; + assert.deepEqual(readdirSync(work), [stale], "the killed export left its directory"); + // things under the state root that are not stale export directories + const decoys = { + "work/keep": "K", + "work/export-short/in.bvh": "S", + "work/exports-keep/in.bvh": "E", + "jobs/decoy.json": "J", + "artifacts/decoy/motion.bvh": "A", + "logs/decoy.log": "L", + "decoy-root-file": "R", + }; + for (const [relative, text] of Object.entries(decoys)) { + mkdirSync(path.dirname(path.join(first.stateRoot, relative)), { recursive: true }); + writeFileSync(path.join(first.stateRoot, relative), text); + } + second = await startDaemon({ root: first.root }); + assert.deepEqual(readdirSync(work).sort(), ["export-short", "exports-keep", "keep"], "the stale export is gone, the rest stays"); + for (const [relative, text] of Object.entries(decoys)) assert.equal(readFileSync(path.join(second.stateRoot, relative), "utf8"), text, relative); + assert.equal((await generate(second, exportRequest({ clipName: "after" }))).status, 200); + } finally { + if (first.proc.signalCode === null) first.proc.kill("SIGKILL"); + await (second ?? first).stop(); + } +}); + +test("a daemon that does not hold the state root sweeps nothing", async () => { + const first = await startDaemon(); + let second = null; + try { + const pending = generate(first, exportRequest({ clipName: "slow" })); + await until(() => exportStarts(first).length === 1, "the export to start"); + const work = path.join(first.stateRoot, "work"); + const live = readdirSync(work); + assert.equal(live.length, 1); + second = await startDaemon({ root: first.root, hold: false }); + await until(() => second.proc.exitCode !== null, "the second daemon to refuse", 20); + assert.equal(second.proc.exitCode, 2); + assert.deepEqual(readdirSync(work), live, "the live export's directory is still there"); + assert.equal((await pending).status, 200, "the live export finished"); + } finally { + if (second && second.proc.exitCode === null && second.proc.signalCode === null) second.proc.kill("SIGKILL"); + await first.stop(); + } +}); From 6bdbc27c1c3a0d5226fc91a15710a79d58f16173 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 25 Oct 2026 01:45:14 +0200 Subject: [PATCH 33/36] Fix: a listed BVH is opened non-blocking, and the work directory is a declared state slot swept at start (Soul s2 readinside-opens-before-checking, work-dir-undeclared-unswept) readInside opens O_NONBLOCK|O_NOFOLLOW and checks the open descriptor before reading, so a FIFO is refused at once and holds no filesystem thread. work/ is a slot in the recipe; a daemon that holds the state root creates it and removes stale export-XXXXXX directories from it, nothing else, before it serves. Co-Authored-By: Claude Opus 5.5 --- deployment/idunn/recipe.toml | 9 +++++++++ scripts/vili-daemon.mjs | 29 +++++++++++++++++++++++------ 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/deployment/idunn/recipe.toml b/deployment/idunn/recipe.toml index 9fed140..6dfafef 100644 --- a/deployment/idunn/recipe.toml +++ b/deployment/idunn/recipe.toml @@ -369,6 +369,15 @@ writer = "process-bound-single-writer" recovery = "preserve" startup = "create-or-open-after-write-lease" +[[state.slots]] +id = "work" +relative_path = "work" +kind = "external-directory" +schema = "gamecult.vili.export_scratch.v0" +writer = "process-bound-single-writer" +recovery = "rebuildable" +startup = "create-or-open-after-write-lease" + [[state.slots]] id = "logs" relative_path = "logs" diff --git a/scripts/vili-daemon.mjs b/scripts/vili-daemon.mjs index ba781f6..908ca98 100644 --- a/scripts/vili-daemon.mjs +++ b/scripts/vili-daemon.mjs @@ -3,7 +3,7 @@ import http from "node:http"; import os from "node:os"; import { createHash, randomBytes, randomInt } from "node:crypto"; import { closeSync, constants, lstatSync, openSync, readdirSync, readFileSync, realpathSync, unlinkSync, writeFileSync, writeSync } from "node:fs"; -import { copyFile, mkdir, mkdtemp, open, readFile, rm, writeFile } from "node:fs/promises"; +import { copyFile, mkdir, mkdtemp, open, readdir, readFile, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import readline from "node:readline"; import net from "node:net"; @@ -495,6 +495,11 @@ function regularFileInside(file, directory) { } const exportScript = path.join(__dirname, "bvh-to-fbx.py"); +// The state slot "work" (deployment/idunn/recipe.toml): one private directory per export, removed by the export itself +// and, if the daemon died mid-export, swept by the next daemon that holds the state root (sweepWork). +const WORK_DIR = "work"; +const EXPORT_PREFIX = "export-"; +const EXPORT_NAME = new RegExp(`^${EXPORT_PREFIX}[A-Za-z0-9]{6}$`); const EXPORT_SETTINGS = "standard-tpose soma77 metres hashseed0 time1970"; const EXPORT_TIMEOUT_MS = 120000; let exportScriptDigest = null; @@ -565,11 +570,12 @@ async function probeBlender() { } // The bytes of a regular file strictly inside `directory`, or null. The file is opened without following a symlink -// and the open file is the one checked, so a path swapped after the check cannot redirect the read. +// and without blocking (a FIFO or a device would otherwise hold the open, and a filesystem thread, indefinitely), and +// the open file is the one checked, so a path swapped after the check cannot redirect the read. async function readInside(file, directory) { let handle = null; try { - handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW); + handle = await open(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); const opened = await handle.stat(); if (!opened.isFile() || !regularFileInside(file, directory)) return null; const named = lstatSync(file); @@ -591,9 +597,7 @@ async function exportClip(bvh, fbx, clipName, timeoutMs, artifactDir) { const input = await readInside(bvh, artifactDir); if (input === null) return { error: "fbx-export-refused" }; guard(); - await mkdir(path.join(args.stateRoot, "work"), { recursive: true }); - guard(); - const work = await mkdtemp(path.join(args.stateRoot, "work", "export-")); + const work = await mkdtemp(path.join(args.stateRoot, WORK_DIR, EXPORT_PREFIX)); try { const privateBvh = path.join(work, "in.bvh"); const privateFbx = path.join(work, "out.fbx"); @@ -631,6 +635,17 @@ async function exportClip(bvh, fbx, clipName, timeoutMs, artifactDir) { } } +// The export directories a killed daemon left: only directories named as mkdtemp names them, only under work/. Called +// once, after the runtime holds the state root, so a live daemon's export is never swept. +async function sweepWork() { + const root = path.join(args.stateRoot, WORK_DIR); + for (const entry of await readdir(root, { withFileTypes: true })) { + if (!entry.isDirectory() || !EXPORT_NAME.test(entry.name)) continue; + guard(); + await rm(path.join(root, entry.name), { recursive: true, force: true }); + } +} + // Every BVH the worker listed becomes an FBX, or the job fails. A listed BVH must be a regular file inside the job's // artifact directory, and that is decided when its export begins (exportClip), never earlier. Sample N of several is // _NN. @@ -1184,6 +1199,8 @@ export async function serve(rt) { try { guard(); await mkdir(path.join(args.stateRoot, "jobs"), { recursive: true }); + await mkdir(path.join(args.stateRoot, WORK_DIR), { recursive: true }); + await sweepWork(); await persistSurfaces(); await probeBlender(); } catch (error) { From 8e007cd10d6f40836f3a88804424d7b1a16ba518 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 25 Oct 2026 01:45:14 +0200 Subject: [PATCH 34/36] README: the rest job id is rest-<13-digit ms>-<8 hex>, and the work slot is named (Soul s2 readme-rest-job-id-stale) Co-Authored-By: Claude Opus 5.5 --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 85eb3ee..6a59398 100644 --- a/README.md +++ b/README.md @@ -155,7 +155,7 @@ and the FBX take. With Blender not ready (`backend.blender` is `unconfigured` or The worker never runs Blender. After it answers, the daemon runs the release's Blender (`blender -b --factory-startup --python-use-system-env --python scripts/bvh-to-fbx.py`) on each BVH it listed. The BVH must be a regular file inside the job's artifact directory, opened without following a symlink; Blender is -handed a private copy of it and writes a private FBX in a directory made for that export (`/work/`), and the +handed a private copy of it and writes a private FBX in a directory made for that export (`/work/export-XXXXXX`, the `work` state slot; a daemon that holds the state root sweeps the ones a killed daemon left at start), and the daemon creates the FBX beside the BVH exclusively, so a path planted in the job directory is never read, written through or replaced. The FBX path is the BVH's, derived from the job id, which is the clock plus random bits and is taken by an exclusive mkdir. Blender converts and nothing else: the SOMA77 joint names are Kimodo's, the pose is the standard T-pose in @@ -169,7 +169,7 @@ carries Blender's output. One BVH gives the same FBX bytes on one host body (a fixed hash seed and a fixed time stamp); FBX bytes differ between glibc versions in the last float digits, so the BVH is the cross-body reproducibility unit. -`POST /motion/rest-fbx` exports Kimodo's own standard-T-pose rest skeleton as `SOMA77_Rest.fbx` in a `rest-` job, +`POST /motion/rest-fbx` exports Kimodo's own standard-T-pose rest skeleton as `SOMA77_Rest.fbx` in a `rest-<13-digit ms>-<8 hex>` job, the source for the avatar. `GET /motion/artifacts/{jobId}/{name}` serves `motion.fbx`, `motion.bvh`, `SOMA77_Rest.fbx` and `motion/motion_NN.fbx|bvh` of a job as bytes, read-only; anything else is a 404. From 579244b16635479a14b1e609371b5db91a08a0e8 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 25 Oct 2026 01:49:47 +0200 Subject: [PATCH 35/36] Test: the FIFO refusal's canary is checked outside the job record, which keeps the request by design Co-Authored-By: Claude Opus 5.5 --- scripts/test-vili-daemon.mjs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/test-vili-daemon.mjs b/scripts/test-vili-daemon.mjs index d964f48..a720567 100644 --- a/scripts/test-vili-daemon.mjs +++ b/scripts/test-vili-daemon.mjs @@ -1902,7 +1902,8 @@ test("a listed BVH that is a FIFO is refused promptly and other file work procee for (const answer of answers) { assert.equal(answer.status, 502); assert.equal(answer.body.ok, false); - assert.ok(!answer.raw.includes("canary-fifo-clip"), "the refusal does not echo the clip name"); + const { request: recorded, ...outcome } = answer.body; // the record keeps the request; the refusal itself must not echo it + assert.ok(recorded && !JSON.stringify(outcome).includes("canary-fifo-clip"), "the refusal does not echo the clip name"); } assert.equal(exportStarts(daemon).length, 0, "no Blender for a node that is not a regular file"); const other = await within(generate(daemon, exportRequest({ clipName: "after" })), 8000, "an ordinary job"); From 889c3eb9450ac56d41d4812284b0f65d020fd26b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 25 Oct 2026 01:51:42 +0200 Subject: [PATCH 36/36] Test: the ordinary job after the FIFO jobs names a model, since the resident worker keeps the last one served Co-Authored-By: Claude Opus 5.5 --- scripts/test-vili-daemon.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/test-vili-daemon.mjs b/scripts/test-vili-daemon.mjs index a720567..2bf9a0b 100644 --- a/scripts/test-vili-daemon.mjs +++ b/scripts/test-vili-daemon.mjs @@ -1906,7 +1906,7 @@ test("a listed BVH that is a FIFO is refused promptly and other file work procee assert.ok(recorded && !JSON.stringify(outcome).includes("canary-fifo-clip"), "the refusal does not echo the clip name"); } assert.equal(exportStarts(daemon).length, 0, "no Blender for a node that is not a regular file"); - const other = await within(generate(daemon, exportRequest({ clipName: "after" })), 8000, "an ordinary job"); + const other = await within(generate(daemon, exportRequest({ model: "stub-model", clipName: "after" })), 8000, "an ordinary job"); assert.equal(other.status, 200); assert.ok(!daemon.stdout().includes("canary-fifo-clip") && !daemon.stderr().includes("canary-fifo-clip")); } finally {