Skip to content

The agent that grows with you

fix(gateway): a contended settlement write no longer stalls the owner event loop

Teknium7fef5d8b6c46
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index 3d9986193c4..0cef8896879 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -39,6 +39,11 @@ class LiveSession:
# preflight refusal), not per message; the drain clears it when the FIFO moves again.
pause_notified: bool = False
mutation_lock: asyncio.Lock = field(default_factory=asyncio.Lock)
+ # 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
+ # still see the claim as started, so no snapshot shows a terminal row without its completion.
+ settling: dict = field(default_factory=dict)
def __post_init__(self):
self.controls = PendingControls(self.event_stream)
@@ -137,9 +142,22 @@ class SessionAuthority:
lookup = getattr(self.runner, '_resident_agent_for', None) or self.runner._cached_agent_for
return lookup(self.sessions[ref.session_id].route)
+ def _pending_rows(self, ref):
+ """Pending admissions as the event stream presents them: a settlement committed but not yet
+ published (``LiveSession.settling``) still reads as its started claim. Callers that pair the
+ result with stream state hold ``event_stream.lock``, under which ``settling`` changes."""
+ rows = list_session_admissions(self.db, session_id=ref.session_id)
+ live = self.sessions.get(ref.session_id)
+ masked = dict(live.settling) if live is not None else {}
+ if not masked:
+ return rows
+ rows = {row['admission_id']: row for row in rows}
+ rows.update(masked)
+ return sorted(rows.values(), key=lambda row: row['seq'])
+
def _handle(self, ref):
row = self.db.get_session(ref.session_id)
- pending = list_session_admissions(self.db, session_id=ref.session_id)
+ pending = self._pending_rows(ref)
state = 'unknown' if any(r['status'] == 'unknown' for r in pending) else (
'running' if any(r['status'] == 'started' for r in pending) else 'idle')
return SessionHandle(ref, self.instance_id, self.epoch, row['runtime_revision'],
@@ -167,8 +185,7 @@ class SessionAuthority:
epoch, sequence = live.event_stream.watermark()
return SubscriptionSnapshot(subscription, handle, epoch,
sequence, tuple(local_history(self, ref)),
- tuple(self._pending_receipt(r) for r in list_session_admissions(
- self.db, session_id=ref.session_id)), prompts)
+ tuple(self._pending_receipt(r) for r in self._pending_rows(ref)), prompts)
def _retire_overflowed(self, session_id, transport):
"""The fanout dropped this peer's backlog: its subscription is over even though the
@@ -211,8 +228,7 @@ class SessionAuthority:
live = self.sessions[ref.session_id]
with live.event_stream.lock:
handle = self._handle(ref)
- pending = [asdict(self._pending_receipt(row)) for row in
- list_session_admissions(self.db, session_id=ref.session_id)]
+ pending = [asdict(self._pending_receipt(row)) for row in self._pending_rows(ref)]
# Turns bump runtime_revision without any session.updated event, so
# this is the only place a viewer learns the CAS revision a later
# prepared mutation must present.
@@ -397,6 +413,11 @@ class SessionAuthority:
raise RuntimeStoreError('not_found')
if row['principal_id'] != actor.subject and 'session:control' not in actor.capabilities:
raise RuntimeStoreError('permission_denied')
+ live = self.sessions[ref.session_id]
+ with live.event_stream.lock:
+ # Read after the row: a terminal row whose completion is not yet published reads as
+ # its claim, so a receipt poller never replays events that lack the completion frame.
+ row = live.settling.get(admission_id, row)
return self._receipt(row)
async def cancel_queued(self, actor, ref, admission_id):
diff --git a/gateway/session_settlement_recovery.py b/gateway/session_settlement_recovery.py
index fdfbb470470..95f3419eef8 100644
--- a/gateway/session_settlement_recovery.py
+++ b/gateway/session_settlement_recovery.py
@@ -60,38 +60,54 @@ def completion_payload(row, settled, response, captured):
def _publish_completion(authority, live, ref, row, settled, response, captured):
- """Thread-safe half of terminal publication; the caller holds the stream lock."""
+ """Thread-safe half of terminal publication; the caller holds the stream lock. No SQLite write
+ happens here: loop-side readers wait on this lock, so it never spans storage I/O."""
try:
live.controls.snapshot(ref.session_id, None)
except Exception:
logger.exception('Terminal control cleanup failed for admission %s', row['admission_id'])
+ live.event_stream.publish(ref.session_id, completion_payload(row, settled, response, captured))
+
+
+def _release_media(authority, row):
+ """Terminal media cleanup: its own write txn after publication, never under the stream lock."""
try:
from gateway.session_ingress_media import release_admission_media
release_admission_media(authority.db, row['admission_id'])
except Exception:
logger.exception('Terminal media cleanup failed for admission %s', row['admission_id'])
- live.event_stream.publish(ref.session_id, completion_payload(row, settled, response, captured))
def commit_and_publish(authority, live, ref, row, response, outcome, captured, settlement):
"""Worker-thread settlement: redaction, encoding and the SQLite write never stall the owner loop.
- The commit and its completion frame share one stream-lock hold, so replay/attach (which take
- that lock) never see the terminal row without its completion. ``settlement`` receives the
- committed ``(settled, response)`` before publication, so a publish failure is not a lost commit.
+ The write runs OUTSIDE ``event_stream.lock``: attach, replay, receipts and pending publication
+ take that lock on the loop, and a writer held by another process (up to ``_WRITE_PATIENCE_S``)
+ would stall every session behind it. Ordering is kept by ``live.settling``: from before the
+ write until the completion frame is published, lock holders read this claim as still started,
+ so none sees the terminal row without its completion. ``settlement`` receives the committed
+ ``(settled, response)`` before publication, so a publish failure is not a lost commit.
The caller publishes idle ``session.info`` on the loop afterwards (bot receipt wakeups are tasks).
"""
from gateway.session_results import finish_result, prepare_result
- # Compaction, redaction and outcome flags are CPU-only: outside the lock, which then
- # covers only the transaction and the completion frame.
+ # Compaction, redaction and outcome flags are CPU-only.
prepared = prepare_result(row, response, outcome, captured)
+ admission_id = row['admission_id']
# ``live`` is the drain's own entry: a delete committing on the loop after this write may
# already have dropped it from ``authority.sessions``.
with live.event_stream.lock:
+ live.settling[admission_id] = row
+ try:
settlement['settled'], settlement['response'] = finish_result(
authority.db, epoch=authority.epoch, row=row, response=response, outcome=outcome,
result=captured, prepared=prepared)
- _publish_completion(authority, live, ref, row, settlement['settled'], settlement['response'], captured)
+ with live.event_stream.lock:
+ live.settling.pop(admission_id, None)
+ _publish_completion(authority, live, ref, row, settlement['settled'], settlement['response'], captured)
+ finally:
+ with live.event_stream.lock:
+ live.settling.pop(admission_id, None)
+ _release_media(authority, row)
# Pauses between settlement attempts after a transient storage error (held writer past its
@@ -121,6 +137,9 @@ async def settle_with_retry(authority, live, ref, row, response, outcome, captur
def publish_terminal(authority, ref, row, settled, response, captured):
"""Cleanup cannot withhold a committed outcome; publication is attempted once."""
- _publish_completion(authority, authority.sessions[ref.session_id], ref, row, settled, response, captured)
+ live = authority.sessions[ref.session_id]
+ with live.event_stream.lock:
+ _publish_completion(authority, live, ref, row, settled, response, captured)
+ _release_media(authority, row)
# Idle follows the completion so a viewer cannot mistake a settled turn for a lost frame.
authority._publish_pending(ref)
diff --git a/tests/gateway/test_settlement_lock_liveness.py b/tests/gateway/test_settlement_lock_liveness.py
new file mode 100644
index 00000000000..47709eb5aa9
--- /dev/null
+++ b/tests/gateway/test_settlement_lock_liveness.py
@@ -0,0 +1,94 @@
+"""A settlement waiting on a contended SQLite writer never stalls the owner event loop.
+
+The settlement worker holds no stream lock across its write, so loop-side attach/replay/pending
+publication keep running; the commit still looks atomic with its completion frame to them.
+"""
+import asyncio
+import sqlite3
+import threading
+import time
+
+import pytest
+
+from gateway.session_contract import Principal, Submission
+from tests.gateway.test_session_authority_cancel_settlement import ACTOR, REF, _authority
+
+_HOLD_S = 1.5
+VIEWER = Principal('human', 'owned', frozenset({'session:read', 'session:submit'}), 'viewer')
+
+
+async def _settling_behind_a_held_writer(tmp_path, monkeypatch):
+ """Run a turn whose settlement write waits on a real competing SQLite writer."""
+ from gateway import session_results
+ db, authority = _authority(tmp_path, monkeypatch)
+ monkeypatch.setattr(authority, '_schedule', lambda ref: None)
+ frames, entered, released = [], threading.Event(), threading.Event()
+ authority.sessions['s'].event_stream.observers.add(frames.append)
+ settle = session_results.settle_session_input
+
+ def contended_settle(*args, **kwargs):
+ entered.set()
+ return settle(*args, **kwargs)
+ monkeypatch.setattr(session_results, 'settle_session_input', contended_settle)
+
+ async def execute(owner, ref, row):
+ owner.pending_results[row['admission_id']] = {'result': {'final_response': 'done'}, 'usage': {}}
+ # Another process holds the write lock while this turn settles.
+ writer = sqlite3.connect(str(tmp_path / 'state.db'), isolation_level=None, check_same_thread=False)
+ writer.execute('BEGIN IMMEDIATE')
+
+ def release():
+ time.sleep(_HOLD_S)
+ released.set()
+ writer.rollback()
+ writer.close()
+ threading.Thread(target=release, daemon=True).start()
+ return 'done'
+ monkeypatch.setattr('gateway.session_finite.execute_finite_admission', execute)
+ await authority.submit(ACTOR, Submission('work', REF, {'text': 'work'}, 'queue'))
+ drain = asyncio.create_task(authority._drain(REF))
+ while not entered.is_set():
+ await asyncio.sleep(0.01)
+ return db, authority, frames, released, drain
+
+
+def _types(frames):
+ return [(f['params']['type'], f['params']['payload'].get('running')) for f in frames]
+
+
+async def test_attach_during_a_contended_settlement_leaves_the_loop_free(tmp_path, monkeypatch):
+ db, authority, frames, released, drain = await _settling_behind_a_held_writer(tmp_path, monkeypatch)
+ with db:
+ ticks = []
+ asyncio.get_running_loop().call_later(0.05, lambda: ticks.append(released.is_set()))
+ attach = asyncio.create_task(authority.attach(VIEWER, REF))
+ await asyncio.sleep(0.3)
+ assert ticks == [False], 'an unrelated 50 ms callback waited for the held writer'
+ snapshot = await asyncio.wait_for(attach, 10)
+ await asyncio.wait_for(drain, 10)
+ # The snapshot still never shows the terminal row without its completion frame.
+ complete = next(f['params']['seq'] for f in frames if f['params']['type'] == 'message.complete')
+ if snapshot.handle.execution_state == 'idle':
+ assert snapshot.last_sequence >= complete
+ else:
+ assert snapshot.last_sequence < complete
+
+
+async def test_pending_publication_during_a_contended_settlement_keeps_idle_after_completion(
+ tmp_path, monkeypatch):
+ db, authority, frames, released, drain = await _settling_behind_a_held_writer(tmp_path, monkeypatch)
+ with db:
+ ticks = []
+ loop = asyncio.get_running_loop()
+ # A loop-side publisher (submit/cancel/automation call this) racing the settlement.
+ loop.call_later(0.02, authority._publish_pending, REF)
+ loop.call_later(0.05, lambda: ticks.append(released.is_set()))
+ await asyncio.sleep(0.3)
+ assert ticks == [False], 'pending publication waited for the held writer'
+ await asyncio.wait_for(drain, 10)
+ kinds = _types(frames)
+ start, complete = kinds.index(('message.start', None)), kinds.index(('message.complete', None))
+ assert ('session.info', False) not in kinds[start:complete], kinds
+ assert ('session.info', False) in kinds[complete:], kinds