The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): keep the pre-flight's proof through a completion's turn
yoniebansfd4e277c8491
diff --git a/gateway/run_busy.py b/gateway/run_busy.pyindex e4e1b5d2f7d..bf6d7d9ed27 100644--- a/gateway/run_busy.py+++ b/gateway/run_busy.py@@ -368,7 +368,7 @@ class GatewayBusySessionMixin:# Metadata that must match for two pending events to merge into one slot._SECURITY_METADATA_KEYS = ("hermes_plugin_id", "hermes_plugin_injection", "gateway_session_key",- "gateway_session_id", "gateway_session_strict",+ "gateway_session_id", "gateway_session_strict", "gateway_proven_session_id","notification_category",)diff --git a/gateway/run_notifications.py b/gateway/run_notifications.pyindex 8ef692d645d..7af654820f8 100644--- a/gateway/run_notifications.py+++ b/gateway/run_notifications.py@@ -174,6 +174,7 @@ class GatewayNotificationsMixin(GatewayNotificationOwnershipMixin):proceed: bool = Trueearly_result: Optional[bool] = Noneowner_session_id: str = "" # owning session the pre-flight proved for the completion's pin+ proven_session_id: str = "" # session the pre-flight proved delivery reaches (a compression tip included)defer: bool = False # unadmitted retry: settle without spending a delivery attemptasync def _deliver_platform_notice(self, source, content: str) -> None:@@ -1184,6 +1185,9 @@ class GatewayNotificationsMixin(GatewayNotificationOwnershipMixin):parent_session_id = str(evt.get("parent_session_id") or "").strip()if parent_session_id:metadata["gateway_session_id"] = parent_session_id+ proven_session_id = str(evt.get("proven_session_id") or "").strip()+ if proven_session_id:+ metadata["gateway_proven_session_id"] = proven_session_id# The queued event's ``message_id`` is the message that STARTED the process, and the# persisted origin carries the same stale id. A synthetic completion is not a reply to# it: by delivery time the user has often continued elsewhere, and an event anchored@@ -1277,13 +1281,14 @@ class GatewayNotificationsMixin(GatewayNotificationOwnershipMixin):rather than falsely ack), ``"retry"`` (DB unavailable / rotation mid-flight; defer the claim)."""return (await self._classify_completion_owner(parent_session_id, session_key))[0]- async def _classify_completion_owner(self, parent_session_id: str, session_key: str = "") -> tuple[str, str]:+ async def _classify_completion_owner(self, parent_session_id: str, session_key: str = "") -> tuple[str, str, str]:"""``_classify_completion_target``'s verdict and, on ``"deliver"``, the owning session it proved- (a delegate child's pin resolved through ``model_config._delegate_from``)."""+ (a delegate child's pin resolved through ``model_config._delegate_from``) and the session delivery+ reaches (the owner, or its compression tip)."""from gateway.run import _USER_BOUNDARY_END_REASONSsession_db = getattr(self, "_session_db", None)if session_db is None:- return "retry", ""+ return "retry", "", ""entry = Noneif session_key:try:@@ -1292,10 +1297,11 @@ class GatewayNotificationsMixin(GatewayNotificationOwnershipMixin):entry = session_store._entries.get(session_key)except Exception:logger.debug("Completion route lookup failed for %s", session_key, exc_info=True)- return "retry", ""+ return "retry", "", ""verdict, parent_session_id, parent = await self._lookup_completion_owner(parent_session_id, entry.session_id if entry else "",)+ target_session_id = parent_session_idif verdict == "deliver" and parent is not None and parent.get("ended_at"):end_reason = str(parent.get("end_reason") or "")if end_reason != "compression":@@ -1303,10 +1309,12 @@ class GatewayNotificationsMixin(GatewayNotificationOwnershipMixin):# ends stay routable and the resolver retargets. Boundary set shared with the resolver.verdict = "terminal" if end_reason in _USER_BOUNDARY_END_REASONS else "deliver"else:- verdict, _ = await self._resolve_compression_lineage_target(+ verdict, target_session_id = await self._resolve_compression_lineage_target(session_db, entry, parent_session_id,)- return verdict, parent_session_id if verdict == "deliver" else ""+ if verdict != "deliver":+ return verdict, "", ""+ return verdict, parent_session_id, target_session_id or parent_session_id@staticmethoddef _settle_durable_claim(kind: str, delegation_id: str, claim_id: str) -> None:@@ -1387,7 +1395,7 @@ class GatewayNotificationsMixin(GatewayNotificationOwnershipMixin):# can still fail closed inside the message pipeline AFTER the adapter accepted, which would falsely# acknowledge the durable row as delivered. Verify the target here, before acceptance, and give# drops an honest durable disposition.- verdict, claim.owner_session_id = await self._classify_completion_owner(+ verdict, claim.owner_session_id, claim.proven_session_id = await self._classify_completion_owner(parent_session_id, str(evt.get("session_key") or ""))if verdict == "terminal":if evt_type == "async_delegation":@@ -1484,7 +1492,8 @@ class GatewayNotificationsMixin(GatewayNotificationOwnershipMixin):identity_claimed = Trueif claim.owner_session_id:# Admission settles the durable claim, so the resolver starts from the owner proven here.- evt = {**evt, "parent_session_id": claim.owner_session_id}+ evt = {**evt, "parent_session_id": claim.owner_session_id,+ "proven_session_id": claim.proven_session_id}injection_result = await self._inject_watch_notification(synth_text, evt, raise_not_accepted=True)if injection_result is not True:return injection_resultdiff --git a/gateway/run_notifications_ownership.py b/gateway/run_notifications_ownership.pyindex d70fbeea6aa..55ba5141f26 100644--- a/gateway/run_notifications_ownership.py+++ b/gateway/run_notifications_ownership.py@@ -111,7 +111,7 @@ class GatewayNotificationOwnershipMixin:return "terminal", session_id, Noneasync def _resolve_async_delegation_session(- self, session_entry: SessionEntry, pinned_session_id: str,+ self, session_entry: SessionEntry, pinned_session_id: str, proven_session_id: str = "",) -> Optional[SessionEntry]:"""Resolve an async completion to its verified owning gateway session.@@ -135,6 +135,9 @@ class GatewayNotificationOwnershipMixin:"dropping injection (#55578 fail-closed).")return None+ if proven_session_id and proven_session_id == session_entry.session_id:+ # Admission already settled the durable claim on this proof; another read could only lose it.+ return session_entry# Snapshot before ownership awaits: a concurrent /stop or /new wins.run_generation = self._current_session_run_generation(session_entry.session_key)verdict, pinned_session_id, pinned_row = await self._lookup_completion_owner(diff --git a/gateway/run_turn.py b/gateway/run_turn.pyindex cdb3146450b..03bb8093039 100644--- a/gateway/run_turn.py+++ b/gateway/run_turn.py@@ -448,7 +448,7 @@ class GatewayTurnMixin:)session_key = session_entry.session_keyif not strict_session and pinned_session_id:- resolved_entry = await self._resolve_async_delegation_session(session_entry, pinned_session_id)+ resolved_entry = await self._resolve_async_delegation_session(session_entry, pinned_session_id, event_metadata.get("gateway_proven_session_id") or "")if resolved_entry is None:returnsession_entry = resolved_entrydiff --git a/tests/gateway/test_completion_owner_retry.py b/tests/gateway/test_completion_owner_retry.pyindex c1bf4228d27..75daf2c1662 100644--- a/tests/gateway/test_completion_owner_retry.py+++ b/tests/gateway/test_completion_owner_retry.py@@ -186,12 +186,52 @@ async def test_claimed_ownership_retries_do_not_spend_the_delivery_budget(runner.close_all_session_db_handles()+async def _admit_with_session_rows_unreadable(runner, store, entry, monkeypatch, delegation_id, pinned):+ """Deliver one completion; every session-row read raises once the adapter has accepted it."""+ async_db = runner._session_db+ get_session = async_db.get_session+ admitted_phase = False++ async def lookup_session(sid):+ if admitted_phase:+ raise RuntimeError("session rows unreadable after admission")+ return await get_session(sid)++ monkeypatch.setattr(async_db, "get_session", lookup_session)+ resolved = []++ async def accept(event):+ nonlocal admitted_phase+ admitted_phase = True+ current = store.lookup_by_session_key(entry.session_key)+ assert current is not None+ result = await runner._resolve_async_delegation_session(+ current, event.metadata["gateway_session_id"],+ proven_session_id=event.metadata.get("gateway_proven_session_id", ""),+ )+ resolved.append(result.session_id if result else None)+ event._gateway_accepted = True++ runner.adapters[Platform.TELEGRAM] = cast(BasePlatformAdapter, SimpleNamespace(handle_message=accept))+ event = {+ "type": "async_delegation", "delegation_id": delegation_id,+ "session_key": entry.session_key, "parent_session_id": pinned,+ "dispatched_at": 1.0, "status": "completed", "summary": "completed result",+ }+ ad._persist_dispatch(event)+ ad._persist_completion(event, {"status": "completed", "summary": event["summary"]})+ assert await runner._deliver_completion_notification("completed result", event) is True+ delivered = ad.get_durable_delegation(delegation_id)+ assert delivered is not None and delivered["delivery_state"] == "delivered"+ return resolved++@pytest.mark.asyncio-async def test_admitted_delegate_completion_reaches_owner_without_rereading_the_chain(+async def test_admitted_delegate_completion_reaches_owner_without_reading_ownership_again(tmp_path, monkeypatch, private_db_probe_cleanup,):"""Admission acknowledges the durable claim, so the resolver must reach the owner preflight proved- even when the delegate chain cannot be read afterwards."""+ even when no session row can be read afterwards."""with _profile_runtime_scope(tmp_path):runner = GatewayRunner(GatewayConfig(sessions_dir=tmp_path / "sessions"))store = runner.session_store@@ -203,44 +243,43 @@ async def test_admitted_delegate_completion_reaches_owner_without_rereading_the_owner = entry.session_iddb.create_session("worker", source="subagent", model_config={"_delegate_from": owner})db.create_session("nested-worker", source="subagent", model_config={"_delegate_from": "worker"})- async_db = runner._session_db- get_session = async_db.get_session- admitted_phase = False- async def lookup_session(sid):- if admitted_phase and sid in {"worker", "nested-worker"}:- raise RuntimeError("delegate chain unreadable after admission")- return await get_session(sid)+ resolved = await _admit_with_session_rows_unreadable(+ runner, store, entry, monkeypatch, "owner-admitted", "nested-worker")- monkeypatch.setattr(async_db, "get_session", lookup_session)- resolved = []+ assert resolved == [owner]+ current = store.lookup_by_session_key(entry.session_key)+ assert current is not None and current.session_id == owner+ finally:+ store.close_all_db_handles()+ runner.close_all_session_db_handles()- async def accept(event):- nonlocal admitted_phase- admitted_phase = True- current = store.lookup_by_session_key(entry.session_key)- assert current is not None- result = await runner._resolve_async_delegation_session(- current, event.metadata["gateway_session_id"],- )- resolved.append(result.session_id if result else None)- event._gateway_accepted = True- runner.adapters[Platform.TELEGRAM] = cast(BasePlatformAdapter, SimpleNamespace(handle_message=accept))- event = {- "type": "async_delegation", "delegation_id": "owner-admitted",- "session_key": entry.session_key, "parent_session_id": "nested-worker",- "dispatched_at": 1.0, "status": "completed", "summary": "completed result",- }- ad._persist_dispatch(event)- ad._persist_completion(event, {"status": "completed", "summary": event["summary"]})+async def test_admitted_completion_reaches_compressed_owners_tip_without_reading_lineage_again(+ tmp_path, monkeypatch, private_db_probe_cleanup,+):+ """A compressed owner is proven through its live tip before admission; delivery reads no lineage after it."""+ with _profile_runtime_scope(tmp_path):+ runner = GatewayRunner(GatewayConfig(sessions_dir=tmp_path / "sessions"))+ store = runner.session_store+ try:+ entry = store.get_or_create_session(SessionSource(+ platform=Platform.TELEGRAM, chat_id="ownership-compressed", chat_type="dm",+ ))+ db = cast(Any, store._db)+ owner = entry.session_id+ db.create_session("worker", source="subagent", model_config={"_delegate_from": owner})+ db.create_session("owner-tip", source="telegram", parent_session_id=owner)+ db.end_session(owner, end_reason="compression")+ assert store.advance_compression_session(entry.session_key, owner, "owner-tip") is not None- assert await runner._deliver_completion_notification("completed result", event) is True- assert resolved == [owner]- delivered = ad.get_durable_delegation(event["delegation_id"])- assert delivered is not None and delivered["delivery_state"] == "delivered"+ resolved = await _admit_with_session_rows_unreadable(+ runner, store, entry, monkeypatch, "tip-admitted", "worker")++ assert resolved == ["owner-tip"]current = store.lookup_by_session_key(entry.session_key)- assert current is not None and current.session_id == owner+ assert current is not None and current.session_id == "owner-tip"finally:store.close_all_db_handles()runner.close_all_session_db_handles()