The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): a steer accepted before the turn adopts its agent reaches that agent
Tekniumb079061c2183
diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex 914dd088024..d1ee20c5e63 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -84,6 +84,9 @@ 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 = {}+ # session -> (generation, [steer text]) accepted before that generation adopted an agent;+ # adopt_agent hands it to that agent (never a later generation's), the drain drops the rest.+ self.pending_steers = {}# session -> generation of the last Stop delivered to a live agent. A repeated# 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.@@ -630,13 +633,19 @@ class SessionAuthority:delivered 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] = (generation, agent)- clear = getattr(agent, 'clear_interrupt', None)- if self.delivered_stops.pop(session_id, generation) != generation and clear is not None:- clear()- if self.pending_stops.get(session_id) == generation:- del self.pending_stops[session_id]- agent.interrupt()+ live = self.sessions.get(session_id)+ # The turn's executor thread runs this; the stream lock orders it against session.steer's latch.+ with live.event_stream.lock if live is not None else contextlib.nullcontext():+ self.adopted[session_id] = (generation, agent)+ clear = getattr(agent, 'clear_interrupt', None)+ if self.delivered_stops.pop(session_id, generation) != generation and clear is not None:+ clear()+ if self.pending_stops.get(session_id) == generation:+ del self.pending_stops[session_id]+ agent.interrupt()+ latched, steers = self.pending_steers.pop(session_id, (None, ()))+ for text in steers if latched == generation else ():+ agent.steer(text)def check_approval_generation(self, session_id, generation):handle = self._handle(SessionRef(self.profile_id, session_id))@@ -807,6 +816,7 @@ class SessionAuthority:with live.event_stream.lock:live.event_stream.execution = {}self.pending_stops.pop(ref.session_id, None)+ self.pending_steers.pop(ref.session_id, None)self.adopted.pop(ref.session_id, None)self._pause(ref, 'unknown_execution')return@@ -880,6 +890,7 @@ class SessionAuthority:with live.event_stream.lock:live.event_stream.execution = {}self.pending_stops.pop(ref.session_id, None)+ self.pending_steers.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.diff --git a/gateway/session_busy_controls.py b/gateway/session_busy_controls.pyindex 35082f25bb4..cb9b63f43d5 100644--- a/gateway/session_busy_controls.py+++ b/gateway/session_busy_controls.py@@ -111,6 +111,18 @@ async def yolo_config(connection, ref, params, write):return {'key': 'yolo', 'value': '1' if enabled else '0', 'scope': 'session'}+def _adopts_owner_agent(authority, ref):+ """The claimed turn runs an in-process owner agent, which adopt_agent hands latched steers to;+ a cron job or a managed worker has no steer seam, so a latch there would be acknowledged and lost."""+ from gateway.session_managed_worker import managed_policy+ from gateway.session_policy import policy_for_source+ try:+ policy = policy_for_source(authority.runner, authority.sessions[ref.session_id].source)+ return not (policy is not None and policy.source == 'cron') and managed_policy(authority, ref) is None+ except RuntimeStoreError:+ return False++async def correct(connection, ref, params, *, verb):if (set(params) - {'session_id', 'profile', 'text', 'execution_generation'}or not isinstance(params.get('text'), str) or not params['text'].strip()@@ -126,7 +138,19 @@ async def correct(connection, ref, params, *, verb):# agent. Refuse explicitly instead of acknowledging undeliverable text.if ref.session_id in getattr(authority, '_managed_workers', {}):raise RuntimeStoreError('unsupported_control')- agent = authority.agent(ref)+ adopted_generation, agent = authority.adopted.get(ref.session_id, (None, None))+ if adopted_generation != generation:+ # Before adoption the resident agent is the previous turn's cached one, which this+ # turn may replace: only a running slot holding a real agent is this turn's own.+ agent = authority.agent(ref) if authority._runs_own_agent(ref) else None+ if agent is None and verb == 'steer' and _adopts_owner_agent(authority, ref):+ # Accepted for this exact claim before its turn built an agent: adopt_agent hands it+ # to the agent this generation adopts (under this lock), never to a later one.+ latched, texts = authority.pending_steers.get(ref.session_id, (None, []))+ authority.pending_steers[ref.session_id] = (generation, [*texts, params['text']] if latched == generation+ else [params['text']])+ return {'status': 'queued', 'text': params['text'], 'execution_generation': generation,+ 'authority_epoch': authority.epoch}method = getattr(agent, verb, None)if not callable(method):raise RuntimeStoreError('execution_not_ready')diff --git a/tests/gateway/test_session_steer_before_adopt.py b/tests/gateway/test_session_steer_before_adopt.pynew file mode 100644index 00000000000..b4d5d0f53cd--- /dev/null+++ b/tests/gateway/test_session_steer_before_adopt.py@@ -0,0 +1,62 @@+"""A steer accepted while the claimed turn is still building its agent reaches that agent."""+import asyncio+from types import SimpleNamespace++import pytest++from agent.interrupt_control import InterruptControlMixin+from gateway.session_busy_controls import correct+from tests.gateway.test_session_authority_cancel_settlement import ACTOR, REF, _authority, _submit, _wire_turn_agent+++class Agent(InterruptControlMixin):+ def __init__(self):+ self._pending_steer = None+ self._interrupt_requested = False++ def interrupt(self, *args, **kwargs):+ self._interrupt_requested = True+++async def test_steer_before_adoption_reaches_the_rebuilt_agent_not_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; this turn rebuilds+ authority.runner._cached_agent_for = cache.get+ claimed, steered = asyncio.Event(), asyncio.Event()+ seen = {}++ async def execute(authority, ref, row):+ claimed.set()+ await asyncio.wait_for(steered.wait(), 5)+ fresh._pending_steer = None+ cache['route'] = fresh+ # The real per-turn wiring runs on the executor thread and calls adopt_agent.+ await asyncio.to_thread(_wire_turn_agent, authority, row['generation'], fresh)+ seen[row['request_id']] = fresh._drain_pending_steer()+ return 'done'+ monkeypatch.setattr(session_finite, 'execute_finite_admission', execute)++ connection = SimpleNamespace(authority=authority, actor=ACTOR)+ with db:+ await _submit(authority, 'building')+ await asyncio.wait_for(claimed.wait(), 5)+ generation = authority._handle(REF).execution_generation+ for text in ('use the staging db', 'and skip tests'):+ reply = await correct(connection, REF, {'session_id': 's', 'text': text,+ 'execution_generation': generation}, verb='steer')+ assert reply['status'] == 'queued'+ steered.set()+ await asyncio.wait_for(authority.sessions['s'].task, 5)+ assert seen['building'] == 'use the staging db\nand skip tests', 'the acknowledged steer was lost'+ assert stale._pending_steer is None, 'the replaced cached agent must not swallow it'++ # The latch was that generation's: the next turn's agent starts with nothing pending.+ await _submit(authority, 'next')+ steered.set()+ await asyncio.wait_for(authority.sessions['s'].task, 5)+ assert seen['next'] is None+ assert not authority.pending_steers