The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): hand the resolver the owner the completion pre-flight proved
yoniebans7d432912d17d
diff --git a/gateway/run_notifications.py b/gateway/run_notifications.pyindex 034d1c2b425..0d60d897a83 100644--- a/gateway/run_notifications.py+++ b/gateway/run_notifications.py@@ -173,6 +173,7 @@ class GatewayNotificationsMixin(GatewayNotificationOwnershipMixin):claim_id: str = ""proceed: bool = Trueearly_result: Optional[bool] = None+ owner_session_id: str = "" # owning session the pre-flight proved for the completion's pindefer: bool = False # unadmitted retry: settle without spending a delivery attemptasync def _deliver_platform_notice(self, source, content: str) -> None:@@ -1273,11 +1274,16 @@ class GatewayNotificationsMixin(GatewayNotificationOwnershipMixin):"""Classify an async-completion target before adapter acceptance: ``"deliver"`` (spawningsession live or compression-rotated with a live continuation; the resolver still retargets),``"terminal"`` (parent gone for good — unknown / user boundary like /new; drop the durable row- rather than falsely ack), ``"retry"`` (DB unavailable / rotation mid-flight; release the claim)."""+ 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]:+ """``_classify_completion_target``'s verdict and, on ``"deliver"``, the owning session it proved+ (a delegate child's pin resolved through ``model_config._delegate_from``)."""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:@@ -1286,23 +1292,21 @@ 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 "",)- if verdict != "deliver" or parent is None:- return verdict- if not parent.get("ended_at"):- return "deliver"- end_reason = str(parent.get("end_reason") or "")- if end_reason != "compression":- # Only a USER-closed session (/new, user_exit, session_switch) is unreachable; idle/timeout- # ends stay routable and the resolver retargets. Boundary set shared with the resolver.- return "terminal" if end_reason in _USER_BOUNDARY_END_REASONS else "deliver"- verdict, _ = await self._resolve_compression_lineage_target(- session_db, entry, parent_session_id,- )- return verdict+ if verdict == "deliver" and parent is not None and parent.get("ended_at"):+ end_reason = str(parent.get("end_reason") or "")+ if end_reason != "compression":+ # Only a USER-closed session (/new, user_exit, session_switch) is unreachable; idle/timeout+ # 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(+ session_db, entry, parent_session_id,+ )+ return verdict, parent_session_id if verdict == "deliver" else ""@staticmethoddef _settle_durable_claim(kind: str, delegation_id: str, claim_id: str) -> None:@@ -1383,7 +1387,8 @@ 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 = await self._classify_completion_target(parent_session_id, str(evt.get("session_key") or ""))+ verdict, claim.owner_session_id = await self._classify_completion_owner(+ parent_session_id, str(evt.get("session_key") or ""))if verdict == "terminal":if evt_type == "async_delegation":logger.warning(@@ -1459,6 +1464,9 @@ class GatewayNotificationsMixin(GatewayNotificationOwnershipMixin):if self._completion_identity_seen(identity, claim=True):return Noneidentity_claimed = True+ if 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}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/tests/gateway/test_background_process_notifications.py b/tests/gateway/test_background_process_notifications.pyindex 877521be264..9493caa7885 100644--- a/tests/gateway/test_background_process_notifications.py+++ b/tests/gateway/test_background_process_notifications.py@@ -1020,7 +1020,7 @@ async def test_profile_scoped_child_noise_and_handoff_admission(assert event.source.profile == name and home == homes[name]assert resolved_id == entry.session_idif path == "agent":- assert event.metadata["gateway_session_id"] == child+ assert event.metadata["gateway_session_id"] == entry.session_idcompletion = runner._build_process_completion_event(watcher, proc, proc.id)assert completion["owner_task_id"] == proc.owner_task_idassert completion["parent_session_id"] == childdiff --git a/tests/gateway/test_completion_owner_retry.py b/tests/gateway/test_completion_owner_retry.pyindex ec60336dfe3..c1bf4228d27 100644--- a/tests/gateway/test_completion_owner_retry.py+++ b/tests/gateway/test_completion_owner_retry.py@@ -62,7 +62,7 @@ async def test_transient_ownership_ancestor_failure_retries_durable_delivery_oncasync def accept(event):assert event.source.chat_id == "ownership-retry"assert event.metadata["gateway_session_key"] == entry.session_key- assert event.metadata["gateway_session_id"] == "nested-worker"+ assert event.metadata["gateway_session_id"] == ownercurrent = store.lookup_by_session_key(entry.session_key)assert current is not Noneresolved = await runner._resolve_async_delegation_session(@@ -184,3 +184,63 @@ async def test_claimed_ownership_retries_do_not_spend_the_delivery_budget(finally:store.close_all_db_handles()runner.close_all_session_db_handles()+++async def test_admitted_delegate_completion_reaches_owner_without_rereading_the_chain(+ 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."""+ 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-admitted", 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("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)++ 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"],+ )+ 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"]})++ 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"+ 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()