Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(remesh): stop discarding a finished FBX because Blender crashed on the way out

nirholas59d9aa9cd3d9
diff --git a/workers/remesh/README.md b/workers/remesh/README.md
index 733abc9f4..2112d09d4 100644
--- a/workers/remesh/README.md
+++ b/workers/remesh/README.md
@@ -19,12 +19,23 @@ held open.
## Why Blender for FBX
FBX is the only format here that needs Blender: `trimesh` has no FBX writer, so
-every other format is written directly and FBX is bridged through a temporary
-GLB handed to a one-shot headless Blender subprocess (`blender_fbx.py`). A plain
-`convert` of a **rigged** GLB to FBX keeps its bone hierarchy, skin weights, and
-blendshapes — that route (`remesh_mode: "triangle"`, `operation: "convert"`,
-`output_format: "fbx"`) skips the geometry pipelines entirely so the skeleton
-survives. Any geometry-changing op discards the rig and yields a static FBX.
+FBX is bridged through a temporary GLB handed to a one-shot headless Blender
+subprocess (`blender_fbx.py`). USDZ has no trimesh writer either, but it needs no
+Blender: it is authored directly on a USD stage with `pxr` (`_write_usdz` in
+[`main.py`](./main.py)). Every other format trimesh writes itself.
+
+That Blender subprocess exits without running interpreter finalization, and the
+worker judges it by the `FACE_COUNT:` marker it prints rather than by its exit
+status. Tearing `bpy` down after a scene has been loaded segfaults in this
+container: the FBX is written in full, then the process dies during Blender's own
+shutdown. Reading that as a failed export is what made every `output_format:
+"fbx"` request fail until 2026-08-11.
+
+A plain `convert` of a **rigged** GLB to FBX keeps its bone hierarchy, skin
+weights, and blendshapes. That route (`remesh_mode: "triangle"`,
+`operation: "convert"`, `output_format: "fbx"`) skips the geometry pipelines
+entirely so the skeleton survives. Any geometry-changing op discards the rig and
+yields a static FBX.
## Modes
diff --git a/workers/remesh/blender_fbx.py b/workers/remesh/blender_fbx.py
index 7f72165fc..377744e43 100644
--- a/workers/remesh/blender_fbx.py
+++ b/workers/remesh/blender_fbx.py
@@ -24,11 +24,29 @@ On success, prints `FACE_COUNT:<n>` to stdout (polygons across all mesh objects)
from __future__ import annotations
+import os
import sys
from pathlib import Path
import bpy
+
+def _leave(code: int, message: str = "") -> None:
+ """Exit without running interpreter finalization.
+
+ Tearing down the `bpy` module segfaults in the Cloud Run container once a
+ scene has been imported: the FBX is written, `export finished` is printed,
+ and the process then dies with SIGSEGV in Blender's own shutdown. The worker
+ read that exit code as a failed export and discarded a perfectly good file,
+ so every `output_format: "fbx"` request failed. Nothing here needs
+ finalization, so skip it and report the real result."""
+ if message:
+ print(message, file=sys.stderr)
+ sys.stdout.flush()
+ sys.stderr.flush()
+ os._exit(code)
+
+
# Input extensions whose importers ship in the standalone `bpy` wheel. `.dae`
# (Collada) and `.off` are excluded — the wheel doesn't bundle the Collada
# importer and has no OFF importer, so the worker bridges those through a
@@ -102,12 +120,12 @@ def main() -> None:
static = "--static" in args
positional = [a for a in args if not a.startswith("--")]
if len(positional) != 2:
- raise SystemExit("usage: blender_fbx.py <input> <output.fbx> [--static]")
+ _leave(2, "usage: blender_fbx.py <input> <output.fbx> [--static]")
in_path = Path(positional[0])
out_path = Path(positional[1])
if in_path.suffix.lower() not in _IMPORTERS:
- raise SystemExit(f"blender_fbx: cannot import '{in_path.suffix}'")
+ _leave(2, f"blender_fbx: cannot import '{in_path.suffix}'")
_reset_scene()
_import_source(in_path)
@@ -115,9 +133,12 @@ def main() -> None:
_export_fbx(out_path, static)
if not out_path.exists() or out_path.stat().st_size == 0:
- raise SystemExit("blender_fbx: exporter produced no output")
+ _leave(1, "blender_fbx: exporter produced no output")
+ # FACE_COUNT is the worker's completion marker: it is printed only after the
+ # exporter returned and the file was confirmed non-empty.
print(f"FACE_COUNT:{faces}")
+ _leave(0)
if __name__ == "__main__":
diff --git a/workers/remesh/main.py b/workers/remesh/main.py
index 1dc12b73b..f26e54ca3 100644
--- a/workers/remesh/main.py
+++ b/workers/remesh/main.py
@@ -526,13 +526,35 @@ def _write_textured_quad_obj(verts, polys, uvs, image, task_id: str) -> list:
return artifacts
+def _face_count_marker(stdout: str) -> Optional[int]:
+ """Read blender_fbx.py's completion marker, or None when it never got there.
+
+ The child prints `FACE_COUNT:<n>` only after the exporter returned and the
+ written file was confirmed non-empty, which makes it a stronger success
+ signal than the exit code."""
+ for line in stdout.splitlines():
+ if line.startswith("FACE_COUNT:"):
+ try:
+ return int(line.split(":", 1)[1].strip())
+ except ValueError:
+ return None
+ return None
+
+
def _blender_to_fbx(in_path: Path, out_path: Path, static: bool) -> int:
"""Convert a local model file to FBX via headless Blender, preserving the
skeleton, skin weights, and blendshapes when the input carries them.
Returns the exported polygon count. Raises RuntimeError with a clipped log
tail on failure. `static=True` skips animation baking (used when the upstream
- geometry op already discarded any rig)."""
+ geometry op already discarded any rig).
+
+ Completion is judged by the child's FACE_COUNT marker plus a non-empty file,
+ not by its exit status. Blender can die in its own interpreter teardown after
+ a fully written export (this is why every FBX request failed until
+ 2026-08-11), and throwing away a finished file over that is a bug, not
+ caution. `blender_fbx.py` now exits before finalization, so the fallback
+ should never fire; it stays as the guard that keeps a good export."""
cmd = [sys.executable, str(BLENDER_FBX_SCRIPT), str(in_path), str(out_path)]
if static:
cmd.append("--static")
@@ -543,17 +565,19 @@ def _blender_to_fbx(in_path: Path, out_path: Path, static: bool) -> int:
except subprocess.TimeoutExpired as exc:
raise RuntimeError(f"FBX export timed out after {BLENDER_TIMEOUT}s") from exc
- if proc.returncode != 0 or not out_path.exists():
+ faces = _face_count_marker(proc.stdout)
+ written = out_path.exists() and out_path.stat().st_size > 0
+ if faces is None or not written:
tail = (proc.stderr or proc.stdout or "").strip().splitlines()[-6:]
- raise RuntimeError("FBX export failed: " + " | ".join(tail))
+ raise RuntimeError(
+ f"FBX export failed (rc={proc.returncode}): " + " | ".join(tail)
+ )
- faces = 0
- for line in proc.stdout.splitlines():
- if line.startswith("FACE_COUNT:"):
- try:
- faces = int(line.split(":", 1)[1].strip())
- except ValueError:
- faces = 0
+ if proc.returncode != 0:
+ log.warning(
+ "blender exited abnormally (rc=%s) after writing a complete %s-byte FBX; keeping it",
+ proc.returncode, out_path.stat().st_size,
+ )
return faces
diff --git a/workers/remesh/test_remesh.py b/workers/remesh/test_remesh.py
index 970ccc8f9..e8ac5321d 100644
--- a/workers/remesh/test_remesh.py
+++ b/workers/remesh/test_remesh.py
@@ -294,7 +294,13 @@ with tempfile.TemporaryDirectory() as tmp:
names = zipfile.ZipFile(usdz_path).namelist()
check("usdz package carries the usd layer", "smoke.usdc" in names, str(names))
- check("usdz package carries the baked texture", "smoke.png" in names, str(names))
+ # UsdUtils rewrites referenced assets into numbered subdirectories inside
+ # the archive, so match on the file name rather than the authored path.
+ check(
+ "usdz package carries the baked texture",
+ any(name.endswith("smoke.png") for name in names),
+ str(names),
+ )
from pxr import Usd, UsdGeom
@@ -427,12 +433,16 @@ for point in stretch.data:
bpy.ops.export_scene.gltf(filepath=out, export_format="GLB")
"""
-try:
- import bpy # noqa: F401
- has_bpy = True
-except Exception as exc: # pragma: no cover - import guard
- has_bpy = False
- skip("rigged FBX export", f"bpy unavailable ({exc})")
+# Probed in a subprocess, and every bpy call below stays in one too: importing
+# bpy here would leave this process to die in Blender's teardown and report a
+# passing run as a crash.
+_probe = subprocess.run(
+ [sys.executable, "-c", "import bpy; print(bpy.app.version_string)"],
+ capture_output=True, text=True,
+)
+has_bpy = _probe.returncode == 0 or bool(_probe.stdout.strip())
+if not has_bpy:
+ skip("rigged FBX export", f"bpy unavailable ({_probe.stderr.strip()[-200:]})")
if has_bpy:
with tempfile.TemporaryDirectory() as tmp:
diff --git a/workers/remesh/verify_fbx.py b/workers/remesh/verify_fbx.py
index 7f5833178..2a3afb720 100644
--- a/workers/remesh/verify_fbx.py
+++ b/workers/remesh/verify_fbx.py
@@ -19,22 +19,36 @@ installed — the remesh worker image already has it (see requirements.txt).
from __future__ import annotations
+import os
import sys
from pathlib import Path
import bpy
+def _leave(code: int, message: str = "") -> None:
+ """Exit without interpreter finalization.
+
+ Same reason as `blender_fbx.py`: tearing down `bpy` after a scene has been
+ loaded segfaults in the worker container, which would turn this checker's
+ verdict into an indistinguishable SIGSEGV."""
+ if message:
+ print(message, file=sys.stderr)
+ sys.stdout.flush()
+ sys.stderr.flush()
+ os._exit(code)
+
+
def _reset() -> None:
bpy.ops.wm.read_factory_settings(use_empty=True)
def main() -> None:
if len(sys.argv) != 2:
- raise SystemExit("usage: verify_fbx.py <model.fbx>")
+ _leave(2, "usage: verify_fbx.py <model.fbx>")
path = Path(sys.argv[1])
if not path.exists():
- raise SystemExit(f"verify_fbx: no such file: {path}")
+ _leave(2, f"verify_fbx: no such file: {path}")
_reset()
try:
@@ -64,9 +78,10 @@ def main() -> None:
problems.append("no mesh has vertex groups (skin weights lost)")
if problems:
- raise SystemExit("FAIL: " + "; ".join(problems))
+ _leave(1, "FAIL: " + "; ".join(problems))
print("PASS: skeleton + skin weights intact")
+ _leave(0)
if __name__ == "__main__":