Skip to content

The agent that grows with you

fix(tui): gate only startup-replayed delegations on a live consumer

Tekniumb0f9ade1984f
diff --git a/tests/tui_gateway/test_launch_db_home_override_race.py b/tests/tui_gateway/test_launch_db_home_override_race.py
index ea64134880e..b5dcbd0a091 100644
--- a/tests/tui_gateway/test_launch_db_home_override_race.py
+++ b/tests/tui_gateway/test_launch_db_home_override_race.py
@@ -189,7 +189,7 @@ def test_notification_owner_gate_resolves_rotated_key_in_the_session_profile_sto
def test_restored_delegation_requires_a_live_notification_consumer():
"""Regression for #138343: a persisted completion cannot wake a detached runtime."""
session = {"session_key": "chat", "transport": None}
- event = {"type": "async_delegation", "session_key": "chat", "restored": True}
+ event = {"type": "async_delegation", "session_key": "chat", "restored": True, "startup_replay": True}
assert server._session_owns_notification_event("ui1", session, event) is False
diff --git a/tests/tui_gateway/test_restored_delegation_transport.py b/tests/tui_gateway/test_restored_delegation_transport.py
index ce7f339afa0..ba07d675333 100644
--- a/tests/tui_gateway/test_restored_delegation_transport.py
+++ b/tests/tui_gateway/test_restored_delegation_transport.py
@@ -1,8 +1,9 @@
-"""Restored delegations require a real notification consumer (#138348)."""
+"""A completion replayed at process start requires a real notification consumer (#138348)."""
import asyncio
import io
import queue
+import sqlite3
import threading
import time
from unittest.mock import Mock
@@ -39,33 +40,27 @@ def notification_env(monkeypatch, tmp_path):
def _session(notification_env, monkeypatch, kind):
home, loop, _submit = notification_env
- stdio = StdioTransport(io.StringIO, threading.Lock())
- if "sidecar" in kind:
- stdio = TeeTransport(stdio, StdioTransport(io.StringIO, threading.Lock()))
+ stdio = TeeTransport(StdioTransport(io.StringIO, threading.Lock()),
+ StdioTransport(io.StringIO, threading.Lock())) # dashboard-sidecar-wrapped
monkeypatch.setattr(server, "_stdio_transport", stdio)
- monkeypatch.setattr(server, "_stdio_is_rpc_channel", kind in {"stdio", "sidecar"})
- ws = WSTransport(None, loop)
- if kind == "closed":
- ws._closed = True
- transport = {
- "stdio": stdio, "sidecar": stdio, "websocket": ws,
- "headless": stdio, "headless_sidecar": stdio,
- "detached": server._detached_ws_transport, "closed": ws, "absent": None,
- "foreign_stdio": StdioTransport(io.StringIO, threading.Lock()),
- "finalized": stdio,
- }[kind]
- if kind in {"foreign_stdio", "finalized"}:
- monkeypatch.setattr(server, "_stdio_is_rpc_channel", True)
- session = {
- "session_key": "chat", "transport": transport, "profile_home": str(home),
- "history_lock": threading.RLock(), "running": False,
- "_finalized": kind == "finalized",
- }
+ monkeypatch.setattr(server, "_stdio_is_rpc_channel", kind == "stdio")
+ transport = {"stdio": stdio, "websocket": WSTransport(None, loop),
+ "detached": server._detached_ws_transport}[kind]
+ session = {"session_key": "chat", "transport": transport, "profile_home": str(home),
+ "history_lock": threading.RLock(), "running": False, "_finalized": False}
server._sessions["ui1"] = session
return session
-def _completion(*, restored=True):
+def _orphan_owner(home):
+ """The owner died while this process runs: pid 0 never passes the liveness probe."""
+ conn = sqlite3.connect(home / "state.db")
+ with conn:
+ conn.execute("UPDATE async_delegations SET owner_pid=0, updated_at=?", (time.time() - 3600,))
+ conn.close()
+
+
+def _completion(home, *, via):
event = {
"type": "async_delegation", "delegation_id": "completed-child",
"session_key": "chat", "origin_ui_session_id": "ui1",
@@ -75,81 +70,36 @@ def _completion(*, restored=True):
}
ad._persist_dispatch(event)
ad._persist_completion(event, {"summary": "child result"})
- if restored:
- offered = queue.Queue()
+ offered = queue.Queue()
+ if via == "startup":
assert ad.restore_undelivered_completions(offered) == 1
- return offered.get_nowait()
- return event
+ else:
+ _orphan_owner(home)
+ assert ad.sweep_orphaned_completions(offered) == 1
+ return offered.get_nowait()
[email protected]("kind,owns", [
- ("stdio", True), ("sidecar", True), ("websocket", True),
- ("headless", False), ("headless_sidecar", False), ("detached", False),
- ("closed", False), ("absent", False), ("foreign_stdio", False), ("finalized", False),
[email protected]("kind,via,owns", [
+ ("detached", "startup", False), # the reported shape: no client, lease survived the restart
+ ("websocket", "startup", True), # live WS peer
+ ("stdio", "startup", True), # this process's real TUI stdio RPC channel
+ ("detached", "sweep", True), # in-process orphan sweep keeps its routing
])
[email protected]("origin", ["ui1", "retired-tab"])
-def test_restored_notification_transport(notification_env, monkeypatch, kind, owns, origin):
+def test_startup_replay_requires_a_live_consumer(notification_env, monkeypatch, kind, via, owns):
+ home, _loop, submit = notification_env
session = _session(notification_env, monkeypatch, kind)
- event = _completion()
- event["origin_ui_session_id"] = origin
- assert event["restored"] is True
- assert server._session_owns_notification_event("ui1", session, event) is owns
- foreign = dict(event, origin_ui_session_id="other", session_key="other")
- assert server._session_owns_notification_event("ui1", session, foreign) is False
- # Stdio's notification exception must not change shared peer membership.
- assert server._session_has_live_transport(session) is (kind in {"websocket"})
+ event = _completion(home, via=via)
+ assert event["restored"] is True and bool(event.get("startup_replay")) is (via == "startup")
server._notif_handle_ready(
"ui1", session, [event], set(), process_registry, format_process_notification, None)
- submit = notification_env[2]
assert submit.call_count == int(owns)
- assert server._emit.call_count == int(owns)
row = ad.get_durable_delegation(event["delegation_id"])
- assert row["delivery_state"] == ("delivered" if owns else "pending")
- assert row["delivery_attempts"] == int(owns)
- if owns:
- assert submit.call_args.args[1:3] == ("ui1", session)
- assert "child result" in submit.call_args.args[3]
- assert submit.call_args.kwargs["display_kind"] == "async_delegation_complete"
- else:
- assert session["running"] is False
- # Rejection returns the durable offer for a future attached owner.
+ assert (row["delivery_state"], row["delivery_attempts"]) == (("delivered", 1) if owns else ("pending", 0))
+ if not owns:
+ # Refusal hands the offer back; the sweep's re-offer stays gated until a client attaches.
+ _orphan_owner(home)
offered = queue.Queue()
- assert ad.restore_undelivered_completions(offered) == 1
- assert offered.get_nowait()["delegation_id"] == event["delegation_id"]
-
-
[email protected]("kind", ["stdio", "sidecar", "websocket", "headless", "detached", "closed", "absent"])
-def test_non_restored_routing_is_preserved(notification_env, monkeypatch, kind):
- session = _session(notification_env, monkeypatch, kind)
- event = _completion(restored=False)
- assert server._session_owns_notification_event("ui1", session, event) is True
- foreign = dict(event, origin_ui_session_id="other", session_key="other")
- assert server._session_owns_notification_event("ui1", session, foreign) is False
- server._notif_handle_ready(
- "ui1", session, [event], set(), process_registry, format_process_notification, None)
- notification_env[2].assert_called_once()
- assert ad.get_durable_delegation(event["delegation_id"])["delivery_state"] == "delivered"
-
-
[email protected]("blocked", ["execution", "cancel", "busy"])
-def test_live_stdio_waits_for_admission(notification_env, monkeypatch, blocked):
- session = _session(notification_env, monkeypatch, "stdio")
- event = _completion()
- submit = notification_env[2]
- if blocked == "execution":
- submit.return_value = False
- elif blocked == "cancel":
- session["_turn_cancel_requested"] = True
- else:
- session["running"] = True
- deferred = []
- server._notif_handle_ready(
- "ui1", session, [event], set(), process_registry, format_process_notification, deferred)
- row = ad.get_durable_delegation(event["delegation_id"])
- assert row["delivery_state"] == "pending"
- assert row["delivery_attempts"] == 0
- assert submit.call_count == int(blocked == "execution")
- assert session["running"] is (blocked == "busy")
- assert process_registry.completion_queue.get_nowait() == event
+ assert ad.sweep_orphaned_completions(offered) == 1
+ assert offered.get_nowait()["startup_replay"] is True
diff --git a/tools/async_delegation.py b/tools/async_delegation.py
index b3746bb23f0..7852e07a43d 100644
--- a/tools/async_delegation.py
+++ b/tools/async_delegation.py
@@ -65,6 +65,9 @@ _orphan_lock = threading.Lock()
# 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()
+# Delegation ids this process first offered from its startup replay. Their copies carry
+# ``startup_replay`` on the sweep's later re-offers too, so a refused one stays gated.
+_startup_replayed: set = set()
_last_orphan_sweep: dict[str, float] = {}
# ── Stale-delegation detection (progress-based, on by default) ──────────────
@@ -351,10 +354,10 @@ def restore_undelivered_completions(target_queue) -> int:
FROM async_delegations
WHERE state != 'running' AND delivery_state='pending' AND event_json IS NOT NULL
ORDER BY completed_at, delegation_id""").fetchall()
- return _replay_pending(conn, rows, target_queue, now)
+ return _replay_pending(conn, rows, target_queue, now, startup=True)
-def _replay_pending(conn, rows, target_queue, now: float) -> int:
+def _replay_pending(conn, rows, target_queue, now: float, *, startup: bool = False) -> 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``. Records the offer so
the orphan sweep skips the row until the copy is handed back (``return_completion_offer``)."""
@@ -378,7 +381,13 @@ def _replay_pending(conn, rows, target_queue, now: float) -> int:
evt = json.loads(payload)
if isinstance(evt, dict):
evt = redact_completion_event(evt)
- evt["restored"] = True
+ with _orphan_lock:
+ if startup:
+ _startup_replayed.add(delegation_id)
+ if isinstance(evt, dict):
+ evt["restored"] = True
+ if delegation_id in _startup_replayed:
+ evt["startup_replay"] = True
target_queue.put(evt)
with _orphan_lock:
_offered.add((home, delegation_id))
@@ -585,6 +594,8 @@ def requeue_admitted_completion(delegation_id: str, target_queue) -> bool:
return False
rows = conn.execute("""SELECT delegation_id, event_json, completed_at, dispatched_at
FROM async_delegations WHERE delegation_id=?""", (delegation_id,)).fetchall()
+ with _orphan_lock: # an admitted copy already had its consumer: requeue keeps live routing
+ _startup_replayed.discard(delegation_id)
return _replay_pending(conn, rows, target_queue, now) == 1
@@ -1288,4 +1299,5 @@ def _reset_for_tests() -> None:
_records.clear()
with _orphan_lock:
_offered.clear()
+ _startup_replayed.clear()
_last_orphan_sweep.clear()
diff --git a/tui_gateway/session_notifications.py b/tui_gateway/session_notifications.py
index e11d2f994e7..a7c89af9808 100644
--- a/tui_gateway/session_notifications.py
+++ b/tui_gateway/session_notifications.py
@@ -96,12 +96,12 @@ def _session_owns_notification_event(sid: str, session: dict, evt: dict) -> bool
resolved matches) — the fail-closed gate for addressed notifications, without the orphan-adoption fallback."""
if session.get("_finalized"):
return False
- # A completion restored after process restart has no in-process owner. A matching
+ # A completion replayed at process start has no in-process owner. A matching
# persisted key alone can belong to a detached runtime whose old lease survived;
# requiring a current client prevents it from spending a full model turn unseen.
# Shared peer membership excludes stdio, even when it is the real TUI RPC channel
# (possibly wrapped for a dashboard sidecar), rather than a headless fallback sink.
- if (evt.get("type") == "async_delegation" and evt.get("restored")
+ if (evt.get("type") == "async_delegation" and evt.get("startup_replay")
and not (_session_has_live_transport(session)
or (_stdio_is_rpc_channel and session.get("transport") is _stdio_transport))):
return False