fix(update): verify the launchd job comes back on a fresh PID, follow wrapper plists, warn on --stop

Adopted from the sibling PRs in this cluster, with thanks:

- #99807 (@Chevron7Locked) and #101541 (@ivcdigital26): a kickstart that returns 0 is only
  "restart requested" — success now requires launchd to report a live PID other than the one
  that was stopped (the gateway's _wait_for_launchd_service_pid, 15 s), and a job that never
  comes back is reported with the manual `launchctl kickstart -k` command instead of a tick.
- #89793 (@mettamyron) and #101541: a plist may wrap the backend in `/bin/sh -c …` without
  exec, so launchd's live PID is the shell and the stale backend is its child — ownership now
  follows the parent chain (bounded, cycle-safe).
- #89793: `hermes dashboard --stop` on a launchd-owned backend now says a KeepAlive job
  restarts itself and gives the `launchctl bootout` command, instead of the misleading
  "restart it yourself" hint. The job scan runs for --stop too, on macOS only.
This commit is contained in:
John Paul Soliva
2026-09-15 17:34:49 +09:00
committed by Teknium
parent 99b727bd96
commit efc2b8e28d
3 changed files with 160 additions and 47 deletions
+43 -14
View File
@@ -345,22 +345,27 @@ def _kill_stale_dashboard_processes(
# Snapshot systemd unit/cgroup and argv BEFORE killing (the cgroup dies with the process).
pid_cgroup: dict[int, str | None] = {}
pid_service: dict[int, str | None] = {}
pid_launchd: dict[int, tuple[str, str]] = {}
pid_launchd: dict[int, tuple[str, str, int | None]] = {}
pid_cmdline: dict[int, list[str]] = {}
pid_home: dict[int, str | None] = {}
# macOS: a backend supervised by a launchd job (LaunchAgent / LaunchDaemon) must come back
# through launchd, never as a detached argv respawn — the respawn holds the job's port, the
# job then fails every KeepAlive restart with "port already in use", and the running backend
# is left unsupervised. Snapshot the loaded jobs once, before the kill; ``--stop`` reads them
# too, so it can say that a KeepAlive job will undo the stop.
launchd_jobs = _dash._loaded_launchd_backend_jobs() if sys.platform != "win32" else []
def _launchd_owner(pid: int, cmdline: list[str] | None):
return _dash._launchd_job_owning_backend(pid, cmdline, launchd_jobs, ancestors=_process_ancestors(pid))
if restart_managed and sys.platform != "win32":
# macOS: a backend supervised by a launchd job (LaunchAgent / LaunchDaemon) must come back
# through launchd, never as a detached argv respawn — the respawn holds the job's port, the
# job then fails every KeepAlive restart with "port already in use", and the running
# backend is left unsupervised. Snapshot the loaded jobs once, before the kill.
launchd_jobs = _dash._loaded_launchd_backend_jobs()
for pid in pids:
pid_cgroup[pid] = _dash._get_pid_cgroup_path(pid)
pid_service[pid] = _dash._get_systemd_service_for_pid(pid)
if pid_service[pid]:
continue
cmdline = _dash._dashboard_cmdline_for_pid(pid)
if launchd_jobs and (job := _dash._launchd_job_owning_backend(pid, cmdline, launchd_jobs)):
if launchd_jobs and (job := _launchd_owner(pid, cmdline)):
pid_launchd[pid] = job
elif cmdline:
# Manual process: exact argv + HERMES_HOME for the respawn and its profile cap.
@@ -374,6 +379,10 @@ def _kill_stale_dashboard_processes(
not in already_restarted_units]
if not pids:
return _empty_result()
elif launchd_jobs:
for pid in pids:
if job := _launchd_owner(pid, _dash._dashboard_cmdline_for_pid(pid)):
pid_launchd[pid] = job
print(f"\n⟲ Stopping {len(pids)} dashboard process(es) ({reason})")
killed: list[int] = []
failed: list[tuple[int, str]] = []
@@ -387,7 +396,12 @@ def _kill_stale_dashboard_processes(
killed, pid_service, pid_cgroup, pid_cmdline, pid_home, pid_launchd=pid_launchd)
else:
unrecovered = list(killed)
if killed:
# A stopped launchd job with KeepAlive restarts itself: say so instead of a misleading
# "restart it yourself" hint, and give the command that actually keeps it down.
for target in sorted({f"{d}/{l}" for p in killed if (j := pid_launchd.get(p)) for d, l, _ in (j,)}):
print(f" ⚠ PID(s) supervised by launchd job {target}: a KeepAlive job restarts itself.\n"
f" To keep it down: launchctl bootout {target}")
if any(p not in pid_launchd for p in killed):
print(" Restart the dashboard when you're ready:\n hermes dashboard --port <port>")
return {"matched": list(pids), "killed": list(killed), "failed": list(failed),
"unrecovered": list(unrecovered)}
@@ -396,7 +410,7 @@ def _kill_stale_dashboard_processes(
def _restart_killed_backends(
killed: list[int], pid_service: dict[int, str | None], pid_cgroup: dict[int, str | None],
pid_cmdline: dict[int, list[str]], pid_home: dict[int, str | None], *,
pid_launchd: dict[int, tuple[str, str]] | None = None) -> list[int]:
pid_launchd: dict[int, tuple[str, str, int | None]] | None = None) -> list[int]:
"""Update path: restart systemd units, kickstart launchd jobs (macOS), respawn manual argv
(detached, headless, logged to logs/dashboard-restart.log; one per profile, no ``--port 0``).
Returns PIDs not brought back."""
@@ -422,17 +436,19 @@ def _restart_killed_backends(
failed_restarts.append((svc_name, "systemctl restart returned non-zero"))
unrecovered.append(pid)
elif launchd_job:
# launchd owns the backend: the job brings it back (KeepAlive, or the kickstart below);
# an argv respawn would sit on the job's port and leave it failing forever.
domain, label = launchd_job
# launchd owns the backend: the job brings it back (KeepAlive, or the kickstart below),
# and success means launchd reports a fresh supervised PID — an argv respawn would sit
# on the job's port and leave it failing forever.
domain, label, old_pid = launchd_job
target = f"{domain}/{label}"
if target in seen_services:
continue
seen_services.add(target)
if _dash._try_kickstart_launchd_job(domain, label):
if _dash._restart_launchd_job(domain, label, old_pid):
print(f" ✓ restarted launchd job {target}")
else:
failed_restarts.append((target, f"launchctl kickstart failed; run: launchctl kickstart -k {target}"))
failed_restarts.append(
(target, f"launchd is not supervising a fresh process; run: launchctl kickstart -k {target}"))
unrecovered.append(pid)
elif pid in pid_cmdline:
respawn_candidates.append((pid, pid_cmdline[pid], pid_home.get(pid)))
@@ -540,6 +556,19 @@ def _flag_value(tokens: list[str], flag: str) -> str | None:
return None
def _process_ancestors(pid: int, *, max_depth: int = 8) -> list[int]:
"""Parent chain of *pid* (nearest first), stopping at init / a lookup failure / *max_depth*."""
chain: list[int] = []
current = pid
while len(chain) < max_depth:
parent = _process_ppid(current)
if parent is None or parent <= 1 or parent == pid or parent in chain:
break
chain.append(parent)
current = parent
return chain
def _process_ppid(pid: int) -> int | None:
"""Best-effort parent pid; None on failure (always None on Windows: desktop tree-kill reaps)."""
try:
+21 -12
View File
@@ -270,23 +270,32 @@ def _loaded_launchd_backend_jobs(
def _launchd_job_owning_backend(
pid: int, cmdline: list[str] | None, jobs: list[tuple[str, str, list[str], int | None]],
) -> tuple[str, str] | None:
"""``(domain, label)`` of the loaded launchd job that owns *pid*: launchd reports *pid* as the
job's live process, OR the process runs the job's exact ``ProgramArguments`` — a detached copy of
a supervised backend (an earlier respawn) holds the port the job needs, and respawning it again
would only re-create that conflict. None when no loaded job claims the process."""
ancestors: "list[int] | tuple[int, ...]" = (),
) -> tuple[str, str, int | None] | None:
"""``(domain, label, live_pid)`` of the loaded launchd job that owns *pid*: launchd reports *pid*
(or one of its *ancestors* — a plist may wrap the backend in ``/bin/sh -c …`` without ``exec``)
as the job's live process, OR the process runs the job's exact ``ProgramArguments`` — a detached
copy of a supervised backend (an earlier respawn) holds the port the job needs, and respawning it
again would only re-create that conflict. None when no loaded job claims the process."""
for domain, label, argv, live_pid in jobs:
if live_pid == pid or (cmdline is not None and list(cmdline) == argv):
return (domain, label)
if live_pid is not None and (live_pid == pid or live_pid in ancestors):
return (domain, label, live_pid)
if cmdline is not None and list(cmdline) == argv:
return (domain, label, live_pid)
return None
def _try_kickstart_launchd_job(domain: str, label: str) -> bool:
"""``launchctl kickstart <domain>/<label>`` (no ``-k``: the process was already stopped, and a
KeepAlive job may have respawned it — a kill would take that fresh process down). True on
success; False on a non-zero exit or when launchctl is unavailable / wedged."""
def _restart_launchd_job(domain: str, label: str, old_pid: int | None, *, timeout: float = 15.0) -> bool:
"""Bring a launchd-supervised backend back after its process was stopped: ``launchctl kickstart
<domain>/<label>`` (no ``-k`` — a KeepAlive job may already have respawned it, and a kill would
take that fresh process down), then require launchd to report a live PID other than *old_pid*
within *timeout*. A kickstart that returns 0 only means "restart requested"; a job that is loaded
but never comes back on a fresh PID is a failure the operator must hear about."""
from hermes_cli.gateway import _wait_for_launchd_service_pid
try:
return _run_probe(["launchctl", "kickstart", f"{domain}/{label}"], timeout=30).returncode == 0
if _run_probe(["launchctl", "kickstart", f"{domain}/{label}"], timeout=30).returncode != 0:
return False
return _wait_for_launchd_service_pid(label, old_pid=old_pid, timeout=timeout, domain=domain)
except _SYSTEMCTL_ERRORS:
return False
+96 -21
View File
@@ -56,6 +56,16 @@ def _refresh_bindings_against_live_module():
yield
@pytest.fixture(autouse=True)
def _no_real_launchd_jobs():
"""The kill path now scans the host's launchd jobs on macOS; a developer's own LaunchAgents
must never leak into these tests. Tests that need jobs patch the scan themselves; the one
test that exercises the real scan takes this fixture explicitly to get the original back."""
original = main_dashboard._loaded_launchd_backend_jobs
with patch.object(main_dashboard, "_loaded_launchd_backend_jobs", return_value=[]):
yield original
def _ps_line(pid: int, cmd: str) -> str:
"""Format a line as it would appear in ``ps -A -o pid=,command=`` output."""
return f"{pid:>7} {cmd}"
@@ -949,7 +959,7 @@ class TestLaunchdSupervisedBackends:
if sig == 0:
raise ProcessLookupError
def _run(self, pid, jobs, *, kickstart_ok=True):
def _run(self, pid, jobs, *, restart_ok=True, restart_managed=True, ancestors=()):
live = self._live()
with patch.object(main_dashboard, "_restart_managed_dashboard_service", return_value=False), \
patch.object(live, "_find_stale_dashboard_pids", return_value=[pid]), \
@@ -957,21 +967,22 @@ class TestLaunchdSupervisedBackends:
patch.object(main_dashboard, "_get_systemd_service_for_pid", return_value=None), \
patch.object(main_dashboard, "_dashboard_cmdline_for_pid", return_value=list(self.ARGV)), \
patch.object(main_dashboard, "_loaded_launchd_backend_jobs", return_value=jobs), \
patch.object(main_dashboard, "_try_kickstart_launchd_job", return_value=kickstart_ok) as kickstart, \
patch.object(main_dashboard, "_restart_launchd_job", return_value=restart_ok) as restart, \
patch("hermes_cli.dashboard_procs._process_ancestors", return_value=list(ancestors)), \
patch("hermes_cli.dashboard_procs._hermes_home_for_pid", return_value=None), \
patch.object(live, "_respawn_dashboard_processes", return_value=[]) as respawn, \
patch("os.kill", side_effect=self._fake_kill), \
patch("time.sleep"):
result = _kill_stale_dashboard_processes(restart_managed=True)
return result, kickstart, respawn
result = _kill_stale_dashboard_processes(restart_managed=restart_managed)
return result, restart, respawn
@pytest.mark.skipif(sys.platform == "win32", reason="POSIX cmdline capture + respawn")
def test_launchd_owned_pid_is_kickstarted_not_respawned(self, capsys):
"""launchd reports the PID as the job's live process → kickstart the job, never respawn."""
result, kickstart, respawn = self._run(9101, [("system", "ai.hermes.dashboard", list(self.ARGV), 9101)])
def test_launchd_owned_pid_is_restarted_through_launchd_not_respawned(self, capsys):
"""launchd reports the PID as the job's live process → restart the job, never respawn."""
result, restart, respawn = self._run(9101, [("system", "ai.hermes.dashboard", list(self.ARGV), 9101)])
respawn.assert_not_called()
kickstart.assert_called_once_with("system", "ai.hermes.dashboard")
restart.assert_called_once_with("system", "ai.hermes.dashboard", 9101)
assert result["killed"] == [9101]
assert result["unrecovered"] == []
out = capsys.readouterr().out
@@ -983,20 +994,32 @@ class TestLaunchdSupervisedBackends:
"""The state an earlier respawn leaves behind: the job is loaded but has no live process
(it fails on the port), and a detached copy runs its exact ProgramArguments. Killing the
copy hands the port back to the job; respawning it would recreate the conflict."""
result, kickstart, respawn = self._run(9102, [("system", "ai.hermes.dashboard", list(self.ARGV), None)])
result, restart, respawn = self._run(9102, [("system", "ai.hermes.dashboard", list(self.ARGV), None)])
respawn.assert_not_called()
kickstart.assert_called_once_with("system", "ai.hermes.dashboard")
restart.assert_called_once_with("system", "ai.hermes.dashboard", None)
assert result["unrecovered"] == []
assert "✓ restarted launchd job system/ai.hermes.dashboard" in capsys.readouterr().out
@pytest.mark.skipif(sys.platform == "win32", reason="POSIX cmdline capture + respawn")
def test_launchd_kickstart_failure_reports_the_manual_command(self, capsys):
result, kickstart, respawn = self._run(
9103, [("gui/501", "ai.hermes.dashboard", list(self.ARGV), 9103)], kickstart_ok=False)
def test_wrapper_plist_child_is_attributed_through_its_ancestors(self, capsys):
"""A plist that runs ``/bin/sh -c "… hermes dashboard …"`` without exec: launchd's live
PID is the shell, the stale backend PID is its child. Ownership follows the parent chain."""
wrapper_argv = ["/bin/sh", "-c", "exec-less wrapper: hermes dashboard --port 9119"]
result, restart, respawn = self._run(
9105, [("gui/501", "com.example.hermes-dashboard", wrapper_argv, 777)], ancestors=[777, 1])
respawn.assert_not_called()
kickstart.assert_called_once_with("gui/501", "ai.hermes.dashboard")
restart.assert_called_once_with("gui/501", "com.example.hermes-dashboard", 777)
assert result["unrecovered"] == []
@pytest.mark.skipif(sys.platform == "win32", reason="POSIX cmdline capture + respawn")
def test_launchd_restart_failure_reports_the_manual_command(self, capsys):
result, restart, respawn = self._run(
9103, [("gui/501", "ai.hermes.dashboard", list(self.ARGV), 9103)], restart_ok=False)
respawn.assert_not_called()
restart.assert_called_once_with("gui/501", "ai.hermes.dashboard", 9103)
assert result["unrecovered"] == [9103]
out = capsys.readouterr().out
assert "launchctl kickstart -k gui/501/ai.hermes.dashboard" in out
@@ -1006,26 +1029,78 @@ class TestLaunchdSupervisedBackends:
def test_unrelated_launchd_job_does_not_claim_a_manual_backend(self, capsys):
"""A loaded job with a different PID and different argv leaves the manual respawn intact."""
other_argv = ["hermes", "dashboard", "--port", "8300"]
result, kickstart, respawn = self._run(9104, [("gui/501", "ai.hermes.dashboard", other_argv, 777)])
result, restart, respawn = self._run(9104, [("gui/501", "ai.hermes.dashboard", other_argv, 777)])
kickstart.assert_not_called()
restart.assert_not_called()
respawn.assert_called_once_with([list(self.ARGV)])
assert result["unrecovered"] == []
def test_owning_job_matches_by_live_pid_or_exact_argv(self):
@pytest.mark.skipif(sys.platform == "win32", reason="POSIX cmdline capture + respawn")
def test_stop_says_a_keepalive_job_will_undo_the_stop(self, capsys):
"""``hermes dashboard --stop`` on a launchd-owned backend: no respawn, no "restart it
yourself" hint — the job comes back on its own; print how to keep it down instead."""
result, restart, respawn = self._run(
9106, [("system", "ai.hermes.dashboard", list(self.ARGV), 9106)], restart_managed=False)
restart.assert_not_called()
respawn.assert_not_called()
assert result["killed"] == [9106]
out = capsys.readouterr().out
assert "launchctl bootout system/ai.hermes.dashboard" in out
assert "when you're ready" not in out
def test_owning_job_matches_by_live_pid_ancestor_or_exact_argv(self):
jobs = [
("gui/501", "ai.hermes.dashboard", ["hermes", "dashboard", "--port", "8300"], 4242),
("system", "ai.hermes.serve", ["hermes", "serve", "--port", "8301"], None),
]
owning = main_dashboard._launchd_job_owning_backend
assert owning(4242, ["something", "else"], jobs) == ("gui/501", "ai.hermes.dashboard")
assert owning(9999, ["hermes", "serve", "--port", "8301"], jobs) == ("system", "ai.hermes.serve")
assert owning(4242, ["something", "else"], jobs) == ("gui/501", "ai.hermes.dashboard", 4242)
assert owning(9999, ["python"], jobs, ancestors=[4242, 1]) == ("gui/501", "ai.hermes.dashboard", 4242)
assert owning(9999, ["hermes", "serve", "--port", "8301"], jobs) == ("system", "ai.hermes.serve", None)
assert owning(9999, ["hermes", "serve", "--port", "8302"], jobs) is None
assert owning(9999, None, jobs) is None
assert owning(4242, None, []) is None
def test_process_ancestors_walks_to_init_and_stops_on_cycles(self):
parents = {900: 800, 800: 700, 700: 1}
with patch("hermes_cli.dashboard_procs._process_ppid", side_effect=lambda p: parents.get(p)):
assert dashboard_procs._process_ancestors(900) == [800, 700]
looped = {900: 800, 800: 900}
with patch("hermes_cli.dashboard_procs._process_ppid", side_effect=lambda p: looped.get(p)):
assert dashboard_procs._process_ancestors(900) == [800]
with patch("hermes_cli.dashboard_procs._process_ppid", return_value=None):
assert dashboard_procs._process_ancestors(900) == []
def test_restart_launchd_job_requires_a_fresh_supervised_pid(self):
"""kickstart returning 0 is only "restart requested": success needs launchd to report a
PID other than the one that was stopped."""
kickstarts: list[list[str]] = []
def fake_probe(cmd, *, timeout):
kickstarts.append(cmd)
return MagicMock(returncode=0)
with patch.object(main_dashboard, "_run_probe", side_effect=fake_probe), \
patch("hermes_cli.gateway._wait_for_launchd_service_pid", return_value=True) as wait:
assert main_dashboard._restart_launchd_job("system", "ai.hermes.dashboard", 4242) is True
assert kickstarts == [["launchctl", "kickstart", "system/ai.hermes.dashboard"]]
wait.assert_called_once_with("ai.hermes.dashboard", old_pid=4242, timeout=15.0, domain="system")
with patch.object(main_dashboard, "_run_probe", side_effect=fake_probe), \
patch("hermes_cli.gateway._wait_for_launchd_service_pid", return_value=False):
assert main_dashboard._restart_launchd_job("system", "ai.hermes.dashboard", 4242) is False
with patch.object(main_dashboard, "_run_probe", return_value=MagicMock(returncode=1)), \
patch("hermes_cli.gateway._wait_for_launchd_service_pid") as wait:
assert main_dashboard._restart_launchd_job("gui/501", "x", None) is False
wait.assert_not_called()
with patch.object(main_dashboard, "_run_probe", side_effect=FileNotFoundError("launchctl")):
assert main_dashboard._restart_launchd_job("gui/501", "x", None) is False
@pytest.mark.macos_only
def test_loaded_backend_jobs_scans_plists_and_probes_only_backend_labels(self, tmp_path):
def test_loaded_backend_jobs_scans_plists_and_probes_only_backend_labels(self, tmp_path, _no_real_launchd_jobs):
"""Only LOADED jobs whose ProgramArguments are a dashboard/serve backend are returned:
gateway jobs are never probed, unloaded backends are dropped, unreadable plists skipped,
and LaunchDaemons resolve to the system domain."""
@@ -1060,7 +1135,7 @@ class TestLaunchdSupervisedBackends:
return (False, None)
with patch("hermes_cli.gateway._launchd_print_service_pid", side_effect=fake_print):
jobs = main_dashboard._loaded_launchd_backend_jobs([("agent", agents), ("daemon", daemons)])
jobs = _no_real_launchd_jobs([("agent", agents), ("daemon", daemons)])
assert jobs == [
(f"user/{uid}", "ai.hermes.dashboard", backend_argv, 4242),