The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): shutdown drains, stops and bounds managed-worker turns
Tekniumc222074e8535
diff --git a/gateway/run_runtime.py b/gateway/run_runtime.pyindex 1ad2897c2f4..05a8e7e6fbf 100644--- a/gateway/run_runtime.py+++ b/gateway/run_runtime.py@@ -164,6 +164,56 @@ def _authority_tasks(authority):return list(dict.fromkeys(tasks))+# How long a Stopped turn gets to settle durably before its task is cancelled: a managed worker+# acknowledges Stop within STOP_ACK_SECONDS (30) or is terminated, then closed (<=10).+TURN_SETTLE_SECONDS = 45.0+++def managed_turn_count(runner):+ """Managed-worker turns across every served authority: out-of-process work that+ ``_running_agents`` never sees. A worker registers before it can be reserved, and a draining+ owner refuses the reservation, so nothing unbootstrapped can start work behind this count."""+ return sum(1 for authority in _authorities(runner)+ for worker in list(getattr(authority, '_managed_workers', {}).values()) if not worker.closed.is_set())+++def stop_authority_turns(authority):+ """Cooperative Stop for every managed turn *authority* is executing: the control a user's Stop+ sends. The worker acknowledges or is terminated within STOP_ACK_SECONDS; the admission then+ settles through its own fenced path (interrupted, or durable ``unknown``)."""+ from hermes_state_runtime import RuntimeStoreError+ signalled = 0+ for worker in list(getattr(authority, '_managed_workers', {}).values()):+ if worker.closed.is_set():+ continue+ try:+ worker.control({'type': 'stop'})+ except RuntimeStoreError as exc:+ # A full control queue: control() latched worker.stop first, and the owner's read+ # loop escalates on that latch alone (terminate after STOP_ACK_SECONDS).+ logger.debug('managed Stop not queued (%s); the latch escalates it', exc.reason)+ signalled += 1+ return signalled+++def stop_managed_turns(runner):+ """``stop_authority_turns`` across every served authority (whole-runtime shutdown)."""+ return sum(stop_authority_turns(authority) for authority in _authorities(runner))+++async def _settle_tasks(tasks, timeout):+ """Wait up to *timeout* for *tasks*; cancel the rest and give their cleanup the same bound.+ Returns the tasks that missed the first deadline."""+ if not tasks:+ return set()+ _, late = await asyncio.wait(tasks, timeout=timeout)+ for task in late:+ task.cancel()+ if late:+ await asyncio.wait(late, timeout=timeout)+ return late++async def _retire_profile_authority(authority):"""Stop profile-local services/tasks before its ownership is released."""from gateway.session_cron import unbind_owner@@ -323,10 +373,17 @@ async def drain_gateway_runtime(runner):async def settle_gateway_runtime(runner):- """Keep authority tasks alive until their last durable settlement write."""- tasks = [task for authority in _authorities(runner) for task in _authority_tasks(authority)]- if tasks:- await asyncio.gather(*tasks, return_exceptions=True)+ """Keep authority tasks alive until their last durable settlement write, within a bound.++ A managed turn still running here gets its Stop first (its worker acknowledges or is+ terminated, and the admission settles interrupted or ``unknown``); a task that still misses+ TURN_SETTLE_SECONDS is cancelled, which leaves its admission for recovery, never settled."""+ authorities = _authorities(runner)+ stop_managed_turns(runner)+ tasks = [task for authority in authorities for task in _authority_tasks(authority)]+ late = await _settle_tasks(tasks, TURN_SETTLE_SECONDS)+ if late:+ logger.warning('%d authority task(s) did not settle within %.0fs; cancelled', len(late), TURN_SETTLE_SECONDS)# Sockets closed in drain_gateway_runtime; work settled above. ACP has no per-session destroy,# so the stop is the end of every ACP session nobody is viewing (#118216).from gateway.session_acp_lifecycle import end_idle_acp_sessionsdiff --git a/gateway/run_shutdown.py b/gateway/run_shutdown.pyindex c9d5418c0bf..cb3d2a3a478 100644--- a/gateway/run_shutdown.py+++ b/gateway/run_shutdown.py@@ -28,6 +28,7 @@ from gateway.restart import (effective_stop_drain_timeout, effective_stop_watchdog_delay, resolve_cron_drain_budget)from gateway.run_common import _UNSET+from gateway.run_runtime import managed_turn_count, stop_managed_turnsfrom gateway.shutdown_watchdog import arm_shutdown_watchdog, resolve_shutdown_watchdog_delay# Log-record parity with the origin module.@@ -192,6 +193,7 @@ class GatewayShutdownMixin:"""All agent work the gateway must expose and drain as one total."""return (self._running_agent_count()+ + managed_turn_count(self)+ self._active_cron_job_count()+ self._active_api_run_count()+ self._active_deferred_agent_worker_count()@@ -799,9 +801,9 @@ class GatewayShutdownMixin:# Drain / interruptdef _drain_work_counts(self) -> tuple:- """``(agents, cron, api, deferred)`` — the four sources the drain waits on."""+ """``(agents, cron, api, deferred)`` the drain waits on; a managed-worker turn is a chat turn."""return (- self._running_agent_count(), self._active_cron_job_count(),+ self._running_agent_count() + managed_turn_count(self), self._active_cron_job_count(),self._active_api_run_count(), self._active_deferred_agent_worker_count(),)@@ -822,9 +824,8 @@ class GatewayShutdownMixin:last_counts, last_status_at = counts, now# Cron/API/deferred work lives outside ``_running_agents``; fold it in or it is killed unwarned.- _cron0, _api0, _deferred0 = last_counts[1:]_maybe_update_status(force=True)- if not self._running_agents and not (_cron0 or _api0 or _deferred0):+ if not self._running_agents and not any(last_counts):return snapshot, False# Cron and api_server runs ride the cron floor: a chat turn is announced+resumable, but a killed# cron run is a permanent failure and a killed /v1 run fails a caller blocked on its result.@@ -854,11 +855,11 @@ class GatewayShutdownMixin:with _log_suppressed(logging.DEBUG, "Failed interrupting agent during shutdown: %s"):request_hard_interrupt(agent, reason, tool_reason=_INTERRUPT_TOOL_REASON_GATEWAY_SHUTDOWN)logger.debug("Interrupted running agent for session %s during shutdown", session_key)- # API-server / desk turns are adapter-owned and never enter _running_agents, so the loop above- # cannot see them even though _drain_active_agents() waited for them.+ # API-server / desk / managed-worker turns never enter _running_agents: the drain waited on them.for count, what in ((self._interrupt_api_server_runs(reason), "api_server run(s)"),(self._interrupt_deferred_agent_workers(reason), "deferred agent worker(s)"),+ (stop_managed_turns(self), "managed-worker turn(s)"),):if count:logger.debug("Interrupted %d %s during shutdown", count, what)@@ -1590,6 +1591,7 @@ class GatewayShutdownMixin:"""non_cron = (self._running_agent_count()+ + managed_turn_count(self)+ self._active_api_run_count()+ self._active_deferred_agent_worker_count())@@ -1603,7 +1605,7 @@ class GatewayShutdownMixin:(``hermes update``, ``hermes gateway status``) can name it instead of printing a bare count.``kind`` ∈ ``chat`` (session turn), ``cron`` (job id + external worker pid when the run was- handed to a restart-safe scope), ``api`` / ``deferred`` (count only — those sources expose+ handed to a restart-safe scope), ``managed`` / ``api`` / ``deferred`` (count only — those sources exposeno identity). Best-effort: a source that can't be read is omitted, never raises."""from gateway.run import _AGENT_PENDING_SENTINEL@@ -1633,7 +1635,8 @@ class GatewayShutdownMixin:"pid": job["worker_pid"] or os.getpid(), "external": bool(job["worker_pid"]),"wedged": job["job_id"] in wedged,"restart_safe": bool(job.get("restart_safe"))})- for kind, count in (("api", self._active_api_run_count()), ("deferred", self._active_deferred_agent_worker_count())):+ for kind, count in (("managed", managed_turn_count(self)), ("api", self._active_api_run_count()),+ ("deferred", self._active_deferred_agent_worker_count())):units.extend({"kind": kind, "pid": os.getpid()} for _ in range(count))return units@@ -1952,7 +1955,7 @@ class GatewayShutdownMixin:logger.info("Shutdown phase: allowing %.1fs for interrupted agents to unwind", interrupt_grace_timeout)def _work_live() -> bool:- return bool(self._running_agents or self._active_api_run_count() or ctx.deferred_count())+ return bool(self._running_agents or managed_turn_count(self) or self._active_api_run_count() or ctx.deferred_count())# Wait on API-server work too, or an API turn's tool subprocesses are killed before it unwinds.while _work_live() and loop.time() < interrupt_deadline:diff --git a/tests/gateway/test_managed_turn_shutdown_drain.py b/tests/gateway/test_managed_turn_shutdown_drain.pynew file mode 100644index 00000000000..5ddc38db6b4--- /dev/null+++ b/tests/gateway/test_managed_turn_shutdown_drain.py@@ -0,0 +1,70 @@+"""R10: managed-worker turns are part of the bounded shutdown drain.++They run in child processes, outside ``_running_agents``: the drain must count them, the timed-out+path must send them the same Stop a user's Stop sends, and the final settlement wait must stay+bounded while keeping the admission's own fenced settlement (real subprocess workers)."""+import asyncio+import subprocess+import sys+from types import SimpleNamespace++import pytest++from gateway.session_contract import SessionRef+from tests.gateway.restart_test_helpers import make_restart_runner++[email protected]("linux")+async def test_drain_counts_managed_turns_and_the_timeout_path_stops_them(tmp_path):+ from gateway.session_managed_worker import ManagedWorker+ seen = tmp_path / 'controls'+ child = subprocess.Popen([sys.executable, '-c', 'import sys; open(sys.argv[1], "wb").write(sys.stdin.buffer.readline())',+ str(seen)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)+ worker = ManagedWorker(child)+ worker.writer.start()+ runner, _adapter = make_restart_runner()+ runner.session_authority = SimpleNamespace(sessions={}, _managed_workers={'s': worker})+ try:+ assert runner._active_work_count() == 1+ _snapshot, timed_out = await runner._drain_active_agents(0)+ assert timed_out is True+ runner._interrupt_running_agents('Gateway shutting down')+ await asyncio.to_thread(child.wait, 10)+ assert seen.read_bytes() == b'{"type":"stop"}\n'+ finally:+ await asyncio.to_thread(worker.close)+ assert runner._active_work_count() == 0++[email protected]("linux")+def test_settlement_stops_a_silent_managed_worker_instead_of_waiting_unbounded(monkeypatch):+ """The reviewer's probe: a started managed admission whose child never answers. Settlement sends+ Stop, the turn settles interrupted through its own path, and nothing waits on HELLO_SECONDS."""+ from gateway import run_runtime+ from gateway import session_managed_worker as managed+ original = subprocess.Popen++ def silent_child(args, **kwargs):+ return original([sys.executable, '-c', 'import time\nwhile True: time.sleep(1)'], **kwargs)+ monkeypatch.setattr(managed.subprocess, 'Popen', silent_child)+ ref = SessionRef('profile', 's')+ live = SimpleNamespace(task=None)+ authority = SimpleNamespace(profile_id='profile', pending_results={}, waiters={}, sessions={'s': live},+ check_approval_generation=lambda *a: None)+ runner = SimpleNamespace(session_authority=authority)+ row = {'admission_id': 'adm', 'principal_id': 'owner', 'generation': 3, 'payload': {'text': 'go'}}++ async def scenario():+ live.task = asyncio.create_task(managed.execute_managed(authority, ref, row, policy=None))+ async with asyncio.timeout(10):+ while 's' not in getattr(authority, '_managed_workers', {}):+ await asyncio.sleep(.01)+ async with asyncio.timeout(15):+ await run_runtime.settle_gateway_runtime(runner)+ return live.task++ task = asyncio.run(scenario())+ assert task.done() and not task.cancelled() and task.result() == ''+ assert authority.pending_results['adm']['result']['interrupted'] is True+ assert authority._managed_workers == {}