Skip to content

The agent that grows with you

refactor(gateway): second try/except-log fold pass (12 sites), suppress() for bare passes, fused log-call literals

Teknium64b5c7ab38d5
diff --git a/gateway/run_adapters.py b/gateway/run_adapters.py
index 5d5ca6573c6..fe12fd04961 100644
--- a/gateway/run_adapters.py
+++ b/gateway/run_adapters.py
@@ -11,6 +11,7 @@ import logging
from typing import TYPE_CHECKING
import asyncio
import contextlib
+from contextlib import suppress
import functools
import os
import time
@@ -88,7 +89,10 @@ class GatewayAdapterLifecycleMixin:
)
except Exception as e:
logger.debug("✗ %s background-task cancel error%s: %s", platform.value, suffix, e)
- try:
+ with _log_suppressed(
+ logging.ERROR, "✗ %s disconnect error after %.2fs%s: %s",
+ platform.value, time.monotonic() - started_at, suffix,
+ ):
if await self._await_adapter_cleanup_with_timeout(adapter.disconnect(), timeout):
logger.info(
"✓ %s disconnected (%.2fs)%s", platform.value, time.monotonic() - started_at, suffix,
@@ -98,11 +102,6 @@ class GatewayAdapterLifecycleMixin:
"✗ %s disconnect timed out after %.1fs - forcing continue%s",
platform.value, timeout, suffix,
)
- except Exception as e:
- logger.error(
- "✗ %s disconnect error after %.2fs%s: %s",
- platform.value, time.monotonic() - started_at, suffix, e,
- )
@staticmethod
def _env_timeout_override(name: str) -> Optional[float]:
@@ -256,12 +255,11 @@ class GatewayAdapterLifecycleMixin:
await self.stop()
def _queue_retryable_best_effort(self, adapter: BasePlatformAdapter, why: str) -> None:
- try:
+ with _log_suppressed(
+ logging.DEBUG, "Failed to queue %s after fatal-handler %s",
+ adapter.platform.value, why, exc_info=True,
+ ):
self._queue_retryable_fatal_platform(adapter)
- except Exception:
- logger.debug(
- "Failed to queue %s after fatal-handler %s", adapter.platform.value, why, exc_info=True,
- )
async def _handle_adapter_fatal_error_impl(self, adapter: BasePlatformAdapter) -> None:
# Snapshot the slot owner first: a stale notification must not overwrite a healthy
@@ -512,10 +510,9 @@ class GatewayAdapterLifecycleMixin:
"""Bounded slow-tier respawn of the reconnect watcher."""
if attempt >= self._MAX_SLOW_WATCHER_RESPAWNS:
logger.error(
- "Reconnect watcher could not be kept alive after %d slow "
- "respawns; %d platform(s) remain queued and unattended: %s. "
- "Manual intervention or a gateway restart is required.", attempt,
- len(self._failed_platforms), ", ".join(str(p) for p in self._failed_platforms),
+ "Reconnect watcher could not be kept alive after %d slow respawns; %d platform(s) remain "
+ "queued and unattended: %s. Manual intervention or a gateway restart is required.",
+ attempt, len(self._failed_platforms), ", ".join(str(p) for p in self._failed_platforms),
)
return
@@ -529,9 +526,8 @@ class GatewayAdapterLifecycleMixin:
):
return
logger.warning(
- "Reconnect watcher still down with %d platform(s) queued — "
- "slow respawn %d/%d", len(self._failed_platforms), attempt + 1,
- self._MAX_SLOW_WATCHER_RESPAWNS,
+ "Reconnect watcher still down with %d platform(s) queued — slow respawn %d/%d",
+ len(self._failed_platforms), attempt + 1, self._MAX_SLOW_WATCHER_RESPAWNS,
)
self._spawn_reconnect_watcher(
on_give_up=lambda _name: self._schedule_slow_reconnect_watcher_respawn(attempt=attempt + 1)
@@ -597,12 +593,10 @@ class GatewayAdapterLifecycleMixin:
queued_for = now - info.get("queued_at", now)
retrying_since_iso = (datetime.now(timezone.utc) - timedelta(seconds=queued_for)).isoformat()
logger.warning(
- "%s has been failing/reconnecting continuously for "
- "%.1f hours (%d attempts) — flagging NEEDS_ATTENTION. "
- "Retries continue, but this usually means a permanent "
- "problem (revoked credentials, missing intents, broken "
- "sidecar). Check `hermes status` / `/platform list`.", platform.value,
- queued_for / 3600.0, info.get("attempts", 0),
+ "%s has been failing/reconnecting continuously for %.1f hours (%d attempts) — flagging "
+ "NEEDS_ATTENTION. Retries continue, but this usually means a permanent problem (revoked "
+ "credentials, missing intents, broken sidecar). Check `hermes status` / `/platform list`.",
+ platform.value, queued_for / 3600.0, info.get("attempts", 0),
)
self._update_platform_runtime_status(
platform.value, platform_state="retrying", needs_attention=True, retrying_since=retrying_since_iso
@@ -707,18 +701,15 @@ class GatewayAdapterLifecycleMixin:
logger.info("✓ %s reconnected successfully", platform.value)
# Final responses rejected while this adapter was down are still owned by this live
# process, so startup recovery cannot claim them. Replay the transient subset now.
- try:
+ with _log_suppressed(
+ logging.DEBUG, "failed-obligation redelivery after %s reconnect failed",
+ platform.value, exc_info=True,
+ ):
await self._redeliver_failed_obligations_for_platform(platform)
- except Exception:
- logger.debug(
- "failed-obligation redelivery after %s reconnect failed", platform.value, exc_info=True,
- )
# Rebuild channel directory with the new adapter
- try:
+ with suppress(Exception):
from gateway.channel_directory import build_channel_directory
await build_channel_directory(self.adapters)
- except Exception:
- pass
# A platform offline at gateway startup never got its restart-interrupted sessions
# auto-resumed — the startup pass skips sessions whose adapter isn't connected yet.
try:
@@ -1221,11 +1212,9 @@ class GatewayAdapterLifecycleMixin:
@staticmethod
def _stamp_event_profile(event, profile_name: str) -> None:
"""Best-effort: stamp ``source.profile`` on an inbound event that has none yet."""
- try:
+ with suppress(Exception):
if getattr(event, "source", None) is not None and not event.source.profile:
event.source.profile = profile_name
- except Exception:
- pass
def _make_profile_message_handler(self, profile_name: str):
"""Message handler that stamps source.profile, then delegates under the profile scope
@@ -1292,13 +1281,11 @@ class GatewayAdapterLifecycleMixin:
async def _handle_gateway_platform_event(self, event: dict, source) -> None:
"""Authorize and publish one normalized adapter event to plugin hooks."""
- try:
+ # Observer failures must never break the adapter's update loop.
+ with _log_suppressed(logging.DEBUG, "gateway_platform_event hook dispatch failed", exc_info=True):
from hermes_cli.lifecycle import has_hook, invoke_hook
if has_hook("gateway_platform_event") and self._is_user_authorized_for_source(source):
invoke_hook("gateway_platform_event", **event)
- except Exception:
- # Observer failures must never break the adapter's update loop.
- logger.debug("gateway_platform_event hook dispatch failed", exc_info=True)
def _make_profile_platform_event_handler(self, profile_name: str):
"""Bind platform-event auth and hook dispatch to one multiplex profile."""
diff --git a/gateway/run_notifications.py b/gateway/run_notifications.py
index d9ca12fe21b..828b386c23f 100644
--- a/gateway/run_notifications.py
+++ b/gateway/run_notifications.py
@@ -105,15 +105,13 @@ class GatewayNotificationsMixin:
)
metadata = self._thread_metadata_for_source(source)
if notice_delivery == "private" and getattr(source, "user_id", None):
- try:
+ with _log_suppressed(
+ logging.DEBUG, "[%s] send_private_notice failed, falling back to public",
+ getattr(source, "platform", "?"), exc_info=True,
+ ):
result = await adapter.send_private_notice(source.chat_id, source.user_id, content, metadata=metadata)
if getattr(result, "success", False):
return
- except Exception:
- logger.debug(
- "[%s] send_private_notice failed, falling back to public",
- getattr(source, "platform", "?"), exc_info=True,
- )
await adapter.send(source.chat_id, content, metadata=metadata)
async def _resolve_compression_lineage_target(
@@ -360,7 +358,7 @@ class GatewayNotificationsMixin:
for path in (paths.claimed, paths.pending):
if not path.exists():
continue
- try:
+ with suppress(Exception):
pending = json.loads(path.read_text(encoding="utf-8"))
platform_str = pending.get("platform")
chat_id = pending.get("chat_id")
@@ -376,8 +374,6 @@ class GatewayNotificationsMixin:
return self._UpdateTarget(
adapter, chat_id, session_key or f"{platform_str}:{chat_id}", metadata, platform,
)
- except Exception:
- pass
return None
def _pending_marker_metadata(self, platform, chat_id, data: dict, adapter):
@@ -486,11 +482,9 @@ class GatewayNotificationsMixin:
def _read_new_output() -> None:
nonlocal buffer, bytes_sent
if paths.output.exists():
- try:
+ with suppress(OSError):
chunk, bytes_sent = self._read_update_output_since(paths.output, bytes_sent)
buffer += chunk
- except OSError:
- pass
while loop.time() < deadline:
if paths.exit_code.exists():
diff --git a/gateway/run_shutdown.py b/gateway/run_shutdown.py
index aefc59568c8..294d74aeabc 100644
--- a/gateway/run_shutdown.py
+++ b/gateway/run_shutdown.py
@@ -407,9 +407,8 @@ class GatewayShutdownMixin:
if not self._scale_to_zero_no_suspend_logged:
self._scale_to_zero_no_suspend_logged = True
logger.info(
- "scale-to-zero: idle, but this platform suspends on "
- "its own timer (no in-machine suspend API); staying "
- "connected rather than quiescing"
+ "scale-to-zero: idle, but this platform suspends on its own timer (no "
+ "in-machine suspend API); staying connected rather than quiescing"
)
continue
logger.info(
@@ -544,9 +543,8 @@ class GatewayShutdownMixin:
platform.value, platform_state="paused", error_code=None, error_message=info["pause_reason"],
)
logger.warning(
- "%s paused after %d consecutive failures (%s) — "
- "fix the underlying issue then run `/platform resume %s` "
- "to retry, or `hermes gateway restart` to restart the gateway.",
+ "%s paused after %d consecutive failures (%s) — fix the underlying issue then run `/platform "
+ "resume %s` to retry, or `hermes gateway restart` to restart the gateway.",
platform.value, info.get("attempts", 0), info["pause_reason"], platform.value,
)
@@ -815,16 +813,14 @@ class GatewayShutdownMixin:
# Suppress ONLY the home-channel broadcast when the drain asked to be quiet (routine fleet
# auto-update); per-session pings above stay (empty on a drained shutdown, useful on a
# force-interrupt). Current-epoch marker only, so an orphaned marker can't silence a fresh gateway.
- try:
+ # Never let the suppression check block the broadcast — fail toward the louder behaviour.
+ with _log_suppressed(logging.DEBUG, "drain_notification_suppressed check failed: %s"):
from gateway.drain_control import drain_notification_suppressed
if drain_notification_suppressed():
logger.info(
"Home-channel shutdown broadcast suppressed by drain marker (suppress_notification=true)"
)
return
- except Exception as e:
- # Never let the suppression check block the broadcast — fail toward the louder behaviour.
- logger.debug("drain_notification_suppressed check failed: %s", e)
# Snapshot adapters: adapter.send() can hit a fatal path (_handle_fatal) that pops the adapter
# from self.adapters -> ``RuntimeError: dictionary changed size during iteration``.
for platform, adapter in list(self.adapters.items()):
@@ -1027,7 +1023,7 @@ class GatewayShutdownMixin:
return 0
suspended = 0
for session_key in [k for k, v in counts.items() if v >= self._STUCK_LOOP_THRESHOLD]:
- try:
+ with suppress(Exception):
entry = self.session_store._entries.get(session_key)
if entry and not entry.suspended:
entry.suspended = True
@@ -1036,8 +1032,6 @@ class GatewayShutdownMixin:
"Auto-suspended stuck session %s (active across %d consecutive restarts — likely a stuck loop)",
session_key, counts[session_key],
)
- except Exception:
- pass
if suspended:
with suppress(Exception):
self.session_store._save()
diff --git a/gateway/run_startup.py b/gateway/run_startup.py
index bdca671c884..1b4849d9a44 100644
--- a/gateway/run_startup.py
+++ b/gateway/run_startup.py
@@ -104,7 +104,10 @@ class GatewayStartupMixin:
"""Initialize turn machinery on an executor thread before the gate opens. Never raises: a
failed warm-up degrades to lazy init and must not block startup."""
from gateway.run import _warm_turn_machinery_sync
- try:
+ with _log_suppressed(
+ logging.WARNING, "Turn-machinery warm-up failed; first inbound turn will initialize lazily",
+ exc_info=True,
+ ):
loop = asyncio.get_running_loop()
t0 = time.monotonic()
tool_count = await loop.run_in_executor(None, _warm_turn_machinery_sync)
@@ -112,10 +115,6 @@ class GatewayStartupMixin:
"Turn machinery warmed in %.1fs (%d tool schema(s) materialized)",
time.monotonic() - t0, tool_count,
)
- except Exception:
- logger.warning(
- "Turn-machinery warm-up failed; first inbound turn will initialize lazily", exc_info=True,
- )
async def _await_startup_warmup(self) -> None:
"""Bounded wait for the boot warm-up. On timeout the gate opens anyway (availability outranks
@@ -326,9 +325,8 @@ class GatewayStartupMixin:
await asyncio.to_thread(mark_delivered, row["obligation_id"])
redelivered += 1
logger.info(
- "Redelivered recovered final response to %s:%s "
- "(obligation %s, attempt %d)", row["platform"], row["chat_id"],
- row["obligation_id"], row["attempts"],
+ "Redelivered recovered final response to %s:%s (obligation %s, attempt %d)",
+ row["platform"], row["chat_id"], row["obligation_id"], row["attempts"],
)
else:
await asyncio.to_thread(
@@ -774,11 +772,10 @@ class GatewayStartupMixin:
os.getenv(v, "").lower() in {"true", "1", "yes"} for v in allow_all_vars
):
logger.warning(
- "No env user allowlists configured. Messaging platforms default to "
- "pairing/allowlist policies and will deny unknown senders unless you "
- "configure platform allowlists (e.g., TELEGRAM_ALLOWED_USERS=your_id) "
- "or explicitly opt in with GATEWAY_ALLOW_ALL_USERS=true plus "
- "dm_policy/group_policy: open on the platform."
+ "No env user allowlists configured. Messaging platforms default to pairing/allowlist "
+ "policies and will deny unknown senders unless you configure platform allowlists (e.g., "
+ "TELEGRAM_ALLOWED_USERS=your_id) or explicitly opt in with GATEWAY_ALLOW_ALL_USERS=true "
+ "plus dm_policy/group_policy: open on the platform."
)
reason = _own_policy_open_startup_violation(self.config)
if reason: