Skip to content

The agent that grows with you

fix(launchd): stop stranding gateway label on plist reload

Rob Hilgeforta1e4c905f525
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index 2a03ff1004e..ab33508d115 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -308,6 +308,32 @@ def _graceful_restart_via_sigusr1(pid: int, drain_timeout: float) -> bool:
return False
+def _wait_for_pid_exit(pid: int, timeout: float) -> bool:
+ """Wait up to ``timeout`` seconds for ``pid`` to leave the process table.
+
+ ``launchctl bootstrap`` of a label whose previous instance is still draining
+ fails with EIO ("already loaded"), so callers that tear the gateway down
+ must wait for the old process to actually exit before re-bootstrapping.
+
+ Returns True once the PID is gone (or was never alive), False on timeout.
+ """
+ if pid <= 0:
+ return True
+
+ import time as _time
+
+ # ``os.kill(pid, 0)`` hard-kills on Windows — use the cross-platform helper.
+ from gateway.status import _pid_exists
+
+ deadline = _time.monotonic() + max(timeout, 0.0)
+ while True:
+ if not _pid_exists(pid):
+ return True
+ if _time.monotonic() >= deadline:
+ return False
+ _time.sleep(0.5)
+
+
def _get_ancestor_pids() -> set[int]:
"""Return the set of PIDs in the current process's ancestor chain.
@@ -4199,9 +4225,21 @@ def refresh_launchd_plist_if_needed() -> bool:
except Exception:
gateway_pid = None
+ # NOTE: POSIX ancestry is NOT a reliable test for "the bootout will kill us".
+ # What bootout tears down is the launchd job's process *coalition*, and
+ # coalition membership is inherited at spawn — it survives reparenting. A
+ # process the gateway spawned whose intermediate parent has since exited is
+ # reparented to PID 1, so the gateway is no longer an ancestor, yet the
+ # process is still in the coalition and still dies with it. That
+ # misclassification stranded the job on 2026-08-05: the in-process retry loop
+ # below was killed mid-bootstrap (4 attempts, rc=5, no exhaustion line) and
+ # nothing was left to re-register the label, so KeepAlive could not revive it.
+ #
+ # Since the detached helper is also correct when we are genuinely outside the
+ # coalition (just asynchronous), always prefer it and keep the in-process path
+ # only as the fallback for when the helper cannot be spawned.
if (
gateway_pid is not None
- and _is_pid_ancestor_of_current_process(gateway_pid)
and hasattr(os, "setsid") # POSIX-only; launchd is macOS so always true here
):
# Delegate to a new session: `start_new_session=True` detaches the
@@ -4239,6 +4277,20 @@ def refresh_launchd_plist_if_needed() -> bool:
reload_script = (
f"sleep 2; "
f"launchctl bootout {shlex.quote(target)} 2>/dev/null; "
+ # Wait for the OLD gateway to actually exit before bootstrapping.
+ # bootout only sends SIGTERM; the gateway then drains in-flight agent
+ # runs (up to agent.restart_drain_timeout), and every bootstrap issued
+ # while it is still draining fails EIO ("already loaded"). Racing the
+ # drain is what burned the retry budget on 2026-08-05.
+ f"_wait_deadline=$(($(date +%s) + {_reload_budget})); "
+ f"while kill -0 {gateway_pid} 2>/dev/null; do "
+ f" if [ $(date +%s) -ge $_wait_deadline ]; then "
+ f" echo \"[$(date '+%Y-%m-%d %H:%M:%S %z')] old gateway pid {gateway_pid} still alive after {_reload_budget}s drain wait — bootstrapping anyway\" >> {shlex.quote(str(reload_log_path))}; "
+ f" break; "
+ f" fi; "
+ f" sleep 1; "
+ f"done; "
+ # Let launchd finish unregistering the label after the process exits.
f"sleep 1; "
f"_deadline=$(($(date +%s) + {_reload_budget})); "
f"while :; do "
@@ -4282,16 +4334,21 @@ def refresh_launchd_plist_if_needed() -> bool:
stderr=subprocess.DEVNULL,
)
except Exception as e:
+ # Don't give up — fall through to the in-process bootout/bootstrap
+ # below. It risks being killed mid-reload if we share the gateway's
+ # coalition, but an attempt beats leaving the plist updated and the
+ # service never reloaded.
logger.warning("Deferred launchd reload could not be spawned: %s", e)
_append_launchd_reload_log(
- f"FAILED to spawn launchd reload helper for {target}: {e}"
+ f"FAILED to spawn launchd reload helper for {target}: {e} — "
+ f"falling back to in-process bootout/bootstrap"
)
- return False
- print(
- "↻ Updated gateway launchd service definition; reload deferred to a "
- "transient launchd job (refresh ran inside the gateway process tree)"
- )
- return True
+ else:
+ print(
+ "↻ Updated gateway launchd service definition; reload deferred to "
+ "a transient launchd job (survives the bootout of this process)"
+ )
+ return True
# Bootout/bootstrap so launchd picks up the new definition. The reported
# incident (2026-06-26) happened when bootout succeeded but bootstrap
@@ -4310,6 +4367,16 @@ def refresh_launchd_plist_if_needed() -> bool:
# fixed ~10s: the failure mode occurs while the old gateway is still
# draining, so a short window can exhaust before launchd settles.
_reload_budget = max(30.0, _get_restart_drain_timeout())
+ # Wait out the old gateway's drain first, so the retry budget is spent on
+ # real bootstrap failures rather than on EIO ("already loaded") responses
+ # that are guaranteed while the previous instance is still shutting down.
+ if gateway_pid is not None and not _wait_for_pid_exit(
+ gateway_pid, _reload_budget
+ ):
+ _append_launchd_reload_log(
+ f"old gateway pid {gateway_pid} still alive after "
+ f"{int(_reload_budget)}s drain wait — bootstrapping {target} anyway"
+ )
_deadline = time.monotonic() + _reload_budget
if not _retry_launchctl_bootstrap_until_registered(
domain, plist_path, label, deadline=_deadline
diff --git a/tests/hermes_cli/test_gateway_service.py b/tests/hermes_cli/test_gateway_service.py
index 5b1a9260f8b..ea2c60f4d2d 100644
--- a/tests/hermes_cli/test_gateway_service.py
+++ b/tests/hermes_cli/test_gateway_service.py
@@ -264,6 +264,25 @@ class TestGatewayStopCleanup:
class TestLaunchdServiceRecovery:
+ def test_wait_for_pid_exit_returns_when_process_gone(self, monkeypatch):
+ alive = [True, True, False]
+ monkeypatch.setattr(
+ "gateway.status._pid_exists", lambda pid: alive.pop(0) if alive else False
+ )
+ monkeypatch.setattr(gateway_cli.time, "sleep", lambda s: None)
+
+ assert gateway_cli._wait_for_pid_exit(4242, timeout=30) is True
+ assert not alive # polled until the PID disappeared
+
+ def test_wait_for_pid_exit_times_out_on_wedged_process(self, monkeypatch):
+ """A wedged gateway must not block the reload forever."""
+ monkeypatch.setattr("gateway.status._pid_exists", lambda pid: True)
+
+ assert gateway_cli._wait_for_pid_exit(4242, timeout=0) is False
+
+ def test_wait_for_pid_exit_ignores_nonpositive_pid(self):
+ assert gateway_cli._wait_for_pid_exit(0, timeout=30) is True
+
def test_refresh_defers_reload_when_running_inside_gateway_tree(self, tmp_path, monkeypatch):
@@ -334,6 +353,209 @@ class TestLaunchdServiceRecovery:
submit_label = cmd[cmd.index("-l") + 1]
assert f"launchctl remove {submit_label}" in script
+ def test_refresh_defers_reload_even_when_not_a_posix_descendant(self, tmp_path, monkeypatch):
+ """The detached helper is used even when the gateway is NOT an ancestor.
+
+ POSIX ancestry does not decide who ``bootout`` kills — the launchd job's
+ process *coalition* does, and coalition membership is inherited at spawn
+ and survives reparenting. A gateway-spawned process whose intermediate
+ parent has exited is reparented to PID 1 (gateway no longer an ancestor)
+ yet still dies with the coalition. Trusting ancestry stranded the job on
+ 2026-08-05: the in-process retry loop was killed mid-bootstrap and
+ nothing re-registered the label. So always prefer the detached helper.
+ """
+ plist_path = tmp_path / "ai.hermes.gateway.plist"
+ plist_path.write_text("<plist>old content</plist>", encoding="utf-8")
+
+ monkeypatch.setattr(gateway_cli, "get_launchd_plist_path", lambda: plist_path)
+ monkeypatch.setattr(gateway_cli, "launchd_plist_is_current", lambda: False)
+ monkeypatch.setattr(
+ gateway_cli,
+ "generate_launchd_plist",
+ lambda: (
+ "<plist>--replace\n<key>HERMES_HOME</key>"
+ "<string>/Users/alice/.hermes</string></plist>"
+ ),
+ )
+ # Gateway running, but we are NOT inside its tree.
+ monkeypatch.setattr("gateway.status.get_running_pid", lambda *a, **k: 4242)
+ monkeypatch.setattr(
+ gateway_cli, "_is_pid_ancestor_of_current_process", lambda pid: False
+ )
+
+ run_calls = []
+
+ def fake_run(cmd, check=False, **kwargs):
+ run_calls.append(cmd)
+ return SimpleNamespace(returncode=0, stdout="", stderr="")
+
+ monkeypatch.setattr(gateway_cli.subprocess, "run", fake_run)
+
+ popen_calls = []
+ monkeypatch.setattr(
+ gateway_cli.subprocess, "Popen",
+ lambda cmd, **kw: popen_calls.append(cmd) or SimpleNamespace(pid=1),
+ )
+
+ result = gateway_cli.refresh_launchd_plist_if_needed()
+
+ assert result is True
+ # Reload was delegated, NOT run in-process where bootout could kill it.
+ assert len(popen_calls) == 1
+ assert popen_calls[0][:2] == ["launchctl", "submit"]
+ assert not [c for c in run_calls if "bootout" in c or "bootstrap" in c]
+
+
+ def test_deferred_reload_waits_for_old_gateway_pid_before_bootstrap(
+ self, tmp_path, monkeypatch
+ ):
+ """The helper must wait for the old gateway to exit before bootstrapping.
+
+ ``bootout`` only sends SIGTERM; the gateway then drains in-flight agent
+ runs (agent.restart_drain_timeout, default 180s). Every ``bootstrap``
+ issued while it drains fails EIO ("already loaded"), which is how the
+ retry budget got burned on 2026-08-05 (4 attempts, all rc=5).
+ """
+ plist_path = tmp_path / "ai.hermes.gateway.plist"
+ plist_path.write_text("<plist>old content</plist>", encoding="utf-8")
+
+ monkeypatch.setattr(gateway_cli, "get_launchd_plist_path", lambda: plist_path)
+ monkeypatch.setattr(gateway_cli, "launchd_plist_is_current", lambda: False)
+ monkeypatch.setattr(
+ gateway_cli,
+ "generate_launchd_plist",
+ lambda: (
+ "<plist>--replace\n<key>HERMES_HOME</key>"
+ "<string>/Users/alice/.hermes</string></plist>"
+ ),
+ )
+ monkeypatch.setattr("gateway.status.get_running_pid", lambda *a, **k: 4242)
+ monkeypatch.setattr(
+ gateway_cli.subprocess,
+ "run",
+ lambda cmd, check=False, **kw: SimpleNamespace(
+ returncode=0, stdout="", stderr=""
+ ),
+ )
+
+ popen_calls = []
+ monkeypatch.setattr(
+ gateway_cli.subprocess,
+ "Popen",
+ lambda cmd, **kw: popen_calls.append(cmd) or SimpleNamespace(pid=1),
+ )
+
+ assert gateway_cli.refresh_launchd_plist_if_needed() is True
+
+ cmd = popen_calls[0]
+ script = cmd[cmd.index("--") + 3]
+ # Waits on the OLD pid, and does so AFTER bootout but BEFORE bootstrap.
+ assert "kill -0 4242" in script
+ assert (
+ script.index("bootout")
+ < script.index("kill -0 4242")
+ < script.index("bootstrap")
+ )
+ # The wait must be bounded, so a wedged gateway can't block the reload.
+ assert "_wait_deadline" in script
+
+
+ def test_refresh_falls_back_to_direct_reload_when_helper_cannot_spawn(
+ self, tmp_path, monkeypatch
+ ):
+ """If the transient job can't be spawned, still attempt the reload.
+
+ Bailing out would leave the plist rewritten but the service never
+ reloaded. The in-process path waits out the old gateway's drain first so
+ its retry budget isn't spent on guaranteed-EIO bootstraps.
+ """
+ plist_path = tmp_path / "ai.hermes.gateway.plist"
+ plist_path.write_text("<plist>old content</plist>", encoding="utf-8")
+
+ monkeypatch.setattr(gateway_cli, "get_launchd_plist_path", lambda: plist_path)
+ monkeypatch.setattr(gateway_cli, "launchd_plist_is_current", lambda: False)
+ monkeypatch.setattr(
+ gateway_cli,
+ "generate_launchd_plist",
+ lambda: (
+ "<plist>--replace\n<key>HERMES_HOME</key>"
+ "<string>/Users/alice/.hermes</string></plist>"
+ ),
+ )
+ monkeypatch.setattr("gateway.status.get_running_pid", lambda *a, **k: 4242)
+
+ def boom(cmd, **kwargs):
+ raise OSError("launchctl submit unavailable")
+
+ monkeypatch.setattr(gateway_cli.subprocess, "Popen", boom)
+
+ waited = []
+ monkeypatch.setattr(
+ gateway_cli,
+ "_wait_for_pid_exit",
+ lambda pid, timeout: waited.append((pid, timeout)) or True,
+ )
+
+ run_calls = []
+
+ def fake_run(cmd, check=False, **kwargs):
+ run_calls.append(cmd)
+ if cmd[:2] == ["launchctl", "list"]:
+ # Post-bootstrap launchd reports a supervised PID; without one
+ # the success check correctly refuses to stop retrying.
+ return SimpleNamespace(
+ returncode=0,
+ stdout='{\n\t"PID" = 5150;\n\t"Label" = "ai.hermes.gateway";\n};',
+ stderr="",
+ )
+ return SimpleNamespace(returncode=0, stdout="", stderr="")
+
+ monkeypatch.setattr(gateway_cli.subprocess, "run", fake_run)
+
+ assert gateway_cli.refresh_launchd_plist_if_needed() is True
+
+ label = gateway_cli.get_launchd_label()
+ domain = gateway_cli._launchd_domain()
+ service_calls = [c for c in run_calls if "bootout" in c or "bootstrap" in c]
+ assert service_calls[:2] == [
+ ["launchctl", "bootout", f"{domain}/{label}"],
+ ["launchctl", "bootstrap", domain, str(plist_path)],
+ ]
+ # Drained the old pid between bootout and bootstrap.
+ assert waited and waited[0][0] == 4242
+
+
+ def test_registered_but_not_running_is_not_success(self, monkeypatch):
+ """A definition with no PID must not end the loop.
+
+ `launchctl list` exits 0 for a registered-but-not-running job (macOS
+ 26+ `state = not running`), so exit-0 alone would report success for a
+ gateway launchd is not actually running. Verified against live launchd
+ on 2026-08-05.
+ """
+ list_calls = {"n": 0}
+
+ def fake_run(cmd, check=False, **kwargs):
+ if cmd[:2] == ["launchctl", "list"]:
+ list_calls["n"] += 1
+ # Registered (exit 0) but no PID line — never running.
+ return SimpleNamespace(
+ returncode=0,
+ stdout='{\n\t"Label" = "ai.hermes.gateway";\n};',
+ stderr="",
+ )
+ return SimpleNamespace(returncode=0, stdout="", stderr="")
+
+ monkeypatch.setattr(gateway_cli.subprocess, "run", fake_run)
+ monkeypatch.setattr(gateway_cli.time, "sleep", lambda *_a, **_k: None)
+
+ ok = gateway_cli._retry_launchctl_bootstrap_until_registered(
+ self.DOMAIN, self.PLIST, self.LABEL,
+ deadline=gateway_cli.time.monotonic() - 1, # already expired
+ )
+ assert ok is False
+ assert list_calls["n"] >= 1
+
def test_launchd_domain_uses_user_domain(self, monkeypatch):
# The user/<uid> domain (not gui/<uid>) is the one reachable from