Skip to content

The agent that grows with you

fix(cache): honor the host-declared conversation key on the affinity-key path

joaomarcos65672e3a9399
diff --git a/agent/portal_tags.py b/agent/portal_tags.py
index ecfecdc6c57..453ba1bbfbc 100644
--- a/agent/portal_tags.py
+++ b/agent/portal_tags.py
@@ -56,6 +56,48 @@ _conversation_id: ContextVar[Optional[str]] = ContextVar(
)
+# ── Ambient routing/affinity scope ───────────────────────────────────────────
+#
+# Separate from the conversation id above, which is an ATTRIBUTION value: it
+# names the conversation a request belongs to and is sent to the Portal as
+# ``conversation=<id>``. The affinity scope is a ROUTING value — OpenRouter's
+# sticky ``session_id``, Nous Portal's sticky key and xAI's ``x-grok-conv-id``
+# use it to pin one conversation to one backend/prompt cache.
+#
+# The two agree for every host that keeps one session id per conversation, so
+# the providers historically read the attribution id for both. They diverge
+# for a host that mints one physical session per RESPONSE: attribution still
+# resolves per row, while routing must follow the key the host declared for
+# the whole chat (``agent.prompt_cache_scope.declared_conversation_scope``,
+# issue #96811). Only that declared value is published here — unset means
+# "no declaration", and consumers fall back to the conversation id exactly as
+# before, so delegate trees keep sharing their parent's sticky key.
+_affinity_scope: ContextVar[Optional[str]] = ContextVar(
+ "hermes_affinity_scope", default=None
+)
+
+
+def set_affinity_scope(scope: Optional[str]):
+ """Publish the declared routing/affinity scope for this turn.
+
+ Returns the ContextVar token; pair with :func:`reset_affinity_scope`.
+ """
+ return _affinity_scope.set(scope or None)
+
+
+def reset_affinity_scope(token) -> None:
+ """Restore the previous affinity scope (pair with ``set_affinity_scope``)."""
+ try:
+ _affinity_scope.reset(token)
+ except Exception:
+ _affinity_scope.set(None)
+
+
+def get_affinity_scope() -> Optional[str]:
+ """Return the declared routing/affinity scope, or ``None`` when unset."""
+ return _affinity_scope.get()
+
+
def set_conversation_context(conversation_id: Optional[str]):
"""Publish the active conversation id for ambient Portal tagging.
diff --git a/agent/prompt_cache_scope.py b/agent/prompt_cache_scope.py
index b39fb29672c..8aa45bbd3f6 100644
--- a/agent/prompt_cache_scope.py
+++ b/agent/prompt_cache_scope.py
@@ -28,6 +28,36 @@ intentionally different — do not "deduplicate" them.
timestamp is stripped later by ``_cache_scope_from_session_id`` exactly as
before.
+A host that mints one physical ``session_id`` per RESPONSE (Hermes Studio's
+group chat, and ``POST /v1/responses`` with client-managed history, which
+mints ``str(uuid4())`` per request) re-keys every conversation-affinity hint
+Hermes sends — ``prompt_cache_key`` on both OpenAI-wire transports, plus the
+OpenRouter/Nous sticky ``session_id`` and xAI's ``x-grok-conv-id`` through
+``portal_tags`` (issue #96811). Those rows carry no lineage, so the walk
+above correctly returns the physical id and the scope moves every reply.
+
+Hermes must not infer the logical conversation from the id's SYNTAX (that
+rule collides independent client-supplied ids and merges Studio members
+truncated past its 96-character boundary — the #79017 failure class). The
+host has to declare it, and one carrier already means exactly that:
+``gateway_session_key`` — the "stable per-chat key" (``agent:main:telegram:
+dm:123``) built by ``gateway.session.build_session_key`` from the
+``X-Hermes-Session-Key`` header, which branching deliberately does NOT key
+off. ``declared_conversation_scope()`` consumes it, and it wins over the
+lineage walk because it is stable across rotation AND across per-response
+ids. Two boundaries it must not cross:
+
+- explicit fork children (``/branch``, delegate subagents, tool children)
+ share their parent's chat key but are separate conversations — the row's
+ fork markers keep them on their own scope (#79161);
+- background-review forks run on a clone of the live runtime, so they are
+ excluded by ``_persist_disabled`` for the same reason.
+
+The declared key is hashed into ``gwk_<sha256[:24]>`` before it becomes a
+scope: unlike a session id it embeds platform/chat/user identifiers, and
+this value leaves the process verbatim as OpenRouter's sticky ``session_id``
+and xAI's ``x-grok-conv-id``.
+
The resolution is memoized per (agent, session_id): the lineage walk runs
once per transcript segment — NOT per API call — and re-runs only when
rotation actually changes ``agent.session_id`` (per the no-DB-on-the-hot-path
@@ -35,12 +65,15 @@ constraint recorded on #79017). Default installs compact in place and never
rotate, so they hit the memo forever and behave byte-identically to before.
"""
+import hashlib
import logging
from typing import Any, Optional
logger = logging.getLogger(__name__)
_MEMO_ATTR = "_prompt_cache_scope_memo"
+# Namespace for a scope resolved from a host-declared conversation key.
+_DECLARED_SCOPE_PREFIX = "gwk_"
def _lineage_root(session_id: str, session_db: Any) -> Optional[str]:
@@ -64,12 +97,47 @@ def _lineage_root(session_id: str, session_db: Any) -> Optional[str]:
return None
+def declared_conversation_scope(agent: Any) -> Optional[str]:
+ """Return the host-declared logical conversation scope, or None.
+
+ Resolved from ``agent._gateway_session_key`` (the ``X-Hermes-Session-Key``
+ /``build_session_key`` per-chat key), hashed into ``gwk_<sha256[:24]>``
+ so no platform/chat/user identifier reaches a provider on the wire and
+ the value stays inside every caller's length/charset budget.
+
+ None — meaning "fall back to the physical-id scope" — when no key was
+ declared, when this agent is a background-review fork (``_persist_disabled``:
+ it clones the live runtime, including the key), when the session row is an
+ explicit fork child (``/branch``, delegate, tool), and on any DB error
+ during that check.
+ """
+ key = str(getattr(agent, "_gateway_session_key", "") or "").strip()
+ if not key:
+ return None
+ if getattr(agent, "_persist_disabled", False):
+ return None
+ sid = str(getattr(agent, "session_id", None) or "")
+ db = getattr(agent, "_session_db", None)
+ if sid and db is not None:
+ try:
+ if db.is_explicit_fork_child(sid):
+ return None
+ except Exception:
+ # Degrade to the physical-id scope rather than risk merging a
+ # fork onto its parent's key on a transient DB failure.
+ logger.debug("declared-scope fork check failed", exc_info=True)
+ return None
+ digest = hashlib.sha256(key.encode("utf-8", errors="replace")).hexdigest()[:24]
+ return f"{_DECLARED_SCOPE_PREFIX}{digest}"
+
+
def resolve_prompt_cache_scope(agent: Any) -> str:
"""Resolve the rotation-stable cache-scope id for *agent*'s conversation.
- Returns the compression-lineage ROOT of ``agent.session_id`` (the
- physical id itself when the session has no compression ancestry, no DB
- is attached, or the walk fails). The result is memoized on the agent
+ Returns the host-declared conversation scope when one applies
+ (``declared_conversation_scope``), else the compression-lineage ROOT of
+ ``agent.session_id`` (the physical id itself when the session has no
+ compression ancestry, no DB is attached, or the walk fails). The result is memoized on the agent
keyed by the current session id, so the DB walk happens once per
transcript segment rather than once per API call.
"""
@@ -84,7 +152,12 @@ def resolve_prompt_cache_scope(agent: Any) -> str:
memo = getattr(agent, _MEMO_ATTR, None)
if isinstance(memo, tuple) and len(memo) == 2 and memo[0] == key:
return memo[1]
- root = _lineage_root(sid, db) if db is not None else None
+ # A declared conversation key outranks the lineage walk: it is stable
+ # across compression rotation AND across a host's per-response ids, which
+ # the walk cannot see (#96811).
+ root = declared_conversation_scope(agent) or (
+ _lineage_root(sid, db) if db is not None else None
+ )
scope = root or sid
# Memoize on a successful walk, or when there is no DB to consult at all,
# or when the agent will never persist a row (background-review forks set
@@ -108,6 +181,15 @@ def resolve_prompt_cache_scope(agent: Any) -> str:
return scope
+def declared_conversation_scope_safe(agent: Any) -> Optional[str]:
+ """Never-raising variant of :func:`declared_conversation_scope`."""
+ try:
+ return declared_conversation_scope(agent)
+ except Exception:
+ logger.debug("declared conversation scope resolution failed", exc_info=True)
+ return None
+
+
def resolve_prompt_cache_scope_safe(agent: Any) -> Optional[str]:
"""Never-raising variant of :func:`resolve_prompt_cache_scope`.
diff --git a/hermes_state.py b/hermes_state.py
index 7e95137c9fd..d1446c859c8 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -14123,6 +14123,17 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
return branched == parent_id or delegated == parent_id
return branched is not None or delegated is not None
+ def is_explicit_fork_child(self, session_id: str) -> bool:
+ """True when ``session_id`` is a /branch, delegate, or tool child row.
+
+ Read-only public view of :meth:`_is_explicit_fork_child_row` for
+ callers that must respect the fork boundary without re-implementing
+ its marker rules (``agent/prompt_cache_scope.py`` keeps a declared
+ conversation key from crossing it). A missing row is not a fork.
+ """
+ session = self.get_session(session_id)
+ return bool(session and self._is_explicit_fork_child_row(session))
+
def _is_compression_child_row(self, child: Dict[str, Any]) -> bool:
parent_id = child.get("parent_session_id")
if not parent_id or self._is_explicit_fork_child_row(child):
diff --git a/plugins/model-providers/nous/__init__.py b/plugins/model-providers/nous/__init__.py
index e56470482c8..ad7540ad134 100644
--- a/plugins/model-providers/nous/__init__.py
+++ b/plugins/model-providers/nous/__init__.py
@@ -2,7 +2,11 @@
from typing import Any
-from agent.portal_tags import get_conversation_context, nous_portal_tags
+from agent.portal_tags import (
+ get_affinity_scope,
+ get_conversation_context,
+ nous_portal_tags,
+)
from agent.transports.codex import _cache_scope_from_session_id
from providers import register_provider
from providers.base import ProviderProfile
@@ -50,14 +54,17 @@ class NousProfile(ProviderProfile):
# ``conversation=`` tag but NO sticky key at all, and each one routed
# independently of the conversation it belongs to. Reading the same
# ambient contextvar the tag already uses fixes that with zero
- # per-call-site plumbing.
+ # per-call-site plumbing; a host-declared routing scope (#96811) wins
+ # over it when one was published for this turn.
#
# For the main loop the two agree anyway under the default
# ``compression.in_place: true`` (#38763), where compaction keeps the
# session id; the ambient root additionally keeps the key stable for
# installs that opt back into rotating compaction, and across
# delegate-subagent trees.
- sticky_key = _cache_scope_from_session_id(get_conversation_context() or session_id)
+ sticky_key = _cache_scope_from_session_id(
+ get_affinity_scope() or get_conversation_context() or session_id
+ )
if sticky_key:
body["session_id"] = sticky_key
provider_preferences = context.get("provider_preferences")
diff --git a/plugins/model-providers/openrouter/__init__.py b/plugins/model-providers/openrouter/__init__.py
index 523dd6688ff..6a91d5258ca 100644
--- a/plugins/model-providers/openrouter/__init__.py
+++ b/plugins/model-providers/openrouter/__init__.py
@@ -3,7 +3,7 @@
import logging
from typing import Any
-from agent.portal_tags import get_conversation_context
+from agent.portal_tags import get_affinity_scope, get_conversation_context
from agent.transports.codex import _cache_scope_from_session_id
from providers import register_provider
from providers.base import ProviderProfile
@@ -121,8 +121,9 @@ class OpenRouterProfile(ProviderProfile):
# hashing the opening messages, and it activates stickiness on the
# first successful request rather than only after a cache hit.
#
- # Resolve it from the ambient conversation contextvar first, explicit
- # argument as fallback. The gap this closes is the auxiliary call sites
+ # Resolve it from the declared routing scope first (set only by a host
+ # that names its own conversation, #96811), then the ambient conversation
+ # contextvar, with the explicit argument as fallback. The gap this closes is the auxiliary call sites
# — compression, title generation, vision, web_extract, session_search,
# MoA slots — which funnel through ``agent.auxiliary_client``. That
# module has no session handle and passes no ``session_id``, so those
@@ -133,7 +134,9 @@ class OpenRouterProfile(ProviderProfile):
# (f2f4df064d). The ambient value is the session-lineage ROOT, so it
# also stays stable for installs that opt out of the default
# ``compression.in_place: true`` and across delegate-subagent trees.
- sticky_key = _cache_scope_from_session_id(get_conversation_context() or session_id)
+ sticky_key = _cache_scope_from_session_id(
+ get_affinity_scope() or get_conversation_context() or session_id
+ )
if sticky_key:
body["session_id"] = sticky_key
prefs = context.get("provider_preferences")
@@ -222,7 +225,9 @@ class OpenRouterProfile(ProviderProfile):
# backend server via this header, and aux calls pass no session_id, so
# reading the ambient conversation keeps compression/vision/MoA traffic
# on the same Grok backend as the conversation it belongs to.
- grok_conv_id = _cache_scope_from_session_id(get_conversation_context() or session_id)
+ grok_conv_id = _cache_scope_from_session_id(
+ get_affinity_scope() or get_conversation_context() or session_id
+ )
if grok_conv_id and model and model.startswith(("x-ai/grok-", "xai/grok-")):
extra_headers["x-grok-conv-id"] = grok_conv_id
if extra_headers:
diff --git a/run_agent.py b/run_agent.py
index 3db3e7ff1f8..72e30007543 100644
--- a/run_agent.py
+++ b/run_agent.py
@@ -8376,10 +8376,14 @@ class AIAgent:
)
reset_context_compression_timeout_outcome(self)
from agent.portal_tags import (
+ get_affinity_scope,
get_conversation_context,
+ reset_affinity_scope,
reset_conversation_context,
+ set_affinity_scope,
set_conversation_context,
)
+ from agent.prompt_cache_scope import declared_conversation_scope_safe
# Out-of-turn compaction entry points — ``/compact`` (cli.py), the
# gateway ``/compress`` command and its hygiene sweep (both of which
# build a throwaway agent), and partial head compression — call this
@@ -8399,6 +8403,16 @@ class AIAgent:
root = self._conversation_root_id()
if root:
token = set_conversation_context(root)
+ # Same fallback for the ROUTING scope: out-of-turn compaction would
+ # otherwise send the summarizer's call with no sticky key at all, or
+ # (worse, on a per-response host) with a key that no longer matches
+ # the conversation it is compacting. Only set when the host declared
+ # one — unset keeps the pre-#96811 conversation-id fallback.
+ affinity_token = None
+ if get_affinity_scope() is None:
+ declared = declared_conversation_scope_safe(self)
+ if declared:
+ affinity_token = set_affinity_scope(declared)
# Every AIAgent compression has a fence, including ordinary in-turn and
# manual paths. hard_interrupt() uses this exact instance to serialize
# cancel admission against begin_commit().
@@ -8738,6 +8752,8 @@ class AIAgent:
# tag into the surrounding scope.
if token is not None:
reset_conversation_context(token)
+ if affinity_token is not None:
+ reset_affinity_scope(affinity_token)
def _set_tool_guardrail_halt(self, decision: ToolGuardrailDecision) -> None:
"""Record the first guardrail decision that should stop this turn."""
@@ -9014,9 +9030,12 @@ class AIAgent:
from agent import relay_runtime
from agent.conversation_loop import run_conversation
from agent.portal_tags import (
+ reset_affinity_scope,
reset_conversation_context,
+ set_affinity_scope,
set_conversation_context,
)
+ from agent.prompt_cache_scope import declared_conversation_scope_safe
from hermes_cli.observability.relay_shared_metrics import (
finish_task_run,
start_task_run,
@@ -9479,6 +9498,13 @@ class AIAgent:
# (which copy this Context into their thread) — inherits the
# ``conversation=<root>`` tag with zero per-call-site plumbing.
token = set_conversation_context(self._conversation_root_id())
+ # Routing/affinity scope for the same turn — the conversation the
+ # HOST declared, when it declared one. Providers fall back to the
+ # attribution id above when it is unset, so this changes nothing
+ # for a host that keeps one session id per conversation (#96811).
+ affinity_token = set_affinity_scope(
+ declared_conversation_scope_safe(self)
+ )
# Publish the session accounting handles the same way so auxiliary
# calls record their token usage into session_model_usage (task
# dimension) — the fix for aux spend being invisible in analytics
@@ -9621,6 +9647,8 @@ class AIAgent:
reset_accounting_context(acct_token)
if token is not None:
reset_conversation_context(token)
+ if affinity_token is not None:
+ reset_affinity_scope(affinity_token)
def chat(self, message: str, stream_callback: Optional[callable] = None) -> str:
"""
diff --git a/tests/agent/test_declared_conversation_scope.py b/tests/agent/test_declared_conversation_scope.py
new file mode 100644
index 00000000000..4388ac13caf
--- /dev/null
+++ b/tests/agent/test_declared_conversation_scope.py
@@ -0,0 +1,365 @@
+"""Host-declared conversation scope on the affinity-key path (issue #96811).
+
+A host that mints one physical ``session_id`` per RESPONSE re-keys every
+conversation-affinity hint Hermes sends — ``prompt_cache_key`` on both
+OpenAI-wire transports, the OpenRouter/Nous sticky ``session_id``, and xAI's
+``x-grok-conv-id`` — so the conversation never lands back on the routing
+bucket it warmed. Hermes cannot infer the logical conversation from the id's
+syntax (#79017's failure class), but it does not have to: the host declares
+it through ``gateway_session_key`` (the ``X-Hermes-Session-Key`` /
+``build_session_key`` per-chat key).
+
+These tests pin the declaration contract and the two boundaries it must not
+cross: explicit fork children (``/branch``, delegate, tool) and
+background-review forks, which share the parent's chat key but are separate
+conversations under #79161.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from agent.portal_tags import (
+ get_affinity_scope,
+ reset_affinity_scope,
+ reset_conversation_context,
+ set_affinity_scope,
+ set_conversation_context,
+)
+from agent.prompt_cache_scope import (
+ declared_conversation_scope,
+ declared_conversation_scope_safe,
+ resolve_prompt_cache_scope,
+)
+from agent.transports.codex import _cache_scope_from_session_id, _content_cache_key
+from hermes_state import SessionDB
+
+# One room member, two consecutive replies: the Studio group-chat shape
+# (``gc_run_<room>_<profile>_<name>`` truncated to 96 chars + a per-response
+# UUID4 hex) and the ``POST /v1/responses`` shape (a bare ``str(uuid4())``).
+RUN_1 = "gc_run_room7_default_Reviewer_11111111111141118111111111111111"
+RUN_2 = "gc_run_room7_default_Reviewer_22222222222242228222222222222222"
+CHAT_KEY = "agent:main:telegram:group:-100123:456"
+
+
+def db(tmp_path):
+ session_db = SessionDB(db_path=tmp_path / "state.db")
+ try:
+ yield session_db
+ finally:
+ session_db.close()
+
+
+def _agent(session_id, session_db=None, key=None):
+ return SimpleNamespace(
+ session_id=session_id,
+ _session_db=session_db,
+ _gateway_session_key=key,
+ )
+
+
+def _sticky_key(session_id):
+ from providers import get_provider_profile
+
+ return get_provider_profile("openrouter").build_extra_body(session_id=session_id)[
+ "session_id"
+ ]
+
+
+def _grok_headers(session_id):
+ from providers import get_provider_profile
+
+ _extra_body, top_level = get_provider_profile("openrouter").build_api_kwargs_extras(
+ model="x-ai/grok-4",
+ session_id=session_id,
+ )
+ return top_level["extra_headers"]
+
+
+class TestDeclaredConversationScope:
+ def test_per_response_ids_resolve_to_one_declared_scope(self, db):
+ """THE fix: two replies of one conversation share one scope."""
+ db.create_session(RUN_1, source="api_server")
+ db.create_session(RUN_2, source="api_server")
+
+ first = resolve_prompt_cache_scope(_agent(RUN_1, db, CHAT_KEY))
+ second = resolve_prompt_cache_scope(_agent(RUN_2, db, CHAT_KEY))
+
+ assert first == second
+ assert first not in (RUN_1, RUN_2)
+
+ def test_distinct_declarations_stay_isolated(self, db):
+ db.create_session(RUN_1, source="api_server")
+ other = _agent(RUN_1, db, "agent:main:telegram:group:-100123:999")
+
+ assert resolve_prompt_cache_scope(
+ _agent(RUN_1, db, CHAT_KEY)
+ ) != resolve_prompt_cache_scope(other)
+
+ def test_scope_never_carries_the_raw_key(self, db):
+ """The scope leaves the process verbatim (sticky id, x-grok-conv-id).
+
+ A session id is a Hermes-internal token; a session KEY embeds the
+ platform, chat and user identifiers, so it is hashed first.
+ """
+ db.create_session(RUN_1, source="api_server")
+ scope = resolve_prompt_cache_scope(_agent(RUN_1, db, CHAT_KEY))
+
+ assert scope.startswith("gwk_")
+ assert "telegram" not in scope
+ assert "-100123" not in scope
+ assert len(scope) <= 64 # provider key budget
+
+ def test_no_declaration_keeps_lineage_behavior(self, db):
+ """Unchanged for every host that keeps one id per conversation."""
+ db.create_session("root-sess", source="webui")
+ db.end_session("root-sess", "compression")
+ db.create_session("rotated-1", source="webui", parent_session_id="root-sess")
+
+ assert resolve_prompt_cache_scope(_agent("rotated-1", db)) == "root-sess"
+ assert declared_conversation_scope(_agent("rotated-1", db)) is None
+
+ def test_declaration_outranks_the_lineage_root(self, db):
+ """Both are stable; the declared key is stable across MORE (per-response
+ ids), so it wins rather than being a fallback."""
+ db.create_session("root-sess", source="webui")
+ db.end_session("root-sess", "compression")
+ db.create_session("rotated-1", source="webui", parent_session_id="root-sess")
+
+ scope = resolve_prompt_cache_scope(_agent("rotated-1", db, CHAT_KEY))
+ assert scope == declared_conversation_scope(_agent("x", None, CHAT_KEY))
+ assert scope != "root-sess"
+
+ def test_branch_child_ignores_the_shared_chat_key(self, db):
+ """/branch keys off session_id, not the chat key — #79161 isolation."""
+ db.create_session("root-sess", source="telegram")
+ db.create_session(
+ "branch-child",
+ source="telegram",
+ parent_session_id="root-sess",
+ model_config={"_branched_from": "root-sess"},
+ )
+
+ assert (
+ resolve_prompt_cache_scope(_agent("branch-child", db, CHAT_KEY))
+ == "branch-child"
+ )
+ assert (
+ resolve_prompt_cache_scope(_agent("root-sess", db, CHAT_KEY))
+ != "branch-child"
+ )
+
+ def test_delegate_child_ignores_the_declaration(self, db):
+ db.create_session("parent-sess", source="telegram")
+ db.create_session(
+ "delegate-child",
+ source="telegram",
+ parent_session_id="parent-sess",
+ model_config={"_delegate_from": "parent-sess"},
+ )
+
+ assert (
+ resolve_prompt_cache_scope(_agent("delegate-child", db, CHAT_KEY))
+ == "delegate-child"
+ )
+
+ def test_tool_child_ignores_the_declaration(self, db):
+ db.create_session("parent-sess", source="telegram")
+ db.create_session("tool-child", source="tool", parent_session_id="parent-sess")
+
+ assert (
+ resolve_prompt_cache_scope(_agent("tool-child", db, CHAT_KEY))
+ == "tool-child"
+ )
+
+ def test_background_review_fork_ignores_the_declaration(self, db):
+ """The review fork clones the live runtime, key included."""
+ db.create_session("live-sess", source="telegram")
+ agent = _agent("review-fork", db, CHAT_KEY)
+ agent._persist_disabled = True
+
+ assert declared_conversation_scope(agent) is None
+ assert resolve_prompt_cache_scope(agent) == "review-fork"
+
+ def test_fork_check_failure_degrades_to_the_physical_scope(self):
+ """A transient DB error must not merge a fork onto its parent's key."""
+
+ class BoomDB:
+ def is_explicit_fork_child(self, sid):
+ raise RuntimeError("db exploded")
+
+ def get_compression_lineage(self, sid):
+ return [sid]
+
+ agent = _agent("maybe-fork", BoomDB(), CHAT_KEY)
+ assert declared_conversation_scope(agent) is None
+ assert resolve_prompt_cache_scope(agent) == "maybe-fork"
+
+ def test_declaration_applies_before_the_row_lands(self, db):
+ """turn_context resolves before _ensure_db_session persists the row."""
+ agent = _agent(RUN_1, db, CHAT_KEY)
+ assert resolve_prompt_cache_scope(agent).startswith("gwk_")
+
+ def test_blank_declarations_are_no_declaration(self, db):
+ db.create_session(RUN_1, source="api_server")
+ for blank in (None, "", " "):
+ assert declared_conversation_scope(_agent(RUN_1, db, blank)) is None
+
+ def test_safe_variant_never_raises(self):
+ class ExplodingAgent:
+ @property
+ def _gateway_session_key(self):
+ raise RuntimeError("hostile property")
+
+ assert declared_conversation_scope_safe(ExplodingAgent()) is None
+ assert declared_conversation_scope_safe(
+ _agent("sess", None, CHAT_KEY)
+ ).startswith("gwk_")
+
+
+class TestPromptCacheKeyStability:
+ """The reported symptom, at the wire layer: one conversation, one key."""
+
+ INSTRUCTIONS = "You are Reviewer in room7."
+ TOOLS = [{"type": "function", "name": "terminal"}]
+
+ def _key_for(self, agent):
+ scope = _cache_scope_from_session_id(resolve_prompt_cache_scope(agent))
+ return _content_cache_key(self.INSTRUCTIONS, self.TOOLS, scope)
+
+ def test_key_survives_a_per_response_id(self, db):
+ db.create_session(RUN_1, source="api_server")
+ db.create_session(RUN_2, source="api_server")
+
+ assert self._key_for(_agent(RUN_1, db, CHAT_KEY)) == self._key_for(
+ _agent(RUN_2, db, CHAT_KEY)
+ )
+
+ def test_key_still_churns_without_a_declaration(self, db):
+ """Nothing is inferred from the id itself — the #79017 rule holds."""
+ db.create_session(RUN_1, source="api_server")
+ db.create_session(RUN_2, source="api_server")
+
+ assert self._key_for(_agent(RUN_1, db)) != self._key_for(_agent(RUN_2, db))
+
+ def test_codex_transport_key_matches_across_responses(self, db):
+ from agent.transports.codex import ResponsesApiTransport
+
+ db.create_session(RUN_1, source="api_server")
+ db.create_session(RUN_2, source="api_server")
+ transport = ResponsesApiTransport()
+ base = dict(
+ model="gpt-5.5",
+ messages=[
+ {"role": "system", "content": self.INSTRUCTIONS},
+ {"role": "user", "content": "hi"},
+ ],
+ tools=[],
+ )
+
+ def key(session_id):
+ scope = resolve_prompt_cache_scope(_agent(session_id, db, CHAT_KEY))
+ return transport.build_kwargs(
+ **base, session_id=session_id, cache_scope_id=scope
+ )["prompt_cache_key"]
+
+ assert key(RUN_1) == key(RUN_2)
+
+ def test_chat_completions_key_matches_across_responses(self, db):
+ from agent.transports.chat_completions import _add_prompt_cache_key
+
+ db.create_session(RUN_1, source="api_server")
+ db.create_session(RUN_2, source="api_server")
+ messages = [{"role": "system", "content": self.INSTRUCTIONS}]
+
+ def key(session_id):
+ kwargs: dict = {}
+ _add_prompt_cache_key(
+ kwargs,
+ messages=messages,
+ tools=None,
+ supports_prompt_cache_key=True,
+ session_id=session_id,
+ cache_scope_id=resolve_prompt_cache_scope(
+ _agent(session_id, db, CHAT_KEY)
+ ),
+ )
+ return kwargs["prompt_cache_key"]
+
+ assert key(RUN_1) == key(RUN_2)
+
+ def test_transcript_identity_is_not_rewritten(self, db):
+ """#57012: the session header still carries the physical id."""
+ from agent.transports.codex import ResponsesApiTransport
+
+ db.create_session(RUN_1, source="api_server")
+ kwargs = ResponsesApiTransport().build_kwargs(
+ model="gpt-5.5",
+ messages=[{"role": "system", "content": self.INSTRUCTIONS}],
+ tools=[],
+ session_id=RUN_1,
+ cache_scope_id=resolve_prompt_cache_scope(_agent(RUN_1, db, CHAT_KEY)),
+ is_codex_backend=True,
+ )
+ assert kwargs["extra_headers"]["session_id"] == RUN_1
+
+
+class TestProviderStickyKeys:
+ """OpenRouter / Nous sticky ids and x-grok-conv-id read the same scope."""
+
+ @pytest.fixture(autouse=True)
+ def _clean_context(self):
+ affinity = set_affinity_scope(None)
+ conversation = set_conversation_context(None)
+ try:
+ yield
+ finally:
+ reset_conversation_context(conversation)
+ reset_affinity_scope(affinity)
+
+ def test_declared_scope_pins_the_sticky_key(self):
+ scope = declared_conversation_scope(_agent(RUN_1, None, CHAT_KEY))
+ token = set_affinity_scope(scope)
+ try:
+ first = _sticky_key(RUN_1)
+ second = _sticky_key(RUN_2)
+ finally:
+ reset_affinity_scope(token)
+
+ assert first == second == scope
+
+ def test_without_a_declaration_the_conversation_id_still_wins(self):
+ """Delegate trees keep sharing their parent's sticky key."""
+ conversation = set_conversation_context("parent-root")
+ try:
+ assert get_affinity_scope() is None
+ assert _sticky_key("delegate-child") == "parent-root"
+ finally:
+ reset_conversation_context(conversation)
+
+ def test_grok_conv_id_follows_the_declared_scope(self):
+ scope = declared_conversation_scope(_agent(RUN_1, None, CHAT_KEY))
+ token = set_affinity_scope(scope)
+ try:
+ headers = _grok_headers(RUN_1)
+ headers_next = _grok_headers(RUN_2)
+ finally:
+ reset_affinity_scope(token)
+
+ assert headers["x-grok-conv-id"] == headers_next["x-grok-conv-id"] == scope
+
+ def test_nous_sticky_key_follows_the_declared_scope(self):
+ from providers import get_provider_profile
+
+ scope = declared_conversation_scope(_agent(RUN_1, None, CHAT_KEY))
+ token = set_affinity_scope(scope)
+ try:
+ body = get_provider_profile("nous").build_extra_body(session_id=RUN_1)
+ body_next = get_provider_profile("nous").build_extra_body(session_id=RUN_2)
+ finally:
+ reset_affinity_scope(token)
+
+ assert body["session_id"] == body_next["session_id"] == scope