Skip to content

The agent that grows with you

fix(gateway): a finished managed worker keeps its answer through a slow or failed exit

Tekniumded09df04ea9
diff --git a/gateway/session_managed_worker.py b/gateway/session_managed_worker.py
index 0769eb6f52c..a71944560d8 100644
--- a/gateway/session_managed_worker.py
+++ b/gateway/session_managed_worker.py
@@ -1,6 +1,6 @@
"""Admission-owned production exec; observers never own the worker lifetime."""
import asyncio
-from contextlib import contextmanager
+from contextlib import contextmanager, suppress
from collections import deque
from dataclasses import asdict, replace
import json
@@ -319,7 +319,9 @@ class ManagedWorker:
except subprocess.TimeoutExpired:
self._signal_worker(kill=True)
self._signal_group(kill=True)
- self.process.wait(timeout=5)
+ # Still unreaped after SIGKILL (a launcher's handle): the teardown below must still run.
+ with suppress(subprocess.TimeoutExpired):
+ self.process.wait(timeout=5)
else:
self._signal_worker(kill=True)
if self.writer.ident is not None:
@@ -512,11 +514,11 @@ async def execute_managed(authority, ref, row, policy):
await asyncio.to_thread(worker.send, {'type': 'finish'})
continue
if frame == {'type': 'finished'} and accepted is not None:
- code = await asyncio.to_thread(process.wait, 10)
- if code != 0:
- raise RuntimeStoreError('managed_worker_lost')
+ # 'finished' follows the worker's durable execution.finish: the turn is complete.
+ # A slow or non-zero interpreter exit after it is close()'s cleanup, not a loss.
+ with suppress(subprocess.TimeoutExpired):
+ await asyncio.to_thread(process.wait, 10)
# Like in-process execution, settlement belongs to the drain's stream lock.
- # The worker must acknowledge its durable finish before that boundary.
authority.pending_results[row['admission_id']] = {'result': accepted, 'usage': usage}
return accepted['final_response']
raise RuntimeStoreError('invalid_worker_frame')
diff --git a/tests/gateway/test_managed_worker_finished_exit.py b/tests/gateway/test_managed_worker_finished_exit.py
new file mode 100644
index 00000000000..cd43c8a4f0b
--- /dev/null
+++ b/tests/gateway/test_managed_worker_finished_exit.py
@@ -0,0 +1,74 @@
+"""A managed turn whose worker acknowledged its durable finish keeps its answer even when the
+worker's interpreter is slow to exit or exits non-zero afterwards (interpreter teardown,
+a lingering non-daemon thread, a Windows launcher): that is close()'s cleanup, not a lost
+execution. Real child process, real SQLite authority."""
+import asyncio
+import subprocess
+import sys
+from types import SimpleNamespace
+
+import pytest
+
+from gateway.session_contract import Principal, SessionRef
+
+CHILD = """import json, os, sys, time, psutil
+me = psutil.Process()
+out = os.fdopen(os.dup(sys.stdout.fileno()), 'wb', buffering=0)
+def send(frame):
+ out.write((json.dumps(frame) + '\\n').encode())
+send({'type': 'hello', 'pid': me.pid, 'birth': me.create_time(), 'ancestors': [p.pid for p in me.parents()[:3]]})
+for line in sys.stdin.buffer:
+ frame = json.loads(line)
+ if 'version' in frame:
+ send({'type': 'result', 'result': {'final_response': 'FINISHED_ANSWER'}})
+ elif frame == {'type': 'finish'}:
+ send({'type': 'finished'})
+ break
+if sys.argv[1] == 'nonzero':
+ os._exit(3)
+time.sleep(60) # interpreter teardown that outlives the owner's exit wait
+"""
+
+
[email protected]('exit_shape', ['nonzero', 'lingering'])
+def test_finished_worker_keeps_its_result_on_slow_or_nonzero_exit(tmp_path, monkeypatch, exit_shape):
+ from gateway import session_managed_worker as managed
+ from gateway.session_authority import LiveSession, SessionAuthority
+ from gateway.session_contract import Submission
+ from gateway.session_policy import build_policy
+ from hermes_state import SessionDB
+ from hermes_state_runtime import begin_runtime_epoch, claim_session_input
+
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ db = SessionDB(db_path=tmp_path / 'state.db')
+ db.create_session('s', source='test')
+ runner = SimpleNamespace(_draining=False, _cached_agent_for=lambda route: None,
+ _adapter_for_source=lambda source: None)
+ authority = SessionAuthority(runner, profile_id='owned', instance_id='i', db=db,
+ epoch=begin_runtime_epoch(db, instance_id='i'))
+ authority.sessions['s'] = LiveSession(SimpleNamespace(platform=None, user_id='human', chat_id='c'), 'route')
+ actor = Principal('human', 'owned', frozenset({'session:submit', 'session:control'}), 'cli')
+ ref = SessionRef('owned', 's')
+ monkeypatch.setattr(authority, '_schedule', lambda ref: None)
+ spawned = []
+
+ class Child(subprocess.Popen):
+ def __init__(self, args, **kw):
+ super().__init__([sys.executable, '-c', CHILD, exit_shape], **kw)
+ spawned.append(self)
+ monkeypatch.setattr(managed.subprocess, 'Popen', Child)
+ policy = build_policy({'cwd': str(tmp_path), 'model': 'm'}, {}, profile_terminal=False)
+
+ async def scenario():
+ await authority.submit(actor, Submission('turn', ref, {'text': 'go'}, 'queue'))
+ row = claim_session_input(db, epoch=authority.epoch, session_id='s')
+ async with asyncio.timeout(40):
+ return row, await managed.execute_managed(authority, ref, row, policy)
+ with db:
+ row, response = asyncio.run(scenario())
+ status = db._read_one('SELECT status FROM session_admissions WHERE admission_id=?', (row['admission_id'],))[0]
+ assert response == 'FINISHED_ANSWER'
+ assert authority.pending_results[row['admission_id']]['result']['final_response'] == 'FINISHED_ANSWER'
+ assert status == 'started', 'the finished turn was marked unknown instead of reaching settlement'
+ assert spawned[0].poll() is not None, "close() did not reap the worker"
diff --git a/tests/gateway/test_managed_worker_kill_escalation.py b/tests/gateway/test_managed_worker_kill_escalation.py
new file mode 100644
index 00000000000..66a51bc69b8
--- /dev/null
+++ b/tests/gateway/test_managed_worker_kill_escalation.py
@@ -0,0 +1,42 @@
+"""close() always finishes its teardown: a worker whose handle still has not exited five seconds
+after SIGKILL (a Windows launcher, an uninterruptible exit) must not raise out of close() and
+leave the pipes, reader and stderr drain open (N103). Real child process; only its handle's
+wait() reports the second timeout."""
+import subprocess
+import sys
+
+import pytest
+
+from gateway.session_managed_worker import ManagedWorker
+
+
+class _WedgedHandle(subprocess.Popen):
+ """The child ignores SIGTERM; after SIGKILL the handle keeps reporting it alive."""
+ killed = False
+
+ def kill(self):
+ self.killed = True
+ super().kill()
+
+ def wait(self, timeout=None):
+ if self.killed:
+ raise subprocess.TimeoutExpired(self.args, timeout)
+ return super().wait(timeout)
+
+
[email protected]("linux", "macos")
+def test_close_completes_when_the_post_kill_wait_times_out():
+ process = _WedgedHandle([sys.executable, '-c', 'import signal, time\n'
+ 'signal.signal(signal.SIGTERM, signal.SIG_IGN)\nprint(1, flush=True)\ntime.sleep(120)'],
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
+ close_fds=True) # no own group: the handle alone is signalled
+ try:
+ assert process.stdout.readline() == b'1\n'
+ ManagedWorker(process).close()
+ assert process.killed and process.stdin.closed and process.stdout.closed
+ finally:
+ process.killed = False
+ if process.poll() is None:
+ process.kill()
+ process.killed = False
+ subprocess.Popen.wait(process, timeout=10)