The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): latch a Stop accepted before the turn agent exists (X1, reported by @Xipong)
teknium14141c03f2f78
diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.pyindex 7dec32580db..a3c1e35c923 100644--- a/gateway/run_turn_runner.py+++ b/gateway/run_turn_runner.py@@ -269,6 +269,9 @@ class TurnRunner(GatewayTurnProgressMixin, GatewaySessionAgentMixin):# per platform so global scratch-text doesn't leak into threads).agent.thinking_progress = ctx._thinking_enabledctx.agent_holder[0] = agent # interrupt support+ if self._approval_owner is not None:+ authority, owner_id, generation = self._approval_owner+ authority.adopt_agent(owner_id, generation, agent)# The titler fires from the turn prologue, so attach the rename lane before the run.self._attach_session_title_callback(agent, ctx)# Publish turn ownership for /stop, /new, disconnect and shutdown interrupts; older sessiondiff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex 6e421f717ac..b442c821286 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -47,6 +47,9 @@ class SessionAuthority:self.events = {}self.native_waiters = set()self.pending_results = {}+ # 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 = {}def authorize(self, actor, ref, capability):if actor.profile_id != self.profile_id or ref.profile_id != self.profile_id:@@ -321,11 +324,23 @@ class SessionAuthority:handle = self._handle(ref)if handle.execution_generation != generation:raise RuntimeStoreError('stale_generation')- agent = self.agent(ref)- if agent is not None and handle.execution_state == 'running':- agent.interrupt()+ if handle.execution_state == 'running':+ agent = self.agent(ref)+ if agent is not None:+ agent.interrupt()+ else:+ # Accepted for this exact claim; the turn must not construct its agent+ # afterwards and run the work as if no Stop had arrived.+ self.pending_stops[ref.session_id] = generationreturn self._handle(ref)+ def adopt_agent(self, session_id, generation, agent):+ """The turn installs its agent for the running claim; a Stop latched while there+ was no agent to deliver it to fires now, never against a later generation."""+ if self.pending_stops.get(session_id) == generation:+ del self.pending_stops[session_id]+ agent.interrupt()+def check_approval_generation(self, session_id, generation):handle = self._handle(SessionRef(self.profile_id, session_id))if handle.execution_generation != generation or handle.execution_state != "running":@@ -450,6 +465,7 @@ class SessionAuthority:live.event_stream.publish(ref.session_id, {'text': response, 'content': response, 'admission_id': admission_id,'outcome': 'cancelled' if settled['outcome'] == 'interrupted' else settled['outcome']})+ self.pending_stops.pop(ref.session_id, None)waiter = self.waiters.pop(admission_id, None)if waiter is not None and not waiter.done():waiter.set_result(response)diff --git a/tests/gateway/test_session_authority_cancel_settlement.py b/tests/gateway/test_session_authority_cancel_settlement.pyindex c28d5226372..3c7ad79c372 100644--- a/tests/gateway/test_session_authority_cancel_settlement.py+++ b/tests/gateway/test_session_authority_cancel_settlement.py@@ -132,3 +132,64 @@ async def test_hosted_head_cancelled_during_preclaim_does_not_let_successor_skipassert validated == ['hosted:A', 'hosted:B']statuses = {r['request_id']: r['status'] for r in list_session_admissions(db, session_id='s', pending_only=False)}assert statuses == {'hosted:A': 'terminal', 'hosted:B': 'queued'}+++def _wire_turn_agent(authority, generation, agent):+ """Run the real per-turn agent wiring with this authority as the turn's approval owner."""+ from gateway.run_turn_runner import TurnRunner+ ctx = SimpleNamespace(+ progress_callback=None, native_tool_start_callback=None, voice_ack_callback=None,+ _voice_ack_guild=[None], _native_slack_task_cards=False, native_tool_complete_callback=None,+ _step_callback_sync=None, _hooks_ref=SimpleNamespace(loaded_hooks=[]), _status_callback_sync=None,+ _event_callback_sync=None, _status_adapter=None, session_key='route', user_config={},+ _thinking_enabled=False, agent_holder=[None], tools_holder=[None], process_task_id=None,+ process_baseline=None, run_generation=0)+ holder = SimpleNamespace(+ _ctx=ctx, _approval_owner=(authority, 's', generation),+ _runner=SimpleNamespace(_service_tier=None, _consume_pending_turn_sidecar_notes=lambda key: []),+ _make_bg_review_callbacks=lambda: (lambda message: None, lambda: None),+ _merge_turn_request_overrides=TurnRunner._merge_turn_request_overrides,+ _clarify_callback_sync=lambda *a, **k: None, _notice_callback_sync=lambda *a, **k: None,+ _attach_session_title_callback=lambda agent, ctx: None,+ combined_tool_start_callback=None, combined_tool_complete_callback=None)+ TurnRunner._wire_turn_agent_callbacks(holder, agent, {}, None, None, None, False)+++async def test_stop_before_the_turn_agent_exists_reaches_the_agent_once_it_is_wired(tmp_path, monkeypatch):+ from gateway import session_finite++ db, authority = _authority(tmp_path, monkeypatch)+ cache = {}+ authority.runner._cached_agent_for = cache.get+ agent = SimpleNamespace(interrupted=0)+ agent.interrupt = lambda *a, **k: setattr(agent, 'interrupted', agent.interrupted + 1)+ stopped = asyncio.Event()++ async def execute(authority, ref, row):+ # First turn: the claim is committed and message.start published, but agent+ # construction has not finished. Stop arrives in exactly this window.+ await asyncio.wait_for(stopped.wait(), 5)+ cache['route'] = agent+ _wire_turn_agent(authority, row['generation'], agent)+ return 'done'+ monkeypatch.setattr(session_finite, 'execute_finite_admission', execute)++ with db:+ await _submit(authority, 'first')+ task = authority.sessions['s'].task+ while authority._handle(REF).execution_state != 'running':+ await asyncio.sleep(0)+ handle = await authority.interrupt(ACTOR, REF, authority._handle(REF).execution_generation)+ assert handle.execution_state == 'running'+ stopped.set()+ await asyncio.wait_for(task, 5)+ assert agent.interrupted == 1, 'a Stop accepted for the running generation must reach its agent'++ # The latch belongs to that exact generation: the next turn's agent is not interrupted.+ agent.interrupted = 0+ with db:+ await _submit(authority, 'second')+ stopped.set()+ await asyncio.wait_for(authority.sessions['s'].task, 5)+ assert agent.interrupted == 0