The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(worker): retain persistence and ownership through physical shutdown
David Dudok de Wite32a886e1d9d
diff --git a/agent/managed_worker.py b/agent/managed_worker.pyindex fdbd4cfd07c..2c4916a1e40 100644--- a/agent/managed_worker.py+++ b/agent/managed_worker.py@@ -30,7 +30,8 @@ BOOTSTRAP_FIELDS = {'version', 'home', 'scope', 'policy', 'api_key', 'text', 'roRESULT_FIELDS = ('final_response', 'failed', 'interrupted', 'completed', 'partial', 'error', 'turn_exit_reason','api_calls', 'model', 'provider', 'prompt_tokens', 'completion_tokens', 'total_tokens','cache_read_tokens', 'cache_write_tokens', 'reasoning_tokens',- 'estimated_cost_usd', 'cost_status', 'cost_source', 'service_tier')+ 'estimated_cost_usd', 'cost_status', 'cost_source', 'service_tier', 'failure_reason',+ 'session_id', 'requested_model', 'served_model', '_turn_input_tokens', '_turn_output_tokens')def result_frame(result):@@ -47,12 +48,16 @@ def accept_result(result):for key, value in result.items() if key != 'final_response')):raise ValueError('invalid_worker_result')accepted = dict(result)+ turn_in, turn_out = accepted.pop('_turn_input_tokens', None), accepted.pop('_turn_output_tokens', None)+ if any(value is not None and (type(value) is not int or value < 0) for value in (turn_in, turn_out)):+ raise ValueError('invalid_worker_result')incoming, outgoing = accepted.pop('prompt_tokens', None), accepted.pop('completion_tokens', None)if incoming is None and outgoing is None:return accepted, {}- usage = {'input_tokens': incoming or 0, 'output_tokens': outgoing or 0}+ usage = {'input_tokens': incoming or 0 if turn_in is None else turn_in,+ 'output_tokens': outgoing or 0 if turn_out is None else turn_out}usage['total_tokens'] = usage['input_tokens'] + usage['output_tokens']- accepted.update(input_tokens=usage['input_tokens'], output_tokens=usage['output_tokens'])+ accepted.update(input_tokens=incoming or 0, output_tokens=outgoing or 0)return accepted, usage@@ -260,6 +265,10 @@ def tool_frame(call_id, name, args, *result):from agent.display import _detect_tool_failureframe['result'] = result[0] if isinstance(result[0], str) else str(result[0])frame['is_error'] = bool(_detect_tool_failure(frame['name'], result[0])[0])+ from gateway.session_tool_events import bounded_args, bounded_result+ frame['args'] = bounded_args(frame['args'])+ if result:+ frame['result'] = bounded_result(result[0], frame['is_error'])return json.loads(json.dumps(frame, default=str))@@ -320,7 +329,11 @@ def execute(frame, channel):if skipped:raise ValueError('managed_attachment_unavailable')frame = {**frame, 'text': content}+ before = (getattr(agent, 'session_prompt_tokens', 0) or 0,+ getattr(agent, 'session_completion_tokens', 0) or 0)result = run_worker_turns(agent, frame, history)+ result['_turn_input_tokens'] = max(0, (getattr(agent, 'session_prompt_tokens', 0) or 0) - before[0])+ result['_turn_output_tokens'] = max(0, (getattr(agent, 'session_completion_tokens', 0) or 0) - before[1])retire_agent(agent)agent = None# The auto-title thread bills through this store from a daemon thread; a title landingdiff --git a/agent/runtime_session_store.py b/agent/runtime_session_store.pyindex 0a665e02da7..db913e9043b 100644--- a/agent/runtime_session_store.py+++ b/agent/runtime_session_store.py@@ -49,6 +49,7 @@ class WorkerRPC:def __init__(self, home):self.home = Path(home).resolve()self.lock = threading.Lock()+ self.endpoint = Nonedef __call__(self, method, **params):from hermes_cli.gateway_client import _session_ticket@@ -64,13 +65,15 @@ class WorkerRPC:# A served secondary has no socket; its multiplexer's descriptor names it.from hermes_cli.gateway_runtime import discover_gateway_endpointdiscovery = discover_gateway_endpoint(self.home, timeout=5)- if discovery.state != 'ready' or discovery.endpoint is None:+ if discovery.state == 'ready' and discovery.endpoint is not None:+ self.endpoint = discovery.endpoint+ elif discovery.state != 'draining' or self.endpoint is None:raise WorkerPersistenceError('owner_unavailable')from hermes_cli.gateway_runtime import control_home_for- descriptor = query_identify(control_home_for(self.home, discovery.endpoint), timeout=5)+ endpoint = self.endpoint+ descriptor = query_identify(control_home_for(self.home, endpoint), timeout=5)if descriptor.get('pid') == os.getpid():raise WorkerPersistenceError('synchronous_self_rpc')- endpoint = discovery.endpointticket = _session_ticket(self.home, endpoint,purpose='interactive' if method == 'worker.register' else 'worker-adoption')url = endpoint.api_origin.replace('https:', 'wss:').replace('http:', 'ws:') + '/api/ws'@@ -138,6 +141,8 @@ class RuntimeSessionStore(RuntimeSessionCompressionMixin, RuntimeSessionLifecyclelse:self.journal = {'scope': self.scope, 'next_sequence': 1, 'pending': []}self._save(self.journal)+ if self.journal['pending']:+ self.retry_pending()if is_worker_process():from tools.async_delegation_worker import bind_worker_delegation_storebind_worker_delegation_store(self)diff --git a/gateway/run_api.py b/gateway/run_api.pyindex c671a1ce1fb..84860baa4ac 100644--- a/gateway/run_api.py+++ b/gateway/run_api.py@@ -110,7 +110,10 @@ class GatewayRuntimeAPI:descriptor = getattr(self.runner, 'session_runtime_descriptor', None)if scope['type'] not in {'http', 'websocket'} or descriptor is None:return await self.app(scope, receive, send)- if descriptor['state'] != 'ready' or self.runner._draining:+ draining_socket = (descriptor['state'] in {'ready', 'draining'}+ and (self.runner._draining or descriptor['state'] == 'draining')+ and scope['type'] == 'websocket' and scope['path'] == '/api/ws')+ if (descriptor['state'] != 'ready' or self.runner._draining) and not draining_socket:if scope['type'] == 'websocket':await send({'type': 'websocket.close', 'code': 1013})else:@@ -124,10 +127,11 @@ class GatewayRuntimeAPI:if scope['type'] != 'websocket' or scope['path'] != '/api/ws':return await self.app(scope, receive, send)original_receive = receive+ allow_draining = Falseasync def receive_admitted():message = await original_receive()- if descriptor['state'] != 'ready' or self.runner._draining:+ if (descriptor['state'] != 'ready' or self.runner._draining) and not allow_draining:return {'type': 'websocket.disconnect', 'code': 1013}return message@@ -140,6 +144,9 @@ class GatewayRuntimeAPI:ws = WebSocket(scope, receive, send)ticket, reason = _gateway_ws_ticket_from_subprotocol(ws)if reason == 'none' or ws.headers.get('origin'):+ if draining_socket:+ await ws.close(code=1013)+ returnreturn await self.app(scope, receive, send)from hermes_cli import web_server as webif (reason != 'ok' or not web._DASHBOARD_EMBEDDED_CHAT_ENABLED@@ -156,7 +163,14 @@ class GatewayRuntimeAPI:grant = self.runner.session_ticket_store.redeem(ticket, profile_id=None, purpose='worker-adoption')except PermissionError:# Browser/OAuth tickets have a separate issuer.+ if draining_socket:+ await ws.close(code=1013)+ returnreturn await self.app(scope, receive, send)+ allow_draining = not operator+ if (descriptor['state'] != 'ready' or self.runner._draining) and not allow_draining:+ await ws.close(code=1013)+ returnfrom gateway.session_authorities import authority_for_profile_idauthority = authority_for_profile_id(self.runner, grant['profile_id'])if authority is None:diff --git a/gateway/run_profile_reconcile.py b/gateway/run_profile_reconcile.pyindex 3a5c38dab24..9de5da59033 100644--- a/gateway/run_profile_reconcile.py+++ b/gateway/run_profile_reconcile.py@@ -328,6 +328,10 @@ class GatewayProfileReconcileMixin:profile's). Secrets are not re-hydrated: teardown must not block the loop on a source fetch."""from gateway.run import _profile_runtime_scope, _write_runtime_status_quiet+ from gateway.run_runtime import release_profile_home, unserve_profile_runtime+ if getattr(self, 'session_authorities', None) is not None:+ if not await unserve_profile_runtime(self, home):+ raise TimeoutError('Profile workers did not stop; ownership retained')pending = (getattr(self, "_profile_failed_platforms", None) or {}).pop(name, None) or {}tasks = [t for t in pending.values() if isinstance(t, asyncio.Task) and not t.done()]for task in tasks:@@ -357,15 +361,6 @@ class GatewayProfileReconcileMixin:self._evict_cached_agent(key)# Its session authority and reservation go before the store handles: the authority owns the# state.db writer, and the next restart must not try to reserve a home that no longer exists.- from gateway.run_runtime import release_profile_home, unserve_profile_runtime- retired = True- if getattr(self, "session_authorities", None) is not None:- with _log_suppressed(logging.WARNING, "session authority retirement failed for %s", name, exc_info=True):- retired = await unserve_profile_runtime(self, home)- if not retired:- # A turn outlived its Stop: its thread may still write this home, so keep the- # gateway.lock and store handles (no replacement owner) until this process exits.- returnrelease_profile_home(self, home)with _log_suppressed(logging.DEBUG, "profile handle release failed", exc_info=True):from hermes_state_registry import close_all_underdiff --git a/gateway/run_runtime.py b/gateway/run_runtime.pyindex 25a46720400..d785e4c55a5 100644--- a/gateway/run_runtime.py+++ b/gateway/run_runtime.py@@ -150,6 +150,9 @@ def release_profile_home(runner, home):"""Shrink the reservation by one profile (deleted, or parked because it cannot be served)."""from gateway.runtime_ownership import process_ownershiphome = Path(home).resolve()+ registry = getattr(runner, 'session_authorities', None)+ if registry is not None and registry.for_home(home) is not None:+ raise RuntimeError('Profile authority must retire before ownership is released')reserved = getattr(runner.config, '_runtime_profile_homes', None)if reserved is not None:runner.config._runtime_profile_homes = tuple(@@ -164,17 +167,15 @@ 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+# How long a Stopped turn gets to settle durably before shutdown refuses to release ownership: a managed worker# acknowledges Stop within STOP_ACK_SECONDS (30) or is terminated, then closed (<=10).TURN_SETTLE_SECONDS = 45.0def 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())+ """Unmapped claims, managed workers and owner mutations across the served authorities."""+ from gateway.session_runtime_workers import uncounted_runtime_work+ return uncounted_runtime_work(runner)def stop_authority_turns(authority, *, in_process=False):@@ -186,7 +187,7 @@ def stop_authority_turns(authority, *, in_process=False):signalled = 0workers = getattr(authority, '_managed_workers', {})for worker in list(workers.values()):- if worker.closed.is_set():+ if worker.closed.is_set() or (getattr(worker, 'stop', None) is not None and worker.stop.is_set()):continuetry:worker.control({'type': 'stop'})@@ -218,19 +219,6 @@ def stop_managed_turns(runner):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 and turns before its ownership is released.@@ -239,28 +227,25 @@ async def _retire_profile_authority(authority):admission settled). False when a turn misses TURN_SETTLE_SECONDS: its thread may still call toolsand write history, so the caller must keep the profile's reservation and store handles."""from gateway.session_cron import unbind_owner-+ from gateway.session_runtime_workers import join_authority_work+ authority.retiring = Trueservice = getattr(authority, 'hosted_room_service', None)if service is not None:- await asyncio.to_thread(service.stop, timeout=5)- authority.retiring = True- stop_authority_turns(authority, in_process=True)- # A claim is stamped in the same synchronous step that passed _require_admission_open, so from- # here a session is either executing a stamped turn (join it) or idle/preclaim (nothing ran).- running = [live for live in authority.sessions.values() if live.task is not None]- turns = [live.task for live in running if live.event_stream.execution.get('execution_generation') is not None]- late = await _settle_tasks(turns, TURN_SETTLE_SECONDS)+ if await asyncio.to_thread(service.stop, timeout=5) is False:+ return False+ try:+ await join_authority_work(authority, TURN_SETTLE_SECONDS)+ except TimeoutError:+ logger.error('Profile %s workers did not stop; ownership retained', authority.profile_id)+ return False# Idle drains and receipt watchers wait on admissions this profile will no longer run.- rest = [task for task in _authority_tasks(authority) if task not in turns]+ rest = _authority_tasks(authority)for task in rest:task.cancel()if rest:await asyncio.gather(*rest, return_exceptions=True)unbind_owner(authority)- if late:- logger.error('Profile %s: %d turn(s) still running %.0fs after Stop; keeping its reservation',- authority.profile_id, len(late), TURN_SETTLE_SECONDS)- return not late+ return Trueasync def serve_profile_runtime(runner, name, home):@@ -285,8 +270,8 @@ async def serve_profile_runtime(runner, name, home):if getattr(runner, 'session_control_server', None) is not None:await _ensure_hosted_service(runner, authority)except BaseException:- registry.remove(home)- await _retire_profile_authority(authority)+ if await _retire_profile_authority(authority):+ registry.remove(home)raise_publish_served_set(runner)start_ready_hosted_services(runner)@@ -299,10 +284,13 @@ async def unserve_profile_runtime(runner, home):including for a profile this process never served."""home = await asyncio.to_thread(Path(home).resolve)registry = runner.session_authorities- authority = registry.remove(home) if home in registry else None+ authority = registry.for_home(home)if authority is None:return Trueretired = await _retire_profile_authority(authority)+ if not retired:+ return False+ registry.remove(home)_publish_served_set(runner)return retired@@ -385,7 +373,6 @@ async def wait_gateway_runtime(runner):async def drain_gateway_runtime(runner):"""Withdraw admission before any await; close sockets before DB teardown."""- from gateway.run_api import stop_gateway_apidescriptor = getattr(runner, 'session_runtime_descriptor', None)if descriptor is None:return@@ -400,12 +387,6 @@ async def drain_gateway_runtime(runner):for adapters in getattr(runner, '_profile_adapters', {}).values():for adapter in adapters.values():adapter.set_message_handler(None)- store = getattr(runner, 'session_ticket_store', None)- if store is not None:- store.revoke()- handle = getattr(runner, 'session_api', None)- if handle is not None:- await stop_gateway_api(handle)async def settle_gateway_runtime(runner):@@ -413,14 +394,21 @@ async def settle_gateway_runtime(runner):A managed turn still running here gets its Stop first (its worker acknowledges or isterminated, 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."""+ TURN_SETTLE_SECONDS retains ownership until its writer stops."""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,+ if tasks:+ done, pending = await asyncio.wait(tasks, timeout=TURN_SETTLE_SECONDS)+ for task in done:+ if not task.cancelled():+ task.exception()+ if pending:+ raise TimeoutError('Runtime workers did not settle; ownership retained')+ from gateway.session_runtime_workers import join_authority_work+ for authority in authorities:+ await join_authority_work(authority, 0)+ # 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_sessionsfor authority in _authorities(runner):@@ -431,3 +419,10 @@ async def settle_gateway_runtime(runner):import logginglogging.getLogger(__name__).warning('ACP sessions of %s not ended at shutdown',getattr(authority, 'profile_id', '?'), exc_info=True)+ from gateway.run_api import stop_gateway_api+ store = getattr(runner, 'session_ticket_store', None)+ if store is not None:+ store.revoke()+ handle = getattr(runner, 'session_api', None)+ if handle is not None:+ await stop_gateway_api(handle)diff --git a/gateway/run_turn.py b/gateway/run_turn.pyindex e8bd3d2591a..35cbd6a6886 100644--- a/gateway/run_turn.py+++ b/gateway/run_turn.py@@ -1548,9 +1548,8 @@ class GatewayTurnMixin(GatewayTurnPrepareMixin, GatewayTurnHygieneMixin, Gatewayname=f"gateway-turn-watchdog-{_turn_task_id[:12]}",daemon=True,).start()- worker.executor_task = asyncio.ensure_future(- self._run_in_executor_with_context(_run_sync_with_timeout_lifecycle)- )+ from gateway.session_runtime_workers import start_turn_worker+ start_turn_worker(self, worker, agent_holder, _run_sync_with_timeout_lifecycle)return worker@staticmethoddiff --git a/gateway/run_turn_progress.py b/gateway/run_turn_progress.pyindex 86f3be94994..980bee51fcb 100644--- a/gateway/run_turn_progress.py+++ b/gateway/run_turn_progress.py@@ -37,18 +37,23 @@ def _tool_lifecycle_payload(call_id, tool_name, args) -> dict:from agent.display import build_tool_preview, tool_labels_for_callname = str(tool_name or "tool")args = args if isinstance(args, dict) else {}+ from gateway.session_tool_events import bounded_argspayload = {"tool_id": str(call_id or ""), "name": name, "context": build_tool_preview(name, args, max_len=80) or "",- "tool_call_id": str(call_id or ""), "tool_name": name, "args": args}+ "tool_call_id": str(call_id or ""), "tool_name": name, "args": bounded_args(args)}if labels := [label.as_payload() for label in tool_labels_for_call(name, args)]:payload["labels"] = labelsreturn payload-def _tool_complete_payload(call_id, tool_name, args, result, *, is_error, verbose) -> dict:+def _tool_complete_payload(call_id, tool_name, args, result, *, is_error=None, verbose=False) -> dict:"""``tool.complete`` as every viewer reads it: the start contract plus the executor's verdict andthe result (ACP renders paths/output and failure from it), and ``result_text`` under /verbose."""+ from gateway.session_tool_events import bounded_result+ if is_error is None:+ from agent.display import _detect_tool_failure+ is_error = _detect_tool_failure(tool_name, result)[0]payload = {**_tool_lifecycle_payload(call_id, tool_name, args), "is_error": bool(is_error),- "result": result if isinstance(result, str) else str(result)}+ "result": bounded_result(result, is_error)}if verbose:from tui_gateway.tool_progress import _tool_result_textpayload["result_text"] = _tool_result_text(result)diff --git a/gateway/session_managed_worker.py b/gateway/session_managed_worker.pyindex 81102f6f72d..c4d23321f90 100644--- a/gateway/session_managed_worker.py+++ b/gateway/session_managed_worker.py@@ -281,7 +281,8 @@ async def execute_managed(authority, ref, row, policy):from gateway.run_turn_progress import publish_worker_tool_eventenv = await asyncio.to_thread(_worker_env, authority)cwd = (await asyncio.to_thread(Path(__file__).resolve)).parents[1]- process = await asyncio.to_thread(subprocess.Popen, [sys.executable, '-m', 'agent.managed_worker'],+ from gateway.session_worker_spawn import acquire_process+ process = await acquire_process(subprocess.Popen, [sys.executable, '-m', 'agent.managed_worker'],cwd=cwd, stdin=subprocess.PIPE, env=env,stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, close_fds=True)worker = ManagedWorker(process)diff --git a/gateway/session_runtime_workers.py b/gateway/session_runtime_workers.pynew file mode 100644index 00000000000..e6f7b081d31--- /dev/null+++ b/gateway/session_runtime_workers.py@@ -0,0 +1,74 @@+"""Physical worker liveness and cooperative Stop across every served authority."""+import asyncio++from gateway.session_authorities import all_authorities+++def executing_sessions(authority):+ for sid, live in getattr(authority, 'sessions', {}).items():+ execution = getattr(getattr(live, 'event_stream', None), 'execution', None) or {}+ task = live.task+ if execution.get('execution_generation') is not None and task is not None and not task.done():+ yield sid, live, execution['execution_generation']+++def uncounted_runtime_work(runner):+ """Count claims absent from the ordinary agent map, including pre-bootstrap managed turns."""+ running = getattr(runner, '_running_agents', {})+ authorities = all_authorities(runner)+ managed = sum(not worker.closed.is_set() for authority in authorities+ for worker in getattr(authority, '_managed_workers', {}).values())+ return (managed + sum(live.route not in running and sid not in getattr(authority, '_managed_workers', {})+ for authority in authorities for sid, live, _ in executing_sessions(authority)))+++def start_turn_worker(runner, worker, agent_holder, run_sync):+ authority = track_turn_worker(runner, worker, agent_holder)+ worker.executor_task = asyncio.ensure_future(runner._run_in_executor_with_context(run_sync))+ if authority is not None:+ # Normal settlement releases the retained agent promptly. A cancelled asyncio waiter is+ # not physical completion; leave that entry until worker_done proves the thread exited.+ worker.executor_task.add_done_callback(lambda _: list(physical_workers(authority)))+++def track_turn_worker(runner, worker, agent_holder):+ from gateway.session_authorities import active_authority+ authority = active_authority(runner)+ if authority is not None:+ workers = getattr(authority, '_turn_workers', None)+ if workers is None:+ workers = authority._turn_workers = {}+ list(physical_workers(authority))+ workers[id(worker)] = (worker, agent_holder)+ return authority+++def physical_workers(authority):+ workers = getattr(authority, '_turn_workers', {})+ for key, (worker, holder) in list(workers.items()):+ if worker.worker_done.is_set():+ del workers[key]+ else:+ yield worker, holder+++def stop_authority_work(authority):+ from gateway.run_runtime import stop_authority_turns+ from agent.interrupt_compat import request_hard_interrupt+ stop_authority_turns(authority, in_process=True)+ for _, holder in physical_workers(authority):+ if holder and holder[0] is not None:+ request_hard_interrupt(holder[0], 'Profile runtime is stopping')+ for cancel in getattr(authority, '_cron_cancellations', {}).values():+ cancel.set()+++async def join_authority_work(authority, timeout):+ deadline = asyncio.get_running_loop().time() + timeout+ while True:+ stop_authority_work(authority)+ if not list(physical_workers(authority)) and not list(executing_sessions(authority)):+ return+ if asyncio.get_running_loop().time() >= deadline:+ raise TimeoutError('Profile workers did not stop; ownership retained')+ await asyncio.sleep(.05)diff --git a/gateway/session_tool_events.py b/gateway/session_tool_events.pynew file mode 100644index 00000000000..93cddb4112e--- /dev/null+++ b/gateway/session_tool_events.py@@ -0,0 +1,30 @@+"""Viewer payload limits; the full tool input/output stays in canonical history."""+import json++MAX_TOOL_EVENT_CHARS = 64 * 1024+++def bounded_args(args):+ encoded = json.dumps(args, ensure_ascii=True, default=str)+ if len(encoded) <= MAX_TOOL_EVENT_CHARS:+ return args+ # Retain ordinary scalar paths/commands for editor locations even when a content field is large.+ result = {}+ remaining = MAX_TOOL_EVENT_CHARS // 2+ for key, value in args.items():+ if remaining <= 0 or len(result) >= 64:+ break+ name = str(key)[:256]+ text = value if isinstance(value, str) else json.dumps(value, ensure_ascii=True, default=str)+ text = text[:min(4096, remaining)]+ result[name] = text+ remaining -= len(json.dumps([name, text], ensure_ascii=True))+ return result+++def bounded_result(result, is_error):+ text = result if isinstance(result, str) else json.dumps(result, ensure_ascii=True, default=str)+ if len(text) <= MAX_TOOL_EVENT_CHARS:+ return text+ # ACP reads errors from the result as well as the event flag; keep valid JSON after truncation.+ return json.dumps({'error' if is_error else 'output': text[:MAX_TOOL_EVENT_CHARS // 2], 'truncated': True})diff --git a/gateway/session_worker.py b/gateway/session_worker.pyindex 2a7887417d0..7a87cd707ed 100644--- a/gateway/session_worker.py+++ b/gateway/session_worker.py@@ -70,7 +70,8 @@ async def worker_request(connection, ref, params, *, operation):raise RuntimeStoreError('invalid_params')claim = _claim(connection, ref, params)authority = connection.authority- authority._require_admission_open()+ if operation == 'register':+ authority._require_admission_open()scope = {key: params[key] for key in ('execution_id', 'session_id', 'generation')}if operation == 'register':authority.authorize(connection.actor, ref, 'session:control')diff --git a/gateway/session_worker_delegation.py b/gateway/session_worker_delegation.pyindex 515470d9864..1528cab7355 100644--- a/gateway/session_worker_delegation.py+++ b/gateway/session_worker_delegation.py@@ -237,7 +237,6 @@ async def worker_delegation_request(connection, ref, params):raise RuntimeStoreError('invalid_params')claim = _claim(connection, ref, params)authority = connection.authority- authority._require_admission_open()if 'worker:adopt' not in connection.actor.capabilities:raise RuntimeStoreError('permission_denied')_verify(connection, ref, params, claim)diff --git a/gateway/session_worker_spawn.py b/gateway/session_worker_spawn.pynew file mode 100644index 00000000000..71b47c2626b--- /dev/null+++ b/gateway/session_worker_spawn.py@@ -0,0 +1,36 @@+"""Cancellation-safe handoff of a managed subprocess acquired off the owner loop."""+import asyncio+import threading+++async def acquire_process(spawn, *args, **kwargs):+ from gateway.session_managed_worker import ManagedWorker+ lock = threading.Lock()+ state = {'cancelled': False, 'process': None}++ def create():+ process = spawn(*args, **kwargs)+ with lock:+ cancelled = state['cancelled']+ if not cancelled:+ state['process'] = process+ if cancelled:+ ManagedWorker(process).close()+ return process++ pending = asyncio.create_task(asyncio.to_thread(create))+ try:+ process = await asyncio.shield(pending)+ with lock:+ state['process'] = None+ return process+ except asyncio.CancelledError:+ with lock:+ state['cancelled'] = True+ process = state['process']+ state['process'] = None+ if process is not None:+ await asyncio.to_thread(ManagedWorker(process).close)+ # If creation still runs, its thread owns cleanup; consume an eventual spawn exception.+ pending.add_done_callback(lambda task: task.exception() if not task.cancelled() else None)+ raisediff --git a/tests/agent/test_runtime_session_store.py b/tests/agent/test_runtime_session_store.pyindex 0ea6c396bb6..0e3ddb67d48 100644--- a/tests/agent/test_runtime_session_store.py+++ b/tests/agent/test_runtime_session_store.py@@ -31,14 +31,22 @@ def test_outbox_freezes_failed_payload_and_reopens_exclusively(tmp_path):return {'count': 1, 'annotations': [{'_row_id': 42}]}restored = RuntimeSessionStore(commit, scope, tmp_path / 'private')try:- assert restored.retry_pending()[0]['count'] == 1+ assert restored.retry_pending() == [] # reopening already reconciled the acknowledged journalassert seen[0]['payload']['messages'][0]['content'] == 'frozen'assert json.loads(restored.path.read_text())['pending'] == []- assert restored.path.stat().st_mode & 0o077 == 0finally:restored.close()[email protected]('posix')+def test_outbox_has_private_posix_mode(tmp_path):+ store = RuntimeSessionStore(lambda *a, **k: {}, {'session_id': 's'}, tmp_path / 'private')+ try:+ assert store.path.stat().st_mode & 0o077 == 0+ finally:+ store.close()++def test_outbox_capacity_failure_does_not_advance_or_discard(tmp_path):def unavailable(*args, **kwargs):raise TimeoutError('offline')diff --git a/tests/agent/test_worker_outbox_reopen.py b/tests/agent/test_worker_outbox_reopen.pynew file mode 100644index 00000000000..2939411fe8b--- /dev/null+++ b/tests/agent/test_worker_outbox_reopen.py@@ -0,0 +1,28 @@+"""A worker reopening an acknowledged-but-unjournaled write reconciles before its next write."""+import pytest++from agent.runtime_session_store import RuntimeSessionStore+++def test_reopen_reconciles_pending_receipt_before_new_write(tmp_path):+ calls = []+ def lost_reply(method, **params):+ calls.append(params)+ raise TimeoutError('lost reply')+ scope = {'session_id': 's', 'execution_id': 'w', 'epoch': 1}+ store = RuntimeSessionStore(lost_reply, scope, tmp_path)+ with pytest.raises(TimeoutError):+ store.queue_token_counts('s', input_tokens=10)+ store._outbox_owner.close() # process exit left its durable pending journal+ restored_calls = []+ def owner(method, **params):+ restored_calls.append(params)+ return {'ok': True}+ reopened = RuntimeSessionStore(owner, scope, tmp_path)+ try:+ reopened.queue_token_counts('s', input_tokens=20)+ assert restored_calls[0] == calls[0]+ assert [row['sequence'] for row in restored_calls] == [1, 2]+ assert [row['payload']['input_tokens'] for row in restored_calls] == [10, 20]+ finally:+ reopened.close()diff --git a/tests/agent/test_worker_rpc_proxy.py b/tests/agent/test_worker_rpc_proxy.pynew file mode 100644index 00000000000..a846fa02f23--- /dev/null+++ b/tests/agent/test_worker_rpc_proxy.py@@ -0,0 +1,28 @@+"""Private loopback worker persistence does not use ambient HTTP proxies."""+from contextlib import contextmanager+import json+from types import SimpleNamespace+++def test_worker_persistence_explicitly_bypasses_proxy(tmp_path, monkeypatch):+ from agent.runtime_session_store import WorkerRPC+ monkeypatch.setenv('HTTPS_PROXY', 'http://127.0.0.1:1')+ monkeypatch.delenv('NO_PROXY', raising=False)+ endpoint = SimpleNamespace(api_origin='http://127.0.0.1:1234')+ discoveries = iter([SimpleNamespace(state='ready', endpoint=endpoint),+ SimpleNamespace(state='draining', endpoint=None)])+ monkeypatch.setattr('hermes_cli.gateway_runtime.discover_gateway_endpoint',+ lambda *a, **k: next(discoveries))+ monkeypatch.setattr('hermes_cli.gateway_runtime.control_home_for', lambda home, endpoint: home)+ monkeypatch.setattr('hermes_cli.gateway_runtime_discovery.query_identify', lambda *a, **k: {'pid': -1})+ monkeypatch.setattr('hermes_cli.gateway_client._session_ticket', lambda *a, **k: 'ticket')+ calls = []+ @contextmanager+ def connect(url, **kwargs):+ calls.append(kwargs)+ yield SimpleNamespace(send=lambda value: None, recv=lambda **k: json.dumps({'id': 1, 'result': {'ok': True}}))+ monkeypatch.setattr('websockets.sync.client.connect', connect)+ rpc = WorkerRPC(tmp_path)+ assert rpc('worker.persist') == {'ok': True}+ assert rpc('worker.persist') == {'ok': True}+ assert all(call['proxy'] is None for call in calls)diff --git a/tests/gateway/test_managed_runtime_live_drain.py b/tests/gateway/test_managed_runtime_live_drain.pynew file mode 100644index 00000000000..08832475699--- /dev/null+++ b/tests/gateway/test_managed_runtime_live_drain.py@@ -0,0 +1,68 @@+"""A real managed child persists its final receipt while the ordinary daemon drains."""+import asyncio+from contextlib import closing+from http.server import ThreadingHTTPServer+import json+from pathlib import Path+import sqlite3+import threading++from tests.gateway.fixtures.local_recovery_probe import Model, child_env, daemon, rpc, websocket+from tests.gateway.test_normal_runtime_boot import control+++def test_managed_turn_finishes_inside_configured_restart_drain(tmp_path):+ root = Path(__file__).resolve().parents[2]+ home, user = tmp_path / 'state', tmp_path / 'user'+ home.mkdir()+ user.mkdir()+ peer = ThreadingHTTPServer(('127.0.0.1', 0), Model)+ peer.requests = []+ peer.blocked, peer.release = threading.Event(), threading.Event()+ thread = threading.Thread(target=peer.serve_forever, daemon=True)+ thread.start()+ url = f'http://127.0.0.1:{peer.server_port}/v1'+ (home / 'config.yaml').write_text(json.dumps({+ 'gateway': {'managed_workers': True},+ 'agent': {'restart_after_turn_timeout': 0, 'restart_drain_timeout': 20},+ 'model': {'provider': 'custom', 'default': 'drain-fixture', 'base_url': url},+ 'platform_toolsets': {'cli': []}, 'auxiliary': {'title_generation': {'enabled': False}}}))+ env = child_env()+ env.update(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home), PYTHONPATH=str(root),+ OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=url)+ admission_id = None+ async def exercise(process, descriptor):+ nonlocal admission_id+ async with websocket(home, descriptor) as ws:+ created = await rpc(ws, 'session.create', request_id='drain-session', source='cli', cwd=str(home),+ model='drain-fixture', provider='custom', base_url=url, api_key='loopback-only',+ toolsets=[], ignore_rules=True)+ assert 'result' in created, created+ submitted = await rpc(ws, 'prompt.submit', session_id=created['result']['session_id'],+ input_id='drain-input', text='BLOCK_STARTED', finite=True)+ assert 'result' in submitted, submitted+ admission_id = submitted['result']['admission_id']+ assert await asyncio.to_thread(peer.blocked.wait, 30)+ accepted = await asyncio.to_thread(control, home, 'pause-for-update')+ assert accepted['pausing'] is True, accepted+ async with asyncio.timeout(15):+ while (await asyncio.to_thread(control, home, 'identify'))['state'] != 'draining':+ await asyncio.sleep(.05)+ peer.release.set()+ await asyncio.to_thread(process.wait, 50)+ try:+ with daemon(root, home, env, barrier=False) as (process, descriptor):+ asyncio.run(exercise(process, descriptor))+ with closing(sqlite3.connect(home / 'state.db')) as db:+ row = db.execute('SELECT status,outcome FROM session_admissions WHERE admission_id=?', (admission_id,)).fetchone()+ if row != ('terminal', 'completed'):+ for log in [home / 'restart.log', *(home / 'logs').glob('*.log')]:+ print(log.name, '\n'.join(log.read_text(encoding='utf-8', errors='replace').splitlines()[-100:]))+ assert row == ('terminal', 'completed'), (row, (home / 'restart.log').read_text())+ assert db.execute('SELECT status FROM worker_executions').fetchone()[0] == 'terminal'+ assert len(peer.requests) == 1+ finally:+ peer.release.set()+ peer.shutdown()+ peer.server_close()+ thread.join(timeout=5)diff --git a/tests/gateway/test_managed_spawn_cancellation.py b/tests/gateway/test_managed_spawn_cancellation.pynew file mode 100644index 00000000000..5101e5c743d--- /dev/null+++ b/tests/gateway/test_managed_spawn_cancellation.py@@ -0,0 +1,41 @@+"""Cancelling threaded Popen acquisition still reaps the child it eventually creates."""+import asyncio+import subprocess+import sys+import threading+from types import SimpleNamespace++import pytest+++async def test_cancelled_spawn_reaps_late_child(monkeypatch):+ from gateway import session_managed_worker as managed+ entered, release, created = (threading.Event() for _ in range(3))+ original = subprocess.Popen+ children = []+ def spawn(args, **kwargs):+ entered.set()+ assert release.wait(10)+ child = original([sys.executable, '-c', 'import sys; sys.stdin.read()'], **kwargs)+ children.append(child)+ created.set()+ return child+ monkeypatch.setattr(managed.subprocess, 'Popen', spawn)+ monkeypatch.setattr(managed, '_worker_env', lambda authority: None)+ task = asyncio.create_task(managed.execute_managed(SimpleNamespace(), SimpleNamespace(session_id='s'), {}, None))+ try:+ assert await asyncio.to_thread(entered.wait, 5)+ task.cancel()+ with pytest.raises(asyncio.CancelledError): await task+ release.set()+ assert await asyncio.to_thread(created.wait, 5)+ await asyncio.to_thread(children[0].wait, 5)+ finally:+ release.set()+ for child in children:+ if child.poll() is None:+ child.kill()+ child.wait(timeout=5)+ child.stdin.close()+ child.stdout.close()diff --git a/tests/gateway/test_managed_turn_contract.py b/tests/gateway/test_managed_turn_contract.pynew file mode 100644index 00000000000..8ba20eaf9be--- /dev/null+++ b/tests/gateway/test_managed_turn_contract.py@@ -0,0 +1,157 @@+"""Managed turns carry finite approval policy, accounting, and live tool details."""+import asyncio+from dataclasses import replace+import json+import os+import threading+from types import SimpleNamespace++import pytest+++def assignment(tmp_path, monkeypatch, *, finite=True, unattended=False, yolo=False):+ from gateway.session_local import _bypass_policy+ from gateway.session_managed_worker import _bootstrap+ from tools.approval import clear_session+ clear_session('managed-contract')+ policy = _bypass_policy({'cwd': str(tmp_path), 'model': 'fixture', 'provider': 'custom',+ 'base_url': 'http://127.0.0.1:9/v1', 'ignore_user_config': True}, private_secrets={})+ policy = replace(policy, request_json=json.dumps({**json.loads(policy.request_json), 'yolo': yolo}))+ monkeypatch.setattr('gateway.session_policy.launch_key', lambda *args: None)+ live = SimpleNamespace(source=SimpleNamespace(user_id='u', chat_id='c'), route='managed-contract')+ authority = SimpleNamespace(sessions={'sid': live}, runner=None, profile_id=str(tmp_path))+ ref = SimpleNamespace(session_id='sid')+ row = {'payload': {'text': 'hello', 'finite': finite, 'unattended': unattended}}+ scope = {'profile_id': str(tmp_path), 'session_id': 'sid', 'execution_id': 'x', 'generation': 1,+ 'pid': os.getpid(), 'birth': 0, 'secret': 's', 'epoch': 1}+ return _bootstrap(authority, ref, row, policy, scope), (authority, ref, row, policy, scope)++[email protected]('unattended', [False, True])+def test_child_executes_under_finite_policy_and_preserves_receipt(tmp_path, monkeypatch, unattended):+ from agent import managed_worker as worker+ from gateway.session_finite import finite_turn_required, unattended_turn+ from tools.approval import _yolo_active, clear_session+ frame, _ = assignment(tmp_path, monkeypatch, unattended=unattended)+ observed, frames = [], []++ class Agent:+ def __init__(self, **kwargs):+ self.kwargs = kwargs+ self.session_prompt_tokens = 100+ self.session_completion_tokens = 20+ def run_conversation(self, text, **kwargs):+ observed.append((finite_turn_required(), unattended_turn(), _yolo_active()))+ self.kwargs['tool_start_callback']('call-1', 'read_file', {'path': 'report.txt'})+ self.kwargs['tool_complete_callback']('call-1', 'read_file', {'path': 'report.txt'},+ '{"error":"file missing"}')+ self.session_prompt_tokens += 7+ self.session_completion_tokens += 3+ return {'final_response': 'budget summary', 'completed': False, 'partial': True,+ 'turn_exit_reason': 'max_iterations_reached(1/1)', 'prompt_tokens': 107,+ 'completion_tokens': 23, 'estimated_cost_usd': .02, 'model': 'fixture', 'provider': 'custom',+ 'messages': [{'role': 'assistant', 'content': 'large history'}]}++ class Store:+ def __init__(self, *args): pass+ def get_messages_as_conversation(self, sid): return []+ def flush_token_counts(self): pass+ def finish(self): pass+ def close(self): pass++ class Controls:+ def __init__(self, *args):+ self.stopped = threading.Event()+ self.finish = threading.Event()+ self.finish.set()+ def approval(self, data): pytest.fail('unexpected approval')+ def clarify(self, questions): pytest.fail('unexpected question')++ monkeypatch.setattr(worker, 'bind_bypass_policy', lambda frame: None)+ monkeypatch.setattr(worker, 'discover_profile_mcp', lambda policy: None)+ monkeypatch.setattr(worker, 'retire_agent', lambda agent: None)+ monkeypatch.setattr(worker, 'WorkerControls', Controls)+ monkeypatch.setattr('agent.runtime_session_store.WorkerRPC', lambda home: lambda *a, **k: {'owner_epoch': 1})+ monkeypatch.setattr('agent.runtime_session_store.RuntimeSessionStore', Store)+ monkeypatch.setattr('tools.process_registry.process_registry.recover_from_checkpoint', lambda: None)+ monkeypatch.setattr('run_agent.AIAgent', Agent)+ monkeypatch.setattr('agent.title_generator.wait_for_title_upgrades', lambda: None)+ clear_session('managed-contract') # the child owns a fresh approval registry+ worker.execute(frame, SimpleNamespace(send=lambda kind, **payload: frames.append({'type': kind, **payload})))+ assert observed == [(True, unattended, unattended)]+ receipt = next(f for f in frames if f['type'] == 'result')+ assert receipt['result']['completed'] is False+ assert receipt['result']['estimated_cost_usd'] == .02+ assert receipt['result']['provider'] == 'custom'+ assert receipt['result']['turn_exit_reason'] == 'max_iterations_reached(1/1)'+ assert 'messages' not in receipt['result']+ _, usage = worker.accept_result(receipt['result'])+ assert usage == {'input_tokens': 7, 'output_tokens': 3, 'total_tokens': 10}+ events = [f for f in frames if f['type'].startswith('tool.')]+ assert events[0]['tool_call_id'] == 'call-1' and events[0]['args']['path'] == 'report.txt'+ assert events[1]['is_error'] is True+ assert json.loads(events[1]['result'])['error'] == 'file missing'+++def test_current_yolo_revocation_overrides_frozen_launch(tmp_path, monkeypatch):+ from gateway.session_managed_worker import _bootstrap+ from tools.approval import disable_session_yolo, clear_session, is_session_yolo_enabled+ frame, args = assignment(tmp_path, monkeypatch, yolo=True)+ assert json.loads(frame['policy']['request_json'])['turn_v1']['yolo'] is True+ from gateway.session_managed_worker import worker_turn_scope+ disable_session_yolo('managed-contract')+ assert json.loads(_bootstrap(*args)['policy']['request_json'])['turn_v1']['yolo'] is False+ clear_session('managed-contract')+ with worker_turn_scope(frame):+ assert is_session_yolo_enabled('managed-contract') is True+ clear_session('managed-contract')+++async def test_stop_during_environment_preparation_prevents_bootstrap(tmp_path, monkeypatch):+ from gateway import session_managed_worker as managed+ started, release = threading.Event(), threading.Event()+ frames = []+ def env(authority):+ started.set()+ assert release.wait(5)+ class Worker:+ def __init__(self, process):+ self.stop = asyncio.Event()+ def interrupt(self):+ self.stop.set()+ async def next_frame(self, *args, **kwargs):+ from hermes_state_runtime import RuntimeStoreError+ assert self.stop.is_set(), 'pending Stop was not adopted'+ raise RuntimeStoreError('managed_worker_stopped')+ def close(self): pass+ monkeypatch.setattr(managed, '_worker_env', env)+ monkeypatch.setattr(managed.subprocess, 'Popen', lambda *a, **k: object())+ monkeypatch.setattr(managed, 'ManagedWorker', Worker)+ authority = SimpleNamespace(pending_stops={}, pending_results={})+ def adopt(sid, generation, worker):+ if authority.pending_stops.pop(sid, None) == generation:+ worker.interrupt()+ authority.adopt_agent = adopt+ ref = SimpleNamespace(session_id='sid')+ row = {'admission_id': 'adm', 'generation': 3}+ task = asyncio.create_task(managed.execute_managed(authority, ref, row, None))+ assert await asyncio.to_thread(started.wait, 5)+ authority.pending_stops['sid'] = 3+ release.set()+ await asyncio.wait_for(task, 5)+ assert not frames+ assert authority.pending_results['adm']['result']['interrupted'] is True+ assert not authority.pending_stops+++def test_shared_tool_events_bound_large_content_without_losing_error_or_path():+ from gateway.run_turn_progress import _tool_lifecycle_payload+ start = _tool_lifecycle_payload('call', 'write_file', {'path': 'report.txt', 'content': 'x' * 1_000_000})+ assert start['tool_id'] == 'call' and start['args']['path'] == 'report.txt'+ assert len(json.dumps(start)) < 100_000+ from gateway.run_turn_progress import _tool_complete_payload+ complete = _tool_complete_payload('call', 'write_file', {}, {'error': 'bad output ' + 'x' * 1_000_000})+ assert complete['is_error'] is True+ assert 'error' in json.loads(complete['result'])+ assert len(json.dumps(complete)) < 100_000diff --git a/tests/gateway/test_managed_worker_drain.py b/tests/gateway/test_managed_worker_drain.pynew file mode 100644index 00000000000..899e3c126e8--- /dev/null+++ b/tests/gateway/test_managed_worker_drain.py@@ -0,0 +1,101 @@+"""Already-reserved compute remains able to persist while new work is refused."""+import json+import subprocess+import sys+from types import SimpleNamespace++import pytest+++async def test_reserved_worker_persists_while_runtime_drains(tmp_path):+ from gateway.session_worker import worker_request+ from gateway.session_worker_reservation import reserve_admission_worker+ from tests.gateway.test_worker_admission_reservation import hello+ from hermes_state import SessionDB+ from hermes_state_runtime import admit_session_input, begin_runtime_epoch, claim_session_input, RuntimeStoreError+ db = SessionDB(tmp_path / 'state.db')+ process = subprocess.Popen([sys.executable, '-c', 'import sys; sys.stdin.read()'], stdin=subprocess.PIPE,+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)+ try:+ 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, logical_owner=lambda sid: sid, sessions={})+ row = admit_session_input(db, epoch=epoch, principal_id='human', session_id='owned', request_id='input', payload={})+ claim_session_input(db, epoch=epoch, session_id='owned')+ scope = reserve_admission_worker(authority, admission_id=row['admission_id'], process=process,+ principal_id='human', hello=hello(process))+ actor = SimpleNamespace(subject='human', profile_id=str(tmp_path), capabilities={'worker:adopt'})+ connection = SimpleNamespace(authority=authority, actor=actor)+ identity = {k: v for k, v in scope.items() if k != 'epoch'}+ await worker_request(connection, None, identity, operation='adopt')+ def draining():+ raise RuntimeStoreError('runtime_draining')+ authority._require_admission_open = draining+ await worker_request(connection, None, scope | {+ 'sequence': 1, 'operation': 'session.prompt', 'payload': {'system_prompt': 'settled while draining'}}, operation='persist')+ assert db.get_session('owned')['system_prompt'] == 'settled while draining'+ with pytest.raises(RuntimeStoreError, match='runtime_draining'):+ await worker_request(connection, None, identity | {'kind': 'compute'}, operation='register')+ finally:+ process.stdin.close()+ process.wait(timeout=5)+ db.close()++[email protected]('purpose', ['worker-adoption', 'interactive'])[email protected]('state', ['ready', 'draining'])+async def test_draining_ws_redeems_only_worker_ticket(tmp_path, monkeypatch, purpose, state):+ from gateway.run_api import GatewayRuntimeAPI+ from gateway.runtime_bootstrap import TicketStore+ from hermes_cli import web_server as web+ from hermes_cli import web_server_chat+ tickets = TicketStore('owner', [str(tmp_path)])+ ticket = tickets.mint(profile_id=str(tmp_path), subject='human', purpose=purpose)+ authority = SimpleNamespace(db=SimpleNamespace(db_path=tmp_path / 'state.db'), profile_id=str(tmp_path), runner=None)+ runner = SimpleNamespace(_draining=True, session_runtime_descriptor={'state': state},+ session_authority=authority, session_ticket_store=tickets)+ seen, sent = [], []+ async def fallback(*args):+ pytest.fail('draining native calls must not enter legacy fallback')+ async def handle(ws, **kwargs):+ await ws.accept(subprotocol='hermes-gateway-v1')+ seen.append((await ws.receive_json(), kwargs['auth_identity']['capabilities']))+ monkeypatch.setattr('tui_gateway.ws.handle_ws', handle)+ monkeypatch.setattr(web, '_DASHBOARD_EMBEDDED_CHAT_ENABLED', True)+ monkeypatch.setattr(web_server_chat, '_ws_request_is_allowed', lambda ws: True)+ incoming = iter([{'type': 'websocket.connect'}, {'type': 'websocket.receive', 'text': json.dumps({'method': 'worker.persist'})}])+ async def receive(): return next(incoming)+ async def send(value): sent.append(value)+ scope = {'type': 'websocket', 'path': '/api/ws', 'scheme': 'ws', 'query_string': b'',+ 'client': ('127.0.0.1', 1234), 'server': ('127.0.0.1', 9999),+ 'headers': [(b'sec-websocket-protocol', ('hermes-gateway-v1, hermes-gateway-ticket.' + ticket).encode())],+ 'subprotocols': ['hermes-gateway-v1', 'hermes-gateway-ticket.' + ticket]}+ await GatewayRuntimeAPI(fallback, runner, web.app)(scope, receive, send)+ if purpose == 'worker-adoption':+ assert seen == [({'method': 'worker.persist'}, frozenset({'worker:adopt'}))]+ else:+ assert not seen+ assert sent[-1]['type'] == 'websocket.close'+++async def test_listener_and_tickets_live_until_settlement(tmp_path, monkeypatch):+ from gateway.run_runtime import drain_gateway_runtime, settle_gateway_runtime+ from gateway.runtime_bootstrap import TicketStore+ tickets = TicketStore('owner', [str(tmp_path)])+ ticket = tickets.mint(profile_id=str(tmp_path), subject='human', purpose='worker-adoption')+ closed = []+ async def stop_api(handle): closed.append(handle)+ async def stop_service(runner): pass+ monkeypatch.setattr('gateway.run_api.stop_gateway_api', stop_api)+ monkeypatch.setattr('gateway.session_hosted_service.stop_hosted_service', stop_service)+ runner = SimpleNamespace(_draining=False, adapters={}, session_runtime_descriptor={'state': 'ready'},+ session_ticket_store=tickets, session_api='listener')+ await drain_gateway_runtime(runner)+ assert not closed+ assert tickets.redeem(ticket, profile_id=str(tmp_path), purpose='worker-adoption')['subject'] == 'human'+ await settle_gateway_runtime(runner)+ assert closed == ['listener']diff --git a/tests/gateway/test_run_runtime_hot_serve_cleanup.py b/tests/gateway/test_run_runtime_hot_serve_cleanup.pyindex 419d7abe398..39280faca40 100644--- a/tests/gateway/test_run_runtime_hot_serve_cleanup.py+++ b/tests/gateway/test_run_runtime_hot_serve_cleanup.py@@ -145,6 +145,7 @@ async def test_settle_gateway_runtime_waits_for_bot_receipt_tasks():task = asyncio.create_task(receipt_writer())authority = SimpleNamespace(sessions={}, _bot_receipt_tasks={task})runner = SimpleNamespace(session_authority=authority)+ authority.runner = runnersettling = asyncio.create_task(run_runtime.settle_gateway_runtime(runner))await asyncio.sleep(0)diff --git a/tests/gateway/test_runtime_worker_shutdown.py b/tests/gateway/test_runtime_worker_shutdown.pynew file mode 100644index 00000000000..e70d697774c--- /dev/null+++ b/tests/gateway/test_runtime_worker_shutdown.py@@ -0,0 +1,86 @@+"""Shutdown counts managed claims and retains profile ownership until actual threads stop."""+import asyncio+import threading+from types import SimpleNamespace++import pytest++from gateway import run_runtime+from gateway.run_shutdown import GatewayShutdownMixin+from gateway.session_authorities import SessionAuthorities+++async def test_managed_claims_participate_in_zero_and_nonzero_drain(tmp_path):+ release = asyncio.Event()+ task = asyncio.create_task(release.wait())+ stopped = []+ live = SimpleNamespace(task=task, route='route', event_stream=SimpleNamespace(execution={'execution_generation': 2}))+ authority = SimpleNamespace(sessions={'s': live}, _managed_workers={+ 's': SimpleNamespace(control=lambda frame: stopped.append(frame), closed=threading.Event())})+ runner = SimpleNamespace(session_authority=authority, _running_agents={},+ _running_agent_count=lambda: 0, _active_cron_job_count=lambda: 0, _active_api_run_count=lambda: 0,+ _active_deferred_agent_worker_count=lambda: 0, _snapshot_running_agents=lambda: {},+ _update_runtime_status=lambda *a: None)+ runner._drain_work_counts = GatewayShutdownMixin._drain_work_counts.__get__(runner)+ authority.runner = runner+ authority.pending_stops = {}+ try:+ assert GatewayShutdownMixin._active_work_count(runner) == 1+ _, timed_out = await GatewayShutdownMixin._drain_active_agents(runner, timeout=0)+ assert timed_out is True+ run_runtime.stop_managed_turns(runner)+ assert stopped == [{'type': 'stop'}]+ drain = asyncio.create_task(GatewayShutdownMixin._drain_active_agents(runner, timeout=5))+ await asyncio.sleep(0)+ assert not drain.done()+ authority._managed_workers['s'].closed.set()+ release.set()+ _, timed_out = await asyncio.wait_for(drain, 5)+ assert timed_out is False+ finally:+ release.set()+ await asyncio.gather(task, return_exceptions=True)+++async def test_profile_timeout_keeps_authority_until_physical_worker_exits(tmp_path, monkeypatch):+ started, release, done, stopped = (threading.Event() for _ in range(4))+ def turn():+ started.set()+ try:+ assert release.wait(10)+ finally:+ done.set()+ task = asyncio.create_task(asyncio.to_thread(turn))+ assert await asyncio.to_thread(started.wait, 5)+ launch, beta = tmp_path, tmp_path / 'profiles' / 'beta'+ beta.mkdir(parents=True)+ registry = SessionAuthorities(launch)+ registry.add(launch, SimpleNamespace(profile_id=str(launch)))+ agent = SimpleNamespace(hard_interrupt=lambda message: stopped.set())+ live = SimpleNamespace(task=task, route='beta-route', event_stream=SimpleNamespace(execution={'execution_generation': 2}))+ authority = SimpleNamespace(sessions={'s': live}, profile_id=str(beta), pending_stops={},+ agent=lambda ref: agent, _turn_workers={1: (SimpleNamespace(worker_done=done), [agent])})+ registry.add(beta, authority, name='beta')+ runner = SimpleNamespace(session_authorities=registry, session_runtime_descriptor={},+ session_ticket_store=SimpleNamespace(profile_ids=registry.profile_ids()))+ unbound = []+ monkeypatch.setattr('gateway.session_cron.unbind_owner', lambda a: unbound.append(a))+ authority.runner = runner+ monkeypatch.setattr(run_runtime, 'TURN_SETTLE_SECONDS', 0)+ try:+ assert await run_runtime.unserve_profile_runtime(runner, beta) is False+ assert stopped.is_set() and not done.is_set()+ assert registry.for_home(beta) is authority+ assert not unbound+ assert str(beta) in runner.session_ticket_store.profile_ids+ release.set()+ await asyncio.wait_for(task, 5)+ await run_runtime.unserve_profile_runtime(runner, beta)+ assert registry.for_home(beta) is None+ assert str(beta) not in runner.session_ticket_store.profile_ids+ assert unbound == [authority]+ finally:+ release.set()+ await asyncio.gather(task, return_exceptions=True)