Skip to content

The agent that grows with you

refactor(gateway): _log_suppressed context manager replaces 38 try/except-log seams across run_* mixins

Tekniume577d60dc04a
diff --git a/gateway/run_adapters.py b/gateway/run_adapters.py
index ec8db588c76..e748ff99133 100644
--- a/gateway/run_adapters.py
+++ b/gateway/run_adapters.py
@@ -21,6 +21,7 @@ from datetime import datetime, timedelta, timezone
from gateway.config import Platform, platform_binds_port as _platform_binds_port
from gateway.platforms.base import BasePlatformAdapter
from gateway.restart import is_global_startup_conflict
+from gateway.run_shutdown import _log_suppressed
from gateway.session import SessionSource
from pathlib import Path
from typing import Any, Awaitable, Callable, Dict, Optional
@@ -73,14 +74,12 @@ class GatewayAdapterLifecycleMixin:
"""
timeout = self._adapter_disconnect_timeout_secs()
label = platform.value if platform is not None else "adapter"
- try:
+ with _log_suppressed(logging.DEBUG, "Defensive %s disconnect after failed connect raised: %s", label):
if not await self._await_adapter_cleanup_with_timeout(adapter.disconnect(), timeout):
logger.warning(
"Timed out after %.1fs while disconnecting %s adapter; continuing shutdown",
timeout, label,
)
- except Exception as e:
- logger.debug("Defensive %s disconnect after failed connect raised: %s", label, e)
async def _bounded_adapter_teardown(self, adapter, platform, *, profile: Optional[str] = None) -> None:
"""Tear down one adapter on the shutdown path with bounded awaits (never raises).
@@ -174,10 +173,8 @@ class GatewayAdapterLifecycleMixin:
async def _handle_reaction_event(self, ctx: Dict[str, Any]) -> None:
"""Fan a normalised reaction event out to the HookRegistry; errors never block the adapter."""
event_name = str(ctx.get("event_name") or "reaction:added")
- try:
+ with _log_suppressed(logging.DEBUG, "[Gateway] reaction hook emit failed", exc_info=True):
await self.hooks.emit(event_name, ctx)
- except Exception:
- logger.debug("[Gateway] reaction hook emit failed", exc_info=True)
async def _handle_adapter_fatal_error(self, adapter: BasePlatformAdapter) -> None:
"""React to an adapter failure after startup (retryable → background reconnect queue).
@@ -467,10 +464,8 @@ class GatewayAdapterLifecycleMixin:
raise
except Exception as exc:
logger.warning("Handoff for session %s failed: %s", session_id, exc, exc_info=True)
- try:
+ with _log_suppressed(logging.DEBUG, "Could not record handoff failure", exc_info=True):
await session_db.fail_handoff(session_id, str(exc))
- except Exception:
- logger.debug("Could not record handoff failure", exc_info=True)
finally:
inflight.pop(session_id, None)
@@ -507,11 +502,9 @@ class GatewayAdapterLifecycleMixin:
return _async_profile_runtime_scope(profile_home)
for _pname, _phome in _handoff_watch_scopes(self):
- try:
+ with _log_suppressed(logging.DEBUG, "Stale-handoff reclaim failed", exc_info=True):
async with _scope(_phome):
await _reclaim_stale(self)
- except Exception:
- logger.debug("Stale-handoff reclaim failed", exc_info=True)
try:
while self._running:
@@ -528,10 +521,8 @@ class GatewayAdapterLifecycleMixin:
# Bounded drain: cancelling would strand in-flight rows in 'running'.
pending_tasks = [t for t in inflight.values() if not t.done()]
if pending_tasks:
- try:
+ with _log_suppressed(logging.DEBUG, "Handoff drain raised", exc_info=True):
await asyncio.wait(pending_tasks, timeout=drain_timeout)
- except Exception:
- logger.debug("Handoff drain raised", exc_info=True)
for task in pending_tasks:
if not task.done():
task.cancel()
@@ -858,7 +849,7 @@ class GatewayAdapterLifecycleMixin:
def _record_served_profiles(self, active: str, profile_homes) -> None:
"""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."""
- try:
+ with _log_suppressed(logging.DEBUG, "could not record served_profiles", exc_info=True):
from gateway.status import write_runtime_status
from gateway.pairing import PairingStore
served = [active] + sorted(name for name, _home in profile_homes if name != active)
@@ -868,8 +859,6 @@ class GatewayAdapterLifecycleMixin:
self.pairing_store if name == active else PairingStore(profile=name)
)
write_runtime_status(served_profiles=served)
- except Exception:
- logger.debug("could not record served_profiles", exc_info=True)
async def _load_secondary_profile_config(self, profile_name: str, profile_home: "Path"):
"""Hydrate + enter ``profile_home``'s scope once; return its gateway config.
@@ -1463,7 +1452,7 @@ class GatewayAdapterLifecycleMixin:
"thread_sessions_per_user", getattr(self.config, "thread_sessions_per_user", False)
)
- try:
+ with _log_suppressed(logging.DEBUG, "Platform registry lookup for '%s' failed: %s", platform.value):
from gateway.platform_registry import platform_registry
if platform_registry.is_registered(platform.value):
adapter = platform_registry.create_adapter(platform.value, config)
@@ -1473,8 +1462,6 @@ class GatewayAdapterLifecycleMixin:
"(check dependencies and config)", platform.value,
)
return adapter
- except Exception as e:
- logger.debug("Platform registry lookup for '%s' failed: %s", platform.value, e)
return _instantiate_builtin_adapter(platform, config)
def _make_adapter_auth_check(
diff --git a/gateway/run_notifications.py b/gateway/run_notifications.py
index 3ed6b08ed9e..8c0791c6d7f 100644
--- a/gateway/run_notifications.py
+++ b/gateway/run_notifications.py
@@ -19,7 +19,7 @@ from typing import Any, Dict, Optional, cast
from gateway.config import Platform, _BUILTIN_PLATFORM_VALUES
from gateway.platforms.base import MessageEvent, MessageType
from gateway.session import SessionEntry, SessionSource
-from gateway.run_shutdown import _notice_target_key, _send_error, _send_failed
+from gateway.run_shutdown import _log_suppressed, _notice_target_key, _send_error, _send_failed
# Log-record parity with the origin module.
logger = logging.getLogger("gateway.run")
@@ -271,7 +271,7 @@ class GatewayNotificationsMixin:
stale auto-appended tags are deduped upstream (_collect_auto_append_media_tags).
"""
from urllib.parse import quote as _quote
- try:
+ with _log_suppressed(logging.WARNING, "Post-stream media extraction failed: %s"):
# Capture [[as_document]] before extract_media strips it: image files then go through
# send_document (preserving bytes), not send_multiple_images (Telegram recompresses).
force_document_attachments = "[[as_document]]" in response
@@ -318,8 +318,6 @@ class GatewayNotificationsMixin:
except Exception as e:
logger.warning("[%s] Post-stream media delivery failed: %s", adapter.name, e)
- except Exception as e:
- logger.warning("Post-stream media extraction failed: %s", e)
async def _deliver_queued_first_response(
self, response: str, source: SessionSource, adapter,
@@ -451,24 +449,20 @@ class GatewayNotificationsMixin:
return
max_chunk = 3500
for i in range(0, len(clean), max_chunk):
- try:
+ with _log_suppressed(logging.DEBUG, "Update stream send failed: %s"):
await target.send(f"```\n{clean[i:i + max_chunk]}\n```")
- except Exception as e:
- logger.debug("Update stream send failed: %s", e)
async def _forward_update_prompt(self, target: "_UpdateTarget", prompt_text: str, default: str) -> None:
"""Forward an update prompt: platform-native buttons first (Discord, Telegram), else text."""
sent_buttons = False
adapter = target.adapter
if getattr(type(adapter), "send_update_prompt", None) is not None:
- try:
+ with _log_suppressed(logging.DEBUG, "Button-based update prompt failed: %s"):
await adapter.send_update_prompt(
chat_id=target.chat_id, prompt=prompt_text, default=default,
session_key=target.session_key, metadata=target.send_metadata(),
)
sent_buttons = True
- except Exception as btn_err:
- logger.debug("Button-based update prompt failed: %s", btn_err)
if not sent_buttons:
default_hint = f" (default: {default})" if default else ""
_p = getattr(adapter, "typed_command_prefix", "/")
@@ -529,15 +523,13 @@ class GatewayNotificationsMixin:
if paths.exit_code.exists():
_read_new_output()
await _flush_buffer()
- try:
+ with _log_suppressed(logging.WARNING, "Update final notification failed: %s"):
exit_code = int(paths.exit_code.read_text(encoding="utf-8").strip() or "1")
await target.send(
"✅ Hermes update finished." if exit_code == 0
else "❌ Hermes update failed (exit code {}).".format(exit_code)
)
logger.info("Update finished (exit=%s), notified %s", exit_code, session_key)
- except Exception as e:
- logger.warning("Update final notification failed: %s", e)
self._clear_update_markers(paths, session_key)
return
@@ -887,10 +879,8 @@ class GatewayNotificationsMixin:
synth_text = _format_gateway_process_notification(evt)
if not synth_text:
continue
- try:
+ with _log_suppressed(logging.ERROR, "Watch notification injection error: %s"):
await self._inject_watch_notification(synth_text, evt)
- except Exception as exc:
- logger.error("Watch notification injection error: %s", exc)
def _adapter_by_platform_value(self, platform_name: str):
"""Literal ``p.value == platform_name`` scan over connected adapters (native adapters only)."""
@@ -1446,7 +1436,7 @@ class GatewayNotificationsMixin:
await asyncio.sleep(3) # let platforms finish connecting
from tools.process_registry import process_registry as _pr
while self._running:
- try:
+ with _log_suppressed(logging.DEBUG, "Async delegation watcher error: %s"):
# Peek for async-delegation events only; watch/completion events belong to other drains,
# so requeue anything that isn't ours.
requeue = []
@@ -1476,8 +1466,6 @@ class GatewayNotificationsMixin:
for evt in group:
_pr.completion_queue.put(evt)
logger.error("Async delegation injection error: %s", e)
- except Exception as e:
- logger.debug("Async delegation watcher error: %s", e)
await asyncio.sleep(interval)
@staticmethod
@@ -1498,13 +1486,11 @@ class GatewayNotificationsMixin:
from gateway.run import _non_conversational_metadata
adapter = self._adapter_by_platform_value(platform_name)
if adapter and chat_id:
- try:
+ with _log_suppressed(logging.ERROR, "Watcher delivery error: %s"):
send_meta = {"thread_id": thread_id} if thread_id else None
await adapter.send(
chat_id, message_text, metadata=_non_conversational_metadata(send_meta, platform=platform_name),
)
- except Exception as e:
- logger.error("Watcher delivery error: %s", e)
@staticmethod
def _build_process_completion_event(watcher: dict, session, session_id: str) -> dict:
diff --git a/gateway/run_shutdown.py b/gateway/run_shutdown.py
index baff2d22faf..e0803edc085 100644
--- a/gateway/run_shutdown.py
+++ b/gateway/run_shutdown.py
@@ -16,7 +16,7 @@ import shlex
import sys
import threading
import time
-from contextlib import suppress
+from contextlib import contextmanager, suppress
from pathlib import Path
from typing import Any, Callable, Dict, Optional
@@ -80,6 +80,23 @@ subprocess.Popen(
""".strip()
+@contextmanager
+def _log_suppressed(level: int, msg: str, *args, exc_info: bool = False):
+ """``suppress(Exception)`` that logs the swallowed exception on ``gateway.run``.
+
+ Without ``exc_info`` the exception is appended as the last ``%s`` argument (``msg % (*args, exc)``);
+ with it the traceback is attached instead. Best-effort seams use this everywhere a failure must be
+ visible in the log but must never propagate.
+ """
+ try:
+ yield
+ except Exception as exc:
+ if exc_info:
+ logger.log(level, msg, *args, exc_info=(type(exc), exc, exc.__traceback__))
+ else:
+ logger.log(level, msg, *args, exc)
+
+
def _send_failed(result: Any) -> bool:
"""True when an adapter ``send()`` result explicitly reports failure."""
return result is not None and getattr(result, "success", True) is False
@@ -606,11 +623,9 @@ class GatewayShutdownMixin:
for session_key, agent in list(self._running_agents.items()):
if agent is _AGENT_PENDING_SENTINEL:
continue
- try:
+ with _log_suppressed(logging.DEBUG, "Failed interrupting agent during shutdown: %s"):
request_hard_interrupt(agent, reason)
logger.debug("Interrupted running agent for session %s during shutdown", session_key)
- except Exception as e:
- logger.debug("Failed interrupting agent during shutdown: %s", e)
# API-server / desk turns are adapter-owned and never enter _running_agents, so the loop above
# cannot see them even though _drain_active_agents() waited for them.
interrupted_api = self._interrupt_api_server_runs(reason)
@@ -632,11 +647,9 @@ class GatewayShutdownMixin:
for _sk, _agent in list(self._running_agents.items()):
if _agent is _AGENT_PENDING_SENTINEL:
continue
- try:
+ with _log_suppressed(logging.DEBUG, "%s failed for %s: %s", log_prefix, _sk):
await self.async_session_store.mark_resume_pending(_sk, reason)
marked.append(_sk)
- except Exception as _e:
- logger.debug("%s failed for %s: %s", log_prefix, _sk, _e)
return marked
def _restart_notification_allowed(self, platform: Platform) -> bool:
@@ -851,7 +864,7 @@ class GatewayShutdownMixin:
A force-interrupted agent may never reach finalize_turn (the only mid-turn flush), so its
tool rounds would vanish on resume. Idempotent; gracefully finished agents re-flush nothing.
"""
- try:
+ with _log_suppressed(logging.DEBUG, "Shutdown transcript flush failed: %s"):
_flush = getattr(agent, "_flush_messages_to_session_db", None)
_session_messages = getattr(agent, "_session_messages", None)
if not (callable(_flush) and isinstance(_session_messages, list) and _session_messages):
@@ -873,8 +886,6 @@ class GatewayShutdownMixin:
)
from gateway.shutdown_flush import flush_agent_history_to_file
flush_agent_history_to_file(getattr(agent, "session_id", None), _session_messages)
- except Exception as _e:
- logger.debug("Shutdown transcript flush failed: %s", _e)
async def _finalize_shutdown_agents(self, active_agents: Dict[str, Any]) -> None:
for agent in active_agents.values():
@@ -1254,10 +1265,8 @@ class GatewayShutdownMixin:
# Launch the detached helper only AFTER the after-turn wait: its drain_timeout+5 deadline
# covers stop() teardown; earlier it would fire the restart mid-turn.
if detached:
- try:
+ with _log_suppressed(logging.ERROR, "Failed to launch detached gateway restart helper: %s"):
await self._launch_detached_restart_command()
- except Exception as e:
- logger.error("Failed to launch detached gateway restart helper: %s", e)
await asyncio.sleep(0.05)
await self.stop(restart=True, detached_restart=detached, service_restart=via_service)
@@ -1471,19 +1480,15 @@ class GatewayShutdownMixin:
logger.info("Shutdown phase: post-interrupt tool kill done at +%.2fs", ctx.elapsed())
# Last window with the transport up: the cron worker's own "interrupted" notice arrives
# after adapter teardown and is lost.
- try:
+ with _log_suppressed(logging.DEBUG, "Cron interrupt notification failed: %s"):
await self._notify_interrupted_cron_jobs(_interrupted_cron_jobs)
- except Exception as _e:
- logger.debug("Cron interrupt notification failed: %s", _e)
logger.info("Shutdown phase: cron interrupt notices done at +%.2fs", ctx.elapsed())
async def _stop_finalize_agents_and_adapters(self, ctx: "GatewayShutdownMixin._StopContext") -> None:
"""Detached restart launch, agent finalization, idle-cache cleanup, adapter teardown."""
if self._restart_requested and self._restart_detached:
- try:
+ with _log_suppressed(logging.ERROR, "Failed to launch detached gateway restart: %s"):
await self._launch_detached_restart_command()
- except Exception as e:
- logger.error("Failed to launch detached gateway restart: %s", e)
await self._finalize_shutdown_agents(ctx.active_agents)
# Idle cached agents too: _finalize_shutdown_agents only covers agents mid-turn at drain
# time, but _agent_cache may hold agents whose MemoryProviders never got on_session_end().
@@ -1644,7 +1649,7 @@ class GatewayShutdownMixin:
if ctx.active_agents:
self._increment_restart_failure_counts(set(ctx.active_agents.keys()))
if self._restart_requested and self._restart_command_source is None:
- try:
+ with _log_suppressed(logging.DEBUG, "Failed to write planned restart notification marker: %s"):
atomic_json_write(
_planned_restart_notification_path(),
{
@@ -1654,8 +1659,6 @@ class GatewayShutdownMixin:
},
indent=None,
)
- except Exception as e:
- logger.debug("Failed to write planned restart notification marker: %s", e)
if self._restart_requested and self._restart_via_service:
# Service manager owns restarts: exit 75 + ``RestartForceExitStatus=75`` has systemd
# replace this process without a second helper racing the unit's stop/start job.
diff --git a/gateway/run_startup.py b/gateway/run_startup.py
index 7ae70480349..1dad13227f2 100644
--- a/gateway/run_startup.py
+++ b/gateway/run_startup.py
@@ -23,6 +23,7 @@ from gateway.session import SessionSource, build_session_key
from gateway.restart import (
DEFAULT_GATEWAY_CRON_DRAIN_TIMEOUT, GATEWAY_FATAL_CONFIG_EXIT_CODE, is_global_startup_conflict
)
+from gateway.run_shutdown import _log_suppressed
from gateway.shutdown_watchdog import (
DEFAULT_HEARTBEAT_INTERVAL_S, DEFAULT_LOOP_WATCHDOG_INTERVAL_S,
DEFAULT_LOOP_WATCHDOG_MAX_STRIKES, DEFAULT_LOOP_WATCHDOG_TIMEOUT_S, loop_heartbeat_forever,
@@ -339,7 +340,7 @@ class GatewayStartupMixin:
"obligation %s: redelivery send raised: %s", row["obligation_id"], send_err
)
result = None
- try:
+ with _log_suppressed(logging.DEBUG, "delivery ledger update failed", exc_info=True):
if result is not None and getattr(result, "success", False):
await asyncio.to_thread(mark_delivered, row["obligation_id"])
redelivered += 1
@@ -353,8 +354,6 @@ class GatewayStartupMixin:
mark_failed, row["obligation_id"],
str(getattr(result, "error", "") or "send failed"),
)
- except Exception:
- logger.debug("delivery ledger update failed", exc_info=True)
return redelivered
async def _obligation_adapter(self, row: dict):
@@ -535,10 +534,8 @@ class GatewayStartupMixin:
async def _startup_teardown_adapter(self, adapter, platform) -> None:
"""Cancel an adapter's background tasks (best-effort) then disconnect it."""
- try:
+ with _log_suppressed(logging.DEBUG, "✗ %s background-task cancel error: %s", platform.value):
await adapter.cancel_background_tasks()
- except Exception as e:
- logger.debug("✗ %s background-task cancel error: %s", platform.value, e)
await self._safe_adapter_disconnect(adapter, platform)
def _startup_retry_entry(self, platform, adapter, platform_config, *, queued: bool = True) -> dict:
@@ -572,10 +569,8 @@ class GatewayStartupMixin:
if config is not None and not getattr(config, "loop_watchdog", True):
return
if getattr(self, "_loop_floor_timer_handle", None) is None:
- try:
+ with _log_suppressed(logging.DEBUG, "Failed to arm gateway loop floor timer", exc_info=True):
self._loop_floor_timer_handle = _arm_loop_floor_timer(loop)
- except Exception:
- logger.debug("Failed to arm gateway loop floor timer", exc_info=True)
watchdog = getattr(self, "_loop_liveness_watchdog", None)
if watchdog is None or not watchdog.is_alive():
@@ -608,10 +603,8 @@ class GatewayStartupMixin:
guard = getattr(self, attr, None)
setattr(self, attr, None)
if guard is not None:
- try:
+ with _log_suppressed(logging.DEBUG, "Failed to %s", what, exc_info=True):
getattr(guard, method)()
- except Exception:
- logger.debug("Failed to %s", what, exc_info=True)
async def _consume_clean_shutdown_marker(self, marker_path) -> int:
"""Discard orphan turn markers before consuming a clean-exit receipt. Raises (fail closed):
@@ -625,17 +618,13 @@ class GatewayStartupMixin:
from gateway.run import _float_env
exact = 0
fallback = 0
- try:
+ with _log_suppressed(logging.WARNING, "Exact active-turn recovery on startup failed: %s"):
agent_timeout = max(1.0, _float_env("HERMES_AGENT_TIMEOUT", 1800))
exact = await self.async_session_store.recover_interrupted_turns(
max_age_seconds=max(60 * 60, int(agent_timeout * 2))
)
- except Exception as exc:
- logger.warning("Exact active-turn recovery on startup failed: %s", exc)
- try:
+ with _log_suppressed(logging.WARNING, "Legacy session recovery on startup failed: %s"):
fallback = await self.async_session_store.suspend_recently_active(max_age_seconds=120)
- except Exception as exc:
- logger.warning("Legacy session recovery on startup failed: %s", exc)
return exact, fallback
@staticmethod
@@ -671,7 +660,7 @@ class GatewayStartupMixin:
def _start_loop_heartbeat_task(self) -> None:
"""Start the loop-liveness heartbeat task (idempotent, best-effort). An asyncio task so a
frozen loop stops refreshing ``state/gateway.heartbeat``; cancelled with the others in stop()."""
- try:
+ with _log_suppressed(logging.DEBUG, "Failed to start gateway loop heartbeat", exc_info=True):
_existing_hb = getattr(self, "_loop_heartbeat_task", None)
if _existing_hb is not None and not _existing_hb.done():
return
@@ -688,8 +677,6 @@ class GatewayStartupMixin:
_bg = getattr(self, "_background_tasks", None)
if _bg is not None:
self._track_task_in(_bg, task)
- except Exception:
- logger.debug("Failed to start gateway loop heartbeat", exc_info=True)
def _open_faulthandler_log(self):
"""Open (append) ``<log_dir>/gateway_faulthandler.log``, creating the directory."""
@@ -707,21 +694,17 @@ class GatewayStartupMixin:
try:
faulthandler.enable()
except (RuntimeError, ValueError, OSError):
- try:
+ with _log_suppressed(logging.DEBUG, "faulthandler.enable() unavailable", exc_info=True):
faulthandler.enable(file=self._open_faulthandler_log(), all_threads=True)
- except Exception:
- logger.debug("faulthandler.enable() unavailable", exc_info=True)
# Also dump stacks to a file on SIGUSR2 for off-line analysis under a service manager that
# doesn't capture stderr. faulthandler.register()/SIGUSR2 are POSIX-only: skip on Windows
# (faulthandler.enable() above still covers fatal errors).
_sigusr2 = getattr(signal, "SIGUSR2", None)
if _sigusr2 is not None and hasattr(faulthandler, "register"):
- try:
+ with _log_suppressed(logging.DEBUG, "Could not set up faulthandler file logging", exc_info=True):
faulthandler.register(
_sigusr2, file=self._open_faulthandler_log(), all_threads=True, chain=True,
)
- except Exception:
- logger.debug("Could not set up faulthandler file logging", exc_info=True)
def _start_log_startup_environment(self) -> None:
"""Bind the gateway loop, disarm the startup watchdog, and log the startup environment."""
@@ -735,11 +718,9 @@ class GatewayStartupMixin:
# watchdog (armed above) takes over. Disarm even when loop guards are config-disabled —
# the startup watchdog covers only the pre-loop window. Deliberately inside this branch:
# if the loop isn't live, startup has NOT reached the milestone and it must stay armed.
- try:
+ with _log_suppressed(logging.DEBUG, "Startup watchdog disarm failed", exc_info=True):
from gateway.startup_watchdog import disarm_startup_watchdog
disarm_startup_watchdog()
- except Exception:
- logger.debug("Startup watchdog disarm failed", exc_info=True)
logger.info("Session storage: %s", self.config.sessions_dir)
self._start_log_systemd_timing_alignment()
# Log the resolved max_iterations budget so operators can verify the config.yaml → env
@@ -777,14 +758,12 @@ class GatewayStartupMixin:
write_runtime_status(
gateway_state="starting", exit_reason=None, clear_profile_platforms=True
)
- try:
+ 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
self._gateway_health_export_runtime = start_gateway_health_export(load_config())
if getattr(self._gateway_health_export_runtime, "enabled", False):
logger.info("Gateway health OTLP export: enabled")
- except Exception:
- logger.debug("gateway health OTLP export startup failed", exc_info=True)
# Log any active supply-chain security advisories. Deliberately does NOT block startup or
# surface inline to users — only the operator can act (uninstall, rotate credentials).
@@ -800,7 +779,7 @@ class GatewayStartupMixin:
def _start_log_systemd_timing_alignment(self) -> None:
"""Warn when systemd's TimeoutStopSec does not cover the drain window (a unit file from before
an upgrade may encode the old default, so SIGKILL hits mid-drain). Never raises."""
- try:
+ with _log_suppressed(logging.DEBUG, "check_systemd_timing_alignment failed: %s"):
from gateway.shutdown_forensics import check_systemd_timing_alignment
_alignment = check_systemd_timing_alignment(
self._restart_drain_timeout,
@@ -818,8 +797,6 @@ class GatewayStartupMixin:
_alignment.get("cron_drain_timeout", DEFAULT_GATEWAY_CRON_DRAIN_TIMEOUT),
_alignment["expected_min"],
)
- except Exception as _e:
- logger.debug("check_systemd_timing_alignment failed: %s", _e)
# Builtin platforms whose ``<P>_ALLOWED_USERS`` / ``<P>_ALLOW_ALL_USERS`` env vars count as
# "an allowlist is configured" / "open access opted in"; plugin platforms are appended at
@@ -882,11 +859,9 @@ class GatewayStartupMixin:
# Discover Python plugins before shell hooks so plugin block decisions take precedence in
# tie cases. Explicit here because the gateway lazily imports run_agent per request, so
# the discover_plugins() side-effect in model_tools.py is NOT guaranteed to have run yet.
- try:
+ with _log_suppressed(logging.WARNING, "plugin discovery failed at gateway startup", exc_info=True):
from hermes_cli.plugins import discover_plugins
discover_plugins()
- except Exception:
- logger.warning("plugin discovery failed at gateway startup", exc_info=True)
# Generic relay adapter only if GATEWAY_RELAY_URL / gateway.relay_url is set; no URL -> no-op.
try:
@@ -932,13 +907,11 @@ class GatewayStartupMixin:
self.hooks.discover_and_load()
# Recover background processes from checkpoint (crash recovery)
- try:
+ with _log_suppressed(logging.WARNING, "Process checkpoint recovery: %s"):
from tools.process_registry import process_registry
recovered = process_registry.recover_from_checkpoint()
if recovered:
logger.info("Recovered %s background process(es) from previous run", recovered)
- except Exception as e:
- logger.warning("Process checkpoint recovery: %s", e)
# Recover sessions active when the gateway last exited. Exact durable turn markers cover
# long-running work; the 120s recency heuristic remains as a fallback for turns from older
@@ -966,12 +939,10 @@ class GatewayStartupMixin:
# Stuck-loop detection: a session active across 3+ consecutive restarts is probably looping
# (its history keeps hanging the agent); auto-suspend so the next message starts clean.
- try:
+ with _log_suppressed(logging.DEBUG, "Stuck-loop detection failed: %s"):
stuck = self._suspend_stuck_loop_sessions()
if stuck:
logger.warning("Auto-suspended %d stuck-loop session(s)", stuck)
- except Exception as e:
- logger.debug("Stuck-loop detection failed: %s", e)
async def _start_prefilter_platforms(self) -> Tuple[bool, int, list, list]:
"""Create + wire an adapter per enabled platform (no connects). Returns
@@ -1253,13 +1224,11 @@ class GatewayStartupMixin:
logger.info("Gateway running with %s platform(s)", connected_count)
# Initial channel directory for send_message name resolution
- try:
+ with _log_suppressed(logging.WARNING, "Channel directory build failed: %s"):
from gateway.channel_directory import build_channel_directory
directory = await build_channel_directory(self.adapters)
ch_count = sum(len(chs) for chs in directory.get("platforms", {}).values())
logger.info("Channel directory built: %d target(s)", ch_count)
- except Exception as e:
- logger.warning("Channel directory build failed: %s", e)
# Restarting after a /update? If the update is still running, keep watching so we notify
# once it actually finishes.
@@ -1307,7 +1276,7 @@ class GatewayStartupMixin:
# reassigning a fresh list takes ownership of exactly the watchers present now, so one
# appended concurrently during the yield below isn't dropped by a clear() on the shared
# list. Yield every 100 to avoid O(n^2) loop blocking when recovering thousands.
- try:
+ with _log_suppressed(logging.ERROR, "Recovered watcher setup error: %s"):
from tools.process_registry import process_registry
watchers = process_registry.pending_watchers
process_registry.pending_watchers = []
@@ -1319,8 +1288,6 @@ class GatewayStartupMixin:
logger.info("Resumed watcher for recovered process %s", watcher.get("session_id"))
if i % 100 == 99:
await asyncio.sleep(0)
- except Exception as e:
- logger.error("Recovered watcher setup error: %s", e)
# Long-lived supervised watchers spawned at the end of start(), in order; the supervised name is
# the method name without its leading underscore. Each watcher's docstring explains its job