fix(gateway): queued-input cancellation writes off the owner event loop

cancel_queued ran cancel_session_input and the media collection pass synchronously on the
owner loop. A Delete on a queued card (prompt.cancel) while another process held the
state.db writer therefore stalled every session for up to the write patience, the same
class as the settlement-lock stall.

Both writes now run in a worker thread. The commit and its observer settlement form one
tracked task shielded from the caller, so a client that disconnects mid-write cannot leave
a committed cancellation with unsettled waiters (profile retirement joins tracked work).
The obligation/exact-retry contract is unchanged.

Test: test_settlement_lock_liveness.py::test_cancel_behind_a_held_writer_... (real held
BEGIN IMMEDIATE writer, 50 ms loop-progress control): before 1 failed (callback ran only
after the writer released); after passed, the cancelled waiter still settles once.

Review: https://github.com/NousResearch/hermes-agent/pull/106742#pullrequestreview-5464152170
(cherry picked from commit 5d7351402c101c101817b76206d4dc9a164a469b)
This commit is contained in:
Teknium
2026-10-09 00:09:37 -07:00
parent 7fef5d8b6c
commit 9dadd0be5b
2 changed files with 42 additions and 6 deletions

View File

@@ -422,12 +422,23 @@ class SessionAuthority:
async def cancel_queued(self, actor, ref, admission_id):
before = await self.receipt(actor, ref, admission_id)
from gateway.session_runtime_workers import track_mutation
# Write off the shared loop; commit and observer settlement are one tracked task the
# caller cannot cancel between (an exact retry still pays a left-over obligation).
row = await asyncio.shield(track_mutation(self, self._commit_cancel(ref, admission_id, before)))
# Media collection is its own write txn after the committed, settled cancellation: its
# failure surfaces to the caller, and an exact retry collects again without re-settling.
from gateway.session_ingress_media import release_admission_media
await asyncio.to_thread(release_admission_media, self.db, admission_id)
return self._receipt(row)
async def _commit_cancel(self, ref, admission_id, before):
if before.status == 'queued':
# Owed from before the write: a commit that reports failure, or anything raising
# between the commit and observer settlement, leaves it for an exact retry to pay.
self.cancel_obligations.add(admission_id)
try:
row = cancel_session_input(self.db, epoch=self.epoch, admission_id=admission_id)
row = await asyncio.to_thread(cancel_session_input, self.db, epoch=self.epoch, admission_id=admission_id)
except RuntimeStoreError:
self.cancel_obligations.discard(admission_id) # a definite refusal: nothing committed
raise
@@ -437,11 +448,7 @@ class SessionAuthority:
if row['status'] != 'queued':
self.cancel_obligations.discard(admission_id)
self._publish_pending(ref)
# Media collection is its own write txn after the committed, settled cancellation: its
# failure surfaces to the caller, and an exact retry collects again without re-settling.
from gateway.session_ingress_media import release_admission_media
release_admission_media(self.db, admission_id)
return self._receipt(row)
return row
def _settle_cancelled(self, ref, admission_id):
# The only place a queued row becomes terminal: every observer kind that waits on

View File

@@ -92,3 +92,32 @@ async def test_pending_publication_during_a_contended_settlement_keeps_idle_afte
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
@pytest.mark.asyncio
async def test_cancel_behind_a_held_writer_leaves_the_loop_free_and_still_settles_its_observer(
tmp_path, monkeypatch):
"""``prompt.cancel`` / Delete on a queued card: its write waits on the writer, never on the loop."""
db, authority = _authority(tmp_path, monkeypatch)
monkeypatch.setattr(authority, '_schedule', lambda ref: None)
with db:
receipt = await authority.submit(ACTOR, Submission('queued', REF, {'text': 'queued'}, 'queue'))
waiter = authority.waiters.setdefault(receipt.admission_id, asyncio.get_running_loop().create_future())
released = threading.Event()
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()
ticks = []
asyncio.get_running_loop().call_later(0.05, lambda: ticks.append(released.is_set()))
cancel = asyncio.create_task(authority.cancel_queued(ACTOR, REF, receipt.admission_id))
await asyncio.sleep(0.3)
assert ticks == [False], 'an unrelated 50 ms callback waited for the held writer'
cancelled = await asyncio.wait_for(cancel, 10)
assert (cancelled.status, cancelled.outcome) == ('terminal', 'cancelled')
assert waiter.done() and receipt.admission_id not in authority.cancel_obligations