The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(cache): never-raising scope resolver shared by both call sites
kshitije3fab0437ee5
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.pyindex 6c645c17dd4..ad6d0f1320c 100644--- a/agent/chat_completion_helpers.py+++ b/agent/chat_completion_helpers.py@@ -581,15 +581,16 @@ def _provider_preferences_for_agent(agent) -> Dict[str, Any]:def _prompt_cache_scope_for_agent(agent) -> "str | None":"""Rotation-stable logical cache scope for *agent*, or None.- Thin guard around ``agent.prompt_cache_scope.resolve_prompt_cache_scope``- — the transports treat a None/empty value as "fall back to the physical+ Guarded-import wrapper over the never-raising+ ``agent.prompt_cache_scope.resolve_prompt_cache_scope_safe`` — the+ transports treat a None/empty value as "fall back to the physicalsession_id", so any resolution failure degrades to pre-#79017 behaviorinstead of blocking the request build."""try:- from agent.prompt_cache_scope import resolve_prompt_cache_scope+ from agent.prompt_cache_scope import resolve_prompt_cache_scope_safe- return resolve_prompt_cache_scope(agent) or None+ return resolve_prompt_cache_scope_safe(agent)except Exception:logger.debug("prompt-cache scope resolution failed", exc_info=True)return Nonediff --git a/agent/prompt_cache_scope.py b/agent/prompt_cache_scope.pyindex 6d23e3d9547..b39fb29672c 100644--- a/agent/prompt_cache_scope.py+++ b/agent/prompt_cache_scope.py@@ -106,3 +106,20 @@ def resolve_prompt_cache_scope(agent: Any) -> str:# unmemoized.passreturn scope+++def resolve_prompt_cache_scope_safe(agent: Any) -> Optional[str]:+ """Never-raising variant of :func:`resolve_prompt_cache_scope`.++ Returns None on any failure (or when there is no scope). Consumers treat+ None/empty as "fall back to the physical session_id", so a resolution+ failure degrades to pre-#79017 behavior instead of blocking the caller —+ important at turn_context's call site, where an exception raised inside+ the ``set_runtime_main(...)`` argument list would otherwise skip the whole+ runtime binding, not just the cache scope.+ """+ try:+ return resolve_prompt_cache_scope(agent) or None+ except Exception:+ logger.debug("prompt-cache scope resolution failed", exc_info=True)+ return Nonediff --git a/agent/turn_context.py b/agent/turn_context.pyindex 0998ae22130..a4b2f14c272 100644--- a/agent/turn_context.py+++ b/agent/turn_context.py@@ -485,7 +485,17 @@ def build_turn_context(# after primary restoration has settled the runtime.try:from agent.auxiliary_client import set_runtime_main- from agent.prompt_cache_scope import resolve_prompt_cache_scope+ from agent.prompt_cache_scope import resolve_prompt_cache_scope_safe+ # Rotation-stable prompt-cache scope. Memoized per segment on the+ # agent, so this is a DB walk at most once per segment — except a+ # brand-new session whose row lands later in turn setup+ # (_ensure_db_session); that first turn falls back to the physical+ # id here and the first build_api_kwargs re-resolves. Stays valid+ # through a mid-turn compression rotation because the lineage root+ # is by definition rotation-invariant (#79017). Resolved with the+ # never-raising variant OUTSIDE the argument list, so a resolution+ # failure can only lose the scope — never the whole runtime binding.+ _cache_scope = resolve_prompt_cache_scope_safe(agent) or ""set_runtime_main(getattr(agent, "provider", "") or "",getattr(agent, "model", "") or "",@@ -495,14 +505,7 @@ def build_turn_context(api_mode=getattr(agent, "api_mode", "") or "",auth_mode=getattr(agent, "auth_mode", "") or "",session_id=getattr(agent, "session_id", "") or "",- # Rotation-stable prompt-cache scope. Memoized per segment on the- # agent, so this is a DB walk at most once per segment — except a- # brand-new session whose row lands later in turn setup- # (_ensure_db_session); that first turn falls back to the physical- # id here and the first build_api_kwargs re-resolves. Stays valid- # through a mid-turn compression rotation because the lineage root- # is by definition rotation-invariant (#79017).- cache_scope=resolve_prompt_cache_scope(agent),+ cache_scope=_cache_scope,)except Exception:passdiff --git a/tests/agent/test_prompt_cache_scope.py b/tests/agent/test_prompt_cache_scope.pyindex c7147fa9b55..d7c9765ba6b 100644--- a/tests/agent/test_prompt_cache_scope.py+++ b/tests/agent/test_prompt_cache_scope.py@@ -191,6 +191,19 @@ class TestResolvePromptCacheScope:assert resolve_prompt_cache_scope(_agent("sess-y", WeirdDB())) == "sess-y"+ def test_safe_variant_never_raises(self):+ from agent.prompt_cache_scope import resolve_prompt_cache_scope_safe++ class ExplodingAgent:+ @property+ def session_id(self):+ raise RuntimeError("hostile property")++ assert resolve_prompt_cache_scope_safe(ExplodingAgent()) is None+ # Normal path still resolves through to the plain variant.+ assert resolve_prompt_cache_scope_safe(_agent("sess-ok")) == "sess-ok"+ assert resolve_prompt_cache_scope_safe(_agent("")) is None+class TestRotationContinuityEndToEnd:"""The acceptance shape from #79017: same conversation, same key."""