The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): off-loop claim and admission keep the FIFO live under races
Tekniumcc4f8c6d7b71
diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex 51259b6882a..45a1ce768cf 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -43,6 +43,9 @@ class LiveSession:# ``mutation_lock``, so admissions are not parked behind an LLM call): no turn is claimed# under a compression that is still preparing its replacement transcript.claim_gate: asyncio.Lock = field(default_factory=asyncio.Lock)+ # Set by ``_schedule`` while a drain is alive. The claim commits off-loop, so input admitted+ # after its transaction read the FIFO would otherwise be stranded by a drain that exits idle.+ rescan: bool = False# admission id -> its started claim, from the moment the settlement worker starts the terminal# write until the completion frame is published. The write runs outside ``event_stream.lock``# (a contended SQLite writer must not stall loop-side lock takers); readers holding that lock@@ -261,6 +264,7 @@ class SessionAuthority:def _schedule(self, ref):live = self.sessions[ref.session_id]+ live.rescan = Trueif live.task is None or live.task.done():live.task = asyncio.create_task(self._drain(ref))live.task.add_done_callback(_log_drain_failure)@@ -525,12 +529,11 @@ class SessionAuthority:# result the answer is normally already the transcript tail, so the closer is a no-op.from gateway.session_results import close_discarded_turnfrom gateway.session_runtime_workers import tracked_write- row = await tracked_write(self, partial(+ return await tracked_write(self, partial(resolve_unknown_session_input, self.db, epoch=self.epoch, admission_id=admission_id,generation=generation, _captured=prepared,_terminal_write=lambda conn, lost: close_discarded_turn(self.db, conn, lost)),then=partial(self._resolved_unknown, ref, admission_id, prepared, captured))- return self._receipt(row)async def _resolved_unknown(self, ref, admission_id, prepared, captured, row):self.pending_results.pop(admission_id, None)@@ -554,7 +557,7 @@ class SessionAuthority:await deliver_resolved(self, admission_id, owed=prepared is not None and row['owner_epoch'] == self.epoch)self._publish_pending(ref)self._schedule(ref)- return row+ return self._receipt(row)async def interrupt(self, actor, ref, generation):self.authorize(actor, ref, 'session:control')@@ -687,10 +690,13 @@ class SessionAuthority:check_api_turn(self, ref, first['payload'])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 readrow = await tracked_write(self, partial(claim_session_input, self.db, epoch=self.epoch,session_id=ref.session_id, _guard=self._admission_gate()),then=partial(self._stamp_claim, ref, live))- return row, first+ # 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.+ return (False if row is None and live.rescan else row), firstdef _stamp_claim(self, ref, live, row):"""The claim's execution stamp, in the same tracked task as its commit: no observer (ordiff --git a/gateway/session_runtime_workers.py b/gateway/session_runtime_workers.pyindex 21520da0b1d..e9be31d449c 100644--- a/gateway/session_runtime_workers.py+++ b/gateway/session_runtime_workers.py@@ -57,8 +57,8 @@ async def tracked_write(authority, write, then=None, *, ordered=False):"""Run a synchronous ledger write (``write()``) in a worker thread, off the owner loop.A held SQLite writer (``_WRITE_PATIENCE_S``) must not freeze every session, timer, socket,- Stop and approval. The write and its loop-side follow-up (``then(result)``: publication,- scheduling, the claim's execution stamp) are one task tracked like ``track_mutation``, so+ Stop and approval. The write and its loop-side follow-up (``then(result)``, sync or a+ coroutine: publication, scheduling, the claim's execution stamp) are one task tracked like ``track_mutation``, soretirement joins it, and shielded, so a cancelled caller cannot separate a commit from it.``ordered`` writes (admissions) commit in call order, as they did on the loop: worker threadsalone would let a later input take an earlier FIFO position."""@@ -74,7 +74,6 @@ async def tracked_write(authority, write, then=None, *, ordered=False):result = await asyncio.to_thread(write)if then is None:return result- # An async follow-up (Discard's delivery) runs inside the same tracked task, before it ends.followed = then(result)return await followed if asyncio.iscoroutine(followed) else followedreturn await asyncio.shield(track_mutation(authority, run()))diff --git a/tests/gateway/fixtures/native_ingress_media_peer.py b/tests/gateway/fixtures/native_ingress_media_peer.pyindex 8288520780a..a161731593f 100644--- a/tests/gateway/fixtures/native_ingress_media_peer.py+++ b/tests/gateway/fixtures/native_ingress_media_peer.py@@ -88,6 +88,9 @@ async def probe(mode, peer):assert not event._gateway_acceptedfinally:digest_dir.unlink()+ # Capture only admits (the owner is killed below with media-1 still queued and the second+ # row claimed here). Admission commits off-loop, so a drain would otherwise run first.+ authority._schedule = lambda ref: Nonereceipt = await authority.admit_native(event)assert event._gateway_acceptedsaved = rows(receipt.ref.session_id)[0]diff --git a/tests/gateway/fixtures/shared_authority_recovery.py b/tests/gateway/fixtures/shared_authority_recovery.pyindex 1fec4318b05..f4eb769fdec 100644--- a/tests/gateway/fixtures/shared_authority_recovery.py+++ b/tests/gateway/fixtures/shared_authority_recovery.py@@ -61,9 +61,10 @@ async def prepare_crash(runner, adapter, source, peer):# reading); the follower itself stays queued behind the started head until the crash.await asyncio.wait_for(follower, 5)assert [r['status'] for r in rows(authority, sid) if r['request_id'] == 'unknown-follower'] == ['queued']- # Production trusted ingress commits synchronously before its first execution- # yield. Freeze THIS scheduling boundary, not a claim/storage predicate.+ # Trusted ingress commits before it schedules execution. Freeze THIS scheduling boundary,+ # not a claim/storage predicate: the owner dies with the safe row committed and unclaimed.safe_source = replace(source, chat_id='recover-chat', thread_id='recover-thread')+ authority._schedule = lambda ref: Noneaccepted = await authority.admit_native(MessageEvent(text='RECOVER_EXACTLY_ONCE', source=safe_source,message_id='crash-queued', reply_to_message_id='quote-7'))evidence = {'blocked_sid': sid, 'safe_sid': accepted.ref.session_id,diff --git a/tests/gateway/test_settlement_lock_liveness.py b/tests/gateway/test_settlement_lock_liveness.pyindex 054a4fd6b3a..e859fa8c505 100644--- a/tests/gateway/test_settlement_lock_liveness.py+++ b/tests/gateway/test_settlement_lock_liveness.py@@ -175,3 +175,39 @@ async def test_submit_claim_and_discard_behind_a_held_writer_leave_the_loop_freeassert (resolved.status, resolved.outcome) == ('terminal', 'interrupted')assert get_session_admission(db, admission_id=receipt.admission_id)['status'] == 'terminal'assert not mutation_tasks(authority)+++async def test_input_admitted_while_an_idle_claim_is_in_flight_still_runs(tmp_path, monkeypatch):+ """The claim's transaction runs off-loop: an admission that commits after it read an empty+ FIFO must not be stranded by the drain exiting idle (its ``_schedule`` saw the drain alive)."""+ from gateway import session_authority as sa+ db, authority = _authority(tmp_path, monkeypatch)+ ran, read_empty, admitted = [], threading.Event(), threading.Event()+ claim = sa.claim_session_input++ def racing_claim(*args, **kwargs):+ row = claim(*args, **kwargs)+ if row is None and not read_empty.is_set():+ read_empty.set()+ admitted.wait(5) # the submit commits and schedules while this claim reports idle+ return row+ monkeypatch.setattr(sa, 'claim_session_input', racing_claim)++ async def execute(owner, ref, row):+ ran.append(row['request_id'])+ owner.pending_results[row['admission_id']] = {'result': {'final_response': 'done'}, 'usage': {}}+ return 'done'+ monkeypatch.setattr('gateway.session_finite.execute_finite_admission', execute)+ with db:+ authority._schedule(REF)+ assert await asyncio.to_thread(read_empty.wait, 5)+ # The API path's shape (admit_api_turn, then observe_api_turn's _schedule): it takes no+ # session mutation lock, so it can commit while the claim's transaction is in flight.+ from hermes_state_runtime import admit_session_input+ admit_session_input(db, epoch=authority.epoch, principal_id='api', session_id='s',+ request_id='late', payload={'text': 'late'})+ authority._schedule(REF)+ admitted.set()+ await asyncio.wait_for(authority.sessions['s'].task, 10)+ assert ran == ['late']