The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(gateway): second pass on shutdown_* / scale_to_zero / systemd_notify (inline helpers, compact docs)
Tekniumab10d351b029
diff --git a/gateway/scale_to_zero.py b/gateway/scale_to_zero.pyindex f438bb0b13c..8eb50540b1e 100644--- a/gateway/scale_to_zero.py+++ b/gateway/scale_to_zero.py@@ -1,29 +1,13 @@"""Scale-to-zero idle detection + dormant-quiesce for the gateway.-Gateway-side behaviour layer over the relay scale-to-zero primitives: it owns-the *decision* to go idle, drives the relay transport's ``go_dormant()``, then-SUSPENDS the machine through the local Fly Machines API socket. Wake stays-platform-side (autostart-on-wakeUrl).--Why the gateway self-suspends instead of relying on Fly ``autostop:"suspend"``:-Fly Proxy judges idle only on INBOUND proxied connections — it cannot see an-in-flight agent turn (outbound-only LLM traffic) and no longer counts open-outbound sockets, so it would suspend mid-job or BEFORE ``go_dormant()`` flipped-the relay destination (buffered-event black hole). Owning the call means it only-fires after the idle predicate holds AND the dormant quiesce completed.--Design constraints:- - Per-instance enable is gated SOLELY by the NAS "Labs" toggle, carried as- the ``HERMES_SCALE_TO_ZERO`` env stamp — not a config key;- ``scale_to_zero.idle_timeout_minutes`` IS config.yaml.- - Arm only when messaging is relay-only or absent AND a wakeUrl is registered- AND the flag is set.- - Idle = no in-flight work AND no inbound for N min AND no live background work.- - Quiesce uses ``go_dormant()`` (socket closed, supervisor preserved), NEVER- the stop/restart drain or ``disconnect()``. The process stays alive.- - ``mark_resume_pending`` is deliberately NOT called: suspend preserves RAM.--The pure helpers take plain inputs so they unit-test without a live gateway.+Owns the *decision* to go idle, drives the relay transport's ``go_dormant()``,+then SUSPENDS the machine via the local Fly Machines API socket; wake stays+platform-side (autostart-on-wakeUrl). The gateway self-suspends because Fly+Proxy only sees INBOUND proxied connections — it would suspend mid-turn or+before ``go_dormant()`` flipped the relay destination (buffered-event black hole).+Enable is gated SOLELY by the NAS "Labs" toggle env stamp (not config); the idle+timeout IS config.yaml. Quiesce uses ``go_dormant()`` (never disconnect/drain)+and ``mark_resume_pending`` is NOT called: suspend preserves RAM."""from __future__ import annotations@@ -38,31 +22,19 @@ from typing import Any, Iterable, Optionallogger = logging.getLogger(__name__)-# Env flag stamped by NAS when the scaleToZero Labs toggle is on. Truthy values only.-SCALE_TO_ZERO_ENV = "HERMES_SCALE_TO_ZERO"--# Fly-injected machine identity; both must be present for self_suspend_available().-FLY_APP_NAME_ENV = "FLY_APP_NAME"+SCALE_TO_ZERO_ENV = "HERMES_SCALE_TO_ZERO" # stamped by NAS when the Labs toggle is on+FLY_APP_NAME_ENV = "FLY_APP_NAME" # Fly-injected identity; both needed for self_suspend_available()FLY_MACHINE_ID_ENV = "FLY_MACHINE_ID"--# Local flaps (Fly Machines API) unix socket. POST .../suspend snapshots RAM and-# suspends THIS machine (https://fly.io/docs/reference/suspend-resume/).+# Local flaps (Fly Machines API) socket; POST .../suspend freezes THIS machine.FLY_API_SOCKET = "/.fly/api"--# config.yaml default (behavioural setting -> config, not env). Short is safe-# because real work always blocks the suspend and resume is sub-second; longer-# windows just bill idle RAM. Raise via gateway.scale_to_zero.idle_timeout_minutes.+# Short is safe: real work always blocks the suspend and resume is sub-second; longer just bills+# idle RAM.DEFAULT_IDLE_TIMEOUT_MINUTES = 2-_TRUTHY = {"1", "true", "yes", "on"}--# Dashboard-client liveness marker. The dashboard process (tui_gateway/ws.py, a-# DIFFERENT process on hosted instances) touches this on every /api/ws connect and-# inbound frame (clients ping every 15s). The gateway folds the mtime into its-# inbound clock so an open client holds the box awake like a chat message does —-# otherwise the box suspends under the client, whose reconnect re-pokes the wake-# URL and the instance flaps every ~60s. Deliberately NO staleness cutoff: the-# mtime is a real inbound timestamp and is_idle decides whether it is recent enough.+# Dashboard-client liveness marker, touched by the (separate) dashboard process on every /api/ws+# connect and inbound frame. Folded into the inbound clock so an open client holds the box awake —+# otherwise it suspends under the client, whose reconnect re-pokes the wake URL and the instance+# flaps every ~60s. Deliberately NO staleness cutoff: is_idle decides whether the mtime is recent.DASHBOARD_CLIENT_HEARTBEAT_REL = os.path.join("state", "dashboard_clients.heartbeat")@@ -80,8 +52,7 @@ def parse_idle_timeout_seconds() -> float:"""Coerce ``scale_to_zero.idle_timeout_minutes`` to seconds.- Any non-numeric / non-positive value degrades to the default (never <= 0:- that would make the gateway go dormant instantly).+ Non-numeric / non-positive degrades to the default (never <= 0: instant dormancy)."""try:minutes = float(cfg_value)@@ -102,10 +73,9 @@ def messaging_is_relay_only_or_absent(platforms: Iterable[Any]) -> bool:def should_arm(*, enabled: bool, relay_only_or_absent: bool, wake_url: Optional[str]) -> bool:- """Start the idle watcher only if ALL hold: flag on, relay-only/absent messaging,- wakeUrl registered (a suspended instance with no wake target is a black hole).- Any unmet -> the watcher never starts (no idle timer, no dormancy), so a- non-opted instance behaves exactly as before."""+ """Arm only if ALL hold: flag on, relay-only/absent messaging, wakeUrl registered+ (a suspended instance with no wake target is a black hole). Otherwise the watcher+ never starts, so a non-opted instance behaves exactly as before."""return bool(enabled) and bool(relay_only_or_absent) and bool(wake_url)@@ -116,16 +86,17 @@ def is_idle(idle_timeout_seconds: float,has_live_background_work: bool,) -> bool:- """The pure idle predicate: no counted active work, no inbound within the- timeout window, and no live background work (backgrounded delegate_task /- kanban / bg terminal) — suspending mid-flight would lose it.-- ``active_work_count`` is the BROAD aggregate (agent turns + cron + API runs),- not just agents — passing only ``len(_running_agents)`` reopens the- mid-cron-job suspend hole. Callers that cannot read a work source must fail- AWAKE (pass a positive sentinel), never fail to 0.+ """Pure idle predicate: no active work, no inbound within the window, no live background work.++ ``active_work_count`` is the BROAD aggregate (agent turns + cron + API runs) — passing only+ ``len(_running_agents)`` reopens the mid-cron-job suspend hole. Callers that cannot read a+ work source must fail AWAKE (pass a positive sentinel), never fail to 0."""- return active_work_count <= 0 and not has_live_background_work and seconds_since_last_inbound >= idle_timeout_seconds+ return (+ active_work_count <= 0+ and not has_live_background_work+ and seconds_since_last_inbound >= idle_timeout_seconds+ )def dashboard_client_heartbeat_path(hermes_home: Optional[os.PathLike | str] = None):@@ -156,15 +127,13 @@ def dashboard_client_last_seen() -> Optional[float]:"""Epoch seconds a dashboard client last sent a WS frame, or None if never.- Missing marker -> None (steady state when nobody has the dashboard open —- NOT fail-awake, or no instance would ever sleep). Unreadable marker ->- ``now`` (fail-awake, same rule as the work counters in ``is_idle``).+ Missing marker -> None (steady state when nobody has the dashboard open — NOT fail-awake,+ or no instance would ever sleep). Unreadable marker -> ``now`` (fail-awake, as in ``is_idle``).+ Clamped to now: an NTP step-back can leave the mtime in the future."""current = time.time() if now is None else nowp = dashboard_client_heartbeat_path() if path is None else pathtry:- # Clamp to now: an NTP step-back can leave the mtime in the future,- # which would push idle out by the step size for no reason.return min(os.stat(p).st_mtime, current)except FileNotFoundError:return None@@ -175,22 +144,25 @@ def dashboard_client_last_seen(def self_suspend_available(environ: Optional[dict] = None) -> bool:"""True iff Fly machine identity is present AND the local Machines API socket exists.- Off-Fly (local dev, other clouds, tests) the watcher skips the quiesce:- the platform owns the freeze, so the gateway stays connected until it lands.+ Off-Fly the watcher skips the quiesce: the platform owns the freeze."""return bool(- _env_str(environ, FLY_APP_NAME_ENV) and _env_str(environ, FLY_MACHINE_ID_ENV) and os.path.exists(FLY_API_SOCKET)+ _env_str(environ, FLY_APP_NAME_ENV)+ and _env_str(environ, FLY_MACHINE_ID_ENV)+ and os.path.exists(FLY_API_SOCKET))-def suspend_self(environ: Optional[dict] = None, *, socket_path: str = FLY_API_SOCKET, timeout: float = 10.0) -> bool:- """POST /v1/apps/{app}/machines/{id}/suspend on the local flaps socket.+def suspend_self(+ environ: Optional[dict] = None, *, socket_path: str = FLY_API_SOCKET, timeout: float = 10.0+) -> bool:+ """POST /v1/apps/{app}/machines/{id}/suspend on the local flaps socket (the socket is the+ credential).- No token needed — the socket is the credential. Returns True when flaps- accepted (2xx); on success the kernel freezes this process shortly after,- so treat as fire-and-forget. Never raises: a failed suspend just leaves the- machine running (fail-awake, never fail-frozen). stdlib-only on purpose —- a plain unix-socket HTTP/1.1 request, no async plumbing to freeze mid-await.+ Returns True when flaps accepted (2xx); the kernel then freezes this process shortly after, so+ treat as fire-and-forget. Never raises: a failed suspend leaves the machine running (fail-+ awake). stdlib-only on purpose — a plain unix-socket HTTP/1.1 request, no async plumbing to+ freeze mid-await."""app = _env_str(environ, FLY_APP_NAME_ENV)machine_id = _env_str(environ, FLY_MACHINE_ID_ENV)@@ -222,5 +194,7 @@ def suspend_self(environ: Optional[dict] = None, *, socket_path: str = FLY_API_Slogger.info("scale-to-zero: machine suspend accepted by flaps (%s)", status_line)else:body = response.split(b"\r\n\r\n", 1)[-1][:500].decode("utf-8", "replace")- logger.warning("scale-to-zero: flaps suspend rejected: %s %s", status_line, json.dumps(body)[:500])+ logger.warning(+ "scale-to-zero: flaps suspend rejected: %s %s", status_line, json.dumps(body)[:500]+ )return okdiff --git a/gateway/shutdown_flush.py b/gateway/shutdown_flush.pyindex 3715a20e5bb..5728bc09d21 100644--- a/gateway/shutdown_flush.py+++ b/gateway/shutdown_flush.py@@ -1,17 +1,17 @@"""Flush pending messages and agent transcripts to disk before shutdown to prevent data loss.When FTS5 corruption blocks ``INSERT INTO messages``, ``_pending_messages`` and the live-``agent._session_messages`` are the only surviving copies; shutdown ``.clear()`` would drop-them. All hooks write atomic JSON payloads under ``<hermes_home>/pending_messages/``:-``flush_pending_to_file`` / ``flush_overflow_to_file`` (queue head / FIFO tail, before-clear), ``recover_pending_to_db`` (after ``runner.start()``; replays via-``SessionDB.append_message`` and deletes each file on success), ``flush_agent_history_to_file``-(when the DB flush raises), ``spool_dropped_transcript_message`` / ``drain_transcript_spool``-(live spool for cap-evicted transcript messages).+``agent._session_messages`` are the only surviving copies; shutdown ``.clear()`` would drop them.+All hooks write atomic JSON payloads under ``<hermes_home>/pending_messages/``:+``flush_pending_to_file`` / ``flush_overflow_to_file`` (queue head / FIFO tail, before clear),+``recover_pending_to_db`` (after ``runner.start()``; replays via ``SessionDB.append_message``,+deletes each file on success), ``flush_agent_history_to_file`` (DB flush raised),+``spool_dropped_transcript_message`` / ``drain_transcript_spool``."""from __future__ import annotations+import contextlibimport itertoolsimport jsonimport logging@@ -23,10 +23,9 @@ from typing import Any, Dict, Optionallogger = logging.getLogger(__name__)-# Reason tag for transcript messages dropped by the in-memory pending cap during-# live operation. Payloads carry the full transcript message dict for verbatim replay.+# Reason tag for transcript messages dropped by the in-memory pending cap during live+# operation. Payloads carry the full transcript message dict for verbatim replay.TRANSCRIPT_CAP_DROP_REASON = "transcript_cap_drop"-# Monotonic tiebreaker so same-second spool files replay in drop order._TRANSCRIPT_SPOOL_SEQ = itertools.count()@@ -34,7 +33,6 @@ _TRANSCRIPT_SPOOL_SEQ = itertools.count()def _get_flush_dir():"""Return the pending-messages flush directory under the active HERMES_HOME."""from hermes_constants import get_hermes_home-flush_dir = get_hermes_home() / "pending_messages"flush_dir.mkdir(parents=True, exist_ok=True, mode=0o700)if os.name == "posix":@@ -45,12 +43,11 @@ def _get_flush_dir():def _write_payload(flush_dir: Path, payload: Dict[str, Any]) -> Path:"""Atomically write one private, uniquely named recovery payload; return its path."""from utils import atomic_json_write-final_path = flush_dir / f"pending-{uuid.uuid4().hex}.json"atomic_json_write(final_path, payload, mode=0o600, default=str)if os.name == "posix":- # Persist the directory entry too. The published file is still the only- # recovery copy; keep it even if this filesystem cannot fsync directories.+ # Persist the directory entry too; keep the published file (the only recovery copy) even if+ # fsync fails.try:directory_fd = os.open(flush_dir, os.O_RDONLY)except OSError as exc:@@ -79,93 +76,86 @@ def _flush_value(flush_dir: Path, kind: str, session_key: str, value: Any, **extdef flush_pending_to_file(pending: Dict[str, Any], *, reason: str = "shutdown") -> int:- """Serialise non-empty ``_pending_messages`` slots to disk.-- ``pending`` values may be ``MessageEvent`` objects (adapter) or plain- strings (runner). Returns the number of sessions flushed.+ """Serialise non-empty ``_pending_messages`` slots (``MessageEvent`` or str) to disk; return+ sessions flushed."""if not pending:return 0-- flush_dir = _get_flush_dir()- ts = int(time.time())- flushed = 0+ flush_dir, ts, flushed = _get_flush_dir(), int(time.time()), 0for session_key, value in list(pending.items()):if value is not None:flushed += _flush_value(flush_dir, "pending", session_key, value, reason=reason, ts=ts)-if flushed:logger.info("Flushed %d pending message(s) to %s (reason=%s)", flushed, flush_dir, reason)return flusheddef flush_overflow_to_file(overflow_by_session: Dict[str, Any], *, reason: str = "shutdown") -> int:- """Serialise the FIFO overflow tails (``queued_events``) to disk.+ """Serialise the FIFO overflow tails (``queued_events``) to disk; return events flushed.- The adapter slot holds the queue head and ``SessionState.conversation- .queued_events`` holds the tail; both must survive restart. Each event- is its own payload in the slot-flush shape so ``recover_pending_to_db``- replays them unchanged; ``seq`` preserves arrival order within a session.- Returns the number of events flushed.+ The adapter slot holds the queue head and ``SessionState.conversation.queued_events`` the+ tail; both must survive restart. Each event is its own payload in the slot-flush shape so+ ``recover_pending_to_db`` replays them unchanged; ``seq`` preserves arrival order per session."""if not overflow_by_session:return 0-- flush_dir = _get_flush_dir()- ts = int(time.time())- flushed = 0+ flush_dir, ts, flushed = _get_flush_dir(), int(time.time()), 0for session_key, events in list(overflow_by_session.items()):if not session_key or not events:continuefor seq, value in enumerate(list(events)):if value is not None:- flushed += _flush_value(flush_dir, "overflow", session_key, value, reason=reason, ts=ts, seq=seq)-+ flushed += _flush_value(+ flush_dir, "overflow", session_key, value, reason=reason, ts=ts, seq=seq+ )if flushed:- logger.info("Flushed %d queued overflow message(s) to %s (reason=%s)", flushed, flush_dir, reason)+ logger.info(+ "Flushed %d queued overflow message(s) to %s (reason=%s)", flushed, flush_dir, reason+ )return flusheddef spool_dropped_transcript_message(session_id: str, message: Dict[str, Any]) -> Optional[Path]:- """Spool a transcript message evicted by the runtime pending cap.-- Returns the written spool path, or ``None`` when spooling failed —- callers must degrade to drop-and-log.+ """Spool a cap-evicted transcript message; ``None`` on failure (callers degrade to drop-and-+ log)."""try:- return _write_payload(_get_flush_dir(), {- "session_key": session_id,- "reason": TRANSCRIPT_CAP_DROP_REASON,- "ts": int(time.time()),- "seq": next(_TRANSCRIPT_SPOOL_SEQ),- "data": {"session_id": session_id, "message": message},- })+ return _write_payload(+ _get_flush_dir(),+ {+ "session_key": session_id,+ "reason": TRANSCRIPT_CAP_DROP_REASON,+ "ts": int(time.time()),+ "seq": next(_TRANSCRIPT_SPOOL_SEQ),+ "data": {"session_id": session_id, "message": message},+ },+ )except Exception as exc:logger.debug("Failed to spool cap-dropped transcript message for %s: %s", session_id, exc)return Nonedef drain_transcript_spool(session_id: str, replay) -> tuple[int, int]:- """Replay cap-dropped transcript messages spooled for *session_id*.-- ``replay(message_dict)`` runs per message in drop order; a spool file is- deleted only after its replay succeeds. The first failure stops the- drain (the DB is likely still unhealthy) and keeps the rest for retry.- Returns ``(replayed, remaining)``.+ """Replay cap-dropped transcript messages spooled for *session_id*; return ``(replayed,+ remaining)``. ``replay(message_dict)`` runs per message in drop order; a spool file is deleted+ only after its replay succeeds. The first failure stops the drain (the DB is likely still+ unhealthy) and keeps the rest for retry."""try:candidates = list(_get_flush_dir().glob("pending-*.json"))except Exception as exc:logger.debug("Cannot scan transcript spool: %s", exc)return 0, 0-entries = []for path in candidates:try:payload = json.loads(path.read_text(encoding="utf-8"))except Exception:continue- if payload.get("reason") != TRANSCRIPT_CAP_DROP_REASON or payload.get("session_key") != session_id:+ if (+ payload.get("reason") != TRANSCRIPT_CAP_DROP_REASON+ or payload.get("session_key") != session_id+ ):continuemessage = (payload.get("data") or {}).get("message")if not isinstance(message, dict):@@ -173,25 +163,23 @@ def drain_transcript_spool(session_id: str, replay) -> tuple[int, int]:path.unlink(missing_ok=True)continueentries.append((payload.get("ts", 0), payload.get("seq", 0), path.name, path, message))-- ordered = sorted(entries, key=lambda e: e[:3])- replayed = remaining = 0+ ordered, replayed, remaining = sorted(entries, key=lambda e: e[:3]), 0, 0for idx, (_ts, _seq, _name, path, message) in enumerate(ordered):try:replay(message)except Exception as exc:- logger.warning(- "Replay of spooled transcript message %s for %s failed; "- "keeping spool file for retry: %s",- path, session_id, exc,- )+ logger.warning("Replay of spooled transcript message %s for %s failed; "+ "keeping spool file for retry: %s", path, session_id, exc)remaining = len(ordered) - idxbreakpath.unlink(missing_ok=True)replayed += 1-if replayed:- logger.info("Replayed %d spooled transcript message(s) for %s after DB recovery", replayed, session_id)+ logger.info(+ "Replayed %d spooled transcript message(s) for %s after DB recovery",+ replayed,+ session_id,+ )return replayed, remaining@@ -207,7 +195,15 @@ def _serialise_value(value: Any) -> Optional[dict]:"""Convert a pending message value to a JSON-serialisable dict."""if hasattr(value, "text"): # MessageEvent-like objectresult: Dict[str, Any] = {"text": getattr(value, "text", "")}- for attr in ("session_id", "platform", "sender_id", "sender_name", "reply_to", "media", "raw_event"):+ for attr in (+ "session_id",+ "platform",+ "sender_id",+ "sender_name",+ "reply_to",+ "media",+ "raw_event",+ ):val = getattr(value, attr, None)if val is not None:result[attr] = val if _json_safe(val) else str(val)@@ -220,61 +216,48 @@ def _serialise_value(value: Any) -> Optional[dict]:def recover_pending_to_db(session_db=None) -> int:- """Recover flushed pending messages into state.db via SessionDB.+ """Replay flush-dir ``*.json`` files via ``SessionDB.append_message``, deleting each on success.- Reads all ``*.json`` files from the flush directory, inserts messages via- ``SessionDB.append_message`` and deletes each flush file on success.- ``session_db=None`` opens (and afterwards releases) the shared default- ``state.db``. Returns the number of messages recovered.+ ``session_db=None`` opens (and afterwards releases) the shared default ``state.db``.+ Returns the number of messages recovered."""flush_files = sorted(_get_flush_dir().glob("*.json"))if not flush_files:return 0-own_db = session_db is Noneif own_db:from hermes_state import get_shared_session_dbsession_db = get_shared_session_db()-recovered = 0try:for path in flush_files:payload = json.loads(path.read_text(encoding="utf-8"))- # Agent-history snapshots (reason + messages list) are for manual- # operator recovery, not automatic DB insertion.+ # Agent-history snapshots are for manual operator recovery, not automatic DB insertion.if payload.get("reason") == "shutdown-with-unpersisted-agent-history":continueif _recover_one_payload(session_db, path, payload):recovered += 1path.unlink(missing_ok=True)finally:- # Shutdown cancellation/interrupt must not strand an owned DB.- if own_db:- try:+ if own_db: # shutdown cancellation/interrupt must not strand an owned DB+ with contextlib.suppress(Exception):from hermes_state import release_or_closerelease_or_close(session_db)- except Exception:- pass-if recovered:logger.info("Recovered %d pending message(s) from shutdown flush", recovered)return recovereddef _recover_one_payload(session_db, path: Path, payload: Dict[str, Any]) -> bool:- """Append one flush payload to ``session_db``; False (file preserved) when structurally invalid."""+ """Append one flush payload to ``session_db``; False (file preserved) when structurally invalid.+ """if payload.get("reason") == TRANSCRIPT_CAP_DROP_REASON:- # Cap-dropped transcript payloads carry the full message dict keyed by- # session_id — replay directly (spool never drained before restart).+ # Cap-dropped payloads carry the full message dict keyed by session_id — replay directly.data = payload.get("data", {}) or {}- spooled_sid = data.get("session_id", "")- message = data.get("message")+ spooled_sid, message = data.get("session_id", ""), data.get("message")if not spooled_sid or not isinstance(message, dict):- logger.warning(- "Cannot recover structurally invalid transcript spool "- "file %s; preserved for manual inspection",- path,- )+ logger.warning("Cannot recover structurally invalid transcript spool "+ "file %s; preserved for manual inspection", path)return Falsesession_db.append_message(session_id=spooled_sid,@@ -283,43 +266,34 @@ def _recover_one_payload(session_db, path: Path, payload: Dict[str, Any]) -> bootimestamp=message.get("timestamp") or payload.get("ts"),)return True- session_key = payload.get("session_key", "")- data = payload.get("data", {})+ session_key, data = payload.get("session_key", ""), payload.get("data", {})text = data.get("text", "")if not text or not session_key:- logger.warning(- "Cannot recover structurally invalid pending message from %s; "- "the flush file has been preserved",- path,- )+ logger.warning("Cannot recover structurally invalid pending message from %s; "+ "the flush file has been preserved", path)return False- # session_key is a gateway routing key (e.g. "agent:main:telegram:...");- # appending a row needs the real session_id, which only the serialised- # data can supply at this recovery stage.+ # session_key is a gateway routing key (e.g. "agent:main:telegram:..."); appending a row+ # needs the real session_id, which only the serialised data can supply at this stage.session_id = data.get("session_id", "")if not session_id:- logger.warning(- "Cannot recover pending message for %s: no session_id "- "in flush file and session_key-to-id resolution is not "- "available at this recovery stage. The message text is "- "preserved in %s",- session_key, path,- )+ logger.warning("Cannot recover pending message for %s: no session_id in flush file and "+ "session_key-to-id resolution is not available at this recovery stage. "+ "The message text is preserved in %s", session_key, path)return Falsesession_db.append_message(- session_id=session_id, role="user", content=text, timestamp=payload.get("ts", int(time.time())),+ session_id=session_id,+ role="user",+ content=text,+ timestamp=payload.get("ts", int(time.time())),)return Truedef flush_agent_history_to_file(session_id: Optional[str], history: list) -> None:- """Best-effort dump of an agent's in-memory transcript before teardown.-- Used when ``_flush_messages_to_session_db`` raises (e.g. FTS/SQLite- corruption): the transcript is written outside the broken DB so an- operator can salvage it after repairing state.db. Failures are- swallowed — shutdown must never block on a best-effort backup.- """+ """Best-effort dump of an agent's in-memory transcript before teardown. Used when+ ``_flush_messages_to_session_db`` raises (e.g. FTS/SQLite corruption): the transcript is written+ outside the broken DB so an operator can salvage it after repairing state.db. Failures are+ swallowed — shutdown must never block on a best-effort backup."""if not history:returntry:@@ -327,20 +301,24 @@ def flush_agent_history_to_file(session_id: Optional[str], history: list) -> Nonsnapshot = []for _m in history:try:- snapshot.append(_m if isinstance(_m, (dict, list, str, int, float, bool, type(None))) else str(_m))+ snapshot.append(+ _m+ if isinstance(_m, (dict, list, str, int, float, bool, type(None)))+ else str(_m)+ )except Exception:continue_write_payload(flush_dir, {- "reason": "shutdown-with-unpersisted-agent-history",- "issue": "#72680",- "session_id": session_id,- "count": len(snapshot),- "messages": snapshot,+ "reason": "shutdown-with-unpersisted-agent-history", "issue": "#72680",+ "session_id": session_id, "count": len(snapshot), "messages": snapshot,})logger.warning("Preserved %d in-memory message(s) for session %s ""(possible FTS corruption — recover after repairing state.db)",- len(snapshot), session_id,+ len(snapshot),+ session_id,)except Exception as _e:- logger.warning("Agent-history shutdown preservation failed for session %s: %s", session_id, _e)+ logger.warning(+ "Agent-history shutdown preservation failed for session %s: %s", session_id, _e+ )diff --git a/gateway/shutdown_forensics.py b/gateway/shutdown_forensics.pyindex fd3a900fc14..fa9e881fdc4 100644--- a/gateway/shutdown_forensics.py+++ b/gateway/shutdown_forensics.py@@ -40,13 +40,10 @@ def _signal_name(sig: Any) -> str:def _read_proc_field(pid: int, key: str) -> Optional[str]:"""Read a single field from /proc/<pid>/status. Linux only; None elsewhere."""- try:- with open(f"/proc/{pid}/status", encoding="utf-8") as fh:- for line in fh:- if line.startswith(key + ":"):- return line.split(":", 1)[1].strip()- except OSError:- pass+ with contextlib.suppress(OSError), open(f"/proc/{pid}/status", encoding="utf-8") as fh:+ for line in fh:+ if line.startswith(key + ":"):+ return line.split(":", 1)[1].strip()return None@@ -56,21 +53,18 @@ def _proc_summary(pid: int) -> Dict[str, Any]:if pid <= 0:return summaryfor out_key, proc_key in (("name", "Name"), ("state", "State")):- value = _read_proc_field(pid, proc_key)- if value is not None:+ if (value := _read_proc_field(pid, proc_key)) is not None:summary[out_key] = value- ppid = _read_proc_field(pid, "PPid")- if ppid is not None:+ if (ppid := _read_proc_field(pid, "PPid")) is not None:with contextlib.suppress(ValueError):summary["ppid"] = int(ppid)- uid = _read_proc_field(pid, "Uid")- if uid is not None:+ if (uid := _read_proc_field(pid, "Uid")) is not None:summary["uid"] = uid.split()[0] if uid else uid # "real effective saved fs"try:data = Path(f"/proc/{pid}/cmdline").read_bytes()except OSError:data = b""- if data: # Truncate aggressively — these can be 4KB.+ if data: # truncate aggressively — these can be 4KBsummary["cmdline"] = data.replace(b"\x00", b" ").decode("utf-8", errors="replace").strip()[:300]return summary@@ -84,14 +78,10 @@ def _read_marker(path: Path) -> Optional[str]:def snapshot_shutdown_context(received_signal: Any = None) -> Dict[str, Any]:- """Fast (<10ms) snapshot of who/what is asking us to shut down.-- Signal name/number, own + parent /proc summaries, systemd parentage,- takeover/planned-stop markers, TracerPid, 1-min load, wall/monotonic- timestamps. Pure stdlib, never raises, never blocks on subprocesses.- """- pid = os.getpid()- ppid = os.getppid()+ """Fast (<10ms) snapshot of who/what is asking us to shut down: signal name/number, own + parent+ /proc summaries, systemd parentage, takeover/planned-stop markers, TracerPid, 1-min load,+ timestamps. Pure stdlib, never raises, never blocks."""+ pid, ppid = os.getpid(), os.getppid()ctx: Dict[str, Any] = {"ts": time.time(),"ts_monotonic": time.monotonic(),@@ -102,53 +92,48 @@ def snapshot_shutdown_context(received_signal: Any = None) -> Dict[str, Any]:"parent": _proc_summary(ppid),"self": _proc_summary(pid),}-- # INVOCATION_ID is set by systemd units; ppid==1 also strongly suggests- # systemd reaped+forwarded the SIGTERM.- for ctx_key, env_key in (("systemd_invocation_id", "INVOCATION_ID"), ("systemd_journal_stream", "JOURNAL_STREAM")):+ # INVOCATION_ID is set by systemd units; ppid==1 also strongly suggests systemd forwarded the+ # SIGTERM.+ for ctx_key, env_key in (+ ("systemd_invocation_id", "INVOCATION_ID"),+ ("systemd_journal_stream", "JOURNAL_STREAM"),+ ):if os.environ.get(env_key):ctx[ctx_key] = os.environ[env_key]ctx["under_systemd"] = bool(os.environ.get("INVOCATION_ID")) or ppid == 1-# High load points at "something crushing the box" rather than an external killer.with contextlib.suppress(OSError, AttributeError):ctx["loadavg_1m"] = os.getloadavg()[0]-# Nonzero TracerPid means a debugger/strace is attached.- try:- tracer = _read_proc_field(pid, "TracerPid")- if tracer is not None and tracer != "0":+ with contextlib.suppress(TypeError, ValueError):+ if (tracer := _read_proc_field(pid, "TracerPid")) is not None and tracer != "0":ctx["tracer_pid"] = int(tracer) if tracer.isdigit() else tracerctx["tracer"] = _proc_summary(int(tracer)) if tracer.isdigit() else None- except (TypeError, ValueError):- pass-- # Race hint: a takeover marker on disk that does NOT name us is a smoking- # gun for "another --replace instance is killing us". Filenames mirror- # gateway.status; literals keep the signal-handler path import-light.- try:+ # Race hint: a takeover marker on disk that does NOT name us is a smoking gun for "another+ # --replace instance is killing us". Filenames mirror gateway.status; literals keep the signal-+ # handler path import-light.+ with contextlib.suppress(Exception): # noqa: BLE001 — never raise from a signal handlerhermes_home_str = os.environ.get("HERMES_HOME")if hermes_home_str:raw = _read_marker(Path(hermes_home_str) / ".gateway-takeover.json")if raw is not None:ctx["takeover_marker"] = raw[:300]- ctx["takeover_marker_for_self"] = f'"target_pid": {pid}' in raw or f"'target_pid': {pid}" in raw+ ctx["takeover_marker_for_self"] = (+ f'"target_pid": {pid}' in raw or f"'target_pid': {pid}" in raw+ )raw = _read_marker(Path(hermes_home_str) / ".gateway-planned-stop.json")if raw is not None:ctx["planned_stop_marker"] = raw[:300]- except Exception: # noqa: BLE001 — never raise from a signal handler- pass-return ctx-def spawn_async_diagnostic(log_path: Path, signal_name: str, *, timeout_seconds: float = 5.0) -> Optional[int]:- """Fire-and-forget ``ps``-style snapshot appended to ``log_path``.-- A detached subprocess (own ``timeout`` so a wedged ``ps`` self-cleans) rather- than a blocking ``ps aux`` in the signal handler, which can freeze the loop >2s- on a busy host. Returns the subprocess PID, or ``None`` on failure / Windows- (bash -c is available on every POSIX target; Windows has no ps anyway).+def spawn_async_diagnostic(+ log_path: Path, signal_name: str, *, timeout_seconds: float = 5.0+) -> Optional[int]:+ """Fire-and-forget ``ps``-style snapshot appended to ``log_path``: a detached subprocess (own+ ``timeout`` so a wedged ``ps`` self-cleans) rather than a blocking ``ps aux`` in the signal+ handler, which can freeze the loop >2s on a busy host. Returns the subprocess PID, or ``None``+ on failure / Windows (bash -c is available on every POSIX target; Windows has no ps anyway)."""try:log_path.parent.mkdir(parents=True, exist_ok=True)@@ -156,53 +141,49 @@ def spawn_async_diagnostic(log_path: Path, signal_name: str, *, timeout_seconds:return Noneif sys.platform == "win32":return None-script = (f"echo '=== shutdown diagnostic @ {signal_name} ==='; ""echo '--- date ---'; date -u +%Y-%m-%dT%H:%M:%SZ; "- "echo '--- ps auxf (top 60 by cpu) ---'; "- "ps auxf --sort=-pcpu 2>/dev/null | head -60; "- "echo '--- pstree of self ---'; "- f"pstree -plau {os.getpid()} 2>/dev/null | head -40 || true; "- "echo '--- /proc/loadavg ---'; "- "cat /proc/loadavg 2>/dev/null || true; "+ "echo '--- ps auxf (top 60 by cpu) ---'; ps auxf --sort=-pcpu 2>/dev/null | head -60; "+ f"echo '--- pstree of self ---'; pstree -plau {os.getpid()} 2>/dev/null | head -40 || true; "+ "echo '--- /proc/loadavg ---'; cat /proc/loadavg 2>/dev/null || true; ""echo '--- recent dmesg (oom/killed) ---'; ""dmesg -T 2>/dev/null | tail -20 || journalctl --user -n 20 --no-pager 2>/dev/null | tail -20 || true; ""echo '=== end ==='")-- try:- # O_APPEND so concurrent diagnostics from rapid signals don't trample each other.+ try: # O_APPEND so concurrent diagnostics from rapid signals don't trample each otherfd = os.open(str(log_path), os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o644)except OSError:return None-try:- # start_new_session: survive systemd killing our cgroup (KillMode=control-group)- # long enough to flush.- proc = subprocess.Popen(+ # start_new_session: survive systemd killing our cgroup (KillMode=control-group) long enough+ # to flush.+ return subprocess.Popen(["timeout", f"{timeout_seconds:.0f}", "bash", "-c", script],- stdout=fd, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL,- start_new_session=True, close_fds=True,- )+ stdout=fd,+ stderr=subprocess.STDOUT,+ stdin=subprocess.DEVNULL,+ start_new_session=True,+ close_fds=True,+ ).pidexcept OSError:return Nonefinally:- # Subprocess inherited the fd; we can drop our handle.- with contextlib.suppress(OSError):+ with contextlib.suppress(OSError): # subprocess inherited the fd; drop our handleos.close(fd)- return proc.pid-def format_context_for_log(ctx: Dict[str, Any]) -> str:- """Render a shutdown context dict as a single, scannable log line (parent cmdline is the key signal)."""+ """Render a shutdown context dict as a single, scannable log line (parent cmdline is the key+ signal).+ """parent = ctx.get("parent") or {}- load = ctx.get("loadavg_1m")- load_str = f"{load:.2f}" if isinstance(load, (int, float)) else "?"+ load_str = f"{load:.2f}" if isinstance(load := ctx.get("loadavg_1m"), (int, float)) else "?"extras: List[str] = []if ctx.get("takeover_marker") is not None:- extras.append(f"takeover_marker_present={'self' if ctx.get('takeover_marker_for_self') else 'other'}")+ extras.append(+ f"takeover_marker_present={'self' if ctx.get('takeover_marker_for_self') else 'other'}"+ )if ctx.get("planned_stop_marker") is not None:extras.append("planned_stop_marker_present=yes")if ctx.get("tracer_pid"):@@ -226,31 +207,25 @@ def context_as_json(ctx: Dict[str, Any]) -> str:def check_systemd_timing_alignment(drain_timeout: float, cron_drain_timeout: float = DEFAULT_GATEWAY_CRON_DRAIN_TIMEOUT) -> Optional[Dict[str, Any]]:- """At startup, sanity-check that systemd's TimeoutStopSec covers stop.-- A stale unit file (upgraded without re-running ``hermes setup``) can have- ``TimeoutStopSec`` below the stop budget, so systemd SIGKILLs the cgroup mid-drain- (a phantom ``code=killed status=9`` in the journal). ``None`` when aligned OR- undeterminable (not under systemd, no ``systemctl``); otherwise a dict with- ``timeout_stop_sec``/``drain_timeout``/``expected_min``/``mismatch``.+ """At startup, sanity-check that systemd's TimeoutStopSec covers stop. A stale unit file+ (upgraded without re-running ``hermes setup``) can have ``TimeoutStopSec`` below the stop+ budget, so systemd SIGKILLs the cgroup mid-drain (a phantom ``code=killed status=9`` in the+ journal). ``None`` when aligned OR undeterminable (not under systemd, no ``systemctl``);+ otherwise a dict with ``timeout_stop_sec``/``drain_timeout``/``expected_min``/``mismatch``."""if not os.environ.get("INVOCATION_ID"):return None # Not running under systemd (or at least not directly)-# /proc/self/cgroup: "0::/user.slice/.../hermes-gateway.service"unit_name: Optional[str] = None- try:- with open("/proc/self/cgroup", encoding="utf-8") as fh:- for line in fh:- unit_name = next((p for p in reversed(line.strip().split("/")) if p.endswith(".service")), None)- if unit_name:- break- except OSError:- pass- timeout_us = _systemd_timeout_stop_us(unit_name) if unit_name else None- if timeout_us is None:+ with contextlib.suppress(OSError), open("/proc/self/cgroup", encoding="utf-8") as fh:+ for line in fh:+ unit_name = next(+ (p for p in reversed(line.strip().split("/")) if p.endswith(".service")), None+ )+ if unit_name:+ break+ if (timeout_us := _systemd_timeout_stop_us(unit_name) if unit_name else None) is None:return None-timeout_stop_sec = timeout_us / 1_000_000.0expected = float(resolve_systemd_timeout_stop_sec(drain_timeout, cron_drain_timeout))return {@@ -264,7 +239,9 @@ def check_systemd_timing_alignment(def _systemd_timeout_stop_us(unit_name: str) -> Optional[int]:- """``TimeoutStopUSec`` of ``unit_name`` in microseconds; ``--user`` first (hermes' common case), then system."""+ """``TimeoutStopUSec`` of ``unit_name`` in microseconds; ``--user`` first (hermes' common case),+ then system.+ """for flag in (["--user"], []):try:result = subprocess.run(@@ -273,10 +250,8 @@ def _systemd_timeout_stop_us(unit_name: str) -> Optional[int]:)except (subprocess.TimeoutExpired, OSError):continue- if result.returncode != 0:- continue# Output: "TimeoutStopUSec=1min 30s" or "TimeoutStopUSec=90000000"- for line in result.stdout.splitlines():+ for line in result.stdout.splitlines() if result.returncode == 0 else ():if line.startswith("TimeoutStopUSec="):value = line.split("=", 1)[1].strip()timeout_us = int(value) if value.isdigit() else parse_systemd_duration_to_us(value)@@ -286,22 +261,16 @@ def _systemd_timeout_stop_us(unit_name: str) -> Optional[int]:def parse_systemd_duration_to_us(raw: str) -> Optional[int]:- """Parse 'TimeoutStopUSec=1min 30s' / '90s' style values to microseconds.-- Covers us, ms, s, min, h; a bare number is seconds. None on anything unexpected;- never raises. Public: also consumed by hermes_cli.gateway's restart-wait sizing.+ """Parse 'TimeoutStopUSec=1min 30s' / '90s' style values to microseconds. Covers us, ms, s, min,+ h; a bare number is seconds. None on anything unexpected; never raises. Public: also consumed by+ hermes_cli.gateway's restart-wait sizing."""if not raw:return None- units = {- "us": 1, "ms": 1_000, "s": 1_000_000, "sec": 1_000_000,- "min": 60_000_000, "h": 3_600_000_000, "hr": 3_600_000_000,- }- total_us = 0- token = digits = ""-- def _flush() -> bool:- """Fold the pending ``digits``/``token`` pair into ``total_us``."""+ units = {"us": 1, "ms": 1_000, "s": 1_000_000, "sec": 1_000_000,+ "min": 60_000_000, "h": 3_600_000_000, "hr": 3_600_000_000}+ total_us, token, digits = 0, "", ""+ def _flush() -> bool: # fold the pending digits/token pair into total_usnonlocal total_us, token, digitsmultiplier = units.get(token.lower()) if token else 1_000_000if multiplier is None or not digits:@@ -312,11 +281,9 @@ def parse_systemd_duration_to_us(raw: str) -> Optional[int]:return Falsedigits = token = ""return True-for ch in raw + " ":if ch.isdigit() or ch == ".":- # A digit after a unit ends the previous number- if token and not _flush():+ if token and not _flush(): # a digit after a unit ends the previous numberreturn Nonedigits += chelif ch.isalpha():diff --git a/gateway/shutdown_watchdog.py b/gateway/shutdown_watchdog.pyindex cfcbec7d8ea..3b20b6bbf5a 100644--- a/gateway/shutdown_watchdog.py+++ b/gateway/shutdown_watchdog.py@@ -1,13 +1,11 @@"""Out-of-loop shutdown and event-loop liveness backstops.-A frozen asyncio loop takes every asyncio-based recovery path down with it, and-launchd/systemd KeepAlive only restarts a *dead* process. Hence: (1) an OS-thread-shutdown watchdog that dumps stacks and ``os._exit``s past ``restart_drain_timeout-+ grace``; (2) a heartbeat file at ``<HERMES_HOME>/state/gateway.heartbeat`` so-supervisors can tell "process alive" from "loop frozen" (``gateway_state.json``-only rewrites on transitions/turns); (3) a lifetime thread watchdog that hard-exits-when the loop is too frozen to run its own callbacks; (4) a self-rescheduling floor-timer that keeps the selector timeout finite so async recovery tasks can resume.+A frozen asyncio loop takes every asyncio-based recovery path down with it, and launchd/systemd+KeepAlive only restarts a *dead* process. Hence: (1) an OS-thread shutdown watchdog that dumps+stacks and ``os._exit``s past ``restart_drain_timeout + grace``; (2) a heartbeat file at+``<HERMES_HOME>/state/gateway.heartbeat`` so supervisors can tell "process alive" from "loop+frozen"; (3) a lifetime thread watchdog that hard-exits when the loop is too frozen to run its+own callbacks; (4) a self-rescheduling floor timer that keeps the selector timeout finite."""from __future__ import annotations@@ -31,15 +29,14 @@ from utils import atomic_json_writelogger = logging.getLogger(__name__)-# Extra leash beyond ``agent.restart_drain_timeout`` so a slow-but-progressing-# drain is not cut short.+# Extra leash beyond ``agent.restart_drain_timeout`` so a slow-but-progressing drain survives.DEFAULT_SHUTDOWN_WATCHDOG_GRACE_S = 60.0DEFAULT_HEARTBEAT_INTERVAL_S = 30.0DEFAULT_LOOP_FLOOR_TIMER_INTERVAL_S = 5.0DEFAULT_LOOP_WATCHDOG_INTERVAL_S = 30.0DEFAULT_LOOP_WATCHDOG_TIMEOUT_S = 10.0-# 3 sustained misses (~90-120s of loop block) escalate; stays tight because the-# heartbeat write is off-loop. Slow loops tune gateway.loop_watchdog_* in config.yaml.+# 3 sustained misses (~90-120s of loop block) escalate; stays tight because the heartbeat+# write is off-loop. Slow loops tune gateway.loop_watchdog_* in config.yaml.DEFAULT_LOOP_WATCHDOG_MAX_STRIKES = 3_HEARTBEAT_RELATIVE = ("state", "gateway.heartbeat")_WATCHDOG_DUMP_RELATIVE = ("logs", "gateway-shutdown-watchdog.log")@@ -55,11 +52,8 @@ def _coerce_float(value: Any, default: float, floor: float = 0.0) -> float:class _LoopFloorTimerHandle:"""Cancelable owner for the currently scheduled selector floor timer."""-def __init__(self, loop: asyncio.AbstractEventLoop, interval: float):- self._loop = loop- self._interval = interval- self._cancelled = False+ self._loop, self._interval, self._cancelled = loop, interval, Falseself._timer: Optional[asyncio.TimerHandle] = Noneself._tick()@@ -75,20 +69,19 @@ class _LoopFloorTimerHandle:class _LoopLivenessWatchdogHandle:"""Small lifecycle handle for the daemon liveness thread."""-def __init__(self, stop_event: threading.Event, thread: threading.Thread):self._stop_event = stop_event- self.stop = stop_event.set- self.join = thread.join- self.is_alive = thread.is_alive+ self.stop, self.join, self.is_alive = stop_event.set, thread.join, thread.is_alivedef _arm_loop_floor_timer(loop: asyncio.AbstractEventLoop, interval: float = DEFAULT_LOOP_FLOOR_TIMER_INTERVAL_S) -> _LoopFloorTimerHandle:"""Keep at least one timer pending so selector waits remain bounded."""- resolved_interval = _coerce_float(interval, 0.0)- return _LoopFloorTimerHandle(loop, resolved_interval if resolved_interval > 0 else DEFAULT_LOOP_FLOOR_TIMER_INTERVAL_S)+ resolved = _coerce_float(interval, 0.0)+ return _LoopFloorTimerHandle(+ loop, resolved if resolved > 0 else DEFAULT_LOOP_FLOOR_TIMER_INTERVAL_S+ )def start_loop_liveness_watchdog(@@ -99,13 +92,11 @@ def start_loop_liveness_watchdog(max_strikes: int = DEFAULT_LOOP_WATCHDOG_MAX_STRIKES,exit_code: int = GATEWAY_SERVICE_RESTART_EXIT_CODE,) -> Optional[_LoopLivenessWatchdogHandle]:- """Start an out-of-loop watchdog that hard-exits after missed probes.-- The ``gateway.loop_watchdog: false`` opt-out is enforced by the caller- (``GatewayRunner._start_loop_liveness_guards``) so this stays config-agnostic.+ """Start an out-of-loop watchdog that hard-exits after missed probes. The+ ``gateway.loop_watchdog: false`` opt-out is enforced by the caller+ (``GatewayRunner._start_loop_liveness_guards``)."""stop_event = threading.Event()-def _wait_for_probe(probe_event: threading.Event) -> Optional[bool]:"""True/False = probe answered / timed out; None = stop requested mid-wait."""deadline = time.monotonic() + probe_timeout@@ -116,28 +107,25 @@ def start_loop_liveness_watchdog(if probe_event.wait(timeout=min(remaining, 0.05)):return Truereturn None-def _watchdog() -> None:strikes = 0while not stop_event.wait(timeout=probe_interval):probe_event = threading.Event()try:loop.call_soon_threadsafe(probe_event.set)- except RuntimeError:- # Normally closed loop: nothing left to backstop.+ except RuntimeError: # normally closed loop: nothing left to backstopreturnexcept Exception:logger.debug("Failed to schedule gateway loop liveness probe", exc_info=True)return-responded = _wait_for_probe(probe_event)if responded is None:returnif responded:strikes = 0continue- # Re-check stop_event between each irreversible step: a late stop()- # during the dump must still win over the hard exit.+ # Re-check stop_event between each irreversible step: a late stop() during the dump must+ # win.if stop_event.is_set():returnstrikes += 1@@ -147,9 +135,8 @@ def start_loop_liveness_watchdog(returnwith contextlib.suppress(Exception):logger.critical(- "Gateway event loop missed %d consecutive liveness probes; "- "dumping all thread stacks and exiting with code %d so the "- "service supervisor can restart it.",+ "Gateway event loop missed %d consecutive liveness probes; dumping all thread "+ "stacks and exiting with code %d so the service supervisor can restart it.",strikes,exit_code,)@@ -159,11 +146,10 @@ def start_loop_liveness_watchdog(logger.debug("Loop liveness faulthandler dump failed", exc_info=True)if stop_event.is_set():return- # Record the exit in the lifecycle sentinel so the next boot reports- # "watchdog hard-exit" rather than an unclean SIGKILL/OOM death.+ # Stamp the lifecycle sentinel so the next boot reports "watchdog hard-exit", not+ # SIGKILL/OOM._mark_exited_quietly(exit_code, "loop_liveness_watchdog")os._exit(exit_code)-thread = threading.Thread(target=_watchdog, daemon=True, name="gateway-loop-liveness-watchdog")try:thread.start()@@ -175,12 +161,9 @@ def start_loop_liveness_watchdog(def _mark_exited_quietly(exit_code: int, reason: str) -> None:"""Best-effort lifecycle-ledger stamp so the next boot names the watchdog, not SIGKILL/OOM."""- try:+ with contextlib.suppress(Exception):from gateway.lifecycle_ledger import mark_exited-mark_exited(exit_code, reason=reason)- except Exception:- passdef _process_hermes_home() -> Path:@@ -199,13 +182,15 @@ def get_loop_heartbeat_path(home: Optional[Path] = None) -> Path:def get_loop_tick_socket_path(home: Optional[Path] = None, pid: Optional[int] = None) -> Path:- """``<HERMES_HOME>/state/gateway.loop-tick.<pid>.sock``.-- PID-suffixed so a stale node from a previous process is never mistaken for this- gateway's witness. Served by the loop itself (``_tick_socket_handler``), so an- answer proves the loop dispatches — what the off-loop heartbeat can't.+ """``<HERMES_HOME>/state/gateway.loop-tick.<pid>.sock`` — PID-suffixed so a stale node from a+ dead process is never mistaken for this gateway's witness. Served by the loop itself+ (``_tick_socket_handler``), so an answer proves the loop dispatches — what the heartbeat can't."""- return _home(home) / "state" / f"gateway.loop-tick.{int(pid if pid is not None else os.getpid())}.sock"+ return (+ _home(home)+ / "state"+ / f"gateway.loop-tick.{int(pid if pid is not None else os.getpid())}.sock"+ )def get_shutdown_watchdog_dump_path(home: Optional[Path] = None) -> Path:@@ -214,31 +199,23 @@ def get_shutdown_watchdog_dump_path(home: Optional[Path] = None) -> Path:def write_loop_heartbeat(- *,- pid: Optional[int] = None,- start_time: Optional[float] = None,- home: Optional[Path] = None,- extra: Optional[Dict[str, Any]] = None,+ *, pid: Optional[int] = None, start_time: Optional[float] = None,+ home: Optional[Path] = None, extra: Optional[Dict[str, Any]] = None,) -> Path:- """Atomically rewrite the loop-liveness heartbeat file. Never raises.-- ``start_time`` (process start, epoch seconds) lets supervisors detect PID reuse.- """+ """Atomically rewrite the loop-liveness heartbeat file; never raises.+ ``start_time`` (process start, epoch seconds) lets supervisors detect PID reuse."""path = get_loop_heartbeat_path(home)payload: Dict[str, Any] = {"pid": int(pid if pid is not None else os.getpid()),- "updated_at": datetime.now(timezone.utc).isoformat(),- "monotonic": time.monotonic(),+ "updated_at": datetime.now(timezone.utc).isoformat(), "monotonic": time.monotonic(),}if start_time is not None:payload["start_time"] = float(start_time)- # Cheap memory sample (RSS + MemAvailable + swap): after an unclean death the- # last heartbeat is the closest surviving record of memory pressure.+ # Cheap memory sample: after an unclean death the last heartbeat is the closest record of memory+ # pressure.with contextlib.suppress(Exception):from gateway.lifecycle_ledger import sample_memory-- mem = sample_memory()- if mem:+ if mem := sample_memory():payload["mem"] = memif extra:payload.update(extra)@@ -250,31 +227,25 @@ def write_loop_heartbeat(def resolve_shutdown_watchdog_delay(- drain_timeout: float,- *,- grace_s: float = DEFAULT_SHUTDOWN_WATCHDOG_GRACE_S,-) -> float:+ drain_timeout: float, *, grace_s: float = DEFAULT_SHUTDOWN_WATCHDOG_GRACE_S) -> float:"""Return the wall-clock leash for the shutdown watchdog thread."""- return _coerce_float(drain_timeout, 0.0) + _coerce_float(grace_s, DEFAULT_SHUTDOWN_WATCHDOG_GRACE_S)+ return _coerce_float(drain_timeout, 0.0) + _coerce_float(+ grace_s, DEFAULT_SHUTDOWN_WATCHDOG_GRACE_S+ )-def _write_watchdog_dump(dump_path: Path, *, delay_s: float, snapshot: Optional[Dict[str, Any]]) -> None:+def _write_watchdog_dump(+ dump_path: Path, *, delay_s: float, snapshot: Optional[Dict[str, Any]]+) -> None:"""Best-effort faulthandler + metadata dump before hard-exit."""try:dump_path.parent.mkdir(parents=True, exist_ok=True)except OSError:return-- header = {- "event": "shutdown_watchdog_fired",- "pid": os.getpid(),- "delay_s": delay_s,- "fired_at": datetime.now(timezone.utc).isoformat(),- "snapshot": snapshot or {},- }+ header = {"event": "shutdown_watchdog_fired", "pid": os.getpid(), "delay_s": delay_s,+ "fired_at": datetime.now(timezone.utc).isoformat(), "snapshot": snapshot or {}}with contextlib.suppress(Exception), open(dump_path, "a", encoding="utf-8") as fh:- fh.write(json.dumps(header, default=str) + "\n")- fh.write("--- faulthandler dump (all threads) ---\n")+ fh.write(json.dumps(header, default=str) + "\n--- faulthandler dump (all threads) ---\n")fh.flush()try:faulthandler.dump_traceback(file=fh, all_threads=True)@@ -282,81 +253,59 @@ def _write_watchdog_dump(dump_path: Path, *, delay_s: float, snapshot: Optional[fh.write("(faulthandler.dump_traceback failed)\n")fh.write("--- end dump ---\n")fh.flush()-# Also to stderr so journald/launchd capture it even if the disk is wedged.with contextlib.suppress(Exception):- sys.stderr.write(- f"Gateway shutdown watchdog fired after {delay_s:.0f}s "- f"(pid={os.getpid()}); dumping all thread stacks.\n"- )+ sys.stderr.write(f"Gateway shutdown watchdog fired after {delay_s:.0f}s "+ f"(pid={os.getpid()}); dumping all thread stacks.\n")sys.stderr.flush()faulthandler.dump_traceback(all_threads=True)def arm_shutdown_watchdog(- delay_s: float,- *,- done_event: Optional[threading.Event] = None,- snapshot_fn: Optional[Callable[[], Dict[str, Any]]] = None,- exit_code: int = 1,- dump_path: Optional[Path] = None,- name: str = "gateway-shutdown-watchdog",+ delay_s: float, *, done_event: Optional[threading.Event] = None,+ snapshot_fn: Optional[Callable[[], Dict[str, Any]]] = None, exit_code: int = 1,+ dump_path: Optional[Path] = None, name: str = "gateway-shutdown-watchdog",) -> threading.Event:"""Arm a daemon-thread hard-exit backstop for a wedged shutdown path.-- Exits quietly if ``done_event`` is set within ``delay_s``, else dumps diagnostics- and ``os._exit(exit_code)``. Never raises; returns ``done_event`` for disarming.- """+ Exits quietly if ``done_event`` is set within ``delay_s``, else dumps diagnostics and+ ``os._exit(exit_code)``. Never raises; returns ``done_event`` for disarming."""done = done_event if done_event is not None else threading.Event()delay = _coerce_float(delay_s, DEFAULT_SHUTDOWN_WATCHDOG_GRACE_S)if delay <= 0:return done-def _watchdog() -> None:- # Chunked wait so a late disarm is observed within ~1s.- deadline = time.monotonic() + delay+ deadline = time.monotonic() + delay # chunked wait so a late disarm is observed within ~1swhile time.monotonic() < deadline:if done.wait(timeout=min(deadline - time.monotonic(), 1.0)):returnif done.is_set():return-snapshot: Optional[Dict[str, Any]] = Noneif snapshot_fn is not None:try:snapshot = snapshot_fn()except Exception as exc:snapshot = {"snapshot_error": repr(exc)}-target = dump_path if dump_path is not None else get_shutdown_watchdog_dump_path()_write_watchdog_dump(target, delay_s=delay, snapshot=snapshot)-with contextlib.suppress(Exception):- logger.critical(- "Shutdown watchdog fired after %.0fs — forcing process exit "- "(asyncio drain path appears wedged; see %s)",- delay,- target,- )-+ logger.critical("Shutdown watchdog fired after %.0fs — forcing process exit "+ "(asyncio drain path appears wedged; see %s)", delay, target)for stream in (sys.stdout, sys.stderr):with contextlib.suppress(Exception):stream.flush()- # Mirror _exit_after_graceful_shutdown: release PID file + runtime lock- # BEFORE the log drain (locks must never be stranded), then drain the async- # log queue so logger.critical reaches the file before os._exit skips atexit.+ # Mirror _exit_after_graceful_shutdown: release PID file + runtime lock BEFORE the log drain+ # (locks must never be stranded), then drain the async log queue so logger.critical+ # reaches the file before os._exit skips atexit.with contextlib.suppress(Exception):from gateway.status import remove_pid_file, release_gateway_runtime_lock-remove_pid_file()release_gateway_runtime_lock()with contextlib.suppress(Exception):from hermes_logging import drain_log_queue-drain_log_queue(timeout=1.0)_mark_exited_quietly(exit_code, "shutdown_watchdog")os._exit(exit_code)-try:threading.Thread(target=_watchdog, daemon=True, name=name).start()except Exception:@@ -365,11 +314,9 @@ def arm_shutdown_watchdog(async def _tick_socket_handler(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:- """Answer a liveness ping with one byte. Never raises.-- Runs on the gateway loop, so a reply witnesses loop schedulability; the write is- a socket-buffer copy (no fsync), immune to the stalls that age the heartbeat.- """+ """Answer a liveness ping with one byte; never raises. Runs on the gateway loop, so a reply+ witnesses loop schedulability; the write is a socket-buffer copy (no fsync), immune to the+ stalls that age the heartbeat."""with contextlib.suppress(Exception):writer.write(b"1")await writer.drain()@@ -379,17 +326,15 @@ async def _tick_socket_handler(reader: asyncio.StreamReader, writer: asyncio.Strdef _sweep_stale_tick_sockets(own_path: Path) -> None:"""Unlink loop-tick socket nodes left by dead PIDs (POSIX only; never raises).-- create_unix_server removes a leftover node at OUR path (os._exit / SIGKILL skip- the finally-unlink) but not SIBLING nodes from other dead PIDs. os.kill(pid, 0)- is a liveness probe only on POSIX (Windows would TerminateProcess).- """+ create_unix_server removes a leftover node at OUR path (os._exit / SIGKILL skip the+ finally-unlink) but not SIBLING nodes from other dead PIDs. os.kill(pid, 0) is a liveness+ probe only on POSIX (Windows would TerminateProcess)."""try:- for stale in own_path.parent.glob("gateway.loop-tick.*.sock"):- if stale == own_path:- continue+ for stale in (p for p in own_path.parent.glob("gateway.loop-tick.*.sock") if p != own_path):try:- os.kill(int(stale.name.split(".")[-2]), 0) # windows-footgun: ok — POSIX-only caller+ os.kill(+ int(stale.name.split(".")[-2]), 0+ ) # windows-footgun: ok — POSIX-only callerexcept (ValueError, IndexError, OSError):stale.unlink(missing_ok=True)except Exception:@@ -397,71 +342,66 @@ def _sweep_stale_tick_sockets(own_path: Path) -> None:async def loop_heartbeat_forever(- *,- interval_s: float = DEFAULT_HEARTBEAT_INTERVAL_S,- start_time: Optional[float] = None,- home: Optional[Path] = None,- should_continue: Optional[Callable[[], bool]] = None,+ *, interval_s: float = DEFAULT_HEARTBEAT_INTERVAL_S, start_time: Optional[float] = None,+ home: Optional[Path] = None, should_continue: Optional[Callable[[], bool]] = None,) -> None:"""Rewrite the loop heartbeat file on a cadence until cancelled / gated off.- Runs on the gateway loop so a frozen loop lets the file age for monitors. The- write (``atomic_json_write`` -> ``os.fsync``) goes to a thread: inline, a stalled- filesystem blocked the loop inside its own heartbeat and the liveness watchdog- killed it (WSL2 fsync stalls p99 31s / max 112s vs a ~90-120s budget). The- thread write is *awaited*, never fire-and-forget: an unawaited task would keep- the file fresh while the loop was wedged, and one in-flight write at a time- keeps a long stall from queuing a thread per interval.-- Off-loop, file freshness alone no longer proves loop schedulability, so this- task also arms a loop-scheduling witness (``_tick_socket_handler``) and records- it as ``loop_tick_socket``. Probes must require the witness to agree with file- staleness before classifying WEDGED; see ``probe_gateway_loop_liveness``.+ Runs on the gateway loop so a frozen loop lets the file age for monitors. The write+ (``atomic_json_write`` -> ``os.fsync``) goes to a thread: inline, a stalled filesystem blocked+ the loop inside its own heartbeat and the liveness watchdog killed it (WSL2 fsync stalls p99 31s+ / max 112s vs a ~90-120s budget). The thread write is *awaited*, never fire-and-forget: an+ unawaited task would keep the file fresh while the loop was wedged, and one in-flight write at a+ time keeps a long stall from queuing a thread per interval. Off-loop, file freshness alone no+ longer proves loop schedulability, so this task also arms a loop-scheduling witness+ (``_tick_socket_handler``) recorded as ``loop_tick_socket``; probes must require the witness to+ agree before classifying WEDGED."""interval = _coerce_float(interval_s, DEFAULT_HEARTBEAT_INTERVAL_S, floor=1.0)-- # Arm the witness. Best-effort: a failed bind only disables it, and the payload- # flag makes probes classify UNKNOWN, never WEDGED (drain backstop stays). asyncio- # AF_UNIX is POSIX-only (ungated it raised AttributeError on native Windows), so- # non-POSIX binds TCP loopback on 127.0.0.1 and publishes ``loop_tick_tcp_port``.+ # Arm the witness. Best-effort: a failed bind only disables it, and the payload flag makes+ # probes classify UNKNOWN, never WEDGED (drain backstop stays). asyncio AF_UNIX is POSIX-only+ # (ungated it raised AttributeError on native Windows), so non-POSIX binds TCP loopback and+ # publishes ``loop_tick_tcp_port``.tick_server = tick_socket_path = tick_tcp_port = Nonetry:if os.name == "posix":tick_socket_path = get_loop_tick_socket_path(home)tick_socket_path.parent.mkdir(parents=True, exist_ok=True)_sweep_stale_tick_sockets(tick_socket_path)- tick_server = await asyncio.start_unix_server(_tick_socket_handler, path=str(tick_socket_path))+ tick_server = await asyncio.start_unix_server(+ _tick_socket_handler, path=str(tick_socket_path)+ )else:tick_server = await asyncio.start_server(_tick_socket_handler, host="127.0.0.1", port=0)for _s in tick_server.sockets or []:with contextlib.suppress(Exception):- _sname = _s.getsockname()- if isinstance(_sname, tuple) and len(_sname) >= 2:+ if isinstance(_sname := _s.getsockname(), tuple) and len(_sname) >= 2:tick_tcp_port = int(_sname[1])breakexcept Exception:- tick_server = None- tick_tcp_port = None+ tick_server = tick_tcp_port = Nonelogger.warning("Loop tick socket unavailable — liveness probes will have no ""loop-scheduling witness and will not escalate on a stale heartbeat",exc_info=True,)-async def _write_off_loop() -> None:- # write_loop_heartbeat never raises, so a failure here is an executor- # problem (shutdown, saturation) and must not kill the heartbeat task.+ # write_loop_heartbeat never raises, so a failure here is an executor problem and must not+ # kill the task.try:await asyncio.to_thread(- write_loop_heartbeat, start_time=start_time, home=home,- extra={"loop_tick_socket": tick_server is not None, "loop_tick_tcp_port": tick_tcp_port},+ write_loop_heartbeat,+ start_time=start_time,+ home=home,+ extra={+ "loop_tick_socket": tick_server is not None,+ "loop_tick_tcp_port": tick_tcp_port,+ },)except Exception:logger.debug("Loop heartbeat write failed off-loop", exc_info=True)-try:- # Immediate first write so monitors see a fresh file at once.- await _write_off_loop()+ await _write_off_loop() # immediate first write so monitors see a fresh file at oncewhile should_continue is None or should_continue():await asyncio.sleep(interval)if should_continue is not None and not should_continue():diff --git a/gateway/systemd_notify.py b/gateway/systemd_notify.pyindex 1fa71737b29..9cabb6d46ba 100644--- a/gateway/systemd_notify.py+++ b/gateway/systemd_notify.py@@ -7,11 +7,9 @@ import contextlibimport mathimport osimport socket-from typing import Optionaldef _notify_socket() -> str:- """``NOTIFY_SOCKET`` address, or "" when systemd did not configure one / no AF_UNIX."""address = os.environ.get("NOTIFY_SOCKET", "").strip()return address if address and hasattr(socket, "AF_UNIX") else ""@@ -19,17 +17,15 @@ def _notify_socket() -> str:def notify(message: str) -> bool:"""Send one nonblocking sd_notify datagram when systemd configured it.- Failures are non-fatal: a missing socket or an older platform must never- prevent the gateway from starting.+ Failures are non-fatal: a missing socket or an older platform must never prevent the gateway+ from starting."""- address = _notify_socket()- if not address or not isinstance(message, str) or not message:+ if not (address := _notify_socket()) or not isinstance(message, str) or not message:return Falsetry:payload = message.encode("utf-8")with socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) as sender:- # A full receiver buffer must not stall the gateway event loop.- sender.setblocking(False)+ sender.setblocking(False) # a full receiver buffer must not stall the event loop# systemd's ``@abstract`` notation -> Python's leading-NUL address form.sender.connect("\0" + address[1:] if address.startswith("@") else address)sender.send(payload)@@ -38,8 +34,7 @@ def notify(message: str) -> bool:return False-def watchdog_interval_seconds() -> Optional[float]:- """Return systemd's configured watchdog interval in seconds."""+def watchdog_interval_seconds() -> float | None:raw = os.environ.get("WATCHDOG_USEC", "").strip() if _notify_socket() else ""try:interval = float(raw) / 1_000_000.0@@ -51,26 +46,18 @@ def watchdog_interval_seconds() -> Optional[float]:class SystemdWatchdog:"""Feed systemd while the asyncio event loop continues to make progress."""- def __init__(self, *, config_enabled: bool = True, lag_tolerance_seconds: Optional[float] = None) -> None:+ def __init__(+ self, *, config_enabled: bool = True, lag_tolerance_seconds: float | None = None+ ) -> None:self._config_enabled = bool(config_enabled)self.interval_seconds = watchdog_interval_seconds()self._lag_tolerance_seconds = lag_tolerance_seconds- self._task: Optional[asyncio.Task[None]] = None- self._unhealthy = False- self._stopping = False- self._stopping_notified = False+ self._task: asyncio.Task[None] | None = None+ self._unhealthy = self._stopping = self._stopping_notified = False- @property- def enabled(self) -> bool:- return self._config_enabled and self.interval_seconds is not None-- @property- def unhealthy(self) -> bool:- return self._unhealthy-- @property- def task(self) -> Optional[asyncio.Task[None]]:- return self._task+ enabled = property(lambda self: self._config_enabled and self.interval_seconds is not None)+ unhealthy = property(lambda self: self._unhealthy)+ task = property(lambda self: self._task)def _lag_tolerance(self) -> float:default = max(0.1, (self.interval_seconds or 0.0) * 0.25)@@ -81,7 +68,6 @@ class SystemdWatchdog:return max(0.0, value) if math.isfinite(value) else defaultdef start(self) -> bool:- """Start the loop-progress sampler when systemd watchdog is enabled."""if not self.enabled:return Falseif self._task is not None and not self._task.done():@@ -95,11 +81,8 @@ class SystemdWatchdog:return Truedef ready(self, status: str = "Gateway running") -> bool:- """Tell systemd that startup completed and the gateway is ready."""- if not self.enabled:- return Falsesafe_status = str(status or "Gateway running").replace("\n", " ")- return notify(f"READY=1\nSTATUS={safe_status}")+ return self.enabled and notify(f"READY=1\nSTATUS={safe_status}")def record_tick(self, *, scheduled_at: float, now: float) -> bool:"""Feed systemd only when the event loop woke within its lag budget."""@@ -128,9 +111,9 @@ class SystemdWatchdog:now = loop.time()if not self.record_tick(scheduled_at=scheduled_at, now=now):return- scheduled_at += cadence- if scheduled_at < now:- scheduled_at = now + cadence+ scheduled_at = (+ scheduled_at + cadence if scheduled_at + cadence >= now else now + cadence+ )async def stop(self) -> None:"""Stop feeding systemd and emit ``STOPPING=1`` at most once."""