The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
chore(cache): take the pre-merge cleanups on the declared conversation scope
joaomarcos6b9b3e014500
diff --git a/agent/prompt_cache_scope.py b/agent/prompt_cache_scope.pyindex 46dd0f7e317..45c703025c1 100644--- a/agent/prompt_cache_scope.py+++ b/agent/prompt_cache_scope.py@@ -97,12 +97,20 @@ def _lineage_root(session_id: str, session_db: Any) -> Optional[str]:return None-def _agent_source(agent: Any, session_id: str, session_db: Any) -> str:+def _agent_source(+ agent: Any, session_id: str, session_db: Any, row_source: Optional[str] = None+) -> str:"""The ``sessions.source`` this agent's conversation is recorded under.Read from the agent's own row when it exists, because that is the valuethe peer queries below match on.+ ``row_source`` is that value when the caller already has it — the single+ identity read in :func:`declared_conversation_scope` — where ``""`` means+ "the row was read and carries no source". ``None`` means "not read yet"+ and keeps the original lookup, which is the path a ``SessionDB`` without+ :meth:`~hermes_state.SessionDB.declared_scope_identity` still takes.+Before the row lands — this module resolves the first scope ahead of``_ensure_db_session`` — it uses the SAME resolver persistence will use,``run_agent._session_source_for_agent``, not ``agent.platform``. The two@@ -113,16 +121,15 @@ def _agent_source(agent: Any, session_id: str, session_db: Any) -> str:a ``/new`` would then read the platform domain, miss the boundary recordedunder the override, and hash the same scope."""- if session_id and session_db is not None:+ if row_source is None and session_id and session_db is not None:try:row = session_db.get_session(session_id)except Exception:logger.debug("declared-scope source lookup failed", exc_info=True)row = None- if row:- source = str(row.get("source") or "").strip()- if source:- return source+ row_source = str(row.get("source") or "").strip() if row else ""+ if row_source:+ return row_sourceplatform = getattr(agent, "platform", None)try:# Imported lazily: run_agent imports this module, and this is the@@ -211,16 +218,32 @@ def declared_conversation_scope(agent: Any) -> Optional[str]:sid = str(getattr(agent, "session_id", None) or "")db = getattr(agent, "_session_db", None)generation = ""+ row_source: Optional[str] = Noneif sid and db is not None:try:- if db.is_explicit_fork_child(sid):+ # One read for both halves of the row's identity: the fork verdict+ # and the source the peer queries match on live on the same+ # ``sessions`` row, and asking for them separately read it twice+ # per resolution (@teknium1 on #98811). A SessionDB without the+ # combined view keeps the original call, so nothing that predates+ # it — including the doubles that certify the fail-closed contract+ # below — changes behaviour.+ identity = getattr(db, "declared_scope_identity", None)+ if callable(identity):+ is_fork, row_source = identity(sid)+ else:+ is_fork = db.is_explicit_fork_child(sid)+ if is_fork:return Noneexcept Exception:# Degrade to the physical-id scope rather than risk merging a- # fork onto its parent's key on a transient DB failure.+ # fork onto its parent's key on a transient DB failure. The+ # source read is inside this same guard for the same reason: it+ # was always the second half of a read that had already failed+ # closed here.logger.debug("declared-scope fork check failed", exc_info=True)return None- source = _agent_source(agent, sid, db)+ source = _agent_source(agent, sid, db, row_source)if db is not None:try:generation = _conversation_generation(key, source, db)diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.pyindex 8a297354bd7..004ef1a9e1e 100644--- a/gateway/platforms/api_server.py+++ b/gateway/platforms/api_server.py@@ -2307,8 +2307,20 @@ class APIServerAdapter(BasePlatformAdapter):at a conversation boundary — ``session_reset`` (/new),``session_switch``, ``idle``, ``daily``, ``suspended`` — are fencedout, so a new conversation still gets a new id and a cold affinity- scope. The generation that must rotate is therefore already durable- in ``sessions.end_reason``; nothing here needs a counter.+ scope. The generation that must rotate is durable independently of+ this lookup, in the ``conversation_generations`` counter advanced+ inside each boundary's own transaction+ (``SessionDB._bump_conversation_generation``); all this has to resolve+ is the live transcript.++ Two first requests arriving concurrently on one declared key can each+ miss this lookup, mint their own row and both bind — the mismatch+ guard in :meth:`_bind_declared_conversation` does not fire, because+ each row is still unkeyed at bind time. That converges instead of+ crossing: both rows carry the same key under the same source, so this+ lookup returns the later one for every subsequent reply and the+ earlier row is an abandoned transcript, never another conversation's+ identity.Returns ``None`` when nothing was declared, when no live row isrecorded for the declared key, or on any DB error — every one ofdiff --git a/hermes_state.py b/hermes_state.pyindex c14a0d78201..4f1bbe2b0a8 100644--- a/hermes_state.py+++ b/hermes_state.py@@ -14182,6 +14182,30 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)session = self.get_session(session_id)return bool(session and self._is_explicit_fork_child_row(session))+ def declared_scope_identity(self, session_id: str) -> Tuple[bool, str]:+ """Fork verdict and recorded ``source`` for *session_id*, in ONE read.++ ``agent/prompt_cache_scope.py`` needs both to resolve a host-declared+ conversation scope, and both live on the same ``sessions`` row; asking+ for them separately read that row twice per resolution (@teknium1 on+ #98811). The marker rules stay here, beside+ :meth:`is_explicit_fork_child`, instead of being re-implemented by the+ caller.++ A missing row is not a fork and has no source, which is the right+ answer before ``_ensure_db_session`` persists it. This raises whatever+ :meth:`get_session` raises: the caller fails closed on a DB error, and+ merging the two reads cannot weaken that, because the fork check was+ already the first of the two.+ """+ session = self.get_session(session_id)+ if not session:+ return False, ""+ return (+ self._is_explicit_fork_child_row(session),+ str(session.get("source") or "").strip(),+ )+def latest_conversation_boundary(self, session_key: str, source: str) -> Optional[int]:@@ -14217,6 +14241,12 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)their first one from the next boundary written; a conversation thatreset before the upgrade shares its predecessor's scope once, whichcosts a warm prompt-cache bucket and never crosses an identity.++ These rows are never garbage-collected, by design: dropping one resets+ the peer to "no generation", so its next boundary writes ``1`` again+ and re-issues a scope a retired conversation already used — the ABA+ this counter exists to prevent. See the schema comment in+ ``hermes_state_common.py``."""if not session_key or not source:return Nonediff --git a/hermes_state_common.py b/hermes_state_common.pyindex 736ed18ee0c..2d2793bcf67 100644--- a/hermes_state_common.py+++ b/hermes_state_common.py@@ -534,6 +534,14 @@ CREATE TABLE IF NOT EXISTS gateway_hygiene_state (-- This counter lives outside prunable session history and only ever-- increments, once per boundary actually written, so a generation can never-- be reused for a peer even if every session row behind it is deleted.+--+-- These rows are deliberately NEVER garbage-collected, including when every+-- session row for the peer is gone. Collecting one resets that peer to "no+-- generation", so its next boundary writes generation = 1 again and re-issues+-- a gwk_ scope a retired conversation already used — exactly the ABA this+-- table exists to close. Do not add it to delete_session()'s cascade or to any+-- prune sweep. One (TEXT, TEXT, INTEGER) row per routing peer is the intended,+-- bounded cost.CREATE TABLE IF NOT EXISTS conversation_generations (source TEXT NOT NULL,session_key TEXT NOT NULL,diff --git a/scratch/repro_96811.py b/scratch/repro_96811.pydeleted file mode 100644index 4707e5fc54c..00000000000--- a/scratch/repro_96811.py+++ /dev/null@@ -1,208 +0,0 @@-"""Four-stage probe for #96811 — per-response session ids churn every-conversation-affinity key.--Run: ``python scratch/repro_96811.py`` (no pytest, no network, temp state.db).--The probe walks the causal chain end to end on a real ``SessionDB``:-- S1 reproduce the churn on current main's ``/v1/responses`` shape- S2 show why the durable key->session mapping cannot help today- S3 show the two-line repair restores affinity across replies- S4 isolation: /new rotates, distinct keys never collide, no-key unchanged--Every stage prints PASS/FAIL; the process exits non-zero if any stage fails.-"""--from __future__ import annotations--import sys-import tempfile-import time-import types-import uuid-from pathlib import Path--sys.path.insert(0, str(Path(__file__).resolve().parents[1]))--from agent.prompt_cache_scope import resolve_prompt_cache_scope # noqa: E402-from hermes_state import SessionDB # noqa: E402--SOURCE = "api_server"-DECLARED_KEY = "agent:main:api_server:room-42:member-7"-OTHER_KEY = "agent:main:api_server:room-42:member-8"--_failures: list[str] = []---def check(stage: str, label: str, ok: bool, detail: str = "") -> None:- status = "PASS" if ok else "FAIL"- print(f" [{status}] {stage} {label}" + (f" -- {detail}" if detail else ""))- if not ok:- _failures.append(f"{stage} {label} {detail}".strip())---def agent_for(session_id: str, db: SessionDB) -> types.SimpleNamespace:- """Minimal stand-in for the attributes resolve_prompt_cache_scope reads."""- return types.SimpleNamespace(session_id=session_id, _session_db=db)---def responses_turn(- db: SessionDB,- *,- declared_key: str | None,- resolve_declared: bool,- stamp_peer: bool,-) -> str:- """One POST /v1/responses turn with client-managed conversation_history.-- ``resolve_declared`` / ``stamp_peer`` toggle the two proposed repairs so- the same code path reproduces both the defect and the fix.- """- # gateway/platforms/api_server.py::_handle_responses — client supplies its- # own history, so the previous_response_id chain yields nothing.- stored_session_id = None-- declared_session_id = None- if resolve_declared and declared_key:- row = db.find_latest_gateway_session_for_peer(- source=SOURCE, session_key=declared_key- )- declared_session_id = row["id"] if row else None-- # main today: `session_id = stored_session_id or str(uuid.uuid4())`- session_id = stored_session_id or declared_session_id or str(uuid.uuid4())-- # AIAgent._ensure_db_session() — note: no session_key is written.- if db.get_session(session_id) is None:- db.create_session(session_id=session_id, source=SOURCE, model="m")-- if stamp_peer and declared_key:- db.record_gateway_session_peer(- session_id, source=SOURCE, session_key=declared_key- )- return session_id---def affinity_surfaces(session_id: str, db: SessionDB) -> str:- """The single value all four wire surfaces are derived from.-- prompt_cache_key (codex + chat_completions transports) reads- resolve_prompt_cache_scope; the OpenRouter/Nous sticky ``session_id`` and- xAI's ``x-grok-conv-id`` read the conversation root, which is the same- lineage walk over the same physical id. One value, four consumers.- """- return resolve_prompt_cache_scope(agent_for(session_id, db))---def stage_1_reproduce(db: SessionDB) -> tuple[str, str]:- print("\nS1 reproduce: two replies on one declared conversation")- a = responses_turn(db, declared_key=DECLARED_KEY, resolve_declared=False, stamp_peer=False)- time.sleep(0.01)- b = responses_turn(db, declared_key=DECLARED_KEY, resolve_declared=False, stamp_peer=False)- check("S1", "physical ids differ per reply", a != b, f"{a[:8]} != {b[:8]}")- check(- "S1",- "affinity scope churns per reply",- affinity_surfaces(a, db) != affinity_surfaces(b, db),- "prompt_cache_key / sticky session_id / x-grok-conv-id all re-key",- )- return a, b---def stage_2_mapping_unreachable(db: SessionDB, session_id: str) -> None:- print("\nS2 why the durable mapping cannot help today")- row = db.get_session(session_id)- check("S2", "row is created unkeyed", not (row or {}).get("session_key"),- f"session_key={(row or {}).get('session_key')!r}")- found = db.find_latest_gateway_session_for_peer(- source=SOURCE, session_key=DECLARED_KEY- )- check("S2", "reset-fenced peer lookup finds nothing", found is None,- "unkeyed rows are invisible to recovery")---def stage_3_repair(db: SessionDB) -> str:- print("\nS3 repair: stamp the routing key, resolve the id from it")- a = responses_turn(db, declared_key=DECLARED_KEY, resolve_declared=True, stamp_peer=True)- time.sleep(0.01)- b = responses_turn(db, declared_key=DECLARED_KEY, resolve_declared=True, stamp_peer=True)- c = responses_turn(db, declared_key=DECLARED_KEY, resolve_declared=True, stamp_peer=True)- check("S3", "physical id is stable across replies", a == b == c, f"{a[:8]}")- scopes = {affinity_surfaces(x, db) for x in (a, b, c)}- check("S3", "affinity scope is stable across replies", len(scopes) == 1,- next(iter(scopes))[:16])- return a---def stage_4_isolation(db: SessionDB, live_id: str) -> None:- print("\nS4 isolation: rotation, collision, opt-out")-- # /new — SessionStore.reset_session ends the row with 'session_reset',- # which is inside _RESET_END_REASONS, so the recovery fence blocks it.- live_scope = affinity_surfaces(live_id, db)- db.end_session(live_id, "session_reset")- after_reset = responses_turn(- db, declared_key=DECLARED_KEY, resolve_declared=True, stamp_peer=True- )- check("S4", "/new rotates the physical id", after_reset != live_id,- f"{live_id[:8]} -> {after_reset[:8]}")- check(- "S4",- "/new rotates the affinity scope",- affinity_surfaces(after_reset, db) != live_scope,- "no ABA: the boundary is durable in sessions.end_reason",- )-- # idle / daily / suspended auto-resets use the same fence set.- for reason in ("idle", "daily", "suspended"):- prev = responses_turn(- db, declared_key=DECLARED_KEY, resolve_declared=True, stamp_peer=True- )- db.end_session(prev, reason)- nxt = responses_turn(- db, declared_key=DECLARED_KEY, resolve_declared=True, stamp_peer=True- )- check("S4", f"'{reason}' auto-reset rotates", nxt != prev,- f"{prev[:8]} -> {nxt[:8]}")-- # A second declared channel never lands on the first one's conversation.- mine = responses_turn(- db, declared_key=DECLARED_KEY, resolve_declared=True, stamp_peer=True- )- theirs = responses_turn(- db, declared_key=OTHER_KEY, resolve_declared=True, stamp_peer=True- )- check("S4", "distinct declared keys stay isolated", mine != theirs,- f"{mine[:8]} != {theirs[:8]}")-- # A client that declares nothing keeps today's per-request identity.- n1 = responses_turn(db, declared_key=None, resolve_declared=True, stamp_peer=True)- n2 = responses_turn(db, declared_key=None, resolve_declared=True, stamp_peer=True)- check("S4", "no declared key -> behavior unchanged", n1 != n2,- "undeclared clients keep per-request ids")---def main() -> int:- # ignore_cleanup_errors: SessionDB holds the SQLite handle open, and- # Windows refuses to unlink a mapped file (WinError 32).- with tempfile.TemporaryDirectory(- prefix="repro96811_", ignore_cleanup_errors=True- ) as tmp:- db = SessionDB(Path(tmp) / "state.db")- churn_a, _ = stage_1_reproduce(db)- stage_2_mapping_unreachable(db, churn_a)- live = stage_3_repair(db)- stage_4_isolation(db, live)-- print("\n" + "=" * 62)- if _failures:- print(f"{len(_failures)} FAILED:")- for f in _failures:- print(f" - {f}")- return 1- print("all four stages PASS")- return 0---if __name__ == "__main__":- raise SystemExit(main())diff --git a/tests/agent/test_declared_conversation_scope.py b/tests/agent/test_declared_conversation_scope.pyindex e658ec3d326..a916583c518 100644--- a/tests/agent/test_declared_conversation_scope.py+++ b/tests/agent/test_declared_conversation_scope.py@@ -224,6 +224,74 @@ class TestDeclaredConversationScope:).startswith("gwk_")+class TestOneIdentityReadPerResolution:+ """The fork verdict and the row's source come from one ``sessions`` read.++ Resolution is memoized per transcript segment, so this was never on the+ per-API-call hot path (#79017) — but reading the same row twice per+ resolution was one read too many (@teknium1 on #98811), and a ``SessionDB``+ that predates the combined view has to keep the path it had.+ """++ def test_the_identity_row_is_read_once(self, db):+ db.create_session(RUN_1, source="api_server")+ reads = []+ real_get_session = db.get_session++ def counted(session_id):+ reads.append(session_id)+ return real_get_session(session_id)++ db.get_session = counted+ try:+ scope = declared_conversation_scope(_agent(RUN_1, db, CHAT_KEY))+ finally:+ del db.get_session++ assert scope.startswith("gwk_")+ assert reads == [RUN_1]++ def test_a_db_without_the_combined_view_keeps_the_two_call_path(self):+ calls = []++ class LegacyDB:+ def is_explicit_fork_child(self, sid):+ calls.append(("fork", sid))+ return False++ def get_session(self, sid):+ calls.append(("row", sid))+ return {"source": "telegram"}++ def latest_conversation_boundary(self, key, source):+ return None++ scope = declared_conversation_scope(_agent("sess-legacy", LegacyDB(), CHAT_KEY))++ assert scope is not None and scope.startswith("gwk_")+ assert calls == [("fork", "sess-legacy"), ("row", "sess-legacy")]++ def test_the_combined_read_still_fails_closed(self):+ """A fork must never merge onto its parent's key on a DB failure."""++ class BoomDB:+ def declared_scope_identity(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_the_combined_read_still_refuses_a_fork(self, db):+ db.create_session("tool-child", source="tool")++ assert declared_conversation_scope(_agent("tool-child", db, CHAT_KEY)) is None++class TestPromptCacheKeyStability:"""The reported symptom, at the wire layer: one conversation, one key."""diff --git a/tests/gateway/test_api_server_declared_conversation.py b/tests/gateway/test_api_server_declared_conversation.pyindex e6d5aa20e3c..53b64825f83 100644--- a/tests/gateway/test_api_server_declared_conversation.py+++ b/tests/gateway/test_api_server_declared_conversation.py@@ -110,7 +110,7 @@ class TestDeclaredConversationResolution:class TestConversationBoundariesRotate:- """The generation that must rotate is already durable in end_reason.+ """The boundary the recovery fence honours is durable in end_reason.#79017/#86733's contract: an affinity scope stays warm acrosscontinuation and compression rotation, and goes cold on a new