Skip to content

The agent that grows with you

fix(gateway): a queued steer no drain of the turn consumed goes back to its queue

unsupportedpastelsbafd32849b1b
diff --git a/agent/interrupt_control.py b/agent/interrupt_control.py
index 06117c1c9ab..45f657e98f4 100644
--- a/agent/interrupt_control.py
+++ b/agent/interrupt_control.py
@@ -358,3 +358,17 @@ class InterruptControlMixin:
text = _ic_slot(self, "_pending_steer_lock", "_pending_steer")
self._pending_steer = None
return text
+
+ def withdraw_steer(self, text: str) -> bool:
+ """Take one earlier ``steer(text)`` back out of the buffer while no drain has consumed it (the
+ gateway returns a queued prompt's unconsumed steer to its queue). Other buffered steers stay."""
+ cleaned = (text or "").strip()
+ with _ic_lock(self, "_pending_steer_lock"):
+ pending = _ic_slot(self, "_pending_steer_lock", "_pending_steer")
+ framed = "\n" + (pending or "") + "\n"
+ index = framed.find("\n" + cleaned + "\n") if cleaned else -1
+ if index < 0:
+ return False
+ rest = (framed[:index] + framed[index + 1 + len(cleaned):]).strip("\n")
+ self._pending_steer = rest or None
+ return True
diff --git a/gateway/session_queued_controls.py b/gateway/session_queued_controls.py
index ed3becd6c82..85b1ef79196 100644
--- a/gateway/session_queued_controls.py
+++ b/gateway/session_queued_controls.py
@@ -66,12 +66,22 @@ async def _queued(connection, ref, admission_id):
def steer_transfers(authority, session_id, generation):
"""``{admission_id: delivered}`` handed to this claim; the caller holds the stream lock. Read by
- the claim's settlement after its execution returned, when no transfer can still be delivered."""
+ the claim's settlement after its execution returned, when no transfer can still be delivered.
+ A text its agent still buffers (accepted after the turn's last drain) never reached the claim: it
+ is withdrawn and reads undelivered, so its admission goes back to its queue place."""
entry = authority.steer_transfers.get(session_id)
- return dict(entry[1]) if entry is not None and entry[0] == generation else None
+ if entry is None or entry[0] != generation:
+ return None
+ adopted_generation, agent = authority.adopted.get(session_id, (None, None))
+ withdraw = getattr(agent, 'withdraw_steer', None) if adopted_generation == generation else None
+ for admission_id, delivered in entry[1].items():
+ if delivered and callable(withdraw) and withdraw(delivered):
+ entry[1][admission_id] = False
+ return {admission_id: bool(delivered) for admission_id, delivered in entry[1].items()}
def _register(authority, session_id, generation, admission_id):
+ """``{admission_id: False | accepted text}`` for the claim ``generation``."""
entry = authority.steer_transfers.get(session_id)
if entry is None or entry[0] != generation:
entry = authority.steer_transfers[session_id] = (generation, {})
@@ -102,8 +112,9 @@ def _deliver(authority, session_id, generation, agent, admission_id, text):
or _receiving_agent(authority, session_id, generation) is not agent):
return False
if not entry[1][admission_id]:
- entry[1][admission_id] = bool(agent.steer(text))
- return entry[1][admission_id]
+ # The accepted text itself: settlement withdraws it if no drain of the turn consumed it.
+ entry[1][admission_id] = text if agent.steer(text) else False
+ return bool(entry[1][admission_id])
async def steer_queued(connection, ref, params):
diff --git a/tests/agent/test_steer.py b/tests/agent/test_steer.py
index 95ff222dbd0..9f7faf069be 100644
--- a/tests/agent/test_steer.py
+++ b/tests/agent/test_steer.py
@@ -80,6 +80,23 @@ class TestSteerDrain:
assert agent._drain_pending_steer() == "hello"
assert agent._pending_steer is None
+ def test_withdraw_takes_back_one_unconsumed_steer_and_keeps_the_rest(self):
+ agent = _bare_agent()
+ for text in ("first", " two\nlines ", "last"):
+ agent.steer(text)
+ assert agent.withdraw_steer("two\nlines") is True
+ assert agent._pending_steer == "first\nlast"
+ assert agent.withdraw_steer("missing") is False
+ assert agent.withdraw_steer("first") is True
+ assert agent.withdraw_steer("last") is True
+ assert agent._pending_steer is None
+
+ def test_withdraw_after_a_drain_took_the_text_is_refused(self):
+ agent = _bare_agent()
+ agent.steer("hello")
+ assert agent._drain_pending_steer() == "hello"
+ assert agent.withdraw_steer("hello") is False
+
class TestActiveTurnRedirect:
diff --git a/tests/gateway/test_prompt_queued_transfer.py b/tests/gateway/test_prompt_queued_transfer.py
index 66d44332e7e..e1e937cfdb3 100644
--- a/tests/gateway/test_prompt_queued_transfer.py
+++ b/tests/gateway/test_prompt_queued_transfer.py
@@ -9,6 +9,7 @@ import time
import pytest
+from agent.interrupt_control import InterruptControlMixin
from gateway import session_finite, session_queued_controls
from gateway.session_contract import SessionRef
from hermes_state_runtime import (
@@ -79,6 +80,55 @@ async def test_a_steer_into_a_turn_that_then_fails_settles_interrupted_not_steer
assert turn.ran == ['running'], 'a steered prompt is never replayed on its own'
+class BufferedAgent(InterruptControlMixin):
+ """The real steer seam (``agent/interrupt_control.py``): ``steer`` only buffers the text, and the turn
+ takes it at its drains. A text no drain took is still buffered when the turn ends."""
+
+ def __init__(self):
+ self._pending_steer, self._pending_steer_lock = None, threading.Lock()
+
+ def clear_interrupt(self, *args, **kwargs):
+ return True
+
+
[email protected]('consumed', [True, False])
+async def test_a_steer_settles_steered_only_when_a_drain_of_the_turn_took_it(tmp_path, monkeypatch, consumed):
+ """Reviewer repro (late steer): the text entered the agent's buffer after the turn's last drain. That
+ claim never ran it, so it is not steered: the admission goes back to its FIFO place and runs once as
+ its own turn, and the cached agent no longer holds it for an unrelated later turn."""
+ db, authority = _authority(tmp_path, monkeypatch)
+ interactive(db)
+ agent, claimed, release, ran, taken, frames = BufferedAgent(), asyncio.Event(), asyncio.Event(), [], [], []
+
+ async def execute(authority, ref, row):
+ ran.append(row['payload']['text'])
+ authority.adopt_agent(ref.session_id, row['generation'], agent)
+ claimed.set()
+ await asyncio.wait_for(release.wait(), 30)
+ if consumed:
+ taken.append(agent._drain_pending_steer()) # the turn's next drain takes the text
+ return 'done'
+ monkeypatch.setattr(session_finite, 'execute_finite_admission', execute)
+ authority.sessions['s'].event_stream.observers.add(frames.append)
+ with db:
+ await _submit(authority, 'running')
+ await asyncio.wait_for(claimed.wait(), 30)
+ queued = await _submit(authority, 'follow-up')
+ reply = await _call(_connection(authority), 'prompt.steer_queued', admission_id=queued.admission_id)
+ assert 'error' not in reply, reply
+ release.set()
+ await _drained(authority)
+ assert agent._pending_steer is None, 'an unconsumed steer must not wait for an unrelated later turn'
+ if consumed:
+ assert (taken, ran) == (['follow-up'], ['running'])
+ assert _ledger(db) == [('running', 'terminal', 'completed'), ('follow-up', 'terminal', 'steered')]
+ else:
+ assert (queued.admission_id, 'steered') not in _completions(frames)
+ assert _ledger(db) == [('running', 'terminal', 'completed'), ('follow-up', 'terminal', 'completed')]
+ assert ran == ['running', 'follow-up'], 'the returned prompt runs once, as its own turn'
+
+
@pytest.mark.asyncio
async def test_a_turn_that_ends_between_the_steer_commit_and_delivery_gets_its_prompt_back(tmp_path, monkeypatch):
"""The receiving execution returns after the steer committed but before the text reached its agent: