The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): a Stop before the claimed turn adopts its agent reaches the agent that runs it
Tekniumedc09f2421df
diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex 4a1ae1a5e53..10f3965671b 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -78,6 +78,10 @@ class SessionAuthority:# Stop can land on the session's reusable cached agent after that turn's finalizer# cleared it; the next generation's adopt_agent drops it instead of starting interrupted.self.delivered_stops = {}+ # session -> generation whose turn adopted its agent. Until then the resident+ # agent is the previous turn's cached one, which pre-turn compression or a changed agent+ # config replaces, so a Stop that only reached it would let the rebuilt agent run the turn.+ self.adopted = {}# Queued admissions whose cancellation may have committed before its observers settled.self.cancel_obligations = set()# Set by profile retirement (unserve): the drain claims no successor after its running turn.@@ -527,18 +531,27 @@ class SessionAuthority:if agent is not None:agent.interrupt()self.delivered_stops[ref.session_id] = generation- else:- # Accepted for this exact claim; the turn must not construct its agent- # afterwards and run the work as if no Stop had arrived.+ if self.adopted.get(ref.session_id) != generation 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] = generationreturn self._handle(ref)+ def _runs_own_agent(self, ref):+ """The route's running slot holds a real agent (not the claim's pending sentinel), so the+ Stop above reached the turn's own agent, not a cached one it may still replace."""+ from gateway.run import _AGENT_PENDING_SENTINEL+ running = getattr(self.runner, '_running_agents', None) or {}+ agent = running.get(self.sessions[ref.session_id].route)+ return agent is not None and agent is not _AGENT_PENDING_SENTINEL+def adopt_agent(self, session_id, generation, agent):"""The turn installs its agent for the running claim; a Stop latched while therewas no agent to deliver it to fires now, never against a later generation. A Stopdelivered to the cached agent for an earlier generation may have landed after thatturn's finalizer cleared it, so it is dropped rather than cancelling this turn. A managedworker is a fresh process per turn and carries no earlier flag to drop."""+ self.adopted[session_id] = generationclear = getattr(agent, 'clear_interrupt', None)if self.delivered_stops.pop(session_id, generation) != generation and clear is not None:clear()@@ -696,6 +709,7 @@ class SessionAuthority:with live.event_stream.lock:live.event_stream.execution = {}self.pending_stops.pop(ref.session_id, None)+ self.adopted.pop(ref.session_id, None)self._pause(ref, 'unknown_execution')returnexcept Exception:@@ -766,6 +780,7 @@ class SessionAuthority:with live.event_stream.lock:live.event_stream.execution = {}self.pending_stops.pop(ref.session_id, None)+ self.adopted.pop(ref.session_id, None)if settled is None:# Uncommitted (unknown or discarded): the user is not told an answer the FIFO lost.self.pending_deliveries.pop(admission_id, None)diff --git a/tests/gateway/test_session_authority_preadopt_stop.py b/tests/gateway/test_session_authority_preadopt_stop.pynew file mode 100644index 00000000000..a315640cb38--- /dev/null+++ b/tests/gateway/test_session_authority_preadopt_stop.py@@ -0,0 +1,56 @@+"""A Stop accepted before the claimed turn adopts its agent reaches the agent that turn runs."""+import asyncio++import pytest++from tests.gateway.test_session_authority_cancel_settlement import ACTOR, REF, _authority, _submit, _wire_turn_agent+++class Agent:+ def __init__(self):+ self.interrupted = False++ def interrupt(self, *args, **kwargs):+ self.interrupted = True++ def clear_interrupt(self, *args, **kwargs):+ self.interrupted = False+++async def test_stop_before_adoption_reaches_the_rebuilt_agent_not_only_the_stale_cached_one(tmp_path, monkeypatch):+ from gateway import session_finite++ db, authority = _authority(tmp_path, monkeypatch)+ stale, fresh = Agent(), Agent()+ cache = {'route': stale} # the previous turn's reusable agent+ authority.runner._cached_agent_for = cache.get+ claimed, stopped = asyncio.Event(), asyncio.Event()+ ran = {}++ async def execute(authority, ref, row):+ # Pre-turn hygiene: compression runs on the cached agent, then evicts it; the turn rebuilds.+ claimed.set()+ await asyncio.wait_for(stopped.wait(), 5)+ cache['route'] = fresh+ _wire_turn_agent(authority, row['generation'], fresh)+ ran[row['request_id']] = fresh.interrupted+ return 'done'+ monkeypatch.setattr(session_finite, 'execute_finite_admission', execute)++ with db:+ await _submit(authority, 'compressing')+ await asyncio.wait_for(claimed.wait(), 5)+ handle = await authority.interrupt(ACTOR, REF, authority._handle(REF).execution_generation)+ assert handle.execution_state == 'running'+ assert stale.interrupted, 'a resident agent (e.g. one compressing) still gets the Stop'+ stopped.set()+ await asyncio.wait_for(authority.sessions['s'].task, 5)+ assert ran['compressing'] is True, 'the agent the stopped turn adopts must start interrupted'++ # The latch was this generation's: the next turn on the same fresh agent runs normally.+ fresh.clear_interrupt()+ await _submit(authority, 'next')+ await asyncio.wait_for(authority.sessions['s'].task, 5)+ assert ran['next'] is False+ assert not authority.pending_stops