The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): admission, claim and Discard ledger writes run off the owner loop
Tekniumf2a717d8c604
diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex f8a075caeca..8cc157e4eb4 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -120,6 +120,15 @@ class SessionAuthority:if self.runner._draining or self.retiring:raise RuntimeStoreError('runtime_draining')+ def _admission_gate(self, authorize=None):+ """The admission gate re-checked inside an off-loop write transaction (with the caller's+ own guard), so a drain that began while the write waited on the writer still refuses it."""+ def guard(conn):+ self._require_admission_open()+ if authorize is not None:+ authorize(conn)+ return guard+def logical_owner(self, session_id):"""The FIFO/admission identity of a route: the root of its compression lineage.Compression advances the physical transcript, never the admission identity. A session this@@ -293,13 +302,25 @@ class SessionAuthority:ref = self.register(source)identity = json.dumps([source.profile, source.platform.value, source.chat_id,source.thread_id, source.user_id], separators=(',', ':'))+ from gateway.session_runtime_workers import tracked_writerequest_id = str(payload['native_text_v1']['event']['message_id'] or uuid.uuid4().hex)+ 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)++ 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+ # against, so a concurrent first delivery of the same message cannot slip between them.from gateway.session_ingress_media import reconcile_native_retry- payload = reconcile_native_retry(self.db, principal_id='messaging:' + identity, session_id=ref.session_id,+ payload = reconcile_native_retry(self.db, principal_id=principal_id, session_id=session_id,request_id=request_id, payload=payload)- row = admit_session_input(self.db, epoch=self.epoch, principal_id='messaging:' + identity,- session_id=ref.session_id, request_id=request_id, payload=payload)- event._gateway_accepted = True+ return admit_session_input(self.db, epoch=self.epoch, principal_id=principal_id, session_id=session_id,+ request_id=request_id, payload=payload, _authorize_write=authorize)++ def _admitted(self, ref, event, row):+ if event is not None:+ event._gateway_accepted = Trueself._publish_pending(ref)self._schedule(ref)return self._receipt(row)@@ -383,17 +404,17 @@ class SessionAuthority:payload['local_operator_v1'] = {'profile_id': self.profile_id, 'session_id': request.ref.session_id,'principal_id': actor.subject}- try:- row = admit_session_input(self.db, epoch=self.epoch, principal_id=actor.subject,- session_id=request.ref.session_id, request_id=request.request_id,- payload=payload, intent=request.intent,- _authorize_write=_authorize_write)- except Exception:- self._release_refused_capture(request, payload)- raise- self._publish_pending(request.ref)- self._schedule(request.ref)- return self._receipt(row)+ def admit():+ try:+ return admit_session_input(self.db, epoch=self.epoch, principal_id=actor.subject,+ session_id=request.ref.session_id, request_id=request.request_id,+ payload=payload, intent=request.intent,+ _authorize_write=self._admission_gate(_authorize_write))+ except Exception:+ 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)def _release_refused_capture(self, request, payload):"""A refused submission's captured bytes have no owner unless another admission holds the@@ -499,9 +520,15 @@ class SessionAuthority:# claimed with the discarded text left open to be merged into its request. With a captured# result the answer is normally already the transcript tail, so the closer is a no-op.from gateway.session_results import close_discarded_turn- row = 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))+ from gateway.session_runtime_workers import tracked_write+ row = 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)if prepared is not None and row['owner_epoch'] == self.epoch:# The captured result committed: viewers told the turn is unknown get its completion,@@ -516,14 +543,14 @@ class SessionAuthority:# Its own write txn + unlink, so it runs after the resolution commits; a discarded image# would otherwise stay on disk forever (the drain releases only settled turns).from gateway.session_ingress_media import release_admission_media- release_admission_media(self.db, admission_id)+ await asyncio.to_thread(release_admission_media, self.db, admission_id)# Before the successor can run: a committed captured answer reaches the chat it was# owed to (a turn fenced unknown already released its delivery waiter), exactly once.from gateway.session_ingress import deliver_resolvedawait deliver_resolved(self, admission_id, owed=prepared is not None and row['owner_epoch'] == self.epoch)self._publish_pending(ref)self._schedule(ref)- return self._receipt(row)+ return rowasync def interrupt(self, actor, ref, generation):self.authorize(actor, ref, 'session:control')@@ -655,9 +682,24 @@ class SessionAuthority:from gateway.session_api_turn import check_api_turncheck_api_turn(self, ref, first['payload'])self._require_admission_open()- row = claim_session_input(self.db, epoch=self.epoch, session_id=ref.session_id)+ from gateway.session_runtime_workers import tracked_write+ 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+ def _stamp_claim(self, ref, live, row):+ """The claim's execution stamp, in the same tracked task as its commit: no observer (or+ retirement's join) ever sees a committed claim that no execution stamp names."""+ if row is not None:+ with live.event_stream.lock:+ live.event_stream.execution = {+ 'authority_epoch': self.epoch, 'execution_generation': row['generation'],+ 'admission_id': row['admission_id']}+ live.event_stream.publish(ref.session_id, {}, event_type='message.start')+ self._publish_pending(ref)+ return row+async def _drain(self, ref):from gateway.session_finite import execute_finite_admissionfrom gateway.session_managed_worker import ManagedExecutionUnknown@@ -700,12 +742,6 @@ class SessionAuthority:end_idle_acp_session(self, ref.session_id)returnadmission_id = row['admission_id']- with live.event_stream.lock:- live.event_stream.execution = {- 'authority_epoch': self.epoch, 'execution_generation': row['generation'],- 'admission_id': admission_id}- live.event_stream.publish(ref.session_id, {}, event_type='message.start')- self._publish_pending(ref)try:response = await execute_finite_admission(self, ref, row)outcome = 'completed'diff --git a/gateway/session_automation.py b/gateway/session_automation.pyindex 86d890cb16f..1ddd6ecde4f 100644--- a/gateway/session_automation.py+++ b/gateway/session_automation.py@@ -4,7 +4,7 @@ Reuse the private native route envelope and FIFO, retaining nonhuman turn semantA producer ACK means committed input, not successful inference or outbound delivery."""from copy import deepcopy-from datetime import datetime, timezone+from datetime import UTC, datetimeimport jsonfrom gateway.config import Platform@@ -120,7 +120,7 @@ def snapshot_automation(authority, adapter, event, identity):# Producer timestamps and platform reply IDs change on retry. Neither belongs# in the identity/fingerprint of the same immutable completion.envelope = {'source': source, 'route': entry.session_key,- 'timestamp': datetime.fromtimestamp(0, timezone.utc).isoformat(),+ 'timestamp': datetime.fromtimestamp(0, UTC).isoformat(),'event': {'message_id': identity}, 'provenance': provenance,'automation': {'identity': identity, 'owner': owner}}envelope['automation'].update(notification)@@ -212,9 +212,9 @@ async def admit_automation(authority, adapter, event, identity):sid = (payload.get('local_automation_v1') or payload['native_text_v1']['automation'])['owner']ref = SessionRef(authority.profile_id, sid)authority.sessions.setdefault(ref.session_id, LiveSession(event.source, entry.session_key))- row = 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))- event._gateway_accepted = True- authority._publish_pending(ref)- authority._schedule(ref)- return authority._receipt(row)+ from functools import partial+ from gateway.session_runtime_workers import tracked_write+ 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)diff --git a/gateway/session_cron.py b/gateway/session_cron.pyindex e4354c2fac6..5a66109e241 100644--- a/gateway/session_cron.py+++ b/gateway/session_cron.py@@ -139,12 +139,13 @@ async def operation(authority, name, params, actor=None):# The job id, jobs file and gateway config belong to the OWNING profile.with owner_scope(authority):ref, request_id = _create(authority, actor, params)- row = 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 ''})- authority._publish_pending(ref)- authority._schedule(ref)- return {'session_id': ref.session_id, 'admission_id': row['admission_id']}+ from functools import partial+ from gateway.session_runtime_workers import tracked_write+ 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)+ 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')ref = SessionRef(authority.profile_id, params['session_id'])diff --git a/gateway/session_runtime_workers.py b/gateway/session_runtime_workers.pyindex a0525d111d2..21520da0b1d 100644--- a/gateway/session_runtime_workers.py+++ b/gateway/session_runtime_workers.py@@ -53,6 +53,33 @@ def track_mutation(authority, operation):return task+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+ 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."""+ order = getattr(authority, '_ordered_writes', None)+ if ordered and order is None:+ order = authority._ordered_writes = asyncio.Lock()++ async def run():+ if ordered:+ async with order:+ result = await asyncio.to_thread(write)+ else:+ 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()))++def start_turn_worker(runner, worker, agent_holder, run_sync):authority = track_turn_worker(runner, worker, agent_holder)worker.executor_task = asyncio.ensure_future(runner._run_in_executor_with_context(run_sync))diff --git a/hermes_state_runtime.py b/hermes_state_runtime.pyindex c47f8849004..24efb77bdfc 100644--- a/hermes_state_runtime.py+++ b/hermes_state_runtime.py@@ -149,9 +149,13 @@ def list_session_admissions(db, *, session_id: str, pending_only: bool = True) -return [_row(row) for row in conn.execute(sql, (session_id,))]-def claim_session_input(db, *, epoch: int, session_id: str) -> dict | None:+def claim_session_input(db, *, epoch: int, session_id: str, _guard=None) -> dict | None:+ """Claim the FIFO head. ``_guard(conn)`` (owner admission gate) raises to refuse inside the+ write transaction, so a drain that began while this waited on the writer still wins."""def write(conn):_epoch(conn, epoch)+ if _guard is not None:+ _guard(conn)session = _session(conn, session_id)blocked = conn.execute("SELECT status FROM session_admissions WHERE target_session_id=? AND status IN ('started','unknown')", (session_id,)).fetchall()if any(row[0] == 'unknown' for row in blocked):diff --git a/tests/gateway/test_session_authority_cancel_settlement.py b/tests/gateway/test_session_authority_cancel_settlement.pyindex b3752d4c878..75905e421b0 100644--- a/tests/gateway/test_session_authority_cancel_settlement.py+++ b/tests/gateway/test_session_authority_cancel_settlement.py@@ -124,8 +124,13 @@ async def test_hosted_head_cancelled_during_preclaim_does_not_let_successor_skipmonkeypatch.setattr(session_finite, 'execute_finite_admission', execute)with db:+ # Both rows are queued before the drain starts (admission commits off-loop, so the+ # first submit's drain would otherwise take the session lock before B is admitted).+ schedule, authority._schedule = authority._schedule, lambda ref: Nonehead = await _submit(authority, 'hosted:A')await _submit(authority, 'hosted:B')+ authority._schedule = schedule+ schedule(REF)await asyncio.get_running_loop().run_in_executor(None, head_checking.wait, 5)await authority.cancel_queued(ACTOR, REF, head.admission_id)release_head.set()diff --git a/tests/gateway/test_settlement_lock_liveness.py b/tests/gateway/test_settlement_lock_liveness.pyindex b921f373388..054a4fd6b3a 100644--- a/tests/gateway/test_settlement_lock_liveness.py+++ b/tests/gateway/test_settlement_lock_liveness.py@@ -121,3 +121,57 @@ async def test_cancel_behind_a_held_writer_leaves_the_loop_free_and_still_settlecancelled = 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+++def _hold_writer(tmp_path):+ """A second connection holds the state.db write lock for ``_HOLD_S`` (another process)."""+ 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()+ return released+++async def _loop_stays_free(tmp_path, operation):+ released = _hold_writer(tmp_path)+ ticks = []+ asyncio.get_running_loop().call_later(0.05, lambda: ticks.append(released.is_set()))+ task = asyncio.create_task(operation())+ await asyncio.sleep(0.3)+ assert ticks == [False], 'an unrelated 50 ms callback waited for the held writer'+ return await asyncio.wait_for(task, 10)+++async def test_submit_claim_and_discard_behind_a_held_writer_leave_the_loop_free(tmp_path, monkeypatch):+ """Admission, the FIFO claim and Discard wait on a held writer in a worker thread, tracked so+ retirement joins them; the claim's execution stamp still lands with its commit."""+ from gateway.session_runtime_workers import mutation_tasks+ from hermes_state_runtime import get_session_admission, recover_session_inputs, begin_runtime_epoch+ db, authority = _authority(tmp_path, monkeypatch)+ monkeypatch.setattr(authority, '_schedule', lambda ref: None)+ live = authority.sessions['s']+ with db:+ receipt = await _loop_stays_free(+ tmp_path, lambda: authority.submit(ACTOR, Submission('work', REF, {'text': 'work'}, 'queue')))+ assert receipt.status == 'queued' and not mutation_tasks(authority)+ row, first = await _loop_stays_free(tmp_path, lambda: authority._claim_next(REF, live))+ assert row['admission_id'] == first['admission_id'] == receipt.admission_id+ assert live.event_stream.execution == {'authority_epoch': authority.epoch,+ 'execution_generation': row['generation'],+ 'admission_id': row['admission_id']}+ # The owner restarts mid-turn; the operator discards the now-unknown turn.+ authority.epoch = begin_runtime_epoch(db, instance_id='restart')+ recover_session_inputs(db, epoch=authority.epoch)+ live.event_stream.execution = {}+ resolved = await _loop_stays_free(+ tmp_path, lambda: authority.resolve_unknown(ACTOR, REF, receipt.admission_id, row['generation']))+ assert (resolved.status, resolved.outcome) == ('terminal', 'interrupted')+ assert get_session_admission(db, admission_id=receipt.admission_id)['status'] == 'terminal'+ assert not mutation_tasks(authority)