The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): one Stop deadline bounds managed-worker supervision, not the silence between frames
Teknium0de046dd4e38
diff --git a/gateway/session_managed_worker.py b/gateway/session_managed_worker.pyindex d17237d36c6..9ec8753ee1a 100644--- a/gateway/session_managed_worker.py+++ b/gateway/session_managed_worker.py@@ -10,6 +10,7 @@ from types import SimpleNamespacefrom pathlib import Pathimport subprocessimport sys+import timefrom agent.managed_worker import accept_result, encode_frame, read_framefrom gateway.session_worker_reservation import reserve_admission_worker@@ -115,6 +116,9 @@ class ManagedWorker:# Latched the moment Stop is admitted, before any pipe write: the owner's read loop# supervises it even while the child has not yet said hello or read its bootstrap.self.stop = asyncio.Event()+ # Monotonic instant of the FIRST Stop: one acknowledgment budget runs from here, never+ # renewed by the child's later output or by a repeated Stop.+ self.stopped_at = Noneself.writer = threading.Thread(target=self._write_controls, name='managed-control-writer', daemon=True)def _write_controls(self):@@ -132,25 +136,40 @@ class ManagedWorker:if self.closed.is_set():raise RuntimeStoreError('managed_worker_lost')if frame == {'type': 'stop'}:+ if self.stopped_at is None:+ self.stopped_at = time.monotonic()self.stop.set()try:self.commands.put_nowait(frame)except queue.Full as exc:raise RuntimeStoreError('worker_control_backpressure') from exc+ def _stop_budget(self, ack):+ """Seconds left of the ``ack`` window that opened at the first Stop (zero before the+ child can receive controls)."""+ if self.stopped_at is None:+ self.stopped_at = time.monotonic()+ return self.stopped_at + ack - time.monotonic()+async def next_frame(self, timeout, ack):- """Read one frame. A requested Stop bounds the wait to ``ack`` seconds (zero before the- child can receive controls) and, unanswered, escalates instead of leaving the turn- started behind a silent-but-alive child."""+ """Read one frame. A requested Stop bounds supervision to ``ack`` seconds TOTAL from the+ first Stop: a child that keeps emitting valid frames is escalated on the same deadline as a+ silent one, instead of leaving the turn started behind it."""reader = asyncio.ensure_future(asyncio.to_thread(read_frame, self.process.stdout))stopper = asyncio.ensure_future(self.stop.wait())try:- done, _ = await asyncio.wait({reader, stopper}, timeout=timeout, return_when=asyncio.FIRST_COMPLETED)- if reader not in done and stopper in done and ack:- done, _ = await asyncio.wait({reader}, timeout=ack)- if reader in done:- return reader.result()- raise RuntimeStoreError('managed_worker_stopped' if self.stop.is_set() else 'managed_worker_hello_timeout')+ if not self.stop.is_set():+ done, _ = await asyncio.wait({reader, stopper}, timeout=timeout, return_when=asyncio.FIRST_COMPLETED)+ if reader in done:+ return reader.result()+ if not self.stop.is_set():+ raise RuntimeStoreError('managed_worker_hello_timeout')+ remaining = self._stop_budget(ack)+ if remaining > 0:+ done, _ = await asyncio.wait({reader}, timeout=remaining)+ if reader in done:+ return reader.result()+ raise RuntimeStoreError('managed_worker_stopped')finally:stopper.cancel()reader.cancel()diff --git a/tests/gateway/test_managed_worker_stop_deadline.py b/tests/gateway/test_managed_worker_stop_deadline.pynew file mode 100644index 00000000000..9614ab0c32a--- /dev/null+++ b/tests/gateway/test_managed_worker_stop_deadline.py@@ -0,0 +1,53 @@+"""Stop bounds managed-worker supervision by ONE deadline from the first Stop: a child that keeps+emitting valid frames after Stop is escalated on the same budget as a silent one (real child)."""+import asyncio+import subprocess+import sys+import time++import pytest++from hermes_state_runtime import RuntimeStoreError++# Harmless child: on Stop it keeps streaming valid deltas and never sends its result.+CHATTY = """import json, sys, threading, time+def chatter():+ while True:+ sys.stdout.buffer.write(json.dumps({'type': 'delta', 'text': 'x'}).encode() + b'\\n')+ sys.stdout.buffer.flush()+ time.sleep(.05)+for line in sys.stdin.buffer:+ if json.loads(line) == {'type': 'stop'}:+ threading.Thread(target=chatter, daemon=True).start()+"""++[email protected]("linux")+def test_valid_output_after_stop_does_not_renew_the_ack_budget():+ from gateway.session_managed_worker import ManagedWorker+ child = subprocess.Popen([sys.executable, '-c', CHATTY], stdin=subprocess.PIPE,+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)+ worker = ManagedWorker(child)+ worker.writer.start()+ ack = 1.5++ async def supervise():+ frames = []+ worker.control({'type': 'stop'})+ started = time.monotonic()+ async with asyncio.timeout(10):+ with pytest.raises(RuntimeStoreError) as stopped:+ while True:+ frames.append(await worker.next_frame(None, ack=ack))+ if len(frames) == 5:+ worker.control({'type': 'stop'}) # a repeated Stop must not extend it either+ return stopped.value.reason, time.monotonic() - started, frames++ try:+ reason, elapsed, frames = asyncio.run(supervise())+ finally:+ worker.close()+ assert reason == 'managed_worker_stopped'+ assert len(frames) >= 5 and all(f == {'type': 'delta', 'text': 'x'} for f in frames)+ assert elapsed < ack + 1.0, elapsed+ assert child.poll() is not None