Skip to content

The agent that grows with you

fix(cache): qualify the declared key with the conversation generation

joaomarcosd7995bffaf03
diff --git a/agent/prompt_cache_scope.py b/agent/prompt_cache_scope.py
index 8aa45bbd3f6..1ffca5dd63c 100644
--- a/agent/prompt_cache_scope.py
+++ b/agent/prompt_cache_scope.py
@@ -97,19 +97,65 @@ def _lineage_root(session_id: str, session_db: Any) -> Optional[str]:
return None
+def _conversation_generation(session_key: str, session_db: Any) -> str:
+ """Return the generation marker for *session_key*'s current conversation.
+
+ The declared key is a per-CHAT identifier and deliberately outlives any
+ single conversation on it — ``reset_session()`` mints a fresh physical id
+ on ``/new`` but keeps the key, and the idle/daily/suspended policy resets
+ do the same. Hashing the key alone would therefore map the conversation
+ before a reset and the one after it onto ONE affinity scope, violating the
+ #79017/#86733 contract (warm across compression rotation, cold across a
+ new conversation).
+
+ The generation that must rotate is already durable: every one of those
+ boundaries closes the outgoing row with an ``_RESET_END_REASONS``
+ end_reason, and ``SessionDB.latest_conversation_boundary`` reports the most
+ recent one. Qualifying the key with it gives a carrier that is
+
+ - stable across a host's per-response physical ids (no boundary is written
+ when nothing was reset, so every reply hashes the same value), and
+ - rotating on every conversation replacement, ``/new`` and the policy
+ auto-resets alike, monotonically — ``ended_at`` only moves forward, so a
+ retired generation can never be reused.
+
+ No counter is introduced anywhere: the marker is read from state the
+ reset paths already write, and it is read on the memoized resolution path,
+ not per API call.
+
+ Returns ``""`` when the key has never been reset, when the DB does not
+ expose the lookup, or when it reports nothing.
+ """
+ reader = getattr(session_db, "latest_conversation_boundary", None)
+ if not callable(reader):
+ return ""
+ boundary = reader(session_key)
+ if boundary is None:
+ return ""
+ # Fixed-point so the carrier is byte-identical across repr differences.
+ return f"{float(boundary):.6f}"
+
+
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.
+ /``build_session_key`` per-chat key) qualified by the conversation
+ generation currently live on it (:func:`_conversation_generation`), hashed
+ together 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.
+
+ The key alone would outlive the conversation — it survives ``/new`` and the
+ idle/daily policy resets by design — so the generation is what makes this
+ carrier legal: stable across a host's per-response physical ids, and cold
+ on every conversation replacement.
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.
+ during either lookup.
"""
key = str(getattr(agent, "_gateway_session_key", "") or "").strip()
if not key:
@@ -118,6 +164,7 @@ def declared_conversation_scope(agent: Any) -> Optional[str]:
return None
sid = str(getattr(agent, "session_id", None) or "")
db = getattr(agent, "_session_db", None)
+ generation = ""
if sid and db is not None:
try:
if db.is_explicit_fork_child(sid):
@@ -127,7 +174,16 @@ def declared_conversation_scope(agent: Any) -> Optional[str]:
# 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]
+ if db is not None:
+ try:
+ generation = _conversation_generation(key, db)
+ except Exception:
+ # Same fail-closed rule as the fork check: an unqualified key
+ # spans /new, so degrade to the physical-id scope instead.
+ logger.debug("declared-scope generation read failed", exc_info=True)
+ return None
+ carrier = f"{key}|{generation}" if generation else key
+ digest = hashlib.sha256(carrier.encode("utf-8", errors="replace")).hexdigest()[:24]
return f"{_DECLARED_SCOPE_PREFIX}{digest}"
diff --git a/hermes_state.py b/hermes_state.py
index d1446c859c8..0909289e459 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -14134,6 +14134,39 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)
session = self.get_session(session_id)
return bool(session and self._is_explicit_fork_child_row(session))
+ def latest_conversation_boundary(self, session_key: str) -> Optional[float]:
+ """When the most recent conversation boundary closed for *session_key*.
+
+ A boundary is a row this key ended at an intentional conversation
+ break — the ``_RESET_END_REASONS`` set (``/new``, ``/switch``, idle,
+ daily, suspended, resume_pending_expired). That is the same fence
+ :meth:`find_latest_gateway_session_for_peer` refuses to reach behind,
+ so the two agree on where one conversation stops and the next begins
+ and cannot drift.
+
+ Returns ``None`` when the key has never been reset. The value is a
+ monotonically advancing ``ended_at``: each reset appends a newer
+ boundary, so a generation derived from it can never roll back to a
+ previous one. Read-only; ``agent/prompt_cache_scope.py`` uses it to
+ keep a host-declared conversation key from outliving the conversation
+ it names.
+ """
+ if not session_key:
+ return None
+ with self._read_ctx() as conn:
+ row = conn.execute(
+ f"""
+ SELECT MAX(ended_at) AS boundary
+ FROM sessions
+ WHERE session_key = ?
+ AND ended_at IS NOT NULL
+ AND end_reason IN ({_RESET_END_REASONS_SQL})
+ """,
+ (session_key,),
+ ).fetchone()
+ boundary = row["boundary"] if row is not None else None
+ return float(boundary) if boundary is not None else None
+
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/tests/agent/test_declared_conversation_scope.py b/tests/agent/test_declared_conversation_scope.py
index 4388ac13caf..21b2bc2b281 100644
--- a/tests/agent/test_declared_conversation_scope.py
+++ b/tests/agent/test_declared_conversation_scope.py
@@ -363,3 +363,147 @@ class TestProviderStickyKeys:
reset_affinity_scope(token)
assert body["session_id"] == body_next["session_id"] == scope
+
+
+class TestConversationGenerationRotates:
+ """The declared key must not outlive the conversation it names.
+
+ ``gateway_session_key`` is a per-CHAT identifier: ``reset_session()``
+ mints a fresh physical id on ``/new`` and keeps the key, and the
+ idle/daily/suspended policy resets do the same. Hashing the key alone
+ would map the conversation before a reset and the one after it onto ONE
+ affinity scope, violating the #79017/#86733 contract.
+
+ The generation is read from the boundary those resets already write
+ (``_RESET_END_REASONS`` on the outgoing row), so nothing new is persisted
+ and the two fences cannot drift.
+ """
+
+ KEY = "agent:main:telegram:dm:123"
+
+ def _keyed(self, db, session_id):
+ db.create_session(
+ session_id=session_id,
+ source="telegram",
+ session_key=self.KEY,
+ )
+ return _agent(session_id, db, self.KEY)
+
+ def test_new_rotates_the_declared_scope(self, db):
+ """The exact reproduction that blocked this PR, now green.
+
+ ``/new`` ends the outgoing row with ``session_reset`` and mints a new
+ physical id under the same chat key; before the generation qualifier
+ both sides hashed to one ``gwk_`` value.
+ """
+ before = self._keyed(db, "sess-A")
+ scope_before = resolve_prompt_cache_scope(before)
+
+ db.end_session("sess-A", "session_reset")
+ after = self._keyed(db, "sess-B")
+
+ assert scope_before.startswith("gwk_")
+ assert resolve_prompt_cache_scope(after).startswith("gwk_")
+ assert resolve_prompt_cache_scope(after) != scope_before
+
+ @pytest.mark.parametrize(
+ "reason",
+ ["session_reset", "session_switch", "idle", "daily", "suspended",
+ "resume_pending_expired"],
+ )
+ def test_every_reset_boundary_rotates(self, db, reason):
+ """Policy auto-resets are conversation replacements too.
+
+ A hand-rolled counter incremented only in ``reset_session()`` would
+ leave these on the previous generation; reading the durable boundary
+ covers the whole set by construction.
+ """
+ first = self._keyed(db, f"sess-{reason}-1")
+ scope_first = resolve_prompt_cache_scope(first)
+ db.end_session(f"sess-{reason}-1", reason)
+ second = self._keyed(db, f"sess-{reason}-2")
+ assert resolve_prompt_cache_scope(second) != scope_first
+
+ def test_generations_never_roll_back(self, db):
+ """Three conversations on one key produce three distinct scopes."""
+ scopes = []
+ for i in range(3):
+ agent = self._keyed(db, f"sess-gen{i}")
+ scopes.append(resolve_prompt_cache_scope(agent))
+ db.end_session(f"sess-gen{i}", "session_reset")
+ assert len(set(scopes)) == 3
+
+ def test_per_response_ids_still_share_one_scope(self, db):
+ """The whole point of the PR survives the fix.
+
+ A host that mints one id per RESPONSE writes no boundary, so every
+ reply reads the same (empty) generation and lands on one scope.
+ """
+ scopes = {
+ resolve_prompt_cache_scope(self._keyed(db, f"gc_run_{i}"))
+ for i in range(4)
+ }
+ assert len(scopes) == 1
+ assert next(iter(scopes)).startswith("gwk_")
+
+ def test_an_accidental_end_is_not_a_boundary(self, db):
+ """Only intentional breaks rotate; a crash-close keeps the scope warm."""
+ first = self._keyed(db, "sess-live")
+ scope_first = resolve_prompt_cache_scope(first)
+ db.end_session("sess-live", "agent_close")
+ second = self._keyed(db, "sess-resumed")
+ assert resolve_prompt_cache_scope(second) == scope_first
+
+ def test_another_chats_reset_does_not_rotate_this_one(self, db):
+ """The boundary is read per declared key, never globally."""
+ mine = self._keyed(db, "sess-mine")
+ scope_mine = resolve_prompt_cache_scope(mine)
+
+ other_key = "agent:main:telegram:dm:999"
+ db.create_session(
+ session_id="sess-other", source="telegram", session_key=other_key
+ )
+ db.end_session("sess-other", "session_reset")
+
+ again = self._keyed(db, "sess-mine-2")
+ assert resolve_prompt_cache_scope(again) == scope_mine
+
+ def test_scope_never_carries_the_raw_key_or_boundary(self, db):
+ agent = self._keyed(db, "sess-A")
+ db.end_session("sess-A", "session_reset")
+ rotated = self._keyed(db, "sess-B")
+ scope = resolve_prompt_cache_scope(rotated)
+ assert self.KEY not in scope
+ assert "telegram" not in scope
+ assert scope.startswith("gwk_")
+ assert len(scope) == len("gwk_") + 24
+
+ def test_generation_read_failure_degrades_to_the_physical_scope(self):
+ """Fail closed: an unqualified key would span a /new."""
+
+ class BoomDB:
+ def is_explicit_fork_child(self, sid):
+ return False
+
+ def latest_conversation_boundary(self, key):
+ raise RuntimeError("db down")
+
+ def get_compression_lineage(self, sid):
+ return []
+
+ agent = _agent("sess-A", BoomDB(), self.KEY)
+ assert declared_conversation_scope(agent) is None
+
+ def test_a_db_without_the_lookup_keeps_the_declaration(self, db):
+ """Forward/backward compatible: no boundary API means no boundary."""
+
+ class LegacyDB:
+ def is_explicit_fork_child(self, sid):
+ return False
+
+ def get_compression_lineage(self, sid):
+ return []
+
+ agent = _agent("sess-A", LegacyDB(), self.KEY)
+ scope = declared_conversation_scope(agent)
+ assert scope is not None and scope.startswith("gwk_")