The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): retain one durable owner for failed input turns
Teknium136d80d0402d
diff --git a/evals/gateway_failure_ownership/README.md b/evals/gateway_failure_ownership/README.mdnew file mode 100644index 00000000000..aa01ab339fb--- /dev/null+++ b/evals/gateway_failure_ownership/README.md@@ -0,0 +1,61 @@+# Gateway failure-writer ownership++Offline, full gateway-handler integration: `_handle_message` → session preparation+and lease → production `_run_agent` / TurnRunner → real AIAgent → loopback HTTP/SSE+→ on-disk SQLite → gateway persistence/delivery → exception fallback.++Run from any checkout using its Python environment:++```sh+.venv/bin/python evals/gateway_failure_ownership/probe.py "$PWD" /tmp/ownership.json+scripts/run_tests.sh -j 1 tests/gateway/test_failure_writer_ownership.py+```++The first argument selects the production checkout, allowing the same fixture to+A/B another worktree. The second is the JSON receipt. The temporary HERMES_HOME is+recorded in that receipt. Inherited credentials are removed; socket connections+are restricted to loopback, tools are disabled, and all state is temporary.+No live account, messaging service, or paid provider is contacted.++## Controlled fault boundaries++- The local peer returns a real HTTP 400 for the provider-failure turn.+- A subclass raises during AIAgent construction for the pre-agent failure cases.+ All successful construction and conversation behavior is production code.+- The voice-policy callback raises after the agent and gateway persistence steps.+ Neither the handler nor its exception writer is mocked or invoked directly.+- A raw baseline read raises `TranscriptReadError` to verify fail-closed admission.++Authorization is allowed for the fixture source, topic recovery is disabled,+provider routing selects the local peer, and the agent cache is evicted per turn.+This proves handler reachability with controlled exception sources, not a claim+that any particular real Telegram or provider failure caused the reporter's rows.+The initial warmup is essential: a first-turn `session_meta` row can separate the+two user rows and mask replay coalescing.++## Evidence++Base `869228cab4a8276d3b4c78da9d9939670c47bd0f`: **6/16** checkpoints.+Fixed implementation: **16/16**, with 14 accepted user rows, same-ID failure retry+not reinserted, and unreadable-baseline input refused. Both runs made only real+loopback requests, with no blocked external connection attempts.++The original 15-checkpoint invariant was RED on base (6/15), with every controlled+exception boundary reached. The added sixteenth checkpoint tests baseline-read+refusal; base does not perform that raw read and incorrectly proceeds.+The matrix includes two separately accepted identical platform inputs, identical+keyless inputs with identical timestamps, HTTP failure and recovery, keyed/keyless+post-persistence exceptions, pre-agent failures, same-delivery failure retry,+separate identical pre-agent inputs, and a healthy follow-up.++Two invariant tests are retained. The second uses real SQLite compaction archives+and durable compression lineage with keyed/keyless input. It proves both parent+and successor-only ownership; disabling successor lookup makes it RED (3 rows+instead of 2). It does not run provider-driven compaction. Independent review+identified baseline-read, content-projection, archive, and successor-only edge+cases; ownership now avoids content comparison and includes durable lineage.++Targeted canonical runner: 25 passing tests in four files (ownership,+`test_42039_duplicate_user_message`, silence tokens, retry replacement). Broad+gateway tests are left to CI, not a local publication gate. No historical rows are+rewritten and no storage-wide deduplication is introduced.diff --git a/evals/gateway_failure_ownership/probe.py b/evals/gateway_failure_ownership/probe.pynew file mode 100644index 00000000000..4aec1b2fe1c--- /dev/null+++ b/evals/gateway_failure_ownership/probe.py@@ -0,0 +1,300 @@+import os, sys, json, asyncio, threading, tempfile, sqlite3, socket+from pathlib import Path+from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler+from types import SimpleNamespace++ROOT = Path(sys.argv[1]).resolve()+RECEIPT = Path(sys.argv[2]).resolve()+HOME = Path(tempfile.mkdtemp(prefix="hermes-104653-state-"))+# Discard inherited credentials/config, preserve only interpreter essentials.+keep = {k: v for k, v in os.environ.items() if k in ("PATH", "LANG", "LC_ALL", "TZ")}+os.environ.clear()+os.environ.update(keep)+os.environ.update(+ HOME=str(HOME),+ HERMES_HOME=str(HOME),+ HERMES_DISABLE_PLUGINS="1",+ NO_PROXY="127.0.0.1,localhost",+)+sys.path.insert(0, str(ROOT))+os.chdir(HOME)+(HOME / "config.yaml").write_text(+ "model:\n provider: openai-compat\n default: fixture-model\n context_length: 131072\nagent:\n max_iterations: 2\ncompression:\n enabled: false\ndatabase:\n journal_mode: delete\n"+)+# Fence all network calls to loopback, including optional discovery/aux paths.+orig_connect = socket.socket.connect+blocked = []+++def local_connect(self, address):+ if isinstance(address, tuple) and address[0] not in (+ "127.0.0.1",+ "::1",+ "localhost",+ ):+ blocked.append(str(address))+ raise OSError("fixture forbids external network")+ return orig_connect(self, address)+++socket.socket.connect = local_connect+requests = []+++class Peer(BaseHTTPRequestHandler):+ def log_message(self, *args):+ pass++ def do_POST(self):+ body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))+ requests.append({"path": self.path, "body": body})+ users = [+ m.get("content") for m in body.get("messages", []) if m["role"] == "user"+ ]+ fail = fault == "http400"+ if fail:+ data = {+ "error": {+ "message": "fixture invalid request",+ "type": "invalid_request_error",+ "code": "fixture_rejected",+ }+ }+ status = 400+ else:+ data = {+ "id": "chatcmpl-fixture",+ "object": "chat.completion",+ "created": 1,+ "model": "fixture-model",+ "choices": [+ {+ "index": 0,+ "message": {"role": "assistant", "content": "fixture reply"},+ "finish_reason": "stop",+ }+ ],+ "usage": {+ "prompt_tokens": 100,+ "completion_tokens": 4,+ "total_tokens": 104,+ },+ }+ status = 200+ if body.get("stream") and not fail:+ chunks = [+ {+ "id": "chatcmpl-fixture",+ "object": "chat.completion.chunk",+ "created": 1,+ "model": "fixture-model",+ "choices": [+ {+ "index": 0,+ "delta": {"role": "assistant", "content": "fixture reply"},+ "finish_reason": None,+ }+ ],+ },+ {+ "id": "chatcmpl-fixture",+ "object": "chat.completion.chunk",+ "created": 1,+ "model": "fixture-model",+ "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],+ "usage": data["usage"],+ },+ ]+ payload = (+ "".join("data: " + json.dumps(c) + "\n\n" for c in chunks)+ + "data: [DONE]\n\n"+ ).encode()+ mime = "text/event-stream"+ else:+ payload = json.dumps(data).encode()+ mime = "application/json"+ self.send_response(status)+ self.send_header("Content-Type", mime)+ self.send_header("Content-Length", str(len(payload)))+ self.end_headers()+ self.wfile.write(payload)+++server = ThreadingHTTPServer(("127.0.0.1", 0), Peer)+threading.Thread(target=server.serve_forever, daemon=True).start()+from run_agent import AIAgent+from hermes_state import SessionDB+from gateway.session import SessionStore, AsyncSessionStore, SessionSource+from gateway.config import GatewayConfig, Platform+from gateway.platforms.event import MessageEvent+from gateway.run import GatewayRunner+++import gateway.run as gateway_run++fault = None+faults = []+runtime = dict(+ api_key="fixture-only",+ base_url=f"http://127.0.0.1:{server.server_port}/v1",+ provider="openai-compat",+ api_mode="chat_completions",+)+gateway_run._resolve_runtime_agent_kwargs = lambda: runtime+import run_agent+++class ControlledAgent(AIAgent):+ def __init__(self, *args, **kwargs):+ if fault == "pre-agent":+ faults.append("agent-construction")+ raise RuntimeError("controlled agent initialization failure")+ kwargs["enabled_toolsets"] = []+ super().__init__(*args, **kwargs)+++run_agent.AIAgent = ControlledAgent+source = SessionSource(+ platform=Platform.TELEGRAM,+ chat_id="-100104653",+ chat_type="group",+ user_id="104653",+)+runner = GatewayRunner(GatewayConfig())+runner._recover_telegram_topic_thread_id = lambda source: None+runner._is_user_authorized = lambda *a: True+++def voice_policy(*args, **kwargs):+ if fault == "post-agent":+ faults.append("voice-policy-after-persistence")+ raise RuntimeError("controlled voice policy failure")+ return False+++runner._should_send_voice_reply = voice_policy+from gateway.session_transcript import TranscriptReadError++original_load = runner.session_store.load_transcript+++def controlled_load(session_id, **kwargs):+ if fault == "raw-read" and kwargs.get("raw"):+ faults.append("raw-read")+ raise TranscriptReadError(session_id)+ return original_load(session_id, **kwargs)+++runner.session_store.load_transcript = controlled_load+entry = runner.session_store.get_or_create_session(source)+sid = entry.session_id+++def rows():+ with sqlite3.connect(HOME / "state.db") as conn:+ conn.row_factory = sqlite3.Row+ return [+ dict(row)+ for row in conn.execute(+ "SELECT id,role,content,platform_message_id,timestamp FROM messages "+ "WHERE session_id=? ORDER BY id",+ (sid,),+ )+ ]+++async def main():+ global fault+ from datetime import datetime++ observations = []+ expected = []+ cases = [+ ("warmup", "100", None, True),+ ("same happy input", "101", None, True),+ ("same happy input", "102", None, True),+ ("synthetic happy", None, None, True),+ ("synthetic happy", None, None, True),+ ("failed provider input", "103", "http400", True),+ ("after failure", "104", "post-agent", True),+ ("failed provider input", "105", "http400", True),+ ("synthetic post-agent", None, "post-agent", True),+ ("init failure", "106", "pre-agent", True),+ ("init failure", "106", "pre-agent", False),+ ("init failure", "107", "pre-agent", True),+ ("synthetic init failure", None, "pre-agent", True),+ ("synthetic init failure", None, "pre-agent", True),+ ("synthetic init failure", None, "raw-read", False),+ ("healthy follow-up", "108", None, True),+ ]+ # Deliberately identical timestamps: independently accepted keyless turns must survive too.+ timestamp = datetime.fromtimestamp(1700000000)+ for text, pid, fault, accepted in cases:+ event = MessageEvent(+ text=text,+ source=source,+ message_id=pid,+ internal=pid is None,+ timestamp=timestamp,+ )+ before_requests = len(requests)+ before_faults = len(faults)+ runner._evict_cached_agent(entry.session_key)+ response = await runner._handle_message(event)+ if accepted:+ expected.append((text, pid))+ actual = [+ (r["content"], r["platform_message_id"])+ for r in rows()+ if r["role"] == "user"+ ]+ hit = faults[before_faults:]+ if fault == "raw-read":+ reached = (+ hit == ["raw-read"]+ and len(requests) == before_requests+ and "history is temporarily unavailable" in response+ )+ elif fault == "pre-agent":+ reached = hit == ["agent-construction"] and len(requests) == before_requests+ elif fault == "post-agent":+ reached = (+ hit == ["voice-policy-after-persistence"]+ and len(requests) > before_requests+ )+ else:+ reached = len(requests) > before_requests+ observations.append(+ dict(+ text=text,+ platform_id=pid,+ fault=fault,+ accepted=accepted,+ expected_users=len(expected),+ actual_users=len(actual),+ pass_=actual == expected,+ reached=reached,+ faults=hit,+ requests=len(requests) - before_requests,+ response=response,+ )+ )+ receipt = dict(+ home=str(HOME),+ observations=observations,+ rows=rows(),+ requests=len(requests),+ blocked_external_attempts=blocked,+ passed=sum(o["pass_"] and o["reached"] for o in observations),+ total=len(observations),+ )+ RECEIPT.write_text(json.dumps(receipt, indent=2))+ print(json.dumps(receipt, indent=2))+ return receipt["passed"] == receipt["total"]+++try:+ passed = asyncio.run(main())+finally:+ server.shutdown()+sys.exit(0 if passed else 1)diff --git a/gateway/run_turn.py b/gateway/run_turn.pyindex 3a861ba6320..707e2e93861 100644--- a/gateway/run_turn.py+++ b/gateway/run_turn.py@@ -1753,22 +1753,17 @@ class GatewayTurnMixin:# Retain Slack thread/workspace routing so a failed turn cannot leave its status visible.await self._hmwa_stop_typing_for_turn(event, source)logger.exception("Agent error in session %s", session_key)- # Failures before run_conversation() (provider/httpx init) can't persist the inbound turn:- # append the user message here once, unless the latest user row already matches it.+ # Replay can coalesce adjacent failed inputs; only raw durable rows establish ownership.try:if prepared.message_text is not None and session_entry is not None:- try:- _recent_transcript = await self.async_session_store.load_transcript(session_entry.session_id)- except Exception:- _recent_transcript = []- _expected_user_content = (- prepared.persist_user_message if prepared.persist_user_message is not None- else prepared.message_text- )- _last_user = next(- (_msg for _msg in reversed(_recent_transcript[-10:]) if _msg.get("role") == "user"), None,+ _rows = await self.async_session_store.load_transcript(prepared.persistence_session_id, raw=True)+ _owned = any(+ row.get("role") == "user" and (+ row.get("platform_message_id") == str(event.message_id) if event.message_id+ else row["id"] not in prepared.persisted_user_row_ids+ ) for row in _rows)- if _last_user is None or _last_user.get("content") != _expected_user_content:+ if not _owned:await self.async_session_store.append_to_transcript(session_entry.session_id, self._hmwa_user_transcript_entry(event, prepared, time.time()),)@@ -1824,6 +1819,8 @@ class GatewayTurnMixin:persist_user_message: Anypersist_user_timestamp: Anypersist_user_display_kind: Optional[str]+ persistence_session_id: Optional[str] = None+ persisted_user_row_ids: frozenset = frozenset()async def _hmwa_prepare_turn(self, event, source, session_entry, session_key, _quick_key, run_generation):"""Everything between session resolution and the agent run: session open, task-local env,@@ -1867,6 +1864,15 @@ class GatewayTurnMixin:# from []. Restore task-local context here (before the broad cleanup finally).try:history = await self.async_session_store.load_transcript(session_entry.session_id)+ history = await self._hmwa_run_session_hygiene(+ event, source, session_entry, session_key, history, _quick_key, run_generation,+ )+ # The lease gives this turn exclusive writer ownership. Snapshot after hygiene:+ # keyless inputs cannot borrow a previous identical turn's durable row.+ persisted_user_row_ids = frozenset(+ row["id"] for row in await self.async_session_store.load_transcript(+ session_entry.session_id, raw=True) if row.get("role") == "user"+ ) if not event.message_id else frozenset()except TranscriptReadError:self._clear_session_env(_session_env_tokens)return (@@ -1875,10 +1881,6 @@ class GatewayTurnMixin:"Use /reset only if you intentionally want to start a new conversation."), _session_env_tokens- history = await self._hmwa_run_session_hygiene(- event, source, session_entry, session_key, history, _quick_key, run_generation,- )-await self._hmwa_first_contact_notes(source, history, turn_sidecar_notes)# Voice channel state rides the user message ONLY when changed (in the system prompt it@@ -1908,7 +1910,7 @@ class GatewayTurnMixin:self._bind_adapter_run_generation(self._adapter_for_source(source), session_key, run_generation)return self._PreparedTurn(history, context_prompt, message_text, persist_user_message, persist_user_timestamp,- persist_user_display_kind,+ persist_user_display_kind, session_entry.session_id, persisted_user_row_ids,), _session_env_tokensasync def _handle_message_with_agent(self, event, source, _quick_key: str, run_generation: int):diff --git a/gateway/session_transcript.py b/gateway/session_transcript.pyindex ff9e795d01f..e3a1bce08a5 100644--- a/gateway/session_transcript.py+++ b/gateway/session_transcript.py@@ -453,12 +453,23 @@ class SessionTranscriptMixin:self._clear_dirty_transcript(session_id)return True- def load_transcript(self, session_id: str) -> List[Dict[str, Any]]:+ def load_transcript(self, session_id: str, *, raw: bool = False) -> List[Dict[str, Any]]:"""Load all messages from a session's transcript (state.db is canonical). Reads follow thesame routing writes use — the in-memory reroute map, then the durable compression tip —- otherwise the transcript "vanishes" while every message sits under the child."""+ otherwise the transcript "vanishes" while every message sits under the child.+ ``raw`` retains physical row identities across the launch session's compression lineage,+ including compaction archives but excluding rewinds; a parent flush may precede rotation+ or fail while the successor write succeeds."""if not self._db_for_session_id(session_id):return []+ if raw:+ try:+ db = self._db_for_session_id(session_id)+ return [row for owner in db.get_compression_lineage(session_id)+ for row in db.get_messages(owner, include_inactive=True)+ if row.get("active") or row.get("compacted")]+ except Exception as e:+ raise TranscriptReadError(session_id) from esession_id = self._follow_reroutes(session_id)with contextlib.suppress(Exception):# Durable successor survives restart; the reroute map doesn't.diff --git a/tests/gateway/test_failure_writer_ownership.py b/tests/gateway/test_failure_writer_ownership.pynew file mode 100644index 00000000000..cdcc9745580--- /dev/null+++ b/tests/gateway/test_failure_writer_ownership.py@@ -0,0 +1,105 @@+"""Accepted inbound turns have one durable owner, including exception fallback."""++import json+import subprocess+import sys+from pathlib import Path+++def test_gateway_failure_writer_preserves_accepted_turn_identity(tmp_path):+ root = Path(__file__).resolve().parents[2]+ receipt = tmp_path / "receipt.json"+ result = subprocess.run(+ [+ sys.executable,+ str(root / "evals/gateway_failure_ownership/probe.py"),+ str(root),+ str(receipt),+ ],+ capture_output=True,+ text=True,+ stdin=subprocess.DEVNULL,+ timeout=90,+ )+ assert receipt.exists(), result.stdout + result.stderr+ data = json.loads(receipt.read_text())+ assert all(row["reached"] for row in data["observations"]), data+ assert data["passed"] == data["total"], data["observations"]+ assert result.returncode == 0, result.stdout + result.stderr+++def test_failure_owner_uses_launch_rows_across_compaction(tmp_path):+ import asyncio+ import sqlite3+ from gateway.config import GatewayConfig, Platform+ from gateway.platforms.event import MessageEvent+ from gateway.run import GatewayRunner+ from gateway.session import SessionSource, SessionStore++ async def check():+ store = SessionStore(tmp_path / "sessions", GatewayConfig())+ runner = object.__new__(GatewayRunner)+ runner.session_store = store++ async def stop_typing(event, source):+ return None++ runner._hmwa_stop_typing_for_turn = stop_typing+ for index, (pid, parent_write) in enumerate(+ (pid, parent_write)+ for pid in (None, "current-platform-input")+ for parent_write in (False, True)+ ):+ source = SessionSource(+ platform=Platform.TELEGRAM,+ chat_id=f"fixture-{index}",+ user_id="fixture",+ )+ entry = store.get_or_create_session(source)+ sid = entry.session_id+ db = store._db_for_session_id(sid)+ # Existing identical input cannot supply current-turn ownership. Rich input's+ # durable text also differs from its prepared content.+ db.append_message(sid, "user", "same [screenshot]")+ baseline = frozenset(r["id"] for r in store.load_transcript(sid, raw=True))+ prepared = runner._PreparedTurn(+ [],+ "",+ "same",+ [{"type": "text", "text": "same"}],+ 1700000000,+ None,+ sid,+ baseline,+ )+ if parent_write:+ current_id = db.append_message(+ sid, "user", "same [screenshot]", platform_message_id=pid+ )+ with sqlite3.connect(db.db_path) as conn:+ conn.execute(+ "UPDATE messages SET active=0, compacted=1 WHERE id=?",+ (current_id,),+ )+ child = sid + "-child"+ db.end_session(sid, "compression")+ db.create_session(child, source="telegram", parent_session_id=sid)+ if not parent_write:+ current_id = db.append_message(+ child, "user", "same [screenshot]", platform_message_id=pid+ )+ store._publish_transcript_reroute(sid, child)+ before = db.message_count()+ await runner._hmwa_agent_error_reply(+ RuntimeError("controlled post-compaction failure"),+ MessageEvent(text="same", source=source, message_id=pid),+ source,+ entry,+ entry.session_key,+ prepared,+ )+ assert db.message_count() == before+ assert current_id in {r["id"] for r in store.load_transcript(sid, raw=True)}+ db.close()++ asyncio.run(check())diff --git a/website/docs/developer-guide/session-storage.md b/website/docs/developer-guide/session-storage.mdindex 09fcaca4506..84db5c2475c 100644--- a/website/docs/developer-guide/session-storage.md+++ b/website/docs/developer-guide/session-storage.md@@ -42,6 +42,25 @@ This also applies to synthetic/keyless input; it does not depend on a platformmessage ID. Existing historical duplicates are not rewritten. The gateway skipsits transcript write when the agent reports that it owns persistence.+## Gateway exception-path input ownership++A gateway exception can happen before the agent starts or after its input has+already reached SQLite. The exception writer checks raw durable user rows, not+replay text: replay may join adjacent unanswered inputs into one message.+Platform deliveries are identified by their inbound message ID. For keyless+internal turns, the gateway snapshots existing physical user-row IDs after+session hygiene, while holding the turn lease; a new durable user row belongs+to that turn. Separately accepted identical inputs remain separate, even with+identical timestamps.++Ownership reads include the launch session's compression lineage and archived+compaction generations, but not undone rows. This covers both a successful+parent write before rotation and a successor-only write after a failed parent+flush. An unreadable keyless baseline stops the turn with the existing+history-unavailable response rather than assuming an empty history. Normal+agent-owned transcript writes are unchanged. This is failure-writer arbitration,+not historical content deduplication or a database migration.+## Architecture Overview```