Skip to content

The agent that grows with you

fix(update): both historical takeover hops run in Windows checkout custody (review F03, N11)

Teknium1c271a86db22
diff --git a/hermes_cli/_old_updater.py b/hermes_cli/_old_updater.py
index 1077f3775a8..b29ed20eedf 100644
--- a/hermes_cli/_old_updater.py
+++ b/hermes_cli/_old_updater.py
@@ -130,14 +130,37 @@ def _run_child(request: dict) -> tuple[int, dict]:
context = Path(directory) / "request.json"
result = Path(directory) / "result.json"
context.write_text(json.dumps(request), encoding="utf-8")
- child = subprocess.run(
+ code = _run_in_custody(
[sys.executable, "-I", "-S", "-B", "-X", "utf8", str(root / "hermes_cli/_update_takeover.py"),
- str(context), str(result)], cwd=root, env=env, **_checkout_custody(root),
+ str(context), str(result)], root, cwd=root, env=env,
)
completed = json.loads(result.read_text(encoding="utf-8-sig")) if result.is_file() else {}
if not isinstance(completed, dict):
raise ValueError("invalid update takeover acknowledgement")
- return child.returncode if child.returncode >= 0 else 1, completed
+ return code if code >= 0 else 1, completed
+
+
+def _run_in_custody(argv: list, root: Path, **kwargs) -> int:
+ """Run the takeover (it syncs and builds the checkout) in this updater's checkout custody,
+ from the update_lock module ALREADY loaded here (nothing new is imported). Windows: created
+ suspended, bound to this updater's kill-on-close job, then resumed; a refused bind still runs
+ (the update committed) and the takeover joins the lock holding its own lease. Releases
+ without these helpers hold no checkout lock, and the takeover acquires it itself."""
+ lock = sys.modules.get("hermes_cli.update_lock")
+ bind, resume = (getattr(lock, name, None) for name in ("bind_child_to_update_tree", "resume_suspended_child"))
+ if os.name != "nt" or bind is None or resume is None or getattr(lock, "_HELD", None) is None:
+ return subprocess.run(argv, **kwargs, **_checkout_custody(root)).returncode
+ proc = subprocess.Popen(argv, creationflags=lock.CREATE_SUSPENDED, **kwargs)
+ try:
+ refusal = bind(proc)
+ if refusal is not None:
+ print(f" ⚠ The update's job would not take the takeover ({refusal}); it runs outside the job, "
+ "holding its own checkout lease.", flush=True)
+ resume(proc)
+ return proc.wait()
+ except BaseException:
+ proc.kill()
+ raise
def _checkout_custody(root: Path) -> dict:
diff --git a/hermes_cli/_update_takeover.py b/hermes_cli/_update_takeover.py
index 248f69851be..38d104a2b3a 100644
--- a/hermes_cli/_update_takeover.py
+++ b/hermes_cli/_update_takeover.py
@@ -103,11 +103,15 @@ def main() -> int:
# update liveness checks while the waiting parent still holds its lock.
command = [str(python), "-I", "-B", "-X", "utf8", str(Path(request["root"]) / "hermes_cli/update_finish.py"),
str(context), str(result)]
- from hermes_cli.update_lock import checkout_lock_fds
-
- fds = checkout_lock_fds(request["root"])
- code = subprocess.run(command, cwd=request["root"], env=env,
- **({"pass_fds": fds} if fds else {})).returncode
+ from hermes_cli.update_custody import popen_post_commit
+
+ # update_finish builds the checkout: POSIX lock fd; Windows bound to the job (or leased).
+ with popen_post_commit(command, label="update finish child", cwd=request["root"], env=env) as child:
+ try:
+ code = child.wait()
+ except BaseException:
+ child.kill()
+ raise
if code != 0 and not result.is_file():
_record_failure(request, result, code, f"completion child exited {code} without acknowledgement")
return code
diff --git a/hermes_cli/update_custody.py b/hermes_cli/update_custody.py
index d9184d9fec0..521a039916c 100644
--- a/hermes_cli/update_custody.py
+++ b/hermes_cli/update_custody.py
@@ -280,6 +280,36 @@ def run(argv: Sequence[str], *, inherit_lock: bool = False, **kwargs) -> subproc
return subprocess.CompletedProcess(proc.args, code, stdout, stderr)
+def popen_post_commit(argv: Sequence[str], *, label: str, **kwargs) -> subprocess.Popen:
+ """``subprocess.Popen`` for a checkout writer that runs after the update committed (the
+ historical takeover's ``update_finish``). POSIX: the lock fd. Windows inside an update:
+ created suspended and bound to the update's kill-on-close job before it runs. A refused bind
+ must not fail a committed update, so the child still runs, never silently (printed and
+ receipted) and never unfenced: it joins the checkout lock holding its own lease (R5b)."""
+ if not (sys.platform == "win32" and _held() is not None):
+ return subprocess.Popen(list(argv), **_custody_kwargs(True, kwargs))
+ from hermes_cli.update_lock import bind_child_to_update_tree, resume_suspended_child
+
+ kwargs["creationflags"] = kwargs.get("creationflags", 0) | _CREATE_SUSPENDED
+ proc = subprocess.Popen(list(argv), **kwargs)
+ try:
+ refusal = bind_child_to_update_tree(proc)
+ if refusal is not None:
+ detail = (f"the update's job would not take the {label} ({refusal}), so it runs outside "
+ "the job, holding its own checkout lease")
+ print(f" ⚠ {detail}", flush=True)
+ with contextlib.suppress(Exception):
+ from hermes_cli.update_receipt import record_step
+
+ record_step("update_custody", False, detail)
+ resume_suspended_child(proc)
+ except BaseException:
+ proc.kill()
+ proc.wait()
+ raise
+ return proc
+
+
# How long a timed-out child's output may still drain after its tree was killed.
_DRAIN_SECONDS = 5
diff --git a/tests/hermes_cli/test_update_lock_windows_live.py b/tests/hermes_cli/test_update_lock_windows_live.py
index 74431df7d14..4de6add8f90 100644
--- a/tests/hermes_cli/test_update_lock_windows_live.py
+++ b/tests/hermes_cli/test_update_lock_windows_live.py
@@ -472,3 +472,60 @@ def test_a_refusal_the_readers_swallow_is_what_the_update_reports(tmp_path):
assert out.returncode == 1, text
assert "`hermes update` stopped: Windows would not put `git` in this update's process job" in text, text
assert "Nothing was changed" in text and "Run `hermes update` again from a regular terminal" in text, text
+
+
+# --- F03/N11: both historical takeover hops are bound to the job (or leased and receipted) -----
+
+def _refusing_job(monkeypatch):
+ import ctypes
+
+ from hermes_cli import update_lock
+
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
+ kernel32.CreateEventW.restype = ctypes.c_void_p
+ event = kernel32.CreateEventW(None, True, False, None)
+ monkeypatch.setattr(update_lock, "update_tree_job", lambda: event)
+
+
+def test_the_takeover_finish_child_is_never_silently_outside_the_job(tmp_path, monkeypatch):
+ """F03: the takeover's update_finish child builds the checkout. It goes through the job bind;
+ a refused bind still runs it (the update committed) but is receipted."""
+ import json
+
+ from hermes_cli import _update_takeover, update_receipt
+
+ root = tmp_path / "checkout"
+ (root / "hermes_cli").mkdir(parents=True)
+ started = tmp_path / "started"
+ (root / "hermes_cli" / "update_finish.py").write_text(
+ f"import sys\nopen({str(started)!r}, 'w').close()\nopen(sys.argv[2], 'w').write('{{}}')\n", encoding="utf-8")
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))
+ monkeypatch.setattr(sys, "path", list(sys.path))
+ monkeypatch.setattr(_update_takeover, "prepare", lambda request: (Path(sys.executable), dict(os.environ)))
+ _refusing_job(monkeypatch)
+ context = tmp_path / "request.json"
+ context.write_text(json.dumps({"root": str(root), "receipt": {}}), encoding="utf-8")
+ monkeypatch.setattr(sys, "argv", ["takeover", str(context), str(tmp_path / "result.json")])
+ with update_receipt.update_receipt_scope():
+ code = _update_takeover.main()
+ steps = update_receipt._current.get().data.get("steps", [])
+ assert code == 0 and started.exists()
+ assert any(s["name"] == "update_custody" and s["ok"] is False for s in steps), steps
+
+
+def test_the_old_updater_runs_its_takeover_in_the_job(tmp_path, monkeypatch, capsys):
+ """N11: the old updater's takeover child syncs and builds the checkout. With this updater
+ holding the checkout lock it is bound before it runs; a refused bind is said out loud."""
+ from hermes_cli import _old_updater
+
+ started = tmp_path / "started"
+ lock = UpdateLock(path=tmp_path / "m", install_root=tmp_path)
+ assert lock.acquire()
+ try:
+ _refusing_job(monkeypatch)
+ code = _old_updater._run_in_custody(
+ [sys.executable, "-c", f"open({str(started)!r}, 'w').close()"], tmp_path, cwd=tmp_path)
+ finally:
+ lock.release()
+ assert code == 0 and started.exists()
+ assert "would not take the takeover" in capsys.readouterr().out