Skip to content

The agent that grows with you

fix(update): the invoking profile's launchd restart is claimed only on a pid that changed

teknium1e7e192817437
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index 60c2eeb2f51..d3074cd8be0 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -3565,14 +3565,23 @@ def _launchd_reload_budget() -> float:
return max(30.0, _get_restart_drain_timeout())
-def _launchctl_label_supervising_process(label: str) -> bool:
- """True when launchd knows ``label`` AND runs a process for it. ``launchctl list`` exits 0 for a
- mere registered definition (``state = not running`` on macOS 26+), so a positive PID is required."""
+def _launchctl_supervised_pid(label: str) -> int | None:
+ """PID launchd currently runs for ``label``, or None when it runs none. ``launchctl list`` exits 0 for
+ a mere registered definition (``state = not running`` on macOS 26+), so a PID — not the exit code — is
+ the answer. Domain-agnostic on purpose: ``launchctl print`` domain probes fail on macOS-26 per-user
+ domains, which is why the invoking profile verifies through this and not ``_launchd_print_service_pid``."""
try:
result = subprocess.run(["launchctl", "list", label], check=False, timeout=10, **_CAPTURE_TEXT)
except (subprocess.TimeoutExpired, OSError):
- return False
- return result.returncode == 0 and _parse_launchd_pid_from_list_output(result.stdout) is not None
+ return None
+ if result.returncode != 0:
+ return None
+ return _parse_launchd_pid_from_list_output(result.stdout)
+
+
+def _launchctl_label_supervising_process(label: str) -> bool:
+ """True when launchd knows ``label`` AND runs a process for it."""
+ return _launchctl_supervised_pid(label) is not None
def _retry_launchctl_bootstrap_until_registered(
@@ -4255,6 +4264,7 @@ def wait_for_launchd_gateway_supervision(
timeout: float = LAUNCHD_SUPERVISION_VERIFY_TIMEOUT,
label: str | None = None,
poll_interval: float = 0.5,
+ old_pid: int | None = None,
) -> bool:
"""Poll launchd until it supervises a live gateway; True at once if the detached fallback is active.
``launchd_restart`` returns once the restart is *requested* (asynchronous), so it can't see a helper
@@ -4266,8 +4276,12 @@ def wait_for_launchd_gateway_supervision(
bootstrap (#88848) — nor a ``launchctl bootstrap`` that exits 0 without registering, which the reporter
measured on macOS 26.6.1.
Judge the outcome the way #80491 taught the helper to judge it: by a live supervised pid, never by an
- exit code. :func:`_launchctl_label_supervising_process` is already that predicate, so this only adds
- the wait.
+ exit code. :func:`_launchctl_supervised_pid` is already that probe, so this only adds the wait.
+
+ ``old_pid`` is the pid launchd ran for the label *before* the restart: a restart that leaves the same
+ process running is not a restart, so passing it holds the invoking profile to the same fresh-pid
+ contract :func:`_wait_for_launchd_service_pid` enforces for sibling labels. With ``old_pid=None``
+ (no pre-restart pid was observable) any supervised pid counts, as before.
"""
if _launchd_unsupported_marker_exists():
return True
@@ -4275,7 +4289,8 @@ def wait_for_launchd_gateway_supervision(
label = label or get_launchd_label()
deadline = time.monotonic() + max(timeout, 0.0)
while True:
- if _launchctl_label_supervising_process(label):
+ pid = _launchctl_supervised_pid(label)
+ if pid is not None and pid != old_pid:
return True
if time.monotonic() >= deadline:
return False
diff --git a/hermes_cli/update_cmd_fleet.py b/hermes_cli/update_cmd_fleet.py
index 92306a44390..29e78585614 100644
--- a/hermes_cli/update_cmd_fleet.py
+++ b/hermes_cli/update_cmd_fleet.py
@@ -156,6 +156,9 @@ def _receipt_reports_stale_runtime(receipt: dict, expected_sha: str | None = Non
_SUPERVISED_SERVE_BACKENDS = frozenset({"manual-serve", "desktop", "systemd", "launchd", "windows-service", "service"})
# Backends whose supervisor restarts the process without any updater bookkeeping. ``manual-serve``
# is excluded: it owes a durable handoff (``defer_manual_serve``) before it stops counting.
+# ``systemd``/``windows-service``/``service`` mirror ``_SUPERVISED_SERVE_BACKENDS`` for parity only —
+# the inventory writer classifies a serve/dashboard row as exactly launchd, desktop or manual-serve
+# (``update_inventory._collect_ledger_runtimes``); those three are set for gateway rows alone.
_SUPERVISOR_OWNED_SERVE_BACKENDS = _SUPERVISED_SERVE_BACKENDS - {"manual-serve"}
@@ -250,6 +253,9 @@ def _marker_only_restart_obsolete() -> bool:
phase draws for the Desktop backend (#111494). Counting it made the warning permanently
undischargeable on every host that runs a dashboard. A manual-serve row still needs its
durable handoff (``defer_manual_serve``), and an unclassified backend stays fail-closed.
+ Discharging here strands nobody: the same row is still accounted at update time by
+ ``update_inventory.report_unaccounted_runtimes``, which prints it and exits 1 when the restart
+ phase never touched it — this marker only stops re-warning about it on every later startup.
"""
from hermes_cli.update_serve_obligations import defer_manual_serve
@@ -794,11 +800,17 @@ def _restart_launchd_gateway_after_update(*, supervision_verify: bool = True) ->
"""
from hermes_cli.gateway import (
get_launchd_label, get_launchd_plist_path, launchd_restart, wait_for_launchd_gateway_supervision,
+ _launchctl_supervised_pid,
)
current_label = get_launchd_label()
+ old_pid = None
try:
if not get_launchd_plist_path().exists():
return [], [] # not a launchd install — nothing to do or warn
+ # Snapshot BEFORE the restart: "supervising some pid" was true before too, so only a pid that
+ # actually changed distinguishes a restart from a no-op (the sibling loop's contract). Read-only
+ # and verification-only — the restart itself is never gated on `launchctl list` (#74973).
+ old_pid = _launchctl_supervised_pid(current_label) if supervision_verify else None
try:
launchd_restart()
except subprocess.CalledProcessError as e:
@@ -829,10 +841,10 @@ def _restart_launchd_gateway_after_update(*, supervision_verify: bool = True) ->
# domain locate fails on macOS-26 per-user domains.
# launchd_restart() returning is only "restart REQUESTED" — the self-restart branch hands work to the
# running gateway, a plist reload to a detached helper; both asynchronous. See #88848.
- if wait_for_launchd_gateway_supervision(label=current_label):
+ if wait_for_launchd_gateway_supervision(label=current_label, old_pid=old_pid):
return [current_label], []
print(
- f" ✗ {current_label} restarted but launchd is not supervising it.\n"
+ f" ✗ {current_label} restarted but launchd is not supervising a new process for it.\n"
" Check logs, then: hermes gateway restart"
)
return [], [current_label]
diff --git a/tests/hermes_cli/test_update_fleet_restart_pending.py b/tests/hermes_cli/test_update_fleet_restart_pending.py
index 567218fedaa..0928cdfc849 100644
--- a/tests/hermes_cli/test_update_fleet_restart_pending.py
+++ b/tests/hermes_cli/test_update_fleet_restart_pending.py
@@ -792,11 +792,17 @@ def test_startup_warn_discharged_when_multiplexer_covers_owed_profiles(monkeypat
assert update_cmd._pending_fleet_restart_needed() is False
[email protected]("supervisor", ["desktop", "systemd", "launchd", "windows-service", "service"])
[email protected]("supervisor", ["desktop", "launchd"])
def test_startup_warn_discharged_when_inventory_holds_supervised_serve(monkeypatch, capsys, supervisor):
"""A supervised serve/dashboard row in the marker's inventory is its supervisor's to
restart (#115090 for receipts, #111494 for the Desktop backend) — it must not make the
- gateway warning permanently undischargeable once every gateway serves the pulled SHA."""
+ gateway warning permanently undischargeable once every gateway serves the pulled SHA.
+
+ Only ``desktop`` and ``launchd`` are parametrized: those are the two supervisor values the
+ inventory writer can actually put on a serve/dashboard row (``update_inventory``'s ledger
+ pass emits exactly launchd, desktop or manual-serve). The systemd/windows-service/service
+ members of ``_SUPERVISOR_OWNED_SERVE_BACKENDS`` only ever appear on gateway rows.
+ """
disk_sha = "e" * 40
update_cmd._write_fleet_restart_pending_marker(
expected_sha=disk_sha,
diff --git a/tests/hermes_cli/test_update_launchd_restart_verification.py b/tests/hermes_cli/test_update_launchd_restart_verification.py
index db21980a2d3..d37c28cc43d 100644
--- a/tests/hermes_cli/test_update_launchd_restart_verification.py
+++ b/tests/hermes_cli/test_update_launchd_restart_verification.py
@@ -30,6 +30,9 @@ from hermes_cli.update_cmd import _warn_incomplete_gateway_fleet_restart
LABEL = "ai.hermes.gateway"
+# Captured at import so a test can re-install the real verifier over a fixture's stub.
+_REAL_WAIT_FOR_SUPERVISION = gateway_cli.wait_for_launchd_gateway_supervision
+
class _FakeClock:
"""Monotonic clock that only advances when the code under test sleeps.
@@ -68,12 +71,13 @@ def _no_detached_fallback(monkeypatch):
def _supervision_returning(*results):
- """Fake ``_launchctl_label_supervising_process`` yielding ``results`` in order.
+ """Fake ``_launchctl_supervised_pid`` yielding ``results`` in order.
- The final value repeats, so a test can say "False twenty times, then True
- from then on".
+ ``True``/``False`` are spelled as "some supervised pid" / "no pid"; an int
+ is passed through so a test can pin a specific pid. The final value
+ repeats, so a test can say "False twenty times, then True from then on".
"""
- seq = list(results)
+ seq = [4242 if r is True else (None if r is False else r) for r in results]
calls = []
def probe(label):
@@ -89,7 +93,7 @@ class TestWaitForLaunchdGatewaySupervision:
"""The common case must not cost a single sleep."""
monkeypatch.setattr(
gateway_cli,
- "_launchctl_label_supervising_process",
+ "_launchctl_supervised_pid",
_supervision_returning(True),
)
@@ -108,7 +112,7 @@ class TestWaitForLaunchdGatewaySupervision:
# 0.5s poll interval: 20 misses is ~10s of throttle, then the pid lands.
probe = _supervision_returning(*([False] * 20 + [True]))
monkeypatch.setattr(
- gateway_cli, "_launchctl_label_supervising_process", probe
+ gateway_cli, "_launchctl_supervised_pid", probe
)
assert gateway_cli.wait_for_launchd_gateway_supervision(label=LABEL) is True
@@ -118,7 +122,7 @@ class TestWaitForLaunchdGatewaySupervision:
"""A job that never comes back must fail, and must fail bounded."""
probe = _supervision_returning(False)
monkeypatch.setattr(
- gateway_cli, "_launchctl_label_supervising_process", probe
+ gateway_cli, "_launchctl_supervised_pid", probe
)
assert (
@@ -144,7 +148,7 @@ class TestWaitForLaunchdGatewaySupervision:
)
probe = _supervision_returning(False)
monkeypatch.setattr(
- gateway_cli, "_launchctl_label_supervising_process", probe
+ gateway_cli, "_launchctl_supervised_pid", probe
)
assert gateway_cli.wait_for_launchd_gateway_supervision(label=LABEL) is True
@@ -247,6 +251,48 @@ class TestInvokingProfileIsVerifiedLikeItsSiblings:
assert failed_or_stale == [LABEL]
assert LABEL in capsys.readouterr().out
+ def test_restart_that_leaves_the_old_pid_supervised_is_not_a_restart(
+ self, monkeypatch, capsys, clock
+ ):
+ """A4: the invoking profile's success claim needs a pid that CHANGED.
+
+ ``launchctl list <label>`` exits 0 with a positive pid both before and
+ after a reload that never happened, so "launchd supervises some pid"
+ was already true of the very process the update meant to replace: the
+ update printed ``✓ Restarted ai.hermes.gateway`` over pre-update code.
+ The sibling loop has required a fresh pid since f29ee96
+ (``_wait_for_launchd_service_pid(old_pid=...)``); this pins the same
+ contract for the profile running the update.
+
+ Driven through a fake ``launchctl`` (not a patched ``sys.platform``):
+ the seam is plain Python, so the fake pins the behaviour on any host.
+ """
+ calls = _patch_launchd_env(monkeypatch, supervised=True)
+ # ...but exercise the REAL verifier, not _patch_launchd_env's stub.
+ monkeypatch.setattr(
+ gateway_cli,
+ "wait_for_launchd_gateway_supervision",
+ _REAL_WAIT_FOR_SUPERVISION,
+ )
+ listings = []
+
+ def fake_launchctl(argv, **kwargs):
+ assert argv[:2] == ["launchctl", "list"]
+ listings.append(argv)
+ return subprocess.CompletedProcess(argv, 0, stdout='\t"PID" = 4242;\n', stderr="")
+
+ monkeypatch.setattr(gateway_cli.subprocess, "run", fake_launchctl)
+
+ restarted, failed_or_stale = _run_fleet_restart()
+
+ assert calls["restart"] == 1
+ assert restarted == []
+ assert failed_or_stale == [LABEL]
+ assert LABEL in capsys.readouterr().out
+ # One pre-restart snapshot, then the bounded poll for a different pid.
+ assert len(listings) > 1
+ assert sum(clock.slept) <= gateway_cli.LAUNCHD_SUPERVISION_VERIFY_TIMEOUT
+
def test_verification_budget_clears_the_respawn_throttle(self):
"""A budget under launchd's ~10s respawn throttle would false-alarm.