Blender export: sweep old-layout stages and journals; bounded lock retry; tolerate unlink refusal

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-28 07:25:04 +01:00
commit e886ab248d
2 changed files with 73 additions and 13 deletions

View file

@ -13,6 +13,7 @@ import struct
import subprocess
import sys
import tempfile
import time
import uuid
import zlib
from array import array
@ -59,6 +60,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-"
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: <stage name>.lock
STAGE_JOURNAL = ".brokkr-journal"
@ -1722,12 +1724,16 @@ def _open_stage(parent: Path) -> tuple[Path, int]:
continue
break
try:
if not _try_lock(fd):
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)
_stage_lock_path(stage).unlink(missing_ok=True)
_unlink_quietly(_stage_lock_path(stage))
raise
return stage, fd
@ -1736,26 +1742,43 @@ 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)
_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 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):
"""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 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)
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):
_sweep_stage(Path(root) / name[:-len(STAGE_LOCK_SUFFIX)])
stage = Path(root) / name[:-len(STAGE_LOCK_SUFFIX)]
_sweep_stage(stage, Path(root) / name)
def _sweep_stage(stage: Path) -> None:
lock_path = _stage_lock_path(stage)
def _sweep_stage(stage: Path, lock_path: Path) -> None:
try:
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
@ -1773,10 +1796,12 @@ def _sweep_stage(stage: Path) -> None:
folder.rmdir()
except OSError:
break
shutil.rmtree(stage, ignore_errors=True)
finally:
os.close(fd)
lock_path.unlink(missing_ok=True)
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:

View file

@ -449,6 +449,41 @@ class ActionTests(unittest.TestCase):
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.assertEqual(list((self.root / "out").iterdir()), [])
def test_every_stage_is_locked_before_its_folder_exists(self):
real_mkdir = Path.mkdir
seen = []