Skip to content

The agent that grows with you

fix(gateway): live foreign token lock at startup exits 78 instead of retry-queueing forever

Teknium6879a621b1da
diff --git a/gateway/restart.py b/gateway/restart.py
index 986b5a4fee3..58e6d15cebd 100644
--- a/gateway/restart.py
+++ b/gateway/restart.py
@@ -16,6 +16,25 @@ GATEWAY_SERVICE_RESTART_EXIT_CODE = 75
# restarting the gateway. See #51228.
GATEWAY_FATAL_CONFIG_EXIT_CODE = 78
+
+def is_global_startup_conflict(error_code: str | None) -> bool:
+ """Return True when an adapter's fatal error is a single-writer ownership conflict.
+
+ ``BasePlatformAdapter._acquire_platform_lock`` emits ``{scope}_lock``
+ with ``retryable=True`` on purpose: a *mid-run* reconnect must be able to
+ recover once the live holder exits or a stale record is cleared (#54167).
+ At startup, though, a live foreign holder is a configuration conflict —
+ two gateways cannot poll one bot token — so the startup router must not
+ treat that flag as "transient blip, retry-queue forever". This matches by
+ error CODE only (the ``{scope}_lock`` / ``lock_conflict`` families every
+ adapter emits for scoped-lock and identity conflicts), never by message
+ text.
+ """
+ code = (error_code or "").strip().lower()
+ if not code:
+ return False
+ return code == "lock_conflict" or code.endswith("_lock")
+
# Set by ``hermes gateway run --external-supervisor``. Unlike systemd's
# INVOCATION_ID and launchd's XPC_SERVICE_NAME, this survives wrappers that
# intentionally replace the child environment (for example ``sudo env -i``).
diff --git a/gateway/run.py b/gateway/run.py
index 5ff6322e222..27057ff85dd 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -3064,6 +3064,7 @@ from gateway.restart import (
DEFAULT_GATEWAY_SIGNAL_INTERRUPT_GRACE_TIMEOUT,
GATEWAY_FATAL_CONFIG_EXIT_CODE,
GATEWAY_SERVICE_RESTART_EXIT_CODE,
+ is_global_startup_conflict,
parse_cron_drain_timeout,
parse_restart_after_turn_timeout,
parse_restart_drain_timeout,
@@ -14100,20 +14101,30 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
# Python logs "Unclosed client session" at process exit.
await self._safe_adapter_disconnect(adapter, platform)
if adapter.has_fatal_error:
+ # A live foreign holder of this bot token / identity is
+ # a single-writer ownership conflict, not a transient
+ # blip — even though ``_acquire_platform_lock`` emits it
+ # retryable so a MID-RUN reconnect can recover (#54167).
+ # At startup route it as non-retryable: with nothing
+ # connected the gateway exits 78 instead of sitting alive
+ # and deaf in the retry queue forever (#83183).
+ _retryable = adapter.fatal_error_retryable and not (
+ is_global_startup_conflict(adapter.fatal_error_code)
+ )
self._update_platform_runtime_status(
platform.value,
- platform_state="retrying" if adapter.fatal_error_retryable else "fatal",
+ platform_state="retrying" if _retryable else "fatal",
error_code=adapter.fatal_error_code,
error_message=adapter.fatal_error_message,
)
target = (
startup_retryable_errors
- if adapter.fatal_error_retryable
+ if _retryable
else startup_nonretryable_errors
)
target.append(f"{platform.value}: {adapter.fatal_error_message}")
# Queue for reconnection if the error is retryable
- if adapter.fatal_error_retryable:
+ if _retryable:
self._failed_platforms[platform] = {
"config": platform_config,
"attempts": 1,
@@ -17058,6 +17069,26 @@ class GatewayRunner(GatewayAuthorizationMixin, GatewayKanbanWatchersMixin, Gatew
"""
if not getattr(adapter, "fatal_error_retryable", True):
return
+ if is_global_startup_conflict(getattr(adapter, "fatal_error_code", None)):
+ # Same startup contract as the primary path: a live foreign holder
+ # of this profile's token/identity is an ownership conflict, not
+ # a transient blip. Park it fatal (like ``duplicate_credential``)
+ # instead of retry-storming the token every backoff (#83183).
+ logger.error(
+ "[MULTIPLEX] Profile '%s': %s credential is held by another "
+ "gateway (%s) — parked, not retried. %s",
+ profile_name,
+ platform.value,
+ adapter.fatal_error_code,
+ adapter.fatal_error_message or "",
+ )
+ self._update_platform_runtime_status(
+ f"{profile_name}:{platform.value}",
+ platform_state="fatal",
+ error_code=adapter.fatal_error_code,
+ error_message=adapter.fatal_error_message,
+ )
+ return
async def _await_running_then_schedule() -> None:
if self._running:
diff --git a/tests/gateway/test_multiplex_adapter_registry.py b/tests/gateway/test_multiplex_adapter_registry.py
index 3d0c196cbfa..20292492491 100644
--- a/tests/gateway/test_multiplex_adapter_registry.py
+++ b/tests/gateway/test_multiplex_adapter_registry.py
@@ -435,6 +435,55 @@ class TestSecondaryStartupFailureRecovery:
assert runner._background_tasks == set()
assert runner._profile_failed_platforms == {}
+ @pytest.mark.asyncio
+ async def test_token_lock_initial_failure_parks_fatal_not_retried(
+ self, monkeypatch
+ ):
+ """Salvage of #83183 claim 2: a secondary whose token is held by a live
+ foreign gateway (``{scope}_lock``, emitted retryable by
+ ``_acquire_platform_lock``) is an ownership conflict — park it fatal
+ like ``duplicate_credential`` instead of retry-storming the token."""
+ runner = _secondary_recovery_runner()
+ failed = _SecondaryRecoveryAdapter()
+ failed.fatal_error_code = "discord-bot-token_lock"
+ failed.fatal_error_message = "Discord bot token already in use (PID 4242)."
+ _install_secondary_reconnect_context(
+ monkeypatch, runner, _SecondaryRecoveryAdapter()
+ )
+ monkeypatch.setattr(runner, "_create_adapter", lambda platform, config: failed)
+ statuses = []
+ monkeypatch.setattr(
+ runner,
+ "_update_platform_runtime_status",
+ lambda key, **kw: statuses.append((key, kw)),
+ )
+
+ async def fail_initial_connect(adapter, platform):
+ return False
+
+ monkeypatch.setattr(
+ runner, "_connect_initial_adapter_with_timeout", fail_initial_connect
+ )
+
+ connected = await runner._start_one_profile_adapters(
+ "reviewer", "/tmp/reviewer", {}
+ )
+
+ assert connected == 0
+ assert failed.disconnected is True
+ assert runner._background_tasks == set()
+ assert runner._profile_failed_platforms == {}
+ assert statuses == [
+ (
+ "reviewer:discord",
+ {
+ "platform_state": "fatal",
+ "error_code": "discord-bot-token_lock",
+ "error_message": failed.fatal_error_message,
+ },
+ )
+ ]
+
@pytest.mark.asyncio
async def test_handoff_failure_is_logged_not_raised(self, monkeypatch, caplog):
"""If the scheduler raises at bridge handoff, the parked task must not
diff --git a/tests/gateway/test_runner_startup_failures.py b/tests/gateway/test_runner_startup_failures.py
index 68fbfdf1624..c3f906f1717 100644
--- a/tests/gateway/test_runner_startup_failures.py
+++ b/tests/gateway/test_runner_startup_failures.py
@@ -3,11 +3,31 @@ from unittest.mock import AsyncMock
from gateway.config import GatewayConfig, Platform, PlatformConfig
from gateway.platforms.base import BasePlatformAdapter
-from gateway.restart import GATEWAY_FATAL_CONFIG_EXIT_CODE
+from gateway.restart import GATEWAY_FATAL_CONFIG_EXIT_CODE, is_global_startup_conflict
from gateway.run import GatewayRunner
from gateway.status import read_runtime_status
+ "code, expected",
+ [
+ ("telegram-bot-token_lock", True), # BasePlatformAdapter._acquire_platform_lock
+ ("discord-bot-token_lock", True),
+ ("whatsapp-session_lock", True),
+ ("feishu_app_lock", True),
+ ("lock_conflict", True), # buzz / irc / line identity conflicts
+ ("telegram_connect_error", False),
+ ("telegram_auth_error", False),
+ ("relay_membership_required", False),
+ ("duplicate_credential", False),
+ ("", False),
+ (None, False),
+ ],
+)
+def test_is_global_startup_conflict_matches_lock_code_families(code, expected):
+ assert is_global_startup_conflict(code) is expected
+
+
class _RetryableFailureAdapter(BasePlatformAdapter):
def __init__(self):
super().__init__(PlatformConfig(enabled=True, token="***"), Platform.TELEGRAM)
@@ -443,3 +463,115 @@ async def test_start_gateway_propagates_fatal_config_exit_code(monkeypatch, tmp_
await start_gateway(config=GatewayConfig(), replace=False, verbosity=0)
assert exc_info.value.code == GATEWAY_FATAL_CONFIG_EXIT_CODE
+
+
+class _ForeignTokenLockAdapter(BasePlatformAdapter):
+ """Connects exactly like telegram/discord do: production
+ ``_acquire_platform_lock`` first, which emits ``{scope}_lock`` with
+ ``retryable=True`` (so a mid-run reconnect can recover, #54167)."""
+
+ def __init__(self):
+ super().__init__(PlatformConfig(enabled=True, token="***"), Platform.TELEGRAM)
+
+ async def connect(self, *, is_reconnect: bool = False) -> bool:
+ return self._acquire_platform_lock(
+ "telegram-bot-token", self.config.token, "Telegram bot token"
+ )
+
+ async def disconnect(self) -> None:
+ self._release_platform_lock()
+ self._mark_disconnected()
+
+ async def send(self, chat_id, content, reply_to=None, metadata=None):
+ raise NotImplementedError
+
+ async def get_chat_info(self, chat_id):
+ return {"id": chat_id}
+
+
+async def test_live_foreign_token_lock_at_startup_exits_ex_config(monkeypatch, tmp_path):
+ """Salvage of #83183 claim 1: a LIVE foreign holder of the bot token at
+ zero-connected startup is a single-writer conflict, not a transient blip.
+
+ ``_acquire_platform_lock`` deliberately emits the conflict retryable so a
+ *mid-run* reconnect can recover once the holder exits. The startup router
+ used to key solely off that flag, so the gateway stayed alive, deaf, and
+ retry-queued forever instead of exiting 78 (EX_CONFIG)."""
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setenv("HERMES_GATEWAY_LOCK_DIR", str(tmp_path / "locks"))
+ # A live foreign holder: acquire_scoped_lock reports (False, record).
+ monkeypatch.setattr(
+ "gateway.status.acquire_scoped_lock",
+ lambda scope, identity, metadata=None: (
+ False,
+ {"pid": 424242, "start_time": 1, "hermes_home": "/other/home", "profile": "other"},
+ ),
+ )
+ config = GatewayConfig(
+ platforms={Platform.TELEGRAM: PlatformConfig(enabled=True, token="***")},
+ sessions_dir=tmp_path / "sessions",
+ )
+ runner = GatewayRunner(config)
+ monkeypatch.setattr(
+ runner, "_create_adapter", lambda platform, platform_config: _ForeignTokenLockAdapter()
+ )
+
+ ok = await runner.start()
+
+ assert ok is True
+ assert runner.should_exit_cleanly is True
+ assert runner.exit_code == GATEWAY_FATAL_CONFIG_EXIT_CODE
+ assert runner._failed_platforms == {}
+ state = read_runtime_status()
+ assert state["gateway_state"] == "startup_failed"
+ assert state["platforms"]["telegram"]["state"] == "fatal"
+ assert state["platforms"]["telegram"]["error_code"] == "telegram-bot-token_lock"
+
+
+async def test_token_lock_plus_retryable_peer_stays_alive(monkeypatch, tmp_path):
+ """A lock conflict alongside a genuinely transient peer failure is the
+ NS-609 mixed mode: the lock is parked fatal, the peer keeps its retry, and
+ the gateway stays alive (no exit 78)."""
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setenv("HERMES_GATEWAY_LOCK_DIR", str(tmp_path / "locks"))
+ monkeypatch.setattr(
+ "gateway.status.acquire_scoped_lock",
+ lambda scope, identity, metadata=None: (False, {"pid": 424242, "start_time": 1}),
+ )
+ config = GatewayConfig(
+ platforms={
+ Platform.TELEGRAM: PlatformConfig(enabled=True, token="***"),
+ Platform.DISCORD: PlatformConfig(enabled=True, token="***"),
+ },
+ sessions_dir=tmp_path / "sessions",
+ )
+ runner = GatewayRunner(config)
+
+ class _DiscordBlip(_RetryableFailureAdapter):
+ def __init__(self):
+ BasePlatformAdapter.__init__(
+ self, PlatformConfig(enabled=True, token="***"), Platform.DISCORD
+ )
+
+ monkeypatch.setattr(
+ runner,
+ "_create_adapter",
+ lambda platform, cfg: (
+ _ForeignTokenLockAdapter() if platform is Platform.TELEGRAM else _DiscordBlip()
+ ),
+ )
+
+ ok = await runner.start()
+ try:
+ assert ok is True
+ assert runner.should_exit_cleanly is False
+ assert runner.exit_code is None
+ assert set(runner._failed_platforms) == {Platform.DISCORD}
+ state = read_runtime_status()
+ assert state["gateway_state"] == "running"
+ assert state["platforms"]["telegram"]["state"] == "fatal"
+ assert state["platforms"]["discord"]["state"] == "retrying"
+ finally:
+ await runner.stop()
diff --git a/website/docs/developer-guide/gateway-internals.md b/website/docs/developer-guide/gateway-internals.md
index 30c8cb9e1f0..a96c3d930d3 100644
--- a/website/docs/developer-guide/gateway-internals.md
+++ b/website/docs/developer-guide/gateway-internals.md
@@ -191,6 +191,8 @@ Adapters implement a common interface:
Adapters that connect with unique credentials call `acquire_scoped_lock()` in `connect()` and `release_scoped_lock()` in `disconnect()`. This prevents two profiles from using the same bot token simultaneously.
+A lock conflict is emitted as `{scope}_lock` with `retryable=True` so a **mid-run** reconnect can recover once the other holder exits. At **startup**, though, a live foreign holder is a configuration conflict: `gateway/restart.py::is_global_startup_conflict()` recognizes the `*_lock` / `lock_conflict` code families and the startup router parks the platform `fatal` instead of retry-queueing it. With nothing else connected the gateway exits `78` (`EX_CONFIG`, `gateway_state=startup_failed`) so the supervisor stops restarting it; alongside a genuinely transient peer failure the gateway stays alive and only the peer retries.
+
## Delivery Path
Outgoing deliveries (`gateway/delivery.py`) handle: