Skip to content

The agent that grows with you

refactor(gateway): one per-route /stop and /new epoch, on the authority

Teknium432daa45333e
diff --git a/gateway/run_busy.py b/gateway/run_busy.py
index e20696b4b35..1ead45fc6cc 100644
--- a/gateway/run_busy.py
+++ b/gateway/run_busy.py
@@ -1232,12 +1232,11 @@ class GatewayBusySessionMixin:
return not (state is not None and state.conversation.one_turn_restore)
def _route_stop_epoch(self, session_key: str) -> int:
- """How many messaging /stop and /new reached *session_key* (``_hm_stop_owner_turn``)."""
- return (getattr(self, "_route_stop_epochs", None) or {}).get(session_key, 0)
-
- def _bump_route_stop_epoch(self, session_key: str) -> None:
- epochs = self.__dict__.setdefault("_route_stop_epochs", {})
- epochs[session_key] = epochs.get(session_key, 0) + 1
+ """How many messaging /stop and /new fenced *session_key*: the authority's one per-route epoch
+ (``fence_route``, bumped by ``_hm_stop_owner_turn``), shared with inputs still capturing."""
+ from gateway.session_authorities import active_authority
+ authority = active_authority(self)
+ return authority.route_epoch(session_key) if authority is not None else 0
@staticmethod
def _as_fifo_turn(event: MessageEvent, stop_epoch: int) -> MessageEvent:
diff --git a/gateway/run_inbound.py b/gateway/run_inbound.py
index 7cb57141dbd..0d32957d918 100644
--- a/gateway/run_inbound.py
+++ b/gateway/run_inbound.py
@@ -617,13 +617,13 @@ class GatewayInboundMixin(GatewayInboundHooksMixin, GatewayInboundTranscriptionM
``messaging:*`` rows of this route's logical owner first (automation wakes, LOCAL/API input
and ``unknown`` rows are untouched; settled silently, no pause notice), then interrupts the
claimed generation: a turn still constructing its agent latches the Stop for adopt_agent."""
- self._bump_route_stop_epoch(_quick_key) # a command's turn not committed yet never commits
from gateway.session_authorities import active_authority
authority = active_authority(self)
sid = authority.logical_owner(self.session_store.peek_session_id(_quick_key)) if authority else None
if not sid or sid not in authority.sessions:
if authority is not None:
- authority.fence_route(_quick_key) # the chat's first input, not committed yet
+ # The chat's first input, and a command's turn, not committed yet never commit.
+ authority.fence_route(_quick_key)
return
from gateway.session_contract import Principal, SessionRef
from hermes_state_runtime import RuntimeStoreError, list_session_admissions
@@ -635,8 +635,9 @@ class GatewayInboundMixin(GatewayInboundHooksMixin, GatewayInboundTranscriptionM
# promised the queued followers stay saved, so a /new from the chat leaves them queued.
paused = any(row['status'] == 'unknown' for row in rows)
if not paused:
- # Input that arrived before this and is not committed yet never commits after it; one
- # that committed before the fence is in the second listing and cancelled below.
+ # Input (and a command's turn) that arrived before this and is not committed yet never
+ # commits after it; one that committed before the fence is in the second listing and
+ # cancelled below. A paused FIFO keeps both, like its queued followers.
authority.fence_route(_quick_key)
rows = await asyncio.to_thread(list_session_admissions, authority.db, session_id=sid)
for row in [] if paused else rows:
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index 89b91b9364a..633ec706e55 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -137,6 +137,10 @@ class SessionAuthority:
self.rotated_owners = {}
# Route key -> [lock, holder + waiters, stop fence] of the native admissions in flight (``_route_turn``).
self._route_turns = {}
+ # Per route: how many messaging /stop and /new fenced it (``fence_route``). Kept for the
+ # owner's life (one int per chat that ever got one): an input or command turn holding an older
+ # value never commits, and a reset entry could read as an old epoch again.
+ self._route_epochs = {}
def authorize(self, actor, ref, capability):
"""Every handler calls this first, so a later ``self.sessions[ref.session_id]`` is
@@ -434,12 +438,12 @@ class SessionAuthority:
if key is None:
yield None
return
- entry = self._route_turns.setdefault(key, [asyncio.Lock(), 0, 0])
+ entry = self._route_turns.setdefault(key, [asyncio.Lock(), 0])
entry[1] += 1
- arrived = entry[2]
+ arrived = self.route_epoch(key)
def fence(_conn=None):
- if entry[2] != arrived:
+ if self.route_epoch(key) != arrived:
raise RuntimeStoreError('stale_generation', field='route',
detail='a /stop or /new of this chat came after this message')
if isinstance(ingress, asyncio.Future) and entry[1] > 1 and not ingress.done():
@@ -454,10 +458,14 @@ class SessionAuthority:
if not entry[1]:
del self._route_turns[key]
+ def route_epoch(self, route):
+ """How many messaging /stop and /new fenced *route* (``fence_route``)."""
+ return self._route_epochs.get(route, 0)
+
def fence_route(self, route):
- """/stop and /new: the route's messaging input still capturing or waiting never commits."""
- if (entry := self._route_turns.get(route)) is not None:
- entry[2] += 1
+ """/stop and /new: the route's messaging input still capturing or waiting, and a slash command's
+ turn read before it (``_stop_epoch``), never commit."""
+ self._route_epochs[route] = self.route_epoch(route) + 1
async def _admit_native(self, event, fence=None):
import json
diff --git a/tests/gateway/test_messaging_slash_command_fifo.py b/tests/gateway/test_messaging_slash_command_fifo.py
index 763f074ad50..364db355594 100644
--- a/tests/gateway/test_messaging_slash_command_fifo.py
+++ b/tests/gateway/test_messaging_slash_command_fifo.py
@@ -239,7 +239,7 @@ async def test_queued_turn_keeps_the_relay_callback(monkeypatch, command):
accepted, transport, home = [], object(), Path.cwd()
class Runner(GatewayBusySessionMixin):
- session_authority = object()
+ session_authority = SimpleNamespace(route_epoch=lambda route: 0)
def _peek_session_state(self, key):
return None
diff --git a/tests/gateway/test_native_admission_arrival_order.py b/tests/gateway/test_native_admission_arrival_order.py
index 7a97ec5ed4e..26a0f28f247 100644
--- a/tests/gateway/test_native_admission_arrival_order.py
+++ b/tests/gateway/test_native_admission_arrival_order.py
@@ -193,3 +193,30 @@ async def test_stop_fences_inputs_still_capturing_or_waiting(tmp_path, monkeypat
if task is not None:
task.cancel()
authority.db.close()
+
+
[email protected]('chat', ['existing', 'first-message', 'paused'])
+async def test_one_stop_epoch_per_route_fences_inputs_and_command_turns(tmp_path, monkeypatch, chat):
+ """/stop and /new bump ONE per-route epoch on the authority. A slash command's turn (``_stop_epoch``)
+ and an input still capturing read the same counter, so they are fenced under the same conditions:
+ both on a live or first-message chat, neither on a FIFO paused on a lost turn (it keeps its
+ followers). The counter outlives the route's FIFO entry, and the runner keeps no second one."""
+ authority, _entered, release, admit, route = await _held_owner(tmp_path, monkeypatch)
+ release.set()
+ runner = authority.runner
+ try:
+ if chat != 'first-message':
+ await admit(X, 'x0-text')
+ if chat == 'paused':
+ authority.db._execute_write(lambda conn: conn.execute(
+ "UPDATE session_admissions SET status='unknown' WHERE request_id='x0-text'"))
+ before = runner._route_stop_epoch(route(X))
+ assert before == authority.route_epoch(route(X))
+ await runner._hm_stop_owner_turn(route(X))
+ after = runner._route_stop_epoch(route(X))
+ assert after == authority.route_epoch(route(X)) == before + (chat != 'paused')
+ assert authority._route_turns == {} and runner._route_stop_epoch(route(Y)) == 0
+ assert not hasattr(runner, '_route_stop_epochs')
+ finally:
+ authority.db.close()