The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(delegation): re-offer completions orphaned by a dead owner while the process runs
brooklyn!021530a69ecb
diff --git a/gateway/run_notifications.py b/gateway/run_notifications.pyindex b79a0891bb2..0f8ca142090 100644--- a/gateway/run_notifications.py+++ b/gateway/run_notifications.py@@ -1838,21 +1838,39 @@ class GatewayNotificationsMixin:"""Re-queue undelivered async completions from every SECONDARY profile's ledger. The processregistry restores only the launch profile's ``state.db`` at import; a secondary's rows wouldotherwise never be replayed after a restart."""- from gateway.run import _profile_runtime_scopefrom tools.async_delegation import restore_undelivered_completionsfrom tools.process_registry import process_registry as _pr+ self._each_secondary_ledger(profile_homes, lambda: restore_undelivered_completions(_pr.completion_queue),+ "Restored")++ def _sweep_orphaned_completion_ledgers(self) -> None:+ """Offer completions whose owner process died while this gateway runs (#97202): the launch+ ledger in the launch scope, each served secondary under its own. Startup replay only covers+ owners that were already gone when the gateway started."""+ from tools.async_delegation import sweep_orphaned_completions+ from tools.process_registry import process_registry as _pr+ sweep = lambda: sweep_orphaned_completions(_pr.completion_queue) # noqa: E731+ with _log_suppressed(logging.DEBUG, "Orphaned async completion sweep failed: %s"):+ if count := sweep():+ logger.info("Re-offered %d orphaned async completion(s)", count)+ self._each_secondary_ledger((getattr(self, "_served_profile_homes", None) or {}).items(), sweep,+ "Re-offered orphaned")++ def _each_secondary_ledger(self, profile_homes, fn, verb: str) -> None:+ """Run ``fn`` (returns a completion count) once per SECONDARY profile, bound to that profile."""+ from gateway.run import _profile_runtime_scopeprimary = getattr(self, "_primary_profile_name", None)for profile_name, profile_home in profile_homes:if profile_name == primary:continuetry:with _profile_runtime_scope(Path(profile_home), {}):- restored = restore_undelivered_completions(_pr.completion_queue)+ count = fn()except Exception:- logger.warning("Could not restore async completions for profile %r", profile_name, exc_info=True)+ logger.warning("Could not replay async completions for profile %r", profile_name, exc_info=True)continue- if restored:- logger.info("Restored %d undelivered async completion(s) for profile %r", restored, profile_name)+ if count:+ logger.info("%s %d undelivered async completion(s) for profile %r", verb, count, profile_name)async def _async_delegation_watcher(self, interval: float = 2.0) -> None:"""Drain async completions and pattern notifications even while sessions are idle.@@ -1861,9 +1879,15 @@ class GatewayNotificationsMixin:consumer; both must progress without a later foreground turn."""await asyncio.sleep(3) # let platforms finish connecting+ from tools.async_delegation import ORPHAN_SWEEP_INTERVAL_Sfrom tools.process_registry import process_registry as _pr+ last_orphan_sweep = Nonewhile self._running:with _log_suppressed(logging.DEBUG, "Async delegation watcher error: %s"):+ # Completions whose owner process died while this gateway runs (#97202).+ if last_orphan_sweep is None or time.monotonic() - last_orphan_sweep >= ORPHAN_SWEEP_INTERVAL_S:+ last_orphan_sweep = time.monotonic()+ await asyncio.to_thread(self._sweep_orphaned_completion_ledgers)# Pattern events also need an idle consumer; foreground turns are optional.await self._drain_watch_notifications(_pr.completion_queue)# Process completions remain owned by their per-process watchers.diff --git a/tests/tools/test_async_delegation_orphan_sweep.py b/tests/tools/test_async_delegation_orphan_sweep.pynew file mode 100644index 00000000000..7b277effe58--- /dev/null+++ b/tests/tools/test_async_delegation_orphan_sweep.py@@ -0,0 +1,250 @@+"""A completion whose owner process died is re-offered by processes that are ALREADY running (#97202).++Startup replay (``restore_undelivered_completions``) runs once per process, so before this a result+persisted by a process that then died (a desktop reload) waited for the next process start. These+tests produce the orphan with a real owner process against a real temp ``state.db``; time is injected+(``now=``) or written into the row, never raced against the wall clock.+"""++import os+import queue+import sqlite3+import subprocess+import sys+import threading+import time+from pathlib import Path++import pytest++from hermes_constants import get_hermes_home, reset_hermes_home_override, set_hermes_home_override+from tools import async_delegation as ad+from tools.process_registry import process_registry++REPO = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))++# The owner dispatches, its child fails (the reload-interrupted child of the report lands as+# state='error'), the completion is persisted, and the process dies before anything delivers it.+_OWNER = r'''+import os, time+from tools import async_delegation as ad+def child():+ raise RuntimeError("interrupted: waiting for model response")+r = ad.dispatch_async_delegation(+ goal="adversarial review", context=None, toolsets=None, role="leaf", model="m",+ session_key="bot-chat", parent_session_id="bot-parent", runner=child)+deadline = time.time() + 10+while ad.active_count() and time.time() < deadline:+ time.sleep(.01)+print(r["delegation_id"], flush=True)+os._exit(0)+'''++[email protected](autouse=True)+def _clean_state():+ ad._reset_for_tests()+ yield+ ad._reset_for_tests()+++def _orphan(home: Path) -> str:+ """Run a real owner process under ``home`` and return the id of the completion it left pending."""+ home.mkdir(parents=True, exist_ok=True)+ env = {**os.environ, "HERMES_HOME": str(home), "PYTHONPATH": REPO}+ out = subprocess.run([sys.executable, "-c", _OWNER], cwd=REPO, env=env, text=True,+ capture_output=True, timeout=60, check=True)+ return out.stdout.strip().splitlines()[-1]+++def _row(home: Path, delegation_id: str) -> dict:+ conn = sqlite3.connect(home / "state.db")+ try:+ conn.row_factory = sqlite3.Row+ return dict(conn.execute("SELECT * FROM async_delegations WHERE delegation_id=?", (delegation_id,)).fetchone())+ finally:+ conn.close()+++def _set(home: Path, delegation_id: str, **cols) -> None:+ conn = sqlite3.connect(home / "state.db")+ try:+ conn.execute(f"UPDATE async_delegations SET {', '.join(f'{k}=?' for k in cols)} WHERE delegation_id=?",+ (*cols.values(), delegation_id))+ conn.commit()+ finally:+ conn.close()+++class _Home:+ """Bind the profile home for code outside a turn, the way a delivery loop does."""++ def __init__(self, home: Path):+ self.home = home++ def __enter__(self):+ self._token = set_hermes_home_override(str(self.home))+ return self++ def __exit__(self, *exc):+ reset_hermes_home_override(self._token)+++def _drain(q) -> list:+ out = []+ while not q.empty():+ out.append(q.get_nowait())+ return out+++def test_orphaned_terminal_completion_is_offered_once_while_the_process_runs(tmp_path):+ home = tmp_path / "home"+ delegation_id = _orphan(home)+ row = _row(home, delegation_id)+ assert (row["state"], row["delivery_state"]) == ("error", "pending") and row["event_json"]+ q = queue.Queue()+ with _Home(home):+ # Freshly written: a live consumer may still be on it, so the sweep leaves it alone.+ assert ad.sweep_orphaned_completions(q, now=row["updated_at"] + 1) == 0+ later = row["updated_at"] + ad._ORPHAN_STALE_S + 1+ assert ad.sweep_orphaned_completions(q, now=later) == 1+ (evt,) = _drain(q)+ assert evt["delegation_id"] == delegation_id and evt["status"] == "error"+ assert evt["session_key"] == "bot-chat" and evt["restored"] is True+ # Offered once per process: the next sweep does not flood the queue with the same row.+ assert ad.sweep_orphaned_completions(q, now=later + 60) == 0+ assert q.empty()+ # Delivery still goes through the atomic claim: a second consumer (another process that+ # also offered the row) cannot claim it, and the winner's ack settles the row.+ claim = ad.claim_event_delivery(evt, "first")+ assert claim+ assert ad.claim_event_delivery(evt, "second") is None+ assert ad.complete_completion_delivery(delegation_id, claim)+ assert _row(home, delegation_id)["delivery_state"] == "delivered"+++def test_row_owned_by_a_live_process_is_never_swept(tmp_path):+ home = tmp_path / "home"+ home.mkdir()+ q = queue.Queue()+ with _Home(home):+ handle = ad.dispatch_async_delegation(+ goal="mine", context=None, toolsets=None, role="leaf", model="m", session_key="live",+ runner=lambda: {"status": "completed", "summary": "done"})+ deadline = time.monotonic() + 10+ while ad.active_count() and time.monotonic() < deadline:+ time.sleep(0.01)+ row = _row(home, handle["delegation_id"])+ assert row["owner_pid"] == os.getpid() and row["delivery_state"] == "pending"+ assert ad.sweep_orphaned_completions(q, now=row["updated_at"] + 3600) == 0+ assert q.empty()+++def test_sweep_is_bound_to_the_profile_home_it_runs_under(tmp_path):+ """A→B→A: each profile's sweep reads only its own ledger and never adopts the other's row."""+ home_a, home_b = tmp_path / "a", tmp_path / "b"+ id_a, id_b = _orphan(home_a), _orphan(home_b)+ later = max(_row(home_a, id_a)["updated_at"], _row(home_b, id_b)["updated_at"]) + ad._ORPHAN_STALE_S + 1+ q = queue.Queue()+ with _Home(home_a):+ ad.sweep_orphaned_completions(q, now=later)+ assert [e["delegation_id"] for e in _drain(q)] == [id_a]+ with _Home(home_b):+ ad.sweep_orphaned_completions(q, now=later)+ assert [e["delegation_id"] for e in _drain(q)] == [id_b]+ with _Home(home_a):+ assert ad.sweep_orphaned_completions(q, now=later + 60) == 0+ assert q.empty()+ assert _row(home_b, id_b)["delivery_state"] == "pending"+++def test_restart_replay_and_sweep_never_offer_the_same_row_twice(tmp_path):+ home = tmp_path / "home"+ delegation_id = _orphan(home)+ later = _row(home, delegation_id)["updated_at"] + ad._ORPHAN_STALE_S + 1+ q = queue.Queue()+ with _Home(home):+ assert ad.restore_undelivered_completions(q) == 1+ assert ad.sweep_orphaned_completions(q, now=later) == 0+ assert [e["delegation_id"] for e in _drain(q)] == [delegation_id]++[email protected]("exhausted", ["attempts", "age"])+def test_orphan_past_its_delivery_budget_converges_to_dropped(tmp_path, exhausted):+ home = tmp_path / "home"+ delegation_id = _orphan(home)+ row = _row(home, delegation_id)+ later = row["updated_at"] + ad._ORPHAN_STALE_S + 1+ if exhausted == "attempts":+ _set(home, delegation_id, delivery_attempts=ad._MAX_DELIVERY_ATTEMPTS)+ else:+ later = row["completed_at"] + ad._MAX_COMPLETION_REPLAY_AGE_S + 1+ q = queue.Queue()+ with _Home(home):+ assert ad.sweep_orphaned_completions(q, now=later) == 0+ assert q.empty()+ assert _row(home, delegation_id)["delivery_state"] == "dropped"+++def test_in_flight_claim_is_left_to_its_holder(tmp_path):+ home = tmp_path / "home"+ delegation_id = _orphan(home)+ row = _row(home, delegation_id)+ later = row["updated_at"] + ad._ORPHAN_STALE_S + 1+ _set(home, delegation_id, delivery_claim="other-process", delivery_claimed_at=later - 1)+ q = queue.Queue()+ with _Home(home):+ assert ad.sweep_orphaned_completions(q, now=later) == 0+ assert q.empty()+++def test_gateway_watcher_sweeps_each_served_ledger_in_its_own_scope(tmp_path, monkeypatch):+ """The gateway's delivery loop re-offers a secondary profile's orphan while it runs."""+ from gateway.run import GatewayRunner++ home_b = tmp_path / "b"+ delegation_id = _orphan(home_b)+ stale = time.time() - ad._ORPHAN_STALE_S - 60+ _set(home_b, delegation_id, updated_at=stale, completed_at=stale)+ isolated = queue.Queue()+ monkeypatch.setattr(process_registry, "completion_queue", isolated)+ runner = object.__new__(GatewayRunner)+ runner._primary_profile_name = "default"+ runner._served_profile_homes = {"default": get_hermes_home(), "b": home_b}+ runner._sweep_orphaned_completion_ledgers()+ assert [e["delegation_id"] for e in _drain(isolated)] == [delegation_id]+++def test_tui_notification_poller_sweeps_under_its_session_profile(tmp_path, monkeypatch):+ """The desktop/TUI delivery loop runs the (throttled) sweep in the session's own profile scope."""+ from tui_gateway import server++ home_b = tmp_path / "b"+ home_b.mkdir()+ stop = threading.Event()+ seen = []++ def fake_sweep(target_queue):+ seen.append((str(get_hermes_home()), target_queue))+ stop.set()+ return 0++ monkeypatch.setattr(ad, "maybe_sweep_orphaned_completions", fake_sweep)+ isolated = queue.Queue()+ monkeypatch.setattr(process_registry, "completion_queue", isolated)+ session = {"profile_home": str(home_b), "_finalized": False}+ server._notification_poller_loop(stop, "sid-orphan-sweep", session)+ assert seen and seen[0][0] == str(home_b) and seen[0][1] is isolated+++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)+ q = queue.Queue()+ with _Home(tmp_path / "a"):+ ad.maybe_sweep_orphaned_completions(q, now=100.0)+ ad.maybe_sweep_orphaned_completions(q, now=101.0)+ with _Home(tmp_path / "b"): # another profile has its own clock+ ad.maybe_sweep_orphaned_completions(q, now=101.0)+ ad.maybe_sweep_orphaned_completions(q, now=100.0 + ad.ORPHAN_SWEEP_INTERVAL_S + 1)+ assert calls == [str(tmp_path / "a"), str(tmp_path / "b"), str(tmp_path / "a")]diff --git a/tools/async_delegation.py b/tools/async_delegation.pyindex 65186f44e5b..c07dc4ff04a 100644--- a/tools/async_delegation.py+++ b/tools/async_delegation.py@@ -20,7 +20,7 @@ import uuidfrom concurrent.futures import ThreadPoolExecutorfrom typing import Any, Callable, Dict, List, Optional-from hermes_constants import get_hermes_home+from hermes_constants import get_hermes_home, hermes_home_keyfrom tools.daemon_pool import DaemonThreadPoolExecutorfrom tools.thread_context import propagate_context_to_thread@@ -47,8 +47,22 @@ _MAX_DELIVERY_ATTEMPTS = 8# Pending completions older than this are dropped on restart replay instead of# re-run as a full-context turn; 48h keeps weekend results deliverable._MAX_COMPLETION_REPLAY_AGE_S = 48 * 3600.0+# A delivery claim older than this is abandoned and may be re-claimed.+_CLAIM_LEASE_S = 300.0_DB_LOCK = threading.Lock()+# ── Orphaned-completion sweep ────────────────────────────────────────────────+# Startup replay runs once per process, so a completion whose owner died while THIS process was+# already running (a desktop reload) would wait for the next restart (#97202). Delivery loops (gateway+# watcher, TUI poller) sweep each home they serve at most once per interval.+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.+_offered: set = set()+_last_orphan_sweep: Dict[str, float] = {}+# ── Stale-delegation detection (progress-based, on by default) ──────────────# A runner wedged before returning never reaches its finalizer, so it would show# "dispatched" forever. No wall-clock timeout (heavy work must never be killed for@@ -225,12 +239,25 @@ def _recovered_results(task: Dict[str, Any], result_json: Optional[str], error:return [recorded.get(i) or {"task_index": i, "status": "unknown", "summary": None, "error": error} for i in indexes]-def recover_abandoned_delegations() -> int:- """Classify records whose owning process disappeared as outcome unknown; children a multi-child unit had already- recorded (``record_unit_child``) are replayed with their real results."""+def _owner_liveness() -> Optional[Callable[[Any, Any], bool]]:+ """``alive(owner_pid, owner_started_at)`` over the shared drift-tolerant start-time comparator,+ or None when the liveness probes cannot be imported."""try:from gateway.status import _pid_exists, get_process_start_time, start_time_fingerprints_matchexcept Exception:+ return None++ def alive(pid, started) -> bool:+ return bool(pid) and _pid_exists(int(pid)) and (+ started is None or start_time_fingerprints_match(started, get_process_start_time(int(pid)) or 0))+ return alive+++def recover_abandoned_delegations() -> int:+ """Classify records whose owning process disappeared as outcome unknown; children a multi-child unit had already+ recorded (``record_unit_child``) are replayed with their real results."""+ alive = _owner_liveness()+ if alive is None:return 0now, recovered = time.time(), 0with _DB_LOCK, _transaction() as conn:@@ -240,9 +267,7 @@ def recover_abandoned_delegations() -> int:FROM async_delegations WHERE state IN ('running','finalizing')""").fetchall()for row in rows:delegation_id, session_key, origin_ui, parent_id, dispatched_at, pid, started, task_json, origin_sid, result_json, last_state = row- if pid and _pid_exists(int(pid)) and (- started is None or start_time_fingerprints_match(started, get_process_start_time(int(pid)) or 0)- ):+ if alive(pid, started):continuetask = json.loads(task_json or "{}")error = "Delegation owner exited before recording a terminal result; outcome unknown."@@ -293,29 +318,100 @@ def restore_undelivered_completions(target_queue) -> int:(#64484)."""recover_abandoned_delegations()- now, restored = time.time(), 0+ now = time.time()with _DB_LOCK, _transaction() as conn:rows = conn.execute("""SELECT delegation_id, event_json, completed_at, dispatched_atFROM async_delegationsWHERE state != 'running' AND delivery_state='pending' AND event_json IS NOT NULLORDER BY completed_at, delegation_id""").fetchall()- for delegation_id, payload, completed_at, dispatched_at in rows:- age_basis = completed_at or dispatched_at- if age_basis and (now - age_basis) > _MAX_COMPLETION_REPLAY_AGE_S:+ return _replay_pending(conn, rows, target_queue, now)+++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."""+ home, restored = hermes_home_key(get_hermes_home()), 0+ for delegation_id, payload, completed_at, dispatched_at in rows:+ age_basis = completed_at or dispatched_at+ if age_basis and (now - age_basis) > _MAX_COMPLETION_REPLAY_AGE_S:+ conn.execute("""UPDATE async_delegations SET delivery_state='dropped',+ delivery_claim=NULL, delivery_claimed_at=NULL,+ updated_at=?+ WHERE delegation_id=? AND delivery_state='pending'""", (now, delegation_id))+ logger.warning("Async delegation %s: pending completion is %.1fh old "+ "(cap %.1fh); terminally dropping the replay (result remains queryable).",+ delegation_id, (now - age_basis) / 3600.0, _MAX_COMPLETION_REPLAY_AGE_S / 3600.0)+ continue+ evt = json.loads(payload)+ if isinstance(evt, dict):+ evt["restored"] = True+ target_queue.put(evt)+ with _orphan_lock:+ _offered.add((home, delegation_id))+ restored += 1+ return restored+++def sweep_orphaned_completions(target_queue, *, now: Optional[float] = None) -> int:+ """Offer this home's completions whose owner died after THIS process started (#97202).++ Startup replay (``restore_undelivered_completions``) covers owners that died before the process+ 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, idle+ past ``_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+ the atomic cross-process gate, so two processes offering one row never both deliver it. Rows past+ the delivery budget or the replay age converge to ``dropped``. Reads the current profile's ledger:+ callers bind the owning profile first."""+ alive = _owner_liveness()+ if alive is None or not _db_path().exists():+ return 0 # never create a ledger just to sweep it+ recover_abandoned_delegations()+ now = time.time() if now is None else now+ home = hermes_home_key(get_hermes_home())+ with _orphan_lock:+ offered = {delegation_id for key, delegation_id in _offered if key == home}+ with _DB_LOCK, _transaction() as conn:+ rows = conn.execute("""SELECT delegation_id, event_json, completed_at, dispatched_at,+ owner_pid, owner_started_at, delivery_attempts+ FROM async_delegations+ WHERE state NOT IN ('running','finalizing') AND delivery_state='pending'+ AND event_json IS NOT NULL AND updated_at < ?+ AND (delivery_claim IS NULL OR delivery_claimed_at < ?)+ ORDER BY completed_at, delegation_id""", (now - _ORPHAN_STALE_S, now - _CLAIM_LEASE_S)).fetchall()+ orphans = []+ for delegation_id, payload, completed_at, dispatched_at, pid, started, attempts in rows:+ if delegation_id in offered or alive(pid, started):+ continue+ if (attempts or 0) >= _MAX_DELIVERY_ATTEMPTS:+ # Its last claimant died holding the final attempt; converge like release_completion_delivery.conn.execute("""UPDATE async_delegations SET delivery_state='dropped',- delivery_claim=NULL, delivery_claimed_at=NULL,- updated_at=?+ delivery_claim=NULL, delivery_claimed_at=NULL, updated_at=?WHERE delegation_id=? AND delivery_state='pending'""", (now, delegation_id))- logger.warning("Async delegation %s: pending completion is %.1fh old "- "(cap %.1fh); terminally dropping the replay (result remains queryable).",- delegation_id, (now - age_basis) / 3600.0, _MAX_COMPLETION_REPLAY_AGE_S / 3600.0)+ logger.warning("Async delegation %s exhausted its %d delivery attempts; "+ "marking terminally dropped (result remains queryable).",+ delegation_id, _MAX_DELIVERY_ATTEMPTS)continue- evt = json.loads(payload)- if isinstance(evt, dict):- evt["restored"] = True- target_queue.put(evt)- restored += 1- return restored+ orphans.append((delegation_id, payload, completed_at, dispatched_at))+ return _replay_pending(conn, orphans, target_queue, now)+++def maybe_sweep_orphaned_completions(target_queue, *, now: Optional[float] = None) -> int:+ """``sweep_orphaned_completions`` at most once per ``ORPHAN_SWEEP_INTERVAL_S`` per home (``now`` is+ monotonic), for delivery loops that tick far more often. Never raises into the loop."""+ home = hermes_home_key(get_hermes_home())+ now = time.monotonic() if now is None else now+ with _orphan_lock:+ last = _last_orphan_sweep.get(home)+ if last is not None and now - last < ORPHAN_SWEEP_INTERVAL_S:+ return 0+ _last_orphan_sweep[home] = now+ try:+ return sweep_orphaned_completions(target_queue)+ except Exception:+ logger.debug("Orphaned async delegation sweep failed", exc_info=True)+ return 0def _update_delivery(sql: str, params: tuple) -> bool:@@ -344,7 +440,7 @@ def claim_completion_delivery(delegation_id: str, claim_id: str) -> bool:delivery_attempts=delivery_attempts+1, updated_at=?WHERE delegation_id=? AND delivery_state='pending'AND (delivery_claim IS NULL OR delivery_claimed_at < ?)""",- (claim_id, now, now, delegation_id, now - 300))+ (claim_id, now, now, delegation_id, now - _CLAIM_LEASE_S))return cur.rowcount == 1@@ -1033,6 +1129,9 @@ def _reset_for_tests() -> None:thread.join(timeout=2)with _records_lock:_records.clear()+ with _orphan_lock:+ _offered.clear()+ _last_orphan_sweep.clear()# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----diff --git a/tui_gateway/session_notifications.py b/tui_gateway/session_notifications.pyindex 74818a4c3fa..67d3be8e9e3 100644--- a/tui_gateway/session_notifications.py+++ b/tui_gateway/session_notifications.py@@ -690,6 +690,7 @@ def _notification_poller_scoped_loop(stop_event: threading.Event, sid: str, sesssubscriptions and delivers terminal task events the same way (status.update + agent turn) — the deliverypath tools/kanban_tools.py documents for platform="tui" rows (issue #59890)."""+ from tools import async_delegationfrom tools.process_registry import process_registryfrom tools.process_registry_notifications import format_process_notificationqueue = process_registry.completion_queue@@ -699,6 +700,8 @@ def _notification_poller_scoped_loop(stop_event: threading.Event, sid: str, sesslast_kanban_poll = last_loop_poll = last_bot_poll = 0.0while not stop_event.is_set() and not session.get("_finalized"):now = time.monotonic()+ # Completions whose owner process died after this one started (#97202); throttled per profile home.+ async_delegation.maybe_sweep_orphaned_completions(queue)if now - last_bot_poll >= _BOT_DELIVERY_POLL_SECONDS: # bot DM → live-owner delivery latency ≤ 5 slast_bot_poll = now_poll_bot_live_delivery_guarded(sid, session, now)