The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: post-update relaunch verification polls every target in one loop
Teknium6483df614dc4
diff --git a/hermes_cli/update_cmd_windows.py b/hermes_cli/update_cmd_windows.pyindex 3a74f8873a9..2fa35f07444 100644--- a/hermes_cli/update_cmd_windows.py+++ b/hermes_cli/update_cmd_windows.py@@ -1383,7 +1383,6 @@ def _relaunch_paused_gateways(profiles: dict, unmapped: list) -> tuple[dict, lis_RELAUNCH_VERIFY_TIMEOUT_S = 30.0-_PER_TARGET_FLOOR_S = 6.0def _pending_relaunch_pids(profiles: dict, unmapped: list, pid_exists) -> list[int]:@@ -1445,6 +1444,53 @@ def _unmapped_ready_filter(entry: dict, taken: set):return lambda pids: [pid for pid in _owned_gateway_pids(pids) if matches(int(pid))]+_READY_INTERVAL_S = 0.4 # gateway_windows._wait_for_gateway_ready's poll interval and+_READY_CONFIRM_S = 2.0 # confirmation window: one hit proves a spawn, not a survived startup+++def _poll_until_ready(targets: list, deadline: float, taken: set) -> dict:+ """``{key: pids}`` for each ``(key, probe, claim_all)`` target whose gateway stayed visible for+ a whole confirmation window. All targets share one loop, so N targets cost one window, not N:+ one fleet process scan per tick (``probe(scan)`` calls ``scan()`` only if it needs the fleet),+ and each target is credited only on its own hits. *taken* holds, while a target is probed, the+ PIDs earlier targets vouched for (all of a profile's, the first of an unmapped entry's) so one+ gateway never retires two debts. A hit provisional at the deadline still finishes its window;+ a probe that raises leaves its target unready."""+ from hermes_cli.gateway import find_gateway_pids+ ready: dict = {}+ since: dict = {}+ failed: set = set()+ while True:+ now = _time.monotonic()+ pending = [t for t in targets if t[0] not in ready and t[0] not in failed and (now < deadline or t[0] in since)]+ if not pending:+ return ready+ fleet: list = []++ def scan() -> list:+ if not fleet:+ fleet.append(list(find_gateway_pids(all_profiles=True)))+ return fleet[0]+ taken.clear()+ taken.update(pid for pids in ready.values() for pid in pids)+ for key, probe, claim_all in pending:+ try:+ pids = list(probe(scan))+ except Exception as exc: # health: allow BLE001 -- one target's probe failure must not stall the others+ logger.warning("Could not verify Windows gateway %s after update: %s", key, exc)+ failed.add(key)+ continue+ if not pids:+ since.pop(key, None)+ continue+ vouched = pids if claim_all else pids[:1]+ taken.update(vouched)+ if now - since.setdefault(key, now) >= _READY_CONFIRM_S:+ ready[key] = vouched+ if len(ready) + len(failed) < len(targets):+ _time.sleep(_READY_INTERVAL_S)++def _verify_relaunched_gateways_alive(token: dict, profiles: dict, unmapped: list) -> None:"""Retire each relaunched runtime on ITS OWN readiness: a profile on a stable gateway in itsprofile home, an unmapped entry on a stable gateway running its argv. A watcher only proves a@@ -1457,27 +1503,16 @@ def _verify_relaunched_gateways_alive(token: dict, profiles: dict, unmapped: lisfrom hermes_cli import gateway_windowsfrom hermes_cli.profiles import get_profile_dirdeadline = _time.monotonic() + _relaunch_verify_timeout_s(profiles, unmapped, _pid_exists)-- def budget() -> float:- return max(deadline - _time.monotonic(), _PER_TARGET_FLOOR_S)-- ready_pids: list[int] = []- ready_profiles = []- for name, old_pid in sorted(profiles.items()):- pids = _try_call(lambda n=name, o=old_pid: gateway_windows._wait_for_gateway_ready(- timeout_s=budget(), home=Path(get_profile_dir(n)), pid_filter=lambda ps, o=o: [p for p in ps if int(p) != int(o)]),- "Could not verify Windows gateway profile %s after update: %s", name, default=[])- if pids:- ready_profiles.append(name)- ready_pids.extend(pids)- ready_unmapped = []- for entry in unmapped:- pids = _try_call(lambda e=entry: gateway_windows._wait_for_gateway_ready(- timeout_s=budget(), all_profiles=True, pid_filter=_unmapped_ready_filter(e, set(ready_pids))),- "Could not verify unmapped Windows gateway (pid %s) after update: %s", entry.get("pid"), default=[])- if pids:- ready_unmapped.append(entry)- ready_pids.extend(pids[:1])+ taken: set = set()+ # Profiles first: a gateway on a profile's home is that profile's, never an unmapped entry's.+ targets = [(("profile", name), lambda _scan, h=Path(get_profile_dir(name)), o=int(old_pid): gateway_windows._live_gateway_pids(+ home=h, pid_filter=lambda ps: [p for p in ps if int(p) != o]), True) for name, old_pid in sorted(profiles.items())]+ targets += [(("unmapped", i), lambda scan, f=_unmapped_ready_filter(entry, taken): f(scan()), False)+ for i, entry in enumerate(unmapped)]+ ready = _poll_until_ready(targets, deadline, taken)+ ready_profiles = [name for name in sorted(profiles) if ("profile", name) in ready]+ ready_unmapped = [entry for i, entry in enumerate(unmapped) if ("unmapped", i) in ready]+ ready_pids = [pid for pids in ready.values() for pid in pids]# Fleet reconciliation (#91277) cross-checks every planned runtime against relaunched_profiles:# only a verified one is listed, so an unready one still surfaces as unaccounted.token["relaunched_profiles"] = ready_profilesdiff --git a/tests/hermes_cli/test_windows_relaunch_ready_poll.py b/tests/hermes_cli/test_windows_relaunch_ready_poll.pynew file mode 100644index 00000000000..9bba794414c--- /dev/null+++ b/tests/hermes_cli/test_windows_relaunch_ready_poll.py@@ -0,0 +1,83 @@+"""Post-update relaunch verification polls every paused target at once (#132338 review, kshitij).++Each relaunched profile / unmapped gateway is retired only on its own stable readiness, and before+this every target ran its own confirmation window in turn: N targets cost N windows (5 profiles,+10 s) where the fleet-wide wait had cost one. One loop keeps the per-target crediting.++Real ``_verify_relaunched_gateways_alive`` and its poll; the seam is the PID-file read that says+which gateway each profile home runs (``get_running_pid``), so no process is spawned or signalled.+"""++from __future__ import annotations++import time++import pytest++from gateway import status+from hermes_cli import gateway_windows, update_cmd_windows+from hermes_cli.update_cmd_windows import _READY_CONFIRM_S, _verify_relaunched_gateways_alive+++def running(monkeypatch):+ """``{profile: callable -> pid or None}``: what each profile home's PID file names right now."""+ table: dict = {}+ monkeypatch.setattr(status, "get_running_pid",+ lambda path, cleanup_stale=False: (table.get(path.parent.name) or (lambda: None))())+ monkeypatch.setattr(status, "_pid_exists", lambda pid: False) # every old gateway is gone+ monkeypatch.setattr(gateway_windows, "_write_start_attestation", lambda *a, **k: None)+ return table+++def test_many_ready_targets_cost_one_confirmation_window(running):+ profiles = {f"p{i}": 40000 + i for i in range(6)}+ for i, name in enumerate(profiles):+ running[name] = lambda pid=50000 + i: pid+ token = {"profiles": dict(profiles), "unmapped": []}+ started = time.monotonic()+ _verify_relaunched_gateways_alive(token, profiles, [])+ elapsed = time.monotonic() - started+ assert token["relaunched_profiles"] == sorted(profiles) and token["profiles"] == {}+ assert elapsed < 2 * _READY_CONFIRM_S, f"6 ready targets took {elapsed:.1f}s: verified one after another"+++def test_each_target_is_credited_only_on_its_own_stable_gateway(running, monkeypatch):+ monkeypatch.setattr(update_cmd_windows, "_RELAUNCH_VERIFY_TIMEOUT_S", 3.0)+ born = time.monotonic()+ running["up"] = lambda: 50001+ running["old"] = lambda: 40002 # only the process the relaunch replaces+ running["flaps"] = lambda: 50003 if time.monotonic() - born < 1.0 else None # died during confirmation+ profiles = {"up": 40001, "old": 40002, "flaps": 40003, "never": 40004}+ token = {"profiles": dict(profiles), "unmapped": []}+ with pytest.raises(RuntimeError, match="not verified alive: flaps, never, old"):+ _verify_relaunched_gateways_alive(token, profiles, [])+ assert token["relaunched_profiles"] == ["up"]+ assert sorted(token["profiles"]) == ["flaps", "never", "old"]++[email protected]("linux")[email protected]_gateway_lookalike # a stub child that sleeps; reaped below+def test_one_gateway_never_retires_two_unmapped_debts(running, monkeypatch, tmp_path):+ import os+ import subprocess+ import sys++ from hermes_cli import gateway+ monkeypatch.setattr(update_cmd_windows, "_RELAUNCH_VERIFY_TIMEOUT_S", 3.0)+ entry = tmp_path / "bin" / "hermes"+ entry.parent.mkdir()+ entry.write_text("import time\ntime.sleep(60)\n", encoding="utf-8")+ argv = [sys.executable, str(entry), "gateway", "run"]+ # Pre-home entries (an older updater's token): argv is all that identifies them.+ debts = [{"pid": 40011, "argv": argv}, {"pid": 40012, "argv": argv}]+ child = subprocess.Popen(argv, env=dict(os.environ))+ try:+ monkeypatch.setattr(gateway, "find_gateway_pids", lambda all_profiles=False: [child.pid])+ token = {"profiles": {}, "unmapped": list(debts)}+ with pytest.raises(RuntimeError, match="pid 40012"):+ _verify_relaunched_gateways_alive(token, {}, debts)+ assert token["unmapped"] == [debts[1]], "one relaunched gateway retired both debts"+ finally:+ child.kill()+ child.wait(timeout=10)diff --git a/tests/hermes_cli/test_windows_update_restart_reconciliation.py b/tests/hermes_cli/test_windows_update_restart_reconciliation.pyindex a7599388c23..f65cab97d65 100644--- a/tests/hermes_cli/test_windows_update_restart_reconciliation.py+++ b/tests/hermes_cli/test_windows_update_restart_reconciliation.py@@ -37,6 +37,9 @@ def _stub_post_relaunch_liveness(monkeypatch):monkeypatch.setattr(gateway_windows, "_wait_for_gateway_ready", lambda **_kw: [4242])+ # The relaunch verifier polls every target in one loop through the same probe.+ monkeypatch.setattr(gateway_windows, "_live_gateway_pids", lambda *_a, **_kw: [4242])+ monkeypatch.setattr("hermes_cli.update_cmd_windows._READY_CONFIRM_S", 0.0)monkeypatch.setattr(gateway_windows, "_write_start_attestation", lambda *_a, **_kw: None)