Skip to content

The agent that grows with you

fix(process): hold a notice's owner through routing, keep unpublished exits out of pruning

Ben Barclay5694f8f733d7
diff --git a/tests/tui_gateway/test_detached_process_notify_keepalive.py b/tests/tui_gateway/test_detached_process_notify_keepalive.py
index 1d84757052a..0f630444150 100644
--- a/tests/tui_gateway/test_detached_process_notify_keepalive.py
+++ b/tests/tui_gateway/test_detached_process_notify_keepalive.py
@@ -118,51 +118,109 @@ def test_orphan_reap_rearms_while_process_will_notify(server, registry, detached
assert server._pending_ws_reaps[sid] is _Timer.created[-1]
-def test_exited_process_keeps_session_until_its_notice_is_dequeued(server, registry, detached):
- """The exit is recorded before the completion is queued, and the notice becomes a turn only once the poller
- dequeues it: a reaper firing anywhere in that hand-off must not close the session and lose the follow-up."""
+def test_exited_process_keeps_session_until_its_notice_is_routed(server, registry, detached):
+ """Exit recorded → completion published → dequeued by a poller → routed: a reaper firing at any point of that
+ hand-off must not close the session and lose the follow-up. Protection ends only when routing returns."""
+ from tools.process_registry_awaiting import release, take_ready
+
sid, session, _ = detached
proc = _spawn(registry, session["session_key"], notify_on_complete=True)
proc.exited = True # mark_exited ran; _move_to_finished (publish) has not yet
+ assert not server._session_is_reapable(sid, session)
+ registry._move_to_finished(proc) # published: queued
assert not server._session_is_reapable(sid, session)
- registry._move_to_finished(proc) # published: queued, not yet dequeued
- assert not registry.completion_queue.empty()
+ ready = take_ready(registry.completion_queue, 0) # a poller took it and is routing it
+ assert registry.completion_queue.empty() and len(ready) == 1
assert not server._session_is_reapable(sid, session)
- registry.completion_queue.get_nowait() # the poller took it
+ release(ready) # routing returned (turn admitted → ``running`` protects it, or requeued, or dropped)
assert server._session_is_reapable(sid, session)
-def test_queued_notice_survives_registry_pruning(server, registry, detached):
- """Retained history is pruned by start time and a process cap, on every spawn: a long job's queued completion
- must keep protecting its owner after its finished entry is gone."""
+def test_unpublished_completion_survives_registry_pruning(server, registry, detached, monkeypatch):
+ """Pruning can run (a concurrent spawn) after the exit is recorded but before the completion is queued; the
+ entry must survive it, since it is the only record that a notice is still coming."""
from tools.process_registry import FINISHED_TTL_SECONDS
sid, session, _ = detached
proc = _spawn(registry, session["session_key"], notify_on_complete=True)
proc.started_at = time.time() - FINISHED_TTL_SECONDS - 1
proc.mark_exited(0)
+ publish = registry._publish_finished
+ seen = []
+
+ def prune_mid_publish(s, was_running):
+ with registry._lock:
+ registry._prune_if_needed()
+ seen.append((s.id in registry._finished, server._session_is_reapable(sid, session)))
+ publish(s, was_running)
+
+ monkeypatch.setattr(registry, "_publish_finished", prune_mid_publish)
registry._move_to_finished(proc)
- with registry._lock:
- registry._prune_if_needed()
+ assert seen == [(True, False)]
+ with registry._lock: # once published, the entry is ordinary history again
+ registry._prune_if_needed()
assert proc.id not in registry._finished
- assert not server._session_is_reapable(sid, session)
-def test_session_released_once_notice_is_delivered(server, registry, detached):
- sid, session, popped = detached
+def test_poller_holds_session_between_dequeue_and_routing(server, registry, detached, monkeypatch):
+ """The real poller loop: a reaper that fires after the poller dequeued the completion but before it routed it
+ must still see the session as protected."""
+ sid, session, _ = detached
proc = _spawn(registry, session["session_key"], notify_on_complete=True)
proc.mark_exited(0)
registry._move_to_finished(proc)
- registry.completion_queue.get_nowait()
+ for name in ("_maybe_fire_tui_loop_tick", "_maybe_fire_tui_heartbeat_tick", "_notif_poll_kanban"):
+ monkeypatch.setattr(server, name, lambda *a, **k: None)
+ monkeypatch.setattr(registry, "restore_completions", lambda: 0)
+ stop, observed = threading.Event(), []
+
+ def routing(*args, **kwargs):
+ if kwargs.get("deferred", args[6] if len(args) > 6 else None) is None and not observed:
+ observed.append((registry.completion_queue.empty(), server._session_is_reapable(sid, session)))
+ stop.set()
+
+ monkeypatch.setattr(server, "_notif_handle_ready", routing)
+ worker = threading.Thread(target=server._notification_poller_scoped_loop, args=(stop, sid, session), daemon=True)
+ worker.start()
+ worker.join(timeout=10)
+
+ assert not worker.is_alive()
+ assert observed == [(True, False)], "dequeued but unrouted: the session must stay protected"
+ assert server._session_is_reapable(sid, session), "routing returned: the hold is released"
+
+
[email protected]("persist", [False, True])
+def test_stop_releases_session_even_with_a_running_watch(server, registry, detached, persist):
+ """After Stop no notification turn can start until the user's next prompt, so a never-exiting watched server
+ must not keep the stopped, disconnected session alive."""
+ sid, session, _ = detached
+ _spawn(registry, session["session_key"], watch_patterns=["ERROR"], persist_on_release=persist)
+ assert not server._session_is_reapable(sid, session)
- server._schedule_ws_orphan_reap(sid)
- _Timer.created[-1].callback()
+ session["_turn_cancel_requested"] = True
- assert sid not in server._sessions and popped == [session]
+ assert server._session_is_reapable(sid, session)
+
+
+def test_queued_notice_survives_registry_pruning(server, registry, detached):
+ """Retained history is pruned by start time and a process cap, on every spawn: a long job's queued completion
+ must keep protecting its owner after its finished entry is gone."""
+ from tools.process_registry import FINISHED_TTL_SECONDS
+
+ sid, session, _ = detached
+ proc = _spawn(registry, session["session_key"], notify_on_complete=True)
+ proc.started_at = time.time() - FINISHED_TTL_SECONDS - 1
+ proc.mark_exited(0)
+ registry._move_to_finished(proc)
+ with registry._lock:
+ registry._prune_if_needed()
+
+ assert proc.id not in registry._finished
+ assert not server._session_is_reapable(sid, session)
def test_notice_held_after_stop_does_not_pin_session(server, registry, detached):
diff --git a/tools/process_registry.py b/tools/process_registry.py
index e1949b6bbe2..b285fc414a2 100644
--- a/tools/process_registry.py
+++ b/tools/process_registry.py
@@ -2547,10 +2547,13 @@ class ProcessRegistry(ProcessTerminationMixin, ProcessCheckpointMixin, ProcessOu
def _prune_if_needed(self):
"""Drop expired finished sessions, then the oldest survivor while over
- MAX_PROCESSES. Must hold _lock. A session whose scope stop is still pending is kept
- either way: it is kill_all's only handle on a scope that may hold live descendants."""
+ MAX_PROCESSES. Must hold _lock. Kept either way: a session whose scope stop is still
+ pending (kill_all's only handle on a scope that may hold live descendants), and one
+ whose completion is not yet published (its owner's reaper protection reads it)."""
now = time.time()
- prunable = {sid: s for sid, s in self._finished.items() if not getattr(s, "_scope_stop_pending", False)}
+ prunable = {sid: s for sid, s in self._finished.items()
+ if not getattr(s, "_scope_stop_pending", False)
+ and not (getattr(s, "_finish_claimed", False) and not s._completion_event.is_set())}
expired = [sid for sid, s in prunable.items() if (now - s.started_at) > FINISHED_TTL_SECONDS]
over_cap = len(self._running) + len(self._finished) - len(expired) >= MAX_PROCESSES
if over_cap and (survivors := [sid for sid in prunable if sid not in expired]):
diff --git a/tools/process_registry_awaiting.py b/tools/process_registry_awaiting.py
index 21bfd7c50ab..0a4b86bba04 100644
--- a/tools/process_registry_awaiting.py
+++ b/tools/process_registry_awaiting.py
@@ -3,39 +3,102 @@
The session reapers keep an owner alive while this is true: the notice reaches the model only through that owner's
notification poller, and closing the owner kills the process (``agent_close``).
-Pending is read from live state, not estimated with a timer: the process is still running and notifies, its exit is
-recorded but its completion not yet published, or an event it produced is still queued. Each state ends on its own
-(the process exits, the publish lands, a poller dequeues the event), so an owner is never pinned after its notice is
-handed over, and pruning retained process history cannot release an owner whose notice is still in flight.
+Pending is read from live state, never estimated with a timer. A notice is pending from the moment its process can
+produce it until a consumer has finished routing it:
+
+1. a notifying process is still running;
+2. its exit is recorded but the completion is not yet published (``_completion_event`` unset; the registry keeps
+ such entries out of pruning);
+3. the event sits in ``completion_queue``;
+4. a consumer has taken it off the queue and is still routing it (an in-flight hold, taken atomically with the
+ dequeue under the queue's own lock and released only after routing returns).
+
+Routing ends by admitting a turn (``running`` then protects the session), requeueing (state 3 again) or dropping the
+notice, so every state hands over to the next without a gap and none outlives delivery.
"""
from __future__ import annotations
+import collections
+import contextlib
+import threading
+
+# Owner task id → number of dequeued-but-unrouted events. take_ready increments it under the queue's mutex in the same
+# critical section as the dequeue, and awaits_notification reads queue and counter under that mutex too, so a reader
+# sees each event either queued or held, never neither. Decrements (release) happen only after any requeue.
+_in_flight: collections.Counter = collections.Counter()
+_in_flight_lock = threading.Lock() # always taken after the queue mutex, never before
+
+
+def _owner(evt) -> str:
+ return str(evt.get("owner_task_id") or "") if isinstance(evt, dict) else ""
+
+
+def _adjust(owners, delta: int) -> None:
+ with _in_flight_lock:
+ for owner in owners:
+ if not owner:
+ continue
+ _in_flight[owner] += delta
+ if _in_flight[owner] <= 0:
+ del _in_flight[owner]
+
+
+def take_ready(queue, timeout: float) -> list:
+ """Dequeue everything queued (waiting up to ``timeout`` for the first event) and hold each event's owner in the
+ same critical section, so no reaper check can observe an event as neither queued nor held. The caller MUST pass
+ the result to ``release`` once routing returns."""
+ with queue.not_empty:
+ if not queue._qsize() and timeout > 0:
+ queue.not_empty.wait(timeout)
+ events = list(queue.queue)
+ queue.queue.clear()
+ if events:
+ queue.not_full.notify_all()
+ _adjust((_owner(e) for e in events), +1)
+ return events
+
+
+def release(events) -> None:
+ """End the in-flight hold ``take_ready`` took for ``events`` (after any requeue, so coverage is continuous)."""
+ if events:
+ _adjust((_owner(e) for e in events), -1)
+
+
+def holding(owner_task_ids):
+ """Hold ``owner_task_ids`` for a drain that dequeues through another API (``drain_notifications``)."""
+ owners = [o for o in owner_task_ids if o]
+ _adjust(owners, +1)
+ try:
+ yield
+ finally:
+ _adjust(owners, -1)
+
def _notifies(s) -> bool:
return bool(s.notify_on_complete or (s.watch_patterns and not s._watch_disabled))
-def awaits_notification(registry, owner_task_ids, *, include_queued: bool = True) -> bool:
+def awaits_notification(registry, owner_task_ids) -> bool:
"""Whether a process spawned by one of ``owner_task_ids`` still has a notice on its way. Keyed on the RAW
- spawning owner, the same field agent close kills by, so it survives compression rotating the session key.
- ``include_queued=False`` ignores already-published events — for an owner whose poller is holding them back
- (the user pressed Stop) until a prompt that only the user can send."""
+ spawning owner, the same field agent close kills by, so it survives compression rotating the session key."""
owners = {o for o in owner_task_ids if o}
if not owners:
return False
- # Running. _any_running refreshes checkpoint-recovered entries (outside the registry lock) first, so a recovered
- # PID that died unobserved reads as gone instead of pinning its owner.
+ # (1) Running. _any_running refreshes checkpoint-recovered entries (outside the registry lock) first, so a
+ # recovered PID that died unobserved reads as gone instead of pinning its owner.
if registry._any_running(lambda s: s.owner_task_id in owners and _notifies(s)):
return True
with registry._lock:
- # Exit recorded, completion not yet queued: _move_to_finished sets _completion_event only after the publish.
- # Entries closed without a collected exit (recovered PID gone or reused) set it too, so they never count.
+ # (2) Exit recorded, completion not yet published. Entries closed without a collected exit (recovered PID
+ # gone or reused) set _completion_event too, so they never count.
if any(s.owner_task_id in owners and s.notify_on_complete and s.exited and not s._completion_event.is_set()
for store in (registry._running, registry._finished) for s in store.values()):
return True
- if not include_queued:
- return False
queue = registry.completion_queue
- with queue.mutex: # published, not yet dequeued (or requeued while the owner was busy)
- return any(isinstance(evt, dict) and evt.get("owner_task_id") in owners for evt in queue.queue)
+ with queue.mutex: # (3) queued and (4) in flight, read together: take_ready moves events between them here
+ with _in_flight_lock:
+ if any(_in_flight.get(o) for o in owners):
+ return True
+ return any(_owner(evt) in owners for evt in queue.queue)
diff --git a/tui_gateway/prompt_turn.py b/tui_gateway/prompt_turn.py
index 00764dc8603..e00e9c3d7d7 100644
--- a/tui_gateway/prompt_turn.py
+++ b/tui_gateway/prompt_turn.py
@@ -463,7 +463,10 @@ def _run_post_turn_followups(
from tools.process_registry import process_registry
# _release_turn_scopes / _post_turn_housekeeping have released the worker's runtime scopes. Queue ownership,
# notification policy and nested dispatch still belong to this session.
- with _session_profile_runtime_scope(session):
+ from tools.process_registry_awaiting import holding
+ # This drain dequeues this session's own events while it is idle; hold its owners until routing finishes so
+ # the reapers cannot close it between dequeue and turn admission.
+ with _session_profile_runtime_scope(session), holding(_session_process_owners(session)):
drained = process_registry.drain_notifications(
session_key=session.get("session_key", ""),
owns_event=lambda e: _session_owns_notification_event(sid, session, e),
diff --git a/tui_gateway/session_notifications.py b/tui_gateway/session_notifications.py
index 0b2d0d23219..e5c95fd8e48 100644
--- a/tui_gateway/session_notifications.py
+++ b/tui_gateway/session_notifications.py
@@ -324,17 +324,24 @@ def _session_owns_live_wakeup_schedule(session: dict) -> bool:
def _session_owns_pending_process_notification(session: dict) -> bool:
"""True while a background process this session started will still report back into it (``notify_on_complete``
- or ``watch_patterns``): running, exited with its completion not yet published, or published but not yet dequeued. The notice
+ or ``watch_patterns``): running, or its notice not yet routed (see ``tools.process_registry_awaiting``). The notice
reaches the model only through THIS session's notification poller, and closing the session kills the process
(``agent_close``), so the reapers must keep it alive. Ownership is the set close() kills by — the agent's raw
spawning task ids, which keep pre-compression ids after the session key rotates. Bounded by delivery: the session
- is released once the notice has been dequeued."""
- agent = session.get("agent")
- owners = {*getattr(agent, "_process_owner_task_ids", ()), str(session.get("session_key") or "")}
+ is released once routing admits the notice's turn (``running`` then protects it), requeues or drops it."""
+ if session.get("_turn_cancel_requested"):
+ # After Stop no notification turn can start until the user's next prompt (``_notif_claim_turn``), so a
+ # pending notice is no reason to keep the session: the user's prompt resumes it like any other.
+ return False
from tools.process_registry import process_registry
from tools.process_registry_awaiting import awaits_notification
- # After Stop the poller requeues notices until the user's next prompt: those must not make the session immortal.
- return awaits_notification(process_registry, owners, include_queued=not session.get("_turn_cancel_requested"))
+ return awaits_notification(process_registry, _session_process_owners(session))
+
+
+def _session_process_owners(session: dict) -> set:
+ """The raw spawning ids ``close()`` kills by (pre-compression ids included), plus the current key."""
+ agent = session.get("agent")
+ return {*getattr(agent, "_process_owner_task_ids", ()), str(session.get("session_key") or "")} - {""}
def _maybe_fire_tui_loop_tick(sid: str, session: dict) -> None:
@@ -726,6 +733,7 @@ def _notification_poller_scoped_loop(stop_event: threading.Event, sid: str, sess
"""
from tools import async_delegation
from tools.process_registry import process_registry
+ from tools.process_registry_awaiting import release as release_in_flight, take_ready
from tools.process_registry_notifications import format_process_notification
process_registry.restore_completions() # first consumer in a TUI process (#123265)
queue = process_registry.completion_queue
@@ -749,34 +757,29 @@ def _notification_poller_scoped_loop(stop_event: threading.Event, sid: str, sess
if now - last_kanban_poll >= _KANBAN_POLL_SECONDS:
last_kanban_poll = now
_notif_poll_kanban(sid, session)
- try:
- evt = queue.get(timeout=0.5)
- except Exception:
+ # Dequeue and in-flight hold are one step: until routing admits a turn, requeues or drops each event, its
+ # owner session stays protected from the reapers (it is in neither the queue nor ``running`` meanwhile).
+ ready = take_ready(queue, 0.5)
+ if not ready:
continue
- ready = [evt]
- for _ in range(queue.qsize()):
- try:
- ready.append(queue.get_nowait())
- except Exception:
- break
try:
handle(ready, None)
except Exception as exc:
# This thread is the session's only path to notifications, /loop, /heartbeat and its
# bot mailbox; one bad event must not end all four.
_notif_log_failure("notification dispatch failed", exc)
+ finally:
+ release_in_flight(ready)
# Drain remaining events after the stop signal so nothing is lost on shutdown; foreign and orphaned-delegation
# events are handed back to the shared queue afterwards.
deferred: list = []
- ready = []
- for _ in range(queue.qsize()):
- try:
- ready.append(queue.get_nowait())
- except Exception:
- break
- handle(ready, deferred)
- for evt in deferred:
- queue.put(evt)
+ ready = take_ready(queue, 0)
+ try:
+ handle(ready, deferred)
+ for evt in deferred:
+ queue.put(evt)
+ finally:
+ release_in_flight(ready)
def _async_delegation_display_metadata(evt: dict) -> dict: