The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(update): a pause owes a live gateway only once its stop request was issued (N1)
Tekniumb00c919cf7b8
diff --git a/hermes_cli/update_cmd_windows.py b/hermes_cli/update_cmd_windows.pyindex e2c3fc1ab58..29293d224ab 100644--- a/hermes_cli/update_cmd_windows.py+++ b/hermes_cli/update_cmd_windows.py@@ -40,13 +40,17 @@ def _abort_on_error(prefix: str):raise RuntimeError(f"{prefix}: {exc}") from exc+def _planned_stop_marker_path(profile_path: Path) -> Path:+ return Path(profile_path) / ".gateway-planned-stop.json"++def _write_update_planned_stop_marker(profile_path: Path, pid: int) -> bool:"""Write a planned-stop marker into a specific profile home."""try:from gateway.status import _get_process_start_timefrom utils import atomic_json_writeatomic_json_write(- Path(profile_path) / ".gateway-planned-stop.json",+ _planned_stop_marker_path(profile_path),{"target_pid": pid, "target_start_time": _get_process_start_time(pid), "stopper_pid": os.getpid(),"written_at": datetime.now(timezone.utc).isoformat()},indent=None, separators=(",", ":"),@@ -863,11 +867,13 @@ def _discover_windows_gateways():return profile_processes, service_gateways, service_gateway_pids, running_pids-def _request_socket_pauses(running_pids, profile_processes, service_gateway_pids):+def _request_socket_pauses(running_pids, profile_processes, service_gateway_pids, on_request=None):"""Marker + socket-first pause for every profile-mapped gateway; ``(profiles, mapped_pids, socket_acks)``.Socket ACK = the gateway drains and exits by its own graceful path. No answer (older- gateway) -> the marker poll / force-kill ladder in the caller."""+ gateway) -> the marker poll / force-kill ladder in the caller. ``on_request(pid)`` runs once the+ request is issued (marker on disk, else a positive socket ACK) and before the socket call: from+ then on a crash leaves that gateway owed while it drains, never before."""profiles: dict[str, int] = {}mapped_pids = []socket_acks: list[dict] = []@@ -877,7 +883,9 @@ def _request_socket_pauses(running_pids, profile_processes, service_gateway_pidscontinueprofiles[str(proc.profile)] = int(pid)mapped_pids.append(int(pid))- _write_update_planned_stop_marker(Path(proc.path), int(pid))+ requested = _write_update_planned_stop_marker(Path(proc.path), int(pid))+ if requested and on_request is not None:+ on_request(int(pid))try:# Socket-first pause (#92091 step 2): ask the gateway to drain and exit itself instead of# relying on the marker poll + force-kill ladder. A positive ACK means the gateway is running@@ -888,6 +896,8 @@ def _request_socket_pauses(running_pids, profile_processes, service_gateway_pidsack = pause_gateway_for_update(Path(proc.path))if ack and (ack.get("pausing") or ack.get("already_stopping")):socket_acks.append(ack)+ if not requested and on_request is not None:+ on_request(int(pid))except Exception as exc:logger.debug("Socket pause unavailable for gateway %s: %s", pid, exc)return profiles, mapped_pids, socket_acks@@ -946,10 +956,14 @@ def _pause_windows_gateways_for_update() -> dict | None:service_profiles={str(s.name): str(s.profile) for s in service_gateways})with _abort_on_error("Could not record the gateways this update pauses"):pause_record.record_pause(intended, adopted, claims)- # A second write, right before the first request: a crash before it leaves every live entry- # "never asked" (still serving, dropped); after it, a live one is draining and stays owed.- pause_record.mark_stop_requested(intended, running_pids)- profiles = _stop_windows_gateways(running_pids, profile_processes, service_gateway_pids, unmapped_pids, unmapped)+ # The intent (and where each request goes), right before the first request. A live entry is owed+ # only once its request was issued (mark_stop_sent, or this update's marker still on disk): a+ # crash before that leaves it "never asked" (still serving, dropped), after it, draining (owed).+ pause_record.mark_stop_requested(intended, running_pids, markers={+ pid: _planned_stop_marker_path(Path(profile_processes[pid].path)) for pid in running_pids+ if pid in profile_processes and pid not in service_gateway_pids})+ profiles = _stop_windows_gateways(running_pids, profile_processes, service_gateway_pids, unmapped_pids, unmapped,+ on_request=lambda pid: pause_record.mark_stop_sent(intended, pid))token = {"resume_needed": True, "profiles": profiles, "unmapped_pids": unmapped_pids, "unmapped": unmapped}# Every profile with ANY live gateway at discovery counts as running: service-supervised ones skip the# socket pause (absent from ``profiles``) but the SCM restart brings them back, not a cold-start.@@ -980,11 +994,14 @@ def _cold_start_pause_token(adopted: dict | None, claims: list) -> dict | None:return pause_record.record_pause(token, adopted, claims)-def _stop_windows_gateways(running_pids, profile_processes, service_gateway_pids, unmapped_pids, unmapped) -> dict:- """Socket-pause the mapped gateways, drain, then tree-kill survivors; the paused ``profiles``."""+def _stop_windows_gateways(running_pids, profile_processes, service_gateway_pids, unmapped_pids, unmapped,+ on_request=None) -> dict:+ """Socket-pause the mapped gateways, drain, then tree-kill survivors; the paused ``profiles``.+ A force-killed process needs no stop record: dead, it is owed; alive, it was never stopped."""from gateway.status import get_process_start_time, terminate_pidfrom hermes_cli.update_cmd import _m- profiles, mapped_pids, socket_acks = _request_socket_pauses(running_pids, profile_processes, service_gateway_pids)+ profiles, mapped_pids, socket_acks = _request_socket_pauses(+ running_pids, profile_processes, service_gateway_pids, on_request=on_request)# Resolve venv-side launchers BEFORE draining: a dead worker's parent cannot be recovered (NoSuchProcess).# The launcher keeps ``.pyd`` mapped and would trip the venv-holder guard; it is killed with the survivors.launcher_pids = _m()._venv_launcher_ancestors(mapped_pids)diff --git a/hermes_cli/update_pause_record.py b/hermes_cli/update_pause_record.pyindex 422f10fe02d..471e1f60385 100644--- a/hermes_cli/update_pause_record.py+++ b/hermes_cli/update_pause_record.py@@ -238,13 +238,29 @@ def write(token: dict, *, owner: dict | None = None, path: Path | None = None) -_atomic_write(path, {"schema": 1, "owner": owner, "install_root": str(install_root()), "token": token})-def mark_stop_requested(token: dict, pids) -> None:- """Persist, BEFORE the first stop request, that these processes are being asked to stop: one- that acknowledged and is still draining keeps its restart obligation after a crash."""+def mark_stop_requested(token: dict, pids, markers: dict | None = None) -> None:+ """Persist, BEFORE the first stop request, the stops this update intends and where each mapped+ gateway's request (its planned-stop marker) will be written. Intent is not a request: a live+ process counts as asked only once :func:`mark_stop_sent` recorded it, or while the request this+ update wrote is still on disk (:func:`_asked`)."""token["stop_requested"] = sorted({*map(str, token.get("stop_requested") or []), *(str(int(p)) for p in pids)})+ token["stop_sent"] = sorted(map(str, token.get("stop_sent") or []))+ token["stopper_pid"] = os.getpid()+ token["stop_markers"] = {**(token.get("stop_markers") or {}), **{str(int(p)): str(m) for p, m in (markers or {}).items()}}write(token, owner=identity())+def mark_stop_sent(token: dict, pid) -> None:+ """Persist that *pid*'s stop request was issued (its planned-stop marker is on disk): from here a+ live *pid* is draining and keeps its restart debt until it exits. Best effort: the marker itself+ is the evidence until this lands, and the token carries it to the next record write."""+ token["stop_sent"] = sorted({*map(str, token.get("stop_sent") or []), str(int(pid))})+ try:+ write(token, owner=identity())+ except OSError as exc:+ print(f" ⚠ Could not record the stop request for gateway {pid}: {exc}")++def discharge(token: dict, path: Path | None = None) -> None:"""Remove the record only while it still names this pause (decided under the mutex)."""path = path or record_path()@@ -411,7 +427,8 @@ def record_pause(token: dict, adopted: dict | None, claims: list[Path]) -> dict:return token-_CARRIED = ("pause_id", "pre_sha", "dirty_at_pause", "identities", "stop_requested", "absorbed")+_CARRIED = ("pause_id", "pre_sha", "dirty_at_pause", "identities", "stop_requested", "stop_sent", "stopper_pid",+ "stop_markers", "absorbed")def finish_pause(token: dict, intended: dict, adopted: dict | None) -> dict:@@ -444,13 +461,38 @@ def _without(token: dict, pids: set[str]) -> dict:return token+def _request_on_disk(token: dict, pid: str) -> bool:+ """The planned-stop marker this update's stopper wrote for *pid* is still on disk (the gateway's+ watcher has not consumed it yet): the request was issued even if the updater died before+ :func:`mark_stop_sent`. A marker naming another stopper (a user's ``hermes gateway stop``) is not."""+ path = (token.get("stop_markers") or {}).get(str(pid))+ if not path:+ return False+ try:+ marker = json.loads(Path(path).read_text(encoding="utf-8-sig"))+ return int(marker["target_pid"]) == int(pid) and int(marker["stopper_pid"]) == int(token["stopper_pid"])+ except (OSError, ValueError, TypeError, KeyError):+ return False+++def _asked(token: dict) -> set[str]:+ """Pids this update actually asked to stop: recorded as sent, or whose request is still on disk."""+ sent = {str(p) for p in token.get("stop_sent") or []}+ return sent | {str(p) for p in token.get("stop_requested") or [] if str(p) not in sent and _request_on_disk(token, str(p))}++def drop_never_stopped(token: dict) -> dict:- """Drop entries whose recorded process is the same live incarnation AND was never asked to stop- (the update died before its first stop request). One it asked to stop may be draining: it keeps- its restart debt (:func:`split_draining`). No stop record at all: nothing can be told apart."""+ """Drop entries whose recorded process is the same live incarnation AND was never actually asked+ to stop (the update died before issuing its request, even with the intent on disk): it is still+ serving, and a later exit — a user's ``hermes gateway stop`` included — is not this update's to+ undo. One it asked may be draining: it keeps its restart debt (:func:`split_draining`). The+ evidence is resolved here, once, into ``stop_sent`` (a merge carries it under another stopper).+ No stop record at all (a set from before stop tracking): nothing can be told apart."""if token.get("stop_requested") is None:return token- return _without(token, _live_pids(token) - {str(p) for p in token["stop_requested"]})+ asked = _asked(token)+ token["stop_sent"] = sorted(asked)+ return _without(token, _live_pids(token) - asked)def split_draining(token: dict) -> dict:@@ -479,10 +521,11 @@ def merge_into(token: dict | None, adopted: dict) -> dict:for pid, ct in (adopted.get("identities") or {}).items():identities.setdefault(pid, ct)if "stop_requested" in adopted or "stop_requested" in token:- requested = adopted.get("stop_requested")+ requested, sent = adopted.get("stop_requested"), adopted.get("stop_sent")if requested is None: # a set with no stop record keeps every live entry: all count as asked- requested = list(adopted.get("identities") or {})+ requested = sent = list(adopted.get("identities") or {})token["stop_requested"] = sorted({*map(str, token.get("stop_requested") or []), *map(str, requested)})+ token["stop_sent"] = sorted({*map(str, token.get("stop_sent") or []), *map(str, sent or [])})services = token.setdefault("services", [])services.extend(s for s in adopted.get("services") or [] if s not in services)if services:diff --git a/tests/hermes_cli/test_update_pause_record.py b/tests/hermes_cli/test_update_pause_record.pyindex dd65e835048..336acc9cec1 100644--- a/tests/hermes_cli/test_update_pause_record.py+++ b/tests/hermes_cli/test_update_pause_record.py@@ -323,6 +323,7 @@ def test_a_gateway_draining_after_the_stop_request_keeps_its_restart_debt(tmp_patoken = r.record_pause({"resume_needed": True, "profiles": {"default": pid},"identities": {str(pid): r.identity(pid)["ct"]}}, None, [])r.mark_stop_requested(token, [pid])+ r.mark_stop_sent(token, pid)os.kill(pid, 15)print("asked", flush=True)time.sleep(120)@@ -365,6 +366,62 @@ def test_a_gateway_never_asked_to_stop_is_not_restarted(tmp_path):gateway.wait(timeout=10)[email protected]_system_guard_bypass+def test_a_stop_intended_but_never_issued_leaves_a_serving_gateway_alone_and_a_later_user_stop_final(tmp_path):+ """The updater recorded its intent, then died before the request (N1): the gateway was never+ asked, keeps serving and owes nothing; when the user stops it later, no launch restarts it."""+ gateway = _child(_DRAINING, str(tmp_path / "unused"), env={"HERMES_HOME": str(tmp_path)})+ assert gateway.stdout.readline().strip() == "up"+ updater = _child(_AT_LINE + """+ pid = int(sys.argv[1])+ token = r.record_pause({"resume_needed": True, "profiles": {"default": pid},+ "identities": {str(pid): r.identity(pid)["ct"]}}, None, [])+ r.mark_stop_requested(token, [pid])+ print("intended", flush=True)+ time.sleep(120)+ """, str(gateway.pid), env={"HERMES_HOME": str(tmp_path)})+ try:+ assert updater.stdout.readline().strip() == "intended"+ updater.send_signal(signal.SIGKILL) # windows-footgun: ok — killed between the intent and the request+ updater.wait(timeout=10)+ assert _launches(tmp_path, 1) == [[]]+ assert _record_files(tmp_path) == [], "a gateway never asked to stop is held as draining"+ finally:+ gateway.kill() # the user's stop, after the update's obligation was retired+ gateway.wait(timeout=10)+ assert _launches(tmp_path, 1) == [[]], "a gateway the user stopped was restarted for an update that never stopped it"++[email protected]_system_guard_bypass+def test_a_request_on_disk_is_owed_even_before_it_is_recorded_sent(tmp_path):+ """Killed after writing the planned-stop marker (the request), before recording it sent: the+ gateway acts on it, so it is owed; a marker the USER's stop wrote is no evidence."""+ marker = tmp_path / "profile" / ".gateway-planned-stop.json"+ marker.parent.mkdir()+ gateway = _child(_DRAINING, str(tmp_path / "unused"), env={"HERMES_HOME": str(tmp_path)})+ assert gateway.stdout.readline().strip() == "up"+ updater = _child(_AT_LINE + """+ pid, marker = int(sys.argv[1]), Path(sys.argv[2])+ token = r.record_pause({"resume_needed": True, "profiles": {"default": pid},+ "identities": {str(pid): r.identity(pid)["ct"]}}, None, [])+ r.mark_stop_requested(token, [pid], markers={pid: marker})+ marker.write_text(json.dumps({"target_pid": pid, "stopper_pid": os.getpid()}), encoding="utf-8")+ print("requested", flush=True)+ time.sleep(120)+ """, str(gateway.pid), str(marker), env={"HERMES_HOME": str(tmp_path)})+ try:+ assert updater.stdout.readline().strip() == "requested"+ updater.send_signal(signal.SIGKILL) # windows-footgun: ok — killed before mark_stop_sent+ updater.wait(timeout=10)+ assert _launches(tmp_path, 1) == [[]] and len(_record_files(tmp_path)) == 1, "an issued request lost its debt"+ marker.write_text(json.dumps({"target_pid": gateway.pid, "stopper_pid": 1}), encoding="utf-8") # a user's stop replaced it+ assert _launches(tmp_path, 1) == [[]] and len(_record_files(tmp_path)) == 1, "resolved evidence was re-judged"+ finally:+ gateway.kill()+ gateway.wait(timeout=10)+ assert _launches(tmp_path, 2) == [["resume ['default']"], []]++# --- R13: a checkout sharing the home never takes another checkout's paused set --------------def _checkout_copy(root: Path) -> Path:"""A second checkout: the real module file under another install root."""diff --git a/tests/hermes_cli/test_windows_gateway_cold_start_desktop_lifecycle.py b/tests/hermes_cli/test_windows_gateway_cold_start_desktop_lifecycle.pyindex 64fc4367961..7d30978192c 100644--- a/tests/hermes_cli/test_windows_gateway_cold_start_desktop_lifecycle.py+++ b/tests/hermes_cli/test_windows_gateway_cold_start_desktop_lifecycle.py@@ -104,7 +104,7 @@ def _running_beta_pause_fixture(monkeypatch, tmp_path):monkeypatch.setattr(update_cmd_windows, "_desktop_owns_gateway_lifecycle", lambda: True)beta = SimpleNamespace(pid=777, profile="beta")monkeypatch.setattr(update_cmd_windows, "_discover_windows_gateways", lambda: ({777: beta}, [], set(), [777]))- monkeypatch.setattr(update_cmd_windows, "_request_socket_pauses", lambda *a: ({"beta": 777}, [777], []))+ monkeypatch.setattr(update_cmd_windows, "_request_socket_pauses", lambda *a, **k: ({"beta": 777}, [777], []))monkeypatch.setattr(cli_main, "_venv_launcher_ancestors", lambda pids: [])monkeypatch.setattr(cli_main, "_wait_for_windows_update_gateway_exit", lambda pids, timeout: set())monkeypatch.setattr(profiles_mod, "get_active_profile_name", lambda: "default")@@ -194,7 +194,7 @@ def test_service_supervised_running_profile_is_not_cold_started(monkeypatch, tmpservice = SimpleNamespace(name="HermesGw-beta", profile="beta", service_pid=800, gateway_pid=900,descendant_identities=(), service_create_time=1.0, gateway_create_time=2.0)monkeypatch.setattr(update_cmd_windows, "_discover_windows_gateways", lambda: ({900: svc_proc}, [service], {900}, [900]))- monkeypatch.setattr(update_cmd_windows, "_request_socket_pauses", lambda *a: ({}, [], []))+ monkeypatch.setattr(update_cmd_windows, "_request_socket_pauses", lambda *a, **k: ({}, [], []))monkeypatch.setattr(update_cmd, "_stop_windows_gateway_service", lambda *a, **k: None)gateway_windows._write_start_attestation([900], "direct spawn (PID 900)", home=homes["beta"])