diff --git a/surfaces/blender/brokkr_bridge/blender_target.py b/surfaces/blender/brokkr_bridge/blender_target.py index e030c89..db3a939 100644 --- a/surfaces/blender/brokkr_bridge/blender_target.py +++ b/surfaces/blender/brokkr_bridge/blender_target.py @@ -13,6 +13,7 @@ import struct import subprocess import sys import tempfile +import time import uuid import zlib from array import array @@ -59,7 +60,8 @@ SYNC_RECEIPT_SCHEMA = "brokkr.sync.receipt.v0" GL_RENDER_ENGINES = ("BLENDER_WORKBENCH", "BLENDER_EEVEE", "BLENDER_EEVEE_NEXT") GL_PROBE_TIMEOUT_SECONDS = 120 EXPORT_STAGE_PREFIX = ".brokkr-export-" -STAGE_LOCK = ".brokkr-lock" +LEGACY_STAGE_LOCK = ".brokkr-lock" # older layout: the lock file inside the stage folder +STAGE_LOCK_SUFFIX = ".lock" # the lock file sits beside its stage folder: .lock STAGE_JOURNAL = ".brokkr-journal" LOOK_DIR = "look" # under the output directory: scratch captures named by command id (brush-tree:ruling:look-files-are-scratch) @@ -1062,7 +1064,7 @@ 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() and f != stage / STAGE_LOCK) + written = sorted(f.relative_to(stage) for f in stage.rglob("*") if f.is_file()) 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]) @@ -1083,19 +1085,21 @@ class BrokkrBlenderTarget: os.rename(target, source) except OSError: 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") + # target. The journal is written while the lock is held, so no sweep can take the stage + # first; once the lock is released the next export's sweep removes them and the retry works. + try: + (stage / STAGE_JOURNAL).write_text( + "\n".join(t.relative_to(path.parent).as_posix() for t in stuck), encoding="utf-8") + finally: + os.close(lock_fd) 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: - shutil.rmtree(stage, ignore_errors=True) + _close_stage(stage, lock_fd) for folder in sorted(set(new_dirs), key=lambda f: -len(f.parts)): try: folder.rmdir() @@ -1107,8 +1111,7 @@ class BrokkrBlenderTarget: except OSError: pass raise - os.close(lock_fd) - shutil.rmtree(stage, ignore_errors=True) + _close_stage(stage, lock_fd) return self._receipt(command, "accepted", f"Exported glTF to {path} ({path.stat().st_size} bytes).", "") def _resolve_typed(self, command: dict[str, Any], object_type: str) -> Any: @@ -1704,34 +1707,78 @@ def _try_lock(fd: int) -> bool: return True +def _stage_lock_path(stage: Path) -> Path: + return stage.with_name(stage.name + STAGE_LOCK_SUFFIX) + + 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): + """A fresh staging folder in parent, guarded by a lock file beside it that this export holds until it + closes the descriptor or dies. The lock file is created and locked first and the folder second, so + every stage on disk is either locked-live or sweepable: a kill at any step leaves a lock file a sweep + can take, never a folder no sweep can see.""" + while True: + stage = parent / (EXPORT_STAGE_PREFIX + uuid.uuid4().hex[:16]) + try: + fd = os.open(_stage_lock_path(stage), os.O_RDWR | os.O_CREAT | os.O_EXCL) + except FileExistsError: + continue + break + try: + for attempt in range(5): # a sweep may hold a fresh lock file for an instant + if _try_lock(fd): + break + time.sleep(0.02 * (attempt + 1)) + else: + raise OSError(f"could not lock staging folder {stage}") + stage.mkdir() + except BaseException: os.close(fd) - raise OSError(f"could not lock staging folder {stage}") + _unlink_quietly(_stage_lock_path(stage)) + raise return stage, fd +def _close_stage(stage: Path, fd: int) -> None: + """End a finished stage: remove the folder while the lock is held, then the lock file.""" + shutil.rmtree(stage, ignore_errors=True) + os.close(fd) + _unlink_quietly(_stage_lock_path(stage)) + + +def _unlink_quietly(path: Path) -> None: + """Remove a lock file; where the OS refuses (Windows, a sweeper holds it) the next sweep removes it.""" + try: + path.unlink(missing_ok=True) + except OSError: + pass + + 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): + died. A held lock (an export running now, in any process) leaves the stage alone. A lock file with + no folder is a stage killed before its folder existed. A folder with no sibling lock file is the + older layout, locked by a file inside it, or never locked at all.""" + for root, dirs, files 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) + stage = Path(root) / name + if not _stage_lock_path(stage).exists(): + _sweep_stage(stage, stage / LEGACY_STAGE_LOCK) + for name in files: + if name.startswith(EXPORT_STAGE_PREFIX) and name.endswith(STAGE_LOCK_SUFFIX): + stage = Path(root) / name[:-len(STAGE_LOCK_SUFFIX)] + _sweep_stage(stage, Path(root) / name) -def _sweep_stage(stage: Path) -> None: +def _sweep_stage(stage: Path, lock_path: Path) -> None: try: - fd = os.open(stage / STAGE_LOCK, os.O_RDWR) + fd = os.open(lock_path, os.O_RDWR) + except FileNotFoundError: + fd = None # no lock was ever made for this folder: nothing can hold it except OSError: return try: - if not _try_lock(fd): + if fd is not None and not _try_lock(fd): return journal = stage / STAGE_JOURNAL if journal.is_file(): # a failed rollback's leftovers in the target @@ -1750,8 +1797,11 @@ def _sweep_stage(stage: Path) -> None: except OSError: break finally: - os.close(fd) + if fd is not None: + os.close(fd) shutil.rmtree(stage, ignore_errors=True) + if lock_path.parent != stage: + _unlink_quietly(lock_path) def _kill_tree(process: "subprocess.Popen[str]") -> None: diff --git a/surfaces/blender/tests/test_scene_actions.py b/surfaces/blender/tests/test_scene_actions.py index 0281ba3..ef3ae3b 100644 --- a/surfaces/blender/tests/test_scene_actions.py +++ b/surfaces/blender/tests/test_scene_actions.py @@ -435,11 +435,93 @@ class ActionTests(unittest.TestCase): 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() + def test_a_stage_killed_at_each_step_is_swept_by_the_next_export(self): + out = self.root / "out" + lock_only = out / ".brokkr-export-1.lock" # killed after taking the lock, before making the folder + lock_only.write_bytes(b"") + empty = out / ".brokkr-export-2" # killed after making the folder, before staging anything + empty.mkdir() + (out / ".brokkr-export-2.lock").write_bytes(b"") + mid = out / ".brokkr-export-3" # killed mid-export with files staged + mid.mkdir() + (mid / "a.glb").write_bytes(b"half") + (out / ".brokkr-export-3.lock").write_bytes(b"") + self.assertEqual(self.run_action(action="exportGltf", filepath="b.glb")["status"], "accepted") + self.assertEqual([p.name for p in out.iterdir()], ["b.glb"]) + + def test_a_stage_made_the_old_way_is_swept_with_its_journal_so_the_export_can_retry(self): + out = self.root / "out" + out.mkdir(exist_ok=True) + (out / "a.glb").write_bytes(b"left by a failed rollback") + old = out / ".brokkr-export-old" + old.mkdir() + (old / ".brokkr-lock").write_bytes(b"") + (old / ".brokkr-journal").write_text("a.glb", encoding="utf-8") + unlocked = out / ".brokkr-export-nolock" + unlocked.mkdir() + self.assertEqual(self.run_action(action="exportGltf", filepath="a.glb")["status"], "accepted") + self.assertEqual([p.name for p in out.iterdir()], ["a.glb"]) + self.assertNotEqual((out / "a.glb").read_bytes(), b"left by a failed rollback") + + def test_a_stage_whose_lock_a_sweep_briefly_holds_is_locked_after_a_short_wait(self): + calls = [] + real = bt._try_lock + + def busy_twice(fd): + calls.append(fd) + return len(calls) > 2 and real(fd) + + with mock.patch.object(bt, "_try_lock", busy_twice): + stage, fd = bt._open_stage(self.root / "out") + os.close(fd) + self.assertEqual(len(calls), 3) + + def test_a_lock_file_the_os_will_not_unlink_is_left_for_the_next_sweep(self): + stage, fd = bt._open_stage(self.root / "out") + with mock.patch.object(Path, "unlink", side_effect=PermissionError("held")): + bt._close_stage(stage, fd) # no error + self.assertTrue(bt._stage_lock_path(stage).exists()) bt._sweep_stale_stages(self.root / "out") - self.assertTrue(early.exists()) + self.assertEqual(list((self.root / "out").iterdir()), []) + + def test_every_stage_is_locked_before_its_folder_exists(self): + real_mkdir = Path.mkdir + seen = [] + + def watch(path, *args, **kw): + if path.name.startswith(bt.EXPORT_STAGE_PREFIX): + seen.append(bt._stage_lock_path(path).exists()) + return real_mkdir(path, *args, **kw) + + with mock.patch.object(Path, "mkdir", watch): + stage, fd = bt._open_stage(self.root / "out") + os.close(fd) + self.assertEqual(seen, [True]) + + def test_a_concurrent_sweep_during_a_failed_move_never_loses_the_journal(self): + self.bpy.export_siblings = ["tex1.png"] + real_rename = os.rename + real_write = Path.write_text + calls = [] + + def fail_forever_from_third(src, dst): + calls.append(dst) + if len(calls) >= 3: + raise OSError("disk gone") + return real_rename(src, dst) + + def sweep_then_write(path, *args, **kw): + if path.name == bt.STAGE_JOURNAL: + bt._sweep_stale_stages(self.root / "out") # another export's sweep, mid-failure + self.assertTrue(path.parent.is_dir()) + return real_write(path, *args, **kw) + + with mock.patch.object(bt.os, "rename", fail_forever_from_third), mock.patch.object(Path, "write_text", sweep_then_write): + receipt = self.run_action(action="exportGltf", filepath="sub/a.gltf") + self.assertIn("could not be rolled back", receipt["message"]) + journals = list((self.root / "out").glob("**/" + bt.STAGE_JOURNAL)) + self.assertEqual(len(journals), 1) + self.assertIn("a.bin", journals[0].read_text(encoding="utf-8")) def test_a_failed_rollback_is_refused_loudly_naming_the_files_and_the_next_export_recovers(self): self.bpy.export_siblings = ["tex1.png"]