Blender export: journal written under the stage lock; stage lock file created before its folder
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
0d4d02437c
commit
2033bdad9f
2 changed files with 102 additions and 30 deletions
|
|
@ -59,7 +59,7 @@ 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"
|
||||
STAGE_LOCK_SUFFIX = ".lock" # the lock file sits beside its stage folder: <stage name>.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 +1062,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 +1083,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 +1109,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,30 +1705,53 @@ 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:
|
||||
if not _try_lock(fd):
|
||||
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}")
|
||||
_stage_lock_path(stage).unlink(missing_ok=True)
|
||||
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)
|
||||
_stage_lock_path(stage).unlink(missing_ok=True)
|
||||
|
||||
|
||||
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)
|
||||
"""Remove every staging folder under top whose lock file can be locked: its export is over or its
|
||||
Blender died. A held lock (an export running now, in any process) leaves the stage alone."""
|
||||
for root, _, files in os.walk(top):
|
||||
for name in files:
|
||||
if name.startswith(EXPORT_STAGE_PREFIX) and name.endswith(STAGE_LOCK_SUFFIX):
|
||||
_sweep_stage(Path(root) / name[:-len(STAGE_LOCK_SUFFIX)])
|
||||
|
||||
|
||||
def _sweep_stage(stage: Path) -> None:
|
||||
lock_path = _stage_lock_path(stage)
|
||||
try:
|
||||
fd = os.open(stage / STAGE_LOCK, os.O_RDWR)
|
||||
fd = os.open(lock_path, os.O_RDWR)
|
||||
except OSError:
|
||||
return
|
||||
try:
|
||||
|
|
@ -1749,9 +1773,10 @@ def _sweep_stage(stage: Path) -> None:
|
|||
folder.rmdir()
|
||||
except OSError:
|
||||
break
|
||||
shutil.rmtree(stage, ignore_errors=True)
|
||||
finally:
|
||||
os.close(fd)
|
||||
shutil.rmtree(stage, ignore_errors=True)
|
||||
lock_path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def _kill_tree(process: "subprocess.Popen[str]") -> None:
|
||||
|
|
|
|||
|
|
@ -435,11 +435,58 @@ 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()
|
||||
bt._sweep_stale_stages(self.root / "out")
|
||||
self.assertTrue(early.exists())
|
||||
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_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"]
|
||||
|
|
|
|||
Loading…
Reference in a new issue