fix(gateway): off-loop claim and admission keep the FIFO live under races
Follow-up to 951bb6e7d2e, found by the full gateway suite: - A drain whose claim transaction (now off-loop) read an empty FIFO exited idle even when input committed meanwhile through a path that takes no session mutation lock (API admit_api_turn + observe_api_turn's _schedule, automation): that _schedule saw the drain alive and did nothing, stranding the admission (test_api_idempotency_namespace hung, the API controls probe timed out). _schedule now sets LiveSession.rescan; the claim clears it before its transaction, and an idle claim with rescan set loops instead of exiting. - resolve_unknown's whole post-commit tail (pending_results, completion, media release, publication, schedule) runs inside the tracked write task (_resolved_unknown, async follow-ups supported by tracked_write), so a cancelled caller cannot drop the media release or the successor wakeup. - Two subprocess fixtures (native_ingress_media_peer capture, shared_authority_recovery prepare_crash) froze "commit, not yet claimed" by relying on admission never yielding; they now freeze the scheduling boundary explicitly (authority._schedule no-op) before the owner is killed. Their assertions are unchanged. Test: test_settlement_lock_liveness.py::test_input_admitted_while_an_idle_claim_is_in_flight_still_runs (an API-shaped admission commits while the claim's transaction reports idle): without the rescan 1 failed (`[] == ['late']`), with it passed. Review: https://github.com/NousResearch/hermes-agent/pull/106742#pullrequestreview-5475590057
This commit is contained in:
@@ -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 = True
|
||||
if 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_turn
|
||||
from 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 read
|
||||
row = 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), first
|
||||
|
||||
def _stamp_claim(self, ref, live, row):
|
||||
"""The claim's execution stamp, in the same tracked task as its commit: no observer (or
|
||||
|
||||
@@ -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``, 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."""
|
||||
@@ -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 followed
|
||||
return await asyncio.shield(track_mutation(authority, run()))
|
||||
|
||||
@@ -88,6 +88,9 @@ async def probe(mode, peer):
|
||||
assert not event._gateway_accepted
|
||||
finally:
|
||||
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: None
|
||||
receipt = await authority.admit_native(event)
|
||||
assert event._gateway_accepted
|
||||
saved = rows(receipt.ref.session_id)[0]
|
||||
|
||||
@@ -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: None
|
||||
accepted = 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,
|
||||
|
||||
@@ -175,3 +175,39 @@ async def test_submit_claim_and_discard_behind_a_held_writer_leave_the_loop_free
|
||||
assert (resolved.status, resolved.outcome) == ('terminal', 'interrupted')
|
||||
assert get_session_admission(db, admission_id=receipt.admission_id)['status'] == 'terminal'
|
||||
assert not mutation_tasks(authority)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
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']
|
||||
|
||||
Reference in New Issue
Block a user