Skip to content

The agent that grows with you

fix(managed-worker): start the Stop ack window at the first real Stop, not at hello

Tekniumc950e462f3d7
diff --git a/gateway/session_managed_worker.py b/gateway/session_managed_worker.py
index d371243acd8..9c07723da04 100644
--- a/gateway/session_managed_worker.py
+++ b/gateway/session_managed_worker.py
@@ -226,10 +226,9 @@ class ManagedWorker:
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()
+ """Seconds left of the ``ack`` window that opened at the first Stop. Pure: only
+ ``control`` stamps ``stopped_at``, so a read before any Stop (the hello) never starts
+ the window a later Stop must receive in full."""
return self.stopped_at + ack - time.monotonic()
async def next_frame(self, timeout, ack):
@@ -252,9 +251,11 @@ class ManagedWorker:
await asyncio.wait({arrived, stopper}, timeout=timeout, return_when=asyncio.FIRST_COMPLETED)
if not self._frames and not self.stop.is_set():
raise RuntimeStoreError('managed_worker_hello_timeout')
- remaining = self._stop_budget(ack)
- if not self._frames and remaining > 0:
- await asyncio.wait({arrived}, timeout=remaining)
+ if not self._frames:
+ # Only a latched Stop gets here; its window runs from the first Stop.
+ remaining = self._stop_budget(ack)
+ if remaining > 0:
+ await asyncio.wait({arrived}, timeout=remaining)
if not self._frames:
raise RuntimeStoreError('managed_worker_stopped')
return self._take()
diff --git a/tests/gateway/test_managed_worker_late_stop.py b/tests/gateway/test_managed_worker_late_stop.py
new file mode 100644
index 00000000000..5a0e2b9ff63
--- /dev/null
+++ b/tests/gateway/test_managed_worker_late_stop.py
@@ -0,0 +1,77 @@
+"""A Stop requested long after hello still receives its full acknowledgement window: only the
+first actual Stop opens the budget, and repeated Stops share that one deadline (real child)."""
+import asyncio
+import subprocess
+import sys
+import time
+
+import pytest
+
+from hermes_state_runtime import RuntimeStoreError
+
+# Harmless child: says hello, then on Stop either acknowledges (finished) or keeps chattering.
+CHILD = """import json, sys, threading, time
+chatty = sys.argv[1] == 'chatty'
+def out(frame):
+ sys.stdout.buffer.write(json.dumps(frame).encode() + b'\\n')
+ sys.stdout.buffer.flush()
+def chatter():
+ while True:
+ out({'type': 'delta', 'text': 'x'})
+ time.sleep(.05)
+out({'type': 'hello'})
+for line in sys.stdin.buffer:
+ if json.loads(line) == {'type': 'stop'}:
+ if chatty:
+ threading.Thread(target=chatter, daemon=True).start()
+ else:
+ out({'type': 'finished'})
+"""
+ACK = 0.6
+
+
+def _run(mode, supervise):
+ from gateway.session_managed_worker import HELLO_SECONDS, ManagedWorker
+ child = subprocess.Popen([sys.executable, '-c', CHILD, mode], stdin=subprocess.PIPE,
+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
+ worker = ManagedWorker(child)
+
+ async def main():
+ async with asyncio.timeout(15):
+ assert await worker.next_frame(HELLO_SECONDS, ack=0) == {'type': 'hello'}
+ worker.writer.start()
+ await asyncio.sleep(ACK + 0.4) # the turn outlives the ack interval before any Stop
+ return await supervise(worker)
+
+ try:
+ return asyncio.run(main())
+ finally:
+ worker.close()
+
+
+def test_late_stop_gets_its_full_ack_window():
+ async def supervise(worker):
+ worker.control({'type': 'stop'})
+ return await worker.next_frame(None, ack=ACK)
+
+ assert _run('ack', supervise) == {'type': 'finished'}
+
+
+def test_repeated_late_stop_shares_the_first_stops_deadline():
+ async def supervise(worker):
+ worker.control({'type': 'stop'})
+ first = time.monotonic()
+ frames = []
+ with pytest.raises(RuntimeStoreError) as stopped:
+ while True:
+ frames.append(await worker.next_frame(None, ack=ACK))
+ if len(frames) == 3:
+ worker.control({'type': 'stop'}) # must not renew the window
+ return stopped.value.reason, time.monotonic() - first, frames
+
+ reason, elapsed, frames = _run('chatty', supervise)
+ assert reason == 'managed_worker_stopped'
+ assert len(frames) >= 3, frames # the late Stop did get a live window
+ assert ACK - 0.1 < elapsed < ACK + 1.0, elapsed