The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): the Windows build launcher returns only once the command's whole tree is gone
Teknium72aaf38372e3
diff --git a/hermes_cli/update_custody.py b/hermes_cli/update_custody.pyindex d34d17c7535..ba8a9ed5f09 100644--- a/hermes_cli/update_custody.py+++ b/hermes_cli/update_custody.py@@ -19,7 +19,9 @@ can still write the checkout, and must NOT leak into processes that outlive thechild started here is created SUSPENDED, assigned to the update's kill-on-close job and onlythen resumed, so it and everything it spawns die with the lock owner. The Node build goesthrough ``pm.progress.run_contained`` (whose Popen it never sees): :func:`contained_command`- wraps it in a stdlib launcher that joins the job before it starts node.+ wraps it in a stdlib launcher that joins the job before it starts node and, once node exits,+ terminates and waits out everything node left running (C3): a normal release never frees the+ checkout under a build descendant.* Windows fails CLOSED (D2): a child the job refuses is never run. The msvcrt byte lock belongsto the process that took it — an inherited handle does not keep it, the kernel unlocks it whenthe owner exits — so nothing else could fence a writer outside the job: after the owner's@@ -470,14 +472,26 @@ def _prefetch_for_move(git_cmd: list[str], args: list[str], kwargs: dict) -> Non# keep the job open). A refused join, or a command outside the job, never runs (D2): the launcher says so on stderr, writes the notice to the report file# (argv[2]) — run_contained captures the child's stderr, so stderr alone is not seen (m1) — and# exits; the updater logs the notice, notes it in the receipt and raises CustodyRefused.+# The command also runs in a kill-on-close job of the launcher's own, nested in the update job+# (review C3): once the command exits, the launcher terminates that job — whatever npm / the+# builder started and left running — and waits until no process of it is left before it+# returns, so the caller never releases the checkout while a build descendant still writes.+# Only the command's tree: the update job also holds the update's other children. The Windows+# twin of the POSIX launcher below (_REAP_TREE); the nested job's handle closing (a killed+# launcher) kills the tree too._CUSTODY_UNAVAILABLE = "hermes: update custody unavailable"_REFUSED_EXIT = 87_JOIN_JOB = (- "import ctypes, subprocess, sys\n"+ "import ctypes, subprocess, sys, time\n""k = ctypes.WinDLL('kernel32', use_last_error=True)\n""k.AssignProcessToJobObject.argtypes = [ctypes.c_void_p, ctypes.c_void_p]\n""k.GetCurrentProcess.restype = ctypes.c_void_p\n""k.CloseHandle.argtypes = [ctypes.c_void_p]\n"+ "k.CreateJobObjectW.restype = ctypes.c_void_p\n"+ "k.SetInformationJobObject.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_ulong]\n"+ "k.TerminateJobObject.argtypes = [ctypes.c_void_p, ctypes.c_uint]\n"+ "k.QueryInformationJobObject.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_void_p, ctypes.c_ulong,\n"+ " ctypes.c_void_p]\n""h = ctypes.c_void_p(int(sys.argv[1]))\n""def refuse(why):\n"f" note = '{_CUSTODY_UNAVAILABLE} (%s); the command was not run' % why\n"@@ -491,6 +505,21 @@ _JOIN_JOB = (f" sys.exit({_REFUSED_EXIT})\n""if not k.AssignProcessToJobObject(h, k.GetCurrentProcess()):\n"" refuse('could not join the update job: %d' % ctypes.get_last_error())\n"+ # JOBOBJECT_EXTENDED_LIMIT_INFORMATION (KILL_ON_JOB_CLOSE) and the BASIC_ACCOUNTING record+ # whose ActiveProcesses says when the command's tree is gone.+ "class Basic(ctypes.Structure):\n"+ " _fields_ = [('times', ctypes.c_int64 * 2), ('flags', ctypes.c_uint32), ('ws', ctypes.c_size_t * 2),\n"+ " ('procs', ctypes.c_uint32), ('affinity', ctypes.c_size_t), ('classes', ctypes.c_uint32 * 2)]\n"+ "class Limits(ctypes.Structure):\n"+ " _fields_ = [('basic', Basic), ('io', ctypes.c_uint64 * 6), ('memory', ctypes.c_size_t * 4)]\n"+ "class Usage(ctypes.Structure):\n"+ " _fields_ = [('times', ctypes.c_int64 * 4), ('faults', ctypes.c_uint32), ('total', ctypes.c_uint32),\n"+ " ('active', ctypes.c_uint32), ('terminated', ctypes.c_uint32)]\n"+ "tree = k.CreateJobObjectW(None, None)\n"+ "limits = Limits()\n"+ "limits.basic.flags = 0x2000\n"+ "if not tree or not k.SetInformationJobObject(tree, 9, ctypes.byref(limits), ctypes.sizeof(limits)):\n"+ " refuse('could not create the job for the command tree: %d' % ctypes.get_last_error())\n"# Verify, never assume the topology: a redirecting interpreter (a Store Python alias) can# join while what it starts lands outside the job. Start the command suspended and run it# only once Windows says it is in the job (F54).@@ -501,12 +530,27 @@ _JOIN_JOB = (" p.kill()\n"" p.wait()\n"" refuse('the command would start outside the update job')\n"+ "if not k.AssignProcessToJobObject(tree, ctypes.c_void_p(int(p._handle))):\n"+ " error = ctypes.get_last_error()\n"+ " p.kill()\n"+ " p.wait()\n"+ " refuse('could not hold the command tree in a job: %d' % error)\n""k.CloseHandle(h)\n""nt = ctypes.WinDLL('ntdll')\n""nt.NtResumeProcess.argtypes = [ctypes.c_void_p]\n""if nt.NtResumeProcess(ctypes.c_void_p(int(p._handle))) != 0:\n"" p.kill()\n"- "sys.exit(p.wait())\n"+ "code = p.wait()\n"+ # C3: nothing the command started outlives it; return only once its whole tree is gone.+ "k.TerminateJobObject(tree, 1)\n"+ "usage, end = Usage(), time.monotonic() + 10\n"+ "while time.monotonic() < end:\n"+ " if not k.QueryInformationJobObject(tree, 1, ctypes.byref(usage), ctypes.sizeof(usage), None):\n"+ " break\n"+ " if not usage.active:\n"+ " break\n"+ " time.sleep(0.02)\n"+ "sys.exit(code)\n")@@ -704,8 +748,9 @@ def contained_command(argv: Sequence[str], *, inherit_lock: bool = True, root=Noinherited for checkout ``root``), under a launcher that keeps the command in the caller'sprocess group and kills every descendant left when it exits (:data:`_REAP_TREE`).Windows inside an update: the command runs under a launcher that joins the update's- kill-on-close job first; when the job cannot be handed over or the join is refused, the- command never runs and :class:`CustodyRefused` is raised (D2)."""+ kill-on-close job first and returns only once no process the command started is left (C3);+ when the job cannot be handed over or the join is refused, the command never runs and+ :class:`CustodyRefused` is raised (D2)."""argv = list(argv)if not (sys.platform == "win32" and _held() is not None):from hermes_cli.update_lock import checkout_lock_fdsdiff --git a/tests/hermes_cli/test_update_custody.py b/tests/hermes_cli/test_update_custody.pyindex 8b6ad3b4bbe..ab80e50053f 100644--- a/tests/hermes_cli/test_update_custody.py+++ b/tests/hermes_cli/test_update_custody.py@@ -614,3 +614,97 @@ def test_the_desktop_build_runs_in_checkout_custody(repo, tmp_path, monkeypatch)finally:lock.release()assert out.read_text(encoding="utf-8-sig").split() == ["yes"], "the desktop build ran without the checkout lock"++++# --- C3: the Windows build launcher returns only once the command's whole tree is gone ---------++class _FakeWinCall:+ def __init__(self, name, events, answer):+ self.name, self.events, self.answer = name, events, answer+ self.argtypes = self.restype = None++ def __call__(self, *args):+ import ctypes++ self.events.append((self.name, *(a.value if isinstance(a, ctypes.c_void_p) else a for a in args)))+ return self.answer(*args) if callable(self.answer) else self.answer+++def _run_join_launcher(monkeypatch, *, stray_polls: int):+ """Execute the real ``_JOIN_JOB`` launcher source against a recording kernel32/ntdll and a+ fake leader process. The command's job reports ``stray_polls`` live processes (a build+ grandchild still writing) before its tree is empty. Returns the ordered events."""+ import ctypes+ import types++ from hermes_cli.update_custody import _JOIN_JOB++ events = []+ live = {"left": stray_polls}++ def query(job, info_class, usage, size, _ret):+ usage._obj.active = 1 if live["left"] > 0 else 0+ live["left"] -= 1+ return 1++ def in_job(proc, job, inside):+ inside._obj.value = 1+ return 1++ kernel32 = {"AssignProcessToJobObject": 1, "GetCurrentProcess": 7, "CloseHandle": 1, "CreateJobObjectW": 22,+ "SetInformationJobObject": 1, "TerminateJobObject": 1, "QueryInformationJobObject": query,+ "IsProcessInJob": in_job}+ dlls = {"kernel32": types.SimpleNamespace(**{n: _FakeWinCall(n, events, a) for n, a in kernel32.items()}),+ "ntdll": types.SimpleNamespace(NtResumeProcess=_FakeWinCall("NtResumeProcess", events, 0))}+ # The real ctypes (its Structure, byref, c_* types), with Windows' DLL loader recorded.+ monkeypatch.setattr(ctypes, "WinDLL", lambda name, **_kw: dlls[name], raising=False)+ monkeypatch.setattr(ctypes, "get_last_error", lambda: 0, raising=False)++ class _Leader:+ _handle = 33++ def __init__(self, argv, **kwargs):+ events.append(("Popen", tuple(argv), kwargs.get("creationflags")))++ def wait(self):+ events.append(("leader exited",))+ return 3++ def kill(self):+ events.append(("kill",))++ monkeypatch.setattr(subprocess, "Popen", _Leader)+ monkeypatch.setattr(sys, "argv", ["launcher", "11", "report.txt", "npm", "run", "build"])+ with pytest.raises(SystemExit) as exited:+ exec(compile(_JOIN_JOB, "<join-job>", "exec"), {"__name__": "__main__"})+ events.append(("exit", exited.value.code))+ return events+++def _index(events, name, *args):+ return next(i for i, event in enumerate(events) if event[0] == name and event[1:1 + len(args)] == args)+++def test_the_windows_build_launcher_reaps_the_command_tree_before_it_returns(monkeypatch):+ """C3: npm (the leader) exits while a build/builder descendant it started still writes. A+ normal return of the launcher lets the updater release the checkout, so the launcher must+ terminate the command's own job (never the update job, which holds the update's other+ children) and return only once no process of it is left, with the leader's exit status."""+ events = _run_join_launcher(monkeypatch, stray_polls=2)+ tree = 22+ assert _index(events, "AssignProcessToJobObject", tree, 33) < _index(events, "NtResumeProcess"), \+ "the command ran before it was held in its own job"+ assert _index(events, "leader exited") < _index(events, "TerminateJobObject", tree), events+ assert not any(e[0] == "TerminateJobObject" and e[1] != tree for e in events), "terminated the update job"+ polls = [i for i, e in enumerate(events) if e[0] == "QueryInformationJobObject"]+ assert len(polls) == 3 and polls[0] > _index(events, "TerminateJobObject", tree), \+ "the launcher returned while a build descendant was still alive"+ assert events[-1] == ("exit", 3), events+++def test_the_windows_build_launcher_returns_at_once_when_nothing_was_left(monkeypatch):+ """C3 healthy control: a build whose descendants all exited with the leader costs one poll."""+ events = _run_join_launcher(monkeypatch, stray_polls=0)+ assert [e[0] for e in events if e[0] == "QueryInformationJobObject"] == ["QueryInformationJobObject"]+ assert events[-1] == ("exit", 3), eventsdiff --git a/tests/hermes_cli/test_update_lock_windows_live.py b/tests/hermes_cli/test_update_lock_windows_live.pyindex e37371ac86e..c8beddd8028 100644--- a/tests/hermes_cli/test_update_lock_windows_live.py+++ b/tests/hermes_cli/test_update_lock_windows_live.py@@ -534,3 +534,36 @@ def test_the_old_updater_runs_its_takeover_in_the_job(tmp_path, monkeypatch, caplock.release()assert code == 0 and started.exists()assert "would not take the takeover" in capsys.readouterr().out++++# --- C3: a normal release never frees the checkout under a build descendant ------------------++def test_a_build_descendant_left_by_its_leader_never_writes_after_a_normal_release(tmp_path):+ """C3: npm exits while a builder grandchild it started keeps running. The launcher returns+ only once that grandchild is gone, so after the owner's ordinary release a contender+ admitted to the checkout sees no late write. Control: the leader's exit status passes through."""+ from hermes_cli.update_custody import contained_command++ install = tmp_path / "checkout"+ install.mkdir()+ late = tmp_path / "late"+ writer = f"import pathlib, time; time.sleep(4); pathlib.Path({str(late)!r}).touch()"+ leader = [sys.executable, "-c",+ "import subprocess, sys; d = subprocess.DEVNULL; "+ f"subprocess.Popen([sys.executable, '-c', {writer!r}], stdin=d, stdout=d, stderr=d); sys.exit(3)"]+ lock = UpdateLock(path=tmp_path / "m", install_root=install)+ assert lock.acquire()+ try:+ with contained_command(leader, root=install) as (argv, custody):+ done = subprocess.run(argv, stdin=subprocess.DEVNULL, capture_output=True, timeout=60, **custody)+ finally:+ lock.release()+ assert done.returncode == 3, done+ contender = UpdateLock(path=tmp_path / "other-home-marker", install_root=install)+ assert contender.acquire(), "the checkout stayed locked after a normal release"+ try:+ time.sleep(6)+ assert not late.exists(), "a build descendant wrote after the checkout was handed to a contender"+ finally:+ contender.release()