Skip to content

The agent that grows with you

refactor(gateway): gate loop-liveness watchdog via config.yaml, drop HERMES_* env knobs

Hermes Agent9cd729684989
diff --git a/gateway/config.py b/gateway/config.py
index 6e72e2942a3..781a9421733 100644
--- a/gateway/config.py
+++ b/gateway/config.py
@@ -930,6 +930,13 @@ class GatewayConfig:
# disables sd_notify at runtime.
systemd_watchdog_seconds: int = 0
+ # In-process event-loop liveness watchdog (#69089). A daemon OS thread
+ # probes the gateway loop with call_soon_threadsafe; after consecutive
+ # missed probes it dumps all-thread stacks and hard-exits with the
+ # service-restart code so the supervisor can revive the process. On by
+ # default; set gateway.loop_watchdog: false in config.yaml to disable.
+ loop_watchdog: bool = True
+
# Unauthorized DM policy
unauthorized_dm_behavior: str = "pair" # "pair" or "ignore"
@@ -1064,6 +1071,7 @@ class GatewayConfig:
"max_concurrent_sessions": self.max_concurrent_sessions,
"multiplex_profiles": self.multiplex_profiles,
"systemd_watchdog_seconds": self.systemd_watchdog_seconds,
+ "loop_watchdog": self.loop_watchdog,
"unauthorized_dm_behavior": self.unauthorized_dm_behavior,
"streaming": self.streaming.to_dict(),
"session_store_max_age_days": self.session_store_max_age_days,
@@ -1135,6 +1143,11 @@ class GatewayConfig:
systemd_watchdog_seconds = coerce_systemd_watchdog_seconds(
systemd_watchdog_raw, systemd_watchdog_key
)
+ if "loop_watchdog" in data:
+ loop_watchdog_raw = data.get("loop_watchdog")
+ else:
+ loop_watchdog_raw = nested_gateway.get("loop_watchdog")
+ loop_watchdog = _coerce_bool(loop_watchdog_raw, True)
if multiplex_profiles is None and isinstance(nested_gateway, dict):
# Also honor gateway.multiplex_profiles written by
# ``hermes config set gateway.multiplex_profiles true``.
@@ -1195,6 +1208,7 @@ class GatewayConfig:
thread_sessions_per_user=_coerce_bool(thread_sessions_per_user, False),
multiplex_profiles=_coerce_bool(multiplex_profiles, False),
systemd_watchdog_seconds=systemd_watchdog_seconds,
+ loop_watchdog=loop_watchdog,
max_concurrent_sessions=max_concurrent_sessions,
unauthorized_dm_behavior=unauthorized_dm_behavior,
streaming=StreamingConfig.from_dict(data.get("streaming", {})),
diff --git a/gateway/run.py b/gateway/run.py
index e25a97ad610..9a6b5d98333 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -7763,7 +7763,14 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
return True
def _start_loop_liveness_guards(self, loop: asyncio.AbstractEventLoop) -> None:
- """Arm the selector floor and out-of-loop watchdog before adapters."""
+ """Arm the selector floor and out-of-loop watchdog before adapters.
+
+ Disabled entirely with ``gateway.loop_watchdog: false`` in config.yaml
+ (no env override — config-only knob, #69089).
+ """
+ config = getattr(self, "config", None)
+ if config is not None and not getattr(config, "loop_watchdog", True):
+ return
if getattr(self, "_loop_floor_timer_handle", None) is None:
try:
self._loop_floor_timer_handle = _arm_loop_floor_timer(loop)
diff --git a/gateway/shutdown_watchdog.py b/gateway/shutdown_watchdog.py
index 70cb302d6cc..eb3c9074ac0 100644
--- a/gateway/shutdown_watchdog.py
+++ b/gateway/shutdown_watchdog.py
@@ -107,24 +107,6 @@ def _arm_loop_floor_timer(
return _LoopFloorTimerHandle(loop, resolved_interval)
-def _positive_float_env(name: str, default: float) -> float:
- raw = os.environ.get(name, "").strip()
- try:
- value = float(raw) if raw else float(default)
- except (TypeError, ValueError):
- return float(default)
- return value if value > 0 else float(default)
-
-
-def _positive_int_env(name: str, default: int) -> int:
- raw = os.environ.get(name, "").strip()
- try:
- value = int(raw) if raw else int(default)
- except (TypeError, ValueError):
- return int(default)
- return value if value > 0 else int(default)
-
-
def start_loop_liveness_watchdog(
loop: asyncio.AbstractEventLoop,
*,
@@ -135,21 +117,14 @@ def start_loop_liveness_watchdog(
) -> Optional[_LoopLivenessWatchdogHandle]:
"""Start an out-of-loop watchdog that hard-exits after missed probes.
- Environment overrides are intentionally read here, the owner module, like
- other gateway runtime-only safety knobs. Set
- ``HERMES_GATEWAY_LOOP_WATCHDOG=0`` to disable it.
+ The guard is on by default; operators opt out with
+ ``gateway.loop_watchdog: false`` in config.yaml (enforced by the caller,
+ ``GatewayRunner._start_loop_liveness_guards`` — this module stays
+ config-agnostic so bare-loop tests can drive it directly).
"""
- enabled = os.environ.get("HERMES_GATEWAY_LOOP_WATCHDOG", "1").strip().lower()
- if enabled in {"0", "false", "no", "off"}:
- return None
-
- interval = _positive_float_env(
- "HERMES_GATEWAY_LOOP_WATCHDOG_INTERVAL", probe_interval
- )
- timeout = _positive_float_env("HERMES_GATEWAY_LOOP_WATCHDOG_TIMEOUT", probe_timeout)
- strikes_limit = _positive_int_env(
- "HERMES_GATEWAY_LOOP_WATCHDOG_STRIKES", max_strikes
- )
+ interval = probe_interval
+ timeout = probe_timeout
+ strikes_limit = max_strikes
stop_event = threading.Event()
def _wait_for_probe(probe_event: threading.Event) -> Optional[bool]:
diff --git a/hermes_cli/config.py b/hermes_cli/config.py
index 568aafbcafb..d4e9ed843ca 100644
--- a/hermes_cli/config.py
+++ b/hermes_cli/config.py
@@ -3058,6 +3058,13 @@ DEFAULT_CONFIG = {
# works as a manual override and wins if set explicitly.
"platform_connect_timeout": 30,
+ # In-process event-loop liveness watchdog (#69089). A daemon OS thread
+ # probes the gateway asyncio loop; after consecutive missed probes it
+ # dumps all-thread stacks and hard-exits with the service-restart exit
+ # code so the supervisor (systemd/launchd) revives the process instead
+ # of leaving a wedged-but-alive zombie. Set to false to disable.
+ "loop_watchdog": True,
+
# Whether the gateway keeps writing the legacy sessions.json mirror of
# its routing index. The primary copy lives in state.db (the
# gateway_routing table). Default True for backward compatibility with
diff --git a/tests/gateway/test_loop_liveness_watchdog.py b/tests/gateway/test_loop_liveness_watchdog.py
index 1403fd831e0..77ac3df73c8 100644
--- a/tests/gateway/test_loop_liveness_watchdog.py
+++ b/tests/gateway/test_loop_liveness_watchdog.py
@@ -156,16 +156,15 @@ def test_loop_liveness_watchdog_stop_during_final_miss_disarms_hard_exit():
loop.call_soon_threadsafe.side_effect = hold_scheduled_probe
with (
- patch(
- "gateway.shutdown_watchdog._positive_int_env",
- return_value=FinalStrikeLimit(),
- ),
patch("gateway.shutdown_watchdog.logger.critical") as critical,
patch("gateway.shutdown_watchdog.faulthandler.dump_traceback") as dump,
patch("gateway.shutdown_watchdog.os._exit", side_effect=exit_codes.append),
):
handle = start_loop_liveness_watchdog(
- loop, probe_interval=0.01, probe_timeout=0.01, max_strikes=1
+ loop,
+ probe_interval=0.01,
+ probe_timeout=0.01,
+ max_strikes=FinalStrikeLimit(),
)
assert handle is not None
handle_ref["handle"] = handle
@@ -282,41 +281,43 @@ def test_loop_liveness_watchdog_stop_exits_thread_and_stops_probes():
assert loop.call_soon_threadsafe.call_count == calls_after_stop
-def test_loop_liveness_watchdog_env_can_disable(monkeypatch):
- monkeypatch.setenv("HERMES_GATEWAY_LOOP_WATCHDOG", "0")
- loop = MagicMock(spec=asyncio.AbstractEventLoop)
-
- handle = start_loop_liveness_watchdog(
- loop, probe_interval=0.01, probe_timeout=0.01, max_strikes=1
- )
-
- assert handle is None
- loop.call_soon_threadsafe.assert_not_called()
-
+def test_loop_liveness_guards_config_can_disable():
+ """gateway.loop_watchdog: false must skip arming both guards."""
+ from gateway.run import GatewayRunner
-def test_loop_liveness_watchdog_env_overrides_probe_settings(monkeypatch):
- monkeypatch.setenv("HERMES_GATEWAY_LOOP_WATCHDOG_INTERVAL", "0.01")
- monkeypatch.setenv("HERMES_GATEWAY_LOOP_WATCHDOG_TIMEOUT", "0.01")
- monkeypatch.setenv("HERMES_GATEWAY_LOOP_WATCHDOG_STRIKES", "1")
+ runner = object.__new__(GatewayRunner)
+ runner._loop_floor_timer_handle = None
+ runner._loop_liveness_watchdog = None
+ runner.config = MagicMock()
+ runner.config.loop_watchdog = False
loop = MagicMock(spec=asyncio.AbstractEventLoop)
- fired = threading.Event()
with (
- patch("gateway.shutdown_watchdog.faulthandler.dump_traceback"),
- patch(
- "gateway.shutdown_watchdog.os._exit",
- side_effect=lambda code: fired.set(),
- ),
+ patch("gateway.run._arm_loop_floor_timer") as arm_floor,
+ patch("gateway.run.start_loop_liveness_watchdog") as start_watchdog,
):
- handle = start_loop_liveness_watchdog(
- loop, probe_interval=10.0, probe_timeout=10.0, max_strikes=10
- )
- assert handle is not None
- assert fired.wait(timeout=2.0), "env overrides were not applied"
- handle.join(timeout=1.0)
+ runner._start_loop_liveness_guards(loop)
- assert not handle.is_alive()
- assert loop.call_soon_threadsafe.call_count == 1
+ arm_floor.assert_not_called()
+ start_watchdog.assert_not_called()
+ assert runner._loop_floor_timer_handle is None
+ assert runner._loop_liveness_watchdog is None
+
+
+def test_gateway_config_loop_watchdog_round_trip():
+ """loop_watchdog is a config.yaml knob: default on, nested-gateway form honored."""
+ from gateway.config import GatewayConfig
+
+ assert GatewayConfig.from_dict({}).loop_watchdog is True
+ assert GatewayConfig.from_dict({"loop_watchdog": False}).loop_watchdog is False
+ assert (
+ GatewayConfig.from_dict(
+ {"gateway": {"loop_watchdog": "off"}}
+ ).loop_watchdog
+ is False
+ )
+ config = GatewayConfig.from_dict({"loop_watchdog": False})
+ assert config.to_dict()["loop_watchdog"] is False
@pytest.mark.asyncio