Blender add-on: roll back a partly moved export, sweep killed exports' staging, probe caches only definite outcomes and kills the child's tree on timeout

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-28 02:06:08 +01:00
commit bbf616f7cd
3 changed files with 156 additions and 16 deletions

View file

@ -7,10 +7,12 @@ import math
import os
import re
import shutil
import signal
import struct
import subprocess
import sys
import tempfile
import time
import uuid
import zlib
from array import array
@ -50,6 +52,9 @@ CREATABLE_OBJECT_TYPES = ("MESH", "LIGHT", "CAMERA", "EMPTY")
# will is found by rendering one pixel in a child Blender (gl_render_failure), not by guessing at libraries.
GL_RENDER_ENGINES = ("BLENDER_WORKBENCH", "BLENDER_EEVEE", "BLENDER_EEVEE_NEXT")
GL_PROBE_TIMEOUT_SECONDS = 120
EXPORT_STAGE_PREFIX = ".brokkr-export-"
_PROCESS_START = time.time()
_LIVE_STAGES: set[Path] = set() # staging folders of exports running now in this process
# Actions that only read the scene and so push no undo step.
READ_ACTIONS = ("look",)
@ -907,12 +912,15 @@ class BrokkrBlenderTarget:
break
made.append(folder)
stage = None
moved: list[tuple[Path, Path]] = []
try:
path.parent.mkdir(parents=True, exist_ok=True)
_sweep_stale_stages(path.parent)
# Re-check after the folders exist and just before use (residual TOCTOU as in renderStill).
if sa.resolve_inside(self.output_dir, name, "output", new_file=True) != path:
raise sa.ActionRefused("Output path changed while it was being checked.")
stage = Path(tempfile.mkdtemp(prefix=".brokkr-export-", dir=path.parent))
stage = Path(tempfile.mkdtemp(prefix=EXPORT_STAGE_PREFIX, dir=path.parent))
_LIVE_STAGES.add(stage)
staged = stage / path.name
# The selection is touched only when one was asked for, and only on view-layer objects.
objects = list(context.view_layer.objects.values()) if chosen else []
@ -938,8 +946,16 @@ class BrokkrBlenderTarget:
for relative in written:
(path.parent / relative).parent.mkdir(parents=True, exist_ok=True)
os.rename(stage / relative, path.parent / relative)
moved.append((stage / relative, path.parent / relative))
except BaseException:
# A move that fails partway is rolled back: the target is the whole new export or untouched.
for source, target in reversed(moved):
try:
os.rename(target, source)
except OSError:
pass
if stage is not None:
_LIVE_STAGES.discard(stage)
shutil.rmtree(stage, ignore_errors=True)
for folder in made: # deepest first: only the folders this call made, only if still empty
try:
@ -947,6 +963,7 @@ class BrokkrBlenderTarget:
except OSError:
pass
raise
_LIVE_STAGES.discard(stage)
shutil.rmtree(stage, ignore_errors=True)
return self._receipt(command, "accepted", f"Exported glTF to {path} ({path.stat().st_size} bytes).", "")
@ -1550,26 +1567,69 @@ def _load_cultmesh(cultlib_py_src: str) -> tuple[Any, Any]:
GL_PROBE_SCRIPT = Path(__file__).with_name("gl_probe.py") # runs inside the child Blender
@functools.lru_cache(maxsize=None)
def _sweep_stale_stages(folder: Path) -> None:
"""Remove staging folders a killed Blender left in folder: not held by an export running in this
process and older than this process (so another Blender's live export is not touched)."""
for entry in folder.glob(EXPORT_STAGE_PREFIX + "*"):
try:
if entry.is_dir() and not entry.is_symlink() and entry not in _LIVE_STAGES \
and entry.stat().st_mtime < _PROCESS_START:
shutil.rmtree(entry, ignore_errors=True)
except OSError:
pass
def _kill_tree(process: "subprocess.Popen[str]") -> None:
"""Kill process and everything it started, so none keeps its output pipe open."""
if os.name == "nt":
subprocess.run(["taskkill", "/F", "/T", "/PID", str(process.pid)], capture_output=True, check=False)
else:
try:
os.killpg(process.pid, signal.SIGKILL)
except OSError:
pass
process.kill()
_GL_PROBES: dict[tuple[str, str], str | None] = {}
def gl_render_failure(binary: str, engine: str) -> str | None:
"""Why a headless render with this engine would not survive on this host, or None when it does.
Renders one pixel in a child process of the same Blender binary: the render aborts the process
it runs in, so only a child can find out. Probed once per binary and engine and cached for the
life of the process; an exit with no completion marker, a signal, or a hang is the failure."""
it runs in, so only a child can find out. A definite outcome (it rendered, or it exited without
finishing) is cached per binary and engine for the life of the process; a hang, an unstartable
binary or an unknown binary is reported but not cached, so the next render probes again."""
if not binary or not os.path.isfile(binary):
return "the Blender binary is unknown, so rendering could not be probed"
if (binary, engine) in _GL_PROBES:
return _GL_PROBES[(binary, engine)]
command = [binary, "--background", "--factory-startup", "--python-exit-code", "1",
"--python", str(GL_PROBE_SCRIPT), "--", engine]
group = {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP} if os.name == "nt" else {"start_new_session": True}
try:
done = subprocess.run(command, capture_output=True, text=True, timeout=GL_PROBE_TIMEOUT_SECONDS, check=False)
except subprocess.TimeoutExpired:
return f"a one-pixel test render did not finish in {GL_PROBE_TIMEOUT_SECONDS} s"
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, **group)
except OSError as exc:
return f"the one-pixel test render could not start: {exc}"
if done.returncode == 0 and "BROKKR_GL_PROBE_OK" in done.stdout:
return None
return f"a one-pixel test render exited with status {done.returncode}"
try:
stdout, _ = process.communicate(timeout=GL_PROBE_TIMEOUT_SECONDS)
except subprocess.TimeoutExpired:
_kill_tree(process)
try:
process.communicate(timeout=10)
except subprocess.TimeoutExpired:
pass
return f"a one-pixel test render did not finish in {GL_PROBE_TIMEOUT_SECONDS} s"
if process.returncode == 0 and "BROKKR_GL_PROBE_OK" in stdout:
outcome = None
else:
outcome = f"a one-pixel test render exited with status {process.returncode}"
_GL_PROBES[(binary, engine)] = outcome
return outcome
gl_render_failure.cache_clear = _GL_PROBES.clear
def _parse_time(value: Any) -> datetime | None:

View file

@ -9,7 +9,7 @@
{
"name": "glb accepted",
"ok": true,
"detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-mp8mip04\\all.glb (72752 bytes)."
"detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-fhcwwdpf\\all.glb (72752 bytes)."
},
{
"name": "glb written, no staging folder",
@ -26,12 +26,12 @@
{
"name": "extras=false leaves them out",
"ok": true,
"detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-mp8mip04\\noextras.glb (72720 bytes)."
"detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-fhcwwdpf\\noextras.glb (72720 bytes)."
},
{
"name": "selection exports only the sphere",
"ok": true,
"detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-mp8mip04\\only.glb (70240 bytes)."
"detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-fhcwwdpf\\only.glb (70240 bytes)."
},
{
"name": "selection restored",
@ -44,7 +44,7 @@
{
"name": "gltf accepted",
"ok": true,
"detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-mp8mip04\\sep\\s.gltf (2840 bytes)."
"detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-fhcwwdpf\\sep\\s.gltf (2840 bytes)."
},
{
"name": "gltf writes its bin and the texture beside it",
@ -108,7 +108,7 @@
{
"name": "the same name then exports",
"ok": true,
"detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-mp8mip04\\fresh\\deep\\x.glb (72752 bytes)."
"detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-fhcwwdpf\\fresh\\deep\\x.glb (72752 bytes)."
}
]
}

View file

@ -389,6 +389,47 @@ class ActionTests(unittest.TestCase):
self.assertEqual(retry["status"], "accepted", retry)
self.assertTrue((self.root / "out" / "new" / "deep" / "a.glb").is_file())
def test_a_move_that_fails_partway_rolls_back_so_the_target_is_untouched_and_retry_works(self):
self.bpy.export_siblings = ["tex1.png", "tex2.png"]
real_rename = os.rename
calls = []
def fail_on_third(src, dst):
calls.append(dst)
if len(calls) == 3:
raise OSError("disk full")
return real_rename(src, dst)
with mock.patch.object(bt.os, "rename", fail_on_third):
receipt = self.run_action(action="exportGltf", filepath="sub/a.gltf")
self.assertEqual(receipt["status"], "failed")
self.assertGreaterEqual(len(calls), 3)
self.assertEqual(list((self.root / "out").iterdir()), []) # nothing moved stays; no staging, no new folder
retry = self.run_action(action="exportGltf", filepath="sub/a.gltf")
self.assertEqual(retry["status"], "accepted", retry)
self.assertEqual(sorted(p.name for p in (self.root / "out" / "sub").iterdir()),
["a.bin", "a.gltf", "tex1.png", "tex2.png"])
def test_an_export_sweeps_staging_folders_a_killed_blender_left_but_not_live_or_newer_ones(self):
import time
old = self.root / "out" / ".brokkr-export-dead"
old.mkdir()
(old / "a.glb").write_bytes(b"partial")
past = bt._PROCESS_START - 3600
os.utime(old, (past, past))
newer = self.root / "out" / ".brokkr-export-other" # another Blender's export in progress
newer.mkdir()
live = self.root / "out" / ".brokkr-export-mine"
live.mkdir()
os.utime(live, (past, past))
bt._LIVE_STAGES.add(live)
self.addCleanup(bt._LIVE_STAGES.discard, live)
receipt = self.run_action(action="exportGltf", filepath="a.glb")
self.assertEqual(receipt["status"], "accepted", receipt)
self.assertFalse(old.exists())
self.assertTrue(newer.exists())
self.assertTrue(live.exists())
def test_export_refuses_a_symlinked_folder(self):
try:
os.symlink(self.root, self.root / "out" / "link")
@ -538,11 +579,50 @@ class ActionTests(unittest.TestCase):
self.assertIn("unknown", bt.gl_render_failure("", "BLENDER_EEVEE"))
self.assertIn("unknown", bt.gl_render_failure(str(self.root / "missing"), "BLENDER_EEVEE"))
def slow_blender(self):
"""A stand-in that starts a child which holds the output pipe for 30 s."""
if os.name == "nt":
path = self.root / "slow_blender.cmd"
path.write_text("@echo off\r\nping -n 30 127.0.0.1 >nul\r\n")
else:
path = self.root / "slow_blender.sh"
path.write_text("#!/bin/sh\nsleep 30\necho BROKKR_GL_PROBE_OK\n")
path.chmod(0o755)
return path
def test_gl_probe_timeout_returns_on_time_killing_the_childs_children_and_is_not_cached(self):
import time
bt.gl_render_failure.cache_clear()
self.addCleanup(bt.gl_render_failure.cache_clear)
slow = self.slow_blender()
with mock.patch.object(bt, "GL_PROBE_TIMEOUT_SECONDS", 1):
started = time.monotonic()
failure = bt.gl_render_failure(str(slow), "BLENDER_EEVEE")
took = time.monotonic() - started
self.assertIn("did not finish", failure)
self.assertLess(took, 10)
# the same binary and engine, now fast: a timeout was not remembered
slow.unlink()
fast = self.fake_blender(0)
os.replace(fast, str(slow.with_suffix(Path(fast).suffix)))
self.assertIsNone(bt.gl_render_failure(str(slow.with_suffix(Path(fast).suffix)), "BLENDER_EEVEE"))
def test_gl_probe_caches_a_definite_abort_and_forgets_an_unstartable_binary(self):
bt.gl_render_failure.cache_clear()
self.addCleanup(bt.gl_render_failure.cache_clear)
binary = self.fake_blender(3)
self.assertIn("status 3", bt.gl_render_failure(binary, "BLENDER_EEVEE"))
self.fake_blender(0) # same path, now a working binary: the abort is still the answer
self.assertIn("status 3", bt.gl_render_failure(binary, "BLENDER_EEVEE"))
with mock.patch.object(bt.subprocess, "Popen", side_effect=OSError("denied")):
self.assertIn("could not start", bt.gl_render_failure(binary, "BLENDER_WORKBENCH"))
self.assertIsNone(bt.gl_render_failure(binary, "BLENDER_WORKBENCH"))
def test_gl_probe_runs_once_per_binary_and_engine(self):
bt.gl_render_failure.cache_clear()
self.addCleanup(bt.gl_render_failure.cache_clear)
binary = self.fake_blender(0)
with mock.patch.object(bt.subprocess, "run", wraps=bt.subprocess.run) as run:
with mock.patch.object(bt.subprocess, "Popen", wraps=bt.subprocess.Popen) as run:
bt.gl_render_failure(binary, "BLENDER_EEVEE")
bt.gl_render_failure(binary, "BLENDER_EEVEE")
bt.gl_render_failure(binary, "BLENDER_WORKBENCH")