Skip to content

The agent that grows with you

fix(fallback): surface provider transitions and primary recovery

Ailirag5908c577f904
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.py
index 9ef90d4bcfe..c7f0f5dacb8 100644
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@ -1604,6 +1604,19 @@ def restore_primary_runtime(agent) -> bool:
agent._restore_wait_logged = False
rt = agent._primary_runtime
+ fallback_route = getattr(agent, "_provider_fallback_route", None)
+ if (
+ isinstance(fallback_route, (list, tuple))
+ and len(fallback_route) == 2
+ ):
+ previous_model = str(fallback_route[0] or "unknown")
+ previous_provider = str(fallback_route[1] or "unknown")
+ else:
+ previous_model = str(getattr(agent, "model", "") or "unknown")
+ previous_provider = str(getattr(agent, "provider", "") or "unknown")
+ provider_fallback_active = bool(
+ getattr(agent, "_provider_fallback_active", False)
+ )
try:
# ── Core runtime state ──
agent.model = rt["model"]
@@ -1792,6 +1805,18 @@ def restore_primary_runtime(agent) -> bool:
"Primary runtime restored for new turn: %s (%s)",
agent.model, agent.provider,
)
+ agent._provider_fallback_active = False
+ agent._provider_fallback_route = None
+ if provider_fallback_active:
+ try:
+ agent._emit_status(
+ f"✅ Primary model restored: {agent.model} via {agent.provider}; "
+ f"fallback {previous_model} via {previous_provider} is no longer active."
+ )
+ except Exception:
+ # Notification surfaces are best-effort and must never undo a
+ # successful runtime restoration.
+ pass
return True
except Exception as e:
logger.warning("Failed to restore primary runtime: %s", e)
@@ -3105,6 +3130,8 @@ def switch_model(agent, new_model, new_provider, api_key='', base_url='', api_mo
# ── Reset fallback state ──
agent._fallback_activated = False
+ agent._provider_fallback_active = False
+ agent._provider_fallback_route = None
agent._fallback_index = 0
# When the user deliberately swaps primary providers (e.g. openrouter
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.py
index 1917a2ede2e..e63e28f3bd3 100644
--- a/agent/chat_completion_helpers.py
+++ b/agent/chat_completion_helpers.py
@@ -2423,6 +2423,41 @@ def _fallback_entry_unavailable_without_network(agent, fb: dict) -> Optional[str
return None
+def _fallback_reason_text(reason: "FailoverReason | None") -> str:
+ """Return a concise operator-facing explanation for a fallback switch."""
+ if reason is None:
+ return "provider failure"
+ labels = {
+ FailoverReason.auth: "authentication failed",
+ FailoverReason.auth_permanent: "authentication permanently failed",
+ FailoverReason.billing: "billing or quota exhausted",
+ FailoverReason.rate_limit: "rate limit",
+ FailoverReason.upstream_rate_limit: "upstream model rate limit",
+ FailoverReason.overloaded: "provider overloaded",
+ FailoverReason.server_error: "provider server error",
+ FailoverReason.timeout: "request timeout",
+ FailoverReason.ssl_cert_verification: "TLS certificate verification failed",
+ FailoverReason.context_overflow: "context window exceeded",
+ FailoverReason.payload_too_large: "request payload too large",
+ FailoverReason.image_too_large: "image payload too large",
+ FailoverReason.model_not_found: "model not found",
+ FailoverReason.provider_policy_blocked: "provider policy blocked the request",
+ FailoverReason.content_policy_blocked: "content policy blocked the request",
+ FailoverReason.format_error: "request format rejected",
+ FailoverReason.invalid_encrypted_content: "encrypted reasoning state rejected",
+ FailoverReason.multimodal_tool_content_unsupported: "multimodal tool content unsupported",
+ FailoverReason.thinking_signature: "thinking signature rejected",
+ FailoverReason.long_context_tier: "long-context tier unavailable",
+ FailoverReason.oauth_long_context_beta_forbidden: "OAuth long-context beta unavailable",
+ FailoverReason.llama_cpp_grammar_pattern: "grammar pattern rejected",
+ FailoverReason.unknown: "provider failure",
+ }
+ label = labels.get(reason)
+ if label:
+ return label
+ value = getattr(reason, "value", None)
+ return str(value or reason or "provider failure").replace("_", " ")
+
def try_activate_fallback(agent, reason: "FailoverReason | None" = None) -> bool:
"""Switch to the next fallback model/provider in the chain.
@@ -2814,20 +2849,26 @@ def try_activate_fallback(agent, reason: "FailoverReason | None" = None) -> bool
# answering, so "what model are you?" doesn't report the primary.
rewrite_prompt_model_identity(agent, fb_model, fb_provider)
- agent._buffer_status(
- f"🔄 Primary model failed — switching to fallback: "
- f"{fb_model} via {fb_provider}"
- )
- # The buffered line above is dropped on successful recovery, but a
- # provider/model switch is a durable state change operators must see
- # even when the fallback succeeds. Record a one-shot notice that the
- # success path surfaces exactly once via _emit_pending_fallback_notice
- # (see run_agent.py); it is discarded on terminal failure since the
- # buffered line is flushed instead. See fallback-observability fix.
- agent._pending_fallback_notice = (
- f"🔄 Switched to fallback model: {old_model} via {old_provider} "
- f"→ {fb_model} via {fb_provider}"
+ notice = (
+ f"⚠️ Model fallback: {old_model} via {old_provider} unavailable "
+ f"({_fallback_reason_text(reason)}); using {fb_model} via {fb_provider}."
)
+ # The buffered switch is surfaced on terminal failure. A successful
+ # fallback clears retry chatter, so retain every switch as a durable
+ # one-shot notice for _emit_pending_fallback_notice (run_agent.py).
+ agent._buffer_status(notice)
+ pending = getattr(agent, "_pending_fallback_notice", None)
+ if isinstance(pending, list):
+ pending.append(notice)
+ elif pending:
+ agent._pending_fallback_notice = [str(pending), notice]
+ else:
+ agent._pending_fallback_notice = [notice]
+ # ``_fallback_activated`` is also reused by temporary `/model --once`
+ # restoration. Keep separate provenance so the restore path only emits
+ # a fallback-recovery notice after an actual provider fallback.
+ agent._provider_fallback_active = True
+ agent._provider_fallback_route = (str(fb_model), str(fb_provider))
logger.info(
"Fallback activated: %s → %s (%s)",
old_model, fb_model, fb_provider,
diff --git a/run_agent.py b/run_agent.py
index d55b473e182..6cfa4fe8fd5 100644
--- a/run_agent.py
+++ b/run_agent.py
@@ -1205,7 +1205,14 @@ class AIAgent:
# Clear before emitting so a (swallowed) callback error can't
# leave the notice set for a stale re-emit on a later turn.
self._pending_fallback_notice = None
- self._emit_status(notice)
+ notices = notice if isinstance(notice, list) else [notice]
+ for item in notices:
+ try:
+ self._emit_status(str(item))
+ except Exception:
+ # A single surface callback failure must not hide later
+ # switches from the same fallback chain.
+ continue
except Exception:
# Never break the conversation loop on a notice hiccup.
pass
diff --git a/tests/run_agent/test_primary_runtime_restore.py b/tests/run_agent/test_primary_runtime_restore.py
index 7592adf654b..a3344f4f658 100644
--- a/tests/run_agent/test_primary_runtime_restore.py
+++ b/tests/run_agent/test_primary_runtime_restore.py
@@ -155,6 +155,76 @@ class TestRestorePrimaryRuntime:
assert agent.model == original_model
assert agent.provider == original_provider
+ def test_emits_user_visible_primary_restore_notice(self):
+ agent = _make_agent(
+ fallback_model={"provider": "openrouter", "model": "anthropic/claude-sonnet-4"},
+ )
+ agent.model = "primary-model"
+ agent._primary_runtime["model"] = "primary-model"
+ original_model = agent.model
+ original_provider = agent.provider
+ mock_client = _mock_resolve()
+ with patch(
+ "agent.auxiliary_client.resolve_provider_client",
+ return_value=(mock_client, None),
+ ):
+ assert agent._try_activate_fallback() is True
+
+ emitted = []
+ agent._emit_status = emitted.append
+ with patch("run_agent.OpenAI", return_value=MagicMock()):
+ assert agent._restore_primary_runtime() is True
+
+ assert emitted == [
+ f"✅ Primary model restored: {original_model} via {original_provider}; "
+ "fallback anthropic/claude-sonnet-4 via openrouter is no longer active."
+ ]
+
+ def test_does_not_label_temporary_model_restore_as_fallback_recovery(self):
+ """`/model --once` reuses restore with no provider fallback lifecycle."""
+ agent = _make_agent()
+ agent.model = "temporary-model"
+ agent.provider = "openrouter"
+ agent._fallback_activated = True
+ emitted = []
+ agent._emit_status = emitted.append
+
+ with patch("run_agent.OpenAI", return_value=MagicMock()):
+ assert agent._restore_primary_runtime() is True
+
+ assert emitted == []
+
+ def test_restore_retry_preserves_fallback_identity_after_partial_failure(self):
+ agent = _make_agent(
+ fallback_model={"provider": "openrouter", "model": "anthropic/claude-sonnet-4"},
+ )
+ agent.model = "primary-model"
+ agent._primary_runtime["model"] = "primary-model"
+ mock_client = _mock_resolve()
+ with patch(
+ "agent.auxiliary_client.resolve_provider_client",
+ return_value=(mock_client, None),
+ ):
+ assert agent._try_activate_fallback() is True
+
+ emitted = []
+ agent._emit_status = emitted.append
+ with (
+ patch("run_agent.OpenAI", return_value=MagicMock()),
+ patch.object(
+ agent.context_compressor,
+ "update_model",
+ side_effect=[RuntimeError("transient restore failure"), None],
+ ),
+ ):
+ assert agent._restore_primary_runtime() is False
+ assert agent._restore_primary_runtime() is True
+
+ assert emitted == [
+ "✅ Primary model restored: primary-model via custom; "
+ "fallback anthropic/claude-sonnet-4 via openrouter is no longer active."
+ ]
+
def test_resets_fallback_index(self):
"""After restore, the full fallback chain should be available again."""
agent = _make_agent(
diff --git a/tests/run_agent/test_provider_fallback.py b/tests/run_agent/test_provider_fallback.py
index 4faeb2b5592..eaffe66d320 100644
--- a/tests/run_agent/test_provider_fallback.py
+++ b/tests/run_agent/test_provider_fallback.py
@@ -7,6 +7,10 @@ advancement through multiple providers.
from unittest.mock import MagicMock, patch
+import pytest
+
+from agent import chat_completion_helpers
+from agent.error_classifier import FailoverReason
from run_agent import AIAgent, _pool_may_recover_from_rate_limit
@@ -68,6 +72,28 @@ class TestFallbackChainInit:
# ── Chain advancement ─────────────────────────────────────────────────────
+ ("reason", "expected"),
+ [
+ (FailoverReason.auth, "authentication failed"),
+ (FailoverReason.billing, "billing or quota exhausted"),
+ (FailoverReason.rate_limit, "rate limit"),
+ (FailoverReason.upstream_rate_limit, "upstream model rate limit"),
+ (FailoverReason.overloaded, "provider overloaded"),
+ (FailoverReason.server_error, "provider server error"),
+ (FailoverReason.timeout, "request timeout"),
+ (FailoverReason.model_not_found, "model not found"),
+ (FailoverReason.unknown, "provider failure"),
+ ],
+)
+def test_fallback_reason_text_is_operator_friendly(reason, expected):
+ assert chat_completion_helpers._fallback_reason_text(reason) == expected
+
+
+def test_fallback_reason_text_defaults_when_reason_is_missing():
+ assert chat_completion_helpers._fallback_reason_text(None) == "provider failure"
+
+
class TestFallbackChainAdvancement:
def test_exhausted_returns_false(self):
agent = _make_agent(fallback_model=None)
@@ -86,8 +112,51 @@ class TestFallbackChainAdvancement:
assert agent.model == "gpt-4o"
assert agent._fallback_activated is True
+ def test_records_user_visible_switch_with_reason(self):
+ agent = _make_agent(
+ fallback_model={"provider": "zai", "model": "glm-5.2"},
+ )
+ agent.model = "gpt-5.6-sol"
+ agent.provider = "openai-codex"
+ with patch(
+ "agent.auxiliary_client.resolve_provider_client",
+ return_value=(_mock_client(base_url="https://api.z.ai/v1"), "glm-5.2"),
+ ):
+ assert agent._try_activate_fallback(FailoverReason.rate_limit) is True
-
+ expected = (
+ "⚠️ Model fallback: gpt-5.6-sol via openai-codex unavailable "
+ "(rate limit); using glm-5.2 via zai."
+ )
+ assert agent._pending_fallback_notice == [expected]
+ assert agent._retry_status_buffer[-1] == ("status", expected)
+
+ def test_records_sequential_switches_in_order(self):
+ agent = _make_agent(
+ fallback_model=[
+ {"provider": "zai", "model": "glm-5.2"},
+ {"provider": "deepseek", "model": "deepseek-v4-flash"},
+ ],
+ )
+ agent.model = "gpt-5.6-sol"
+ agent.provider = "openai-codex"
+ clients = [
+ _mock_client(base_url="https://api.z.ai/v1"),
+ _mock_client(base_url="https://api.deepseek.com/v1"),
+ ]
+ with patch(
+ "agent.auxiliary_client.resolve_provider_client",
+ side_effect=[(clients[0], "glm-5.2"), (clients[1], "deepseek-v4-flash")],
+ ):
+ assert agent._try_activate_fallback(FailoverReason.rate_limit) is True
+ assert agent._try_activate_fallback(FailoverReason.overloaded) is True
+
+ assert agent._pending_fallback_notice == [
+ "⚠️ Model fallback: gpt-5.6-sol via openai-codex unavailable "
+ "(rate limit); using glm-5.2 via zai.",
+ "⚠️ Model fallback: glm-5.2 via zai unavailable "
+ "(provider overloaded); using deepseek-v4-flash via deepseek.",
+ ]
def test_skips_unconfigured_provider_to_next(self):
"""If resolve_provider_client returns None, skip to next in chain."""
fbs = [
diff --git a/tests/run_agent/test_retry_status_buffer.py b/tests/run_agent/test_retry_status_buffer.py
index fca885bc768..dabbde0f495 100644
--- a/tests/run_agent/test_retry_status_buffer.py
+++ b/tests/run_agent/test_retry_status_buffer.py
@@ -152,6 +152,35 @@ def test_pending_fallback_notice_emitted_once_on_success():
assert emitted == ["🔄 Switched to fallback model: m1 via p1 → m2 via p2"]
+def test_pending_fallback_notice_emits_all_switches_in_order():
+ agent = _make_bare_agent()
+ emitted = []
+ agent._emit_status = emitted.append
+ agent._pending_fallback_notice = ["primary → fallback-1", "fallback-1 → fallback-2"]
+
+ agent._emit_pending_fallback_notice()
+
+ assert emitted == ["primary → fallback-1", "fallback-1 → fallback-2"]
+ assert agent._pending_fallback_notice is None
+
+
+def test_pending_fallback_notice_continues_after_callback_error():
+ agent = _make_bare_agent()
+ attempted = []
+ agent._pending_fallback_notice = ["first", "second"]
+
+ def emit(message):
+ attempted.append(message)
+ if message == "first":
+ raise RuntimeError("surface unavailable")
+
+ agent._emit_status = emit
+ agent._emit_pending_fallback_notice()
+
+ assert attempted == ["first", "second"]
+ assert agent._pending_fallback_notice is None
+
+
def test_pending_fallback_notice_noop_when_unset():
"""No fallback this turn → no notice emitted on the success path."""
agent = _make_bare_agent()
diff --git a/tests/run_agent/test_switch_model_fallback_prune.py b/tests/run_agent/test_switch_model_fallback_prune.py
index c5178f8f8a7..a01a60348c4 100644
--- a/tests/run_agent/test_switch_model_fallback_prune.py
+++ b/tests/run_agent/test_switch_model_fallback_prune.py
@@ -78,6 +78,20 @@ def test_switch_with_empty_chain_stays_empty():
assert agent._fallback_model is None
+def test_manual_switch_clears_provider_fallback_provenance():
+ agent = _make_agent([
+ {"provider": "openrouter", "model": "x-ai/grok-4"},
+ {"provider": "nous", "model": "hermes-4"},
+ ])
+ agent._provider_fallback_active = True
+ agent._provider_fallback_route = ("fallback-model", "fallback-provider")
+
+ _switch_to_anthropic(agent)
+
+ assert agent._provider_fallback_active is False
+ assert agent._provider_fallback_route is None
+
+
def test_switch_within_same_provider_preserves_chain():