fix(gateway): keep the primary's failed login with the turn and the route that resolved it

The failure found while resolving a turn's route was stashed on the shared runner, so another chat resolving on another thread could clear or replace it before the turn read it, and the sign-in hint went missing or named another session's provider. It now travels in a context variable, which each gateway turn's executor copy keeps to itself.

The failure also survived later steps that move the turn onto another provider (`/model --once`, an API caller's provider, a channel override), so a failure of that route told the user to sign in to the primary. attach_primary_auth_failure now drops it unless the agent runs the backup it names.

Reported-by: greptile-apps[bot]
This commit is contained in:
yoniebans
2026-11-13 23:37:33 +01:00
committed by jonny
parent 9bb39e8f01
commit deb7cc3643
4 changed files with 147 additions and 12 deletions

View File

@@ -9,6 +9,7 @@ the structured reason and the one place that leads a failed turn's copy with it.
from __future__ import annotations
import contextvars
from dataclasses import dataclass
from typing import Any, Optional
@@ -50,9 +51,35 @@ def primary_auth_failure_from_exc(exc: Any, provider: Any, backup: Any = "") ->
def attach_primary_auth_failure(agent: Any, failure: Optional[PrimaryAuthFailure]) -> None:
"""Bind (or clear, with None) the reason on an agent built from a fallback runtime."""
if agent is not None:
agent._primary_auth_failure = failure if isinstance(failure, PrimaryAuthFailure) else None
"""Bind (or clear, with None) the reason on an agent built from a fallback runtime.
The failure belongs to the route that resolution fell back to: when a later step moved the turn
onto another provider (``/model --once``, an API caller's provider, a channel override), the
backup it names is not the one running, so it is dropped rather than blamed on that route."""
if agent is None:
return
if isinstance(failure, PrimaryAuthFailure) and failure.backup:
running = str(getattr(agent, "provider", "") or "").strip().lower()
if running and running != failure.backup.strip().lower():
failure = None
agent._primary_auth_failure = failure if isinstance(failure, PrimaryAuthFailure) else None
# The failure found while resolving this turn's route. A context variable, not a runner attribute: the
# gateway resolves concurrent chats on separate threads, each with its own copied context.
_PENDING: contextvars.ContextVar[Optional[PrimaryAuthFailure]] = contextvars.ContextVar(
"pending_primary_auth_failure", default=None)
def set_pending_primary_auth_failure(failure: Optional[PrimaryAuthFailure]) -> None:
_PENDING.set(failure if isinstance(failure, PrimaryAuthFailure) else None)
def take_pending_primary_auth_failure() -> Optional[PrimaryAuthFailure]:
"""This turn's pending failure, cleared so a later resolution in the same context starts clean."""
failure = _PENDING.get()
_PENDING.set(None)
return failure
# Backup failure reason -> what the backup's problem is, in the user's words.

View File

@@ -59,14 +59,14 @@ def _resolve_policy_agent_runtime(runner, policy, *, fallback=True, record_notic
fallback=fallback)
if fallback_entry is not None:
from hermes_cli.fallback_config import pre_agent_fallback_notice
from agent.primary_auth_fallback import RUNTIME_KEY, set_pending_primary_auth_failure
set_pending_primary_auth_failure(runtime.get(RUNTIME_KEY))
notice = pre_agent_fallback_notice(
provider or '', model or '',
runtime.get('provider') or fallback_entry.get('provider') or 'unknown',
fallback_entry.get('model') or 'default')
if record_notice:
runner._pre_agent_fallback_notice = notice
from agent.primary_auth_fallback import RUNTIME_KEY
runner._pre_agent_primary_auth_failure = runtime.get(RUNTIME_KEY)
return fallback_entry['model'], _runtime_agent_kwargs(runtime)
return model, _runtime_agent_kwargs(runtime)
@@ -209,7 +209,9 @@ class GatewayTurnPrepareMixin:
# turn (#74349). Set again below only when THIS resolution fell back.
if record_notice:
self._pre_agent_fallback_notice = None
self._pre_agent_primary_auth_failure = None
# This turn's context only (each gateway turn runs in its own context copy), so no record_notice gate.
from agent.primary_auth_fallback import set_pending_primary_auth_failure
set_pending_primary_auth_failure(None)
policy = policy_for_source(self, source) if source is not None else None
if policy is not None:
return _resolve_policy_agent_runtime(self, policy, fallback=fallback, record_notice=record_notice)
@@ -272,9 +274,7 @@ class GatewayTurnPrepareMixin:
# runner surfaces it through the agent's one-shot fallback notice (#74349).
notice = runtime_kwargs.pop("_fallback_notice", None)
from agent.primary_auth_fallback import RUNTIME_KEY
primary_auth_failure = runtime_kwargs.pop(RUNTIME_KEY, None)
if record_notice:
self._pre_agent_primary_auth_failure = primary_auth_failure
set_pending_primary_auth_failure(runtime_kwargs.pop(RUNTIME_KEY, None))
runtime_model = runtime_kwargs.pop("model", None)
if runtime_model:
logger.info("Runtime provider supplied explicit model override: %s -> %s", model, runtime_model)

View File

@@ -1386,8 +1386,8 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):
# fallback was resolved before any agent exists (#74349); one-shot per turn.
pending_fallback_notice = getattr(runner, "_pre_agent_fallback_notice", None)
runner._pre_agent_fallback_notice = None
pending_primary_auth = getattr(runner, "_pre_agent_primary_auth_failure", None)
runner._pre_agent_primary_auth_failure = None
from agent.primary_auth_fallback import take_pending_primary_auth_failure
pending_primary_auth = take_pending_primary_auth_failure()
from gateway.session_api_turn import prepare_api_runtime
model, runtime_kwargs = prepare_api_runtime(model, runtime_kwargs)
if policy and policy.model and not pending_fallback_notice:
@@ -1441,7 +1441,8 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):
if pending_fallback_notice:
# Reuse the in-agent one-shot notice so the pre-agent provider switch is user-visible too.
agent._pending_fallback_notice = pending_fallback_notice
# Set every turn (None clears it): a cached agent must not keep a login failure that resolved.
# Set every turn (None clears it): a cached agent must not keep a login failure that resolved, and
# a route replaced after resolution (`/model --once`, an API caller's provider) drops it.
from agent.primary_auth_fallback import attach_primary_auth_failure
attach_primary_auth_failure(agent, pending_primary_auth)
self._wire_turn_agent_callbacks(agent, turn_route, reasoning_config, stream_delta_cb, interim_cb, want_interim)

View File

@@ -0,0 +1,107 @@
"""The primary provider's failed login, found while resolving a gateway turn's route, belongs to that turn.
Drives the production path (``_resolve_session_agent_runtime`` bound to the runner, then
``TurnRunner.run_sync``), as ``test_pre_agent_fallback_notice`` does: another chat resolving its own
route on another thread must not erase or replace this turn's failure, and a later step that swaps
the turn onto a different provider (``/model --once``, an API caller's provider) drops it.
"""
import threading
from types import SimpleNamespace
from unittest.mock import patch
from gateway.session import Platform, SessionSource
from gateway.turn_context import TurnContext
from hermes_cli.auth import AuthError
from tests.gateway.test_pre_agent_fallback_notice import _RecordingAgent, _runner_with_real_runtime_resolution
_FALLBACK = {"provider": "anthropic", "model": "claude-sonnet-5", "api_key": "k", "base_url": "u"}
def _primary_auth_fails(**kw):
if kw.get("requested") is None: # the primary, resolved from config.yaml
raise AuthError("No access token found for Nous Portal", provider="nous")
return dict(_FALLBACK)
def _ctx(agent_cls=None):
return TurnContext(
source=SessionSource(platform=Platform.LOCAL, chat_id="c", user_id="u"),
message="hi", history=[], session_id="sid", session_key="test-session-key", user_config={},
AIAgent=agent_cls or _RecordingAgent, resolve_display_setting=lambda *_a: False, _run_still_current=lambda: True,
_hooks_ref=SimpleNamespace(loaded_hooks=False),
)
def _run(runner, ctx, *extra):
from gateway.run_turn_runner import TurnRunner
patches = [
patch("hermes_cli.runtime_provider.resolve_runtime_provider", side_effect=_primary_auth_fails),
patch("hermes_cli.runtime_provider._get_model_config", return_value={"provider": "nous", "default": "hermes-5"}),
patch("gateway.run._load_gateway_config",
return_value={"fallback_providers": [{"provider": "anthropic", "model": "claude-sonnet-5"}]}),
patch("gateway.run._resolve_gateway_model", return_value="hermes-5"),
patch("gateway.run._get_channel_override", return_value=None),
patch("gateway.run._credential_pool_for_provider", return_value=None),
*extra,
]
for p in patches:
p.start()
try:
TurnRunner(runner, ctx).run_sync()
finally:
for p in reversed(patches):
p.stop()
return ctx.agent_holder[0]
def test_another_chats_resolution_on_another_thread_keeps_this_turns_primary_failure():
runner = _runner_with_real_runtime_resolution()
override = {"model": "gpt-5", "provider": "openrouter", "api_key": "k2", "base_url": "u2"}
# The other chat has a /model override: its resolution takes the fast path, which clears any stash.
runner._peek_session_state.side_effect = lambda *a, **k: (
SimpleNamespace(conversation=SimpleNamespace(model_override=override))
if threading.current_thread().name == "other-chat" else None)
from gateway import run_turn_prepare
real_channel = run_turn_prepare._resolve_channel_runtime
def other_chat_resolves_meanwhile(*args, **kwargs):
other = threading.Thread(target=runner._resolve_session_agent_runtime, name="other-chat",
kwargs={"session_key": "other-key"})
other.start()
other.join(10)
return real_channel(*args, **kwargs)
agent = _run(runner, _ctx(), patch.object(run_turn_prepare, "_resolve_channel_runtime",
side_effect=other_chat_resolves_meanwhile))
failure = agent._primary_auth_failure
assert failure is not None and failure.provider == "nous"
def test_a_route_replaced_after_resolution_drops_the_primary_failure():
"""``/model --once`` moves this turn to another provider: the backup the failure names is not the
route that runs, so a failure of that route must not tell the user to sign in to Nous."""
runner = _runner_with_real_runtime_resolution()
def once_to_openrouter(_turn, _policy, model, runtime_kwargs):
return "gpt-5", {**runtime_kwargs, "provider": "openrouter", "base_url": "https://openrouter.test/v1"}
agent = _run(runner, _ctx(_AgentWithProvider),
patch("gateway.session_cli_turn.one_turn_route", side_effect=once_to_openrouter))
assert agent.provider == "openrouter"
assert agent._primary_auth_failure is None
def test_the_fallback_route_that_runs_keeps_the_primary_failure():
agent = _run(_runner_with_real_runtime_resolution(), _ctx(_AgentWithProvider))
assert agent.provider == "anthropic"
assert agent._primary_auth_failure is not None and agent._primary_auth_failure.backup == "anthropic"
class _AgentWithProvider(_RecordingAgent):
"""The real AIAgent keeps the provider it was built with on ``.provider``."""
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.provider = kwargs.get("provider")