diff --git a/README.md b/README.md index 5639475..6a59398 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` 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 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, 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,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` (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) - `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,42 @@ 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 + +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 +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. +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/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 +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-<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. + +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 diff --git a/deployment/idunn/recipe.toml b/deployment/idunn/recipe.toml index 304ad29..6dfafef 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,135 @@ 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-linux-x64" +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 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]] +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" + +[[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]] @@ -67,6 +196,37 @@ 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", + "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]] id = "install-build-tools" phase = "prepare" @@ -93,7 +253,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 +274,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 +299,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 +355,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" @@ -201,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/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:]) diff --git a/scripts/bvh-to-fbx.py b/scripts/bvh-to-fbx.py new file mode 100644 index 0000000..c15b5a5 --- /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 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. +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/fixtures/stub-blender.mjs b/scripts/fixtures/stub-blender.mjs new file mode 100755 index 0000000..a330321 --- /dev/null +++ b/scripts/fixtures/stub-blender.mjs @@ -0,0 +1,65 @@ +#!/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, 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* 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"; +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")) { + console.log("Blender 0.0.0 (stub)"); + console.log("\tbuild date: never"); + 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); +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", () => setInterval(() => console.error("after-sigterm-line"), 100)); + setInterval(() => {}, 1000); +} else { + if (clip.startsWith("slow")) await new Promise((resolve) => setTimeout(resolve, 6000)); + if (clip.startsWith("orphan")) { + const before = grandchildren(); + 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)); + } + writeFbx(); + console.log(result); +} diff --git a/scripts/fixtures/stub-worker.mjs b/scripts/fixtures/stub-worker.mjs index 3cf1831..1ad2ccc 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), 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 { appendFileSync, writeFileSync } from "node:fs"; +import { execFileSync, spawn } from "node:child_process"; +import { appendFileSync, mkdirSync, symlinkSync, writeFileSync } from "node:fs"; const argv = process.argv.slice(2); const flag = (name) => { @@ -81,8 +81,43 @@ 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-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`); + 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`); + 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"); + 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\n"); + symlinkSync(outside, `${payload.output}.link`); + symlinkSync(path.dirname(outside), `${payload.output}-linkdir`); + } 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, @@ -108,6 +143,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/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/test-vili-daemon.mjs b/scripts/test-vili-daemon.mjs index 8b1d9c3..2bf9a0b 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, 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"; @@ -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 }); } }, }; @@ -209,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(); @@ -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); @@ -672,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(); } @@ -789,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 } : {}), }, @@ -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,9 @@ 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.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 { @@ -1289,3 +1322,658 @@ 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.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", + 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`))); + + 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 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" })); + 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; + known.add(left); + 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); + 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(); + } +}); + +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("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"); + 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); + 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 { + await until(() => existsSync(path.join(daemon.stateRoot, "vili.service.cc")), "the service store", 10); + 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)}`); }); + 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); + 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 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 { + 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"); + + // 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`, + `${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(); + } +}); + +// 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(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" } }); + assert.equal(answer.status, 200); + const job = answer.body; + 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"]); + 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(); + } +}); + +// ---- 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", "directory"]) { + 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"); + 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 === "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(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`); + } + } + 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); + 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"); + 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(); + } +}); + +// 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); + 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({ 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 { + 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(); + } +}); diff --git a/scripts/test_bvh_to_fbx.py b/scripts/test_bvh_to_fbx.py new file mode 100644 index 0000000..b8ea8e5 --- /dev/null +++ b/scripts/test_bvh_to_fbx.py @@ -0,0 +1,227 @@ +"""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 struct +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. 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 +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, +} +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) + 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["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: + 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)) + out["reference_hips_curve"] = [list(world("Hips", 1 + i)) for i in range(31)] +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 result(run): + line = next(line for line in run.stdout.splitlines() if line.startswith("VILI-FBX ")) + 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("\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() diff --git a/scripts/verify-blender-selfcontained.sh b/scripts/verify-blender-selfcontained.sh new file mode 100755 index 0000000..b8eb2a2 --- /dev/null +++ b/scripts/verify-blender-selfcontained.sh @@ -0,0 +1,102 @@ +#!/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. (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 '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("--") + 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 +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 +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" diff --git a/scripts/vili-daemon.mjs b/scripts/vili-daemon.mjs index e7977ae..908ca98 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, randomBytes, randomInt } from "node:crypto"; +import { closeSync, constants, lstatSync, openSync, readdirSync, readFileSync, realpathSync, unlinkSync, writeFileSync, writeSync } from "node:fs"; +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"; @@ -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,249 @@ 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"); +// 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; +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; 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(); + 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(), + stdio: ["ignore", "pipe", "pipe"], + shell: false, + detached: true, + }); + exportGroups.add(proc); + const seen = { first: null, result: null }; + 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) => { + 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); + if (sink !== null) closeSync(sink); + sinkOpen = false; + 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, false); + guard(); + blender.version = run.code === 0 && run.first?.startsWith("Blender ") ? run.first : null; +} + +// The bytes of a regular file strictly inside `directory`, or null. The file is opened without following a symlink +// 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 | constants.O_NONBLOCK); + 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(); + 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"); + 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 }); + } +} + +// 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. +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; + 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, artifactDir); + 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,15 +801,37 @@ 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() }); } } +// 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()) { @@ -562,19 +861,40 @@ async function generate(request, response) { return; } - const jobId = `vili-${Date.now()}`; - const artifactDir = path.join(args.stateRoot, "artifacts", jobId); - guard(); - await mkdir(artifactDir, { recursive: true }); - const duration = firstDefined(body.durationSeconds, body.duration, 4); + // 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 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 seed = body.seed === undefined ? null : Number(body.seed); + const seed = askedSeed ?? randomInt(0, SEED_LIMIT); const numSamples = Math.max(1, Number(firstDefined( body.numSamples, body.num_samples, @@ -591,7 +911,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 +935,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 +966,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 +990,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 +1011,66 @@ 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, 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); + 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}-[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); + 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 +1113,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 +1125,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 +1180,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 +1193,16 @@ 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 mkdir(path.join(args.stateRoot, WORK_DIR), { recursive: true }); + await sweepWork(); 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;