The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): refund the delivery attempt when completion ownership is uncertain
yoniebans63fdd2115177
diff --git a/gateway/run_notifications.py b/gateway/run_notifications.pyindex cca304bb575..034d1c2b425 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+ defer: bool = False # unadmitted retry: settle without spending a delivery attemptasync def _deliver_platform_notice(self, source, content: str) -> None:"""Deliver a setup/operational notice using platform-specific privacy rules."""@@ -1401,10 +1402,8 @@ class GatewayNotificationsMixin(GatewayNotificationOwnershipMixin):)claim.proceed = Falseelif verdict == "retry":- # Transient uncertainty: tell the watcher to re-poll rather than drop or misroute.- if claim.claim_id:- self._settle_durable_claim("release", claim.delegation_id, claim.claim_id)- claim.proceed, claim.early_result = False, False+ # Transient uncertainty before admission: re-poll without spending a delivery attempt.+ claim.proceed, claim.early_result, claim.defer = False, False, Truereturn claimdef _completion_event_scope(self, evt: dict):@@ -1475,7 +1474,7 @@ class GatewayNotificationsMixin(GatewayNotificationOwnershipMixin):if identity_claimed and not accepted:with self._completion_delivery_lock:self._completion_deliveries_inflight.discard(identity)- operation = "complete" if accepted else "defer" if refused else "release"+ operation = "complete" if accepted else "defer" if refused or claim.defer else "release"if claim.claim_id:self._settle_durable_claim(operation, claim.delegation_id, claim.claim_id)for sibling, claim_id in sibling_claims:diff --git a/tests/gateway/test_async_delegation_session_binding.py b/tests/gateway/test_async_delegation_session_binding.pyindex cd486bb1a25..03a5bb730d8 100644--- a/tests/gateway/test_async_delegation_session_binding.py+++ b/tests/gateway/test_async_delegation_session_binding.py@@ -349,9 +349,7 @@ async def test_compression_uncertainty_keeps_durable_completion_retryable(assert await runner._deliver_completion_notification("completed result", event) is Falserow = ad.get_durable_delegation(event["delegation_id"])assert row is not None- assert (row["delivery_state"], row["delivery_attempts"]) == (- "pending", 0 if phase == "readiness" else 1,- )+ assert (row["delivery_state"], row["delivery_attempts"]) == ("pending", 0)import sqlite3with sqlite3.connect(ad._db_path()) as conn:assert conn.execute("SELECT delivery_claim FROM async_delegations WHERE delegation_id=?",diff --git a/tests/gateway/test_completion_owner_retry.py b/tests/gateway/test_completion_owner_retry.pyindex 7c72b670e98..ec60336dfe3 100644--- a/tests/gateway/test_completion_owner_retry.py+++ b/tests/gateway/test_completion_owner_retry.py@@ -87,8 +87,7 @@ async def test_transient_ownership_ancestor_failure_retries_durable_delivery_oncassert walk_count == (1 if phase == "readiness" else 2)pending = ad.get_durable_delegation(event["delegation_id"])assert pending is not None- attempts = 0 if phase == "readiness" else 1- assert (pending["delivery_state"], pending["delivery_attempts"]) == ("pending", attempts)+ assert (pending["delivery_state"], pending["delivery_attempts"]) == ("pending", 0)with sqlite3.connect(ad._db_path()) as conn:assert conn.execute("SELECT delivery_claim FROM async_delegations WHERE delegation_id=?",@@ -103,7 +102,7 @@ async def test_transient_ownership_ancestor_failure_retries_durable_delivery_oncassert await runner._deliver_completion_notification("completed result", event) is Truedelivered = ad.get_durable_delegation(event["delegation_id"])assert delivered is not None- assert (delivered["delivery_state"], delivered["delivery_attempts"]) == ("delivered", attempts + 1)+ assert (delivered["delivery_state"], delivered["delivery_attempts"]) == ("delivered", 1)assert admitted == [owner]assert await runner._deliver_completion_notification("completed result", event) is None@@ -124,3 +123,64 @@ async def test_transient_ownership_ancestor_failure_retries_durable_delivery_oncreplay_runner.close_all_session_db_handles()store.close_all_db_handles()runner.close_all_session_db_handles()+++async def test_claimed_ownership_retries_do_not_spend_the_delivery_budget(+ tmp_path, monkeypatch, private_db_probe_cleanup,+):+ """More transient owner-read failures than the attempt budget leave the result pending; recovery admits it once."""+ 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-budget", chat_type="dm",+ ))+ owner = entry.session_id+ cast(Any, store._db).create_session("worker", source="subagent", model_config={"_delegate_from": owner})+ async_db = runner._session_db+ get_session = async_db.get_session+ walks = 0+ failing = True++ async def lookup_session(sid):+ nonlocal walks+ if sid == "worker":+ walks += 1+ # Each delivery walks twice, readiness then the claimed preflight; only the second fails.+ if failing and sid == owner and walks % 2 == 0:+ raise RuntimeError("temporary owner lookup failure")+ return await get_session(sid)++ monkeypatch.setattr(async_db, "get_session", lookup_session)+ admitted = []++ async def accept(event):+ admitted.append(event.metadata["gateway_session_id"])+ event._gateway_accepted = True++ runner.adapters[Platform.TELEGRAM] = cast(BasePlatformAdapter, SimpleNamespace(handle_message=accept))+ event = {+ "type": "async_delegation", "delegation_id": "owner-budget",+ "session_key": entry.session_key, "parent_session_id": "worker",+ "dispatched_at": 1.0, "status": "completed", "summary": "completed result",+ }+ ad._persist_dispatch(event)+ ad._persist_completion(event, {"status": "completed", "summary": event["summary"]})++ for _ in range(ad._MAX_DELIVERY_ATTEMPTS + 1):+ assert await runner._deliver_completion_notification("completed result", event) is False+ pending = ad.get_durable_delegation(event["delegation_id"])+ assert pending is not None+ assert (pending["delivery_state"], pending["delivery_attempts"]) == ("pending", 0)+ assert admitted == []++ failing = False+ assert await runner._deliver_completion_notification("completed result", event) is True+ assert len(admitted) == 1+ delivered = ad.get_durable_delegation(event["delegation_id"])+ assert delivered is not None and delivered["delivery_state"] == "delivered"+ finally:+ store.close_all_db_handles()+ runner.close_all_session_db_handles()