Skip to content

The agent that grows with you

fix(gateway): the claim takes only the head its preclaim checks validated

sprmn243a529a279b18
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index ec3b887265c..6f64116895a 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -698,8 +698,11 @@ class SessionAuthority:
self._require_admission_open()
from gateway.session_runtime_workers import tracked_write
live.rescan = False # a _schedule from here on may not be visible to this claim's read
+ # The row these checks validated, never whichever is first when the write runs: a
+ # cancellation commits from a worker thread and can advance the FIFO at any point.
row = await tracked_write(self, partial(claim_session_input, self.db, epoch=self.epoch,
- session_id=ref.session_id, _guard=self._admission_gate()),
+ session_id=ref.session_id, _guard=self._admission_gate(),
+ head=first['admission_id'] if first is not None else None),
then=partial(self._stamp_claim, ref, live))
# Input scheduled while this claim's transaction ran may postdate its read: re-read
# instead of letting the drain exit idle over a committed admission.
@@ -708,7 +711,7 @@ class SessionAuthority:
def _stamp_claim(self, ref, live, row):
"""The claim's execution stamp, in the same tracked task as its commit: no observer (or
retirement's join) ever sees a committed claim that no execution stamp names."""
- if row is not None:
+ if row: # None or False (the head changed under the write) claimed nothing
with live.event_stream.lock:
live.event_stream.execution = {
'authority_epoch': self.epoch, 'execution_generation': row['generation'],
diff --git a/hermes_state_runtime.py b/hermes_state_runtime.py
index 24efb77bdfc..cc6a246c3f7 100644
--- a/hermes_state_runtime.py
+++ b/hermes_state_runtime.py
@@ -149,9 +149,15 @@ def list_session_admissions(db, *, session_id: str, pending_only: bool = True) -
return [_row(row) for row in conn.execute(sql, (session_id,))]
-def claim_session_input(db, *, epoch: int, session_id: str, _guard=None) -> dict | None:
+_ANY_HEAD = object()
+
+
+def claim_session_input(db, *, epoch: int, session_id: str, _guard=None, head=_ANY_HEAD) -> dict | bool | None:
"""Claim the FIFO head. ``_guard(conn)`` (owner admission gate) raises to refuse inside the
- write transaction, so a drain that began while this waited on the writer still wins."""
+ write transaction, so a drain that began while this waited on the writer still wins.
+ ``head`` is the admission id the caller's preclaim checks validated (None: it saw nothing
+ queued); if the head is another row by the time this write runs, nothing is claimed and False
+ tells the caller to re-read and validate the row that is now first."""
def write(conn):
_epoch(conn, epoch)
if _guard is not None:
@@ -167,6 +173,8 @@ def claim_session_input(db, *, epoch: int, session_id: str, _guard=None) -> dict
if blocked or workers:
return None
row = conn.execute("SELECT * FROM session_admissions WHERE target_session_id=? AND status='queued' ORDER BY seq LIMIT 1", (session_id,)).fetchone()
+ if head is not _ANY_HEAD and (row['admission_id'] if row is not None else None) != head:
+ return False
if row is None:
return None
generation = session['runtime_generation'] + 1
diff --git a/tests/gateway/test_session_authority_cancel_settlement.py b/tests/gateway/test_session_authority_cancel_settlement.py
index 75905e421b0..e40517f0605 100644
--- a/tests/gateway/test_session_authority_cancel_settlement.py
+++ b/tests/gateway/test_session_authority_cancel_settlement.py
@@ -142,6 +142,59 @@ async def test_hosted_head_cancelled_during_preclaim_does_not_let_successor_skip
assert statuses == {'hosted:A': 'terminal', 'hosted:B': 'queued'}
+async def test_head_cancelled_after_its_last_preclaim_check_does_not_hand_the_claim_to_its_successor(
+ tmp_path, monkeypatch):
+ """Cancellation commits from a worker thread, so it can land after the head passed every preclaim
+ check (and was re-read as queued) while the off-loop claim waits for the writer: the claim takes
+ the validated head or nothing, never the successor."""
+ import threading
+ from gateway import session_authority, session_finite, session_hosted_transport, session_local_recovery
+ from gateway.config import Platform
+
+ db, authority = _authority(tmp_path, monkeypatch, platform=Platform.LOCAL)
+ monkeypatch.setattr(session_local_recovery, 'restore_local_session', lambda authority, sid: None)
+ monkeypatch.setattr(session_local_recovery, 'reopen_local_session', lambda authority, ref: None)
+ validated, executed = [], []
+ claim_waiting, head_cancelled = threading.Event(), threading.Event()
+
+ def check_remote_hosted_admission(authority, ref, row):
+ validated.append(row['request_id'])
+ if row['request_id'] == 'hosted:B':
+ raise RuntimeStoreError('permission_denied') # B's own source binding is revoked
+ return True
+ monkeypatch.setattr(session_hosted_transport, 'check_remote_hosted_admission', check_remote_hosted_admission)
+ claim = session_authority.claim_session_input
+
+ def claim_behind_the_cancellation(*args, **kwargs):
+ if not head_cancelled.is_set():
+ claim_waiting.set()
+ head_cancelled.wait(5)
+ return claim(*args, **kwargs)
+ monkeypatch.setattr(session_authority, 'claim_session_input', claim_behind_the_cancellation)
+
+ async def execute(authority, ref, row):
+ executed.append(row['request_id'])
+ return 'done'
+ monkeypatch.setattr(session_finite, 'execute_finite_admission', execute)
+
+ with db:
+ schedule, authority._schedule = authority._schedule, lambda ref: None
+ head = await _submit(authority, 'hosted:A')
+ await _submit(authority, 'hosted:B')
+ authority._schedule = schedule
+ schedule(REF)
+ assert await asyncio.get_running_loop().run_in_executor(None, claim_waiting.wait, 5)
+ await authority.cancel_queued(ACTOR, REF, head.admission_id)
+ head_cancelled.set()
+ await asyncio.wait_for(authority.sessions['s'].task, 5)
+
+ assert executed == [], 'the successor reached execution without its own hosted validation'
+ assert 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