The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): owner-liveness update marker v2 and a checkout lock held by the whole update tree
Teknium5a7a692af762
diff --git a/.gitignore b/.gitignoreindex 56781d5f0b4..eb08488bcc1 100644--- a/.gitignore+++ b/.gitignore@@ -262,6 +262,8 @@ docs/superpowers/*# — ignore so `git status` stays clean and update's autostash skips them..update-incomplete.update-incomplete.lock+# Kernel lock `hermes update` holds on the checkout (hermes_cli/update_lock.py).+.hermes-update.lock# Checkout fingerprint the __pycache__ tree was last validated against# (launch-time stale-bytecode sweep). Runtime state, never a code change.diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex 8d1dc1172a5..6ebbb4a2231 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -2515,7 +2515,7 @@ def cmd_update(args):describe_holder,)- _update_lock = UpdateLock()+ _update_lock = UpdateLock(install_root=PROJECT_ROOT)if not _update_lock.acquire():print(describe_holder(_update_lock.holder))_finalize_update_output(_update_io_state)diff --git a/hermes_cli/update_completion.py b/hermes_cli/update_completion.pyindex d51d4896fb6..80f1cc11a1e 100644--- a/hermes_cli/update_completion.py+++ b/hermes_cli/update_completion.py@@ -59,10 +59,15 @@ def run_completion(request: dict) -> dict:command = [sys.executable, "-I", "-S", "-u", "-X", "utf8", "-X", f"pycache_prefix={request['bytecode_cache']}",str(root / "hermes_cli/update_completion.py"),str(request_path), str(result_path)]+ from hermes_cli.update_lock import bind_child_to_update_tree, checkout_lock_fds++ # The child joins the update tree's checkout lock: it inherits the locked fd (POSIX)+ # or dies with us (Windows job), so the lock is never free while it runs.proc = subprocess.Popen(command, cwd=root, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,- **({"start_new_session": True} if os.name == "posix" else+ **({"start_new_session": True, "pass_fds": checkout_lock_fds(root)} if os.name == "posix" else{"creationflags": subprocess.CREATE_NO_WINDOW}))+ bind_child_to_update_tree(proc)decoder = codecs.getincrementaldecoder("utf-8")("replace")try:while True:@@ -314,7 +319,10 @@ def _prepare(request: dict, request_path: Path, result_path: Path) -> int:str(request_path), str(result_path), "--prepared"]# A second interpreter is mandatory: PM may have selected a different Python# and dependency graph. No application maintenance runs in this bootstrap.- code = _exit_status(subprocess.call(command, cwd=root, env=activation_environment(root)))+ from hermes_cli.update_lock import checkout_lock_fds++ code = _exit_status(subprocess.call(command, cwd=root, env=activation_environment(root),+ pass_fds=checkout_lock_fds(root)))if not result_path.exists():return _settle_after_commit(request, result_path, "completion",f"the completion process exited {code} without a result")diff --git a/hermes_cli/update_lock.py b/hermes_cli/update_lock.pyindex 34c9050a63f..1f365fa53c2 100644--- a/hermes_cli/update_lock.py+++ b/hermes_cli/update_lock.py@@ -1,9 +1,20 @@"""Cross-process mutual exclusion for in-flight Hermes updates.-The marker file the Tauri updater writes (``UpdateMarkerGuard`` in-``apps/bootstrap-installer/src-tauri/src/update.rs``) and the Electron desktop reads-(``electron/update-marker.ts``) is the single lock for **all** update entrypoints.-Format and location are byte-compatible with both readers.+Two artifacts, one authority each:++* The update marker ``<root hermes home>/.hermes-update-in-progress`` (contract C1, format v2)+ is shared with the Tauri updater (``UpdateMarkerGuard`` in+ ``apps/bootstrap-installer/src-tauri/src/update.rs``), the Electron gate+ (``electron/update-marker.ts``) and the Desktop hand-off scripts. Body::++ <pid>\\n<started_at>\\nct:<owner creation time, 3 decimals>\\n[delegate:<pid> ct:<ct>\\n]++ An owner is live while its pid is alive and its creation time still matches: never by age+ (the 20-minute ceiling only ages out v1 markers, which carry no creation time).+* The checkout lock ``<install root>/.hermes-update.lock`` — a kernel lock (flock / msvcrt)+ that ``hermes update`` holds for its whole process tree, so two updates of one checkout+ started from different homes exclude each other and a killed updater whose completion+ child still runs keeps the checkout locked until that child exits."""from __future__ import annotations@@ -19,12 +30,15 @@ from pathlib import Pathlogger = logging.getLogger(__name__)-# Keep in sync with UPDATE_MARKER_MAX_AGE_MS in apps/desktop/electron/update-marker.ts:-# a shorter ceiling here would let Python steal a lock Electron still considers live.-# A full update (git pull + uv sync + desktop rebuild) is minutes.+# Applies to v1 markers only (no creation-time line): their pid may have been reused, and a+# ceiling is the only way such a marker self-heals. A v2 owner is live for as long as it runs.UPDATE_MARKER_MAX_AGE_SECONDS = 20 * 60+# Clock skew allowed between a recorded and a probed process creation time (C1 rule 3).+CREATE_TIME_TOLERANCE_SECONDS = 2.0+MARKER_NAME = ".hermes-update-in-progress"+CHECKOUT_LOCK_NAME = ".hermes-update.lock"# Set by an orchestrating updater (Tauri `hermes-setup --update`) to its own pid before# spawning `hermes update` as a child stage; the parent holds the marker for its whole run,@@ -42,20 +56,34 @@ _MAX_ANCESTRY_DEPTH = 128# Tauri updater (UPDATE_EXIT_CONCURRENT in update.rs) to show "Hermes is still running".UPDATE_EXIT_CONCURRENT = 2+# msvcrt locks a byte range; lock one byte far past the holder record so other processes can+# still read who holds it (a locked range is unreadable to them on Windows).+_WINDOWS_LOCK_OFFSET = 1 << 20++_FILETIME_UNIX_EPOCH = 116444736000000000+def update_marker_path() -> Path:- """Path of the shared update marker.+ """Path of the shared update marker: always the profile-tree ROOT home.- Uses the *process* Hermes home (never the context-local profile override): the Rust- updater resolves ``$HERMES_HOME`` or the platform default and the desktop pins that same- value into the updater's env, so a profile-scoped path would be one the other owners never look at.+ A sticky or ``-p`` profile re-homes ``HERMES_HOME`` to ``<root>/profiles/<p>``; the Desktop,+ the hand-off scripts and the Tauri updater all look at the root, so a profile-scoped marker+ would be one the other owners never see."""- from hermes_constants import get_process_hermes_home- return get_process_hermes_home() / MARKER_NAME+ from hermes_constants import get_default_hermes_root+ return get_default_hermes_root() / MARKER_NAME+++def _default_install_root() -> Path:+ return Path(__file__).resolve().parents[1]+++def checkout_lock_path(install_root: Path | str | None = None) -> Path:+ return Path(install_root or _default_install_root()) / CHECKOUT_LOCK_NAMEdef _pid_alive(pid: int) -> bool:- """Use the dependency-free, Windows-safe probe before PM is available."""+ """Use the dependency-free, Windows-safe, zombie-aware probe before PM is available."""if pid <= 0:return Falsetry:@@ -66,6 +94,107 @@ def _pid_alive(pid: int) -> bool:return False+# --- process creation time ---------------------------------------------------------------+++def _windows_kernel32():+ import ctypes+ from ctypes import wintypes++ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)+ kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]+ kernel32.OpenProcess.restype = wintypes.HANDLE+ kernel32.GetProcessTimes.argtypes = [wintypes.HANDLE] + [ctypes.POINTER(wintypes.FILETIME)] * 4+ kernel32.GetProcessTimes.restype = wintypes.BOOL+ kernel32.CloseHandle.argtypes = [wintypes.HANDLE]+ kernel32.CloseHandle.restype = wintypes.BOOL+ return kernel32+++def _windows_create_filetime(pid: int) -> int | None:+ """GetProcessTimes creation FILETIME (100 ns ticks since 1601) or ``None``."""+ import ctypes+ from ctypes import wintypes++ kernel32 = _windows_kernel32()+ handle = kernel32.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION+ if not handle:+ return None+ try:+ times = [wintypes.FILETIME() for _ in range(4)]+ if not kernel32.GetProcessTimes(handle, *(ctypes.byref(t) for t in times)):+ return None+ return (times[0].dwHighDateTime << 32) | times[0].dwLowDateTime+ finally:+ kernel32.CloseHandle(handle)+++def _stdlib_create_time(pid: int) -> float | None:+ """Creation time in unix seconds without psutil (``-I -S`` children, early recovery).++ Same clock psutil reports: Linux ``starttime / CLK_TCK + btime``, macOS the kernel start+ time (``ps -o lstart=``, second resolution — inside the 2 s tolerance), Windows the+ ``GetProcessTimes`` creation FILETIME.+ """+ try:+ if sys.platform == "win32":+ ticks = _windows_create_filetime(pid)+ return None if ticks is None else (ticks - _FILETIME_UNIX_EPOCH) / 1e7+ if os.path.isdir("/proc"):+ with open(f"/proc/{pid}/stat", "rb") as fh:+ stat = fh.read()+ start_ticks = int(stat[stat.rindex(b")") + 2:].split()[19])+ with open("/proc/stat", "rb") as fh:+ btime = next(int(line.split()[1]) for line in fh if line.startswith(b"btime "))+ return btime + start_ticks / os.sysconf("SC_CLK_TCK")+ out = subprocess.run(+ ["ps", "-o", "lstart=", "-p", str(pid)], capture_output=True, text=True,+ encoding="utf-8", errors="replace", timeout=5, stdin=subprocess.DEVNULL,+ env={**os.environ, "LC_ALL": "C"},+ ).stdout.strip()+ if not out:+ return None+ return time.mktime(time.strptime(" ".join(out.split()), "%a %b %d %H:%M:%S %Y"))+ except (OSError, ValueError, IndexError, StopIteration, subprocess.SubprocessError, AttributeError):+ return None+++def process_create_time(pid: int | None = None) -> float | None:+ """Creation time of ``pid`` (default: this process) in unix seconds, or ``None``.++ psutil when importable — the value ``process_identity._process_create_time`` records —+ else the stdlib probe of the same kernel clock, so a marker written by either is+ comparable by the other within :data:`CREATE_TIME_TOLERANCE_SECONDS`.+ """+ target = os.getpid() if pid is None else pid+ try:+ import psutil+ except ImportError:+ return _stdlib_create_time(target)+ try:+ return float(psutil.Process(target).create_time())+ except Exception:+ return _stdlib_create_time(target)+++def _identity_live(pid: int, create_time: float | None) -> bool:+ """C1 rule 3 for one (pid, ct) identity: alive, not a zombie, and not a reused pid."""+ if not _pid_alive(pid):+ return False+ if create_time is None:+ return True+ actual = process_create_time(pid)+ return actual is None or abs(actual - create_time) <= CREATE_TIME_TOLERANCE_SECONDS+++def _identity_line(pid: int | None = None) -> str:+ ct = process_create_time(pid)+ return "" if ct is None else f"ct:{ct:.3f}"+++# --- ancestry ----------------------------------------------------------------------------++def _handoff_pid() -> int | None:"""Pid of the orchestrating updater that spawned us (:data:`HANDOFF_PID_ENV`); malformedvalues count as absent so a broken handoff falls back to the normal refusal."""@@ -94,30 +223,12 @@ def _windows_parent_pid(pid: int) -> int | None:("dwFlags", wintypes.DWORD), ("szExeFile", ctypes.c_wchar * 260),]- kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)+ kernel32 = _windows_kernel32()kernel32.CreateToolhelp32Snapshot.argtypes = [wintypes.DWORD, wintypes.DWORD]kernel32.CreateToolhelp32Snapshot.restype = wintypes.HANDLEfor walk in (kernel32.Process32FirstW, kernel32.Process32NextW):walk.argtypes = [wintypes.HANDLE, ctypes.POINTER(PROCESSENTRY32W)]walk.restype = wintypes.BOOL- kernel32.OpenProcess.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]- kernel32.OpenProcess.restype = wintypes.HANDLE- kernel32.GetProcessTimes.argtypes = [wintypes.HANDLE] + [ctypes.POINTER(wintypes.FILETIME)] * 4- kernel32.GetProcessTimes.restype = wintypes.BOOL- kernel32.CloseHandle.argtypes = [wintypes.HANDLE]- kernel32.CloseHandle.restype = wintypes.BOOL-- def created(target: int) -> int | None:- handle = kernel32.OpenProcess(0x1000, False, target) # PROCESS_QUERY_LIMITED_INFORMATION- if not handle:- return None- try:- times = [wintypes.FILETIME() for _ in range(4)]- if not kernel32.GetProcessTimes(handle, *(ctypes.byref(t) for t in times)):- return None- return (times[0].dwHighDateTime << 32) | times[0].dwLowDateTime- finally:- kernel32.CloseHandle(handle)snapshot = kernel32.CreateToolhelp32Snapshot(0x2, 0) # TH32CS_SNAPPROCESSif not snapshot or snapshot == ctypes.c_void_p(-1).value:@@ -136,7 +247,7 @@ def _windows_parent_pid(pid: int) -> int | None:kernel32.CloseHandle(snapshot)if not parent:return None- parent_created, child_created = created(parent), created(pid)+ parent_created, child_created = _windows_create_filetime(parent), _windows_create_filetime(pid)if parent_created is not None and child_created is not None and parent_created > child_created:return Nonereturn parent@@ -164,6 +275,7 @@ def _stdlib_parent_pid(pid: int) -> int | None:out = subprocess.run(["ps", "-o", "ppid=", "-p", str(pid)],capture_output=True, text=True, encoding="utf-8", errors="replace", check=True, timeout=5,+ stdin=subprocess.DEVNULL,).stdoutvalue = int(out.strip() or -1)return value if value > 0 else None@@ -245,45 +357,163 @@ def _is_ancestor_pid(pid: int) -> bool:return False+# --- the marker --------------------------------------------------------------------------++@dataclass(frozen=True)class UpdateHolder:- """A confirmed-live update currently holding the lock."""+ """A confirmed-live update holding the lock, or the reason a claim was refused."""pid: intage_seconds: float+ reason: str | None = None-def read_live_update(*, path: Path | None = None) -> UpdateHolder | None:- """Return the live update holding the lock, or ``None``.+@dataclass(frozen=True)+class _Marker:+ raw: bytes+ pid: int+ started_at: float | None+ create_time: float | None+ delegate_pid: int | None+ delegate_create_time: float | None- Mirrors ``readLiveUpdateMarker`` in ``electron/update-marker.ts``: absent, unreadable,- malformed, dead-pid, and past-the-ceiling all mean "no live update", and a stale marker- file is deleted so it can't strand future runs. Never raises.- """- marker = path or update_marker_path()- try:- lines = marker.read_text(encoding="utf-8-sig").splitlines()- except OSError:+ @property+ def base(self) -> bytes:+ """Lines 1–3 exactly as written (what a delegate keeps byte-identical)."""+ return b"".join(self.raw.splitlines(keepends=True)[:3])++ def age(self) -> float:+ return time.time() - self.started_at if self.started_at is not None else float("inf")++ def owner_live(self) -> bool:+ if self.create_time is None and self.age() > UPDATE_MARKER_MAX_AGE_SECONDS:+ return False # v1 marker: pid-only, so only a ceiling can expose a reused pid+ return _identity_live(self.pid, self.create_time)++ def delegate_live(self) -> bool:+ return self.delegate_pid is not None and _identity_live(self.delegate_pid, self.delegate_create_time)++ def live_pid(self) -> int | None:+ if self.owner_live():+ return self.pid+ return self.delegate_pid if self.delegate_live() else None+++def _parse_ct(text: str) -> float | None:+ text = text.strip()+ if not text.startswith("ct:"):return Nonetry:- pid = int(lines[0].strip())- except (IndexError, ValueError):- pid = -1+ return float(text[3:])+ except ValueError:+ return None+++def _parse_marker(raw: bytes) -> _Marker:+ lines = raw.decode("utf-8-sig", errors="replace").splitlines()++ def field(index: int, cast):+ try:+ return cast(lines[index].strip())+ except (IndexError, ValueError):+ return None++ delegate_pid = delegate_ct = None+ if len(lines) > 3 and lines[3].startswith("delegate:"):+ head, _, tail = lines[3][len("delegate:"):].partition(" ")+ with suppress(ValueError):+ delegate_pid = int(head)+ delegate_ct = _parse_ct(tail)+ pid = field(0, int)+ return _Marker(+ raw=raw, pid=pid if pid is not None else -1, started_at=field(1, float),+ create_time=_parse_ct(lines[2]) if len(lines) > 2 else None,+ delegate_pid=delegate_pid, delegate_create_time=delegate_ct,+ )+++def _read_bytes(path: Path) -> bytes | None:try:- started_at = float(lines[1].strip())- except (IndexError, ValueError):- started_at = float("-inf")+ return path.read_bytes()+ except OSError:+ return None+++def _compare_and_delete(path: Path, expected: bytes) -> bool:+ """Delete ``path`` only while it still holds exactly ``expected`` (C1 rule 5)."""+ if _read_bytes(path) != expected:+ return False+ with suppress(FileNotFoundError):+ path.unlink()+ return True- age = time.time() - started_at- if not _pid_alive(pid) or age > UPDATE_MARKER_MAX_AGE_SECONDS:++def _compare_and_swap(path: Path, expected: bytes, new: bytes) -> bool:+ """Atomically replace ``path`` (tmp + ``os.replace``) only while it still holds ``expected``."""+ if _read_bytes(path) != expected:+ return False+ tmp = path.with_name(f"{path.name}.{os.getpid()}.tmp")+ try:+ with open(tmp, "wb") as fh:+ fh.write(new)+ fh.flush()+ os.fsync(fh.fileno())+ if _read_bytes(path) != expected:+ return False+ os.replace(tmp, path)+ return True+ except OSError as exc:+ logger.debug("Could not rewrite update marker %s: %s", path, exc)+ return False+ finally:with suppress(OSError):- marker.unlink()+ tmp.unlink()+++def _live_partners(marker: _Marker) -> list[int]:+ """Live identities behind a marker: the owner, then the delegate.++ A v1 marker naming our own pid is a killed update's claim whose pid this run inherited+ (containers restart pid numbering), not ours: without a creation time it cannot be told+ apart, and nothing pre-writes a v1 marker for this process.+ """+ partners = []+ if marker.owner_live() and not (marker.pid == os.getpid() and marker.create_time is None):+ partners.append(marker.pid)+ if marker.delegate_live():+ partners.append(marker.delegate_pid)+ return partners+++def read_live_update(*, path: Path | None = None) -> UpdateHolder | None:+ """Return the live update holding the marker, or ``None``.++ Mirrors ``readLiveUpdateMarker`` in ``electron/update-marker.ts``: absent, unreadable,+ malformed and dead-owner all mean "no live update", and a dead marker is removed with+ compare-and-delete so it can't strand future runs. Never raises.+ """+ marker = path or update_marker_path()+ raw = _read_bytes(marker)+ if raw is None:return None- return UpdateHolder(pid=pid, age_seconds=age)+ parsed = _parse_marker(raw)+ live = parsed.live_pid()+ if live is None:+ _compare_and_delete(marker, raw)+ return None+ return UpdateHolder(pid=live, age_seconds=parsed.age() if parsed.started_at is not None else 0.0)def describe_holder(holder: UpdateHolder | None) -> str:"""One-line, user-facing explanation of who holds the update lock."""+ if holder is not None and holder.reason:+ return (+ f"✗ Cannot lock this install for the update: {holder.reason}.\n"+ "\n"+ " Updating without the lock could let two updates corrupt the install.\n"+ " Run `hermes update` as the user that owns the install."+ )minutes, seconds = divmod(int(max(0 if holder is None else holder.age_seconds, 0)), 60)elapsed = f"{minutes}m {seconds}s" if minutes else f"{seconds}s"who = f", process {holder.pid}" if holder else ""@@ -296,62 +526,315 @@ def describe_holder(holder: UpdateHolder | None) -> str:)+# --- the checkout lock -------------------------------------------------------------------++# This process's hold on the checkout lock: {"path", "fd", "owned", "depth"}. "owned" means+# we opened and locked it; otherwise the fd was inherited from the `hermes update` that holds+# it (pass_fds) and belongs to the whole tree — it is never unlocked or closed here.+_HELD: dict | None = None+_JOBS: list = []+++def _try_lock(fd: int) -> bool:+ if sys.platform == "win32":+ import msvcrt++ os.lseek(fd, _WINDOWS_LOCK_OFFSET, os.SEEK_SET)+ try:+ msvcrt.locking(fd, msvcrt.LK_NBLCK, 1)+ except OSError:+ return False+ return True+ import fcntl++ try:+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)+ except BlockingIOError:+ return False+ return True+++def _unlock(fd: int) -> None:+ if sys.platform == "win32":+ import msvcrt++ with suppress(OSError):+ os.lseek(fd, _WINDOWS_LOCK_OFFSET, os.SEEK_SET)+ msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)+++def _inherited_lock_fd(path: Path) -> int | None:+ """An fd this process inherited that holds the lock on ``path`` (POSIX ``pass_fds``)."""+ if sys.platform == "win32":+ return None+ try:+ target = os.stat(path)+ fd_dir = "/proc/self/fd" if os.path.isdir("/proc/self/fd") else "/dev/fd"+ candidates = [int(name) for name in os.listdir(fd_dir) if name.isdigit()]+ except OSError:+ return None+ import fcntl++ for fd in candidates:+ try:+ st = os.fstat(fd)+ if (st.st_dev, st.st_ino) != (target.st_dev, target.st_ino):+ continue+ # Succeeds only when this open file description already holds the lock (or the+ # lock is free, in which case taking it on an fd we hold is still correct).+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)+ return fd+ except OSError:+ continue+ return None+++def _lock_holder(fd_or_path) -> UpdateHolder:+ raw = _read_bytes(fd_or_path) or b""+ parsed = _parse_marker(raw)+ return UpdateHolder(pid=max(parsed.pid, 0), age_seconds=parsed.age() if parsed.started_at else 0.0)+++def _acquire_checkout(install_root: Path) -> UpdateHolder | None:+ """Take (or join, when inherited) the checkout lock; the refusal holder, else ``None``."""+ global _HELD+ path = checkout_lock_path(install_root)+ if _HELD is not None and _HELD["path"] == str(path):+ _HELD["depth"] += 1+ return None+ inherited = _inherited_lock_fd(path)+ if inherited is not None:+ _HELD = {"path": str(path), "fd": inherited, "owned": False, "depth": 1}+ return None+ try:+ fd = os.open(path, os.O_RDWR | os.O_CREAT | getattr(os, "O_BINARY", 0), 0o644)+ except OSError as exc:+ return UpdateHolder(pid=0, age_seconds=0.0,+ reason=f"{path} is not writable ({exc.strerror or exc})")+ try:+ if not _try_lock(fd):+ os.close(fd)+ return _lock_holder(path)+ record = f"{os.getpid()}\n{int(time.time())}\n{_identity_line()}\n".encode()+ os.lseek(fd, 0, os.SEEK_SET)+ os.ftruncate(fd, 0)+ os.write(fd, record)+ except OSError as exc:+ _unlock(fd)+ os.close(fd)+ return UpdateHolder(pid=0, age_seconds=0.0, reason=f"{path} could not be locked ({exc})")+ _HELD = {"path": str(path), "fd": fd, "owned": True, "depth": 1}+ return None+++def _release_checkout() -> None:+ global _HELD+ if _HELD is None:+ return+ _HELD["depth"] -= 1+ if _HELD["depth"] > 0:+ return+ held, _HELD = _HELD, None+ if held["owned"]:+ # Close, never LOCK_UN: flock belongs to the open file description, which completion+ # children share through pass_fds. A survivor keeps the checkout locked until it exits.+ _unlock(held["fd"])+ with suppress(OSError):+ os.close(held["fd"])+++def checkout_lock_fds(install_root: Path | str | None = None) -> tuple[int, ...]:+ """Fds a child of the update tree must inherit (``subprocess`` ``pass_fds``) so the+ checkout stays locked while it runs, even after its parent is killed. POSIX only."""+ if sys.platform == "win32":+ return ()+ if _HELD is not None:+ return (_HELD["fd"],)+ fd = _inherited_lock_fd(checkout_lock_path(install_root))+ return () if fd is None else (fd,)+++def bind_child_to_update_tree(proc: subprocess.Popen) -> None:+ """Windows: put an update-tree child in a kill-on-close job owned by this process, so the+ child (and everything it spawns) dies when the lock owner dies and frees the lock.++ POSIX children inherit the lock fd instead (:func:`checkout_lock_fds`).+ """+ if sys.platform != "win32":+ return+ import ctypes+ from ctypes import wintypes++ class _Basic(ctypes.Structure):+ _fields_ = [("PerProcessUserTimeLimit", ctypes.c_int64), ("PerJobUserTimeLimit", ctypes.c_int64),+ ("LimitFlags", wintypes.DWORD), ("MinimumWorkingSetSize", ctypes.c_size_t),+ ("MaximumWorkingSetSize", ctypes.c_size_t), ("ActiveProcessLimit", wintypes.DWORD),+ ("Affinity", ctypes.c_size_t), ("PriorityClass", wintypes.DWORD),+ ("SchedulingClass", wintypes.DWORD)]++ class _Extended(ctypes.Structure):+ _fields_ = [("BasicLimitInformation", _Basic), ("IoInfo", ctypes.c_ulonglong * 6),+ ("ProcessMemoryLimit", ctypes.c_size_t), ("JobMemoryLimit", ctypes.c_size_t),+ ("PeakProcessMemoryUsed", ctypes.c_size_t), ("PeakJobMemoryUsed", ctypes.c_size_t)]++ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)+ kernel32.CreateJobObjectW.argtypes = [ctypes.c_void_p, wintypes.LPCWSTR]+ kernel32.CreateJobObjectW.restype = wintypes.HANDLE+ kernel32.SetInformationJobObject.argtypes = [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD]+ kernel32.SetInformationJobObject.restype = wintypes.BOOL+ kernel32.AssignProcessToJobObject.argtypes = [wintypes.HANDLE, wintypes.HANDLE]+ kernel32.AssignProcessToJobObject.restype = wintypes.BOOL+ job = kernel32.CreateJobObjectW(None, None) # unnamed, non-inheritable: only we hold it+ if not job:+ raise ctypes.WinError(ctypes.get_last_error())+ limits = _Extended()+ limits.BasicLimitInformation.LimitFlags = 0x2000 # JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE+ if not kernel32.SetInformationJobObject(job, 9, ctypes.byref(limits), ctypes.sizeof(limits)) \+ or not kernel32.AssignProcessToJobObject(job, int(proc._handle)):+ raise ctypes.WinError(ctypes.get_last_error())+ _JOBS.append(job) # never closed: the handle closes when this process dies, killing the tree+++def update_in_progress(install_root: Path | str | None = None) -> bool:+ """True while an update owns this install: a LIVE marker or a held checkout lock."""+ if read_live_update() is not None:+ return True+ path = checkout_lock_path(install_root)+ if _HELD is not None and _HELD["path"] == str(path):+ return True+ try:+ fd = os.open(path, os.O_RDONLY | getattr(os, "O_BINARY", 0))+ except OSError:+ return False+ try:+ if not _try_lock(fd):+ return True+ _unlock(fd)+ return False+ except OSError:+ return False+ finally:+ os.close(fd)+++# --- the lock object ---------------------------------------------------------------------++class UpdateLock:- """Context manager owning the shared update marker for this process.+ """Context manager owning the shared update marker (and, with ``install_root``, the+ checkout lock) for this process.- ``acquired`` is False when another live update holds it; callers decide between hard- refusal (CLI/dashboard) and waiting. Release only removes the marker when *we* still own- it, so a marker rewritten by a handoff partner (the Tauri updater writes its own pid) is- never deleted from under its new owner.+ ``acquired`` is True when we wrote the marker; adopting a live partner's claim (hand-off+ pid, ancestor, or an outer claim of this same process) succeeds with ``acquired`` False.+ ``acquire`` returns False (and sets ``holder``) when another live update owns either lock+ or the lock cannot be created at all — never "proceed unlocked"."""- def __init__(self, *, path: Path | None = None) -> None:+ def __init__(self, *, path: Path | None = None, install_root: Path | str | None = None) -> None:self.path = path or update_marker_path()+ self.install_root = None if install_root is None else Path(install_root)self.acquired = Falseself.holder: UpdateHolder | None = None+ self._written: bytes | None = None+ self._delegate_base: bytes | None = None+ self._checkout = Falsedef acquire(self) -> bool:- """Claim the lock. Returns False (and sets ``holder``) if it's taken.-- A live holder whose pid matches :data:`HANDOFF_PID_ENV` — or is an ancestor of ours —- is our own orchestrating parent: run under ITS claim and leave its marker untouched on- release. The ancestry path covers staged updaters older than the env-var export.- """- existing = read_live_update(path=self.path)- # A live claim naming our own pid is a killed update's marker whose pid this retry- # inherited (containers restart pid numbering): no other live process has our pid, and- # nothing pre-writes a marker for `hermes update` (it always runs under a parent's claim).- # It is a new attempt, so it is claimed fresh like a dead holder's. Keeping the old- # started_at would let the ceiling expire mid-run and admit a second updater.- if existing is not None and existing.pid != os.getpid():- if existing.pid == _handoff_pid() or _is_ancestor_pid(existing.pid):- return True- self.holder = existing- return False+ if self.install_root is not None:+ refused = _acquire_checkout(self.install_root)+ if refused is not None:+ self.holder = refused+ return False+ self._checkout = True+ try:+ ok = self._claim_marker()+ except BaseException:+ self._drop_checkout()+ raise+ if not ok:+ self._drop_checkout()+ return ok++ def _claim_marker(self) -> bool:try:self.path.parent.mkdir(parents=True, exist_ok=True)- self.path.write_text(f"{os.getpid()}\n{int(time.time())}\n", encoding="utf-8")except OSError as exc:- # Best-effort, like the Rust guard: an unwritable marker must not block the- # update itself (worse than the race it prevents). Degrade to pre-lock behavior.- logger.debug("Could not write update marker %s: %s", self.path, exc)+ self.holder = UpdateHolder(pid=0, age_seconds=0.0, reason=f"{self.path.parent} is not writable ({exc})")+ return False+ body = f"{os.getpid()}\n{int(time.time())}\n{_identity_line()}\n".encode()+ for attempt in range(2):+ try:+ fd = os.open(self.path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_BINARY", 0), 0o644)+ except FileExistsError:+ raw = _read_bytes(self.path)+ if raw is None:+ continue # vanished between create and read: retry the create+ existing = _parse_marker(raw)+ if _live_partners(existing):+ return self._adopt_or_refuse(existing)+ if attempt == 0 and _compare_and_delete(self.path, raw):+ continue+ self.holder = UpdateHolder(pid=max(existing.pid, 0), age_seconds=0.0)+ return False+ except OSError as exc:+ self.holder = UpdateHolder(pid=0, age_seconds=0.0, reason=f"{self.path} is not writable ({exc})")+ return False+ try:+ os.write(fd, body)+ os.fsync(fd)+ finally:+ os.close(fd)+ self._written = body+ self.acquired = Truereturn True- self.acquired = True+ self.holder = read_live_update(path=self.path) or UpdateHolder(pid=0, age_seconds=0.0)+ return False++ def _adopt_or_refuse(self, existing: _Marker) -> bool:+ """C1 rule 4: a LIVE claim by us, an ancestor or the hand-off partner is run under."""+ partners = _live_partners(existing)+ if os.getpid() not in partners and not any(+ p == _handoff_pid() or _is_ancestor_pid(p) for p in partners):+ self.holder = UpdateHolder(pid=partners[0], age_seconds=existing.age() if existing.started_at else 0.0)+ return False+ if os.getpid() not in partners and existing.delegate_pid not in partners \+ and existing.create_time is not None:+ # Rule 6: name ourselves as the delegate so the claim stays visible if the partner+ # (a hand-off script, the Tauri updater) dies while this update still runs.+ delegated = existing.base + f"delegate:{os.getpid()} {_identity_line()}\n".encode()+ if _compare_and_swap(self.path, existing.raw, delegated):+ self._written, self._delegate_base = delegated, existing.basereturn True+ def _drop_checkout(self) -> None:+ if self._checkout:+ self._checkout = False+ _release_checkout()+def release(self) -> None:- """Drop the marker if this process still owns it. Never raises."""- if not self.acquired:- return- self.acquired = False+ """Give back what we wrote (compare-and-delete / compare-and-swap). Never raises."""try:- owner = int(self.path.read_text(encoding="utf-8-sig").splitlines()[0].strip())- except (OSError, IndexError, ValueError):- return- if owner != os.getpid():- return # a handoff partner took ownership — still a live update- with suppress(OSError):- self.path.unlink()+ if self._written is not None:+ current = _read_bytes(self.path)+ if current is None:+ pass+ elif self.acquired:+ if current == self._written:+ _compare_and_delete(self.path, current)+ elif current.startswith(self._written) \+ and not _parse_marker(current).delegate_live():+ _compare_and_delete(self.path, current) # our claim + a dead delegate+ elif current == self._written and self._delegate_base is not None:+ if _parse_marker(self._delegate_base).owner_live():+ _compare_and_swap(self.path, current, self._delegate_base)+ else:+ _compare_and_delete(self.path, current)+ except OSError as exc:+ logger.debug("Could not release update marker %s: %s", self.path, exc)+ finally:+ self.acquired = False+ self._written = self._delegate_base = None+ self._drop_checkout()def __enter__(self) -> "UpdateLock":self.acquire()diff --git a/tests/hermes_cli/test_update_lock.py b/tests/hermes_cli/test_update_lock.pyindex 325bb0303cd..70c6d1c8f82 100644--- a/tests/hermes_cli/test_update_lock.py+++ b/tests/hermes_cli/test_update_lock.py@@ -28,8 +28,12 @@ from hermes_cli.update_lock import (HANDOFF_PID_ENV,UPDATE_MARKER_MAX_AGE_SECONDS,UpdateLock,+ checkout_lock_fds,+ checkout_lock_path,describe_holder,+ process_create_time,read_live_update,+ update_in_progress,update_marker_path,)@@ -58,17 +62,26 @@ def other_pid():def _claim(marker, pid, started_at=None):+ """A v1 (legacy, pid-only) claim."""marker.write_text(f"{pid}\n{int(time.time() if started_at is None else started_at)}\n", encoding="utf-8")-def test_marker_path_follows_process_hermes_home(tmp_path, monkeypatch):- """The lock must land where the Rust updater and Electron gate look.+def _claim_v2(marker, pid, started_at=None, ct_offset=0.0):+ started = int(time.time() if started_at is None else started_at)+ marker.write_text(f"{pid}\n{started}\nct:{process_create_time(pid) + ct_offset:.3f}\n", encoding="utf-8")- All three resolve the *process* HERMES_HOME; a profile-scoped path would- put the lock somewhere the other two owners never read.++def test_marker_path_is_the_profile_tree_root(tmp_path, monkeypatch):+ """The lock must land where the Rust updater, Electron gate and hand-off scripts look.++ They all read the ROOT home; a sticky/`-p` profile re-homes HERMES_HOME to+ ``<root>/profiles/<p>``, and a marker there is invisible to every other owner (V9c)."""- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- assert update_marker_path() == tmp_path / ".hermes-update-in-progress"+ root = tmp_path / "root"+ monkeypatch.setenv("HERMES_HOME", str(root / "profiles" / "work"))+ assert update_marker_path() == root / ".hermes-update-in-progress"+ monkeypatch.setenv("HERMES_HOME", str(root))+ assert update_marker_path() == root / ".hermes-update-in-progress"def test_acquire_writes_pid_and_start_time(marker):@@ -82,7 +95,10 @@ def test_acquire_writes_pid_and_start_time(marker):"the Electron gate probes this pid for liveness")assert int(lines[1]) == pytest.approx(time.time(), abs=5)- assert len(lines) == 2, "wire format is exactly pid + started_at"+ assert float(lines[2].removeprefix("ct:")) == pytest.approx(process_create_time(), abs=0.01), (+ "line 3 is our creation time: readers tell a reused pid from us by it"+ )+ assert len(lines) == 3def test_second_acquire_is_refused_while_the_first_is_live(marker, other_pid):@@ -184,13 +200,54 @@ def test_dead_owner_is_reclaimed_not_honored(marker):assert int(marker.read_text(encoding="utf-8").splitlines()[0]) == os.getpid()-def test_owner_past_the_age_ceiling_is_reclaimed(marker):- """A live-but-wedged updater must not hold the lock forever."""- long_ago = int(time.time()) - UPDATE_MARKER_MAX_AGE_SECONDS - 60- marker.write_text(f"{os.getpid()}\n{long_ago}\n", encoding="utf-8")+def test_v1_owner_past_the_age_ceiling_is_reclaimed(marker, other_pid):+ """A legacy pid-only marker carries no creation time: only the ceiling exposes a reused pid."""+ _claim(marker, other_pid, int(time.time()) - UPDATE_MARKER_MAX_AGE_SECONDS - 60)lock = UpdateLock(path=marker)- assert lock.acquire() is True+ assert lock.acquire() is True and lock.acquired is True+++def test_v2_live_owner_is_live_regardless_of_age(marker, other_pid):+ """An update running 25 minutes (Windows builds, long drains) still owns the lock (V3/V10/V11)."""+ _claim_v2(marker, other_pid, time.time() - 25 * 60)+ before = marker.read_bytes()++ lock = UpdateLock(path=marker)+ assert lock.acquire() is False+ assert lock.holder is not None and lock.holder.pid == other_pid+ assert read_live_update(path=marker) is not None+ assert marker.read_bytes() == before, "a refused claimant never rewrites the owner's marker"+++def test_v2_marker_whose_pid_was_reused_is_reclaimed(marker, other_pid):+ """A live pid whose creation time does not match the record is a recycled pid (V22)."""+ _claim_v2(marker, other_pid, ct_offset=-100.0)++ lock = UpdateLock(path=marker)+ assert lock.acquire() is True and lock.acquired is True+ assert int(marker.read_text(encoding="utf-8").splitlines()[0]) == os.getpid()+++def test_delegate_keeps_the_claim_live_after_the_partner_dies(marker, monkeypatch, other_pid):+ """Rule 6: `hermes update` adopting a hand-off claim names itself on line 4, restores+ lines 1-3 byte-identical on exit, and is what keeps the claim visible if the partner dies."""+ _claim_v2(marker, other_pid)+ base = marker.read_bytes()+ monkeypatch.setenv(HANDOFF_PID_ENV, str(other_pid))++ lock = UpdateLock(path=marker)+ assert lock.acquire() is True and lock.acquired is False+ lines = marker.read_text(encoding="utf-8").splitlines()+ assert marker.read_bytes().startswith(base) and lines[3].startswith(f"delegate:{os.getpid()} ct:")++ dead_partner = f"{DEAD_PID}\n{int(time.time())}\nct:1.000\n{lines[3]}\n"+ marker.write_text(dead_partner, encoding="utf-8")+ holder = read_live_update(path=marker)+ assert holder is not None and holder.pid == os.getpid(), "the running delegate keeps the update visible"+ marker.write_bytes(base + f"{lines[3]}\n".encode())+ lock.release()+ assert marker.read_bytes() == base, "the live partner gets its own claim back, byte-identical"@pytest.mark.parametrize(@@ -239,19 +296,81 @@ def test_describe_holder_names_the_pid_and_elapsed_time(marker):assert "already running" in message-def test_unwritable_marker_location_does_not_block_the_update(tmp_path):- """Degrade to pre-lock behavior rather than refusing to update at all.-- An unwritable marker path is a worse reason to block an update than the- race the lock prevents.- """+def test_unwritable_marker_location_refuses_instead_of_running_unlocked(tmp_path):+ """No "proceed unlocked": an update that cannot claim the lock cannot exclude another."""lock = UpdateLock(path=tmp_path / "nonexistent-file" / "marker")(tmp_path / "nonexistent-file").write_text("i am a file, not a dir", encoding="utf-8")+ assert lock.acquire() is False+ assert lock.holder is not None and lock.holder.reason+ assert "Cannot lock this install" in describe_holder(lock.holder)+++_HOLD_CHECKOUT = """+import sys, time+sys.path.insert(0, sys.argv[1])+from hermes_cli.update_lock import UpdateLock+lock = UpdateLock(path=__import__("pathlib").Path(sys.argv[3]), install_root=sys.argv[2])+assert lock.acquire()+print("held", flush=True)+time.sleep(120)+"""++[email protected]("posix")+def test_checkout_lock_excludes_an_update_from_another_home(tmp_path):+ """Two `hermes update` runs on one checkout from different homes exclude each other (V3)."""+ install = tmp_path / "checkout"+ install.mkdir()+ holder = subprocess.Popen(+ [sys.executable, "-c", _HOLD_CHECKOUT, str(REPO_ROOT), str(install), str(tmp_path / "homeA" / "m")],+ stdout=subprocess.PIPE, stdin=subprocess.DEVNULL, text=True,+ )+ try:+ assert holder.stdout.readline().strip() == "held"+ lock = UpdateLock(path=tmp_path / "homeB-marker", install_root=install)+ assert lock.acquire() is False+ assert lock.holder is not None and lock.holder.pid == holder.pid+ assert not (tmp_path / "homeB-marker").exists()+ assert update_in_progress(install)+ finally:+ holder.kill()+ holder.wait()+ assert not update_in_progress(install), "the kernel frees the lock with its holder"+ lock = UpdateLock(path=tmp_path / "homeB-marker", install_root=install)+ assert lock.acquire() is True+ lock.release()++[email protected]("posix")+def test_checkout_lock_outlives_its_owner_while_an_inheriting_child_runs(tmp_path):+ """Invariant: lock free => no process of the update tree alive (pass_fds children)."""+ install = tmp_path / "checkout"+ install.mkdir()+ lock = UpdateLock(path=tmp_path / "marker", install_root=install)assert lock.acquire() is True- assert lock.acquired is False, "nothing was written, so there is nothing to release"+ child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(120)"],+ pass_fds=checkout_lock_fds(install), stdin=subprocess.DEVNULL)+ try:+ lock.release()+ assert update_in_progress(install), "the owner's exit must not free a lock its child holds"+ finally:+ child.kill()+ child.wait()+ assert not update_in_progress(install)+ assert checkout_lock_path(install).name == ".hermes-update.lock"+++def test_unwritable_install_root_refuses(tmp_path):+ """A checkout we cannot write is refused through the exit-2 path, never updated unlocked."""+ install = tmp_path / "not-a-dir"+ install.write_text("file", encoding="utf-8")+ lock = UpdateLock(path=tmp_path / "marker", install_root=install)+ assert lock.acquire() is False+ assert lock.holder is not None and lock.holder.reason+ assert not (tmp_path / "marker").exists()class TestHandoffFromOrchestratingUpdater: