The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): stopping a served profile stops and joins its turns before releasing it
Tekniume28da35e4ee3
diff --git a/gateway/run_profile_reconcile.py b/gateway/run_profile_reconcile.pyindex b53c0ec67a8..3a5c38dab24 100644--- a/gateway/run_profile_reconcile.py+++ b/gateway/run_profile_reconcile.py@@ -358,9 +358,14 @@ class GatewayProfileReconcileMixin:# 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 = Trueif getattr(self, "session_authorities", None) is not None:with _log_suppressed(logging.WARNING, "session authority retirement failed for %s", name, exc_info=True):- await unserve_profile_runtime(self, home)+ 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 05a8e7e6fbf..25a46720400 100644--- a/gateway/run_runtime.py+++ b/gateway/run_runtime.py@@ -177,13 +177,15 @@ def managed_turn_count(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``)."""+def stop_authority_turns(authority, *, in_process=False):+ """Cooperative Stop for every turn *authority* is executing: the control a user's Stop sends to a+ managed worker (acknowledged, or terminated within STOP_ACK_SECONDS, and the admission settles+ through its own fenced path). ``in_process`` also hard-interrupts the running agent of each+ executing in-process turn, or latches the generation ``adopt_agent`` consumes before it exists."""from hermes_state_runtime import RuntimeStoreErrorsignalled = 0- for worker in list(getattr(authority, '_managed_workers', {}).values()):+ workers = getattr(authority, '_managed_workers', {})+ for worker in list(workers.values()):if worker.closed.is_set():continuetry:@@ -193,6 +195,21 @@ def stop_authority_turns(authority):# 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+ if not in_process:+ return signalled+ from agent.interrupt_compat import request_hard_interrupt+ from gateway.run import _AGENT_PENDING_SENTINEL+ running = getattr(authority.runner, '_running_agents', {})+ for sid, live in list(authority.sessions.items()):+ generation = live.event_stream.execution.get('execution_generation')+ if generation is None or sid in workers:+ continue+ agent = running.get(live.route)+ if agent is None or agent is _AGENT_PENDING_SENTINEL:+ authority.pending_stops[sid] = generation+ else:+ request_hard_interrupt(agent, 'Profile stopping', tool_reason='gateway shutdown')+ signalled += 1return signalled@@ -215,18 +232,35 @@ async def _settle_tasks(tasks, timeout):async def _retire_profile_authority(authority):- """Stop profile-local services/tasks before its ownership is released."""+ """Stop profile-local services and turns before its ownership is released.++ Claims are refused from here on; every executing turn gets a cooperative Stop, and its session+ task is joined (an in-process turn's task ends only after its executor thread returned and the+ admission settled). False when a turn misses TURN_SETTLE_SECONDS: its thread may still call tools+ and write history, so the caller must keep the profile's reservation and store handles."""from gateway.session_cron import unbind_ownerservice = getattr(authority, 'hosted_room_service', None)if service is not None:await asyncio.to_thread(service.stop, timeout=5)- tasks = _authority_tasks(authority)- for task in tasks:+ 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)+ # 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]+ for task in rest:task.cancel()- if tasks:- await asyncio.gather(*tasks, return_exceptions=True)+ 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 lateasync def serve_profile_runtime(runner, name, home):@@ -261,14 +295,16 @@ async def serve_profile_runtime(runner, name, home):async def unserve_profile_runtime(runner, home):"""Retire one profile's authority (deleted while running) and shrink the published set.- No-op for a profile this process never served."""+ False when one of its turns outlived the Stop deadline (keep the reservation); True otherwise,+ including for a profile this process never served."""home = await asyncio.to_thread(Path(home).resolve)registry = runner.session_authoritiesauthority = registry.remove(home) if home in registry else Noneif authority is None:- return- await _retire_profile_authority(authority)+ return True+ retired = await _retire_profile_authority(authority)_publish_served_set(runner)+ return retireddef _authorities(runner):diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex 8b4e6018793..3682d41c9f3 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -62,6 +62,8 @@ class SessionAuthority:# Stops accepted for a running generation whose agent does not exist yet# (first-turn construction); consumed by adopt_agent, keyed session -> generation.self.pending_stops = {}+ # Set by profile retirement (unserve): the drain claims no successor after its running turn.+ self.retiring = Falsedef authorize(self, actor, ref, capability):"""Every handler calls this first, so a later ``self.sessions[ref.session_id]`` is@@ -93,7 +95,7 @@ class SessionAuthority:raise RuntimeStoreError('permission_denied')def _require_admission_open(self):- if self.runner._draining:+ if self.runner._draining or self.retiring:raise RuntimeStoreError('runtime_draining')def logical_owner(self, session_id):diff --git a/tests/gateway/test_profile_retire_stops_turns.py b/tests/gateway/test_profile_retire_stops_turns.pynew file mode 100644index 00000000000..67a55324cbc--- /dev/null+++ b/tests/gateway/test_profile_retire_stops_turns.py@@ -0,0 +1,97 @@+"""Unserving a profile stops and joins its running turns before ownership is released.++Cancelling the drain task alone leaves the turn's executor thread calling tools and writing+history after ``gateway.lock`` and the store handles are released. Retirement must Stop the+turn, wait for its thread (the admission settles), claim no successor, and report a turn that+outlives the deadline so the caller keeps the reservation."""+import asyncio+import threading+from types import SimpleNamespace++import pytest++from gateway import run_runtime+from gateway.session_authority import LiveSession, SessionAuthority+from gateway.session_contract import Principal, SessionRef, Submission+from hermes_state import SessionDB+from hermes_state_runtime import begin_runtime_epoch, list_session_admissions++ACTOR = Principal('human', 'owned', frozenset({'session:submit', 'session:control'}), 'cli')+REF = SessionRef('owned', 's')+++class _Agent:+ """Blocks its executor thread until interrupted (or released), like a turn in a model call."""++ def __init__(self, honours_stop=True):+ self.honours_stop = honours_stop+ self.stopped = threading.Event()+ self.release = threading.Event()+ self.started = threading.Event()+ self.writes_after_return = []++ def hard_interrupt(self, message=None, *, tool_reason=None):+ if self.honours_stop:+ self.stopped.set()++ def run(self):+ self.started.set()+ while not (self.stopped.is_set() or self.release.is_set()):+ self.stopped.wait(.01)+ return {'final_response': '', 'interrupted': True, 'messages': []}+++def _authority(tmp_path, agent):+ db = SessionDB(db_path=tmp_path / 'state.db')+ db.create_session('s', source='test')+ epoch = begin_runtime_epoch(db, instance_id='owner')+ runner = SimpleNamespace(_draining=False, config=SimpleNamespace(multiplex_profiles=False),+ _adapter_for_source=lambda source: None, _running_agents={})+ authority = SessionAuthority(runner, profile_id='owned', instance_id='owner', db=db, epoch=epoch)+ authority.sessions['s'] = LiveSession(SimpleNamespace(platform=None, user_id='human'), 'route')+ returned = threading.Event()++ async def execute(authority, ref, row):+ # The in-process turn: its agent is registered for the route and runs in an executor thread.+ runner._running_agents['route'] = agent+ try:+ result = await asyncio.get_running_loop().run_in_executor(None, agent.run)+ finally:+ runner._running_agents.pop('route', None)+ returned.set()+ authority.pending_results[row['admission_id']] = {'result': result, 'usage': {}}+ return ''+ return db, authority, execute, returned++[email protected]('honours_stop', [True, False])+async def test_unserve_stops_and_joins_the_running_turn_before_release(tmp_path, monkeypatch, honours_stop):+ from gateway import session_finite+ agent = _Agent(honours_stop=honours_stop)+ db, authority, execute, returned = _authority(tmp_path, agent)+ monkeypatch.setattr(session_finite, 'execute_finite_admission', execute)+ monkeypatch.setattr(run_runtime, 'TURN_SETTLE_SECONDS', 1.0, raising=False)+ monkeypatch.setattr('gateway.session_cron.unbind_owner', lambda authority: None)+ try:+ with db:+ await authority.submit(ACTOR, Submission(request_id='running', ref=REF, payload={'text': 'a'}, intent='queue'))+ await authority.submit(ACTOR, Submission(request_id='follower', ref=REF, payload={'text': 'b'}, intent='queue'))+ await asyncio.wait_for(asyncio.to_thread(agent.started.wait, 5), 6)++ retired = await run_runtime._retire_profile_authority(authority)++ # Nothing of the old turn may run once retirement reports the profile releasable.+ if honours_stop:+ assert returned.is_set() and agent.stopped.is_set(), 'turn thread outlived retirement'+ assert retired is True+ rows = {r['request_id']: r for r in list_session_admissions(db, session_id='s', pending_only=False)}+ assert rows['running']['status'] == 'terminal' and rows['running']['outcome'] == 'interrupted'+ assert rows['follower']['status'] == 'queued', rows # no successor claimed after Stop+ else:+ # The thread is still in its call: the caller must keep gateway.lock and the store.+ assert retired is False and not returned.is_set()+ finally:+ agent.release.set()+ await asyncio.sleep(.05)+ db.close()diff --git a/tests/gateway/test_run_runtime_hot_serve_cleanup.py b/tests/gateway/test_run_runtime_hot_serve_cleanup.pyindex 1247ad03db0..419d7abe398 100644--- a/tests/gateway/test_run_runtime_hot_serve_cleanup.py+++ b/tests/gateway/test_run_runtime_hot_serve_cleanup.py@@ -9,6 +9,7 @@ from types import SimpleNamespaceimport pytestfrom gateway import run_runtime+from gateway.session_authority import LiveSessionfrom hermes_state import SessionDBfrom hermes_state_runtime import admit_session_input, begin_runtime_epochfrom tools.bot_live_delivery import _locked, _write@@ -46,7 +47,7 @@ async def test_failed_hot_serve_retires_session_and_bot_recovery_tasks(monkeypatpayload={"text": "queued bot delivery"},)- live = SimpleNamespace(task=None)+ live = LiveSession(SimpleNamespace(platform=None, user_id='owner'), 'route')authority = SimpleNamespace(runner=runner,db=db,