Skip to content

The agent that grows with you

fix(update): restarted Windows gateways break away from the update's job

Teknium3ae6a03d7900
diff --git a/hermes_cli/update_completion.py b/hermes_cli/update_completion.py
index 80f1cc11a1e..56a476dc615 100644
--- a/hermes_cli/update_completion.py
+++ b/hermes_cli/update_completion.py
@@ -67,9 +67,11 @@ def run_completion(request: dict) -> dict:
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}))
- bind_child_to_update_tree(proc)
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)
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.py
index aa2cf1c80a2..3bfde7e5ba2 100644
--- a/hermes_cli/update_lock.py
+++ b/hermes_cli/update_lock.py
@@ -689,14 +689,30 @@ def checkout_lock_fds(install_root: Path | str | None = None) -> tuple[int, ...]
return () if fd is None else (fd,)
-def bind_child_to_update_tree(proc: subprocess.Popen) -> None:
+def bind_child_to_update_tree(proc: subprocess.Popen) -> bool:
"""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`).
+ 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.
"""
if sys.platform != "win32":
- return
+ return True
+ try:
+ _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
+
+
+def _bind_to_kill_on_close_job(proc: subprocess.Popen) -> None:
import ctypes
from ctypes import wintypes
@@ -723,7 +739,8 @@ def bind_child_to_update_tree(proc: subprocess.Popen) -> None:
if not job:
raise ctypes.WinError(ctypes.get_last_error())
limits = _Extended()
- limits.BasicLimitInformation.LimitFlags = 0x2000 # JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
+ # JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_BREAKAWAY_OK
+ limits.BasicLimitInformation.LimitFlags = 0x2000 | 0x0800
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())
diff --git a/tests/e2e/core/windows_update/test_update_lock_tree.py b/tests/e2e/core/windows_update/test_update_lock_tree.py
index 03b93110785..54bcade8e03 100644
--- a/tests/e2e/core/windows_update/test_update_lock_tree.py
+++ b/tests/e2e/core/windows_update/test_update_lock_tree.py
@@ -11,11 +11,15 @@ One install (install.ps1), then, with NEXT published:
``hermes update`` of the installed checkout must exit 2 and leave the checkout at HEAD;
(b) ``taskkill /F`` of the owner (not ``/T``) must take the bound child down with it;
(c) with the tree gone the lock is free: the real ``hermes update`` lands NEXT.
+
+A second install proves the other direction of the job: a gateway the update RESTARTS is started
+with ``CREATE_BREAKAWAY_FROM_JOB`` and must leave the job, so it outlives a successful update.
"""
from __future__ import annotations
import subprocess
+import time
import psutil
import pytest
@@ -33,6 +37,7 @@ pytestmark = [pytest.mark.platforms("windows"), pytest.mark.integration,
pytest.mark.live_system_guard_bypass, REQUIRES_OPT_IN]
REFUSAL = "Another Hermes update is already running"
+SURVIVAL_SECONDS = 30
# Runs on the INSTALLED venv against the installed checkout's own update_lock. Degrades to the
# marker-only API where the checkout has no install-root lock, so an older tree fails on behaviour.
@@ -129,3 +134,37 @@ def test_free_lock_lets_the_next_update_land(journey) -> None:
assert run.returncode == 0 and journey["c_head"] == m.next, fail_with(
m, f"after the whole update tree exited, `hermes update` did not land NEXT "
f"(rc={run.returncode}, checkout {journey['c_head']}, NEXT {m.next})", run)
+
+
[email protected](scope="module")
+def gateway_journey(tmp_path_factory):
+ out: dict = {}
+ with FakeLLMServer() as srv:
+ machine = new_machine(tmp_path_factory.mktemp("lg"), srv.base_url, label="lg", system_git=True)
+ out["machine"] = machine
+ try:
+ install = machine.install()
+ assert install.returncode == 0, fail_with(machine, f"install.ps1 exited {install.returncode}", install)
+ with machine.gateway_phase():
+ machine.spawn_gateway()
+ old_pid = int(machine.wait_gateway_running().get("pid") or 0)
+ machine.advance()
+ out["update"] = machine.update(label="update-with-gateway")
+ exited = time.monotonic()
+ out["relaunched"] = int(machine.wait_gateway_running(not_pid=old_pid).get("pid") or 0)
+ time.sleep(max(0.0, SURVIVAL_SECONDS - (time.monotonic() - exited)))
+ out["alive_after"] = _alive(out["relaunched"])
+ out["status"] = machine.hermes("gateway", "status", label="status-after-30s")
+ machine.kill_owned()
+ yield out
+ finally:
+ machine.teardown()
+
+
+def test_restarted_gateway_outlives_the_update(gateway_journey) -> None:
+ m, run, pid = gateway_journey["machine"], gateway_journey["update"], gateway_journey["relaunched"]
+ assert run.returncode == 0, fail_with(m, f"`hermes update` with a running gateway exited {run.returncode}", run)
+ status = gateway_journey["status"]
+ assert gateway_journey["alive_after"] and str(pid) in status.stdout, fail_with(
+ m, f"the gateway the update restarted (pid {pid}) died with the update's job: alive "
+ f"{SURVIVAL_SECONDS}s after `hermes update` exited = {gateway_journey['alive_after']}", status)