Skip to content

The agent that grows with you

fix(gateway): measure fallback drift from the session's winning model on its primary route

unsupportedpastels0dbaf33f67ac
diff --git a/gateway/run_agent_cache.py b/gateway/run_agent_cache.py
index 0c16754eb0a..5be523d3fc5 100644
--- a/gateway/run_agent_cache.py
+++ b/gateway/run_agent_cache.py
@@ -257,6 +257,38 @@ class GatewayAgentCacheMixin:
# ordinary drift and still evicts.
return getattr(agent, "_nous_model_switch", None) == (config_model, agent.model)
+ def _fallback_baseline_model(self, session_key: str, source: Optional[SessionSource], agent: Any) -> str:
+ """The model *agent* was built to run, for the post-turn fallback check: what
+ ``_resolve_session_agent_runtime`` chose (session /model, then channel_overrides on the chat,
+ thread or parent, then the global model), canonicalized as ``AIAgent.__init__`` did on the
+ agent's PRIMARY route. The route a fallback moved it to would make that fallback look primary."""
+ from gateway.run import _resolve_gateway_model
+ primary = getattr(agent, "_primary_runtime", None) or {}
+ provider = primary.get("provider", getattr(agent, "provider", "")) or ""
+ # An override whose provider was unavailable this turn ran on the default route instead.
+ override = self._session_model_override(session_key) or {}
+ if override.get("model") and override.get("provider") in (None, "", provider):
+ model = override["model"]
+ elif source is not None:
+ model = self._resolve_model_for_channel(
+ source.platform, str(source.chat_id) if source.chat_id else "",
+ thread_id=str(source.thread_id) if getattr(source, "thread_id", None) else None,
+ parent_id=str(source.parent_chat_id) if getattr(source, "parent_chat_id", None) else None,
+ )
+ else:
+ model = _resolve_gateway_model()
+ # Vendor prefix stripped on native providers, else the cached agent is evicted every turn,
+ # destroying prompt caching.
+ with suppress(Exception):
+ from hermes_cli.model_normalize import _AGGREGATOR_PROVIDERS, normalize_model_for_provider
+ if provider and provider not in _AGGREGATOR_PROVIDERS:
+ model = normalize_model_for_provider(model, provider)
+ # The Nous welcome host runs its one model whatever the chat configured (pin_model_for_route).
+ with suppress(Exception):
+ from hermes_cli.anon_auth import pin_model_for_route
+ model = pin_model_for_route(provider, primary.get("base_url", getattr(agent, "base_url", None)), model)
+ return model
+
def _release_running_agent_state(
self, session_key: str, *, run_generation: Optional[int] = None
) -> bool:
diff --git a/gateway/run_turn.py b/gateway/run_turn.py
index 089a632d29c..ad82ba2cf69 100644
--- a/gateway/run_turn.py
+++ b/gateway/run_turn.py
@@ -3592,40 +3592,16 @@ class GatewayTurnMixin:
"""Evict the cached agent when a fallback model activated on a SUCCESSFUL run (so /model shows
the active model and the next message retries the primary). Skip failed runs: evicting
would loop bad model → fallback → evict → recreate."""
- from gateway.run import _resolve_gateway_model
session_key = turn_ctx.session_key
_agent = turn_ctx.agent_holder[0]
_result_for_fb = turn_ctx.result_holder[0]
if _agent is None or not hasattr(_agent, 'model') or (_result_for_fb and _result_for_fb.get("failed")):
return
- source = turn_ctx.source
- if source is not None:
- # A channel_overrides model is this chat's configured model (the lookup
- # _resolve_session_agent_runtime uses), not a fallback.
- _cfg_model = self._resolve_model_for_channel(
- source.platform, str(source.chat_id) if source.chat_id else "",
- thread_id=str(source.thread_id) if getattr(source, "thread_id", None) else None,
- parent_id=str(source.parent_chat_id) if getattr(source, "parent_chat_id", None) else None,
- )
- else:
- _cfg_model = _resolve_gateway_model()
- # Normalize as AIAgent.__init__ does (vendor prefix stripped on native providers), else the
- # cached agent is evicted every turn, destroying prompt caching.
- with suppress(Exception):
- from hermes_cli.model_normalize import _AGGREGATOR_PROVIDERS, normalize_model_for_provider
- _agent_provider = getattr(_agent, 'provider', '') or ''
- if _agent_provider and _agent_provider not in _AGGREGATOR_PROVIDERS:
- _cfg_model = normalize_model_for_provider(_cfg_model, _agent_provider)
- # AIAgent.__init__ also pins the Nous welcome host to its one model (pin_model_for_route), whatever
- # the chat configured. Apply it on the PRIMARY route: a fallback that lands on that host is drift.
- _primary_route = getattr(_agent, '_primary_runtime', None) or {}
- with suppress(Exception):
- from hermes_cli.anon_auth import pin_model_for_route
- _cfg_model = pin_model_for_route(
- _primary_route.get("provider", getattr(_agent, 'provider', None)),
- _primary_route.get("base_url", getattr(_agent, 'base_url', None)),
- _cfg_model,
- )
+ # A provider fallback is drift even when it serves the configured model name on another endpoint.
+ if getattr(_agent, "_provider_fallback_active", False) is True:
+ self._evict_cached_agent(session_key)
+ return
+ _cfg_model = self._fallback_baseline_model(session_key, turn_ctx.source, _agent)
if _agent.model != _cfg_model and not self._is_intentional_model_switch(session_key, _agent, _cfg_model):
self._evict_cached_agent(session_key)
diff --git a/tests/gateway/test_model_switch_persistence.py b/tests/gateway/test_model_switch_persistence.py
index fcd4342fed2..20a5e68f4bc 100644
--- a/tests/gateway/test_model_switch_persistence.py
+++ b/tests/gateway/test_model_switch_persistence.py
@@ -171,12 +171,19 @@ class TestFallbackEvictionHonorsChannelOverrides:
the cached agent after every turn."""
@staticmethod
- def _evicted_after_turn(monkeypatch, source, agent_model, *, global_model="default/model", **agent_attrs):
+ def _evicted_after_turn(
+ monkeypatch, source, agent_model, *, global_model="default/model", channel_model="chan/model",
+ session_model=None, session_provider="nous", **agent_attrs,
+ ):
from gateway.turn_context import TurnContext
monkeypatch.setattr("gateway.run._resolve_gateway_model", lambda *a, **k: global_model)
runner = _make_runner()
- runner.config.platforms[Platform.TELEGRAM].channel_overrides = {"c1": ChannelOverride(model="chan/model")}
+ runner.config.platforms[Platform.TELEGRAM].channel_overrides = {"c1": ChannelOverride(model=channel_model)}
+ if session_model:
+ runner._session_model_overrides[build_session_key(source)] = {
+ "model": session_model, "provider": session_provider,
+ }
runner._evict_cached_agent = MagicMock()
ctx = TurnContext(source=source, session_key=build_session_key(source))
ctx.agent_holder[0] = SimpleNamespace(model=agent_model, **({"provider": "openrouter"} | agent_attrs))
@@ -222,6 +229,43 @@ class TestFallbackEvictionHonorsChannelOverrides:
_primary_runtime={"provider": "openrouter", "base_url": "https://openrouter.ai/api/v1"},
) is True
+ @pytest.mark.parametrize("agent_model, session_provider, switch, evicted", [
+ ("backing/model", "nous", ("nous/welcome", "backing/model"), False), # the server's recorded move
+ ("chan/model", "nous", None, True), # a fallback that happens to land on the channel's model
+ # The override's provider was unavailable, so this turn ran on the channel's model.
+ ("chan/model", "openai-codex", None, False),
+ ], ids=["recorded-switch-off-the-session-model", "fallback-onto-the-channel-model", "override-unavailable"])
+ def test_a_session_model_override_outranks_the_channel_model(
+ self, monkeypatch, agent_model, session_provider, switch, evicted,
+ ):
+ """The agent was built on the session's /model choice, so drift is measured from it."""
+ assert self._evicted_after_turn(
+ monkeypatch, _make_source(), agent_model, global_model="backing/model", session_model="nous/welcome",
+ session_provider=session_provider, provider="nous", base_url="https://inference-api.nousresearch.com/v1",
+ **({"_nous_model_switch": switch} if switch else {}),
+ ) is evicted
+
+ @pytest.mark.parametrize("session_model", [None, "chan/model"], ids=["channel-model", "session-model"])
+ def test_a_provider_fallback_serving_the_configured_model_still_evicts(self, monkeypatch, session_model):
+ """Same model name, different endpoint: the model strings match, but the turn ran on a fallback."""
+ route = {"provider": "custom", "base_url": "https://primary.example/v1"}
+ assert self._evicted_after_turn(
+ monkeypatch, _make_source(), "chan/model", session_model=session_model, session_provider="custom",
+ provider="custom", base_url="https://fallback.example/v1", _primary_runtime=route,
+ _provider_fallback_active=True,
+ ) is True
+
+ @pytest.mark.parametrize("primary_provider, evicted", [
+ ("anthropic", False), # native primary: the agent runs the prefix-stripped channel model
+ ("openrouter", True), # OpenRouter primary that fell back to native Anthropic
+ ])
+ def test_the_channel_model_is_normalized_for_the_primary_provider(self, monkeypatch, primary_provider, evicted):
+ assert self._evicted_after_turn(
+ monkeypatch, _make_source(), "claude-sonnet-4-6", channel_model="anthropic/claude-sonnet-4.6",
+ provider="anthropic", base_url="https://api.anthropic.com",
+ _primary_runtime={"provider": primary_provider},
+ ) is evicted
+
class TestOneTurnModelOverrideRestore:
"""Verify gateway one-turn overrides restore previous session state."""