Skip to content

The agent that grows with you

fix: restore empty-response fallback retry, dedupe alibaba set, thread TTL into aux replan

kshitijd7517d6e734a
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.py
index 4128da8a1b2..dfcf1806ab4 100644
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@ -1982,6 +1982,25 @@ def prompt_caching_disabled_from_config() -> bool:
return cache_ttl_means_disabled(ttl)
+def configured_cache_ttl() -> Optional[str]:
+ """Return the configured ``prompt_caching.cache_ttl`` tier, if valid.
+
+ Mirrors ``agent_init``'s reading of the same key (``5m``/``1h`` accepted,
+ anything else ignored) so stub-based paths without a live ``AIAgent``
+ (auxiliary fallback replan) stop regressing a configured ``1h`` to the
+ 5m default (#84733). Returns ``None`` for unset/disabled/unknown values;
+ ``effective_cache_ttl`` resolves ``None`` to ``5m`` downstream.
+ """
+ try:
+ from hermes_cli.config import load_config_readonly
+
+ pc_cfg = load_config_readonly().get("prompt_caching", {}) or {}
+ ttl = pc_cfg.get("cache_ttl", "5m")
+ except Exception:
+ return None
+ return ttl if ttl in ("5m", "1h") else None
+
+
def blank_cache_policy_stub(cache_disabled: Optional[bool] = None):
"""Build the destination-identity-blank stub for ``anthropic_prompt_cache_policy``.
@@ -2066,7 +2085,11 @@ def plan_cache_sections_for_destination(
messages,
tools,
cache_ttl=effective_cache_ttl(
- cache_ttl or "5m",
+ # effective_cache_ttl resolves None → "5m"; markers are only
+ # emitted at all when should_cache passed above, so a
+ # cache-disabled agent (_cache_ttl=None) never reaches here
+ # with caching active.
+ cache_ttl,
provider=provider,
model=model,
),
@@ -2270,9 +2293,12 @@ def anthropic_prompt_cache_policy(
# format that cache markers produce (content becomes a block array
# instead of a plain string), causing HTTP 400 (#77217).
model_is_qwen = "qwen" in model_lower
- provider_is_alibaba_family = provider_lower in {
- "opencode", "opencode-zen", "opencode-go", "alibaba",
- }
+ # Single source of truth for the family set — shared with the
+ # effective_cache_ttl clamp so the opt-in and the TTL clamp can
+ # never desync (#84733).
+ from agent.prompt_caching import ALIBABA_FAMILY_PROVIDERS
+
+ provider_is_alibaba_family = provider_lower in ALIBABA_FAMILY_PROVIDERS
if provider_is_alibaba_family and model_is_qwen:
# Envelope layout (native_anthropic=False): markers on inner
# content parts, not top-level tool messages. Matches
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py
index c04c99215b5..5532d5eab1f 100644
--- a/agent/auxiliary_client.py
+++ b/agent/auxiliary_client.py
@@ -4904,7 +4904,10 @@ def _replan_synchronous_cache_sections(
destination: _FallbackDestination,
) -> tuple[list, list]:
"""Strip source decoration and plan one synchronous destination locally."""
- from agent.agent_runtime_helpers import plan_cache_sections_for_destination
+ from agent.agent_runtime_helpers import (
+ configured_cache_ttl,
+ plan_cache_sections_for_destination,
+ )
return plan_cache_sections_for_destination(
messages,
@@ -4913,6 +4916,12 @@ def _replan_synchronous_cache_sections(
base_url=destination.base_url,
api_mode=destination.api_mode or "",
model=destination.model or "",
+ # Thread the operator's configured tier so auxiliary fallback
+ # requests stop regressing a configured 1h to the 5m default
+ # (#84733); the planner clamps per-destination (Qwen → 5m). There
+ # is no live agent here, so read the same config key agent_init
+ # snapshots into agent._cache_ttl.
+ cache_ttl=configured_cache_ttl(),
)
diff --git a/agent/conversation_loop.py b/agent/conversation_loop.py
index 3cdac5a1f2d..28560ae62da 100644
--- a/agent/conversation_loop.py
+++ b/agent/conversation_loop.py
@@ -7308,13 +7308,16 @@ def run_conversation(
"now using %s on %s",
agent.model, agent.provider,
)
- # Failover shrank the compressor's context window to
- # the fallback's; restart the outer iteration so the
- # pre-API preflight re-runs against the new threshold
- # before the first fallback call (#84733).
+ # This site sits directly in the OUTER iteration
+ # loop (not the retry loop), so `continue` already
+ # restarts the iteration and re-runs the pre-API
+ # preflight against the fallback's context window
+ # (#84733). A `break` here would exit the outer
+ # loop and end the turn without ever calling the
+ # fallback. Clear the preflight block so the
+ # re-run isn't skipped.
_preflight_compression_blocked = False
- _retry.restart_with_rebuilt_messages = True
- break
+ continue
# Exhausted retries and fallback chain (or no
# fallback configured). Fall through to the
diff --git a/agent/moa_loop.py b/agent/moa_loop.py
index a34808106eb..a55b29af29c 100644
--- a/agent/moa_loop.py
+++ b/agent/moa_loop.py
@@ -464,7 +464,9 @@ def _maybe_apply_moa_cache_control(
return apply_anthropic_cache_control(
messages,
cache_ttl=effective_cache_ttl(
- cache_ttl or "5m",
+ # effective_cache_ttl resolves None → "5m"; the should_cache
+ # gate above already returned for cache-disabled routes.
+ cache_ttl,
provider=runtime.get("provider") or "",
model=runtime.get("model") or "",
),
diff --git a/agent/prompt_caching.py b/agent/prompt_caching.py
index b56591ea5ad..2ef50d5aca2 100644
--- a/agent/prompt_caching.py
+++ b/agent/prompt_caching.py
@@ -120,10 +120,11 @@ def _build_marker(ttl: str) -> Dict[str, str]:
return marker
-# Routes whose context cache documents a five-minute window (renewed on
-# hit) and rejects the Anthropic 1h tier. Kept in parity with the
-# alibaba-family set in agent_runtime_helpers.anthropic_prompt_cache_policy.
-_QWEN_1H_UNSUPPORTED_PROVIDERS = frozenset({
+# Alibaba-family providers (Qwen routes). Their context cache documents a
+# five-minute window (renewed on hit) and rejects the Anthropic 1h tier.
+# Shared with agent_runtime_helpers.anthropic_prompt_cache_policy so the
+# cache-policy opt-in and the TTL clamp can never desync (#84733).
+ALIBABA_FAMILY_PROVIDERS = frozenset({
"opencode",
"opencode-zen",
"opencode-go",
@@ -151,7 +152,7 @@ def effective_cache_ttl(
return ttl or "5m"
if "qwen" in (model or "").lower():
return "5m"
- if (provider or "").lower() in _QWEN_1H_UNSUPPORTED_PROVIDERS:
+ if (provider or "").lower() in ALIBABA_FAMILY_PROVIDERS:
return "5m"
return "1h"
diff --git a/tests/agent/test_failover_identity.py b/tests/agent/test_failover_identity.py
index 0a7d0af828b..2f4485a6602 100644
--- a/tests/agent/test_failover_identity.py
+++ b/tests/agent/test_failover_identity.py
@@ -58,6 +58,7 @@ def _cache_agent(
static=None,
cache_ttl="5m",
provider="openai",
+ model="gpt-4o",
tools=None,
direct_tool_cache=False,
):
@@ -69,6 +70,7 @@ def _cache_agent(
_use_native_cache_layout=native,
_cache_ttl=cache_ttl,
provider=provider,
+ model=model,
tools=tools or [],
_direct_native_anthropic_tool_cache_capability=lambda: direct_tool_cache,
client=None,
diff --git a/tests/agent/test_prompt_cache_ttl_propagation.py b/tests/agent/test_prompt_cache_ttl_propagation.py
index 5a9c3e20650..683b7ce7124 100644
--- a/tests/agent/test_prompt_cache_ttl_propagation.py
+++ b/tests/agent/test_prompt_cache_ttl_propagation.py
@@ -177,19 +177,56 @@ class TestFailoverRestartsPreflight:
"""#84733: a fallback provider switch must re-run the pre-API preflight.
``_try_activate_fallback`` already shrinks the compressor's context
- window to the fallback's; the old ``continue`` re-fired the request
- without re-running the pre-API pressure check. Every activation site
- must instead ``break`` to the ``restart_with_rebuilt_messages`` handler,
- which restarts the outer iteration (and its preflight) via a budget
- refund. Source-level guard: importing the module and parsing the
- function is cheap, and the assertion encodes the bug class — a new
- failover site added with ``continue`` fails here on purpose.
+ window to the fallback's; the pre-API preflight runs at the top of the
+ OUTER iteration loop, before the retry loop. So the restart discipline
+ is loop-aware:
+
+ - Sites INSIDE the retry loop (``while retry_count < max_retries``)
+ must ``break`` out of it with ``restart_with_rebuilt_messages`` set,
+ so the handler after the retry loop refunds the budget and
+ ``continue``s the outer iteration (which re-runs the preflight).
+ A plain ``continue`` there would only re-fire the retry loop and
+ skip the preflight — the original bug.
+ - Sites DIRECTLY in the outer loop must ``continue`` — the next outer
+ iteration re-runs the preflight already. A ``break`` there would
+ exit the conversation loop and end the turn without ever calling
+ the just-activated fallback.
+
+ Source-level guard: parsing the function is cheap, and the assertion
+ encodes the bug class — a new failover site added with the wrong
+ restart statement for its loop fails here on purpose.
"""
- def test_every_fallback_activation_breaks_to_repreflight(self):
+ def test_every_fallback_activation_restarts_preflight(self):
from agent import conversation_loop
tree = ast.parse(inspect.getsource(conversation_loop.run_conversation))
+
+ # Parent map so each site can be bound to its nearest enclosing loop.
+ parents = {}
+ for node in ast.walk(tree):
+ for child in ast.iter_child_nodes(node):
+ parents[child] = node
+
+ retry_loops = [
+ node
+ for node in ast.walk(tree)
+ if isinstance(node, ast.While)
+ and isinstance(node.test, ast.Compare)
+ and isinstance(node.test.left, ast.Name)
+ and node.test.left.id == "retry_count"
+ ]
+ assert retry_loops, "expected the retry loop in run_conversation"
+ retry_loop_ids = {id(loop) for loop in retry_loops}
+
+ def _inside_retry_loop(node):
+ cur = parents.get(node)
+ while cur is not None:
+ if id(cur) in retry_loop_ids:
+ return True
+ cur = parents.get(cur)
+ return False
+
fallback_ifs = [
node
for node in ast.walk(tree)
@@ -200,8 +237,80 @@ class TestFailoverRestartsPreflight:
]
assert fallback_ifs, "expected _try_activate_fallback sites in run_conversation"
for node in fallback_ifs:
- assert any(isinstance(stmt, ast.Break) for stmt in node.body), (
- "fallback activation must break to the restart-with-rebuilt-"
- "messages handler so the pre-API preflight re-runs against "
- "the fallback's context window (#84733)"
+ if _inside_retry_loop(node):
+ assert any(isinstance(stmt, ast.Break) for stmt in node.body), (
+ "retry-loop fallback activation must break to the "
+ "restart-with-rebuilt-messages handler so the pre-API "
+ "preflight re-runs against the fallback's context "
+ "window (#84733)"
+ )
+ else:
+ assert any(
+ isinstance(stmt, ast.Continue) for stmt in node.body
+ ), (
+ "outer-loop fallback activation must continue the outer "
+ "iteration (which re-runs the preflight); a break here "
+ "would end the turn without calling the fallback (#84733)"
+ )
+ assert not any(
+ isinstance(stmt, ast.Break) for stmt in node.body
+ ), (
+ "outer-loop fallback activation must not break — that "
+ "exits the conversation loop and ends the turn (#84733)"
+ )
+
+
+class TestAuxFallbackReplanThreadsTtl:
+ """#84733 follow-up: the auxiliary fallback replan path threads the
+ configured tier too — it has no live agent, so it reads the same
+ config key agent_init snapshots into ``agent._cache_ttl``."""
+
+ def test_configured_cache_ttl_reads_valid_tiers(self, monkeypatch):
+ import agent.agent_runtime_helpers as arh
+
+ monkeypatch.setattr(
+ "hermes_cli.config.load_config_readonly",
+ lambda: {"prompt_caching": {"cache_ttl": "1h"}},
+ )
+ assert arh.configured_cache_ttl() == "1h"
+ monkeypatch.setattr(
+ "hermes_cli.config.load_config_readonly",
+ lambda: {"prompt_caching": {"cache_ttl": "5m"}},
+ )
+ assert arh.configured_cache_ttl() == "5m"
+
+ def test_configured_cache_ttl_none_for_disabled_or_unknown(self, monkeypatch):
+ import agent.agent_runtime_helpers as arh
+
+ for value in ("off", False, None, "2h"):
+ monkeypatch.setattr(
+ "hermes_cli.config.load_config_readonly",
+ lambda value=value: {"prompt_caching": {"cache_ttl": value}},
)
+ assert arh.configured_cache_ttl() is None, value
+
+ def test_replan_threads_configured_ttl_to_markers(self, monkeypatch):
+ from agent import auxiliary_client
+
+ monkeypatch.setattr(
+ "hermes_cli.config.load_config_readonly",
+ lambda: {"prompt_caching": {"cache_ttl": "1h"}},
+ )
+ destination = auxiliary_client._FallbackDestination(
+ "anthropic",
+ "https://api.anthropic.com",
+ "anthropic_messages",
+ "claude-opus-4.8",
+ )
+ messages = [
+ {"role": "system", "content": "You are helpful."},
+ {"role": "user", "content": "hello"},
+ ]
+ out_msgs, _ = auxiliary_client._replan_synchronous_cache_sections(
+ messages, None, destination=destination
+ )
+ markers = _collect_cache_controls(out_msgs)
+ assert markers, "expected cache_control markers on a caching route"
+ assert all(m.get("ttl") == "1h" for m in markers), (
+ "the configured 1h tier must reach auxiliary fallback replans"
+ )