The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): settle cancelled managed startup before reservation
David Dudok de Witcb7cf192ea08
diff --git a/gateway/session_managed_worker.py b/gateway/session_managed_worker.pyindex a9b8bf1684f..99f51bbda2b 100644--- a/gateway/session_managed_worker.py+++ b/gateway/session_managed_worker.py@@ -282,14 +282,24 @@ def _worker_env(authority):return env+def _interrupted_before_bootstrap(authority, row):+ authority.pending_results[row['admission_id']] = {+ 'result': {'final_response': '', 'interrupted': True}, 'usage': {}}+ return ''++async def execute_managed(authority, ref, row, policy):from gateway.run_turn_progress import publish_worker_tool_event- env = await asyncio.to_thread(_worker_env, authority)- cwd = (await asyncio.to_thread(Path(__file__).resolve)).parents[1]- from gateway.session_worker_spawn import acquire_process- process = await acquire_process(subprocess.Popen, [sys.executable, '-m', 'agent.managed_worker'],- cwd=cwd, stdin=subprocess.PIPE, env=env,- stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, close_fds=True)+ try:+ env = await asyncio.to_thread(_worker_env, authority)+ cwd = (await asyncio.to_thread(Path(__file__).resolve)).parents[1]+ from gateway.session_worker_spawn import acquire_process+ process = await acquire_process(subprocess.Popen, [sys.executable, '-m', 'agent.managed_worker'],+ cwd=cwd, stdin=subprocess.PIPE, env=env,+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, close_fds=True)+ except asyncio.CancelledError:+ # acquire_process owns late-child cleanup; no bootstrap or reservation was sent.+ return _interrupted_before_bootstrap(authority, row)worker = ManagedWorker(process)workers = getattr(authority, '_managed_workers', None)if workers is None:@@ -352,12 +362,11 @@ async def execute_managed(authority, ref, row, policy):logging.getLogger(__name__).warning('Managed worker lost: %s',exc.reason if isinstance(exc, RuntimeStoreError) else type(exc).__name__)if scope is None:- if isinstance(exc, RuntimeStoreError) and exc.reason == 'managed_worker_stopped':+ if isinstance(exc, asyncio.CancelledError) or (+ isinstance(exc, RuntimeStoreError) and exc.reason == 'managed_worker_stopped'):# Stopped before the child ever received its bootstrap: nothing executed, so# this settles like an ordinary interrupted turn (the finally kills the child).- authority.pending_results[row['admission_id']] = {- 'result': {'final_response': '', 'interrupted': True}, 'usage': {}}- return ''+ return _interrupted_before_bootstrap(authority, row)raisefrom gateway.session_worker_reservation import lose_admission_workerlose_admission_worker(authority, row, scope)diff --git a/tests/gateway/test_managed_spawn_cancellation.py b/tests/gateway/test_managed_spawn_cancellation.pyindex 5101e5c743d..8fd631d2f07 100644--- a/tests/gateway/test_managed_spawn_cancellation.py+++ b/tests/gateway/test_managed_spawn_cancellation.py@@ -23,11 +23,14 @@ async def test_cancelled_spawn_reaps_late_child(monkeypatch):return childmonkeypatch.setattr(managed.subprocess, 'Popen', spawn)monkeypatch.setattr(managed, '_worker_env', lambda authority: None)- task = asyncio.create_task(managed.execute_managed(SimpleNamespace(), SimpleNamespace(session_id='s'), {}, None))+ authority = SimpleNamespace(pending_results={})+ task = asyncio.create_task(managed.execute_managed(+ authority, SimpleNamespace(session_id='s'), {'admission_id': 'unstarted'}, None))try:assert await asyncio.to_thread(entered.wait, 5)task.cancel()- with pytest.raises(asyncio.CancelledError): await task+ assert await task == ''+ assert authority.pending_results['unstarted']['result']['interrupted'] is Truerelease.set()assert await asyncio.to_thread(created.wait, 5)await asyncio.to_thread(children[0].wait, 5)diff --git a/tests/gateway/test_managed_unstarted_cancel.py b/tests/gateway/test_managed_unstarted_cancel.pynew file mode 100644index 00000000000..7a307634dab--- /dev/null+++ b/tests/gateway/test_managed_unstarted_cancel.py@@ -0,0 +1,68 @@+"""Cancellation before reservation closes any acquired child and settles the unexecuted claim."""+import asyncio+import os+import subprocess+import sys+import threading++import pytest++from gateway.session_contract import Submission+from hermes_state_runtime import get_session_admission+from tests.gateway.test_session_authority_cancel_settlement import _authority, ACTOR, REF++[email protected]('phase', ['environment', 'spawn', 'hello'])+async def test_cancel_before_worker_reservation_settles_interrupted(tmp_path, monkeypatch, phase):+ from gateway import session_managed_worker as managed+ db, authority = _authority(tmp_path, monkeypatch)+ entered, release = threading.Event(), threading.Event()+ children = []+ original_spawn = subprocess.Popen+ def environment(owner):+ if phase == 'environment':+ entered.set()+ assert release.wait(10)+ return dict(os.environ)+ def spawn(args, **kwargs):+ if phase == 'spawn':+ entered.set()+ assert release.wait(10)+ child = original_spawn([sys.executable, '-c', 'import sys; sys.stdin.buffer.read()'], **kwargs)+ children.append(child)+ return child+ original_next = managed.ManagedWorker.next_frame+ async def next_frame(worker, *args, **kwargs):+ if phase == 'hello':+ entered.set()+ return await original_next(worker, *args, **kwargs)+ monkeypatch.setattr(managed, '_worker_env', environment)+ monkeypatch.setattr(managed.subprocess, 'Popen', spawn)+ monkeypatch.setattr(managed.ManagedWorker, 'next_frame', next_frame)+ async def execute(owner, ref, row):+ return await managed.execute_managed(owner, ref, row, policy=None)+ monkeypatch.setattr('gateway.session_finite.execute_finite_admission', execute)+ with db:+ receipt = await authority.submit(ACTOR, Submission('cancelled-startup', REF, {'text': 'work'}, 'queue'))+ task = authority.sessions['s'].task+ try:+ assert await asyncio.to_thread(entered.wait, 5)+ task.cancel()+ release.set()+ await asyncio.wait_for(task, 10)+ row = get_session_admission(db, admission_id=receipt.admission_id)+ assert row['status'] == 'terminal' and row['outcome'] == 'interrupted'+ assert authority.sessions['s'].event_stream.execution == {}+ if phase != 'environment':+ async with asyncio.timeout(10):+ while not children or any(child.poll() is None for child in children):+ await asyncio.sleep(.01)+ assert db._read_one('SELECT COUNT(*) FROM worker_executions')[0] == 0+ finally:+ release.set()+ await asyncio.gather(task, return_exceptions=True)+ for child in children:+ if child.poll() is None:+ child.kill()+ child.wait(timeout=5)