Skip to content

The agent that grows with you

fix(gateway): an admission's drain starts in the admitting caller's step

Teknium390281f7d37c
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index 7c1361db924..ec3b887265c 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -315,7 +315,8 @@ class SessionAuthority:
return await tracked_write(self, partial(
self._admit_native_write, principal_id='messaging:' + identity, session_id=ref.session_id,
request_id=request_id, payload=payload, authorize=self._admission_gate()),
- then=partial(self._admitted, ref, event), ordered=True)
+ then=partial(self._admitted, ref, event), ordered=True,
+ after=partial(self._schedule_admitted, ref))
def _admit_native_write(self, *, principal_id, session_id, request_id, payload, authorize):
# Off the loop and in admission order: the redelivery reconcile reads the ledger it decides
@@ -330,9 +331,12 @@ class SessionAuthority:
if event is not None:
event._gateway_accepted = True
self._publish_pending(ref)
- self._schedule(ref)
return self._receipt(row)
+ def _schedule_admitted(self, ref, _receipt=None):
+ # tracked_write's ``after``: in the admitting caller's own step (see tracked_write).
+ self._schedule(ref)
+
async def recover_native_sessions(self, bindings):
"""Bind only server-observed native routes; unknown work stays paused."""
from collections import Counter
@@ -424,7 +428,8 @@ class SessionAuthority:
self._release_refused_capture(request, payload)
raise
from gateway.session_runtime_workers import tracked_write
- return await tracked_write(self, admit, then=partial(self._admitted, request.ref, None), ordered=True)
+ return await tracked_write(self, admit, then=partial(self._admitted, request.ref, None), ordered=True,
+ after=partial(self._schedule_admitted, request.ref))
def _release_refused_capture(self, request, payload):
"""A refused submission's captured bytes have no owner unless another admission holds the
diff --git a/gateway/session_automation.py b/gateway/session_automation.py
index 1ddd6ecde4f..60bdd726449 100644
--- a/gateway/session_automation.py
+++ b/gateway/session_automation.py
@@ -217,4 +217,5 @@ async def admit_automation(authority, adapter, event, identity):
return await tracked_write(authority, partial(
admit_session_input, authority.db, epoch=authority.epoch, principal_id='automation:' + entry.session_key,
session_id=ref.session_id, request_id=identity, payload=deepcopy(payload),
- _authorize_write=authority._admission_gate()), then=partial(authority._admitted, ref, event), ordered=True)
+ _authorize_write=authority._admission_gate()), then=partial(authority._admitted, ref, event), ordered=True,
+ after=partial(authority._schedule_admitted, ref))
diff --git a/gateway/session_cron.py b/gateway/session_cron.py
index 5a66109e241..a4d8d35543f 100644
--- a/gateway/session_cron.py
+++ b/gateway/session_cron.py
@@ -144,7 +144,8 @@ async def operation(authority, name, params, actor=None):
receipt = await tracked_write(authority, partial(
admit_session_input, authority.db, epoch=authority.epoch, principal_id=actor.subject,
session_id=ref.session_id, request_id=request_id, payload={'text': params['extra_prompt'] or ''},
- _authorize_write=authority._admission_gate()), then=partial(authority._admitted, ref, None), ordered=True)
+ _authorize_write=authority._admission_gate()), then=partial(authority._admitted, ref, None), ordered=True,
+ after=partial(authority._schedule_admitted, ref))
return {'session_id': ref.session_id, 'admission_id': receipt.admission_id}
if set(params) != {'session_id', 'admission_id'} or name not in {'status', 'cancel'}:
raise RuntimeStoreError('invalid_params')
diff --git a/gateway/session_runtime_workers.py b/gateway/session_runtime_workers.py
index e9be31d449c..3631888bab2 100644
--- a/gateway/session_runtime_workers.py
+++ b/gateway/session_runtime_workers.py
@@ -53,7 +53,7 @@ def track_mutation(authority, operation):
return task
-async def tracked_write(authority, write, then=None, *, ordered=False):
+async def tracked_write(authority, write, then=None, *, ordered=False, after=None):
"""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,
@@ -61,7 +61,13 @@ async def tracked_write(authority, write, then=None, *, ordered=False):
coroutine: publication, scheduling, the claim's execution stamp) are one task tracked like ``track_mutation``, so
retirement 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 threads
- alone would let a later input take an earlier FIFO position."""
+ alone would let a later input take an earlier FIFO position.
+
+ ``after(result)`` (an admission's drain scheduling) runs in the CALLER's own step once the
+ write returns, as it did when admission was synchronous: the caller registers its delivery
+ waiter before any drain it scheduled can claim, settle or pause that admission. A caller
+ cancelled while the commit is in flight hands ``after`` to the commit's completion instead,
+ so a committed row is never stranded without a drain."""
order = getattr(authority, '_ordered_writes', None)
if ordered and order is None:
order = authority._ordered_writes = asyncio.Lock()
@@ -76,7 +82,19 @@ async def tracked_write(authority, write, then=None, *, ordered=False):
return result
followed = then(result)
return await followed if asyncio.iscoroutine(followed) else followed
- return await asyncio.shield(track_mutation(authority, run()))
+ task = track_mutation(authority, run())
+ if after is None:
+ return await asyncio.shield(task)
+ try:
+ result = await asyncio.shield(task)
+ except asyncio.CancelledError:
+ def late(done):
+ if not done.cancelled() and done.exception() is None:
+ after(done.result())
+ task.add_done_callback(late)
+ raise
+ after(result)
+ return result
def start_turn_worker(runner, worker, agent_holder, run_sync):
diff --git a/tests/gateway/test_settlement_lock_liveness.py b/tests/gateway/test_settlement_lock_liveness.py
index e859fa8c505..4a5eadd68b4 100644
--- a/tests/gateway/test_settlement_lock_liveness.py
+++ b/tests/gateway/test_settlement_lock_liveness.py
@@ -11,7 +11,7 @@ import time
import pytest
from gateway.session_contract import Principal, Submission
-from tests.gateway.test_session_authority_cancel_settlement import ACTOR, REF, _authority
+from tests.gateway.test_session_authority_cancel_settlement import ACTOR, REF, _authority, _submit
_HOLD_S = 1.5
VIEWER = Principal('human', 'owned', frozenset({'session:read', 'session:submit'}), 'viewer')
@@ -211,3 +211,40 @@ async def test_input_admitted_while_an_idle_claim_is_in_flight_still_runs(tmp_pa
admitted.set()
await asyncio.wait_for(authority.sessions['s'].task, 10)
assert ran == ['late']
+
+
+async def test_admission_schedules_its_drain_in_the_admitting_callers_step(tmp_path, monkeypatch):
+ """The ledger write runs off-loop, but the drain is scheduled only once the caller holds its
+ receipt (the step in which messaging registers its delivery waiter), as it was when admission
+ was synchronous: a drain started inside the write task could claim, run or pause the input
+ before its waiter exists (a lost pause notice), and claim beside another drain's remote
+ authorization await. A caller cancelled mid-commit still leaves its committed input a drain."""
+ db, authority = _authority(tmp_path, monkeypatch)
+ order = []
+
+ async def drain():
+ order.append('drain')
+
+ def schedule(ref):
+ order.append('schedule')
+ asyncio.get_running_loop().create_task(drain())
+ monkeypatch.setattr(authority, '_schedule', schedule)
+ with db:
+ receipt = await _submit(authority, 'first')
+ order.append('caller') # where messaging registers its delivery waiter
+ await asyncio.sleep(0)
+ assert order == ['schedule', 'caller', 'drain'] and receipt.status == 'queued'
+
+ from gateway.session_runtime_workers import mutation_tasks
+ order.clear()
+ task = asyncio.ensure_future(_submit(authority, 'cancelled-mid-commit'))
+ while not mutation_tasks(authority):
+ await asyncio.sleep(0)
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ while mutation_tasks(authority):
+ await asyncio.sleep(0.01)
+ await asyncio.sleep(0)
+ assert order == ['schedule', 'drain']