The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): a direct desktop build holds the checkout lock an updater takes, then its own
Tekniumfa69864013e5
diff --git a/hermes_cli/desktop_build_lock.py b/hermes_cli/desktop_build_lock.pyindex 52be66e0931..f7641a99457 100644--- a/hermes_cli/desktop_build_lock.py+++ b/hermes_cli/desktop_build_lock.py@@ -17,6 +17,14 @@ class DesktopBuildLock:checkout path. Keeping it out of the checkout preserves ``--skip-build``launches from read-only/prebuilt source trees. The open handle owns thelock, so the OS releases it automatically if a builder crashes.++ The build also writes the checkout an update writes, so the lock first takes the+ checkout lock every updater holds (``update_lock``; review C5), then its own: one lock+ order (checkout, then desktop build) for a direct ``hermes desktop`` build and for the+ update's build (which already holds the checkout lock and only joins it again), and no+ gap in which an updater could take the checkout while npm still writes. Holding the+ checkout lock also puts the build in the update custody (``update_custody``): its+ descendants hold the checkout until they exit."""def __init__(self, project_root: Path) -> None:@@ -25,7 +33,9 @@ class DesktopBuildLock:resolved = os.path.normcase(str(project_root.resolve(strict=False)))checkout_key = hashlib.sha256(resolved.encode("utf-8")).hexdigest()[:24]self.path = get_default_hermes_root() / "locks" / f"desktop-build-{checkout_key}.lock"+ self.project_root = project_rootself._handle: IO[str] | None = None+ self._checkout = Nonedef acquire(self, *, wait: bool = False) -> bool:"""Acquire the lock; queue behind the current holder when ``wait``.@@ -37,7 +47,49 @@ class DesktopBuildLock:"""if self._handle is not None:return True+ if not self._acquire_checkout(wait=wait):+ return False+ try:+ acquired = self._acquire_build_lock(wait=wait)+ except BaseException:+ self._release_checkout()+ raise+ if not acquired:+ self._release_checkout()+ return acquired++ def _acquire_checkout(self, *, wait: bool) -> bool:+ """Take (or, inside an update, join) the checkout lock before the build lock (C5)."""+ import time++ from hermes_cli import update_lock++ held = update_lock._HELD+ if held is not None and held["path"] != str(update_lock.checkout_lock_path(self.project_root)):+ # This process is an update already holding a checkout lock under another spelling+ # of the path: it builds inside that custody. A second acquire would wait on its+ # own lock (and a process records only one hold).+ return True+ lock = update_lock.UpdateLock(install_root=self.project_root, checkout_first=False)+ announced = False+ while not lock.acquire_checkout(self.project_root):+ if lock.holder is not None and lock.holder.reason:+ raise OSError(lock.holder.reason) # never build unserialized; the caller says so+ if not wait:+ return False+ if not announced:+ print("→ Waiting for a running Hermes update to release this checkout...")+ announced = True+ time.sleep(1.0)+ self._checkout = lock+ return True++ def _release_checkout(self) -> None:+ lock, self._checkout = self._checkout, None+ if lock is not None:+ lock.release()+ def _acquire_build_lock(self, *, wait: bool) -> bool:from gateway.status import _try_acquire_file_lockself.path.parent.mkdir(parents=True, exist_ok=True)@@ -86,7 +138,10 @@ class DesktopBuildLock:_release_file_lock(handle)finally:- handle.close()+ try:+ handle.close()+ finally:+ self._release_checkout() # the narrower lock first: the order is checkout, builddef __enter__(self) -> "DesktopBuildLock":if not self.acquire():diff --git a/hermes_cli/main_desktop.py b/hermes_cli/main_desktop.pyindex d0be3038de9..1211e6617ee 100644--- a/hermes_cli/main_desktop.py+++ b/hermes_cli/main_desktop.py@@ -1696,7 +1696,7 @@ def cmd_gui(args: argparse.Namespace):print(" Refusing to run npm without serialization; check the checkout permissions and retry.")sys.exit(1)if not acquired:- print("✗ Another Hermes desktop dependency install or build is already running.")+ print("✗ A Hermes update or another desktop dependency install or build is already running.")print(" Wait for it to finish, then retry.")sys.exit(2)diff --git a/tests/hermes_cli/test_desktop_build_lock.py b/tests/hermes_cli/test_desktop_build_lock.pyindex d3fe40b4559..a280990ab4b 100644--- a/tests/hermes_cli/test_desktop_build_lock.py+++ b/tests/hermes_cli/test_desktop_build_lock.py@@ -238,3 +238,84 @@ def test_update_path_waits_for_a_held_lock(tmp_path, monkeypatch, capsys):assert release_calls == [True], "update path must acquire the lock in wait mode"assert built == [True]++++# --- C5: a direct desktop build and an updater never hold different locks over one checkout ---++_UPDATE_HOLDER = (+ "import sys, time\n"+ "from pathlib import Path\n"+ "from hermes_cli.update_lock import UpdateLock\n"+ "lock = UpdateLock(path=Path(sys.argv[2]), install_root=Path(sys.argv[1]))\n"+ "assert lock.acquire()\n"+ "print('held', flush=True)\n"+ "sys.stdin.read()\n"+)+++def test_a_held_desktop_build_lock_keeps_an_updater_off_the_checkout(tmp_path):+ """C5: a direct ``hermes desktop`` build holds DesktopBuildLock while npm writes the+ checkout; an updater (UpdateLock over the same checkout) must be refused meanwhile."""+ root = _checkout(tmp_path)+ build = DesktopBuildLock(root)+ assert build.acquire() is True+ probe = (+ "import sys\n"+ "from pathlib import Path\n"+ "from hermes_cli.update_lock import UpdateLock\n"+ "lock = UpdateLock(path=Path(sys.argv[2]), install_root=Path(sys.argv[1]))\n"+ "raise SystemExit(23 if not lock.acquire() else 0)\n"+ )+ try:+ result = subprocess.run([sys.executable, "-c", probe, str(root), str(tmp_path / "marker")],+ check=False, timeout=60)+ finally:+ build.release()+ assert result.returncode == 23, "an updater took the checkout while a desktop build held it"+++def test_a_running_update_refuses_a_direct_desktop_build(tmp_path):+ """C5, the other acquisition order: while an updater holds the checkout, a direct build is+ refused before it takes the desktop build lock (one lock order: checkout, then build)."""+ root = _checkout(tmp_path)+ holder = subprocess.Popen([sys.executable, "-c", _UPDATE_HOLDER, str(root), str(tmp_path / "marker")],+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, encoding="utf-8")+ try:+ assert holder.stdout.readline().strip() == "held"+ build = DesktopBuildLock(root)+ assert build.acquire() is False, "a desktop build started while an updater held the checkout"+ assert _desktop_lock_free(root), "a refused build kept the desktop build lock"+ finally:+ holder.communicate("", timeout=30)+ assert DesktopBuildLock(root).acquire() is True # the update released it: the build proceeds+++def _desktop_lock_free(root: Path) -> bool:+ from gateway.status import _release_file_lock, _try_acquire_file_lock++ if not DesktopBuildLock(root).path.exists():+ return True+ with DesktopBuildLock(root).path.open("a+", encoding="utf-8") as handle:+ free = _try_acquire_file_lock(handle)+ if free:+ _release_file_lock(handle)+ return free+++def test_the_updates_own_desktop_build_joins_its_checkout_lock(tmp_path):+ """C5 control: the update path takes DesktopBuildLock while already holding the checkout+ lock; it joins it (never waits on itself) and its release leaves the update's hold intact."""+ from hermes_cli import update_lock++ root = _checkout(tmp_path)+ update = update_lock.UpdateLock(path=tmp_path / "marker", install_root=root)+ assert update.acquire()+ try:+ build = DesktopBuildLock(root)+ assert build.acquire(wait=True) is True+ build.release()+ assert update_lock._HELD is not None and update_lock.checkout_lock_held(root)+ finally:+ update.release()+ assert update_lock._HELD is Nonediff --git a/tests/hermes_cli/test_gui_command.py b/tests/hermes_cli/test_gui_command.pyindex a6ed849c9c6..b5066c1e7e5 100644--- a/tests/hermes_cli/test_gui_command.py+++ b/tests/hermes_cli/test_gui_command.py@@ -131,13 +131,21 @@ def _packaged_exe_rel() -> Path:return Path("linux-unpacked") / "hermes"+def _npm_argv(cmd) -> list:+ """The npm command line inside a build call. A direct ``hermes desktop`` build holds the+ checkout lock (review C5), so on POSIX it runs under the custody launcher+ (``python -I -S -c <reaper> <fds> npm ...``)."""+ cmd = list(cmd)+ return cmd[6:] if cmd[1:4] == ["-I", "-S", "-c"] else cmd++def _pack_into_staging(root: Path, content: str = "", returncode: int = 0):"""``subprocess.run`` side effect mimicking a real ``npm run pack``: laysthe packaged app down inside the STAGING dir named on the command line(never in release/), then returns *returncode*. Non-pack commands (thelaunch) return success."""def _run(cmd, **kwargs):- if len(cmd) >= 3 and cmd[1:3] == ["run", "builder"]:+ if _npm_argv(cmd)[1:3] == ["run", "builder"]:exe = _staging_dir_from(cmd) / _packaged_exe_rel()exe.parent.mkdir(parents=True, exist_ok=True)exe.write_text(content, encoding="utf-8")@@ -1827,7 +1835,7 @@ def test_gui_zero_exit_pack_without_artifact_keeps_previous_app(tmp_path, monkeylive_exe.write_text("good build", encoding="utf-8")def empty_pack(cmd, **kwargs):- if cmd[1:3] == ["run", "builder"]:+ if _npm_argv(cmd)[1:3] == ["run", "builder"]:_staging_dir_from(cmd).mkdir(parents=True, exist_ok=True)return subprocess.CompletedProcess(cmd, 0)