The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): a completion child the job refused holds its own checkout lease (review R5b)
Tekniumb2d3c7d3f039
diff --git a/apps/bootstrap-installer/src-tauri/src/marker.rs b/apps/bootstrap-installer/src-tauri/src/marker.rsindex 4025cac820e..027ce328174 100644--- a/apps/bootstrap-installer/src-tauri/src/marker.rs+++ b/apps/bootstrap-installer/src-tauri/src/marker.rs@@ -565,6 +565,10 @@ const GIT_CHECKOUT_LOCK_NAME: &str = "hermes-update.lock";/// `update_lock.py::_WINDOWS_LOCK_OFFSET`: the byte msvcrt locks, far past the holder record.#[cfg(windows)]const WINDOWS_LOCK_OFFSET: u32 = 1 << 20;+/// `update_lock.py::_LEASE_SLOTS`: the lease bytes right after it. A child that joined the lock+/// holds one (R5b) and may outlive its owner, so any held lease reads as a held lock.+#[cfg(windows)]+const LEASE_SLOTS: u32 = 16;/// `update_lock.py::_git_common_dir`: the repository's common git dir, read from disk. `.git`/// is the dir itself, or a `gitdir: <path>` file (linked worktree, submodule) whose target may@@ -643,7 +647,7 @@ fn checkout_lock_held(install_root: &Path) -> bool {/// Windows: msvcrt's `LK_NBLCK` is a `LockFile` byte-range lock on one byte at/// `WINDOWS_LOCK_OFFSET`; `LockFileEx` on the same byte conflicts with it. As in `_try_lock`,-/// a lock that cannot be taken is held.+/// a lock that cannot be taken is held, the lease bytes after it included.#[cfg(windows)]fn checkout_lock_held(install_root: &Path) -> bool {use std::os::windows::fs::OpenOptionsExt;@@ -670,11 +674,11 @@ fn checkout_lock_held(install_root: &Path) -> bool {unsafe {let mut overlapped = at_offset();let flags = LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY;- if LockFileEx(handle, flags, 0, 1, 0, &mut overlapped) == 0 {+ if LockFileEx(handle, flags, 0, 1 + LEASE_SLOTS, 0, &mut overlapped) == 0 {return true;}let mut overlapped = at_offset();- UnlockFileEx(handle, 0, 1, 0, &mut overlapped);+ UnlockFileEx(handle, 0, 1 + LEASE_SLOTS, 0, &mut overlapped);}false}diff --git a/apps/bootstrap-installer/src-tauri/src/marker_tests.rs b/apps/bootstrap-installer/src-tauri/src/marker_tests.rsindex 52b6753db0a..ea84c39711c 100644--- a/apps/bootstrap-installer/src-tauri/src/marker_tests.rs+++ b/apps/bootstrap-installer/src-tauri/src/marker_tests.rs@@ -1297,6 +1297,43 @@ fn checkout_lock_path_follows_the_git_common_dir() {let _ = std::fs::remove_dir_all(&dir);}+/// R5b: a completion child the update's job refused joins the lock holding a lease byte past+/// the owner's and may outlive it; a held lease alone must read as a held checkout.+#[cfg(windows)]+#[test]+fn checkout_lock_held_sees_a_lease_without_its_owner() {+ use std::os::windows::io::AsRawHandle;+ use windows_sys::Win32::Storage::FileSystem::{+ LockFileEx, LOCKFILE_EXCLUSIVE_LOCK, LOCKFILE_FAIL_IMMEDIATELY,+ };+ use windows_sys::Win32::System::IO::OVERLAPPED;++ let dir = unique_tmp_dir("checkout-lease-held");+ let install = dir.join("hermes-agent");+ std::fs::create_dir_all(install.join(".git")).unwrap();+ let lock = checkout_lock_path(&install);+ let lease = std::fs::OpenOptions::new()+ .read(true)+ .write(true)+ .create(true)+ .truncate(false)+ .open(&lock)+ .unwrap();+ let ok = unsafe {+ let mut overlapped: OVERLAPPED = std::mem::zeroed();+ overlapped.Anonymous.Anonymous.Offset = WINDOWS_LOCK_OFFSET + LEASE_SLOTS;+ let flags = LOCKFILE_EXCLUSIVE_LOCK | LOCKFILE_FAIL_IMMEDIATELY;+ LockFileEx(lease.as_raw_handle(), flags, 0, 1, 0, &mut overlapped)+ };+ assert_ne!(ok, 0, "the test takes the last lease byte");+ assert!(+ checkout_lock_held(&install),+ "a held lease read as a free checkout"+ );+ release_checkout_lock(lease, &install);+ let _ = std::fs::remove_dir_all(&dir);+}+#[test]fn checkout_lock_held_sees_another_open_file_holding_it() {let dir = unique_tmp_dir("checkout-lock-held");diff --git a/hermes_cli/update_completion.py b/hermes_cli/update_completion.pyindex 69c47cacee1..a83d05d9a03 100644--- a/hermes_cli/update_completion.py+++ b/hermes_cli/update_completion.py@@ -39,16 +39,18 @@ def _bind_and_resume(proc: subprocess.Popen, request: dict, request_path: Path)"""Windows: bind the suspended completion child to the update's job, then resume it.Post-commit, refusing the child would fail a committed update, so a child the job refuses- runs unfenced (D2 ruling), never silently: the refusal is printed and recorded as a failed- ``update_custody`` step in this run's receipt and, before the child runs (it has not read- its request yet), in the receipt it resumes, so the terminal receipt carries it."""+ still runs, fenced by its own checkout lease instead (R5b: it joins our lock holding a lease+ byte, which keeps the checkout busy after a killed owner until the child exits). Never+ silently: the refusal is printed and recorded as a failed ``update_custody`` step in this+ run's receipt and, before the child runs (it has not read its request yet), in the receipt it+ resumes, so the terminal receipt carries it."""from hermes_cli import update_receiptfrom hermes_cli.update_lock import bind_child_to_update_tree, resume_suspended_childrefusal = bind_child_to_update_tree(proc)if refusal is not None:detail = (f"the update's job would not take the completion child ({refusal}), so it runs "- "unfenced: a killed update would not stop it")+ "outside the job, holding its own checkout lease")print(f" ⚠ Update completion: {detail}")update_receipt.record_step("update_custody", False, detail)current = update_receipt._current.get()diff --git a/hermes_cli/update_lock.py b/hermes_cli/update_lock.pyindex dc2ae7cd985..9fd9edff467 100644--- a/hermes_cli/update_lock.py+++ b/hermes_cli/update_lock.py@@ -73,6 +73,11 @@ 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+# R5b: the lease bytes just past it. A Windows process that joins its ancestor's lock (it cannot+# inherit it) also locks one lease byte of its own: a completion child the job refused runs+# outside the kill-on-close job and outlives a killed owner, and its lease keeps the checkout+# busy until it exits. Takers and probes treat any held lease as a held lock.+_LEASE_SLOTS = 16_FILETIME_UNIX_EPOCH = 116444736000000000@@ -930,13 +935,12 @@ _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:+ if not _lock_bytes(fd, _WINDOWS_LOCK_OFFSET):+ return False+ if not _lock_bytes(fd, _WINDOWS_LOCK_OFFSET + 1, _LEASE_SLOTS): # a dead owner's leased child+ _unlock(fd)return False+ _unlock(fd, _WINDOWS_LOCK_OFFSET + 1, _LEASE_SLOTS)return Trueimport fcntl@@ -947,13 +951,34 @@ def _try_lock(fd: int) -> bool:return True-def _unlock(fd: int) -> None:+def _lock_bytes(fd: int, offset: int, count: int = 1) -> bool:+ """Windows: lock ``count`` bytes at ``offset`` without waiting (fails if any is held)."""+ import msvcrt++ os.lseek(fd, offset, os.SEEK_SET)+ try:+ msvcrt.locking(fd, msvcrt.LK_NBLCK, count)+ except OSError:+ return False+ return True+++def _unlock(fd: int, offset: int = _WINDOWS_LOCK_OFFSET, count: int = 1) -> None:if sys.platform == "win32":import msvcrtwith suppress(OSError):- os.lseek(fd, _WINDOWS_LOCK_OFFSET, os.SEEK_SET)- msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)+ os.lseek(fd, offset, os.SEEK_SET)+ msvcrt.locking(fd, msvcrt.LK_UNLCK, count)+++def _take_lease(fd: int) -> int | None:+ """Windows: lock a free lease byte (R5b) on ``fd``; its offset, or None when all are held+ (the tree's other joiners hold them: this one still runs inside their custody)."""+ for offset in range(_WINDOWS_LOCK_OFFSET + 1, _WINDOWS_LOCK_OFFSET + 1 + _LEASE_SLOTS):+ if _lock_bytes(fd, offset):+ return offset+ return Nonedef _inherited_lock_fd(path: Path) -> int | None:@@ -1032,12 +1057,21 @@ def _acquire_checkout(install_root: Path) -> UpdateHolder | None:return UpdateHolder(pid=0, age_seconds=0.0, reason=f"{path} is not writable ({writable})")try:if not _lock_with_contention_wait(fd, path):- os.close(fd)if _held_by_our_windows_ancestor(path):# Windows has no fd inheritance: the update tree's children run in the lock- # owner's kill-on-close job (bind_child_to_update_tree) and die with it.- _HELD = {"path": str(path), "fd": None, "owned": False, "depth": 1}- return None+ # owner's kill-on-close job (bind_child_to_update_tree) and die with it. One the+ # job refused does not, so every joiner also holds a lease byte (R5b), taken+ # while the owner is seen alive: it never covers a writer after a free lock.+ lease = _take_lease(fd)+ if _held_by_our_windows_ancestor(path):+ _HELD = {"path": str(path), "fd": None, "owned": False, "depth": 1,+ "lease": None if lease is None else (fd, lease)}+ if lease is None:+ os.close(fd)+ return None+ if lease is not None:+ _unlock(fd, lease)+ os.close(fd)return _lock_holder(path)if writable is True:record = f"{os.getpid()}\n{int(time.time())}\n{_identity_line()}\n".encode()@@ -1090,6 +1124,11 @@ def _release_checkout() -> None:if _HELD["depth"] > 0:returnheld, _HELD = _HELD, None+ if held.get("lease"):+ lease_fd, offset = held["lease"]+ _unlock(lease_fd, offset)+ with suppress(OSError):+ os.close(lease_fd)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.@@ -1135,7 +1174,8 @@ def bind_child_to_update_tree(proc: subprocess.Popen) -> OSError | None:POSIX children inherit the lock fd instead (:func:`checkout_lock_fds`). Returns ``None`` whenbound, else the refusal (logged): the caller runs post-commit work, which must not fail over- a weaker lock, so it records the refusal and runs the child unfenced.+ a weaker lock, so it records the refusal and runs the child, which joins the lock holding its+ own lease byte (R5b): the checkout stays busy until it exits, even after the owner's death."""if sys.platform != "win32":return Nonediff --git a/tests/hermes_cli/test_update_lock_windows_live.py b/tests/hermes_cli/test_update_lock_windows_live.pyindex 0958c02e986..74431df7d14 100644--- a/tests/hermes_cli/test_update_lock_windows_live.py+++ b/tests/hermes_cli/test_update_lock_windows_live.py@@ -70,6 +70,63 @@ def test_killed_owner_takes_its_tree_down_and_frees_the_lock(tmp_path):owner.kill()++# --- R5b: a child the job refused (it runs outside the job) holds a lease of its own ----------++_JOINING_CHILD = r"""+import sys, time+from pathlib import Path+sys.path.insert(0, sys.argv[1])+from hermes_cli.update_lock import UpdateLock+assert UpdateLock(path=Path(sys.argv[3]), install_root=sys.argv[2], checkout_first=False).acquire_checkout(sys.argv[2])+print("joined", flush=True)+time.sleep(300)+"""++_UNBOUND_OWNER = r"""+import subprocess, sys+from pathlib import Path+sys.path.insert(0, sys.argv[1])+from hermes_cli.update_lock import UpdateLock+assert UpdateLock(path=Path(sys.argv[3]), install_root=sys.argv[2]).acquire()+# The job refused it: a plain child, outside any kill-on-close job (a refused bind still runs).+child = subprocess.Popen([sys.executable, "-c", sys.argv[4], *sys.argv[1:4]], stdout=subprocess.PIPE,+ stdin=subprocess.DEVNULL, text=True, encoding="utf-8")+assert child.stdout.readline().strip() == "joined"+print(child.pid, flush=True)+child.wait()+"""+++def test_a_child_the_job_refused_keeps_the_checkout_busy_after_its_owner_dies(tmp_path):+ """R5b: never two writers. The owner is killed while its unbound child still runs: the+ checkout must read held (the child's lease) until that child exits, then free."""+ install = tmp_path / "checkout"+ install.mkdir()+ owner = subprocess.Popen([sys.executable, "-c", _UNBOUND_OWNER, str(REPO_ROOT), str(install), str(tmp_path / "m"),+ _JOINING_CHILD], stdout=subprocess.PIPE, stdin=subprocess.DEVNULL, text=True,+ encoding="utf-8")+ child = None+ try:+ child = int(owner.stdout.readline().strip())+ subprocess.run(["taskkill", "/F", "/PID", str(owner.pid)], capture_output=True, check=False)+ owner.wait(timeout=30)+ assert _alive(child), "fixture: the unbound child must outlive its owner"+ assert update_in_progress(install), "the checkout reads free while the refused child still runs"+ assert UpdateLock(path=tmp_path / "other-home-marker", install_root=install).acquire() is False+ finally:+ if child is not None:+ subprocess.run(["taskkill", "/F", "/PID", str(child)], capture_output=True, check=False)+ if owner.poll() is None:+ owner.kill()+ deadline = time.time() + 15+ while _alive(child) and time.time() < deadline:+ time.sleep(0.2)+ fresh = UpdateLock(path=tmp_path / "other-home-marker", install_root=install)+ assert fresh.acquire() is True, "the lease outlived the child that held it"+ fresh.release()++# --- R2 on Windows: the updater's git and Node children join the owner's kill-on-close job -----_GIT_OWNER = r"""