The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): keep the supervisor the sole restart owner on both handback branches
liuhao10249ef2dd0be184
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.pyindex 3e9394ff03b..c6080e8c1a7 100644--- a/hermes_cli/gateway.py+++ b/hermes_cli/gateway.py@@ -6262,6 +6262,36 @@ def _restart_all(system: bool) -> None:_service_call(kind, "start", system)+def _wait_for_supervised_gateway_replacement(+ old_pid: int, timeout: float | None = None, *, poll_interval: float = 0.5+) -> int | None:+ """Poll the pidfile until the supervisor's replacement gateway registers a fresh PID.++ A graceful SIGUSR1 exit only proves the old process left — an unloaded, broken, or+ stopped-retrying supervisor leaves the gateway down. Custom-supervisor counterpart of+ ``_wait_for_launchd_service_pid``: the label is invisible to launchctl queries, so+ identity comes from ``get_running_pid``'s lock+PID liveness verification and freshness+ from ``!= old_pid``. Returns the fresh PID, or None once ``timeout`` passes.+ """+ from gateway.status import get_running_pid++ if timeout is None:+ timeout = SUPERVISED_REPLACEMENT_VERIFY_TIMEOUT+ deadline = time.monotonic() + max(timeout, 0.5)+ while True:+ pid = get_running_pid()+ if pid is not None and pid > 0 and pid != old_pid:+ return pid+ if time.monotonic() >= deadline:+ return None+ time.sleep(poll_interval)+++# A custom KeepAlive supervisor keeps its own respawn interval (launchd's is ~once per 10s,+# per LAUNCHD_SUPERVISION_VERIFY_TIMEOUT); 15s matches _wait_for_launchd_service_pid's budget.+SUPERVISED_REPLACEMENT_VERIFY_TIMEOUT = 15.0++def _cmd_restart(args):_refuse_from_inside_gateway("restart", "restart loops")system = getattr(args, "system", False)@@ -6324,11 +6354,29 @@ def _cmd_restart(args):print(f"→ Restarting externally-supervised gateway (PID {supervised_pid}) — "f"draining in-flight runs (up to {wait_budget:.0f}s)...")if _graceful_restart_via_sigusr1(supervised_pid, wait_budget):- print()- print("✓ Gateway exited for its supervisor to relaunch it")- print(" (a KeepAlive supervisor revives it within its respawn interval)")- return- print(f"⚠ Gateway drain timed out after {wait_budget:.0f}s — falling back to stop/restart")+ # A clean exit doesn't prove supervision — the marker lives in argv, not in a+ # loaded job. launchd_restart verifies a replacement PID for the same reason:+ # a broken/unloaded supervisor must surface as a failed restart, never a+ # success printed over a dead gateway.+ replacement_pid = _wait_for_supervised_gateway_replacement(supervised_pid)+ if replacement_pid is not None:+ print()+ print(f"✓ Gateway relaunched by its supervisor (PID {replacement_pid})")+ return+ print("⚠ Supervisor did not relaunch the gateway after its graceful exit")+ else:+ print(f"⚠ Gateway drain timed out after {wait_budget:.0f}s")+ # The supervisor stays the sole restart owner: falling through to stop + foreground+ # run would SIGTERM a KeepAlive-armed process and stamp this CLI's PID, so every+ # supervisor respawn then refuses with "Gateway already running" (#110637) — the+ # exact wedge this handback exists to prevent. Fail loudly and leave ownership be.+ _print_lines(+ "",+ "✗ Not stopping or foreground-running a supervisor-owned gateway.",+ " Check the supervisor (it may be unloaded, wedged, or stopped retrying),",+ " then rerun once it is healthy: hermes gateway restart",+ )+ sys.exit(1)if stop_profile_gateway():print("✓ Stopped gateway for this profile")diff --git a/tests/hermes_cli/test_gateway_restart_external_supervisor.py b/tests/hermes_cli/test_gateway_restart_external_supervisor.pyindex 97859f4b6c2..c797736735b 100644--- a/tests/hermes_cli/test_gateway_restart_external_supervisor.py+++ b/tests/hermes_cli/test_gateway_restart_external_supervisor.py@@ -8,6 +8,13 @@ with "Gateway already running (PID <restart>)" — the gateway stays down untilprocess is killed (#110637). The fix trusts the same ``--external-supervisor`` argv markerthe update path uses (``_prepare_profile_gateway_update_restart``) and SIGUSR1s the gatewayso it drains, exits, and lets the supervisor relaunch it.++The handback keeps the supervisor the sole restart owner on both lifecycle branches: a+graceful exit only reports success after a fresh, pidfile-verified replacement PID appears+(a broken/unloaded supervisor must fail loudly, not print success over a dead gateway — the+same contract ``launchd_restart`` enforces via ``_wait_for_launchd_service_pid``), and a+drain timeout never falls back to SIGTERM + foreground run (that fallback recreates the+competing-owner wedge this fix exists to remove)."""from types import SimpleNamespace@@ -25,13 +32,23 @@ SUPERVISED_ARGV = [def restart_calls(monkeypatch):"""Drive ``_cmd_restart`` to the manual fallback (no service kind) and record the exits."""calls = {"sigusr1": None, "stopped": False, "started": False}+ replacement = {"pid": 5555}++ def _running_pid(*a, **k):+ # The supervised gateway holds the pidfile until the drain completes; after a+ # graceful exit only the supervisor's replacement can register a fresh PID.+ if calls["sigusr1"] is not None and calls["sigusr1_returns"]:+ return replacement["pid"]+ return 4321+monkeypatch.setattr(gw, "_refuse_from_inside_gateway", lambda *a, **k: None)monkeypatch.setattr(gw, "_guard_named_profile_under_multiplexer", lambda **k: None)monkeypatch.setattr(gw, "_dispatch_via_service_manager_if_s6", lambda *a, **k: False)monkeypatch.setattr(gw, "_installed_service_kind_for", lambda windows: None)monkeypatch.setattr(gw, "_get_restart_exit_wait_budget", lambda: 7.0)- monkeypatch.setattr(gateway_status, "get_running_pid", lambda *a, **k: 4321)+ monkeypatch.setattr(gateway_status, "get_running_pid", _running_pid)monkeypatch.setattr(gw, "_capture_gateway_argv", lambda pid: SUPERVISED_ARGV if pid == 4321 else None)+ monkeypatch.setattr(gw, "SUPERVISED_REPLACEMENT_VERIFY_TIMEOUT", 0.5)def _sigusr1(pid, budget, **k):calls["sigusr1"] = (pid, budget)@@ -42,6 +59,7 @@ def restart_calls(monkeypatch):monkeypatch.setattr(gw, "_wait_for_gateway_exit", lambda **k: None)monkeypatch.setattr(gw, "run_gateway", lambda **k: calls.__setitem__("started", True))calls["sigusr1_returns"] = True+ calls["_replacement"] = replacementreturn calls@@ -54,7 +72,32 @@ def test_external_supervisor_gateway_restarts_via_sigusr1_handback(restart_callsassert restart_calls["sigusr1"] == (4321, 7.0), "must SIGUSR1 the supervised gateway, not stop it"assert not restart_calls["stopped"], "the CLI must not SIGTERM a supervisor-owned gateway"assert not restart_calls["started"], "a foreground run would stamp the CLI PID and wedge respawns"- assert "supervisor to relaunch" in capsys.readouterr().out+ out = capsys.readouterr().out+ assert "relaunched by its supervisor" in out, (+ "success must ride on the verified replacement, not the bare exit"+ )+ assert "5555" in out, "the fresh supervisor PID is the success evidence"+++def test_graceful_exit_without_replacement_fails_loud(restart_calls, capsys):+ # An unloaded/broken supervisor never relaunches: the bare exit must not read as success.+ restart_calls["_replacement"]["pid"] = None+ with pytest.raises(SystemExit) as exc:+ _run_restart()+ assert exc.value.code == 1+ assert not restart_calls["stopped"] and not restart_calls["started"], \+ "the CLI must not take restart ownership from a broken supervisor either"+ assert "did not relaunch" in capsys.readouterr().out+++def test_drain_timeout_fails_loud_without_taking_ownership(restart_calls, capsys):+ restart_calls["sigusr1_returns"] = False+ with pytest.raises(SystemExit) as exc:+ _run_restart()+ assert exc.value.code == 1+ assert restart_calls["sigusr1"] == (4321, 7.0), "the graceful handback must be attempted first"+ assert not restart_calls["stopped"] and not restart_calls["started"], \+ "SIGTERM + foreground run would recreate the competing-owner wedge (#110637)"def test_plain_manual_gateway_still_uses_stop_and_run(restart_calls, monkeypatch):@@ -71,11 +114,3 @@ def test_uncapturable_gateway_still_uses_stop_and_run(restart_calls, monkeypatch_run_restart()assert restart_calls["sigusr1"] is Noneassert restart_calls["started"], "capture failure must degrade to the existing fallback, never a silent no-op"---def test_drain_timeout_falls_back_to_stop_and_run(restart_calls):- restart_calls["sigusr1_returns"] = False- _run_restart()- assert restart_calls["sigusr1"] == (4321, 7.0), "the graceful handback must be attempted first"- assert restart_calls["stopped"] and restart_calls["started"], \- "a wedged/timed-out drain must still complete the restart, not strand the gateway down"