Skip to content

The agent that grows with you

fix(gateway): persist runtime status off event loop

Philip Kirkbrided5479495b879
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py
index 51e3c0c1951..8be693f44f3 100644
--- a/gateway/platforms/base.py
+++ b/gateway/platforms/base.py
@@ -2098,14 +2098,13 @@ class BasePlatformAdapter(ABC):
self._write_runtime_status_safe("fatal", platform_state="fatal", error_code=code, error_message=message)
def _write_runtime_status_safe(self, context: str, **kwargs) -> None:
- """Write runtime status; log first failure per context at warning, rest at debug
- (failures — permissions, ENOSPC — must neither be silent nor spam reconnect loops)."""
+ """Publish runtime status; log preparation failures without disrupting the adapter."""
try:
- from gateway.status import write_runtime_status
+ from gateway.status import publish_runtime_status
# Multiplexed adapters share the status file; the runner stamps
# ``<profile>:<platform>``.
platform_key = getattr(self, "_runtime_status_platform_key", None) or self.platform.value
- write_runtime_status(platform=platform_key, **kwargs)
+ publish_runtime_status(platform=platform_key, **kwargs)
except Exception as exc:
logged = _lazy_attr(self, "_status_write_logged", set) # object.__new__ in tests
first = (self.platform.value, context) not in logged
diff --git a/gateway/run.py b/gateway/run.py
index 8f8007d0f9a..6e12bd02022 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -3276,10 +3276,10 @@ _AUTO_RESET_CONTEXT_NOTES = {
def _write_runtime_status_quiet(**fields: Any) -> None:
- """Best-effort ``gateway_state.json`` write; status persistence must never abort the caller."""
+ """Best-effort status publication; persistence must never abort or block the caller."""
try:
- from gateway.status import write_runtime_status
- write_runtime_status(**fields)
+ from gateway.status import publish_runtime_status
+ publish_runtime_status(**fields)
except Exception:
pass
diff --git a/gateway/run_adapters.py b/gateway/run_adapters.py
index 6c34ca887ed..fb83d9771df 100644
--- a/gateway/run_adapters.py
+++ b/gateway/run_adapters.py
@@ -846,12 +846,12 @@ class GatewayAdapterLifecycleMixin:
from gateway.run import MultiplexConfigError, _multiplex_profile_homes
from gateway.run_profile_reconcile import profile_serve_signature
if not self._multiplex_on():
- # ``write_runtime_status`` re-stamps the previous writer's record in place, so a multiplexer's
+ # Runtime-status publication re-stamps the previous writer's record in place, so a multiplexer's
# ``served_profiles`` would outlive it into this single-profile run and `hermes -p X ...`
# would keep refusing (exit 78) / reporting "served" for profiles nobody serves.
with _log_suppressed(logging.DEBUG, "could not clear served_profiles", exc_info=True):
- from gateway.status import write_runtime_status
- write_runtime_status(served_profiles=[])
+ from gateway.status import publish_runtime_status
+ publish_runtime_status(served_profiles=[])
return 0
try:
from hermes_cli.profiles import get_active_profile_name
@@ -897,7 +897,7 @@ class GatewayAdapterLifecycleMixin:
"""Record the served set (eligible for routing/HTTP prefixes/cron/runtime scope — broader
than "has a connected adapter") for `hermes status`; seed per-profile PairingStores."""
with _log_suppressed(logging.DEBUG, "could not record served_profiles", exc_info=True):
- from gateway.status import write_runtime_status
+ from gateway.status import publish_runtime_status
from gateway.pairing import PairingStore
served = [active] + sorted(name for name, _home in profile_homes if name != active)
self._note_served_profiles(profile_homes)
@@ -906,7 +906,7 @@ class GatewayAdapterLifecycleMixin:
self.pairing_stores[name] = (
self.pairing_store if name == active else PairingStore(profile=name)
)
- write_runtime_status(served_profiles=served)
+ publish_runtime_status(served_profiles=served)
async def _load_secondary_profile_config(self, profile_name: str, profile_home: "Path"):
"""Hydrate + enter ``profile_home``'s scope once; return its gateway config. Raises
diff --git a/gateway/run_shutdown.py b/gateway/run_shutdown.py
index c9864765e99..ef8b1688739 100644
--- a/gateway/run_shutdown.py
+++ b/gateway/run_shutdown.py
@@ -1986,7 +1986,7 @@ class GatewayShutdownMixin:
_step("Shared SessionDB close error", _close_shared)
logger.info("Shutdown phase: SessionDB close done at +%.2fs", ctx.elapsed())
- def _stop_persist_exit_state(self, ctx: "GatewayShutdownMixin._StopContext") -> None:
+ async def _stop_persist_exit_state(self, ctx: "GatewayShutdownMixin._StopContext") -> None:
"""PID/lock release, clean-shutdown marker, restart markers, terminal runtime status."""
from gateway.run import _hermes_home, _planned_restart_notification_path, _shutdown_gateway_health_export
from utils import atomic_json_write
@@ -2032,6 +2032,12 @@ class GatewayShutdownMixin:
self._update_runtime_status("running", self._exit_reason)
else:
self._update_runtime_status("stopped", self._exit_reason)
+ try:
+ from gateway.status import flush_runtime_status_async
+ if not await flush_runtime_status_async(timeout=2.0):
+ logger.warning("Timed out flushing terminal gateway runtime status")
+ except Exception:
+ logger.debug("Failed to flush terminal gateway runtime status", exc_info=True)
_shutdown_gateway_health_export(self)
logger.info("Gateway stopped (total teardown %.2fs)", ctx.elapsed())
@@ -2086,7 +2092,7 @@ class GatewayShutdownMixin:
await GatewayRunner._stop_finalize_agents_and_adapters(self, ctx)
await GatewayRunner._stop_release_runtime_state(self, ctx)
GatewayRunner._stop_quiesce_and_close_session_dbs(self, timeout, ctx)
- GatewayRunner._stop_persist_exit_state(self, ctx)
+ await GatewayRunner._stop_persist_exit_state(self, ctx)
finally:
_watchdog_done.set()
diff --git a/gateway/run_startup.py b/gateway/run_startup.py
index 46c0407251b..f5e013d7036 100644
--- a/gateway/run_startup.py
+++ b/gateway/run_startup.py
@@ -788,9 +788,8 @@ class GatewayStartupMixin:
_sigusr2, file=self._open_faulthandler_log(), all_threads=True, chain=False,
)
- def _start_log_startup_environment(self) -> None:
+ async def _start_log_startup_environment(self) -> None:
"""Bind the gateway loop, disarm the startup watchdog, and log the startup environment."""
- from gateway.run import _write_runtime_status_quiet
try:
self._gateway_loop = asyncio.get_running_loop()
except RuntimeError:
@@ -832,7 +831,20 @@ class GatewayStartupMixin:
_profile = get_active_profile_name() # launch profile, pre-identity (boot log)
if _profile and _profile != "default":
logger.info("Active profile: %s", _profile)
- _write_runtime_status_quiet(gateway_state="starting", exit_reason=None, clear_profile_platforms=True)
+ try:
+ from gateway.status import write_runtime_status
+ persisted = await asyncio.to_thread(
+ write_runtime_status,
+ gateway_state="starting",
+ exit_reason=None,
+ clear_profile_platforms=True,
+ _reload_existing=True,
+ _wait_timeout=2.0,
+ )
+ if not persisted:
+ logger.warning("Timed out persisting initial gateway runtime status")
+ except Exception:
+ logger.debug("Initial gateway runtime-status write failed", exc_info=True)
with _log_suppressed(logging.DEBUG, "gateway health OTLP export startup failed", exc_info=True):
from hermes_cli.config import load_config
from agent.monitoring.gateway_health_export import start_gateway_health_export
@@ -1436,14 +1448,26 @@ class GatewayStartupMixin:
# marker (prior-instantiation markers are ignored via epoch).
self._spawn_supervised(self._drain_control_watcher, "drain_control_watcher")
+ @staticmethod
+ async def _start_flush_runtime_status() -> None:
+ """Bound startup on the latest diagnostic snapshot, never on filesystem health."""
+ try:
+ from gateway.status import flush_runtime_status_async
+ if not await flush_runtime_status_async(timeout=2.0):
+ logger.warning("Timed out flushing final startup runtime status")
+ except Exception:
+ logger.debug("Final startup runtime-status flush failed", exc_info=True)
+
async def start(self) -> bool:
"""Start the gateway and all configured platform adapters."""
logger.info("Starting Hermes Gateway...")
self._start_install_faulthandler()
- self._start_log_startup_environment()
+ await self._start_log_startup_environment()
if await self._abort_startup_if_shutdown_requested():
+ await self._start_flush_runtime_status()
return True
if self._start_check_access_policy():
+ await self._start_flush_runtime_status()
return True
await self._start_recover_previous_run()
# The gateway is a boot owner of the Nous free tier, beside `cmd_chat` and `hermes serve`: every
@@ -1467,27 +1491,34 @@ class GatewayStartupMixin:
_aborted, enabled_platform_count, _multiplex_skipped_platforms, _pending_connects
) = await self._start_prefilter_platforms()
if _aborted:
+ await self._start_flush_runtime_status()
return True
if await self._abort_startup_if_shutdown_requested():
+ await self._start_flush_runtime_status()
return True
_raw = await self._start_connect_pending(_pending_connects)
if _raw is None:
+ await self._start_flush_runtime_status()
return True
connected_count = await self._start_aggregate_connect_results(
_raw, startup_retryable_errors, startup_nonretryable_errors
)
if await self._abort_startup_if_shutdown_requested():
+ await self._start_flush_runtime_status()
return True
_aborted, connected_count = await self._start_secondary_profiles(
connected_count, _multiplex_skipped_platforms
)
if _aborted:
+ await self._start_flush_runtime_status()
return True
if self._start_handle_no_connections(
connected_count, enabled_platform_count, startup_retryable_errors, startup_nonretryable_errors
):
+ await self._start_flush_runtime_status()
return True
if await self._abort_startup_if_shutdown_requested():
+ await self._start_flush_runtime_status()
return True
self.delivery_router.adapters = self.adapters
self._wire_teams_pipeline_runtime()
@@ -1499,6 +1530,7 @@ class GatewayStartupMixin:
self._update_runtime_status(self._serving_state())
await self._start_finish_wiring(connected_count)
self._start_spawn_background_watchers()
+ await self._start_flush_runtime_status()
logger.info("Press Ctrl+C to stop")
return True
diff --git a/gateway/session_db_recovery.py b/gateway/session_db_recovery.py
index 2c001842234..46e315a03bf 100644
--- a/gateway/session_db_recovery.py
+++ b/gateway/session_db_recovery.py
@@ -37,8 +37,8 @@ def _publish_health(source: _HealthSource, path: Path, state: str) -> None:
all_states = {value for item in _health_states.values() for value in item.values()}
aggregate = next((s for s in ("retrying", "unavailable") if s in all_states), "ok")
try:
- from gateway.status import write_runtime_status
- write_runtime_status(session_store={"status": aggregate})
+ from gateway.status import publish_runtime_status
+ publish_runtime_status(session_store={"status": aggregate})
except Exception:
pass # Runtime health is diagnostic only; persistence must not depend on it.
diff --git a/gateway/shutdown_watchdog.py b/gateway/shutdown_watchdog.py
index 87fcc19e7c8..10016ad81e5 100644
--- a/gateway/shutdown_watchdog.py
+++ b/gateway/shutdown_watchdog.py
@@ -159,7 +159,8 @@ def _mark_exited_quietly(exit_code: int, reason: str) -> None:
# Only the supervisor-restart code asserts a restart; other codes leave the recorded
# operator intent (a restart-drain that wedged is still a requested restart) untouched.
restart = {"restart_requested": True} if exit_code == GATEWAY_SERVICE_RESTART_EXIT_CODE else {}
- write_runtime_status(gateway_state="degraded", exit_reason=reason, **restart)
+ write_runtime_status(
+ gateway_state="degraded", exit_reason=reason, _wait_timeout=0.25, **restart)
def _process_hermes_home() -> Path:
diff --git a/gateway/status.py b/gateway/status.py
index 9419b6bf606..ed46f1845eb 100644
--- a/gateway/status.py
+++ b/gateway/status.py
@@ -1,6 +1,7 @@
"""Gateway runtime status helpers: PID/lock/marker files under ``{HERMES_HOME}`` (one set per
home/profile) that tell whether the gateway daemon is running."""
+import asyncio
import contextlib
import copy
import hashlib
@@ -46,6 +47,142 @@ _gateway_running_pid_cache: dict[tuple[str, bool, bool], tuple[float, tuple, Opt
logger = logging.getLogger(__name__)
+class _RuntimeStatusWriter:
+ """Persist the latest complete status snapshot on one daemon thread.
+
+ Runtime status is diagnostic state, not an event log. While one write is
+ blocked in filesystem I/O, newer submissions replace the single pending
+ snapshot. This bounds memory and keeps every status producer off asyncio.
+ """
+
+ def __init__(self, write_fn: Optional[Callable[[Path, dict[str, Any]], None]] = None):
+ self._write_fn = write_fn
+ self._condition = threading.Condition()
+ self._pending: Optional[tuple[int, Path, dict[str, Any]]] = None
+ self._writing_generation = 0
+ self._submitted_generation = 0
+ self._completed_generation = 0
+ self._successful_generation = 0
+ self._last_error: Optional[BaseException] = None
+ self._failure_logged = False
+ self._thread: Optional[threading.Thread] = None
+
+ def submit(self, path: Path, payload: dict[str, Any]) -> int:
+ with self._condition:
+ self._submitted_generation += 1
+ generation = self._submitted_generation
+ self._pending = (generation, path, copy.deepcopy(payload))
+ if self._thread is None or not self._thread.is_alive():
+ self._thread = threading.Thread(
+ target=self._run, daemon=True, name="gateway-runtime-status-writer")
+ self._thread.start()
+ self._condition.notify_all()
+ return generation
+
+ def wait(self, generation: int, timeout: Optional[float] = None) -> bool:
+ deadline = None if timeout is None else time.monotonic() + max(timeout, 0.0)
+ with self._condition:
+ while self._successful_generation < generation:
+ no_more_work = (
+ self._completed_generation >= generation
+ and self._writing_generation == 0
+ and self._pending is None
+ )
+ if no_more_work:
+ if timeout is None and self._last_error is not None:
+ raise self._last_error
+ return False
+ if deadline is None:
+ self._condition.wait()
+ continue
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ return False
+ self._condition.wait(timeout=remaining)
+ return True
+
+ def flush(self, timeout: float = 2.0) -> bool:
+ with self._condition:
+ generation = self._submitted_generation
+ return generation == 0 or self.wait(generation, timeout=timeout)
+
+ def _run(self) -> None:
+ while True:
+ with self._condition:
+ while self._pending is None:
+ self._condition.wait()
+ generation, path, payload = self._pending
+ self._pending = None
+ self._writing_generation = generation
+ error: Optional[BaseException] = None
+ try:
+ (self._write_fn or _write_json_file)(path, payload)
+ except BaseException as exc:
+ error = exc
+ with self._condition:
+ self._writing_generation = 0
+ self._completed_generation = max(self._completed_generation, generation)
+ if error is None:
+ self._successful_generation = max(self._successful_generation, generation)
+ self._last_error = None
+ else:
+ self._last_error = error
+ self._condition.notify_all()
+ if error is None:
+ if self._failure_logged:
+ logger.info("Gateway runtime-status persistence recovered")
+ self._failure_logged = False
+ elif not self._failure_logged:
+ logger.warning(
+ "Failed to persist gateway runtime status; later updates will retry: %s", error)
+ self._failure_logged = True
+ else:
+ logger.debug("Failed to persist gateway runtime status: %s", error)
+
+
+_runtime_status_state_lock = threading.RLock()
+_runtime_status_state_path: Optional[Path] = None
+_runtime_status_state: Optional[dict[str, Any]] = None
+_runtime_status_writer_lock = threading.Lock()
+_runtime_status_writer: Optional[_RuntimeStatusWriter] = None
+
+
+def _get_runtime_status_writer() -> _RuntimeStatusWriter:
+ global _runtime_status_writer
+ if _runtime_status_writer is not None:
+ return _runtime_status_writer
+ with _runtime_status_writer_lock:
+ if _runtime_status_writer is None:
+ _runtime_status_writer = _RuntimeStatusWriter()
+ return _runtime_status_writer
+
+
+def flush_runtime_status(timeout: float = 2.0) -> bool:
+ """Wait boundedly for all runtime-status updates submitted so far."""
+ writer = _runtime_status_writer
+ return True if writer is None else writer.flush(timeout=timeout)
+
+
+async def flush_runtime_status_async(timeout: float = 2.0) -> bool:
+ """Await the current writer generation without blocking the event loop."""
+ writer = _runtime_status_writer
+ if writer is None:
+ return True
+ with writer._condition:
+ generation = writer._submitted_generation
+ if generation == 0:
+ return True
+ loop = asyncio.get_running_loop()
+ deadline = loop.time() + max(timeout, 0.0)
+ while True:
+ if writer.wait(generation, timeout=0.0):
+ return True
+ remaining = deadline - loop.time()
+ if remaining <= 0:
+ return False
+ await asyncio.sleep(min(0.02, remaining))
+
+
class StormInfo(NamedTuple):
"""Respawn-storm check result: start count, window, and backoff to sleep."""
@@ -827,7 +964,7 @@ def _coerce_session_store(session_store: Any) -> dict[str, str]:
return {"status": state if state in {"ok", "unavailable", "retrying"} else "unknown"}
-def write_runtime_status(
+def _prepare_runtime_status_update(
*, gateway_state: Any = _UNSET, exit_reason: Any = _UNSET, restart_requested: Any = _UNSET,
active_agents: Any = _UNSET, active_work: Any = _UNSET, platform: Any = _UNSET, platform_state: Any = _UNSET,
error_code: Any = _UNSET, error_message: Any = _UNSET, needs_attention: Any = _UNSET,
@@ -835,74 +972,132 @@ def write_runtime_status(
multiplex_standalone_reason: Any = _UNSET,
ingress_url: Any = _UNSET, listener_base: Any = _UNSET, clear_profile_platforms: bool = False,
drop_profile_platforms: Optional[str] = None,
-) -> None:
- """Persist gateway runtime health information for diagnostics/status. ``drop_profile_platforms``
- removes one deleted profile's ``<profile>:<platform>`` entries (hot unroute)."""
+ load_existing: bool = True, reload_existing: bool = False,
+) -> tuple[Path, dict[str, Any], dict[str, Any]]:
+ """Merge one update into the process-wide canonical status snapshot."""
+ global _runtime_status_state_path, _runtime_status_state
path = _get_runtime_status_path()
- payload = _read_json_file(path) or _build_runtime_status_record()
- previous_payload = copy.deepcopy(payload)
- current_record = _build_pid_record()
- payload.setdefault("platforms", {})
- if clear_profile_platforms or drop_profile_platforms:
- # Secondary-profile entries are keyed ``<profile>:<platform>``. A fresh process must not
- # inherit them or /api/status stays degraded until every old adapter re-emits.
- platforms = payload["platforms"] if isinstance(payload["platforms"], dict) else {}
- drop_prefix = f"{drop_profile_platforms}:" if drop_profile_platforms else None
- payload["platforms"] = {
- k: v for k, v in platforms.items()
- if not isinstance(k, str) or ":" not in k or (drop_prefix is not None and not k.startswith(drop_prefix))
- }
- # Re-stamp identity + code fields on every write: the file can outlive its creator and the
- # top-level record must describe the CURRENT writer.
- payload.update({key: current_record[key] for key in ("kind", "pid", "argv", "start_time")})
- payload["updated_at"] = _utc_now_iso()
- payload.update(_get_code_identity_fields())
- _apply_set_fields(payload, (
- ("gateway_state", gateway_state, None), ("exit_reason", exit_reason, None),
- ("restart_requested", restart_requested, bool),
- ("active_agents", active_agents, parse_active_agents),
- # Named in-flight units (see GatewayShutdownMixin._describe_active_work); None clears.
- ("active_work", active_work, lambda v: list(v) if v else None),
- # Multiplexed profiles; absent/empty for a single-profile gateway.
- ("served_profiles", served_profiles, lambda v: list(v or [])),
- # Why an unset-default (multiplex on) gateway is serving one profile; None clears it.
- ("multiplex_standalone_reason", multiplex_standalone_reason, lambda v: str(v) if v else None),
- ("session_store", session_store, _coerce_session_store),
- ))
- if platform is not _UNSET:
- platform_payload = payload["platforms"].get(platform, {})
- if platform_state == "connected":
- # Every writer that publishes ``connected`` (startup stamp, adapter ``_mark_connected``,
- # Telegram's in-place polling recovery) ends the retry episode; only the watcher's
- # reconnect path used to say so, and a restart after a NEEDS_ATTENTION escalation
- # carried the flag into a healthy record for weeks.
- needs_attention = False if needs_attention is _UNSET else needs_attention
- retrying_since = None if retrying_since is _UNSET else retrying_since
- _apply_set_fields(platform_payload, (
- ("state", platform_state, None), ("error_code", error_code, None),
- ("error_message", error_message, None),
- # Reconnect-loop escalation past the attention threshold: a signal for owners/fleet
- # monitoring, not a circuit breaker (retry never stops). Cleared on reconnect.
- ("needs_attention", needs_attention, bool),
- # ISO start of the current retry episode; None clears it.
- ("retrying_since", retrying_since, None),
- # Shared-listener secondaries: the /p/<profile>/ callback URL the vendor console must target.
- ("ingress_url", ingress_url, None),
- # Bound listener (``http://host:port``) of the default's api_server/webhook: a served
- # profile's mirror of that platform is reported off it (``<listener_base>/p/<profile>/...``).
- ("listener_base", listener_base, None),
+ with _runtime_status_state_lock:
+ if reload_existing or _runtime_status_state_path != path or _runtime_status_state is None:
+ _runtime_status_state_path = path
+ _runtime_status_state = (
+ (_read_json_file(path) if load_existing else None) or _build_runtime_status_record())
+ payload = copy.deepcopy(_runtime_status_state)
+ previous_payload = copy.deepcopy(payload)
+ current_record = _build_pid_record()
+ payload.setdefault("platforms", {})
+ if not isinstance(payload["platforms"], dict):
+ payload["platforms"] = {}
+ if clear_profile_platforms or drop_profile_platforms:
+ drop_prefix = f"{drop_profile_platforms}:" if drop_profile_platforms else None
+ payload["platforms"] = {
+ k: v for k, v in payload["platforms"].items()
+ if not isinstance(k, str) or ":" not in k
+ or (drop_prefix is not None and not k.startswith(drop_prefix))
+ }
+ payload.update({key: current_record[key] for key in ("kind", "pid", "argv", "start_time")})
+ payload["updated_at"] = _utc_now_iso()
+ payload.update(_get_code_identity_fields())
+ _apply_set_fields(payload, (
+ ("gateway_state", gateway_state, None), ("exit_reason", exit_reason, None),
+ ("restart_requested", restart_requested, bool),
+ ("active_agents", active_agents, parse_active_agents),
+ ("active_work", active_work, lambda v: list(v) if v else None),
+ ("served_profiles", served_profiles, lambda v: list(v or [])),
+ ("multiplex_standalone_reason", multiplex_standalone_reason, lambda v: str(v) if v else None),
+ ("session_store", session_store, _coerce_session_store),
))
- # Per-entry writer provenance: top-level pid/start_time only identify the most recent
- # writer; /api/status tells "live" from "preserved" by exact (pid, start_time) equality.
- platform_payload.update(updated_at=_utc_now_iso(), writer_pid=current_record["pid"],
- writer_start_time=current_record["start_time"])
- payload["platforms"][platform] = platform_payload
- _write_json_file(path, payload)
+ if platform is not _UNSET:
+ platform_payload = copy.deepcopy(payload["platforms"].get(platform, {}))
+ if not isinstance(platform_payload, dict):
+ platform_payload = {}
+ if platform_state == "connected":
+ needs_attention = False if needs_attention is _UNSET else needs_attention
+ retrying_since = None if retrying_since is _UNSET else retrying_since
+ _apply_set_fields(platform_payload, (
+ ("state", platform_state, None), ("error_code", error_code, None),
+ ("error_message", error_message, None),
+ ("needs_attention", needs_attention, bool),
+ ("retrying_since", retrying_since, None),
+ ("ingress_url", ingress_url, None),
+ ("listener_base", listener_base, None),
+ ))
+ platform_payload.update(
+ updated_at=_utc_now_iso(), writer_pid=current_record["pid"],
+ writer_start_time=current_record["start_time"])
+ payload["platforms"][platform] = platform_payload
+ _runtime_status_state = copy.deepcopy(payload)
+ return path, payload, previous_payload
+
+
+def _emit_runtime_status_transition(
+ previous_payload: dict[str, Any], payload: dict[str, Any]
+) -> None:
with contextlib.suppress(Exception):
from agent.monitoring.gateway_health import emit_runtime_status_transition
emit_runtime_status_transition(previous_payload, payload)
+def write_runtime_status(
+ *, gateway_state: Any = _UNSET, exit_reason: Any = _UNSET, restart_requested: Any = _UNSET,
+ active_agents: Any = _UNSET, active_work: Any = _UNSET, platform: Any = _UNSET, platform_state: Any = _UNSET,
+ error_code: Any = _UNSET, error_message: Any = _UNSET, needs_attention: Any = _UNSET,
+ retrying_since: Any = _UNSET, served_profiles: Any = _UNSET, session_store: Any = _UNSET,
+ multiplex_standalone_reason: Any = _UNSET,
+ ingress_url: Any = _UNSET, listener_base: Any = _UNSET, clear_profile_platforms: bool = False,
+ drop_profile_platforms: Optional[str] = None, _reload_existing: bool = False,
+ _wait_timeout: Optional[float] = None,
+) -> bool:
+ """Synchronously persist status for CLI callers and off-loop startup.
+
+ ``_wait_timeout`` bounds how long the caller waits for durable persistence.
+ A timed-out update remains queued for the single background writer.
+ """
+ with _runtime_status_state_lock:
+ path, payload, previous_payload = _prepare_runtime_status_update(
+ gateway_state=gateway_state, exit_reason=exit_reason,
+ restart_requested=restart_requested, active_agents=active_agents, active_work=active_work,
+ platform=platform, platform_state=platform_state, error_code=error_code,
+ error_message=error_message, needs_attention=needs_attention,
+ retrying_since=retrying_since, served_profiles=served_profiles,
+ session_store=session_store, multiplex_standalone_reason=multiplex_standalone_reason,
+ ingress_url=ingress_url, listener_base=listener_base,
+ clear_profile_platforms=clear_profile_platforms, drop_profile_platforms=drop_profile_platforms,
+ reload_existing=_reload_existing)
+ writer = _get_runtime_status_writer()
+ generation = writer.submit(path, payload)
+ persisted = writer.wait(generation, timeout=_wait_timeout)
+ if persisted:
+ _emit_runtime_status_transition(previous_payload, payload)
+ return persisted
+
+
+def publish_runtime_status(
+ *, gateway_state: Any = _UNSET, exit_reason: Any = _UNSET, restart_requested: Any = _UNSET,
+ active_agents: Any = _UNSET, active_work: Any = _UNSET, platform: Any = _UNSET, platform_state: Any = _UNSET,
+ error_code: Any = _UNSET, error_message: Any = _UNSET, needs_attention: Any = _UNSET,
+ retrying_since: Any = _UNSET, served_profiles: Any = _UNSET, session_store: Any = _UNSET,
+ multiplex_standalone_reason: Any = _UNSET,
+ ingress_url: Any = _UNSET, listener_base: Any = _UNSET, clear_profile_platforms: bool = False,
+ drop_profile_platforms: Optional[str] = None,
+) -> int:
+ """Merge and enqueue status without waiting for filesystem persistence."""
+ with _runtime_status_state_lock:
+ path, payload, previous_payload = _prepare_runtime_status_update(
+ gateway_state=gateway_state, exit_reason=exit_reason,
+ restart_requested=restart_requested, active_agents=active_agents, active_work=active_work,
+ platform=platform, platform_state=platform_state, error_code=error_code,
+ error_message=error_message, needs_attention=needs_attention,
+ retrying_since=retrying_since, served_profiles=served_profiles,
+ session_store=session_store, multiplex_standalone_reason=multiplex_standalone_reason,
+ ingress_url=ingress_url, listener_base=listener_base,
+ clear_profile_platforms=clear_profile_platforms, drop_profile_platforms=drop_profile_platforms,
+ load_existing=False)
+ generation = _get_runtime_status_writer().submit(path, payload)
+ _emit_runtime_status_transition(previous_payload, payload)
+ return generation
+
+
def read_runtime_status(path: Optional[Path] = None) -> Optional[dict[str, Any]]:
"""Read ``gateway_state.json``; ``path`` lets callers inspect another profile's file."""
return _read_json_file(path or _get_runtime_status_path())
diff --git a/tests/gateway/test_api_server_active_work_drain.py b/tests/gateway/test_api_server_active_work_drain.py
index 1878df7ff98..c223ede1c60 100644
--- a/tests/gateway/test_api_server_active_work_drain.py
+++ b/tests/gateway/test_api_server_active_work_drain.py
@@ -611,7 +611,7 @@ class TestShutdownSettleWindow:
monkeypatch.setattr(bt_lifecycle, "cleanup_all_browsers", lambda: None)
with patch("gateway.status.remove_pid_file"), \
- patch("gateway.status.write_runtime_status"), \
+ patch("gateway.status.publish_runtime_status"), \
patch("cron.scheduler.mark_job_run"):
await runner.stop()
@@ -663,7 +663,7 @@ class TestShutdownSettleWindow:
monkeypatch.setattr(type(loop), "time", _fast_time)
try:
with patch("gateway.status.remove_pid_file"), \
- patch("gateway.status.write_runtime_status"), \
+ patch("gateway.status.publish_runtime_status"), \
patch("cron.scheduler.mark_job_run"):
await runner.stop()
finally:
@@ -676,4 +676,3 @@ class TestShutdownSettleWindow:
_INTERRUPT_REASON_GATEWAY_SHUTDOWN,
]
-
diff --git a/tests/gateway/test_cron_active_work_drain.py b/tests/gateway/test_cron_active_work_drain.py
index 5fc5db9013d..521819767eb 100644
--- a/tests/gateway/test_cron_active_work_drain.py
+++ b/tests/gateway/test_cron_active_work_drain.py
@@ -111,10 +111,9 @@ class TestKillToolSubprocessesMarksCronInterrupted:
monkeypatch.setattr(sched, "mark_running_jobs_interrupted", _spy)
- with patch("gateway.status.remove_pid_file"), patch("gateway.status.write_runtime_status"), \
+ with patch("gateway.status.remove_pid_file"), patch("gateway.status.publish_runtime_status"), \
patch("cron.scheduler.mark_job_run"):
await runner.stop()
assert marked_calls, "mark_running_jobs_interrupted was never called during shutdown"
assert any(result == ["job-1"] for _reason, result in marked_calls)
-
diff --git a/tests/gateway/test_cron_interrupt_notification.py b/tests/gateway/test_cron_interrupt_notification.py
index f2d6c56fecd..08e28bbae01 100644
--- a/tests/gateway/test_cron_interrupt_notification.py
+++ b/tests/gateway/test_cron_interrupt_notification.py
@@ -246,7 +246,7 @@ class TestShutdownDeliversNoticeBeforeDisconnect:
adapter.disconnect = _tracking_disconnect
with patch("gateway.status.remove_pid_file"), \
- patch("gateway.status.write_runtime_status"), \
+ patch("gateway.status.publish_runtime_status"), \
patch("cron.scheduler.mark_job_run"), \
patch("cron.jobs.get_job", return_value=_telegram_job()), \
patch("cron.scheduler._resolve_delivery_targets",
diff --git a/tests/gateway/test_gateway_shutdown.py b/tests/gateway/test_gateway_shutdown.py
index 233f7fbde27..2df66e10760 100644
--- a/tests/gateway/test_gateway_shutdown.py
+++ b/tests/gateway/test_gateway_shutdown.py
@@ -91,7 +91,7 @@ async def test_gateway_stop_interrupts_running_agents_and_cancels_adapter_tasks(
with (
patch("gateway.status.remove_pid_file"),
- patch("gateway.status.write_runtime_status"),
+ patch("gateway.status.publish_runtime_status"),
patch("agent.auxiliary_client.shutdown_cached_clients") as shutdown_cached_clients,
):
await runner.stop()
@@ -141,7 +141,7 @@ async def test_gateway_stop_settles_completion_batch_before_adapter_disconnect()
await asyncio.sleep(0)
assert runner._completion_notification_batch_flush_tasks
- with patch("gateway.status.remove_pid_file"), patch("gateway.status.write_runtime_status"):
+ with patch("gateway.status.remove_pid_file"), patch("gateway.status.publish_runtime_status"):
await runner.stop()
assert await asyncio.wait_for(pending, timeout=1.0) is False
@@ -163,7 +163,7 @@ async def test_planned_service_exit_issues_no_restart_of_its_own(monkeypatch):
),
)
- with patch("gateway.status.remove_pid_file"), patch("gateway.status.write_runtime_status"):
+ with patch("gateway.status.remove_pid_file"), patch("gateway.status.publish_runtime_status"):
await runner.stop()
assert runner._exit_code == GATEWAY_SERVICE_RESTART_EXIT_CODE
@@ -185,7 +185,7 @@ async def test_unexpected_signal_starts_teardown_after_bounded_interrupt_grace()
adapter.disconnect = disconnect
with patch("gateway.status.remove_pid_file"), patch(
- "gateway.status.write_runtime_status"
+ "gateway.status.publish_runtime_status"
):
stop_task = asyncio.create_task(runner.stop())
await asyncio.wait_for(disconnect_started.wait(), timeout=0.75)
@@ -286,7 +286,7 @@ async def test_gateway_stop_kills_tool_subprocesses_before_adapter_disconnect_on
lambda *a, **k: runner._running_agents.clear()
)
- with patch("gateway.status.remove_pid_file"), patch("gateway.status.write_runtime_status"):
+ with patch("gateway.status.remove_pid_file"), patch("gateway.status.publish_runtime_status"):
await runner.stop()
# First kill_all must precede the first disconnect. (Both the eager
@@ -342,7 +342,7 @@ async def test_signal_initiated_shutdown_persists_running_not_stopped(tmp_path,
adapter.disconnect = AsyncMock()
runner._signal_initiated_shutdown = True # set by handler on unmarked signal
- with patch("gateway.status.remove_pid_file"), patch("gateway.status.write_runtime_status"):
+ with patch("gateway.status.remove_pid_file"), patch("gateway.status.publish_runtime_status"):
await runner.stop()
assert not _stopped_state_persisted(runner), (
diff --git a/tests/gateway/test_multiplex_adapter_registry.py b/tests/gateway/test_multiplex_adapter_registry.py
index 1165f237b63..4a0d3e1c709 100644
--- a/tests/gateway/test_multiplex_adapter_registry.py
+++ b/tests/gateway/test_multiplex_adapter_registry.py
@@ -165,7 +165,7 @@ class TestProfileRuntimeStatus:
adapter._runtime_status_platform_key = "reviewer:discord"
writes = []
monkeypatch.setattr(
- "gateway.status.write_runtime_status",
+ "gateway.status.publish_runtime_status",
lambda **kwargs: writes.append(kwargs),
)
@@ -852,7 +852,7 @@ class TestSecondaryProfileConfigHandling:
monkeypatch.setattr(runner, "_start_one_profile_adapters", fake_start_one)
status = {}
monkeypatch.setattr(
- "gateway.status.write_runtime_status",
+ "gateway.status.publish_runtime_status",
lambda **kwargs: status.update(kwargs),
)
@@ -867,7 +867,7 @@ class TestSecondaryProfileConfigHandling:
@pytest.mark.asyncio
async def test_single_profile_start_clears_inherited_served_profiles(self, monkeypatch, tmp_path):
- """``write_runtime_status`` re-stamps the previous writer's record in place, so a multiplexer's
+ """Runtime-status publication re-stamps the previous writer's record in place, so a multiplexer's
``served_profiles`` survived into a later single-profile run and every `hermes -p X` surface
kept treating X as served (exit 78 on start, "running via multiplexer" on status)."""
import json
diff --git a/tests/gateway/test_platform_reconnect.py b/tests/gateway/test_platform_reconnect.py
index 2dee8ec3d01..4a0347608e2 100644
--- a/tests/gateway/test_platform_reconnect.py
+++ b/tests/gateway/test_platform_reconnect.py
@@ -118,7 +118,7 @@ class TestStartupPlatformIsolation:
coro.close()
return MagicMock()
- with patch("gateway.status.write_runtime_status"):
+ with patch("gateway.status.publish_runtime_status"):
with patch("hermes_cli.plugins.discover_plugins"):
with patch("hermes_cli.config.load_config", return_value={}):
with patch("agent.shell_hooks.register_from_config"):
@@ -930,7 +930,7 @@ class TestVoiceInputCallbackWiring:
return MagicMock()
with patch.object(runner, "_create_adapter", return_value=adapter):
- with patch("gateway.status.write_runtime_status"):
+ with patch("gateway.status.publish_runtime_status"):
with patch("hermes_cli.plugins.discover_plugins"):
with patch("hermes_cli.config.load_config", return_value={}):
with patch("agent.shell_hooks.register_from_config"):
diff --git a/tests/gateway/test_restart_resume_pending.py b/tests/gateway/test_restart_resume_pending.py
index 777885563b4..bf2fd824294 100644
--- a/tests/gateway/test_restart_resume_pending.py
+++ b/tests/gateway/test_restart_resume_pending.py
@@ -597,7 +597,7 @@ async def test_drain_timeout_marks_resume_pending():
runner.session_store = session_store
with patch("gateway.status.remove_pid_file"), patch(
- "gateway.status.write_runtime_status"
+ "gateway.status.publish_runtime_status"
):
await runner.stop()
@@ -1320,4 +1320,3 @@ async def test_startup_boot_sends_still_run_when_they_finish_quickly(monkeypatch
runner._claim_pending_obligations.assert_awaited_once()
runner._redeliver_claimed_obligations.assert_awaited_once()
-
diff --git a/tests/gateway/test_session_db_recovery.py b/tests/gateway/test_session_db_recovery.py
index 0420bbda4ea..b0d0d177146 100644
--- a/tests/gateway/test_session_db_recovery.py
+++ b/tests/gateway/test_session_db_recovery.py
@@ -95,7 +95,7 @@ def test_runtime_health_is_sanitized_and_recovers() -> None:
raise RuntimeError("database disk image is malformed at secret/profile/state.db")
return object()
- with patch("gateway.status.write_runtime_status", side_effect=lambda **kw: writes.append(kw)):
+ with patch("gateway.status.publish_runtime_status", side_effect=lambda **kw: writes.append(kw)):
assert cache.get(path, opener) is None
clock.now = 1.0
assert cache.get(path, opener) is not None
diff --git a/tests/gateway/test_status.py b/tests/gateway/test_status.py
index ae22d75c2c9..5aaf23eda3f 100644
--- a/tests/gateway/test_status.py
+++ b/tests/gateway/test_status.py
@@ -3,6 +3,7 @@
import json
import os
import sys
+import threading
import time
from pathlib import Path
from types import SimpleNamespace
@@ -434,12 +435,96 @@ class TestGatewayRuntimeStatus:
adapter._fatal_error_code = adapter._fatal_error_message = None
adapter._fatal_error_retryable = True
adapter._mark_connected()
+ assert status.flush_runtime_status(timeout=2.0)
entry = status.read_runtime_status()["platforms"]["telegram"]
assert entry["state"] == "connected"
assert entry["needs_attention"] is False
assert entry["retrying_since"] is None
+class TestRuntimeStatusBackgroundWriter:
+ def test_blocked_write_does_not_block_publish_and_burst_coalesces(
+ self, tmp_path, monkeypatch
+ ):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ write_started = threading.Event()
+ release_write = threading.Event()
+ publish_returned = threading.Event()
+ writes = []
+
+ def controlled_write(_path, payload):
+ writes.append(payload)
+ if len(writes) == 1:
+ write_started.set()
+ assert release_write.wait(timeout=5.0)
+
+ writer = status._RuntimeStatusWriter(write_fn=controlled_write)
+ monkeypatch.setattr(status, "_runtime_status_writer", writer)
+
+ def publish_initial_status():
+ status.publish_runtime_status(
+ platform="reviewer:slack", platform_state="fatal"
+ )
+ publish_returned.set()
+
+ caller = threading.Thread(target=publish_initial_status)
+ caller.start()
+ try:
+ assert write_started.wait(timeout=2.0)
+ assert publish_returned.wait(timeout=2.0)
+ status.publish_runtime_status(
+ gateway_state="running",
+ active_work=["telegram:dm:1"],
+ multiplex_standalone_reason="single-profile",
+ )
+ status.publish_runtime_status(
+ platform="telegram",
+ platform_state="connected",
+ ingress_url="https://example.test/p/default/telegram",
+ listener_base="http://127.0.0.1:8080",
+ )
+ status.publish_runtime_status(drop_profile_platforms="reviewer")
+ for active_agents in range(50):
+ status.publish_runtime_status(active_agents=active_agents)
+ finally:
+ release_write.set()
+ caller.join(timeout=2.0)
+
+ assert writer.flush(timeout=2.0)
+ assert len(writes) == 2
+ final = writes[-1]
+ assert final["gateway_state"] == "running"
+ assert final["active_agents"] == 49
+ assert final["active_work"] == ["telegram:dm:1"]
+ assert final["multiplex_standalone_reason"] == "single-profile"
+ assert "reviewer:slack" not in final["platforms"]
+ assert final["platforms"]["telegram"]["ingress_url"].endswith("/telegram")
+ assert final["platforms"]["telegram"]["listener_base"] == "http://127.0.0.1:8080"
+
+ def test_sync_write_can_bound_a_blocked_persistence_wait(
+ self, tmp_path, monkeypatch
+ ):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ write_started = threading.Event()
+ release_write = threading.Event()
+
+ def blocked_write(_path, _payload):
+ write_started.set()
+ assert release_write.wait(timeout=5.0)
+
+ writer = status._RuntimeStatusWriter(write_fn=blocked_write)
+ monkeypatch.setattr(status, "_runtime_status_writer", writer)
+ try:
+ persisted = status.write_runtime_status(
+ gateway_state="starting", _wait_timeout=0.05
+ )
+ assert write_started.is_set()
+ assert persisted is False
+ finally:
+ release_write.set()
+ assert writer.flush(timeout=2.0)
+
+
class TestGetProcessStartTime:
"""Start-time fingerprint backing the PID-reuse guard (#43846 / #50468).