The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(delegation): hand a dropped orphan offer back to the sweep
brooklyn!02ed55e572a9
diff --git a/tests/tools/test_async_delegation_orphan_sweep.py b/tests/tools/test_async_delegation_orphan_sweep.pyindex 7b277effe58..db6af996471 100644--- a/tests/tools/test_async_delegation_orphan_sweep.py+++ b/tests/tools/test_async_delegation_orphan_sweep.py@@ -237,6 +237,72 @@ def test_tui_notification_poller_sweeps_under_its_session_profile(tmp_path, monkassert seen and seen[0][0] == str(home_b) and seen[0][1] is isolated+def _tui_session(session_key: str, home: Path) -> dict:+ return {"history_lock": threading.RLock(), "running": False, "history": [], "session_key": session_key,+ "profile_home": str(home), "_finalized": False, "_notification_emitted": set()}+++def test_offer_dropped_by_a_session_that_cannot_own_it_is_re_offered_to_the_owner(tmp_path, monkeypatch):+ """Every TUI/Desktop poller drains one process-wide queue. A session that cannot prove it owns an+ async delegation drops its copy while the durable row stays pending, so the offer must not+ suppress the next sweep: the owning session, live later, still gets the row without a restart."""+ from tools.process_registry_notifications import format_process_notification+ from tui_gateway import server++ home = tmp_path / "home"+ delegation_id = _orphan(home)+ later = _row(home, delegation_id)["updated_at"] + ad._ORPHAN_STALE_S + 1+ q = queue.Queue()+ registry = type("Registry", (), {"completion_queue": q, "is_completion_consumed": lambda self, sid: False})()+ started = []+ monkeypatch.setattr(server, "_emit", lambda *a, **k: None)+ monkeypatch.setattr(server, "_run_prompt_submit", lambda rid, sid, session, text, **kw: started.append(sid))++ def drain(sid, session):+ server._notif_handle_ready(sid, session, _drain(q), session["_notification_emitted"], registry,+ format_process_notification, None)++ other, owner = _tui_session("other-chat", home), _tui_session("bot-chat", home)+ with _Home(home):+ monkeypatch.setitem(server._sessions, "sid-other", other)+ assert ad.sweep_orphaned_completions(q, now=later) == 1+ drain("sid-other", other) # the wrong session wins the dequeue while the owner is not live yet+ assert q.empty() and started == []+ assert _row(home, delegation_id)["delivery_state"] == "pending"++ monkeypatch.setitem(server._sessions, "sid-owner", owner) # the owner resumes+ assert ad.sweep_orphaned_completions(q, now=later + ad.ORPHAN_SWEEP_INTERVAL_S) == 1+ drain("sid-owner", owner)+ assert started == ["sid-owner"]+ assert _row(home, delegation_id)["delivery_state"] == "delivered"+ with _Home(home): # delivered rows are never offered again+ assert ad.sweep_orphaned_completions(q, now=later + 2 * ad.ORPHAN_SWEEP_INTERVAL_S) == 0+++def test_offer_released_after_a_failed_tui_turn_is_re_offered(tmp_path, monkeypatch):+ """The TUI poller releases its claim and discards its copy when the turn cannot start; the row is+ pending again with one attempt spent, so the sweep offers it again instead of skipping it."""+ from tui_gateway import server++ home = tmp_path / "home"+ delegation_id = _orphan(home)+ later = _row(home, delegation_id)["updated_at"] + ad._ORPHAN_STALE_S + 1+ q = queue.Queue()+ monkeypatch.setattr(server, "_emit", lambda *a, **k: None)+ monkeypatch.setattr(server, "_run_prompt_submit",+ lambda *a, **k: (_ for _ in ()).throw(RuntimeError("no free worker")))+ owner = _tui_session("bot-chat", home)+ with _Home(home):+ assert ad.sweep_orphaned_completions(q, now=later) == 1+ (evt,) = _drain(q)+ assert server._notif_claim_turn(owner)+ server._notif_dispatch_event("sid-owner", owner, evt, "text")+ row = _row(home, delegation_id)+ assert (row["delivery_state"], row["delivery_claim"], row["delivery_attempts"]) == ("pending", None, 1)+ assert ad.sweep_orphaned_completions(q, now=row["updated_at"] + ad._ORPHAN_STALE_S + 1) == 1+ assert [e["delegation_id"] for e in _drain(q)] == [delegation_id]++def test_throttle_runs_at_most_one_sweep_per_home_per_interval(tmp_path, monkeypatch):calls = []monkeypatch.setattr(ad, "sweep_orphaned_completions", lambda q, **kw: calls.append(str(get_hermes_home())) or 0)diff --git a/tools/async_delegation.py b/tools/async_delegation.pyindex c07dc4ff04a..f38e39e54a4 100644--- a/tools/async_delegation.py+++ b/tools/async_delegation.py@@ -59,7 +59,9 @@ ORPHAN_SWEEP_INTERVAL_S = 30.0# Idle time before a dead owner's pending row is re-offered; keeps the sweep off a row just touched._ORPHAN_STALE_S = 60.0_orphan_lock = threading.Lock()-# (home key, delegation_id) already put on this process's queue by replay or sweep: offered once.+# (home key, delegation_id) put on this process's queue by replay or sweep and not re-offered while+# that copy is alive. A consumer that discards its copy with the row still pending hands it back+# (``return_completion_offer``); the delivery claim stays the only thing that settles the row._offered: set = set()_last_orphan_sweep: Dict[str, float] = {}@@ -329,8 +331,8 @@ def restore_undelivered_completions(target_queue) -> int:def _replay_pending(conn, rows, target_queue, now: float) -> int:"""Put each pending ``(delegation_id, event_json, completed_at, dispatched_at)`` row on ``target_queue``- stamped ``restored``, or terminally drop it past ``_MAX_COMPLETION_REPLAY_AGE_S``. Remembers what this- process was offered so the orphan sweep never offers it again."""+ stamped ``restored``, or terminally drop it past ``_MAX_COMPLETION_REPLAY_AGE_S``. Records the offer so+ the orphan sweep skips the row until the copy is handed back (``return_completion_offer``)."""home, restored = hermes_home_key(get_hermes_home()), 0for delegation_id, payload, completed_at, dispatched_at in rows:age_basis = completed_at or dispatched_at@@ -360,7 +362,8 @@ def sweep_orphaned_completions(target_queue, *, now: Optional[float] = None) ->started; this covers the rest while it runs. Abandoned in-flight rows are first classified by``recover_abandoned_delegations``. A terminal row qualifies when it is pending with an event, idlepast ``_ORPHAN_STALE_S``, not under a live delivery claim, and its owner fails the shared liveness- check. Each row is offered to this process once; the consumer's ``claim_completion_delivery`` stays+ check. A row is offered once per live in-memory copy: a consumer that discards the copy with the row+ still pending hands it back for the next sweep. The consumer's ``claim_completion_delivery`` staysthe atomic cross-process gate, so two processes offering one row never both deliver it. Rows pastthe delivery budget or the replay age converge to ``dropped``. Reads the current profile's ledger:callers bind the owning profile first."""@@ -521,7 +524,22 @@ def complete_event_delivery(evt: Dict[str, Any], claim_id: str) -> None:def release_event_delivery(evt: Dict[str, Any], claim_id: str) -> None:+ """Release a failed claim for a consumer that discards its copy (the TUI poller): the row is pending+ again, so it must stay eligible for the orphan sweep."""_event_delivery(release_completion_delivery, evt, claim_id)+ return_completion_offer(evt)+++def return_completion_offer(evt: Dict[str, Any]) -> None:+ """Hand an offered completion back to the orphan sweep after its in-memory copy was discarded while+ the durable row stays pending, e.g. a TUI session that cannot prove it owns the event drops it (every+ session poller drains one process-wide queue). The next sweep may offer the row again. Delegation ids+ are unique across profiles, so this clears the offer in every home."""+ delegation_id = str(evt.get("delegation_id") or "") if evt.get("type") == "async_delegation" else ""+ if not delegation_id or is_interim_delegation_event(evt):+ return+ with _orphan_lock:+ _offered.difference_update({key for key in _offered if key[1] == delegation_id})def _event_delivery(fn, evt: Dict[str, Any], claim_id: str) -> None:diff --git a/tui_gateway/session_notifications.py b/tui_gateway/session_notifications.pyindex 67d3be8e9e3..326f912ec18 100644--- a/tui_gateway/session_notifications.py+++ b/tui_gateway/session_notifications.py@@ -501,9 +501,15 @@ def _notif_handle_event(sid, session, evt, emitted, registry, fmt, deferred, comif not owned and _notification_event_requires_owner(evt) and not _session_owns_notification_event(sid, session, evt):origin, key = str(evt.get("origin_ui_session_id") or ""), str(evt.get("session_key") or "")if deferred is None:- (logger.warning if is_delegation else logger.debug)(+ # A durable replay stays pending: hand it back so the orphan sweep re-offers it once its owner+ # is live (#97202), and keep that retry out of WARNING.+ restored = is_delegation and bool(evt.get("restored"))+ (logger.warning if is_delegation and not restored else logger.debug)("Dropping unowned %s notification (origin=%r key=%r) instead of delivering to session %s",evt_type, origin, key, sid)+ if is_delegation:+ from tools.async_delegation import return_completion_offer+ return_completion_offer(evt)elif is_delegation:deferred.append(evt)else: