fix(gateway): cap signal-driven stop drain to launchd's live ExitTimeOut

launchd's per-user (gui) domain clamps ExitTimeOut at 60s regardless of the
plist value (measured on macOS 26.6.1: 215->60, 90->60, 60->60, 30->30). A
gateway configured with restart_drain_timeout above that drains past the
budget and is SIGKILLed mid-teardown (adapters still connected, SQLite
checkpoint/close never runs). That unclean exit is one half of the
recurring state.db "structural corruption" class.

- gateway/restart.py: parse_launchd_exit_timeout / read_launchd_exit_timeout_s
  (launchctl print gui/<uid>/<label>, bounded, fail-open None when not
  launchd-owned or launchctl fails), resolve_launchd_capped_drain
  (min(drain, exit_timeout - 10s cleanup reserve); never extends a drain),
  effective_stop_drain_timeout (duck-typed for shutdown-path test doubles).
- gateway/run.py: read the live budget once at boot and WARN when the
  configured drain exceeds it; the SIGTERM/SIGINT handler marks the stop as
  signal-driven.
- gateway/run_shutdown.py: _stop_impl caps the drain, the watchdog leash and
  the cron drain ceiling to the launchd budget for those stops only. In-band
  SIGUSR1 restarts and --replace takeovers are not launchd-timed and keep the
  configured drain. systemd/s6/foreground: unchanged (no budget -> no cap).
- hermes_cli/gateway.py: plist template ExitTimeOut 25 -> 60 so LaunchAgents
  ask for the full clamp instead of a quarter of it.
This commit is contained in:
Kyzcreig authored and kshitij committed 2026-09-20 18:49:23 +05:30
1 parent 639823919c
commit aa0289f307
6 files changed
+537 -11

No files matched your search

+125 -1
View File
@@ -2,7 +2,9 @@
import math
import os
from collections.abc import Mapping
import re
import subprocess
from collections.abc import Callable, Mapping
from hermes_cli.config import DEFAULT_CONFIG
@@ -55,6 +57,128 @@ CRON_DRAIN_CLEANUP_RESERVE_S = 10.0
SYSTEMD_STOP_HEADROOM_S = 30.0
SYSTEMD_TIMEOUT_STOP_SEC_FLOOR = 60.0
# launchd is the one supervisor whose stop budget the gateway cannot size:
# ``ExitTimeOut`` lives in the plist, and the per-user (gui) domain CLAMPS
# it — measured on macOS 26.6.1: plist 215 -> live 60, 90 -> 60, 60 -> 60,
# 30 -> 30. The gateway can only *read* the live value (``launchctl print
# gui/<uid>/<label>`` -> ``exit timeout = N``) and fit its SIGTERM-driven
# stop inside it. Draining past it is not "a longer drain" — launchd
# SIGKILLs at N seconds, mid-SQLite-write on a busy restart, which is the
# unclean-exit half of the state.db corruption class.
LAUNCHD_GUI_EXIT_TIMEOUT_CLAMP_S = 60
LAUNCHD_STOP_CLEANUP_RESERVE_S = 10.0
_LAUNCHD_EXIT_TIMEOUT_RE = re.compile(r"^\s*exit timeout\s*=\s*(\d+)\s*$", re.MULTILINE)
def parse_launchd_exit_timeout(print_output: object) -> float | None:
"""Extract ``exit timeout = N`` from ``launchctl print`` output."""
match = _LAUNCHD_EXIT_TIMEOUT_RE.search(str(print_output or ""))
if match is None:
return None
return float(match.group(1))
def launchd_service_label(environ: Mapping[str, str] | None = None) -> str | None:
"""Return this process's launchd job label, or ``None`` when not launchd-owned."""
env = os.environ if environ is None else environ
label = str(env.get("XPC_SERVICE_NAME", "") or "").strip()
if not label or label == "0":
return None
return label
def read_launchd_exit_timeout_s(
label: str | None = None,
*,
environ: Mapping[str, str] | None = None,
uid: int | None = None,
run: Callable[..., "subprocess.CompletedProcess[str]"] = subprocess.run,
) -> float | None:
"""Live ``ExitTimeOut`` (seconds) launchd enforces for this gateway's job.
Returns ``None`` — meaning "no launchd budget applies" — when the process
is not launchd-owned (no ``XPC_SERVICE_NAME``), ``launchctl`` is missing
or fails, or the print output carries no ``exit timeout`` line. Callers
must treat ``None`` as fail-open: the configured drain stands unchanged.
"""
label = label or launchd_service_label(environ)
if not label:
return None
try:
resolved_uid = os.getuid() if uid is None else int(uid)
except (AttributeError, TypeError, ValueError):
return None
domain = "system" if resolved_uid == 0 else f"gui/{resolved_uid}"
try:
proc = run(
["launchctl", "print", f"{domain}/{label}"],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=5,
)
except (OSError, subprocess.SubprocessError, ValueError):
return None
if getattr(proc, "returncode", 1) != 0:
return None
return parse_launchd_exit_timeout(getattr(proc, "stdout", ""))
def resolve_launchd_capped_drain(
drain_timeout: float,
launchd_exit_timeout_s: float | None,
*,
cleanup_reserve_s: float = LAUNCHD_STOP_CLEANUP_RESERVE_S,
) -> float:
"""Clamp a SIGTERM-driven stop drain to what launchd will actually allow.
``launchd_exit_timeout_s`` is the live ``exit timeout`` for this job (see
:func:`read_launchd_exit_timeout_s`); ``None`` means no launchd budget
applies and the configured drain is returned untouched. Otherwise the
drain may use at most ``exit_timeout - cleanup_reserve_s`` so the
post-drain teardown (interrupt agents, disconnect adapters, checkpoint
and close SQLite) still completes before launchd escalates to SIGKILL.
Never *extends* the drain — an operator who configured a short one
keeps it.
"""
def _secs(value: object) -> float:
try:
return max(float(value), 0.0) # type: ignore[arg-type]
except (TypeError, ValueError):
return 0.0
drain = _secs(drain_timeout)
if launchd_exit_timeout_s is None:
return drain
try:
budget = float(launchd_exit_timeout_s)
except (TypeError, ValueError):
return drain
if budget <= 0.0:
return drain
cap = max(budget - _secs(cleanup_reserve_s), 0.0)
return min(drain, cap)
def effective_stop_drain_timeout(runner: object) -> float:
"""Drain budget for the stop in progress on ``runner``.
Signal-driven stops under launchd are timed by launchd's live
``ExitTimeOut`` (``runner._launchd_exit_timeout_s``, set at boot);
everything else — in-band SIGUSR1 restart after the turn, ``--replace``
takeover, tests — keeps the configured drain. Duck-typed and
getattr-guarded on purpose: shutdown-path tests drive ``_stop_impl``
from bare doubles that are not ``GatewayRunner`` instances.
"""
drain = getattr(runner, "_restart_drain_timeout", DEFAULT_GATEWAY_RESTART_DRAIN_TIMEOUT)
if not getattr(runner, "_stop_requested_by_signal", False):
return drain
return resolve_launchd_capped_drain(drain, getattr(runner, "_launchd_exit_timeout_s", None))
_TRUTHY = {"1", "true", "yes", "on"}
+61 -1
View File
@@ -2173,7 +2173,10 @@ from gateway.restart import (
DEFAULT_GATEWAY_CRON_DRAIN_TIMEOUT,
DEFAULT_GATEWAY_RESTART_AFTER_TURN_TIMEOUT,
DEFAULT_GATEWAY_RESTART_DRAIN_TIMEOUT,
DEFAULT_GATEWAY_SIGNAL_INTERRUPT_GRACE_TIMEOUT)
DEFAULT_GATEWAY_SIGNAL_INTERRUPT_GRACE_TIMEOUT,
effective_stop_drain_timeout,
read_launchd_exit_timeout_s,
resolve_launchd_capped_drain)
logger = logging.getLogger(__name__)
@@ -3487,12 +3490,60 @@ class GatewayRunner(
self._busy_input_modes_by_profile: Dict[str, str] = {}
self._busy_text_modes_by_profile: Dict[str, str] = {}
self._restart_drain_timeout = self._load_restart_drain_timeout()
# Live launchd ``ExitTimeOut`` for this job (None when not launchd-owned). Read once at
# boot — launchd fixes it at load — and applied only to signal-driven stops, which are the
# only stops launchd times. See _load_launchd_exit_timeout().
self._stop_requested_by_signal = False
self._launchd_exit_timeout_s = self._load_launchd_exit_timeout(self._restart_drain_timeout)
self._restart_after_turn_timeout = self._load_restart_after_turn_timeout()
self._cron_drain_timeout = self._load_cron_drain_timeout()
self._signal_interrupt_grace_timeout = self._load_signal_interrupt_grace_timeout()
self._provider_routing = self._load_provider_routing()
self._fallback_model = self._load_fallback_model()
@staticmethod
def _load_launchd_exit_timeout(drain_timeout: float) -> Optional[float]:
"""Read the live launchd ``ExitTimeOut`` this job runs under, if any.
launchd is the one supervisor the gateway cannot size from config: the per-user (gui)
domain clamps ``ExitTimeOut`` (measured 60s on macOS 26), and any signal-driven stop that
drains past it is SIGKILLed mid-teardown — the unclean-exit half of the state.db
corruption class. Returns ``None`` (fail-open, drain unchanged) when not launchd-owned or
when ``launchctl print`` is unavailable. Logs a WARNING when the configured drain exceeds
the live budget so the misconfiguration is visible at boot, not at the next SIGKILL.
"""
try:
exit_timeout = read_launchd_exit_timeout_s()
except Exception as e: # pragma: no cover - defensive, launchctl quirks
logger.debug("launchd exit timeout probe failed: %s", e)
return None
if exit_timeout is None:
return None
effective = resolve_launchd_capped_drain(drain_timeout, exit_timeout)
if effective < drain_timeout:
logger.warning(
"restart_drain_timeout=%.0fs exceeds the live launchd exit timeout (%.0fs) for %s; "
"signal-driven stops will drain at most %.0fs so teardown finishes before launchd "
"SIGKILLs (launchd clamps ExitTimeOut in the per-user domain).",
drain_timeout, exit_timeout, os.environ.get("XPC_SERVICE_NAME", "this job"), effective,
)
else:
logger.info(
"launchd exit timeout for %s is %.0fs (drain %.0fs fits)",
os.environ.get("XPC_SERVICE_NAME", "this job"), exit_timeout, drain_timeout,
)
return exit_timeout
def _effective_stop_drain_timeout(self) -> float:
"""Drain budget for the stop in progress.
Signal-driven stops under launchd are timed by launchd's live ``ExitTimeOut``; everything
else (in-band SIGUSR1 restart after the turn, ``--replace`` takeover, tests) keeps the
configured drain. getattr-guarded: shutdown-path tests drive the stop from bare doubles
that skip ``__init__``.
"""
return effective_stop_drain_timeout(self)
def _init_session_store(self) -> None:
"""Build the SessionStore (with process-registry reset guard), its async facade and the router."""
from tools.process_registry import process_registry
@@ -5100,6 +5151,15 @@ def _start_gateway_make_shutdown_signal_handler(runner, _signal_initiated_shutdo
_best_effort(_log_context, "format_context_for_log failed: %s")
_best_effort(_diagnostic, "spawn_async_diagnostic failed: %s")
if not planned_takeover:
# Supervisor/operator SIGNAL stop (bootout, kickstart -k, systemd, s6, bare kill) — the
# only kind launchd times with ExitTimeOut. In-band SIGUSR1 restarts never pass through
# here, and a sibling-driven --replace takeover is not launchd-timed either, so both
# keep the configured drain. _stop_impl uses this to cap the drain to the live budget.
try:
runner._stop_requested_by_signal = True
except Exception:
pass
asyncio.create_task(runner.stop())
return shutdown_signal_handler
+22 -6
View File
@@ -22,7 +22,8 @@ from typing import Any, Callable, Dict, Optional
from gateway.config import Platform
from gateway.restart import (
DEFAULT_GATEWAY_CRON_DRAIN_TIMEOUT, GATEWAY_SERVICE_RESTART_EXIT_CODE, resolve_cron_drain_budget
DEFAULT_GATEWAY_CRON_DRAIN_TIMEOUT, GATEWAY_SERVICE_RESTART_EXIT_CODE,
effective_stop_drain_timeout, resolve_cron_drain_budget
)
from gateway.run_common import _UNSET
from gateway.shutdown_watchdog import arm_shutdown_watchdog, resolve_shutdown_watchdog_delay
@@ -1739,9 +1740,15 @@ class GatewayShutdownMixin:
_deferred_at_start = ctx.deferred_count()
# Cron floor clamped to the watchdog leash; getattr-guard for bare shutdown-path doubles.
_cron_drain_cfg = getattr(self, "_cron_drain_timeout", DEFAULT_GATEWAY_CRON_DRAIN_TIMEOUT)
# Under launchd the real leash is launchd's own exit timeout, not our watchdog
# (drain + grace): a signal-driven stop that lets cron work push past it is SIGKILLed
# before cleanup runs.
_cron_leash = resolve_shutdown_watchdog_delay(timeout)
_launchd_budget = getattr(self, "_launchd_exit_timeout_s", None)
if getattr(self, "_stop_requested_by_signal", False) and _launchd_budget:
_cron_leash = min(_cron_leash, float(_launchd_budget))
_cron_timeout = resolve_cron_drain_budget(
timeout, _cron_drain_cfg, watchdog_delay=resolve_shutdown_watchdog_delay(timeout),
elapsed=ctx.elapsed(),
timeout, _cron_drain_cfg, watchdog_delay=_cron_leash, elapsed=ctx.elapsed(),
)
if _cron_at_start and _cron_timeout > timeout:
logger.info(
@@ -2033,7 +2040,9 @@ class GatewayShutdownMixin:
"active_api_runs": self._active_api_run_count(),
"active_deferred_agent_workers": ctx.deferred_count(),
"restart_drain_timeout": self._restart_drain_timeout,
"watchdog_delay_s": resolve_shutdown_watchdog_delay(self._restart_drain_timeout),
"effective_drain_timeout": effective_stop_drain_timeout(self),
"launchd_exit_timeout_s": getattr(self, "_launchd_exit_timeout_s", None),
"watchdog_delay_s": resolve_shutdown_watchdog_delay(effective_stop_drain_timeout(self)),
"phase_elapsed_s": ctx.elapsed() if ctx.started_at is not None else None,
}
@@ -2053,12 +2062,19 @@ class GatewayShutdownMixin:
)
if not os.environ.get("PYTEST_CURRENT_TEST"):
arm_shutdown_watchdog(
resolve_shutdown_watchdog_delay(self._restart_drain_timeout), done_event=_watchdog_done,
resolve_shutdown_watchdog_delay(effective_stop_drain_timeout(self)), done_event=_watchdog_done,
snapshot_fn=lambda: GatewayRunner._shutdown_watchdog_snapshot(self, ctx), exit_code=1,
)
try:
await GatewayRunner._stop_begin_teardown(self, ctx)
timeout = self._restart_drain_timeout
timeout = effective_stop_drain_timeout(self)
if timeout < self._restart_drain_timeout:
logger.warning(
"Shutdown drain capped to %.0fs (configured %.0fs) to fit the live launchd exit "
"timeout of %.0fs — launchd SIGKILLs past it",
timeout, self._restart_drain_timeout,
getattr(self, "_launchd_exit_timeout_s", None) or 0.0,
)
await GatewayRunner._stop_drain_active_work(self, timeout, ctx)
if ctx.timed_out:
await GatewayRunner._stop_interrupt_remaining_work(self, ctx)
+7 -3
View File
@@ -4112,13 +4112,17 @@ def generate_launchd_plist() -> str:
collisions forever (#89477). Exit 75 and crashes still relaunch.
ThrottleInterval raises launchd's default 10s minimum respawn interval
to 30s so a crash-looping gateway can't hammer launchd into a rapid
respawn storm; ExitTimeOut gives the gateway 25s of graceful-drain
headroom before launchd escalates from SIGTERM to SIGKILL on stop. -->
respawn storm; ExitTimeOut is the graceful-drain headroom before
launchd escalates from SIGTERM to SIGKILL on stop. The per-user
(gui) launchd domain clamps it to 60s regardless of what is written
here, so 60 is the most a LaunchAgent can get; the gateway reads
the live value at boot and fits its signal-driven drain inside it
(gateway.restart.read_launchd_exit_timeout_s). -->
<key>ThrottleInterval</key>
<integer>30</integer>
<key>ExitTimeOut</key>
<integer>25</integer>
<integer>60</integer>
{nofile_block}
<key>StandardOutPath</key>
<string>{log_dir}/gateway.log</string>
@@ -0,0 +1,305 @@
"""Signal-driven stops under launchd must fit the live ``ExitTimeOut``.
launchd's per-user (gui) domain clamps ``ExitTimeOut`` (measured 60s on
macOS 26: plist 215 -> live 60). A gateway configured with a longer
``restart_drain_timeout`` drains past that budget and is SIGKILLed mid
SQLite teardown — the unclean-exit half of the state.db corruption class.
The gateway therefore reads the live value at boot and caps only the
signal-driven stop drain (in-band SIGUSR1 restarts and --replace
takeovers are not launchd-timed and keep the configured drain).
"""
from __future__ import annotations
import subprocess
import pytest
from gateway.restart import (
LAUNCHD_STOP_CLEANUP_RESERVE_S,
launchd_service_label,
parse_launchd_exit_timeout,
read_launchd_exit_timeout_s,
resolve_launchd_capped_drain,
)
from gateway.shutdown_watchdog import (
DEFAULT_SHUTDOWN_WATCHDOG_GRACE_S,
resolve_shutdown_watchdog_delay,
)
_PRINT_OUTPUT = """\
ai.hermes.gateway-aegis = {
\tactive count = 1
\tpath = /Users/x/Library/LaunchAgents/ai.hermes.gateway-aegis.plist
\tstate = running
\tprogram = /bin/sh
\targuments = {
\t\t/bin/sh
\t\t-lc
\t\texec hermes gateway run
\t}
\tdefault environment = {
\t\tPATH => /usr/bin:/bin:/usr/sbin:/sbin
\t}
\tenvironment = {
\t\tXPC_SERVICE_NAME => ai.hermes.gateway-aegis
\t}
\tdomain = gui/501 [100010]
\tminimum runtime = 10
\texit timeout = 60
\truns = 3
\tpid = 83601
\tsuccessive crashes = 0
"""
# ---------------------------------------------------------------------------
# parse / read
# ---------------------------------------------------------------------------
def test_parse_exit_timeout_from_launchctl_print():
assert parse_launchd_exit_timeout(_PRINT_OUTPUT) == 60.0
@pytest.mark.parametrize("text", ["", None, "state = running\n", "exit timeout = abc\n"])
def test_parse_exit_timeout_absent_returns_none(text):
assert parse_launchd_exit_timeout(text) is None
def test_parse_exit_timeout_ignores_lookalike_keys():
# "minimum runtime" and other "= N" lines must not be mistaken for it.
assert parse_launchd_exit_timeout("\tminimum runtime = 10\n\tpid = 5\n") is None
def test_service_label_from_xpc_env():
assert launchd_service_label({"XPC_SERVICE_NAME": "ai.hermes.gateway"}) == "ai.hermes.gateway"
assert launchd_service_label({"XPC_SERVICE_NAME": "0"}) is None
assert launchd_service_label({"XPC_SERVICE_NAME": ""}) is None
assert launchd_service_label({}) is None
def test_read_exit_timeout_queries_gui_domain_for_label():
calls: list[list[str]] = []
def fake_run(argv, **kwargs):
calls.append(list(argv))
assert kwargs.get("timeout"), "launchctl probe must be bounded"
return subprocess.CompletedProcess(argv, 0, stdout=_PRINT_OUTPUT, stderr="")
value = read_launchd_exit_timeout_s(
environ={"XPC_SERVICE_NAME": "ai.hermes.gateway-aegis"}, uid=501, run=fake_run
)
assert value == 60.0
assert calls == [["launchctl", "print", "gui/501/ai.hermes.gateway-aegis"]]
def test_read_exit_timeout_uses_system_domain_for_root():
calls: list[list[str]] = []
def fake_run(argv, **kwargs):
calls.append(list(argv))
return subprocess.CompletedProcess(argv, 0, stdout=_PRINT_OUTPUT, stderr="")
read_launchd_exit_timeout_s(
environ={"XPC_SERVICE_NAME": "ai.hermes.gateway"}, uid=0, run=fake_run
)
assert calls == [["launchctl", "print", "system/ai.hermes.gateway"]]
def test_read_exit_timeout_not_launchd_owned_skips_probe():
def fake_run(*_a, **_k): # pragma: no cover - must not be reached
raise AssertionError("launchctl must not run when XPC_SERVICE_NAME is unset")
assert read_launchd_exit_timeout_s(environ={}, uid=501, run=fake_run) is None
assert (
read_launchd_exit_timeout_s(environ={"XPC_SERVICE_NAME": "0"}, uid=501, run=fake_run)
is None
)
@pytest.mark.parametrize(
"failure",
[
FileNotFoundError("launchctl"),
subprocess.TimeoutExpired(cmd="launchctl", timeout=5),
OSError("boom"),
],
)
def test_read_exit_timeout_fails_open_on_probe_errors(failure):
def fake_run(*_a, **_k):
raise failure
assert (
read_launchd_exit_timeout_s(
environ={"XPC_SERVICE_NAME": "ai.hermes.gateway"}, uid=501, run=fake_run
)
is None
)
def test_read_exit_timeout_fails_open_on_nonzero_rc():
def fake_run(argv, **_k):
return subprocess.CompletedProcess(argv, 113, stdout="", stderr="Could not find service")
assert (
read_launchd_exit_timeout_s(
environ={"XPC_SERVICE_NAME": "ai.hermes.gateway"}, uid=501, run=fake_run
)
is None
)
# ---------------------------------------------------------------------------
# resolve_launchd_capped_drain
# ---------------------------------------------------------------------------
def test_capped_drain_fits_inside_launchd_budget_minus_reserve():
# The incident shape: configured 180s, launchd clamps to 60s.
assert resolve_launchd_capped_drain(180.0, 60.0) == 60.0 - LAUNCHD_STOP_CLEANUP_RESERVE_S
def test_capped_drain_never_extends_a_short_drain():
assert resolve_launchd_capped_drain(20.0, 60.0) == 20.0
assert resolve_launchd_capped_drain(0.0, 60.0) == 0.0
def test_capped_drain_no_launchd_budget_returns_configured():
assert resolve_launchd_capped_drain(180.0, None) == 180.0
assert resolve_launchd_capped_drain(180.0, 0.0) == 180.0
assert resolve_launchd_capped_drain(180.0, -5.0) == 180.0
def test_capped_drain_tiny_budget_clamps_to_zero_not_negative():
assert resolve_launchd_capped_drain(180.0, 5.0) == 0.0
def test_capped_drain_tolerates_garbage_inputs():
assert resolve_launchd_capped_drain("nope", 60.0) == 0.0 # type: ignore[arg-type]
assert resolve_launchd_capped_drain(180.0, "nope") == 180.0 # type: ignore[arg-type]
# ---------------------------------------------------------------------------
# GatewayRunner wiring
# ---------------------------------------------------------------------------
def _runner(*, drain: float, launchd: float | None, by_signal: bool):
from gateway.run import GatewayRunner
runner = GatewayRunner.__new__(GatewayRunner)
runner._restart_drain_timeout = drain
runner._launchd_exit_timeout_s = launchd
runner._stop_requested_by_signal = by_signal
return runner
def test_effective_drain_capped_only_for_signal_stops_under_launchd():
assert _runner(drain=180.0, launchd=60.0, by_signal=True)._effective_stop_drain_timeout() == 50.0
# In-band restart (SIGUSR1 → after-turn → stop()) is not launchd-timed.
assert _runner(drain=180.0, launchd=60.0, by_signal=False)._effective_stop_drain_timeout() == 180.0
# Not launchd-owned (systemd, s6, foreground): configured drain stands.
assert _runner(drain=180.0, launchd=None, by_signal=True)._effective_stop_drain_timeout() == 180.0
def test_effective_drain_getattr_guarded_for_bare_doubles():
from types import SimpleNamespace
from gateway.restart import effective_stop_drain_timeout
from gateway.run import GatewayRunner
runner = GatewayRunner.__new__(GatewayRunner)
runner._restart_drain_timeout = 45.0
# No _stop_requested_by_signal / _launchd_exit_timeout_s set at all.
assert runner._effective_stop_drain_timeout() == 45.0
# Shutdown-path suites drive _stop_impl from non-GatewayRunner doubles.
assert effective_stop_drain_timeout(SimpleNamespace(_restart_drain_timeout=45.0)) == 45.0
assert (
effective_stop_drain_timeout(
SimpleNamespace(
_restart_drain_timeout=180.0,
_stop_requested_by_signal=True,
_launchd_exit_timeout_s=60.0,
)
)
== 50.0
)
def test_load_launchd_exit_timeout_warns_when_drain_exceeds_budget(monkeypatch, caplog):
import logging
from gateway import run as run_mod
monkeypatch.setattr(run_mod, "read_launchd_exit_timeout_s", lambda: 60.0)
monkeypatch.setenv("XPC_SERVICE_NAME", "ai.hermes.gateway-test")
with caplog.at_level(logging.INFO, logger=run_mod.logger.name):
assert run_mod.GatewayRunner._load_launchd_exit_timeout(180.0) == 60.0
warnings = [r for r in caplog.records if r.levelno == logging.WARNING]
assert warnings, "misconfiguration must be loud at boot"
msg = warnings[0].getMessage()
assert "180s" in msg and "60s" in msg and "ai.hermes.gateway-test" in msg
def test_load_launchd_exit_timeout_quiet_when_drain_fits(monkeypatch, caplog):
import logging
from gateway import run as run_mod
monkeypatch.setattr(run_mod, "read_launchd_exit_timeout_s", lambda: 60.0)
with caplog.at_level(logging.INFO, logger=run_mod.logger.name):
assert run_mod.GatewayRunner._load_launchd_exit_timeout(30.0) == 60.0
assert not [r for r in caplog.records if r.levelno >= logging.WARNING]
def test_load_launchd_exit_timeout_none_when_not_launchd(monkeypatch):
from gateway import run as run_mod
monkeypatch.setattr(run_mod, "read_launchd_exit_timeout_s", lambda: None)
assert run_mod.GatewayRunner._load_launchd_exit_timeout(180.0) is None
def test_cron_leash_under_launchd_cannot_exceed_exit_timeout():
"""The cron drain floor (#82161) is clamped to the launchd budget too.
Without the clamp the cron ceiling is watchdog(drain+grace) - reserve,
which for a capped 50s drain is 100s — past launchd's 60s SIGKILL.
"""
from gateway.restart import CRON_DRAIN_CLEANUP_RESERVE_S, resolve_cron_drain_budget
drain = resolve_launchd_capped_drain(180.0, 60.0) # 50
leash = min(resolve_shutdown_watchdog_delay(drain), 60.0)
budget = resolve_cron_drain_budget(drain, 600.0, watchdog_delay=leash, elapsed=0.0)
assert budget == max(drain, 60.0 - CRON_DRAIN_CLEANUP_RESERVE_S)
assert budget <= 60.0
# Sanity: the un-clamped leash would have blown the budget.
unclamped = resolve_cron_drain_budget(
drain, 600.0, watchdog_delay=resolve_shutdown_watchdog_delay(drain), elapsed=0.0
)
assert unclamped == drain + DEFAULT_SHUTDOWN_WATCHDOG_GRACE_S - CRON_DRAIN_CLEANUP_RESERVE_S
assert unclamped > 60.0
def test_signal_handler_marks_stop_as_signal_driven():
"""SIGTERM/SIGINT handler flags the runner before scheduling stop().
The handler is a closure inside the gateway main; this is a structural
contract check that both halves of the cap exist — the producer in the
signal handler and the consumer in the stop path — so neither can be
dropped in a refactor without this test going red.
"""
import inspect
from gateway import run as run_mod
src = inspect.getsource(run_mod)
assert src.count("runner._stop_requested_by_signal = True") == 1
# The drain budget is consumed in the stop path (``_stop_impl``).
assert "effective_stop_drain_timeout(self)" in inspect.getsource(
run_mod.GatewayRunner._stop_impl
)
+17
View File
@@ -1254,6 +1254,23 @@ class TestLaunchdPlistRespawnGovernance:
assert "<key>ExitTimeOut</key>" in plist
assert "<key>KeepAlive</key>" in plist
def test_plist_exit_timeout_uses_full_gui_domain_clamp(self, tmp_path, monkeypatch):
"""launchd's gui domain clamps ExitTimeOut at 60s; ask for all of it.
Anything above 60 is silently clamped, anything below throws away
drain headroom the gateway could have used before SIGKILL.
"""
import re
from gateway.restart import LAUNCHD_GUI_EXIT_TIMEOUT_CLAMP_S
from hermes_cli.gateway import generate_launchd_plist
monkeypatch.setenv("HERMES_HOME", str(tmp_path))
plist = generate_launchd_plist()
m = re.search(r"<key>ExitTimeOut</key>\s*<integer>(\d+)</integer>", plist)
assert m, plist
assert int(m.group(1)) == LAUNCHD_GUI_EXIT_TIMEOUT_CLAMP_S == 60
class TestPermissionErrorOnLockFile:
"""Stale root-owned lock files from launchd Background sessions must not