Skip to content

The agent that grows with you

fix(gateway): count /bg, /btw and preview-restart side agents as owner work

David Dudok de Wit00558b1f0447
diff --git a/gateway/session_runtime_workers.py b/gateway/session_runtime_workers.py
index 3631888bab2..4b949c01c35 100644
--- a/gateway/session_runtime_workers.py
+++ b/gateway/session_runtime_workers.py
@@ -20,7 +20,13 @@ def uncounted_runtime_work(runner):
for worker in getattr(authority, '_managed_workers', {}).values())
return (managed + sum(live.route not in running and sid not in getattr(authority, '_managed_workers', {})
for authority in authorities for sid, live, _ in executing_sessions(authority))
- + sum(len(mutation_tasks(authority)) for authority in authorities))
+ + sum(len(mutation_tasks(authority)) + len(side_agents(authority)) for authority in authorities))
+
+
+def side_agents(authority):
+ """``(thread, holder)`` for each detached side agent (/bg, /btw, preview restart) whose thread
+ has not unwound (``gateway/session_tui_side.py`` ``_spawn``)."""
+ return list(getattr(authority, '_side_agents', {}).items())
def persist_work_count(authority, _task=None):
@@ -131,7 +137,7 @@ def stop_authority_work(authority):
from gateway.run_runtime import stop_authority_turns
from agent.interrupt_compat import request_hard_interrupt
stop_authority_turns(authority, in_process=True)
- for _, holder in physical_workers(authority):
+ for _, holder in [*physical_workers(authority), *side_agents(authority)]:
if holder and holder[0] is not None:
request_hard_interrupt(holder[0], 'Profile runtime is stopping')
for cancel in getattr(authority, '_cron_cancellations', {}).values():
@@ -142,7 +148,8 @@ async def join_authority_work(authority, timeout):
deadline = asyncio.get_running_loop().time() + timeout
while True:
stop_authority_work(authority)
- if not list(physical_workers(authority)) and not list(executing_sessions(authority)) and not mutation_tasks(authority):
+ if (not list(physical_workers(authority)) and not list(executing_sessions(authority))
+ and not mutation_tasks(authority) and not side_agents(authority)):
return
if asyncio.get_running_loop().time() >= deadline:
raise TimeoutError('Profile workers did not stop; ownership retained')
diff --git a/gateway/session_tui_side.py b/gateway/session_tui_side.py
index a20ebd65278..e286b020aee 100644
--- a/gateway/session_tui_side.py
+++ b/gateway/session_tui_side.py
@@ -9,6 +9,7 @@ under the owning profile's scope and the session's frozen launch policy (cwd, te
route, toolsets), so a session that never ran a turn (no resident agent) works the same.
"""
from functools import partial
+import asyncio
import contextlib
import logging
import threading
@@ -19,8 +20,6 @@ from hermes_state_runtime import RuntimeStoreError
logger = logging.getLogger(__name__)
-# Strong references to the running side-agent threads (dropped as each one finishes).
-_RUNNING = set()
_RUNTIME_KEYS = ('api_key', 'base_url', 'provider', 'requested_provider', 'api_mode', 'command', 'args',
'credential_pool', 'max_tokens', 'capabilities')
@@ -106,27 +105,51 @@ def _side_agent(authority, policy, live, task_id, **overrides):
return AIAgent(**kwargs)
-def _spawn(authority, ref, task_id, event_type, body, extra=None):
- """Run ``body()`` on a daemon thread; publish its text (or ``error: <exc>``) on the session."""
+def _spawn(authority, ref, task_id, event_type, body, extra=None, holder=None):
+ """Run ``body()`` on a daemon thread; publish its text (or ``error: <exc>``) on the session.
+
+ The thread is owner work until it unwinds: the authority's ``_side_agents`` ledger is counted by
+ the restart wait, the shutdown drain, the SessionDB close gate and idle exit
+ (``session_runtime_workers.uncounted_runtime_work``), and profile retirement interrupts
+ ``holder[0]`` (the side agent, once built) and joins the thread."""
+ from gateway.session_runtime_workers import persist_work_count
extra = extra or {}
+ ledger = getattr(authority, '_side_agents', None)
+ if ledger is None:
+ ledger = authority._side_agents = {}
+ try:
+ loop = asyncio.get_running_loop()
+ except RuntimeError:
+ loop = None
def run():
+ # The whole target: a BaseException the agent re-raises (cancellation, exit) must not
+ # leave a dead thread counted as owner work.
try:
- text = body()
- except Exception as exc:
- logger.warning('Side agent %s failed', task_id, exc_info=True)
- text = f'error: {getattr(exc, "reason", None) or exc}'
- try:
+ try:
+ text = body()
+ except Exception as exc:
+ logger.warning('Side agent %s failed', task_id, exc_info=True)
+ text = f'error: {getattr(exc, "reason", None) or exc}'
live = authority.sessions.get(ref.session_id)
if live is not None:
live.event_stream.publish(ref.session_id, {'task_id': task_id, **extra, 'text': str(text or '')},
event_type=event_type)
finally:
- _RUNNING.discard(thread)
+ ledger.pop(thread, None)
+ if loop is not None:
+ # gateway_state.json's active_agents drops back, recounted on the owner loop.
+ with contextlib.suppress(RuntimeError): # the loop already closed
+ loop.call_soon_threadsafe(persist_work_count, authority)
thread = threading.Thread(target=run, name=f'side-agent-{task_id}', daemon=True)
- _RUNNING.add(thread)
- thread.start()
+ ledger[thread] = holder
+ try:
+ thread.start()
+ except BaseException:
+ ledger.pop(thread, None)
+ raise
+ persist_work_count(authority)
return {'task_id': task_id}
@@ -134,11 +157,12 @@ async def background(connection, ref, params):
"""``/bg <prompt>``: a fresh agent on the session's route runs the prompt to completion."""
live, policy, text, task_id = _admit(connection, ref, params, 'bg')
authority = connection.authority
+ holder = [None]
def body():
from tui_gateway.methods_prompt import _final_response_text
with _side_scope(authority, policy, task_id):
- agent = _side_agent(authority, policy, live, task_id)
+ agent = holder[0] = _side_agent(authority, policy, live, task_id)
try:
result = agent.run_conversation(user_message=text, task_id=task_id)
finally:
@@ -147,7 +171,7 @@ async def background(connection, ref, params):
agent.close()
return _final_response_text(result)
- return _spawn(authority, ref, task_id, 'background.complete', body)
+ return _spawn(authority, ref, task_id, 'background.complete', body, holder=holder)
async def btw(connection, ref, params):
@@ -185,6 +209,7 @@ async def preview_restart(connection, ref, params):
cwd, context = (str(params.get(key) or '').strip() for key in ('cwd', 'context'))
from gateway.session_local_recovery import transcript_target
target = transcript_target(authority, ref)
+ holder = [None]
def progress(text):
if (text := str(text or '').strip()) and (stream := authority.sessions.get(ref.session_id)) is not None:
@@ -209,6 +234,7 @@ async def preview_restart(connection, ref, params):
agent = _side_agent(authority, policy, live, task_id, enabled_toolsets=['terminal', 'file'],
disabled_toolsets=None, session_db=None, skip_memory=True,
tool_start_callback=lambda _id, name, _args: progress(f'Running {name}'))
+ holder[0] = agent
result = agent.run_conversation(user_message=prompt, task_id=task_id,
conversation_history=history or None)
finally:
@@ -217,4 +243,4 @@ async def preview_restart(connection, ref, params):
clear_task_env_overrides(task_id)
return _final_response_text(result)
- return _spawn(authority, ref, task_id, 'preview.restart.complete', body)
+ return _spawn(authority, ref, task_id, 'preview.restart.complete', body, holder=holder)
diff --git a/tests/gateway/test_runtime_worker_shutdown.py b/tests/gateway/test_runtime_worker_shutdown.py
index 63aabbfba99..bdc145ed2d9 100644
--- a/tests/gateway/test_runtime_worker_shutdown.py
+++ b/tests/gateway/test_runtime_worker_shutdown.py
@@ -167,3 +167,75 @@ async def test_persisted_work_count_returns_to_zero_when_the_drain_ends():
await live.task
await asyncio.sleep(0)
assert persisted and persisted[-1] == 0
+
+
+async def test_side_agent_is_owner_work_until_its_thread_unwinds(monkeypatch):
+ """/bg (like /btw and preview restart) runs on a detached thread (``session_tui_side._spawn``).
+ The restart wait, stop drain, SessionDB close gate and idle exit must count it, and retirement
+ must interrupt and join it, or a planned restart exits under it and its result never arrives."""
+ import contextlib
+ from gateway import session_tui_side
+ from gateway.session_contract import SessionRef
+ from gateway.session_runtime_workers import join_authority_work, uncounted_runtime_work
+
+ started, release, persisted, interrupts = threading.Event(), threading.Event(), [], []
+ def run_conversation(**_):
+ started.set()
+ release.wait(10)
+ return {'final_response': 'done'}
+ agent = SimpleNamespace(run_conversation=run_conversation, close=lambda: None,
+ hard_interrupt=lambda message=None: interrupts.append(message))
+ authority = SimpleNamespace(sessions={}, pending_stops={}, adopted={})
+ runner = SimpleNamespace(_running_agents={}, session_authority=authority,
+ _persist_active_agents=lambda: persisted.append(uncounted_runtime_work(runner)))
+ authority.runner = runner
+ monkeypatch.setattr(session_tui_side, '_admit', lambda *_: (None, None, 'task', 'bg_x'))
+ monkeypatch.setattr(session_tui_side, '_side_scope', lambda *_: contextlib.nullcontext())
+ monkeypatch.setattr(session_tui_side, '_side_agent', lambda *_: agent)
+ try:
+ await session_tui_side.background(SimpleNamespace(authority=authority), SessionRef('p', 's'), {})
+ assert await asyncio.to_thread(started.wait, 5)
+ thread = next(t for t in threading.enumerate() if t.name == 'side-agent-bg_x')
+ assert uncounted_runtime_work(runner) == 1 and persisted == [1]
+ with pytest.raises(TimeoutError): # retirement keeps ownership while it runs
+ await join_authority_work(authority, .2)
+ assert set(interrupts) == {'Profile runtime is stopping'} # the /bg agent, once built
+ release.set()
+ await join_authority_work(authority, 5)
+ await asyncio.to_thread(thread.join, 5)
+ await asyncio.sleep(0) # the thread's recount runs on the owner loop
+ assert uncounted_runtime_work(runner) == 0 and persisted[-1] == 0
+ finally:
+ release.set()
+
+
[email protected]('exit_type', [asyncio.CancelledError, KeyboardInterrupt, SystemExit])
+async def test_side_agent_thread_killed_by_a_base_exception_releases_owner_work(monkeypatch, exit_type):
+ """The agent re-raises cancellation and exit (``agent/turn_facade.py``). A side-agent thread
+ that dies that way must still leave the ledger, or idle exit, retirement, the persisted count
+ and the SessionDB close gate stay blocked on work that no longer exists."""
+ from gateway import session_tui_side
+ from gateway.session_contract import SessionRef
+ from gateway.session_runtime_workers import join_authority_work, uncounted_runtime_work
+
+ started, threads, failures, persisted = threading.Event(), [], [], []
+ authority = SimpleNamespace(sessions={}, pending_stops={}, adopted={})
+ runner = SimpleNamespace(_running_agents={}, session_authority=authority,
+ _persist_active_agents=lambda: persisted.append(uncounted_runtime_work(runner)))
+ authority.runner = runner
+ monkeypatch.setattr(threading, 'excepthook', lambda args: failures.append(args.exc_type))
+
+ def body():
+ threads.append(threading.current_thread())
+ started.set()
+ raise exit_type()
+
+ session_tui_side._spawn(authority, SessionRef('p', 's'), 'bg_abort', 'background.complete', body)
+ assert await asyncio.to_thread(started.wait, 5)
+ await asyncio.to_thread(threads[0].join, 5)
+ await asyncio.sleep(0) # the thread's recount runs on the owner loop
+ assert not threads[0].is_alive() and failures == [exit_type]
+ assert uncounted_runtime_work(runner) == 0 and (not persisted or persisted[-1] == 0)
+ await join_authority_work(authority, 0)
diff --git a/tests/gateway/test_session_config_loaders.py b/tests/gateway/test_session_config_loaders.py
index 8e90c402dba..abf5422956c 100644
--- a/tests/gateway/test_session_config_loaders.py
+++ b/tests/gateway/test_session_config_loaders.py
@@ -174,7 +174,7 @@ def test_bg_side_agent_uses_the_sessions_provider_routing(tmp_path):
reply = await session_tui_side.background(connection, SessionRef(owner.profile_id, ref.session_id),
{'session_id': ref.session_id, 'text': 'BG'})
assert reply['task_id'].startswith('bg_')
- for thread in list(session_tui_side._RUNNING):
+ for thread in list(owner._side_agents):
thread.join(30)
finally:
connection.subscriptions.clear()