The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(launchd): park EX_CONFIG token conflicts instead of KeepAlive-looping (#112079)
xxxigm2eb5395d3fe4
diff --git a/gateway/restart.py b/gateway/restart.pyindex db149b96650..2598feb28c0 100644--- a/gateway/restart.py+++ b/gateway/restart.py@@ -13,6 +13,21 @@ GATEWAY_SERVICE_RESTART_EXIT_CODE = 75# See #51228.GATEWAY_FATAL_CONFIG_EXIT_CODE = 78++def map_fatal_config_exit_for_launchd(returncode: int) -> int:+ """Translate gateway EX_CONFIG so launchd can park the job.++ systemd uses ``RestartPreventExitStatus=78``; s6 maps 78→125. launchd cannot+ gate on a specific status, and unconditional ``KeepAlive=true`` respawns 78+ forever (#89477). The generated plist uses ``KeepAlive.SuccessfulExit=false``;+ mapping 78→0 is a deliberate stop. Exit 75 (please restart) and other+ failures pass through so KeepAlive still relaunches them. Negative ``wait()``+ codes (signals) are left to the caller.+ """+ if returncode == GATEWAY_FATAL_CONFIG_EXIT_CODE:+ return 0+ return returncode+# Set by ``hermes gateway run --external-supervisor``. Unlike systemd's INVOCATION_ID# and launchd's XPC_SERVICE_NAME, this survives wrappers that replace the child# environment (e.g. ``sudo env -i``).diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.pyindex 75de5dc1aea..da048c18425 100644--- a/hermes_cli/gateway.py+++ b/hermes_cli/gateway.py@@ -3915,9 +3915,16 @@ def generate_launchd_plist() -> str:<true/><key>KeepAlive</key>- <true/>+ <dict>+ <key>SuccessfulExit</key>+ <false/>+ </dict>- <!-- ThrottleInterval raises launchd's default 10s minimum respawn interval+ <!-- SuccessfulExit=false parks a clean stop (exit 0), including gateway+ EX_CONFIG 78 after stderr_timestamp maps it to 0 — launchd cannot+ honor RestartPreventExitStatus, and KeepAlive=true respawned token+ collisions forever (#89477). Exit 75 and crashes still relaunch.+ ThrottleInterval raises launchd's default 10s minimum respawn intervalto 30s so a crash-looping gateway can't hammer launchd into a rapidrespawn storm; ExitTimeOut gives the gateway 25s of graceful-drainheadroom before launchd escalates from SIGTERM to SIGKILL on stop. -->diff --git a/hermes_cli/stderr_timestamp.py b/hermes_cli/stderr_timestamp.pyindex 5ed7fe4b607..bc9d1c9fd06 100644--- a/hermes_cli/stderr_timestamp.py+++ b/hermes_cli/stderr_timestamp.py@@ -88,6 +88,22 @@ def _prepare_child_command(command: Sequence[str], environ: Mapping[str, str] |return argv+def _child_returncode_for_supervisor(command: Sequence[str], returncode: int) -> int:+ """Exit status the launchd wrapper reports for *returncode* from *command*.++ Signal deaths stay 128+N. Gateway EX_CONFIG (78) becomes 0 so+ ``KeepAlive.SuccessfulExit=false`` parks the job instead of crash-looping;+ a non-gateway child that happens to exit 78 is left alone.+ """+ if returncode < 0:+ return 128 + abs(returncode)+ from gateway.restart import GATEWAY_FATAL_CONFIG_EXIT_CODE, map_fatal_config_exit_for_launchd++ if returncode == GATEWAY_FATAL_CONFIG_EXIT_CODE and _is_hermes_gateway_run_argv(command):+ return map_fatal_config_exit_for_launchd(returncode)+ return returncode++def _parse_args(argv: Sequence[str] | None) -> argparse.Namespace:parser = argparse.ArgumentParser(description="Run a command and timestamp each stderr line into a log file.")parser.add_argument("--error-log", required=True, type=Path)@@ -120,7 +136,7 @@ def main(argv: Sequence[str] | None = None) -> int:for signum, handler in previous_handlers.items():signal.signal(signum, handler)returncode = proc.wait()- return 128 + abs(returncode) if returncode < 0 else returncode+ return _child_returncode_for_supervisor(args.command, returncode)if __name__ == "__main__":diff --git a/tests/hermes_cli/test_gateway_service.py b/tests/hermes_cli/test_gateway_service.pyindex 772ac6a920c..b9fce170de9 100644--- a/tests/hermes_cli/test_gateway_service.py+++ b/tests/hermes_cli/test_gateway_service.py@@ -2410,6 +2410,22 @@ class TestServiceTakeoverGovernance:assert "<key>KeepAlive</key>" in plistassert "<true/>" in plist+ def test_launchd_plist_parks_ex_config_instead_of_keepalive_loop(self, tmp_path, monkeypatch):+ """Token-collision EX_CONFIG (78) must not KeepAlive-respawn on macOS.++ systemd parks via RestartPreventExitStatus=78; launchd cannot gate on a+ specific status. Unconditional KeepAlive=true turned that exit into a+ 30s crash loop (#89477). SuccessfulExit=false plus the stderr wrapper+ mapping 78→0 is the launchd twin: a clean stop stays down, exit 75 and+ crashes still relaunch.+ """+ home = tmp_path / ".hermes"+ home.mkdir()+ monkeypatch.setattr(gateway_cli, "get_hermes_home", lambda: home)+ parsed = plistlib.loads(gateway_cli.generate_launchd_plist().encode("utf-8"))+ assert parsed["KeepAlive"] == {"SuccessfulExit": False}+ assert parsed["RunAtLoad"] is True+def test_systemd_unit_does_not_arm_takeover(self, tmp_path, monkeypatch):home = tmp_path / ".hermes"home.mkdir()diff --git a/tests/hermes_cli/test_stderr_timestamp.py b/tests/hermes_cli/test_stderr_timestamp.pyindex f1e76a48e3b..d67cb6cac26 100644--- a/tests/hermes_cli/test_stderr_timestamp.py+++ b/tests/hermes_cli/test_stderr_timestamp.py@@ -5,7 +5,11 @@ import sysimport pytest-from gateway.restart import EXTERNAL_GATEWAY_SUPERVISOR_ENV+from gateway.restart import (+ EXTERNAL_GATEWAY_SUPERVISOR_ENV,+ GATEWAY_FATAL_CONFIG_EXIT_CODE,+ GATEWAY_SERVICE_RESTART_EXIT_CODE,+)from hermes_cli import stderr_timestamp_STALE_GATEWAY_ARGV = [@@ -162,3 +166,50 @@ def test_main_does_not_mark_unsupervised_child(tmp_path, monkeypatch):assert rc == 0assert marker_path.read_text(encoding="utf-8") == "unset"++[email protected]_gateway_lookalike+def test_main_maps_gateway_ex_config_to_clean_stop(tmp_path):+ """launchd KeepAlive.SuccessfulExit=false parks exit 0; the wrapper must+ turn gateway EX_CONFIG (78) into that clean stop without swallowing the+ please-restart code (75) or a non-gateway child's 78."""+ log_path = tmp_path / "gateway.error.log"+ gateway_tail = ["-m", "hermes_cli.main", "gateway", "run"]++ rc_config = stderr_timestamp.main(+ [+ "--error-log",+ str(log_path),+ "--",+ sys.executable,+ "-c",+ f"raise SystemExit({GATEWAY_FATAL_CONFIG_EXIT_CODE})",+ *gateway_tail,+ ]+ )+ rc_restart = stderr_timestamp.main(+ [+ "--error-log",+ str(log_path),+ "--",+ sys.executable,+ "-c",+ f"raise SystemExit({GATEWAY_SERVICE_RESTART_EXIT_CODE})",+ *gateway_tail,+ ]+ )+ rc_other = stderr_timestamp.main(+ [+ "--error-log",+ str(log_path),+ "--",+ sys.executable,+ "-c",+ f"raise SystemExit({GATEWAY_FATAL_CONFIG_EXIT_CODE})",+ ]+ )++ assert rc_config == 0+ assert rc_restart == GATEWAY_SERVICE_RESTART_EXIT_CODE+ assert rc_other == GATEWAY_FATAL_CONFIG_EXIT_CODE+diff --git a/website/docs/developer-guide/gateway-internals.md b/website/docs/developer-guide/gateway-internals.mdindex 066d86a4dc5..11d98af4e6f 100644--- a/website/docs/developer-guide/gateway-internals.md+++ b/website/docs/developer-guide/gateway-internals.md@@ -199,7 +199,7 @@ stop, or later turn-preparation gates.Adapters that connect with unique credentials call `acquire_scoped_lock()` in `connect()` and `release_scoped_lock()` in `disconnect()`. This prevents two profiles from using the same bot token simultaneously.-A lock conflict is emitted as `{scope}_lock` with `retryable=True` so a **mid-run** reconnect can recover once the other holder exits. At **startup**, though, a live foreign holder is a configuration conflict: `gateway/restart.py::is_global_startup_conflict()` recognizes the `*_lock` / `lock_conflict` code families and the startup router parks the platform `fatal` instead of retry-queueing it. With nothing else connected the gateway exits `78` (`EX_CONFIG`, `gateway_state=startup_failed`) so the supervisor stops restarting it; alongside a genuinely transient peer failure the gateway stays alive and only the peer retries.+A lock conflict is emitted as `{scope}_lock` with `retryable=True` so a **mid-run** reconnect can recover once the other holder exits. At **startup**, though, a live foreign holder is a configuration conflict: `gateway/restart.py::is_global_startup_conflict()` recognizes the `*_lock` / `lock_conflict` code families and the startup router parks the platform `fatal` instead of retry-queueing it. With nothing else connected the gateway exits `78` (`EX_CONFIG`, `gateway_state=startup_failed`) so the supervisor stops restarting it: systemd via `RestartPreventExitStatus=78`, s6 via finish→125, launchd via `KeepAlive.SuccessfulExit=false` after the stderr wrapper maps 78→0. Alongside a genuinely transient peer failure the gateway stays alive and only the peer retries.## Delivery Path