The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): a channel_overrides model no longer evicts the cached agent after every turn
EloquentBrush0x1df1f1341754
diff --git a/gateway/run_turn.py b/gateway/run_turn.pyindex bd4f47bf3bf..f8587a0debd 100644--- a/gateway/run_turn.py+++ b/gateway/run_turn.py@@ -3598,7 +3598,17 @@ class GatewayTurnMixin:_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- _cfg_model = _resolve_gateway_model()+ 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):diff --git a/tests/gateway/test_model_switch_persistence.py b/tests/gateway/test_model_switch_persistence.pyindex b6b198c17e5..ac0a1ddbd0d 100644--- a/tests/gateway/test_model_switch_persistence.py+++ b/tests/gateway/test_model_switch_persistence.py@@ -17,7 +17,7 @@ from unittest.mock import AsyncMock, MagicMockimport pytest-from gateway.config import GatewayConfig, Platform, PlatformConfig+from gateway.config import ChannelOverride, GatewayConfig, Platform, PlatformConfigfrom gateway.session import SessionEntry, SessionSource, build_session_key@@ -165,6 +165,37 @@ class TestIsIntentionalModelSwitch:assert runner._is_intentional_model_switch(sk, agent, "primary/model") is False+class TestFallbackEvictionHonorsChannelOverrides:+ """A ``channel_overrides`` model is the configured model for that chat, so an agent still running it+ after a successful turn is not a fallback; comparing it with the global default evicted (and rebuilt)+ the cached agent after every turn."""++ @staticmethod+ def _evicted_after_turn(monkeypatch, source, agent_model):+ from gateway.turn_context import TurnContext++ monkeypatch.setattr("gateway.run._resolve_gateway_model", lambda *a, **k: "default/model")+ runner = _make_runner()+ runner.config.platforms[Platform.TELEGRAM].channel_overrides = {"c1": ChannelOverride(model="chan/model")}+ 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")+ ctx.result_holder[0] = {"final_response": "ok"}+ runner._run_agent_evict_on_fallback(ctx)+ return runner._evict_cached_agent.called++ @pytest.mark.parametrize("thread_of_the_channel", [False, True])+ def test_channel_override_model_keeps_the_cached_agent(self, monkeypatch, thread_of_the_channel):+ source = _make_source()+ if thread_of_the_channel:+ source = SessionSource(platform=Platform.TELEGRAM, user_id="u1", chat_id="t9", parent_chat_id="c1",+ user_name="tester", chat_type="thread")+ assert self._evicted_after_turn(monkeypatch, source, "chan/model") is False++ def test_fallback_off_the_channel_model_still_evicts(self, monkeypatch):+ assert self._evicted_after_turn(monkeypatch, _make_source(), "fallback/model") is True++class TestOneTurnModelOverrideRestore:"""Verify gateway one-turn overrides restore previous session state."""