The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: pause managed admission followers when the owned worker is lost
Tekniume6077eccc19e
diff --git a/gateway/session_managed_worker.py b/gateway/session_managed_worker.pyindex 6bb5961e145..87305caea08 100644--- a/gateway/session_managed_worker.py+++ b/gateway/session_managed_worker.py@@ -75,6 +75,7 @@ async def execute_managed(authority, ref, row, policy):workers = authority._managed_workers = {}workers[ref.session_id] = workeraccepted = None+ scope = Nonetry:scope = reserve_admission_worker(authority, admission_id=row['admission_id'],process=process, principal_id=row['principal_id'])@@ -104,6 +105,23 @@ async def execute_managed(authority, ref, row, policy):raise RuntimeStoreError('managed_worker_lost')return accepted['final_response']raise RuntimeStoreError('invalid_worker_frame')+ except (Exception, asyncio.CancelledError) as exc:+ if scope is None:+ raise+ from gateway.session_worker_reservation import lose_admission_worker+ lose_admission_worker(authority, row, scope)+ live = authority.sessions[ref.session_id]+ with live.event_stream.lock:+ live.controls.snapshot(ref.session_id, None)+ authority._publish_pending(ref)+ live.event_stream.publish(ref.session_id, {'text': 'Worker execution is unknown.',+ 'content': 'Worker execution is unknown.', 'admission_id': row['admission_id'], 'outcome': 'unknown'})+ waiter = authority.waiters.pop(row['admission_id'], None)+ if waiter is not None and not waiter.done():+ waiter.set_result('Worker execution is unknown.')+ # Stop this drain without its ordinary Exception→failed settlement. The+ # committed unknown row deliberately pauses every accepted follower.+ raise asyncio.CancelledError('managed_worker_unknown') from excfinally:workers.pop(ref.session_id, None)await asyncio.to_thread(worker.close)diff --git a/gateway/session_worker_reservation.py b/gateway/session_worker_reservation.pyindex 25cd24dacc1..c5587c50134 100644--- a/gateway/session_worker_reservation.py+++ b/gateway/session_worker_reservation.py@@ -55,3 +55,25 @@ def reserve_admission_worker(authority, *, admission_id, process, principal_id):return scope | {'epoch': authority.epoch}return authority.db._execute_write(write)+++def lose_admission_worker(authority, row, scope):+ """Revoke a private assignment and pause its FIFO; no inference replay.++ This also fences a result already in the pipe at loss/shutdown. Retention+ requires a still-started admission even when the generation has not changed.+ """+ def write(conn):+ _epoch(conn, scope['epoch'])+ current = _admission(conn, row['admission_id'])+ if (current['status'] != 'started' or current['owner_epoch'] != scope['epoch']+ or current['generation'] != scope['generation']):+ raise RuntimeStoreError('stale_generation')+ worker = conn.execute('SELECT * FROM worker_executions WHERE execution_id=?',+ (scope['execution_id'],)).fetchone()+ if worker is None or worker['generation'] != scope['generation'] or worker['owner_epoch'] != scope['epoch']:+ raise RuntimeStoreError('stale_generation')+ conn.execute("UPDATE worker_executions SET status='terminal' WHERE execution_id=?", (scope['execution_id'],))+ conn.execute("UPDATE session_admissions SET status='unknown' WHERE admission_id=?", (row['admission_id'],))+ conn.execute('UPDATE sessions SET runtime_revision=runtime_revision+1 WHERE id=?', (current['target_session_id'],))+ authority.db._execute_write(write)diff --git a/tests/gateway/test_managed_worker_fencing.py b/tests/gateway/test_managed_worker_fencing.pynew file mode 100644index 00000000000..99153aafe24--- /dev/null+++ b/tests/gateway/test_managed_worker_fencing.py@@ -0,0 +1,37 @@+"""Loss is not success; delayed parent results cannot revive an admission."""+from contextlib import closing+import subprocess+import sys+from types import SimpleNamespace++import pytest++from hermes_state import SessionDB+from hermes_state_runtime import admit_session_input, begin_runtime_epoch, claim_session_input+++def test_worker_loss_fences_same_generation_parent_result(tmp_path):+ from gateway.session_worker_reservation import reserve_admission_worker, lose_admission_worker+ from gateway.session_results import retain_result+ with closing(SessionDB(tmp_path / 'state.db')) as db:+ db.create_session('owned', 'cli')+ epoch = begin_runtime_epoch(db, instance_id='owner')+ authority = SimpleNamespace(db=db, epoch=epoch, profile_id=str(tmp_path), _require_admission_open=lambda: None)+ admit_session_input(db, epoch=epoch, principal_id='human', session_id='owned', request_id='input', payload={})+ row = claim_session_input(db, epoch=epoch, session_id='owned')+ child = subprocess.Popen([sys.executable, '-c', 'import sys; sys.stdin.read()'],+ stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)+ try:+ scope = reserve_admission_worker(authority, admission_id=row['admission_id'], process=child, principal_id='human')+ child.kill()+ child.wait(timeout=5)+ lose_admission_worker(authority, row, scope)+ with pytest.raises(Exception, match='stale_generation'):+ retain_result(db, epoch=epoch, row=row, result={'result': {'final_response': 'STALE'}, 'usage': {}})+ assert db._read_one('SELECT status FROM session_admissions')[0] == 'unknown'+ assert db._read_one('SELECT status FROM worker_executions')[0] == 'terminal'+ finally:+ child.stdin.close()+ if child.poll() is None:+ child.kill()+ child.wait(timeout=5)diff --git a/tests/gateway/test_managed_worker_launch.py b/tests/gateway/test_managed_worker_launch.pyindex cd97b1f8927..c51ab443e56 100644--- a/tests/gateway/test_managed_worker_launch.py+++ b/tests/gateway/test_managed_worker_launch.py@@ -54,7 +54,8 @@ class Model(BaseHTTPRequestHandler):@pytest.mark.linux_only-def test_ordinary_owner_launches_tool_worker_and_detach_does_not_cancel(tmp_path):[email protected]('worker_action', ['detach', 'kill'])+def test_ordinary_owner_launches_tool_worker_and_detach_does_not_cancel(tmp_path, worker_action):root = Path(__file__).resolve().parents[2]home, user = tmp_path / 'state', tmp_path / 'user'home.mkdir(mode=0o700)@@ -94,6 +95,21 @@ def test_ordinary_owner_launches_tool_worker_and_detach_does_not_cancel(tmp_pathchildren = [p for p in psutil.Process(owner.pid).children() if p.cmdline()[-2:] == ['-m', 'agent.managed_worker']]assert len(children) == 1, [(p.pid, p.cmdline()) for p in psutil.Process(owner.pid).children()]pid = children[0].pid+ if worker_action == 'kill':+ follower = await rpc(ws, 'prompt.submit', session_id=sid, input_id='follower', text='NEVER_REPLAY')+ assert 'result' in follower, follower+ children[0].kill()+ async with asyncio.timeout(10):+ while query('SELECT status FROM session_admissions WHERE request_id=?', ('managed-input',)) == [('started',)]:+ await asyncio.sleep(.05)+ assert query('SELECT request_id,status FROM session_admissions ORDER BY seq') == [+ ('managed-input', 'unknown'), ('follower', 'queued')]+ restored = await rpc(ws, 'session.resume', session_id=sid)+ assert any(p['status'] == 'unknown' for p in restored['result']['pending']), restored+ assert not query("SELECT value FROM state_meta WHERE key LIKE 'gateway.admission.result.v1.%'")+ peer.release.set()+ print(json.dumps({'owner_pid': owner.pid, 'killed_worker_pid': pid, 'outcome': 'unknown', 'follower': 'queued'}))+ return# Viewer connection is gone while the real model still holds the turn.assert psutil.Process(pid).is_running()peer.release.set()