The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): the completion child is bound before it runs, and a refused bind is receipted (R8 m1)
Teknium2e3cecd099a2
diff --git a/hermes_cli/update_completion.py b/hermes_cli/update_completion.pyindex 56a476dc615..0eeaec55502 100644--- a/hermes_cli/update_completion.py+++ b/hermes_cli/update_completion.py@@ -35,6 +35,29 @@ def _write_bootstrap_result(request: dict, result_path: Path, code: int, receiptreturn code+def _bind_and_resume(proc: subprocess.Popen, request: dict, request_path: Path) -> None:+ """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."""+ from hermes_cli import update_receipt+ from hermes_cli.update_lock import bind_child_to_update_tree, resume_suspended_child++ refusal = 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")+ print(f" ⚠ Update completion: {detail}")+ update_receipt.record_step("update_custody", False, detail)+ current = update_receipt._current.get()+ if current is not None and current.data.get("update_id") == request["receipt"]["update_id"]:+ request["receipt"] = json.loads(json.dumps(current.data))+ _write_json(request_path, request)+ resume_suspended_child(proc)++def run_completion(request: dict) -> dict:"""Wait for new code; zero exit without a correlated terminal result fails closed."""root = Path(request["source"])@@ -59,19 +82,20 @@ 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+ from hermes_cli.update_lock import CREATE_SUSPENDED, 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.+ # or dies with us (Windows job: created suspended, bound, then resumed, so nothing it+ # starts runs outside the 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, "pass_fds": checkout_lock_fds(root)} if os.name == "posix" else- {"creationflags": subprocess.CREATE_NO_WINDOW}))+ {"creationflags": subprocess.CREATE_NO_WINDOW | CREATE_SUSPENDED}))decoder = codecs.getincrementaldecoder("utf-8")("replace")try:- # Post-commit: an unbindable child only weakens the lock (logged), never fails the- # update; anything else unwinds through the cleanup below, never orphans the child.- bind_child_to_update_tree(proc)+ # A failure here unwinds through the cleanup below, never orphans the child.+ if os.name != "posix":+ _bind_and_resume(proc, request, request_path)while True:chunk = proc.stdout.read1(8192)sys.stdout.write(decoder.decode(chunk, final=not chunk))diff --git a/hermes_cli/update_lock.py b/hermes_cli/update_lock.pyindex 0303cbab9ad..dc2ae7cd985 100644--- a/hermes_cli/update_lock.py+++ b/hermes_cli/update_lock.py@@ -1119,27 +1119,45 @@ def custody_spawn_kwargs() -> dict:return {"pass_fds": (_HELD["fd"],)}-def bind_child_to_update_tree(proc: subprocess.Popen) -> bool:+CREATE_SUSPENDED = 0x00000004+++def bind_child_to_update_tree(proc: subprocess.Popen) -> OSError | None:"""Windows: put an update-tree child in a kill-on-close job owned by this process, so thechild (and everything it spawns) dies when the lock owner dies and frees the lock.- The job allows breakaway: a process the tree starts with ``CREATE_BREAKAWAY_FROM_JOB`` (the- gateways an update restarts or resumes, ``gateway_windows._spawn_detached``) leaves it and- outlives the update; every other descendant stays bound. Not ``SILENT_BREAKAWAY_OK``, which- would let every descendant escape.+ Create ``proc`` with :data:`CREATE_SUSPENDED` and resume it after the bind+ (:func:`resume_suspended_child`): it runs no instruction before, so nothing it starts can+ escape the job. The job allows breakaway: a process the tree starts+ with ``CREATE_BREAKAWAY_FROM_JOB`` (the gateways an update restarts or resumes,+ ``gateway_windows._spawn_detached``) leaves it and outlives the update; every other+ descendant stays bound. Not ``SILENT_BREAKAWAY_OK``, which would let every descendant escape.- POSIX children inherit the lock fd instead (:func:`checkout_lock_fds`). Returns False (and- logs) when the job cannot be set up: the caller runs post-commit work, which must not fail- over a weaker lock.+ POSIX children inherit the lock fd instead (:func:`checkout_lock_fds`). Returns ``None`` when+ bound, 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."""if sys.platform != "win32":- return True+ return Nonetry:_bind_to_kill_on_close_job(proc)except OSError as exc:logger.warning("Could not bind update child %s to the update's job: %s", proc.pid, exc)- return False- return True+ return exc+ return None+++def resume_suspended_child(proc: subprocess.Popen) -> None:+ """Windows: resume a :data:`CREATE_SUSPENDED` child (a no-op for a running one). A failed+ resume kills it and raises ``OSError``."""+ import ctypes++ ntdll = ctypes.WinDLL("ntdll")+ ntdll.NtResumeProcess.argtypes = [ctypes.c_void_p]+ ntdll.NtResumeProcess.restype = ctypes.c_long+ if ntdll.NtResumeProcess(int(proc._handle)) != 0:+ proc.kill()+ raise OSError(f"could not resume update child {proc.pid}")def _bind_to_kill_on_close_job(proc: subprocess.Popen) -> None:diff --git a/tests/hermes_cli/test_update_lock_windows_live.py b/tests/hermes_cli/test_update_lock_windows_live.pyindex 909a51c5731..a2b882b1fa9 100644--- a/tests/hermes_cli/test_update_lock_windows_live.py+++ b/tests/hermes_cli/test_update_lock_windows_live.py@@ -285,3 +285,55 @@ def test_a_refused_job_join_never_runs_the_command(tmp_path):assert _CUSTODY_UNAVAILABLE in out.stderr# m1: the notice also lands in the report the updater turns into a warning + receipt stepassert _CUSTODY_UNAVAILABLE in report.read_text(encoding="utf-8-sig")++++# --- R8 m1: the completion child is bound before it runs; a refused bind reaches the receipt ---++_COMPLETION_CHILD = (+ "import json, os, sys\n"+ "from pathlib import Path\n"+ "Path(os.environ['HERMES_PROBE_STARTED']).touch()\n" # its first instruction+ "request = json.loads(Path(sys.argv[1]).read_text(encoding='utf-8-sig'))\n"+ "receipt = dict(request['receipt'], finished_at='now', outcome='success')\n"+ "Path(sys.argv[2]).write_text(json.dumps({'schema': 1, 'update_id': receipt['update_id'], 'exit_code': 0,\n"+ " 'receipt': receipt, 'windows_resume': None}), encoding='utf-8')\n"+)+++def test_a_completion_child_runs_only_after_its_bind_and_a_refusal_is_receipted(tmp_path, monkeypatch):+ """The completion child is a checkout writer (dependency sync, product builds). It is created+ suspended and bound before it runs one instruction; when the real AssignProcessToJobObject+ refuses it (handed an event handle), it still runs (post-commit, ruling) but the refusal is a+ failed ``update_custody`` step in the receipt it finishes."""+ import ctypes+ import copy++ from hermes_cli import update_completion, update_lock, update_receipt++ root = tmp_path / "checkout"+ (root / "hermes_cli").mkdir(parents=True)+ (root / "hermes_cli" / "update_completion.py").write_text(_COMPLETION_CHILD, encoding="utf-8")+ started = tmp_path / "started"+ monkeypatch.setenv("HERMES_PROBE_STARTED", str(started))+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)+ kernel32.CreateEventW.restype = ctypes.c_void_p+ event = kernel32.CreateEventW(None, True, False, None)+ ran_before_bind = []++ def refusing_job() -> int:+ time.sleep(2.0) # a child already running has touched its marker by now+ ran_before_bind.append(started.exists())+ return event++ monkeypatch.setattr(update_lock, "update_tree_job", refusing_job)+ with update_receipt.update_receipt_scope():+ update_receipt.begin_update_receipt()+ request = {"source": str(root), "home": str(tmp_path / "home"),+ "receipt": copy.deepcopy(update_receipt._current.get().data)}+ result = update_completion.run_completion(request)+ assert ran_before_bind == [False], "the completion child ran before its job bind"+ assert result["exit_code"] == 0 and started.exists(), result+ steps = [s for s in result["receipt"].get("steps", []) if s["name"] == "update_custody"]+ assert steps and steps[0]["ok"] is False and "completion child" in steps[0]["detail"], result["receipt"]