Skip to content

The agent that grows with you

fix(gateway): retry forced launchd install after drain

Lokee86ed103ebb570e
diff --git a/hermes_cli/gateway_launchd.py b/hermes_cli/gateway_launchd.py
index 5b6ab34465b..ae928f3eac9 100644
--- a/hermes_cli/gateway_launchd.py
+++ b/hermes_cli/gateway_launchd.py
@@ -605,6 +605,11 @@ def launchd_install(force: bool = False, *, start_now: bool = True):
# Loading the plist starts the gateway (RunAtLoad), so a no-start install writes it without
# loading it. A gateway that launchd already runs is still reloaded; this install did not start it.
load = start_now or _gw()._launchctl_label_supervising_process(label)
+ # A forced reinstall over a live job must remember the incumbent before bootstrap starts.
+ # _launchctl_bootstrap() handles EIO by booting the stale label out and retrying once, but
+ # that immediate retry races the old gateway's drain (#120629). The install path can wait
+ # because it runs outside the supervised gateway process.
+ force_old_pid = _gw()._launchctl_supervised_pid(label) if force and load else None
if plist_path.exists() and not force:
if _gw().launchd_plist_is_current():
@@ -648,11 +653,35 @@ def launchd_install(force: bool = False, *, start_now: bool = True):
print(" hermes gateway status # Check status")
return
- try:
- _gw()._launchctl_bootstrap(_gw()._launchd_domain(), plist_path, label, timeout=30)
- except subprocess.CalledProcessError as e:
- _gw()._launchd_degrade_or_raise(e, "launchctl bootstrap")
- return
+ if force_old_pid is not None:
+ domain = _gw()._launchd_domain()
+ target = f"{domain}/{label}"
+ budget = _gw()._launchd_reload_budget()
+ subprocess.run(
+ ["launchctl", "bootout", target],
+ check=False, timeout=90, **_gw()._CAPTURE_TEXT)
+ if not _gw()._wait_for_pid_exit(force_old_pid, budget):
+ _gw()._append_launchd_reload_log(
+ f"old gateway pid {force_old_pid} still alive after "
+ f"{int(budget)}s forced-install drain wait — bootstrapping {target} anyway"
+ )
+ if not _gw()._retry_launchctl_bootstrap_until_registered(
+ domain, plist_path, label, deadline=time.monotonic() + budget):
+ _gw()._append_launchd_reload_log(
+ f"FAILED forced launchd install of {target} — service NOT registered after "
+ f"retrying for {int(budget)}s"
+ )
+ _gw().print_error(
+ f"launchctl bootstrap did not register {target} within {int(budget)}s; "
+ "the gateway service is NOT loaded."
+ )
+ sys.exit(1)
+ else:
+ try:
+ _gw()._launchctl_bootstrap(_gw()._launchd_domain(), plist_path, label, timeout=30)
+ except subprocess.CalledProcessError as e:
+ _gw()._launchd_degrade_or_raise(e, "launchctl bootstrap")
+ return
print()
print("✓ Service installed and loaded!")
diff --git a/tests/hermes_cli/test_launchd_force_install_retry.py b/tests/hermes_cli/test_launchd_force_install_retry.py
new file mode 100644
index 00000000000..75739335afb
--- /dev/null
+++ b/tests/hermes_cli/test_launchd_force_install_retry.py
@@ -0,0 +1,81 @@
+"""Forced launchd reinstall must wait out the old supervised process before bootstrap (#120629)."""
+
+from types import SimpleNamespace
+
+import pytest
+
+import hermes_cli.gateway as gateway_cli
+
+
+LABEL = "ai.hermes.gateway"
+DOMAIN = "gui/501"
+
+
+def _forced_install_fixture(tmp_path, monkeypatch):
+ plist = tmp_path / "LaunchAgents" / f"{LABEL}.plist"
+ plist.parent.mkdir(parents=True)
+ plist.write_text("<old/>", encoding="utf-8")
+ events = []
+
+ monkeypatch.setattr(gateway_cli, "get_launchd_plist_path", lambda: plist)
+ monkeypatch.setattr(gateway_cli, "get_launchd_label", lambda: LABEL)
+ monkeypatch.setattr(gateway_cli, "_launchd_domain", lambda: DOMAIN)
+ monkeypatch.setattr(gateway_cli, "_launchctl_label_supervising_process", lambda _label: True)
+ monkeypatch.setattr(gateway_cli, "_launchctl_supervised_pid", lambda _label: 4242)
+ monkeypatch.setattr(gateway_cli, "generate_launchd_plist", lambda: "<new/>")
+ monkeypatch.setattr(gateway_cli, "_refuse_temp_home_service_write", lambda *_a: False)
+ monkeypatch.setattr(gateway_cli, "_clear_launchd_unsupported_marker", lambda: None)
+ monkeypatch.setattr(gateway_cli, "_launchd_reload_budget", lambda: 45.0)
+ monkeypatch.setattr(
+ gateway_cli, "_wait_for_pid_exit",
+ lambda pid, timeout: events.append(("wait", pid, timeout)) or True,
+ )
+ monkeypatch.setattr(gateway_cli, "_append_launchd_reload_log", lambda msg: events.append(("log", msg)))
+ monkeypatch.setattr(
+ gateway_cli, "_launchctl_bootstrap",
+ lambda *_a, **_k: pytest.fail("forced live reinstall must use the bounded retry path"),
+ )
+
+ def fake_run(cmd, *args, **kwargs):
+ events.append(("run", cmd))
+ return SimpleNamespace(returncode=0, stdout="", stderr="")
+
+ monkeypatch.setattr(gateway_cli.subprocess, "run", fake_run)
+ return plist, events
+
+
+def test_force_install_waits_for_incumbent_then_retries_until_supervised(tmp_path, monkeypatch, capsys):
+ plist, events = _forced_install_fixture(tmp_path, monkeypatch)
+
+ def retry(domain, plist_path, label, *, deadline):
+ events.append(("retry", domain, plist_path, label, deadline))
+ return True
+
+ monkeypatch.setattr(gateway_cli, "_retry_launchctl_bootstrap_until_registered", retry)
+
+ gateway_cli.launchd_install(force=True)
+
+ assert ("run", ["launchctl", "bootout", f"{DOMAIN}/{LABEL}"]) in events
+ wait_index = events.index(("wait", 4242, 45.0))
+ retry_index = next(i for i, event in enumerate(events) if event[0] == "retry")
+ assert wait_index < retry_index
+ assert plist.read_text(encoding="utf-8") == "<new/>"
+ assert "Service installed and loaded" in capsys.readouterr().out
+
+
+def test_force_install_fails_closed_when_launchd_never_registers(tmp_path, monkeypatch, capsys):
+ _plist, events = _forced_install_fixture(tmp_path, monkeypatch)
+ monkeypatch.setattr(
+ gateway_cli, "_retry_launchctl_bootstrap_until_registered",
+ lambda *_a, **_k: False,
+ )
+ errors = []
+ monkeypatch.setattr(gateway_cli, "print_error", errors.append)
+
+ with pytest.raises(SystemExit) as exc_info:
+ gateway_cli.launchd_install(force=True)
+
+ assert exc_info.value.code == 1
+ assert any("service is NOT loaded" in message for message in errors)
+ assert "Service installed and loaded" not in capsys.readouterr().out
+ assert any(event[0] == "wait" for event in events)