Skip to content

The agent that grows with you

fix(gateway): offer an admitted completion again when its turn cannot confirm the owner

yoniebans802fd5782f3b
diff --git a/gateway/run_notifications.py b/gateway/run_notifications.py
index 7af654820f8..2eafbfc0a67 100644
--- a/gateway/run_notifications.py
+++ b/gateway/run_notifications.py
@@ -1174,7 +1174,7 @@ class GatewayNotificationsMixin(GatewayNotificationOwnershipMixin):
raw_sid = str(evt.get("origin_session_id") or "").strip() or str(source.chat_id or "")
return await self._self_post_api_server(adapter, synth_text, raw_sid, evt)
try:
- metadata = {"notification_origin": "process_registry_synthetic"}
+ metadata: dict[str, Any] = {"notification_origin": "process_registry_synthetic"}
synth_text = _mark_internal_notification(synth_text)
session_key = str(evt.get("session_key") or "").strip()
from agent.notification_presentation import diagnostic_process_event
@@ -1188,6 +1188,8 @@ class GatewayNotificationsMixin(GatewayNotificationOwnershipMixin):
proven_session_id = str(evt.get("proven_session_id") or "").strip()
if proven_session_id:
metadata["gateway_proven_session_id"] = proven_session_id
+ if completion_ids := evt.get("completion_ids"):
+ metadata["gateway_completion_ids"] = list(completion_ids)
# 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
@@ -1494,6 +1496,10 @@ class GatewayNotificationsMixin(GatewayNotificationOwnershipMixin):
# Admission settles the durable claim, so the resolver starts from the owner proven here.
evt = {**evt, "parent_session_id": claim.owner_session_id,
"proven_session_id": claim.proven_session_id}
+ # The rows this admission settles: a turn that cannot confirm the owner offers them again.
+ completion_ids = [claim.delegation_id] if claim.claim_id else []
+ completion_ids += [sibling["delegation_id"] for sibling, claim_id in sibling_claims if claim_id]
+ evt = {**evt, "completion_ids": completion_ids}
injection_result = await self._inject_watch_notification(synth_text, evt, raise_not_accepted=True)
if injection_result is not True:
return injection_result
diff --git a/gateway/run_notifications_ownership.py b/gateway/run_notifications_ownership.py
index 55ba5141f26..7d632fe05b4 100644
--- a/gateway/run_notifications_ownership.py
+++ b/gateway/run_notifications_ownership.py
@@ -9,9 +9,10 @@ that owner is proven.
from __future__ import annotations
+import asyncio
import json
import logging
-from typing import Any, Optional, cast
+from typing import Any, Optional, Sequence, cast
from gateway.session import SessionEntry
@@ -112,12 +113,14 @@ class GatewayNotificationOwnershipMixin:
async def _resolve_async_delegation_session(
self, session_entry: SessionEntry, pinned_session_id: str, proven_session_id: str = "",
+ completion_ids: Sequence[str] = (),
) -> Optional[SessionEntry]:
"""Resolve an async completion to its verified owning gateway session.
Follow compression-rotation lineage (parent row ended, child continues), but never let a
late completion override an unrelated /new or restored route. Unknown ownership fails
- closed; the result stays in the delegation records.
+ closed; the result stays in the delegation records. An owner that cannot be confirmed right
+ now (``retry``) sends the completions admitted with the event back to the delivery queue.
A pinned *delegate* row is likewise canonicalized to its human-facing parent through
``model_config._delegate_from`` before any route check or mutation (#92611). Unresolvable
@@ -144,7 +147,7 @@ class GatewayNotificationOwnershipMixin:
pinned_session_id, session_entry.session_id,
)
if verdict != "deliver" or pinned_row is None:
- return None
+ return await self._requeue_uncertain_completion(verdict, completion_ids)
target_session_id = pinned_session_id
follows_compression = False
if pinned_row.get("ended_at"):
@@ -170,7 +173,7 @@ class GatewayNotificationOwnershipMixin:
session_db, session_entry, pinned_session_id,
)
if verdict != "deliver" or target_session_id is None:
- return None
+ return await self._requeue_uncertain_completion(verdict, completion_ids)
if target_session_id == session_entry.session_id:
return session_entry
prior_session_id = session_entry.session_id
@@ -203,3 +206,27 @@ class GatewayNotificationOwnershipMixin:
target_session_id, prior_session_id, session_entry.session_key,
)
return switched
+
+ async def _requeue_uncertain_completion(self, verdict: str, completion_ids: Sequence[str]) -> None:
+ """Offer admitted completions again when the turn could not confirm their owner (``retry``),
+ so the next delivery re-runs the pre-flight; boundary verdicts stay dropped."""
+ if verdict != "retry" or not completion_ids:
+ return None
+ from tools.async_delegation import requeue_admitted_completion
+ from tools.process_registry import process_registry
+ runner = cast(Any, self)
+ with runner._completion_delivery_lock:
+ for delegation_id in completion_ids:
+ runner._completion_deliveries_delivered.pop(("async_delegation", delegation_id, ""), None)
+ for delegation_id in completion_ids:
+ try:
+ requeued = await asyncio.to_thread(
+ requeue_admitted_completion, delegation_id, process_registry.completion_queue)
+ except Exception:
+ logger.debug("Could not requeue admitted completion %s", delegation_id, exc_info=True)
+ requeued = False
+ logger.warning(
+ "Async-delegation completion %s: owner not confirmed after admission; %s.", delegation_id,
+ "offered again" if requeued else "not offered again (result remains queryable)",
+ )
+ return None
diff --git a/gateway/run_turn.py b/gateway/run_turn.py
index 03bb8093039..068f8240ed7 100644
--- a/gateway/run_turn.py
+++ b/gateway/run_turn.py
@@ -448,7 +448,7 @@ class GatewayTurnMixin:
)
session_key = session_entry.session_key
if not strict_session and pinned_session_id:
- resolved_entry = await self._resolve_async_delegation_session(session_entry, pinned_session_id, event_metadata.get("gateway_proven_session_id") or "")
+ resolved_entry = await self._resolve_async_delegation_session(session_entry, pinned_session_id, event_metadata.get("gateway_proven_session_id") or "", event_metadata.get("gateway_completion_ids") or ())
if resolved_entry is None:
return
session_entry = resolved_entry
diff --git a/tests/gateway/test_completion_owner_retry.py b/tests/gateway/test_completion_owner_retry.py
index 75daf2c1662..b41a6fc4f3d 100644
--- a/tests/gateway/test_completion_owner_retry.py
+++ b/tests/gateway/test_completion_owner_retry.py
@@ -1,5 +1,6 @@
"""Durable delivery retries uncertain delegate ancestry without moving the route."""
+import queue
import sqlite3
from types import SimpleNamespace
from typing import Any, cast
@@ -11,6 +12,7 @@ from gateway.platforms.base import BasePlatformAdapter
from gateway.run import GatewayRunner, _profile_runtime_scope
from gateway.session import SessionSource
from tools import async_delegation as ad
+from tools.process_registry import process_registry
@pytest.mark.asyncio
@@ -283,3 +285,69 @@ async def test_admitted_completion_reaches_compressed_owners_tip_without_reading
finally:
store.close_all_db_handles()
runner.close_all_session_db_handles()
+
+
+async def test_unconfirmed_owner_after_admission_offers_the_completion_again(
+ tmp_path, monkeypatch, private_db_probe_cleanup,
+):
+ """A compression after admission plus a failed read leaves the result pending and queued; the next
+ delivery proves the compressed tip and reaches it."""
+ with _profile_runtime_scope(tmp_path):
+ runner = GatewayRunner(GatewayConfig(sessions_dir=tmp_path / "sessions"))
+ store = runner.session_store
+ offered: queue.Queue = queue.Queue()
+ monkeypatch.setattr(process_registry, "completion_queue", offered)
+ try:
+ entry = store.get_or_create_session(SessionSource(
+ platform=Platform.TELEGRAM, chat_id="ownership-requeue", chat_type="dm",
+ ))
+ db = cast(Any, store._db)
+ owner = entry.session_id
+ db.create_session("worker", source="subagent", model_config={"_delegate_from": owner})
+ get_session = runner._session_db.get_session
+ owner_read_fails = False
+
+ async def lookup_session(sid):
+ if owner_read_fails and sid == owner:
+ raise RuntimeError("transient read failure")
+ return await get_session(sid)
+
+ monkeypatch.setattr(runner._session_db, "get_session", lookup_session)
+ admitted = []
+
+ async def accept(event):
+ admitted.append(event)
+ event._gateway_accepted = True
+
+ runner.adapters[Platform.TELEGRAM] = cast(BasePlatformAdapter, SimpleNamespace(handle_message=accept))
+ event = {
+ "type": "async_delegation", "delegation_id": "requeued-owner",
+ "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"]})
+
+ # The turn runs after admission settled the row, as the adapter's background task does.
+ assert await runner._deliver_completion_notification("completed result", event) is True
+ 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
+ owner_read_fails = True
+ assert await runner._hmwa_resolve_session(admitted[0], admitted[0].source) is None
+ owner_read_fails = False
+ row = ad.get_durable_delegation("requeued-owner")
+ assert row is not None and row["delivery_state"] == "pending"
+ again = offered.get_nowait()
+ assert again["delegation_id"] == "requeued-owner" and again["restored"] is True
+
+ assert await runner._deliver_completion_notification("completed result", again) is True
+ resolved = await runner._hmwa_resolve_session(admitted[1], admitted[1].source)
+ assert resolved is not None and resolved[1].session_id == "owner-tip"
+ row = ad.get_durable_delegation("requeued-owner")
+ assert row is not None and row["delivery_state"] == "delivered"
+ assert offered.empty()
+ finally:
+ store.close_all_db_handles()
+ runner.close_all_session_db_handles()
diff --git a/tests/tools/test_async_delegation_requeue.py b/tests/tools/test_async_delegation_requeue.py
new file mode 100644
index 00000000000..2c767388108
--- /dev/null
+++ b/tests/tools/test_async_delegation_requeue.py
@@ -0,0 +1,75 @@
+"""An acknowledged completion goes back to the delivery queue when its turn could not confirm the owner."""
+
+import queue
+
+import pytest
+
+from hermes_constants import get_hermes_home, hermes_home_key
+from tools import async_delegation as ad
+
+
[email protected](autouse=True)
+def _clean_state():
+ ad._reset_for_tests()
+ yield
+ ad._reset_for_tests()
+
+
+def _persisted(delegation_id: str, *, delivered: bool = True) -> None:
+ event = {
+ "type": "async_delegation", "delegation_id": delegation_id, "session_key": "agent:main:telegram:dm:1",
+ "parent_session_id": "parent", "dispatched_at": 1.0, "status": "completed", "summary": "done",
+ }
+ ad._persist_dispatch(event)
+ ad._persist_completion(event, {"status": "completed", "summary": "done"})
+ if delivered:
+ assert ad.claim_completion_delivery(delegation_id, "claim")
+ assert ad.complete_completion_delivery(delegation_id, "claim")
+
+
+def _column(delegation_id: str, column: str):
+ with ad._DB_LOCK, ad._transaction() as conn:
+ return conn.execute(f"SELECT {column} FROM async_delegations WHERE delegation_id=?", (delegation_id,)).fetchone()[0]
+
+
+def _set(delegation_id: str, column: str, value) -> None:
+ with ad._DB_LOCK, ad._transaction() as conn:
+ conn.execute(f"UPDATE async_delegations SET {column}=? WHERE delegation_id=?", (value, delegation_id))
+
+
+def test_requeue_returns_an_acknowledged_completion_to_pending_and_offers_it():
+ _persisted("requeue-ok")
+ offered: queue.Queue = queue.Queue()
+
+ assert ad.requeue_admitted_completion("requeue-ok", offered) is True
+
+ assert _column("requeue-ok", "delivery_state") == "pending"
+ assert _column("requeue-ok", "delivered_at") is None
+ evt = offered.get_nowait()
+ assert evt["delegation_id"] == "requeue-ok" and evt["restored"] is True
+ assert (hermes_home_key(get_hermes_home()), "requeue-ok") in ad._offered
+
+
+def test_requeue_past_the_delivery_budget_drops_the_completion():
+ _persisted("requeue-spent")
+ _set("requeue-spent", "delivery_attempts", ad._MAX_DELIVERY_ATTEMPTS)
+ offered: queue.Queue = queue.Queue()
+
+ assert ad.requeue_admitted_completion("requeue-spent", offered) is False
+
+ assert _column("requeue-spent", "delivery_state") == "dropped"
+ assert offered.empty()
+
+
[email protected]("case", ["not_delivered", "no_stored_event"])
+def test_requeue_leaves_rows_it_cannot_offer(case):
+ _persisted(case, delivered=case != "not_delivered")
+ if case == "no_stored_event":
+ _set(case, "event_json", None)
+ before = _column(case, "delivery_state")
+ offered: queue.Queue = queue.Queue()
+
+ assert ad.requeue_admitted_completion(case, offered) is False
+
+ assert _column(case, "delivery_state") == before
+ assert offered.empty()
diff --git a/tools/async_delegation.py b/tools/async_delegation.py
index b2273f9c7af..6f3203ec9b4 100644
--- a/tools/async_delegation.py
+++ b/tools/async_delegation.py
@@ -523,6 +523,33 @@ def complete_completion_delivery(delegation_id: str, claim_id: str) -> bool:
AND delivery_claim=?""", (now, now, delegation_id, claim_id))
+def requeue_admitted_completion(delegation_id: str, target_queue) -> bool:
+ """Offer an acknowledged completion again when its receiving turn could not confirm the owner.
+
+ The row returns to pending and its event goes back on ``target_queue``, so the next delivery
+ re-runs the pre-flight. A row past the delivery budget converges to ``dropped`` instead, which
+ bounds the loop; a row without a stored event is left as it is."""
+ now = time.time()
+ with _DB_LOCK, _transaction() as conn:
+ exhausted = conn.execute("""UPDATE async_delegations SET delivery_state='dropped', updated_at=?
+ WHERE delegation_id=? AND delivery_state='delivered' AND delivery_attempts>=?""",
+ (now, delegation_id, _MAX_DELIVERY_ATTEMPTS))
+ if exhausted.rowcount == 1:
+ logger.warning("Async delegation %s exhausted its %d delivery attempts; "
+ "marking terminally dropped (result remains queryable).",
+ delegation_id, _MAX_DELIVERY_ATTEMPTS)
+ return False
+ reopened = conn.execute("""UPDATE async_delegations SET delivery_state='pending',
+ delivered_at=NULL, updated_at=?
+ WHERE delegation_id=? AND delivery_state='delivered' AND event_json IS NOT NULL""",
+ (now, delegation_id))
+ if reopened.rowcount != 1:
+ return False
+ rows = conn.execute("""SELECT delegation_id, event_json, completed_at, dispatched_at
+ FROM async_delegations WHERE delegation_id=?""", (delegation_id,)).fetchall()
+ return _replay_pending(conn, rows, target_queue, now) == 1
+
+
def complete_event_delivery(evt: dict[str, Any], claim_id: str) -> None:
_event_delivery(complete_completion_delivery, evt, claim_id)