The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(runtime): key-scoped fallback extra_body re-resolution + request_overrides in switch_model snapshot
Teknium3b3ad958d7ec
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.pyindex c518935ce7c..74dc486da2c 100644--- a/agent/agent_runtime_helpers.py+++ b/agent/agent_runtime_helpers.py@@ -3286,6 +3286,11 @@ def switch_model(agent, new_model, new_provider, api_key='', base_url='', api_mo"use_native_cache_layout": agent._use_native_cache_layout,"reasoning_config": dict(agent.reasoning_config) if getattr(agent, "reasoning_config", None) else None,"reasoning_echo_flag": getattr(agent, "_reasoning_echo_flag", False),+ # Request-level overrides (extra_body etc.) must travel with the+ # switched-to identity; without this, a post-switch transport+ # recovery or fallback restore would resurrect the PRE-switch+ # overrides via the stale init-time snapshot (#75091 seam).+ "request_overrides": dict(getattr(agent, "request_overrides", {}) or {}),"compressor_model": getattr(_cc, "model", agent.model) if _cc else agent.model,"compressor_base_url": getattr(_cc, "base_url", agent.base_url) if _cc else agent.base_url,"compressor_api_key": getattr(_cc, "api_key", "") if _cc else "",diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.pyindex 2880bf17a5d..42f186184c7 100644--- a/agent/chat_completion_helpers.py+++ b/agent/chat_completion_helpers.py@@ -2674,6 +2674,7 @@ def try_activate_fallback(agent, reason: "FailoverReason | None" = None) -> boolold_model = agent.modelold_provider = agent.provider+ old_base_url = agent.base_url# Clear the per-config context_length override so the fallback# model's actual context window is resolved instead of inheriting@@ -2843,18 +2844,49 @@ def try_activate_fallback(agent, reason: "FailoverReason | None" = None) -> bool# Keep whatever reasoning_config was active — don't break the fallback swap.# Re-resolve extra_body for the fallback provider (Closes #75091).- # The primary's provider-specific extra_body (e.g. reasoning_effort)- # must not ride along onto the fallback provider, which is a different- # API that may reject those fields. Clear the stale extra_body first,- # then re-resolve from the fallback provider's config.+ # The OLD provider's custom_providers-contributed extra_body (e.g. a+ # vendor-specific reasoning toggle) must not ride along onto the+ # fallback provider, which is a different API that may reject those+ # fields. Removal is KEY-SCOPED: only keys the old provider's+ # custom_providers entry contributed (value unchanged since init)+ # are dropped; the fallback provider's own extra_body is then merged+ # back in. Caller/profile-provided extra_body keys+ # (request_overrides passed at init, which win over provider config+ # per _merge_custom_provider_extra_body precedence) MUST survive the+ # swap untouched.try:- from agent.agent_init import _merge_custom_provider_extra_body+ from agent.agent_init import (+ _custom_provider_extra_body_for_agent,+ _merge_custom_provider_extra_body,+ )_custom_providers = getattr(agent, "_custom_providers", None) or []- # Strip the primary's extra_body so it doesn't contaminate the- # fallback (existing_extra_body in _merge wins on conflict).+ # What did the OLD provider's config contribute?+ _old_provider_eb = _custom_provider_extra_body_for_agent(+ provider=old_provider,+ model=old_model,+ base_url=old_base_url,+ custom_providers=_custom_providers,+ ) or {}_overrides = dict(getattr(agent, "request_overrides", {}) or {})- _overrides.pop("extra_body", None)- agent.request_overrides = _overrides+ _existing_eb = _overrides.get("extra_body")+ if isinstance(_existing_eb, dict) and _old_provider_eb:+ _scrubbed = dict(_existing_eb)+ for _k, _v in _old_provider_eb.items():+ # Drop only keys the old provider contributed: the value+ # must still match what its config injected — a caller+ # override of the same key would have won at init and+ # differ, so it survives. Keys the new provider+ # redefines are re-added with the NEW provider's value+ # by the merge below.+ if _k in _scrubbed and _scrubbed[_k] == _v:+ _scrubbed.pop(_k)+ if _scrubbed:+ _overrides["extra_body"] = _scrubbed+ else:+ _overrides.pop("extra_body", None)+ agent.request_overrides = _overrides+ # Merge in the fallback provider's own extra_body (existing+ # caller-provided keys win on conflict inside the merge helper)._merge_custom_provider_extra_body(agent, _custom_providers)logger.info("Fallback %s: extra_body resolved: %s",diff --git a/tests/run_agent/test_primary_runtime_restore.py b/tests/run_agent/test_primary_runtime_restore.pyindex cc5bcfb5b5f..72ad60dff35 100644--- a/tests/run_agent/test_primary_runtime_restore.py+++ b/tests/run_agent/test_primary_runtime_restore.py@@ -790,3 +790,79 @@ class TestRateLimitCooldown:# second call should not have extended the cooldownassert second_cooldown == first_cooldown+++# =============================================================================+# request_overrides travels through the switch_model snapshot (#75091 seam)+# =============================================================================+++class TestSwitchModelRequestOverridesSnapshot:+ """switch_model rebuilds _primary_runtime; it must carry request_overrides+ so a post-switch transport recovery or fallback restore reinstates the+ switched-to identity's overrides, not a stale or empty set."""++ def _switch(self, agent, **kwargs):+ from agent.agent_runtime_helpers import switch_model++ with (+ patch("run_agent.OpenAI", return_value=MagicMock()),+ patch(+ "agent.model_metadata.get_model_context_length",+ return_value=128_000,+ ),+ ):+ switch_model(+ agent,+ new_model=kwargs.get("new_model", "gpt-4o"),+ new_provider=kwargs.get("new_provider", "openai"),+ base_url=kwargs.get("base_url", "https://api.openai.com/v1"),+ api_key=kwargs.get("api_key", "sk-test-1234567890"),+ )++ def test_switch_snapshot_carries_request_overrides(self):+ overrides = {"extra_body": {"reasoning": {"effort": "high"}}}+ agent = _make_agent(request_overrides=overrides)+ self._switch(agent)+ rt = agent._primary_runtime+ assert rt.get("request_overrides") == overrides+ assert rt["request_overrides"] is not agent.request_overrides++ def test_switch_then_recover_restores_current_overrides(self):+ """After /model switch, a transport recovery must reinstate the+ overrides that were live at switch time — not drop them."""+ overrides = {"extra_body": {"reasoning": {"effort": "high"}}}+ agent = _make_agent(provider="custom", request_overrides=overrides)+ self._switch(+ agent,+ new_model="local-model",+ new_provider="custom",+ base_url="https://my-llm.example.com/v1",+ )+ # A fallback activation mid-turn clobbers the live overrides…+ agent.request_overrides = {"extra_body": {"fallback_only": True}}+ error = _make_transport_error("ReadTimeout")+ with patch("run_agent.OpenAI", return_value=MagicMock()), \+ patch("time.sleep"):+ result = agent._try_recover_primary_transport(+ error, retry_count=3, max_retries=3,+ )+ assert result is True+ # …and recovery restores the switch-time snapshot.+ assert agent.request_overrides == overrides++ def test_switch_then_restore_restores_current_overrides(self):+ overrides = {"extra_body": {"reasoning": {"effort": "high"}}}+ agent = _make_agent(provider="custom", request_overrides=overrides)+ self._switch(+ agent,+ new_model="local-model",+ new_provider="custom",+ base_url="https://my-llm.example.com/v1",+ )+ agent._fallback_activated = True+ agent.request_overrides = {"extra_body": {"fallback_only": True}}+ with patch("run_agent.OpenAI", return_value=MagicMock()):+ result = agent._restore_primary_runtime()+ assert result is True+ assert agent.request_overrides == overridesdiff --git a/tests/run_agent/test_provider_fallback.py b/tests/run_agent/test_provider_fallback.pyindex eaffe66d320..cf6c4f5475d 100644--- a/tests/run_agent/test_provider_fallback.py+++ b/tests/run_agent/test_provider_fallback.py@@ -414,3 +414,91 @@ class TestFallbackChainDedup:assert called == [("xai", "grok-4.5")]assert agent.provider == "xai"assert agent.model == "grok-4.5"+++# ── extra_body re-resolution on fallback activation (#75091) ─────────────+++class TestFallbackExtraBodyReResolution:+ """Fallback activation must re-resolve extra_body key-scoped.++ The old provider's custom_providers-contributed extra_body keys are+ stale on the new backend and must be dropped; caller-provided+ request_overrides keys must survive; the fallback provider's own+ extra_body must be merged in (salvage of #75139).+ """++ OLD_URL = "https://old-llm.example.com/v1"+ FB_URL = "https://fb-llm.example.com/v1"++ def _agent_with_custom_providers(self, caller_extra_body=None):+ agent = _make_agent(+ fallback_model={+ "provider": "custom:fbprov",+ "model": "fb-model",+ "base_url": self.FB_URL,+ },+ )+ agent.provider = "custom"+ agent.model = "old-model"+ agent.base_url = self.OLD_URL+ agent._custom_providers = [+ {+ "name": "oldprov",+ "base_url": self.OLD_URL,+ "extra_body": {"enable_thinking": True, "old_only": 1},+ },+ {+ "provider_key": "fbprov",+ "base_url": self.FB_URL,+ "extra_body": {"top_k": 20},+ },+ ]+ # Simulate the init-time merge: provider extra_body + caller keys+ # (caller wins on conflict — agent_init._merge_custom_provider_extra_body).+ merged = {"enable_thinking": True, "old_only": 1}+ merged.update(caller_extra_body or {})+ agent.request_overrides = {"extra_body": merged}+ return agent++ def _activate(self, agent):+ with patch(+ "agent.auxiliary_client.resolve_provider_client",+ return_value=(_mock_client(base_url=self.FB_URL), "fb-model"),+ ), patch(+ "agent.model_metadata.get_model_context_length",+ return_value=128_000,+ ):+ assert agent._try_activate_fallback() is True++ def test_stale_provider_keys_removed_and_new_provider_merged(self):+ agent = self._agent_with_custom_providers()+ self._activate(agent)+ eb = agent.request_overrides.get("extra_body") or {}+ # Old provider's contributed keys are gone.+ assert "enable_thinking" not in eb+ assert "old_only" not in eb+ # Fallback provider's own extra_body is applied.+ assert eb.get("top_k") == 20++ def test_caller_override_keys_survive_fallback(self):+ agent = self._agent_with_custom_providers(+ caller_extra_body={"reasoning": {"effort": "high"}, "enable_thinking": False},+ )+ self._activate(agent)+ eb = agent.request_overrides.get("extra_body") or {}+ # Pure caller key survives untouched.+ assert eb.get("reasoning") == {"effort": "high"}+ # Caller redefined a key the old provider also set (caller won at+ # init: False != True) — the caller's value must survive key-scoped+ # removal.+ assert eb.get("enable_thinking") is False+ # But the key the old provider alone contributed is dropped.+ assert "old_only" not in eb+ assert eb.get("top_k") == 20++ def test_non_extra_body_overrides_untouched(self):+ agent = self._agent_with_custom_providers()+ agent.request_overrides["temperature"] = 0.2+ self._activate(agent)+ assert agent.request_overrides.get("temperature") == 0.2