The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): stop only the stopped turn and settle stuck admission heads
unsupportedpastelsc4004c5a8700
diff --git a/gateway/session_api.py b/gateway/session_api.pyindex 60534208809..cbd0314a501 100644--- a/gateway/session_api.py+++ b/gateway/session_api.py@@ -7,6 +7,7 @@ import jsonfrom gateway.config import Platformfrom gateway.session import SessionEntry, SessionSource, _is_path_unsafefrom gateway.session_contract import SessionRef+from gateway.session_local_recovery import unused_sessionfrom hermes_state_runtime import RuntimeStoreError, _epoch, _jsonfrom hermes_state_local import API_BINDING_PREFIX as _BINDING_PREFIX, API_DECLARED_PREFIX as _DECLARED_PREFIX@@ -249,7 +250,10 @@ def bind_api_steps(authority, session_id, *, hosted_dispatch=None, declared_key=receipt['declared_key'] = legacy_keyexisting = conn.execute("SELECT entry_json FROM gateway_routing WHERE scope='' AND session_key=?",(route,)).fetchone()- if existing is not None and json.loads(existing[0])['session_id'] != session_id:+ held = json.loads(existing[0])['session_id'] if existing is not None else session_id+ # The route is derived from this id, so only the stale-route heal (#54878) names another session+ # on it: one it minted that never ran a turn goes back to the caller; anything used still refuses.+ if held != session_id and not unused_session(conn, held):raise RuntimeStoreError('admission_conflict')conn.execute('''INSERT INTO sessions(id,source,title,hidden,started_at) VALUES(?,?,?,?,?)ON CONFLICT(id) DO NOTHING''', (session_id, storage_source, title,@@ -306,7 +310,9 @@ def restore_api_session(authority, session_id):store._ensure_loaded_locked()current = store._entries.get(entry.session_key)if current is not None and current.session_id not in authority.db.get_compression_lineage(session_id):- raise RuntimeStoreError('admission_conflict')+ with authority.db._read_ctx() as conn:+ if not unused_session(conn, current.session_id): # see the bind's routing check+ raise RuntimeStoreError('admission_conflict')store._entries[entry.session_key] = current if current is not None and current.session_id == target else entryauthority.sessions.setdefault(session_id, LiveSession(source, entry.session_key))return SessionRef(authority.profile_id, session_id)diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex 3bc6c596c77..0fe4295d43b 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -874,8 +874,12 @@ class SessionAuthority:with live.event_stream.lock:adopted_generation, agent = self.adopted.get(ref.session_id, (None, None))if adopted_generation != generation:- agent = self.agent(ref)- if not self._runs_own_agent(ref):+ # Its execution returned and only the settlement is left: nothing to stop, and the route's+ # agent may already be the NEXT turn's (own-agent runs install it before their claim).+ returned = (live.event_stream.execution.get('execution_generation') == generation+ and self.executing.get(ref.session_id) != generation)+ agent = None if returned else self.agent(ref)+ if not returned and not self._runs_own_agent(ref):# Accepted for this exact claim before its turn adopted an agent: whatever agent# the turn adopts for this generation must not run the work as if no Stop arrived.self.pending_stops[ref.session_id] = generation@@ -1104,10 +1108,29 @@ class SessionAuthority:return Truereturn False+ async def _refuse_head(self, ref, admission_id, reason):+ """Settle the queued head a preclaim check refused as cancelled: its waiters get *reason* (the+ ingress notice, the API's refusal) and its successors revalidate on their own merits."""+ from gateway.session_runtime_workers import tracked_write+ try:+ row = await tracked_write(self, partial(cancel_session_input, self.db, epoch=self.epoch,+ admission_id=admission_id))+ except RuntimeStoreError:+ return False+ if (row['status'], row['outcome']) != ('terminal', 'cancelled'):+ return False+ waiter = self.waiters.pop(admission_id, None)+ if waiter is not None and not waiter.done():+ waiter.set_exception(RuntimeStoreError(reason))+ self._settle_cancelled(ref, admission_id)+ from gateway.session_ingress_media import release_admission_media+ await asyncio.to_thread(release_admission_media, self.db, admission_id)+ return True+async def _claim_with_retry(self, ref, live):"""The drain's next ``(row, first)``, waiting out transient storage and a classic turn on theroute; None when the drain must exit (paused, or stopping with committed rows left queued)."""- backoff = 0.0+ backoff, conflicted = 0.0, Nonewhile True:try:row, first = await self._claim_next(ref, live)@@ -1118,6 +1141,17 @@ class SessionAuthority:from gateway.session_unattended_unknown import settle_unattended_unknownif await settle_unattended_unknown(self, ref):continue+ if exc.reason == 'admission_conflict':+ # A verdict on the head alone (its route or binding moved under it) that every drain+ # repeats: pausing behind it strands the FIFO for good. Refused only once the same head+ # conflicted twice, read after each: never a successor a cancel advanced the FIFO to.+ head = next((row['admission_id'] for row in list_session_admissions(+ self.db, session_id=ref.session_id) if row['status'] == 'queued'), None)+ if head is not None and head != conflicted:+ conflicted = head+ continue+ if head is not None and await self._refuse_head(ref, head, exc.reason):+ continueimport logginglogging.getLogger(__name__).warning('Session %s paused: %s', ref.session_id, exc.reason)self._pause(ref, exc.reason)diff --git a/gateway/session_local_recovery.py b/gateway/session_local_recovery.pyindex 0661918b215..66ea7e66e9d 100644--- a/gateway/session_local_recovery.py+++ b/gateway/session_local_recovery.py@@ -112,6 +112,16 @@ def owned_receipt(authority, sid):return receipt, source, route, _checked_entry(authority, receipt, source, route)+def unused_session(conn, session_id):+ """*session_id* holds nothing: no transcript, ledger rows or children (what the SessionStore's+ stale-route heal, #54878, mints as a route's replacement before any turn runs on it)."""+ return conn.execute(+ 'SELECT 1 FROM messages WHERE session_id=? UNION ALL SELECT 1 FROM session_admissions '+ 'WHERE target_session_id=? UNION ALL SELECT 1 FROM worker_executions WHERE session_id=? '+ 'UNION ALL SELECT 1 FROM sessions WHERE parent_session_id=? LIMIT 1',+ (session_id, session_id, session_id, session_id)).fetchone() is None++def _stray_route_target(authority, receipt, session_id):"""*session_id* is a replacement the SessionStore's stale-route self-heal minted on this localroute before #140642: outside the receipt's lineage, never admitted, no transcript. The receipt@@ -121,13 +131,8 @@ def _stray_route_target(authority, receipt, session_id):if not session_id or session_id in receipt.get('lineage', [receipt['session_id']]):return Falsewith authority.db._read_ctx() as conn:- busy = conn.execute(- 'SELECT 1 FROM messages WHERE session_id=? UNION ALL SELECT 1 FROM session_admissions '- 'WHERE target_session_id=? UNION ALL SELECT 1 FROM worker_executions WHERE session_id=? '- 'UNION ALL SELECT 1 FROM sessions WHERE parent_session_id=? LIMIT 1',- (session_id, session_id, session_id, session_id)).fetchone()- if busy is not None:- return False+ if not unused_session(conn, session_id):+ return Falselogging.getLogger(__name__).warning('Local route for %s named an empty replacement %s outside its lineage; restoring the receipt target',receipt['session_id'], session_id)@@ -191,10 +196,16 @@ def restore_local_session(authority, sid):else:with store._lock:current = store._entry_locked(route)- if current is None or (current.session_id not in receipt.get('lineage', [sid])- and not _stray_route_target(authority, receipt, current.session_id)):+ if current is None:+ # A route the loaded store cannot see (an older release's scope, a pruned row) is the+ # receipt's to rebuild, as on a cold restore: refusing wedges every claim until a restart.+ entry.origin = source+ store._entries[route] = entry+ elif (current.session_id not in receipt.get('lineage', [sid])+ and not _stray_route_target(authority, receipt, current.session_id)):raise RuntimeStoreError('admission_conflict')- current.session_id = target+ else:+ current.session_id = targetreturn SessionRef(authority.profile_id, sid)diff --git a/tests/gateway/test_api_route_heal_minted.py b/tests/gateway/test_api_route_heal_minted.pynew file mode 100644index 00000000000..ae81053001b--- /dev/null+++ b/tests/gateway/test_api_route_heal_minted.py@@ -0,0 +1,48 @@+"""An API route the stale-route heal (#54878) handed to an empty minted session goes back to its caller."""+from datetime import datetime+import json++import pytest++from gateway.config import Platform+from gateway.session import SessionEntry, SessionSource+from gateway.session_api import bind_api_session+from hermes_state_runtime import RuntimeStoreError+++def _mint_on_route(owner, caller):+ """What the heal leaves: a fresh session row owning the caller's API route."""+ store = owner.runner.session_store+ route = store._generate_session_key(SessionSource(platform=Platform.API_SERVER, chat_id=caller,+ user_id='api', chat_type='dm'))+ owner.db.create_session('minted', source='api_server')+ now = datetime.now()+ minted = SessionEntry(route, 'minted', now, now, platform=Platform.API_SERVER)+ owner.db._execute_write(lambda conn: conn.execute(+ "INSERT INTO gateway_routing(scope,session_key,entry_json,updated_at) VALUES('',?,?,0) "+ 'ON CONFLICT(scope,session_key) DO UPDATE SET entry_json=excluded.entry_json',+ (route, json.dumps(minted.to_dict()))))+ with store._lock:+ store._ensure_loaded_locked()+ store._entries[route] = minted+ return route++[email protected]('bound_before', [False, True])+def test_bind_takes_the_route_back_from_an_empty_minted_session(owner, bound_before):+ if bound_before:+ bind_api_session(owner, 'api-stable')+ route = _mint_on_route(owner, 'api-stable')++ bind_api_session(owner, 'api-stable')++ with owner.runner.session_store._lock:+ assert owner.runner.session_store._entries[route].session_id == 'api-stable'+++def test_bind_still_refuses_a_route_held_by_a_used_session(owner):+ _mint_on_route(owner, 'api-stable')+ owner.db.append_message('minted', 'user', 'a conversation of its own')++ with pytest.raises(RuntimeStoreError, match='admission_conflict'):+ bind_api_session(owner, 'api-stable')diff --git a/tests/gateway/test_local_live_route_heal.py b/tests/gateway/test_local_live_route_heal.pynew file mode 100644index 00000000000..af92a2e0912--- /dev/null+++ b/tests/gateway/test_local_live_route_heal.py@@ -0,0 +1,26 @@+"""A live local session whose route entry the loaded store cannot see rebuilds it from its receipt."""+import pytest++from tests.gateway.test_local_recovery_pre_profile_origin import _served_authority+++async def test_live_session_rebuilds_a_route_entry_missing_from_the_store(tmp_path, monkeypatch):+ from gateway.session_contract import Principal+ from gateway.session_local import create_local_session+ from gateway.session_local_recovery import restore_local_session+ from hermes_state_local import local_receipt++ served, db, secondary = await _served_authority(tmp_path, monkeypatch, 'first')+ actor = Principal('owner', str(secondary), frozenset({'session:create', 'session:read'}), 'socket')+ ref = create_local_session(served, actor, {'request_id': 'live', 'source': 'gui',+ 'cwd': str(tmp_path), 'model': 'frozen', 'toolsets': []})+ route = served.sessions[ref.session_id].route+ store = served.runner.session_store+ with store._lock:+ # A row under a scope the store never reads (an older release's ``''``), or one the prune retired.+ store._entries.pop(route)++ assert restore_local_session(served, ref.session_id) == ref+ with store._lock:+ assert store._entries[route].session_id == local_receipt(db, ref.session_id)['entry']['session_id']diff --git a/tests/gateway/test_preclaim_conflict_settles_head.py b/tests/gateway/test_preclaim_conflict_settles_head.pynew file mode 100644index 00000000000..144a43beac9--- /dev/null+++ b/tests/gateway/test_preclaim_conflict_settles_head.py@@ -0,0 +1,41 @@+"""A preclaim ``admission_conflict`` settles that head instead of pausing its FIFO for good."""+import asyncio++import pytest++from hermes_state_runtime import RuntimeStoreError, list_session_admissions+from tests.gateway.test_session_authority_cancel_settlement import REF, _authority, _submit+++async def test_conflicted_head_settles_with_its_refusal_and_the_successor_runs(tmp_path, monkeypatch):+ from gateway import session_api_turn, session_finite+ from gateway.config import Platform++ db, authority = _authority(tmp_path, monkeypatch, platform=Platform.API_SERVER)+ executed = []++ def check_api_turn(authority, ref, payload):+ if payload['text'] == 'stale':+ raise RuntimeStoreError('admission_conflict') # its route moved under it, on every drain+ monkeypatch.setattr(session_api_turn, 'check_api_turn', check_api_turn)++ async def execute(authority, ref, row):+ executed.append(row['payload']['text'])+ return 'done'+ monkeypatch.setattr(session_finite, 'execute_finite_admission', execute)++ with db:+ authority._schedule = lambda ref: None+ head = await _submit(authority, 'stale')+ await _submit(authority, 'follower')+ waiter = authority.waiters.setdefault(head.admission_id, asyncio.get_running_loop().create_future())+ del authority._schedule+ authority._schedule(REF)+ await asyncio.wait_for(authority.sessions['s'].task, 5)++ assert executed == ['follower']+ statuses = {r['request_id']: (r['status'], r['outcome'])+ for r in list_session_admissions(db, session_id='s', pending_only=False)}+ assert statuses == {'stale': ('terminal', 'cancelled'), 'follower': ('terminal', 'completed')}+ assert waiter.exception().reason == 'admission_conflict'diff --git a/tests/gateway/test_session_authority_returned_stop.py b/tests/gateway/test_session_authority_returned_stop.pynew file mode 100644index 00000000000..6f618ec595f--- /dev/null+++ b/tests/gateway/test_session_authority_returned_stop.py@@ -0,0 +1,39 @@+"""A Stop for a turn whose execution already returned never reaches the next turn's agent (#143290)."""+import asyncio+from types import SimpleNamespace++import pytest++from tests.gateway.test_session_authority_cancel_settlement import ACTOR, REF, _authority, _submit+++async def test_stop_while_the_finished_turn_settles_spares_the_next_turns_agent(tmp_path, monkeypatch):+ from gateway import session_finite, session_settlement_recovery++ db, authority = _authority(tmp_path, monkeypatch)+ stops = []+ next_agent = SimpleNamespace(interrupt=lambda *a, **k: stops.append('next'))+ # Own-agent runs (/v1/runs) install the next turn's agent on the route before it is claimed.+ authority.runner._running_agents = {'route': next_agent}+ authority.runner._resident_agent_for = lambda route: next_agent+ returned, settle = asyncio.Event(), asyncio.Event()+ settle_with_retry = session_settlement_recovery.settle_with_retry++ async def lagging_settlement(*args):+ returned.set()+ await asyncio.wait_for(settle.wait(), 5)+ return await settle_with_retry(*args)+ monkeypatch.setattr(session_settlement_recovery, 'settle_with_retry', lagging_settlement)+ monkeypatch.setattr(session_finite, 'execute_finite_admission',+ lambda authority, ref, row: asyncio.sleep(0, result='done'))++ with db:+ await _submit(authority, 'finished')+ await asyncio.wait_for(returned.wait(), 5)+ handle = authority._handle(REF)+ assert handle.execution_state == 'running' # the lagging settlement still reads as its claim+ await authority.interrupt(ACTOR, REF, handle.execution_generation)+ settle.set()+ await asyncio.wait_for(authority.sessions['s'].task, 5)+ assert stops == [], 'the Stop for the returned turn must not cancel the next one'