The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): carry accepted-input ownership through persistence
Teknium3114916ee4bc
diff --git a/agent/turn_context.py b/agent/turn_context.pyindex 6f36e3524bf..6ecb93a3134 100644--- a/agent/turn_context.py+++ b/agent/turn_context.py@@ -518,8 +518,8 @@ def _stage_turn_user_message(# row; the model still receives role/content unchanged (api_messages strips both).if persist_user_display_kind:user_msg["display_kind"] = persist_user_display_kind- if persist_user_display_metadata:- user_msg["display_metadata"] = persist_user_display_metadata+ if persist_user_display_metadata:+ user_msg["display_metadata"] = persist_user_display_metadata# The platform message id survives the turn-start flush; restart drain-window# recovery dedups via ``has_platform_message_id`` against this row.if persist_user_platform_id is not None:diff --git a/evals/gateway_failure_ownership/README.md b/evals/gateway_failure_ownership/README.mdindex c910e80f61a..c08761fbc4a 100644--- a/evals/gateway_failure_ownership/README.md+++ b/evals/gateway_failure_ownership/README.md@@ -1,63 +1,63 @@# 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:+Offline integration: `_handle_message` → session preparation and lease → production+`_run_agent` / TurnRunner → real AIAgent → loopback HTTP/SSE → on-disk SQLite →+gateway persistence/delivery → exception fallback.```sh.venv/bin/python evals/gateway_failure_ownership/probe.py "$PWD" /tmp/ownership.jsonscripts/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). A new ambient observed row must not masquerade as the accepted-input; that negative control was also RED/GREEN verified. 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.+The first argument selects the production checkout, so the same fixture can A/B+another checkout without editing it. The receipt records its temporary HERMES_HOME.+Inherited credentials are cleared, tools are disabled, and socket connections are+restricted to loopback. No live messaging account or paid provider is contacted.++## Fault boundaries and controls++- Real HTTP 400 from the loopback peer; successful replies use HTTP/SSE.+- Controlled AIAgent constructor failure, or voice-policy failure after persistence.+ The handler and exception writer remain production code.+- Chat A succeeds with ID `100`; chat B resumes that session and fails construction+ with a different input and the same ID. Both inputs must remain, with unmodified+ platform IDs for quote/reply lookup.+- A separate Python process commits an unrelated, nonobserved input during a keyless+ constructor failure. Both writers' inputs must survive; the gateway lease is not+ treated as universal writer authority.+- Separately accepted identical keyed/keyless inputs, identical timestamps,+ same-delivery pre-agent retry, provider failure/recovery, and healthy follow-up.+- A normal history read fails closed before agent construction. There is no longer+ a raw baseline to read or an extra keyless admission query.+- 5,000 archived 4-KiB rows remain in SQLite. The complete keyless failure handler+ must stay below 8 MiB traced peak allocation, with zero raw transcript scans.+- Durable owner markers are unique across accepted inputs and absent from provider+ wire messages. The foreign writer supplies its own independent marker.++The second invariant uses real SQLite archives and a compression tree containing+an earlier `ws_orphan_reap` sibling and a live successor. It checks both published+reroutes and map-free restart routing; root/middle ancestors and successor writes+can establish ownership, while reaped, undone, observed, foreign-marker, and+unmarked rows cannot. These are storage-boundary checks, not provider-driven+compaction.++## Receipts++The expanded full-handler matrix has 20 checkpoints (19 deliveries plus marker+propagation). Base `869228cab4a8276d3b4c78da9d9939670c47bd0f`: **7/20**; reviewed+intermediate `653cd72ef63b013798748774a2509f453b566a77`: **1/20**; fixed: **20/20**.+All fault boundaries were reached. Base and fixed runs made 10 loopback requests+and recorded zero external connection attempts. Counts are cumulative exact-row+sequence checks, not independent defect counts.++The reviewed intermediate lost chat B's input (1 row instead of 2), also lost the+keyless input beside the independent writer, and allocated 28,034,300 bytes in+the archived-history handler. The fixed run retained all 18 expected active user+rows (including the independent writer) and used 107,679 bytes in that handler.+The memory measurement excludes fixture seeding and receipt serialization.++Exactly two invariant tests are retained. Eleven targeted files passed 63 tests;+broader directory suites and CI are not claimed. No historical rows are rewritten.+Existing rows without a marker cannot establish delivery ownership, so historical+redelivery is not deduplicated by this mechanism. This is exception-path input+arbitration, not global exactly-once delivery or content deduplication.diff --git a/evals/gateway_failure_ownership/foreign_writer.py b/evals/gateway_failure_ownership/foreign_writer.pynew file mode 100644index 00000000000..a7095416d90--- /dev/null+++ b/evals/gateway_failure_ownership/foreign_writer.py@@ -0,0 +1,13 @@+"""Independent durable writer used only by the loopback ownership probe."""+import sys+from pathlib import Path++sys.path.insert(0, str(Path(sys.argv[1]).resolve()))+from hermes_state import SessionDB++db = SessionDB(db_path=Path(sys.argv[2]))+db.append_message(+ sys.argv[3], "user", "foreign independent input", observed=False,+ display_metadata={"gateway_input_owner": "independent-process-owner"},+)+db.close()diff --git a/evals/gateway_failure_ownership/probe.py b/evals/gateway_failure_ownership/probe.pyindex 4aec1b2fe1c..1589c260fd4 100644--- a/evals/gateway_failure_ownership/probe.py+++ b/evals/gateway_failure_ownership/probe.py@@ -1,4 +1,4 @@-import os, sys, json, asyncio, threading, tempfile, sqlite3, socket+import os, sys, json, asyncio, threading, tempfile, sqlite3, socket, subprocess, tracemallocfrom pathlib import Pathfrom http.server import ThreadingHTTPServer, BaseHTTPRequestHandlerfrom types import SimpleNamespace@@ -146,7 +146,16 @@ import run_agentclass ControlledAgent(AIAgent):def __init__(self, *args, **kwargs):- if fault == "pre-agent":+ if fault == "foreign-writer":+ result = subprocess.run(+ [sys.executable, str(Path(__file__).with_name("foreign_writer.py")),+ str(ROOT), str(HOME / "state.db"), sid],+ capture_output=True, text=True, stdin=subprocess.DEVNULL, timeout=20,+ )+ assert result.returncode == 0, result.stderr+ faults.append("foreign-writer-committed")+ raise RuntimeError("controlled construction failure after independent write")+ if fault in ("pre-agent", "archive-memory"):faults.append("agent-construction")raise RuntimeError("controlled agent initialization failure")kwargs["enabled_toolsets"] = []@@ -178,9 +187,24 @@ from gateway.session_transcript import TranscriptReadErrororiginal_load = runner.session_store.load_transcript+raw_reads = []+original_get_messages = SessionDB.get_messages+++def observed_get_messages(self, session_id, *args, **kwargs):+ if kwargs.get("include_inactive") or kwargs.get("include_compacted") or any(args[:2]):+ raw_reads.append(session_id)+ return original_get_messages(self, session_id, *args, **kwargs)+++SessionDB.get_messages = observed_get_messages++def controlled_load(session_id, **kwargs):- if fault == "raw-read" and kwargs.get("raw"):- faults.append("raw-read")+ if kwargs.get("raw"):+ raw_reads.append(session_id)+ if fault == "history-read":+ faults.append("history-read")raise TranscriptReadError(session_id)return original_load(session_id, **kwargs)@@ -196,7 +220,7 @@ def rows():return [dict(row)for row in conn.execute(- "SELECT id,role,content,platform_message_id,timestamp FROM messages "+ "SELECT id,role,content,platform_message_id,timestamp,display_metadata,active,compacted FROM messages ""WHERE session_id=? ORDER BY id",(sid,),)@@ -204,13 +228,14 @@ def rows():async def main():- global fault+ global fault, source, entryfrom datetime import datetimeobservations = []expected = []cases = [- ("warmup", "100", None, True),+ ("chat A input", "100", None, True),+ ("chat B distinct input", "100", "pre-agent", True),("same happy input", "101", None, True),("same happy input", "102", None, True),("synthetic happy", None, None, True),@@ -224,12 +249,20 @@ async def main():("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),+ ("synthetic init failure", None, "history-read", False),+ ("keyless independent-writer input", None, "foreign-writer", True),+ ("bounded archive input", None, "archive-memory", True),("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:+ if text == "chat B distinct input":+ from dataclasses import replace+ source = replace(source, chat_id="chat-B")+ other = runner.session_store.get_or_create_session(source)+ entry = runner.session_store.switch_session(other.session_key, sid)+ assert entryevent = MessageEvent(text=text,source=source,@@ -237,25 +270,43 @@ async def main():internal=pid is None,timestamp=timestamp,)+ if fault == "archive-memory":+ # Large archived payloads must stay in SQLite, not become a Python baseline.+ with sqlite3.connect(HOME / "state.db") as conn:+ conn.executemany(+ "INSERT INTO messages (session_id, role, content, timestamp, active, compacted) "+ "VALUES (?, 'user', ?, 1, 0, 1)",+ ((sid, "x" * 4096) for _ in range(5000)),+ )+ tracemalloc.start()+ before_raw = len(raw_reads)before_requests = len(requests)before_faults = len(faults)runner._evict_cached_agent(entry.session_key)response = await runner._handle_message(event)+ peak = None+ if fault == "archive-memory":+ _, peak = tracemalloc.get_traced_memory()+ tracemalloc.stop()+ if fault == "foreign-writer":+ expected.append(("foreign independent input", None))if accepted:expected.append((text, pid))actual = [(r["content"], r["platform_message_id"])for r in rows()- if r["role"] == "user"+ if r["role"] == "user" and r["active"]]hit = faults[before_faults:]- if fault == "raw-read":+ if fault == "history-read":reached = (- hit == ["raw-read"]+ hit == ["history-read"]and len(requests) == before_requestsand "history is temporarily unavailable" in response)- elif fault == "pre-agent":+ elif fault == "foreign-writer":+ reached = hit == ["foreign-writer-committed"] and len(requests) == before_requests+ elif fault in ("pre-agent", "archive-memory"):reached = hit == ["agent-construction"] and len(requests) == before_requestselif fault == "post-agent":reached = (@@ -272,17 +323,28 @@ async def main():accepted=accepted,expected_users=len(expected),actual_users=len(actual),- pass_=actual == expected,+ pass_=actual == expected and len(raw_reads) == before_raw+ and (peak is None or peak < 8 * 1024 * 1024),+ raw_reads=len(raw_reads) - before_raw,+ archive_peak_bytes=peak,reached=reached,faults=hit,requests=len(requests) - before_requests,response=response,))+ users = [r for r in rows() if r["role"] == "user" and r["active"]]+ markers = [json.loads(r["display_metadata"] or "{}").get("gateway_input_owner") for r in users]+ observations.append(dict(+ text="durable marker propagation", reached=bool(users),+ pass_=all(isinstance(m, str) and m for m in markers) and len(set(markers)) == len(markers)+ and all("display_metadata" not in m for request in requests+ for m in request["body"].get("messages", [])),+ ))receipt = dict(home=str(HOME),observations=observations,- rows=rows(),+ rows=[r for r in rows() if r["active"]],requests=len(requests),blocked_external_attempts=blocked,passed=sum(o["pass_"] and o["reached"] for o in observations),diff --git a/gateway/run_turn.py b/gateway/run_turn.pyindex a0fc7ca6d8e..b42ba50eb5d 100644--- a/gateway/run_turn.py+++ b/gateway/run_turn.py@@ -1607,6 +1607,8 @@ class GatewayTurnMixin:}if prepared.persist_user_display_kind:_user_entry["display_kind"] = prepared.persist_user_display_kind+ if prepared.persistence_owner:+ _user_entry["display_metadata"] = {"gateway_input_owner": prepared.persistence_owner}if getattr(event, "message_id", None):_user_entry["message_id"] = str(event.message_id)return _user_entry@@ -1753,15 +1755,11 @@ 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)- # Replay can coalesce adjacent failed inputs; only raw durable rows establish ownership.+ # Replay can coalesce inputs; only this input's durable marker establishes ownership.try:if prepared.message_text is not None and session_entry is not None:- _rows = await self.async_session_store.load_transcript(prepared.persistence_session_id, raw=True)- _owned = any(- row.get("role") == "user" and not row.get("observed") 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+ _owned = await self.async_session_store.has_input_owner(+ prepared.persistence_session_id, prepared.persistence_owner,)if not _owned:await self.async_session_store.append_to_transcript(@@ -1820,7 +1818,7 @@ class GatewayTurnMixin:persist_user_timestamp: Anypersist_user_display_kind: Optional[str]persistence_session_id: Optional[str] = None- persisted_user_row_ids: frozenset = frozenset()+ persistence_owner: Optional[str] = Noneasync 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,12 +1865,6 @@ class GatewayTurnMixin: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 (@@ -1908,9 +1900,16 @@ class GatewayTurnMixin:# Bind this run generation to the adapter so deferred post-delivery callbacks are released# by the run that registered them.self._bind_adapter_run_generation(self._adapter_for_source(source), session_key, run_generation)+ # Delivery IDs are only unique in their transport namespace. Keyless turns+ # need their own identity, even when another process writes to this session.+ import uuid+ namespace = [source.platform.value, source.profile, source.scope_id,+ source.chat_id, source.thread_id, str(event.message_id)]+ owner = (str(uuid.uuid5(uuid.NAMESPACE_URL, json.dumps(namespace)))+ if event.message_id else str(uuid.uuid4()))return self._PreparedTurn(history, context_prompt, message_text, persist_user_message, persist_user_timestamp,- persist_user_display_kind, session_entry.session_id, persisted_user_row_ids,+ persist_user_display_kind, session_entry.session_id, owner,), _session_env_tokensasync def _handle_message_with_agent(self, event, source, _quick_key: str, run_generation: int):@@ -1961,6 +1960,7 @@ class GatewayTurnMixin:persist_user_message=prepared.persist_user_message,persist_user_timestamp=prepared.persist_user_timestamp,persist_user_display_kind=prepared.persist_user_display_kind,+ persist_user_display_metadata={"gateway_input_owner": prepared.persistence_owner},message_type=event.message_type,)_turn_seconds = time.monotonic() - _turn_started_monotonic@@ -3775,6 +3775,7 @@ class GatewayTurnMixin:channel_prompt: Optional[str] = None, moa_config: Optional[dict] = None,persist_user_message: Optional[Any] = None, persist_user_timestamp: Optional[float] = None,persist_user_display_kind: Optional[str] = None, message_type: Optional[str] = None,+ persist_user_display_metadata: Optional[dict] = None,) -> Dict[str, Any]:"""Run the agent; returns the full run_conversation result dict.@@ -3798,6 +3799,7 @@ class GatewayTurnMixin:persist_user_message=persist_user_message,persist_user_timestamp=persist_user_timestamp,persist_user_display_kind=persist_user_display_kind,+ persist_user_display_metadata=persist_user_display_metadata,)_status_thread_metadata = self._run_agent_bind_turn_wiring(turn_ctx, turn_runner, source, event_message_id, disp._native_slack_task_cards,diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.pyindex 6449454b19f..7d7284e420c 100644--- a/gateway/run_turn_runner.py+++ b/gateway/run_turn_runner.py@@ -1430,6 +1430,8 @@ class TurnRunner:# Internal self-injected turn: type the persisted user row so UIs render it as a# timeline notice, not a user bubble (stripped from provider payloads downstream).kwargs["persist_user_display_kind"] = ctx.persist_user_display_kind+ if ctx.persist_user_display_metadata:+ kwargs["persist_user_display_metadata"] = ctx.persist_user_display_metadataif ctx.moa_config is not None:kwargs["moa_config"] = ctx.moa_configif persist_user_timestamp_override is not None:diff --git a/gateway/session_transcript.py b/gateway/session_transcript.pyindex e3a1bce08a5..50ade91a3a7 100644--- a/gateway/session_transcript.py+++ b/gateway/session_transcript.py@@ -453,23 +453,35 @@ class SessionTranscriptMixin:self._clear_dirty_transcript(session_id)return True- def load_transcript(self, session_id: str, *, raw: bool = False) -> List[Dict[str, Any]]:+ def has_input_owner(self, session_id: str, owner: str) -> bool:+ """Find this accepted input on the canonical live continuation and its ancestors.++ Content and unrelated writers cannot establish ownership. Query only existence;+ compaction archives can contain many megabytes that replay never needs to load.+ """+ try:+ current = self._follow_reroutes(session_id)+ db = self._db_for_session_id(current)+ current = db.get_compression_tip(current) or current+ seen = set()+ while current and current not in seen:+ seen.add(current)+ if db.has_gateway_input_owner(current, owner):+ return True+ row = db.get_session(current)+ if not row or not db._is_compression_child_row(row):+ break+ current = row["parent_session_id"]+ return False+ except Exception as e:+ raise TranscriptReadError(session_id) from e++ def load_transcript(self, session_id: str) -> 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.- ``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."""+ otherwise the transcript "vanishes" while every message sits under the child."""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/gateway/turn_context.py b/gateway/turn_context.pyindex bfe807ca656..aa2ce650b91 100644--- a/gateway/turn_context.py+++ b/gateway/turn_context.py@@ -56,6 +56,7 @@ class TurnContext:# display_kind of the persisted user row for a self-injected turn; DB-only, never sent.# "internal_notification" for async-delegation/background notifications (#82888).persist_user_display_kind: Optional[str] = None+ persist_user_display_metadata: Optional[dict] = Noneuser_config: Any = Noneenabled_toolsets: Any = Nonedisabled_toolsets: Any = Nonediff --git a/hermes_state_messages.py b/hermes_state_messages.pyindex 07cb4c69ee5..c81ec6e8cb3 100644--- a/hermes_state_messages.py+++ b/hermes_state_messages.py@@ -1048,6 +1048,15 @@ class SessionMessagesMixin:sql = "SELECT COUNT(*) FROM messages" + (" WHERE session_id = ?" if session_id else "")return self._read_one(sql, (session_id,) if session_id else ())[0]+ def has_gateway_input_owner(self, session_id: str, owner: str) -> bool:+ """Probe the accepted-input marker without allocating message bodies or archives."""+ return self._read_one(+ "SELECT 1 FROM messages WHERE session_id = ? AND role = 'user' "+ "AND observed = 0 AND (active = 1 OR compacted = 1) "+ "AND CASE WHEN json_valid(display_metadata) "+ "THEN json_extract(display_metadata, '$.gateway_input_owner') END = ? LIMIT 1",+ (session_id, owner)) is not None+def has_platform_message_id(self, session_id: str, platform_message_id: str) -> bool:"""True when *platform_message_id* exists (partial-index probe; the gateway's transient-failure dedupe).diff --git a/tests/gateway/test_failure_writer_ownership.py b/tests/gateway/test_failure_writer_ownership.pyindex eff0ad7aca8..cc10b6ed402 100644--- a/tests/gateway/test_failure_writer_ownership.py+++ b/tests/gateway/test_failure_writer_ownership.py@@ -28,7 +28,7 @@ def test_gateway_failure_writer_preserves_accepted_turn_identity(tmp_path):assert result.returncode == 0, result.stdout + result.stderr-def test_failure_owner_uses_launch_rows_across_compaction(tmp_path):+def test_failure_owner_follows_only_live_lineage_markers(tmp_path):import asyncioimport sqlite3from gateway.config import GatewayConfig, Platform@@ -45,81 +45,65 @@ def test_failure_owner_uses_launch_rows_across_compaction(tmp_path):return Nonerunner._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)+ # An archived ancestor or the published live child can own a turn. Neither+ # a reaped sibling nor undone/observed/foreign-marker rows can own it.+ cases = ("ancestor", "middle-ancestor", "live-child", "reaped", "undone", "observed", "foreign", "unmarked")+ for index, (location, pid) in enumerate(+ (location, pid) for location in cases for pid in (None, "100")):source = SessionSource(- platform=Platform.TELEGRAM,- chat_id=f"fixture-{index}",- user_id="fixture",+ platform=Platform.TELEGRAM, chat_id=f"fixture-{index}", user_id="fixture")entry = store.get_or_create_session(source)sid = entry.session_iddb = 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))+ owner = f"accepted-owner-{index}"+ metadata = {"gateway_input_owner": owner}prepared = runner._PreparedTurn(- [],- "",- "same",- [{"type": "text", "text": "same"}],- 1700000000,- None,- sid,- baseline,+ [], "", "same", [{"type": "text", "text": "same"}],+ 1700000000, None, sid, owner,+ )+ db.append_message(sid, "user", "same [screenshot]")+ middle = sid + "-middle"+ db.create_session(middle, source="telegram", parent_session_id=sid)+ orphan = sid + "-orphan"+ child = sid + "-live"+ db.create_session(orphan, source="telegram", parent_session_id=middle)+ db.end_session(orphan, "ws_orphan_reap")+ db.create_session(child, source="telegram", parent_session_id=middle)+ target = {"ancestor": sid, "middle-ancestor": middle, "reaped": orphan}.get(location, child)+ marker = {"gateway_input_owner": "foreign-writer"} if location == "foreign" else metadata+ current_id = db.append_message(+ target, "user", "same [screenshot]", platform_message_id=pid,+ observed=location == "observed",+ display_metadata=None if location == "unmarked" else marker,)- if parent_write:- current_id = db.append_message(- sid, "user", "same [screenshot]", platform_message_id=pid- )+ db.end_session(sid, "compression")+ db.end_session(middle, "compression")+ if location in ("ancestor", "middle-ancestor", "undone"):with sqlite3.connect(db.db_path) as conn:conn.execute(- "UPDATE messages SET active=0, compacted=1 WHERE id=?",- (current_id,),+ "UPDATE messages SET active=0, compacted=? WHERE id=?",+ (int(location != "undone"), 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)+ owned = location in ("ancestor", "middle-ancestor", "live-child")+ assert store.has_input_owner(sid, owner) is owned, location+ # A restarted store has no published map and must pick the same live child.+ store._transcript_reroutes.clear()+ assert store.has_input_owner(sid, owner) is owned, locationbefore = 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,+ 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)}- source = SessionSource(- platform=Platform.TELEGRAM, chat_id="observed", user_id="fixture"- )- entry = store.get_or_create_session(source)- sid = entry.session_id- prepared = runner._PreparedTurn(- [], "", "accepted", "accepted", 1700000000, None, sid- )- db.append_message(sid, "user", "ambient observation", observed=True)- before = db.message_count()- await runner._hmwa_agent_error_reply(- RuntimeError("controlled pre-agent failure"),- MessageEvent(text="accepted", source=source, message_id=None),- source,- entry,- entry.session_key,- prepared,- )- assert db.message_count() == before + 1- assert db.get_messages(sid)[-1]["content"] == "accepted"+ assert db.message_count() == before + (not owned), location+ assert store.has_input_owner(sid, owner), location+ if not owned:+ latest = db.get_messages(child)[-1]+ assert latest["content"] == prepared.persist_user_message+ assert latest["display_metadata"]["gateway_input_owner"] == ownerdb.close()asyncio.run(check())diff --git a/website/docs/developer-guide/session-storage.md b/website/docs/developer-guide/session-storage.mdindex 995e4ec1ff1..23cdb2b412a 100644--- a/website/docs/developer-guide/session-storage.md+++ b/website/docs/developer-guide/session-storage.md@@ -44,22 +44,26 @@ its 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 or ambient observed messages. 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.+A gateway exception can occur before agent construction or after its input reaches+SQLite. The gateway gives the accepted input an owner marker in the existing+`display_metadata` sidecar and passes it through the agent's normal persistence+path. Provider messages never contain this metadata. Platform markers namespace+the inbound message ID by platform, profile, scope, chat, and thread; the original+`platform_message_id` remains unchanged for quote/reply resolution. Keyless turns+receive a fresh marker, even for identical text and timestamps.++The exception writer probes only for that marker, following the published reroute+and canonical live compression successor, then compression ancestors. Active rows+and compaction archives count; undone rows, observed input, and unrelated writers+do not. An unrelated process writing the same session cannot suppress this turn.+No whole-history baseline or archived message-body allocation is needed. Failed+ownership reads do not authorize a speculative append; ordinary history-read+failures retain the existing history-unavailable response.++Normal agent-owned persistence is unchanged. This is failure-writer arbitration,+not universal exactly-once delivery, content deduplication, or a schema migration.+Historical rows are not rewritten; unmarked historical inputs cannot establish+ownership for a redelivered event.## Architecture Overview