The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): macOS parent-death watchdog treats ps: marker drift as inconclusive (#103172)
Austin Pickett79445a496c86
diff --git a/contributors/emails/[email protected] b/contributors/emails/[email protected]new file mode 100644index 00000000000..16b5549857e--- /dev/null+++ b/contributors/emails/[email protected]@@ -0,0 +1 @@+drewTuzsondiff --git a/hermes_cli/web_server_lifecycle.py b/hermes_cli/web_server_lifecycle.pyindex e3a2b1a6e47..aa78e7c52ac 100644--- a/hermes_cli/web_server_lifecycle.py+++ b/hermes_cli/web_server_lifecycle.py@@ -86,7 +86,30 @@ def _valid_parent_start_marker(marker: str) -> bool:return Falseif prefix in ("linux", "win", "winms"):return value.isdigit()- return prefix == "ps"+ if prefix != "ps":+ return False+ # ``ps -o lstart=`` renders as ``Sat Aug 29 15:04:31 2026``. A marker split+ # on whitespace somewhere in the env plumbing arrives as ``ps:Sat`` -- a+ # real-looking identity that can never match, so the watchdog would exit a+ # live backend. Require a full value (#98132).+ tokens = value.split()+ has_year = any(token.isdigit() and len(token) == 4 for token in tokens)+ has_time = any(":" in token for token in tokens)+ return len(tokens) >= 4 and has_year and has_time+++def _parent_start_marker_mismatch_is_conclusive(actual: str, expected: str) -> bool:+ """Whether a marker mismatch proves the Desktop parent was replaced.++ ``linux:`` jiffies and ``win:``/``winms:`` FILETIME markers are machine+ values; a mismatch there is PID-reuse evidence. The POSIX fallback (macOS+ has no ``/proc``) is ``ps -o lstart=`` -- a wall-clock string rendered in+ the current TZ/locale. Electron caches it once per app lifetime while the+ backend re-renders it per spawn, so a timezone change (or DST, or column+ padding) makes the SAME instant differ byte-for-byte. Any ``ps:`` mismatch+ is therefore inconclusive (#95693, #93958).+ """+ return not (actual.startswith("ps:") or expected.startswith("ps:"))def _parent_start_markers_match(actual: str, expected: str) -> bool:@@ -253,7 +276,12 @@ def _is_serve_orphaned(try:if expected_start_marker is not None:probe = process_start_marker or _process_start_marker- return not _parent_start_markers_match(probe(int(desktop_pid)), expected_start_marker)+ actual_marker = probe(int(desktop_pid))+ if _parent_start_markers_match(actual_marker, expected_start_marker):+ return False+ if _parent_start_marker_mismatch_is_conclusive(actual_marker, expected_start_marker):+ return True+ # Inconclusive marker: degrade to PID liveness instead of exiting.if pid_exists is None:from gateway.status import _pid_exists@@ -274,8 +302,9 @@ def _start_parent_death_watchdog() -> None:marker without nonce or vice versa disables the watchdog)."""raw_pid = os.environ.get("HERMES_PARENT_PID")- start_marker = os.environ.get("HERMES_PARENT_START_MARKER")- nonce = os.environ.get("HERMES_PARENT_NONCE")+ # Empty inherited values mean "absent", not "marker present but blank".+ start_marker = os.environ.get("HERMES_PARENT_START_MARKER") or None+ nonce = os.environ.get("HERMES_PARENT_NONCE") or Nonetry:desktop_pid = int(raw_pid or "")@@ -288,6 +317,14 @@ def _start_parent_death_watchdog() -> None:if has_marker != (nonce is not None):returnif has_marker and (not _valid_parent_start_marker(start_marker or "") or not nonce or nonce != nonce.strip()):+ # Disarming is fail-safe (the backend keeps serving) but must not be+ # traceless: this backend will never reap itself if the Desktop dies.+ _log.warning(+ "Parent-death watchdog disabled: unusable HERMES_PARENT_START_MARKER=%r / nonce; "+ "falling back to no parent tracking for desktop PID %s.",+ start_marker,+ desktop_pid,+ )returntry:@@ -298,6 +335,14 @@ def _start_parent_death_watchdog() -> None:def _loop() -> None:while not _is_serve_orphaned(desktop_pid, start_marker):time.sleep(poll)+ try:+ _log.warning(+ "Parent-death watchdog: desktop PID %s appears orphaned (expected_start_marker=%r); exiting.",+ desktop_pid,+ start_marker,+ )+ except Exception:+ passos._exit(0)threading.Thread(target=_loop, daemon=True, name="serve-parent-watchdog").start()diff --git a/tests/hermes_cli/test_serve_parent_watchdog.py b/tests/hermes_cli/test_serve_parent_watchdog.pyindex 08a0c07b232..0b146a2a807 100644--- a/tests/hermes_cli/test_serve_parent_watchdog.py+++ b/tests/hermes_cli/test_serve_parent_watchdog.py@@ -1,6 +1,10 @@"""Regression tests for Desktop-owned ``hermes serve`` lifecycle tracking."""-from hermes_cli.web_server_lifecycle import _is_serve_orphaned, _valid_parent_start_marker+from hermes_cli.web_server_lifecycle import (+ _is_serve_orphaned,+ _parent_start_marker_mismatch_is_conclusive,+ _valid_parent_start_marker,+)def test_parent_watchdog_tracks_recorded_desktop_pid_not_immediate_ppid():@@ -57,3 +61,117 @@ def test_parent_watchdog_preserves_legacy_exact_windows_marker():)is False)+++def test_parent_watchdog_does_not_kill_a_live_parent_on_macos_timezone_drift():+ """#95693: the SAME instant rendered by `ps -o lstart=` under EDT (cached by+ Electron before a TZ change) vs CEST (probed by a fresh backend after) must+ degrade to the PID-only check, not count as proof the parent died."""+ expected = "ps:Thu Aug 20 22:33:11 2026"+ actual = "ps:Fri Aug 21 04:33:11 2026"++ assert (+ _is_serve_orphaned(+ 4242, expected, pid_exists=lambda _pid: True, process_start_marker=lambda _pid: actual+ )+ is False+ )+++def test_parent_watchdog_still_detects_a_genuinely_dead_parent_despite_ps_marker_mismatch():+ expected = "ps:Thu Aug 20 22:33:11 2026"+ actual = "ps:Fri Aug 21 04:33:11 2026"++ assert (+ _is_serve_orphaned(+ 4242, expected, pid_exists=lambda _pid: False, process_start_marker=lambda _pid: actual+ )+ is True+ )+++def test_parent_watchdog_exact_ps_marker_match_still_short_circuits():+ marker = "ps:Thu Aug 20 22:33:11 2026"++ assert (+ _is_serve_orphaned(+ 4242, marker, pid_exists=lambda _pid: False, process_start_marker=lambda _pid: marker+ )+ is False+ )+++def test_parent_watchdog_still_rejects_recycled_pid_via_stable_linux_marker():+ """linux:/win: markers are machine values -- a mismatch stays conclusive."""+ assert (+ _is_serve_orphaned(+ 4242,+ "linux:12345",+ pid_exists=lambda _pid: True,+ process_start_marker=lambda _pid: "linux:99999",+ )+ is True+ )+ assert _parent_start_marker_mismatch_is_conclusive("linux:123", "linux:456") is True+ assert _parent_start_marker_mismatch_is_conclusive("win:1", "winms:2") is True+++def test_macos_ps_marker_requires_full_lstart_not_a_truncated_weekday():+ """#98132: a whitespace-split ``ps:Sat`` must not arm the watchdog."""+ assert _valid_parent_start_marker("ps:Sat Aug 29 15:04:31 2026") is True+ assert _valid_parent_start_marker("ps:Sat") is False+ assert _valid_parent_start_marker("ps:Sat Aug 29") is False+++def test_parent_watchdog_treats_empty_marker_env_as_absent(monkeypatch):+ """Blank inherited HERMES_PARENT_START_MARKER/NONCE degrade to PID-only tracking."""+ from hermes_cli import web_server_lifecycle++ monkeypatch.setenv("HERMES_PARENT_PID", "4242")+ monkeypatch.setenv("HERMES_PARENT_START_MARKER", "")+ monkeypatch.setenv("HERMES_PARENT_NONCE", "")+ seen = {}++ def fake_orphaned(pid, marker):+ seen["args"] = (pid, marker)+ raise SystemExit # stop the loop thread before it sleeps/exits++ monkeypatch.setattr(web_server_lifecycle, "_is_serve_orphaned", fake_orphaned)++ class _Thread:+ def __init__(self, target, **_kw):+ self.target = target++ def start(self):+ try:+ self.target()+ except SystemExit:+ pass++ monkeypatch.setattr(web_server_lifecycle.threading, "Thread", _Thread)+ web_server_lifecycle._start_parent_death_watchdog()+ assert seen["args"] == (4242, None)+++def test_parent_watchdog_warns_when_disarmed_by_unusable_marker(monkeypatch, caplog):+ """Disarming is fail-safe but must leave a trace in the log."""+ import logging++ from hermes_cli import web_server_lifecycle++ monkeypatch.setenv("HERMES_PARENT_PID", "4242")+ monkeypatch.setenv("HERMES_PARENT_START_MARKER", "ps:Sat")+ monkeypatch.setenv("HERMES_PARENT_NONCE", "n")+ started = []+ monkeypatch.setattr(+ web_server_lifecycle.threading, "Thread", lambda *a, **k: started.append(1) or _NoThread()+ )+ with caplog.at_level(logging.WARNING, logger="hermes_cli.web_server"):+ web_server_lifecycle._start_parent_death_watchdog()+ assert started == [], "an unusable marker must disarm, not arm, the watchdog"+ assert any("watchdog disabled" in r.getMessage() for r in caplog.records)+++class _NoThread:+ def start(self):+ raise AssertionError("watchdog thread must not start")diff --git a/tests/hermes_cli/test_serve_parent_watchdog_live_macos.py b/tests/hermes_cli/test_serve_parent_watchdog_live_macos.pynew file mode 100644index 00000000000..80ba358154f--- /dev/null+++ b/tests/hermes_cli/test_serve_parent_watchdog_live_macos.py@@ -0,0 +1,120 @@+"""#95693 / #93958 — live macOS proof for the parent-death watchdog.++The unit tests in ``test_serve_parent_watchdog.py`` pin ``_is_serve_orphaned``+as a pure function. The bug itself lived one layer up: a daemon thread that+calls ``os._exit(0)`` ~5ms after ``HERMES_BACKEND_READY``, which no in-process+test can observe. This file runs the REAL ``start_server`` in a subprocess, on+the host ``ps``, with the marker the Desktop would hand it rendered in a+different timezone than the backend's own probe.++Contract:++* live parent + TZ-drifted ``ps:`` marker → backend announces READY and is+ still alive well past several watchdog polls;+* that same backend still exits once the parent actually dies (the marker+ degrade did not turn the watchdog off).+"""++import os+import subprocess+import sys+import threading+import time+from pathlib import Path++import pytest++REPO_ROOT = Path(__file__).resolve().parents[2]++pytestmark = pytest.mark.macos_only+++def _lstart(pid: int, tz: str) -> str:+ env = dict(os.environ, TZ=tz)+ out = subprocess.run(+ ["ps", "-p", str(pid), "-o", "lstart="], capture_output=True, text=True, env=env, check=True+ ).stdout+ return " ".join(out.split())+++def _read_until(proc: subprocess.Popen, token: str, timeout: float = 120.0) -> bool:+ hit = threading.Event()++ def _pump():+ assert proc.stdout is not None+ for line in proc.stdout:+ if token in line:+ hit.set()+ return++ threading.Thread(target=_pump, daemon=True).start()+ return hit.wait(timeout)+++def _wait_exit(proc: subprocess.Popen, timeout: float) -> bool:+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if proc.poll() is not None:+ return True+ time.sleep(0.1)+ return False+++def test_live_backend_survives_timezone_drifted_parent_marker(tmp_path):+ # Stand-in for the Electron parent: a long-lived process we control.+ parent = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(600)"])+ serve = None+ try:+ backend_tz = "America/New_York"+ cached_tz = "Europe/Paris"+ drifted_marker = f"ps:{_lstart(parent.pid, cached_tz)}"+ assert drifted_marker != f"ps:{_lstart(parent.pid, backend_tz)}", (+ "precondition: the two TZ renderings of the same instant must differ"+ )++ home = tmp_path / "hermes_home"+ home.mkdir()+ env = dict(os.environ)+ env.update(+ TZ=backend_tz,+ HERMES_HOME=str(home),+ HERMES_SERVE_HEADLESS="1",+ PYTHONUNBUFFERED="1",+ HERMES_PARENT_PID=str(parent.pid),+ HERMES_PARENT_START_MARKER=drifted_marker,+ HERMES_PARENT_NONCE="nonce-95693",+ HERMES_SERVE_WATCHDOG_POLL_S="0.5",+ )+ env.pop("HERMES_DESKTOP", None)+ code = (+ "from hermes_cli.web_server import start_server\n"+ "start_server(host='127.0.0.1', port=0, open_browser=False, headless=True)\n"+ )+ serve = subprocess.Popen(+ [sys.executable, "-c", code],+ cwd=str(REPO_ROOT),+ env=env,+ stdout=subprocess.PIPE,+ stderr=subprocess.DEVNULL,+ text=True,+ )++ assert _read_until(serve, "HERMES_BACKEND_READY"), "backend never announced READY"++ # Before the fix the watchdog fired on its very first poll. Several+ # polls later the backend must still be here.+ assert not _wait_exit(serve, timeout=4.0), (+ f"backend exited (code {serve.returncode}) with a live parent; "+ f"TZ-drifted marker {drifted_marker!r} was treated as proof of death"+ )++ # The degrade to PID liveness must still reap a genuinely dead parent.+ parent.kill()+ parent.wait(timeout=10)+ assert _wait_exit(serve, timeout=15.0), "backend outlived its dead parent"+ assert serve.returncode == 0+ finally:+ for proc in (serve, parent):+ if proc is not None and proc.poll() is None:+ proc.kill()+ proc.wait(timeout=10)