Blender add-on: export staging liveness is an OS lock, a failed rollback is refused loudly and recovered by the next export's sweep

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-28 02:10:42 +01:00
commit edb8f70845
4 changed files with 196 additions and 49 deletions

View file

@ -12,7 +12,6 @@ import struct
import subprocess
import sys
import tempfile
import time
import uuid
import zlib
from array import array
@ -21,6 +20,11 @@ from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any, Iterable
if os.name == "nt":
import msvcrt
else:
import fcntl
from . import node_actions as na
from . import scene_actions as sa
from .server_guard import BindRefused, SessionGuard, check_bind, guarded_server_class, is_loopback_host, stop_pending
@ -53,8 +57,8 @@ CREATABLE_OBJECT_TYPES = ("MESH", "LIGHT", "CAMERA", "EMPTY")
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
STAGE_LOCK = ".brokkr-lock"
STAGE_JOURNAL = ".brokkr-journal"
# Actions that only read the scene and so push no undo step.
READ_ACTIONS = ("look",)
@ -878,6 +882,8 @@ class BrokkrBlenderTarget:
name = command.get("filepath")
if not isinstance(name, str):
raise sa.ActionRefused("filepath must be a string.")
if self.output_dir:
_sweep_stale_stages(Path(self.output_dir).resolve())
path = sa.resolve_inside(self.output_dir, name, "output", new_file=True)
suffix = path.suffix.lower()
if suffix not in sa.GLTF_EXTENSIONS:
@ -912,15 +918,15 @@ class BrokkrBlenderTarget:
break
made.append(folder)
stage = None
lock_fd = None
moved: list[tuple[Path, Path]] = []
new_dirs: list[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=EXPORT_STAGE_PREFIX, dir=path.parent))
_LIVE_STAGES.add(stage)
stage, lock_fd = _open_stage(path.parent)
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 []
@ -939,31 +945,52 @@ class BrokkrBlenderTarget:
raise sa.ActionRefused(f"glTF export did not finish: {sorted(result)}")
if not staged.is_file():
raise sa.ActionRefused("glTF export wrote no file.")
written = sorted(f.relative_to(stage) for f in stage.rglob("*") if f.is_file())
written = sorted(f.relative_to(stage) for f in stage.rglob("*") if f.is_file() and f != stage / STAGE_LOCK)
taken = [str(f) for f in written if os.path.lexists(path.parent / f)]
if taken:
raise sa.ActionRefused("output path already exists; output actions never overwrite: " + taken[0])
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:
target = path.parent / relative
for folder in (target.parent, *target.parent.parents):
if folder.exists() or folder == path.parent:
break
new_dirs.append(folder)
target.parent.mkdir(parents=True, exist_ok=True)
os.rename(stage / relative, target)
moved.append((stage / relative, target))
except BaseException as failure:
# A move that fails partway is rolled back: the target is the whole new export or untouched.
stuck = []
for source, target in reversed(moved):
try:
os.rename(target, source)
except OSError:
pass
stuck.append(target)
if lock_fd is not None:
os.close(lock_fd)
if stage is not None and stuck:
# The rollback itself failed: keep the stage with a journal of the files left in the
# target. Its lock is released, so the next export's sweep removes them and the retry works.
(stage / STAGE_JOURNAL).write_text(
"\n".join(t.relative_to(path.parent).as_posix() for t in stuck), encoding="utf-8")
raise sa.ActionRefused(
"glTF export failed and could not be rolled back; files left in the output directory: "
+ ", ".join(t.relative_to(Path(self.output_dir).resolve()).as_posix() for t in stuck)
+ ". The next export removes them.") from failure
if stage is not None:
_LIVE_STAGES.discard(stage)
shutil.rmtree(stage, ignore_errors=True)
for folder in sorted(set(new_dirs), key=lambda f: -len(f.parts)):
try:
folder.rmdir()
except OSError:
pass
for folder in made: # deepest first: only the folders this call made, only if still empty
try:
folder.rmdir()
except OSError:
pass
raise
_LIVE_STAGES.discard(stage)
os.close(lock_fd)
shutil.rmtree(stage, ignore_errors=True)
return self._receipt(command, "accepted", f"Exported glTF to {path} ({path.stat().st_size} bytes).", "")
@ -1567,16 +1594,67 @@ 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
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 _try_lock(fd: int) -> bool:
"""Take an exclusive lock on the file, without waiting; the OS drops it when the holder dies."""
try:
if os.name == "nt":
os.lseek(fd, 0, os.SEEK_SET)
msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)
else:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError:
return False
return True
def _open_stage(parent: Path) -> tuple[Path, int]:
"""A fresh staging folder in parent whose lock file this export holds, locked, until it closes the
descriptor or dies: a held lock is how a sweep knows the stage is live."""
stage = Path(tempfile.mkdtemp(prefix=EXPORT_STAGE_PREFIX, dir=parent))
fd = os.open(stage / STAGE_LOCK, os.O_RDWR | os.O_CREAT)
if not _try_lock(fd):
os.close(fd)
raise OSError(f"could not lock staging folder {stage}")
return stage, fd
def _sweep_stale_stages(top: Path) -> None:
"""Remove every staging folder under top whose lock can be taken: its export is over or its Blender
died. A held lock (an export running now, in any process) leaves the folder alone, and so does a
folder with no lock file yet (an export between creating it and locking it)."""
for root, dirs, _ in os.walk(top):
for name in [d for d in dirs if d.startswith(EXPORT_STAGE_PREFIX)]:
dirs.remove(name)
_sweep_stage(Path(root) / name)
def _sweep_stage(stage: Path) -> None:
try:
fd = os.open(stage / STAGE_LOCK, os.O_RDWR)
except OSError:
return
try:
if not _try_lock(fd):
return
journal = stage / STAGE_JOURNAL
if journal.is_file(): # a failed rollback's leftovers in the target
for line in journal.read_text(encoding="utf-8").splitlines():
relative = Path(line)
if not line or relative.is_absolute() or ".." in relative.parts:
continue
target = stage.parent / relative
if target.is_file() and not target.is_symlink():
target.unlink(missing_ok=True)
for folder in target.parents:
if folder == stage.parent:
break
try:
folder.rmdir()
except OSError:
break
finally:
os.close(fd)
shutil.rmtree(stage, ignore_errors=True)
def _kill_tree(process: "subprocess.Popen[str]") -> None:

View file

@ -198,7 +198,7 @@ gets a `failed` receipt whose message names the rule):
staging folder beside the target and Brokkr then moves each file into place (the `.glb`, or the `.gltf`
with its `.bin` and texture files), refusing the whole export, naming the file, if any of those names is
taken: nothing existing is overwritten. A refused or failed export leaves no file and no new folder, so
the same name can be retried. Not checked: a link or swap made between the check and the move (the
the same name can be retried. Each export holds an OS lock on its staging folder; the next export removes any `.brokkr-export-*` folder under the output directory whose lock is free (its Blender died), and a rollback that itself fails is refused naming the files left, which that same sweep removes. Not checked: a link or swap made between the check and the move (the
same residual as renderStill).
The receipt message carries the written path and byte size. Needs Blender's glTF add-on.
- `setCamera`: `targetObjectName` (a camera object); optional `lens` (mm),

View file

@ -9,7 +9,7 @@
{
"name": "glb accepted",
"ok": true,
"detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-fhcwwdpf\\all.glb (72752 bytes)."
"detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-aa0ee157\\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-fhcwwdpf\\noextras.glb (72720 bytes)."
"detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-aa0ee157\\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-fhcwwdpf\\only.glb (70240 bytes)."
"detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-aa0ee157\\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-fhcwwdpf\\sep\\s.gltf (2840 bytes)."
"detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-aa0ee157\\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-fhcwwdpf\\fresh\\deep\\x.glb (72752 bytes)."
"detail": "Exported glTF to C:\\Users\\Meta\\AppData\\Local\\Temp\\brokkr-export-live-aa0ee157\\fresh\\deep\\x.glb (72752 bytes)."
}
]
}

View file

@ -410,25 +410,94 @@ class ActionTests(unittest.TestCase):
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())
HOLD_STAGE = (
"import sys\n"
"sys.path.insert(0, sys.argv[1])\n"
"import types\n"
"pkg = types.ModuleType('brokkr_bridge'); pkg.__path__ = [sys.argv[1] + '/brokkr_bridge']\n"
"sys.modules['brokkr_bridge'] = pkg\n"
"from brokkr_bridge import blender_target as bt\n"
"from pathlib import Path\n"
"stage, fd = bt._open_stage(Path(sys.argv[2]))\n"
"print(stage, flush=True)\n"
"sys.stdin.read()\n")
def start_export_holding_a_stage(self):
import subprocess
child = subprocess.Popen([sys.executable, "-c", self.HOLD_STAGE, str(ADDON.parent), str(self.root / "out")],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)
self.addCleanup(child.kill)
self.addCleanup(child.wait)
self.addCleanup(child.stdout.close)
self.addCleanup(child.stdin.close)
return child, Path(child.stdout.readline().strip())
def test_a_sweep_spares_another_processs_live_stage_and_removes_a_killed_ones(self):
child, stage = self.start_export_holding_a_stage()
(stage / "a.glb").write_bytes(b"in flight")
os.utime(stage, (0, 0)) # old by any clock: only the lock decides
bt._sweep_stale_stages(self.root / "out")
self.assertTrue((stage / "a.glb").exists())
self.assertEqual(self.run_action(action="exportGltf", filepath="b.glb")["status"], "accepted")
self.assertTrue((stage / "a.glb").exists()) # an export in this process swept too
child.kill()
child.wait()
bt._sweep_stale_stages(self.root / "out")
self.assertFalse(stage.exists())
def test_a_sweep_leaves_a_folder_whose_lock_is_not_made_yet(self):
early = self.root / "out" / ".brokkr-export-early"
early.mkdir()
bt._sweep_stale_stages(self.root / "out")
self.assertTrue(early.exists())
def test_a_failed_rollback_is_refused_loudly_naming_the_files_and_the_next_export_recovers(self):
self.bpy.export_siblings = ["tex1.png"]
real_rename = os.rename
calls = []
def fail_forever_from_third(src, dst):
calls.append(dst)
if len(calls) >= 3:
raise OSError("disk gone")
return real_rename(src, dst)
with mock.patch.object(bt.os, "rename", fail_forever_from_third):
receipt = self.run_action(action="exportGltf", filepath="sub/a.gltf")
self.assertEqual(receipt["status"], "failed")
self.assertIn("could not be rolled back", receipt["message"])
self.assertIn("sub/a.bin", receipt["message"])
self.assertIn("sub/a.gltf", receipt["message"])
self.assertTrue((self.root / "out" / "sub" / "a.bin").exists())
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").rglob("*") if p.is_file()),
["a.bin", "a.gltf", "tex1.png"])
self.assertEqual([p.name for p in (self.root / "out").iterdir()], ["sub"]) # no stage left
def test_a_failed_texture_subfolder_move_leaves_no_empty_folder(self):
self.bpy.export_siblings = []
real_rename = os.rename
def fail_the_texture(src, dst):
if "textures" in str(dst):
raise OSError("no")
return real_rename(src, dst)
orig = self.bpy.export_gltf
def with_subfolder(mode, undo, **kw):
result = orig(mode, undo, **kw)
target = Path(kw["filepath"])
(target.parent / "textures").mkdir()
(target.parent / "textures" / "t.png").write_bytes(b"t")
return result
self.bpy.ops.export_scene.gltf = with_subfolder
with mock.patch.object(bt.os, "rename", fail_the_texture):
receipt = self.run_action(action="exportGltf", filepath="a.gltf")
self.assertEqual(receipt["status"], "failed")
self.assertEqual(list((self.root / "out").iterdir()), [])
def test_export_refuses_a_symlinked_folder(self):
try: