The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(bot): publish local receipts with cancellation-safe mailbox ownership
David Dudok de Witcca52ed3a48a
diff --git a/gateway/platforms/api_server_bot_chat.py b/gateway/platforms/api_server_bot_chat.pyindex 38eca94ff8c..6826f260ad4 100644--- a/gateway/platforms/api_server_bot_chat.py+++ b/gateway/platforms/api_server_bot_chat.py@@ -80,11 +80,13 @@ async def await_peer_receipt(authority, record, timeout, *, should_stop=None):loop = asyncio.get_running_loop()deadline = None if timeout is None else loop.time() + timeoutwhile True:- live, interim = peer_wait_admission(authority, record)+ live, interim = await asyncio.to_thread(peer_wait_admission, authority, record)# Register the waiter BEFORE re-reading: a settle between the two either shows in the read# or resolves this future; a settle before both would otherwise leave a future nobody pops.waiter = None if live is None or interim else authority.waiters.setdefault(live, loop.create_future())current = _receipt(authority, record)+ if live is None and current['status'] in _PENDING:+ continue # The derived retry committed while the receipt was being read.if interim:current['status'] = 'claimed' # the retry is being admittedif live is None or current['status'] not in _PENDING or (should_stop is not None and should_stop()):diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex 178bb02f316..f937012635c 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -210,6 +210,8 @@ class SessionAuthority:'execution_generation': handle.execution_generation,'revision': handle.revision,}, event_type='session.info')+ from gateway.session_bot_mailbox import wake_bot_receipts+ wake_bot_receipts(self, ref.session_id)def _schedule(self, ref):live = self.sessions[ref.session_id]diff --git a/gateway/session_bot.py b/gateway/session_bot.pyindex 7c0a3cd7775..3a0feb23ce1 100644--- a/gateway/session_bot.py+++ b/gateway/session_bot.py@@ -13,7 +13,9 @@ from gateway.session_contract import Principal, SessionReffrom gateway.config import Platformfrom gateway.platforms.event import MessageEventfrom hermes_state_runtime import RuntimeStoreError, get_session_admission-from tools.bot_live_delivery import _delivery_id, _locked, _read, _root, _write+from tools.bot_live_delivery import _delivery_id, _read+from gateway.session_bot_mailbox import (mailbox_lock, read_receipt, write_receipt,+ scan_receipts, remember_receipt, track_receipt_task)_CANONICAL_RECEIPT_STATUSES = frozenset({@@ -164,10 +166,6 @@ def _result(authority, record):status, reply = _admission_outcome(authority, retry_id)else:status, reply = _admission_outcome(authority, record['admission_id'], record)- if status == 'failed' and _retry_due(authority, record):- # Interim, never the answer: the one retry is admitted next (or by the restarted- # owner's recovery while this one drains). Senders poll the published receipt file.- status = 'claimed'error = reason = Noneif status == 'failed':error, reason = _failure(authority, current)@@ -188,65 +186,33 @@ def _failure(authority, admission_id):return error, classify_agent_error(turn_failure_text(saved.get('error'), saved.get('failure_reason')) or error)+def _delivery_result(authority, record):+ result = _result(authority, record)+ if result['status'] == 'failed' and _retry_eligible(authority, record):+ result['status'] = 'claimed' # owner receipt writer still owes the one allowed retry+ return result++def peer_wait_admission(authority, record):"""``(admission_id, interim)`` a live waiter must follow; ``(None, False)`` once the deliverysettled for good. The retry, once admitted, is the only admission whose future fires again.An original that failed while its one retry is still eligible is ``interim``: pending, neverthe answer, while the owner's receipt task admits the retry (or records why it would not;the receipt file is re-read for that, the caller's in-memory record is stale)."""+ from tools.bot_live_delivery import read_delivery_resultretry_id = _retry_admission(authority, record)if retry_id:return (retry_id, False) if _admission_outcome(authority, retry_id)[0] in {'queued', 'claimed'} else (None, False)status = _admission_outcome(authority, record['admission_id'], record)[0]if status in {'queued', 'claimed'}:return record['admission_id'], False- if status == 'failed' and _retry_due(authority, record):- return record['admission_id'], True+ if status == 'failed':+ saved = read_delivery_result(record['profile_home'], record['delivery_id']) or record+ if _retry_eligible(authority, {**record, 'retry': saved.get('retry')}):+ return record['admission_id'], Truereturn None, False-def _retry_due(authority, record):- """The failed original's one retry is still to be admitted. Its refusal is recorded on the- receipt file; an in-memory record without the ``retry`` marker re-reads it there."""- retry = record.get('retry')- if retry is None:- retry = (_read(_root(record['profile_home']) / f"{record['delivery_id']}.json") or {}).get('retry')- return _retry_eligible(authority, {**record, 'retry': retry})---_UNCHECKED = object()---def _store(home, record, *, expect=_UNCHECKED):- """Pin a receipt another process may still move (a new or legacy ticket) under the- cross-process mailbox lock, held for this one write: never across an admission, a FIFO wait or- a recovery scan, and taken off-loop (``asyncio.to_thread``). ``expect`` (the status read before,- None = absent) makes it a compare-and-set that refuses when another writer moved the ticket- first, e.g. a DM runner's ``cancel_queued_delivery``."""- with _locked(home) as root:- path = root / f"{record['delivery_id']}.json"- if expect is not _UNCHECKED and (_read(path) or {}).get('status') != expect:- return False- _write(path, record)- return True---def _publish(home, record):- """Republish a pinned receipt in place. Once pinned (``ambiguous`` → canonical) only this owner- writes it, and every foreign writer refuses it, so an atomic rename needs no cross-process lock;- publishing in the same step the admission settles keeps the file ahead of any reply."""- _write(_root(home) / f"{record['delivery_id']}.json", record)---def _mailbox_order(authority):- """Orders this owner's read-admit-publish sequences per receipt in-process. An asyncio lock:- a contender yields to the event loop instead of blocking it on the file lock."""- order = getattr(authority, '_bot_mailbox_order', None)- if order is None:- order = authority._bot_mailbox_order = asyncio.Lock()- return order--def _retry_identity(key):return 'bot:' + key + ':retry'@@ -269,7 +235,7 @@ def _retry_eligible(authority, record):return result_retry_action(saved['result']) != RETRY_NONE-async def _maybe_retry(authority, home, record):+async def _maybe_retry(authority, home, path, record):"""Admit the delivery's one retry under a DERIVED identity recorded on the same receipt, so arepeated deliver(), an owner restart or a second settle re-reads that admission instead ofminting another. The identity is written before the admission: a death in that two-store window@@ -295,10 +261,12 @@ async def _maybe_retry(authority, home, record):raise RuntimeStoreError('open_user_tail')except RuntimeStoreError as exc:if exc.reason == 'runtime_draining':- return # nothing recorded: the restarted owner's recovery re-evaluates the same gate+ # No retry was attempted. Keep the local projection pending until startup recovery+ # can perform the same derived retry, rather than exposing an interim failure.+ record.update(status='claimed', reply='')+ returnrecord['retry'] = {'identity': identity, 'refused': exc.reason}- record.update(_result(authority, record)) # the refusal makes the original's failure final- _publish(home, record)+ await write_receipt(home, record)returnevent = MessageEvent(text=record['message'], source=live.source, internal=True,message_id=identity, metadata={'gateway_session_key': live.route, 'gateway_session_id': entry.session_id})@@ -307,29 +275,47 @@ async def _maybe_retry(authority, home, record):if record.get('author') is not None:event.metadata['turn_author'] = dict(record['author'])record['retry'] = {'identity': identity}- _publish(home, record)+ record.update(status='queued', reply='')+ await write_receipt(home, record)receipt = await authority.admit_automation(authority.runner._adapter_for_source(live.source), event, identity)record.update(_result(authority, record))- if receipt.status in {'queued', 'started'}:+ if record['status'] in {'queued', 'claimed'}:_watch_reply(authority, home, record['delivery_id'], receipt.admission_id)- _publish(home, record)+ await write_receipt(home, record)+ remember_receipt(authority, home, record)async def _record_reply(authority, home, key, future):+ paused = Falsetry:await asyncio.shield(future)except RuntimeStoreError:- # A paused FIFO is not a terminal Bot outcome; project the durable state below.- pass- async with _mailbox_order(authority):- record = _read(_root(home) / f'{key}.json')+ # A paused FIFO is still queued/unknown. Project that durable state;+ # never turn a wakeup refusal into a failed delivery or a fresh retry.+ paused = True+ async with mailbox_lock(authority):+ root, record = await read_receipt(home, key)+ if record is None:+ return+ path = root / f'{key}.json'record.update(_result(authority, record))- _publish(home, record)- admission_id, interim = peer_wait_admission(authority, record)- if admission_id is not None and not interim:- _watch_reply(authority, home, key, admission_id)+ if not paused:+ await _maybe_retry(authority, home, path, record)+ await write_receipt(home, record)+ remember_receipt(authority, home, record)+++async def refresh_receipt(authority, home, key):+ async with mailbox_lock(authority):+ root, record = await read_receipt(home, key)+ if record is None:return- await _maybe_retry(authority, home, record)+ record.update(_result(authority, record))+ if record['status'] in {'queued', 'claimed'}:+ _watch_reply(authority, home, key, record.get('retry_admission_id') or record['admission_id'])+ await _maybe_retry(authority, home, root / f'{key}.json', record)+ await write_receipt(home, record)+ remember_receipt(authority, home, record)def relay_operation(connection, operation, params):@@ -357,7 +343,7 @@ def relay_operation(connection, operation, params):async def _migrate(authority, actor, home, root):- records = list(_scan_records(root))+ root, records = await scan_receipts(home)legacy = [(path, record) for path, record in recordsif record and 'owner' in record and not record.get('admission_id')and record['status'] in {'queued', 'claimed'}]@@ -375,8 +361,8 @@ async def _migrate(authority, actor, home, root):if active:raise RuntimeStoreError('runtime_coordination_required')if record['status'] == 'claimed':- await asyncio.to_thread(_store, home, dict(record, status='ambiguous', reason='unknown_execution'),- expect='claimed')+ record.update(status='ambiguous', reason='unknown_execution')+ await write_receipt(home, record, expect='claimed')continueawait _admit(authority, actor, home, root, _delivery_id(record['delivery_id']),record['message'], ref, live, entry, author=parse_turn_author(record.get('author')), legacy=record,@@ -386,19 +372,19 @@ async def _migrate(authority, actor, home, root):async def recover_bot_deliveries(authority):"""Rebuild derivative replies and queued legacy admissions at owner startup."""home = Path(authority.db.db_path).parent.resolve()- root = _root(home)- async with _mailbox_order(authority):- records = list(_scan_records(root))+ async with mailbox_lock(authority):+ root, records = await scan_receipts(home)for path, record in records:if not record or record.get('profile_home') != str(home) or not record.get('admission_id'):continuerecord.update(_result(authority, record))- live, interim = peer_wait_admission(authority, record)- if live is not None and not interim:- _watch_reply(authority, home, record['delivery_id'], live)- _publish(home, record)- if live is None or interim:- await _maybe_retry(authority, home, record)+ if record['status'] in {'queued', 'claimed'}:+ _watch_reply(authority, home, record['delivery_id'],+ record.get('retry_admission_id') or record['admission_id'])+ if record['status'] not in {'queued', 'claimed'}:+ await _maybe_retry(authority, home, path, record)+ await write_receipt(home, record)+ remember_receipt(authority, home, record)row = authority.db.get_session_by_title('Bot Chat')if row is None:return@@ -417,16 +403,29 @@ async def recover_bot_deliveries(authority):def _watch_reply(authority, home, key, admission_id):+ watchers = getattr(authority, '_bot_reply_watchers', None)+ if watchers is None:+ watchers = authority._bot_reply_watchers = {}+ previous = watchers.get(key)+ if previous is not None and previous[0] == admission_id and not previous[2].done():+ returnfuture = authority.waiters.setdefault(admission_id, asyncio.get_running_loop().create_future())task = asyncio.create_task(_record_reply(authority, home, key, future))- tasks = getattr(authority, '_bot_receipt_tasks', None)- if tasks is None:- tasks = authority._bot_receipt_tasks = set()- tasks.add(task)- task.add_done_callback(tasks.discard)+ watchers[key] = (admission_id, task, future)+ def done(finished):+ if watchers.get(key) == (admission_id, finished, future):+ watchers.pop(key, None)+ task.add_done_callback(done)+ track_receipt_task(authority, task)async def deliver(connection, params):+ from gateway.session_runtime_workers import track_mutation+ connection.authority._require_admission_open()+ return await asyncio.shield(track_mutation(connection.authority, _deliver(connection, params)))+++async def _deliver(connection, params):authority, actor = connection.authority, connection.actorhome = _home(authority, actor, params.get('profile'))if set(params) - {'id', 'profile', 'message', 'session_id', 'author', 'notification_category'}:@@ -445,28 +444,39 @@ async def deliver(connection, params):if params.get('author') is not None and (not isinstance(params['author'], dict) or author is None):raise RuntimeStoreError('invalid_params')authority._require_admission_open()- # In-process order only: the cross-process file lock is taken for the pin write alone, off-loop- # (``_store``), so a foreign holder or a slow admission never stalls this loop or another delivery.- async with _mailbox_order(authority):- path = _root(home) / f'{key}.json'- record = _read(path)- if record is None or not record.get('admission_id'):- await _migrate(authority, actor, home, path.parent)- record = _read(path)+ async with mailbox_lock(authority):+ root, record = await read_receipt(home, key)+ path = root / f'{key}.json'if record is not None and record.get('admission_id'):if (record['message'] != message or record['principal_id'] != actor.subjector record.get('author') != authoror record.get('notification_category', 'result') != category):raise RuntimeStoreError('admission_conflict')authority.authorize(actor, SessionRef(authority.profile_id, record['session_id']), 'session:submit')- await _maybe_retry(authority, home, record)- return _result(authority, record)+ await _maybe_retry(authority, home, path, record)+ record.update(_delivery_result(authority, record))+ await write_receipt(home, record)+ remember_receipt(authority, home, record)+ return _delivery_result(authority, record)+ await _migrate(authority, actor, home, root)+ _, record = await read_receipt(home, key)+ if record is not None and record.get('admission_id'):+ if (record['message'] != message or record['principal_id'] != actor.subject+ or record.get('author') != author+ or record.get('notification_category', 'result') != category):+ raise RuntimeStoreError('admission_conflict')+ authority.authorize(actor, SessionRef(authority.profile_id, record['session_id']), 'session:submit')+ await _maybe_retry(authority, home, path, record)+ record.update(_delivery_result(authority, record))+ await write_receipt(home, record)+ remember_receipt(authority, home, record)+ return _delivery_result(authority, record)if record is not None:raise RuntimeStoreError('unknown_execution')ref, live, entry = _target(authority, actor)if params.get('session_id', entry.session_id) != entry.session_id:raise RuntimeStoreError('admission_conflict')- return await _admit(authority, actor, home, path.parent, key, message, ref, live, entry, author=author,+ return await _admit(authority, actor, home, root, key, message, ref, live, entry, author=author,notification_category=category)@@ -474,6 +484,7 @@ async def _admit(authority, actor, home, root, key, message, ref, live, entry, anotification_category='result'):from gateway.session_automation import automation_notification_metadatanotification = automation_notification_metadata({'notification_category': notification_category})+ path = root / f'{key}.json'event = MessageEvent(text=message, source=live.source, internal=True,message_id='bot:' + key, metadata={'gateway_session_key': live.route,'gateway_session_id': entry.session_id})@@ -487,17 +498,18 @@ async def _admit(authority, actor, home, root, key, message, ref, live, entry, arecord.update(notification)if author is not None:record['author'] = dict(author)- # Compare-and-set against the state this owner read: a DM runner may cancel a queued legacy- # ticket between the scan and this pin, and that cancellation wins.- if not await asyncio.to_thread(_store, home, record, expect=(legacy or {}).get('status')):+ # Preserve a foreign cancellation or claim that won after our legacy scan.+ if not await write_receipt(home, record, expect=(legacy or {}).get('status')):if legacy is not None:- return None # that cancellation (or a late claim) stands; nothing was admitted+ return Noneraise RuntimeStoreError('admission_conflict')receipt = await authority.admit_automation(authority.runner._adapter_for_source(live.source), event, 'bot:' + key)record.update(status='canonical', admission_id=receipt.admission_id)- record.update(_result(authority, record)) # publish the outcome senders poll, not a bare marker- if receipt.status in {'queued', 'started'}:- # Its task publishes the settled receipt once this delivery releases the in-process order.+ record.update(_result(authority, record))+ if record['status'] in {'queued', 'claimed'}:_watch_reply(authority, home, key, receipt.admission_id)- _publish(home, record)- return _result(authority, record)+ if record['status'] not in {'queued', 'claimed'}:+ await _maybe_retry(authority, home, path, record)+ await write_receipt(home, record)+ remember_receipt(authority, home, record)+ return _delivery_result(authority, record)diff --git a/gateway/session_bot_mailbox.py b/gateway/session_bot_mailbox.pynew file mode 100644index 00000000000..66945ffb3b4--- /dev/null+++ b/gateway/session_bot_mailbox.py@@ -0,0 +1,146 @@+"""Authority-local async serialization; file locks cover only short synchronous mailbox I/O."""+import asyncio+from contextlib import asynccontextmanager++from tools.bot_live_delivery import _locked, _read, _write+++@asynccontextmanager+async def mailbox_lock(authority):+ lock = getattr(authority, '_bot_mailbox_lock', None)+ if lock is None:+ lock = authority._bot_mailbox_lock = asyncio.Lock()+ async with lock:+ active = getattr(authority, '_bot_mailbox_operations', None)+ if active is None:+ active = authority._bot_mailbox_operations = set()+ task = asyncio.current_task()+ active.add(task)+ try:+ yield+ finally:+ active.discard(task)+++async def _mailbox_io(operation, *args):+ """Keep the caller's mailbox ownership until its physical I/O ends, even after cancellation."""+ pending = asyncio.create_task(asyncio.to_thread(operation, *args))+ cancelled = None+ while True:+ try:+ result = await asyncio.shield(pending)+ except asyncio.CancelledError as exc:+ if pending.cancelled():+ raise+ cancelled = exc+ except Exception:+ if cancelled is not None:+ raise cancelled+ raise+ else:+ if cancelled is not None:+ raise cancelled+ return result+++def _read_receipt(home, key):+ with _locked(home) as root:+ return root, _read(root / f'{key}.json')+++async def read_receipt(home, key):+ return await _mailbox_io(_read_receipt, home, key)+++_UNCHECKED = object()+++def _write_receipt(home, record, expect=_UNCHECKED):+ with _locked(home) as root:+ path = root / f"{record['delivery_id']}.json"+ current = _read(path)+ if expect is not _UNCHECKED and (current or {}).get('status') != expect:+ return False+ if current is not None and current.get('principal_id'):+ from hermes_state_runtime import RuntimeStoreError+ fields = ('profile_home', 'session_id', 'principal_id', 'message', 'author')+ if (any(current.get(key) != record.get(key) for key in fields)+ or current.get('notification_category', 'result') != record.get('notification_category', 'result')+ or (current.get('admission_id') and current['admission_id'] != record.get('admission_id'))):+ raise RuntimeStoreError('admission_conflict')+ merged = {**(current or {}), **record}+ if merged != current:+ _write(path, merged)+ return True+++async def write_receipt(home, record, *, expect=_UNCHECKED):+ return await _mailbox_io(_write_receipt, home, record, expect)+++def _scan_receipts(home):+ from gateway.session_bot import _scan_records+ with _locked(home) as root:+ return root, list(_scan_records(root))+++async def scan_receipts(home):+ return await _mailbox_io(_scan_receipts, home)+++def remember_receipt(authority, home, record):+ index = getattr(authority, '_bot_receipt_index', None)+ if index is None:+ index = authority._bot_receipt_index = {}+ if record['status'] in {'settled', 'failed', 'cancelled'}:+ index.pop(record['delivery_id'], None)+ else:+ index[record['delivery_id']] = (home, record['session_id'])+++def track_receipt_task(authority, task):+ tasks = getattr(authority, '_bot_receipt_tasks', None)+ if tasks is None:+ tasks = authority._bot_receipt_tasks = set()+ tasks.add(task)+ def done(finished):+ tasks.discard(finished)+ if not finished.cancelled():+ error = finished.exception()+ if error is not None:+ import logging+ logging.getLogger(__name__).warning('Bot receipt projection failed: %s', type(error).__name__)+ task.add_done_callback(done)+++def wake_bot_receipts(authority, session_id):+ """Re-arm paused receipts from owner publication, without making external pollers dial RPC."""+ pending = getattr(authority, '_bot_receipt_refreshes', None)+ if pending is None:+ pending = authority._bot_receipt_refreshes = {}+ authority._bot_receipt_dirty = set()+ for key, (home, owner) in list(getattr(authority, '_bot_receipt_index', {}).items()):+ if owner != session_id:+ continue+ if key in pending and not pending[key].done():+ authority._bot_receipt_dirty.add(key)+ else:+ _start_refresh(authority, home, key)+++def _start_refresh(authority, home, key):+ from gateway.session_bot import refresh_receipt+ async def refresh_until_current():+ while True:+ authority._bot_receipt_dirty.discard(key)+ await refresh_receipt(authority, home, key)+ if key not in authority._bot_receipt_dirty or key not in authority._bot_receipt_index:+ return+ task = asyncio.create_task(refresh_until_current())+ authority._bot_receipt_refreshes[key] = task+ def done(finished):+ if authority._bot_receipt_refreshes.get(key) is finished:+ authority._bot_receipt_refreshes.pop(key, None)+ authority._bot_receipt_dirty.discard(key)+ task.add_done_callback(done)+ track_receipt_task(authority, task)diff --git a/gateway/session_runtime_workers.py b/gateway/session_runtime_workers.pyindex 7b788b72801..4e8b159c6aa 100644--- a/gateway/session_runtime_workers.py+++ b/gateway/session_runtime_workers.py@@ -24,7 +24,7 @@ def uncounted_runtime_work(runner):def mutation_tasks(authority):- tasks = getattr(authority, '_mutation_tasks', ())+ tasks = {*getattr(authority, '_mutation_tasks', ()), *getattr(authority, '_bot_mailbox_operations', ())}return [task for task in tasks if not task.done()]diff --git a/tests/cron/test_cron_live_bot_delivery.py b/tests/cron/test_cron_live_bot_delivery.pyindex 920838f6eed..4181e3dd912 100644--- a/tests/cron/test_cron_live_bot_delivery.py+++ b/tests/cron/test_cron_live_bot_delivery.py@@ -14,6 +14,12 @@ class _FakeAuthority:def __init__(self):self.records = {}+ def publish(self, key, **changes):+ record = self.records[key]+ record.update(changes)+ with mailbox._locked(record['profile_home']) as root:+ mailbox._write(root / f'{key}.json', record)+def __call__(self, home, params):record = self.records.get(params["id"])if record is None:@@ -60,7 +66,7 @@ def test_live_delivery_retry_keeps_receipt_across_owner_loss(tmp_path, monkeypatassert delivery._deliver_to_bot_chat(dict(job), "payload", profile) == pendingassert key in authority.records and len(authority.records) == admitted_before + 1# The owner dies mid-execution: the authority reports the admission ambiguous.- authority.records[key].update(status="ambiguous", error="owner died")+ authority.publish(key, status="ambiguous", error="owner died")outcome = delivery._deliver_to_bot_chat(dict(job), "payload", profile)assert outcome and "ambiguous" in outcome and "owner died" in outcome# Only a NEW execution mints a new id.@@ -96,7 +102,6 @@ def test_result_records_pending_until_terminal_receipt(tmp_path, monkeypatch):normalized_deliver="bot-chat", incident_acked=False, success=True) == "queued"(key,) = authority.recordsassert next(iter(queued.values()))["delivery_id"] == key- authority.records[key].update(status="settled", reply="done")+ authority.publish(key, status="settled", reply="done")assert delivery._deliver_result(job, "payload") is Noneassert updates[-1]["last_delivery_queued"] is None-diff --git a/tests/gateway/test_automation_notification_category.py b/tests/gateway/test_automation_notification_category.pyindex 1a196767e81..3b818678953 100644--- a/tests/gateway/test_automation_notification_category.py+++ b/tests/gateway/test_automation_notification_category.py@@ -52,14 +52,15 @@ async def test_bot_category_is_committed_restored_and_part_of_retry_identity(tmpfirst = await deliver(connection, params)retry = await deliver(connection, params)assert first['admission_id'] == retry['admission_id']- # Re-open the actual on-disk receipt through the production readback- # helper; substitute only transport, then exercise the real owner gate.+ # Poll the owner's local projection, then explicitly retry its immutable envelope.from tools import bot_live_delivery as live- monkeypatch.setattr(live, 'authority_delivery', lambda home, request: request)+ monkeypatch.setattr(live, 'authority_delivery', lambda *a: pytest.fail('receipt poll opened RPC'))replay = live.read_delivery_result(tmp_path, params['id'])assert replay is not Noneassert replay.get('notification_category', 'result') == category- assert (await deliver(connection, replay))['admission_id'] == first['admission_id']+ repeated = dict(id=replay['delivery_id'], profile='default', message=replay['message'],+ notification_category=replay.get('notification_category', 'result'))+ assert (await deliver(connection, repeated))['admission_id'] == first['admission_id']row = get_session_admission(authority.db, admission_id=first['admission_id'])assert row is not Nonedescriptor = row['payload']['local_automation_v1']diff --git a/tests/gateway/test_bot_mailbox_async.py b/tests/gateway/test_bot_mailbox_async.pynew file mode 100644index 00000000000..0daa9167555--- /dev/null+++ b/tests/gateway/test_bot_mailbox_async.py@@ -0,0 +1,161 @@+"""Bot receipt polling is local and mailbox serialization never parks the event loop."""+import asyncio+import threading++import pytest++pytest_plugins = ('tests.gateway.test_session_bot_retry',)+++def test_canonical_poll_reads_owner_projection_without_handshake(tmp_path, monkeypatch):+ from tools import bot_live_delivery as mailbox+ key = 'a' * 32+ record = dict(delivery_id=key, admission_id='admitted', status='queued', message='hello',+ profile_home=str(tmp_path), session_id='s', principal_id='p', reply='')+ with mailbox._locked(tmp_path) as root:+ mailbox._write(root / f'{key}.json', record)+ monkeypatch.setattr(mailbox, 'authority_delivery', lambda *a, **k: pytest.fail('poll dialed authority'))+ assert mailbox.read_delivery_result(tmp_path, key)['status'] == 'queued'+ with mailbox._locked(tmp_path) as root:+ mailbox._write(root / f'{key}.json', dict(record, status='settled', reply='owner reply'))+ assert mailbox.read_delivery_result(tmp_path, key)['reply'] == 'owner reply'+++async def test_admission_wait_releases_file_lock_and_concurrent_deliver_keeps_loop_live(bot, monkeypatch):+ from gateway.session_bot import deliver+ from tools.bot_live_delivery import _locked+ entered, release, ticked = asyncio.Event(), asyncio.Event(), asyncio.Event()+ original = bot.authority.admit_automation+ async def held(*args, **kwargs):+ entered.set()+ await release.wait()+ return await original(*args, **kwargs)+ monkeypatch.setattr(bot.authority, 'admit_automation', held)+ first = asyncio.create_task(deliver(bot.connection, dict(id='a' * 32, profile='default', message='first')))+ second = None+ acquired = threading.Event()+ def inspect():+ with _locked(bot.home): acquired.set()+ inspecting = None+ try:+ await asyncio.wait_for(entered.wait(), 5)+ inspecting = asyncio.create_task(asyncio.to_thread(inspect))+ assert await asyncio.to_thread(acquired.wait, 3), 'file lock remained held across admission await'+ second = asyncio.create_task(deliver(bot.connection, dict(id='b' * 32, profile='default', message='second')))+ asyncio.get_running_loop().call_soon(ticked.set)+ await asyncio.wait_for(ticked.wait(), 5)+ assert not second.done()+ release.set()+ responses = await asyncio.wait_for(asyncio.gather(first, second), 10)+ assert responses[0]['admission_id'] != responses[1]['admission_id']+ finally:+ release.set()+ await asyncio.gather(first, *([second] if second else []), *([inspecting] if inspecting else []), return_exceptions=True)+ tasks = list(getattr(bot.authority, '_bot_receipt_tasks', ()))+ if tasks: await asyncio.wait_for(asyncio.gather(*tasks, return_exceptions=True), 10)+++async def test_paused_receipt_rearms_on_resume_without_polling_rpc(bot, monkeypatch):+ from gateway.session_bot import deliver+ from gateway.session_contract import SessionRef+ from tools.bot_live_delivery import read_delivery_result+ schedule = bot.authority._schedule+ monkeypatch.setattr(bot.authority, '_schedule', lambda ref: None)+ key = 'c' * 32+ receipt = await deliver(bot.connection, dict(id=key, profile='default', message='paused'))+ ref = SessionRef(bot.authority.profile_id, receipt['session_id'])+ bot.authority._pause(ref, 'unknown_execution')+ await asyncio.wait_for(asyncio.gather(*list(bot.authority._bot_receipt_tasks)), 5)+ assert (await asyncio.to_thread(read_delivery_result, bot.home, key))['status'] == 'queued'+ monkeypatch.setattr(bot.authority, '_schedule', schedule)+ schedule(ref)+ await bot.authority.sessions[ref.session_id].task+ async with asyncio.timeout(5):+ while (await asyncio.to_thread(read_delivery_result, bot.home, key))['status'] != 'settled':+ await asyncio.sleep(.01)+ assert (await asyncio.to_thread(read_delivery_result, bot.home, key))['reply'] == 'pong'+++async def test_adopted_result_during_unknown_projection_is_not_lost(bot, monkeypatch):+ from gateway import session_bot+ from gateway.session_contract import SessionRef+ from hermes_state_runtime import (begin_runtime_epoch, claim_session_input, recover_session_inputs,+ register_worker_execution, adopt_worker_execution, settle_session_input)+ from tools.bot_live_delivery import read_delivery_result+ monkeypatch.setattr(bot.authority, '_schedule', lambda ref: None)+ key = 'd' * 32+ receipt = await session_bot.deliver(bot.connection, dict(id=key, profile='default', message='unknown'))+ ref = SessionRef(bot.authority.profile_id, receipt['session_id'])+ row = claim_session_input(bot.authority.db, epoch=bot.authority.epoch, session_id=ref.session_id)+ assignment = dict(execution_id='recovered-worker', session_id=ref.session_id, generation=row['generation'])+ register_worker_execution(bot.authority.db, epoch=bot.authority.epoch, **assignment,+ kind='compute', adoption_secret='owned-worker')+ bot.authority.epoch = begin_runtime_epoch(bot.authority.db, instance_id='recovery')+ recover_session_inputs(bot.authority.db, epoch=bot.authority.epoch)+ bot.authority._pause(ref, 'unknown_execution')+ await asyncio.wait_for(asyncio.gather(*list(bot.authority._bot_receipt_tasks)), 5)+ entered, release = asyncio.Event(), asyncio.Event()+ original = session_bot.write_receipt+ async def held(home, record):+ if record['status'] == 'ambiguous' and not entered.is_set():+ entered.set()+ await release.wait()+ await original(home, record)+ monkeypatch.setattr(session_bot, 'write_receipt', held)+ bot.authority._publish_pending(ref)+ try:+ await asyncio.wait_for(entered.wait(), 5)+ adopt_worker_execution(bot.authority.db, epoch=bot.authority.epoch, **assignment, adoption_secret='owned-worker')+ settle_session_input(bot.authority.db, epoch=bot.authority.epoch, admission_id=row['admission_id'],+ generation=row['generation'], outcome='completed', result={'result': {'final_response': 'adopted reply'}, 'usage': {}})+ bot.authority._publish_pending(ref)+ release.set()+ async with asyncio.timeout(5):+ while (await asyncio.to_thread(read_delivery_result, bot.home, key))['status'] == 'ambiguous':+ await asyncio.sleep(.01)+ assert (await asyncio.to_thread(read_delivery_result, bot.home, key))['status'] == 'settled'+ assert (await asyncio.to_thread(read_delivery_result, bot.home, key))['reply'] == 'adopted reply'+ finally:+ release.set()+ tasks = list(getattr(bot.authority, '_bot_receipt_tasks', ()))+ if tasks: await asyncio.wait_for(asyncio.gather(*tasks, return_exceptions=True), 10)+++async def test_drain_defers_retry_without_publishing_interim_failure(bot, monkeypatch):+ from gateway.session_bot import deliver, recover_bot_deliveries+ from tools.bot_live_delivery import read_delivery_result+ import gateway.session_finite as finite+ execute = finite.execute_finite_admission+ async def drain_after_failure(authority, ref, row):+ result = await execute(authority, ref, row)+ authority.runner._draining = True+ return result+ monkeypatch.setattr(finite, 'execute_finite_admission', drain_after_failure)+ bot.errors[:] = ['Error code: 429 - rate limit exceeded']+ key = 'e' * 32+ await deliver(bot.connection, dict(id=key, profile='default', message='retry after restart'))+ tasks = list(getattr(bot.authority, '_bot_receipt_tasks', ()))+ if tasks: await asyncio.wait_for(asyncio.gather(*tasks, return_exceptions=True), 10)+ assert (await asyncio.to_thread(read_delivery_result, bot.home, key))['status'] == 'claimed'+ from gateway import session_bot+ read = session_bot.read_receipt+ async def drain_during_read(home, key):+ result = await read(home, key)+ bot.authority.runner._draining = True+ return result+ bot.authority.runner._draining = False+ monkeypatch.setattr(session_bot, 'read_receipt', drain_during_read)+ await deliver(bot.connection, dict(id=key, profile='default', message='retry after restart'))+ assert (await asyncio.to_thread(read_delivery_result, bot.home, key))['status'] == 'claimed'+ monkeypatch.setattr(session_bot, 'read_receipt', read)+ monkeypatch.setattr(finite, 'execute_finite_admission', execute)+ bot.authority.runner._draining = False+ await recover_bot_deliveries(bot.authority)+ async with asyncio.timeout(5):+ while (await asyncio.to_thread(read_delivery_result, bot.home, key))['status'] != 'settled':+ await asyncio.sleep(.01)+ assert (await asyncio.to_thread(read_delivery_result, bot.home, key))['retry_admission_id']diff --git a/tests/gateway/test_bot_mailbox_cancellation.py b/tests/gateway/test_bot_mailbox_cancellation.pynew file mode 100644index 00000000000..1afc62e4dae--- /dev/null+++ b/tests/gateway/test_bot_mailbox_cancellation.py@@ -0,0 +1,49 @@+"""Startup cancellation cannot release ownership before mailbox I/O physically ends."""+import asyncio+import threading++import pytest++pytest_plugins = ('tests.gateway.test_session_bot_retry',)++[email protected]('cancel_count', [1, 3])+async def test_cancelled_startup_recovery_retains_owner_until_receipt_writer_finishes(bot, monkeypatch, cancel_count):+ from gateway import run_runtime, session_bot_mailbox+ from gateway.session_bot import deliver, recover_bot_deliveries+ from tests.gateway.test_session_bot_retry import KEY, _settled++ await deliver(bot.connection, dict(id=KEY, profile='default', message='ping'))+ await _settled(bot, 1)+ watchers = list(getattr(bot.authority, '_bot_receipt_tasks', ()))+ if watchers:+ await asyncio.gather(*watchers)+ entered, release, finished = threading.Event(), threading.Event(), threading.Event()+ original = session_bot_mailbox._write_receipt++ def held_write(*args):+ entered.set()+ try:+ assert release.wait(10), 'test did not release receipt writer'+ return original(*args)+ finally:+ finished.set()++ monkeypatch.setattr(session_bot_mailbox, '_write_receipt', held_write)+ monkeypatch.setattr(run_runtime, 'TURN_SETTLE_SECONDS', 0)+ recovery = asyncio.create_task(recover_bot_deliveries(bot.authority))+ try:+ assert await asyncio.to_thread(entered.wait, 5)+ for _ in range(cancel_count):+ recovery.cancel()+ await asyncio.sleep(0)+ assert not finished.is_set()+ # This is the cleanup path of a cancelled serve_profile_runtime startup.+ assert await run_runtime._retire_profile_authority(bot.authority) is False+ finally:+ release.set()+ assert await asyncio.to_thread(finished.wait, 5)+ results = await asyncio.gather(recovery, return_exceptions=True)+ assert isinstance(results[0], asyncio.CancelledError)+ assert await run_runtime._retire_profile_authority(bot.authority) is Truediff --git a/tests/gateway/test_bot_paused_waiter.py b/tests/gateway/test_bot_paused_waiter.pyindex 745daeab9f0..5aa839bdb73 100644--- a/tests/gateway/test_bot_paused_waiter.py+++ b/tests/gateway/test_bot_paused_waiter.py@@ -3,29 +3,31 @@ import asyncioimport pytest-from tests.gateway.test_session_bot_retry import bot, KEY+from tests.gateway.test_session_bot_retry import KEY++pytest_plugins = ['tests.gateway.test_session_bot_retry']@pytest.mark.asyncioasync def test_paused_bot_follower_rearms_until_its_durable_completion(bot, monkeypatch):from gateway.session_bot import deliverfrom gateway.session_contract import SessionRef- from tools.bot_live_delivery import _read, _root+ from tools.bot_live_delivery import read_delivery_resultauthority = bot.authorityschedule = authority._schedulemonkeypatch.setattr(authority, '_schedule', lambda ref: None)- accepted = await deliver(bot.connection, dict(id=KEY, profile='default', message='ping'))+ await deliver(bot.connection, dict(id=KEY, profile='default', message='ping'))authority._pause(SessionRef(authority.profile_id, bot.chat), 'session_busy')async with asyncio.timeout(5):- while _read(_root(bot.home) / f'{KEY}.json')['status'] != 'queued':+ while (await asyncio.to_thread(read_delivery_result, bot.home, KEY))['status'] != 'queued':await asyncio.sleep(.01)- record = _read(_root(bot.home) / f'{KEY}.json')+ record = (await asyncio.to_thread(read_delivery_result, bot.home, KEY))assert record['status'] == 'queued'schedule(SessionRef(authority.profile_id, bot.chat))await asyncio.wait_for(authority.sessions[bot.chat].task, 5)async with asyncio.timeout(5):- while _read(_root(bot.home) / f'{KEY}.json')['status'] != 'settled':+ while (await asyncio.to_thread(read_delivery_result, bot.home, KEY))['status'] != 'settled':await asyncio.sleep(.01)- record = _read(_root(bot.home) / f'{KEY}.json')+ record = (await asyncio.to_thread(read_delivery_result, bot.home, KEY))assert record['status'] == 'settled' and record['reply'] == 'pong'diff --git a/tests/gateway/test_bot_receipt_corruption.py b/tests/gateway/test_bot_receipt_corruption.pyindex ee0a4a50fd9..940df20ed62 100644--- a/tests/gateway/test_bot_receipt_corruption.py+++ b/tests/gateway/test_bot_receipt_corruption.py@@ -179,6 +179,6 @@ async def test_legacy_migration_skips_structurally_corrupt_neighbor(monkeypatch,monkeypatch.setattr("gateway.session_bot._admit", fake_admit)- await _migrate(authority, object(), tmp_path, root)+ await _migrate(authority, object(), tmp_path, root)assert migrated == [(healthy_key, "healthy legacy", "queued")]diff --git a/tests/gateway/test_cron_canonical_receipt_regression.py b/tests/gateway/test_cron_canonical_receipt_regression.pyindex 2bae212b565..c673eeabbe7 100644--- a/tests/gateway/test_cron_canonical_receipt_regression.py+++ b/tests/gateway/test_cron_canonical_receipt_regression.py@@ -50,7 +50,9 @@ def canonical_bot(tmp_path, monkeypatch):'auxiliary': {'title_generation': {'enabled': False}},'platform_toolsets': {'gui': []}, 'terminal': {'cwd': str(home)},}))- env = child_env() | dict(HOME=str(user), USERPROFILE=str(user), HERMES_HOME=str(home),+ child_user = user / 'daemon'+ child_user.mkdir()+ env = child_env() | dict(HOME=str(child_user), USERPROFILE=str(child_user), HERMES_HOME=str(home),PYTHONPATH=str(root), OPENAI_API_KEY='loopback-only', OPENAI_BASE_URL=base,PYTHONUNBUFFERED='1')diff --git a/tests/gateway/test_session_bot_retry.py b/tests/gateway/test_session_bot_retry.pyindex 54e892235f2..82bd063524d 100644--- a/tests/gateway/test_session_bot_retry.py+++ b/tests/gateway/test_session_bot_retry.py@@ -65,13 +65,13 @@ def _admissions(bot):async def _settled(bot, count):from gateway.session_bot import _result- from tools.bot_live_delivery import _read, _root+ from tools.bot_live_delivery import read_delivery_resultfor _ in range(200):await asyncio.sleep(0.02)rows = _admissions(bot)if len(rows) >= count and all(r['status'] == 'terminal' for r in rows):await asyncio.sleep(0.05) # let the receipt task observe the settle- return _result(bot.authority, _read(_root(bot.home) / f'{KEY}.json'))+ return _result(bot.authority, (await asyncio.to_thread(read_delivery_result, bot.home, KEY)))raise AssertionError(f'admissions never settled: {_admissions(bot)}')@@ -119,8 +119,8 @@ async def test_retry_that_fails_again_and_non_transient_failures_are_never_replaawait asyncio.sleep(0.1)assert [r['request_id'] for r in _admissions(bot)][2:] == ['bot:' + other]from gateway.session_bot import _result- from tools.bot_live_delivery import _read, _root- auth = _result(bot.authority, _read(_root(bot.home) / f'{other}.json'))+ from tools.bot_live_delivery import read_delivery_result+ auth = _result(bot.authority, (await asyncio.to_thread(read_delivery_result, bot.home, other)))assert (auth['status'], auth['reason']) == ('failed', 'provider_auth_or_access'), auth@@ -131,7 +131,7 @@ async def test_context_overflow_retries_once_unless_the_failed_dm_is_still_an_oprow, and refuses (recorded, typed) when the DM is still the durable tail: the owner execution hasno adoption seam, and a second copy would merge into the unanswered one."""from gateway.session_bot import deliver- from tools.bot_live_delivery import _read, _root+ from tools.bot_live_delivery import read_delivery_resultbot.errors[:] = ["This model's maximum context length is 200000 tokens"]await deliver(bot.connection, dict(id=KEY, profile='default', message='ping'))receipt = await _settled(bot, 2)@@ -143,7 +143,7 @@ async def test_context_overflow_retries_once_unless_the_failed_dm_is_still_an_opawait deliver(bot.connection, dict(id=other, profile='default', message='overflowed dm'))for _ in range(100):await asyncio.sleep(0.02)- record = _read(_root(bot.home) / f'{other}.json')+ record = (await asyncio.to_thread(read_delivery_result, bot.home, other))if (record.get('retry') or {}).get('refused'):breakassert record['retry']['refused'] == 'open_user_tail' and len(_admissions(bot)) == 3diff --git a/tests/tools/test_bot_live_owner_delivery.py b/tests/tools/test_bot_live_owner_delivery.pyindex d86e911a247..ed58d07cdfe 100644--- a/tests/tools/test_bot_live_owner_delivery.py+++ b/tests/tools/test_bot_live_owner_delivery.py@@ -147,15 +147,17 @@ def test_owner_from_another_home_or_malformed_id_is_refused_before_admission(tmpassert authority.calls == []-def test_receipt_read_forwards_the_immutable_author(tmp_path, monkeypatch):- """F10: an authored admission is re-read with its stored author, so the authority sees the same payload."""+def test_receipt_read_retains_the_immutable_author_without_replaying_admission(tmp_path, monkeypatch):+ """The owner-published local projection keeps the author; polling never replays admission."""authority = _FakeAuthority()monkeypatch.setattr(mailbox, "authority_delivery", authority)delivery_id = "d" * 32author = {"kind": "user", "id": "u-1", "display": "Ann"}queued = mailbox.deliver_to_live_owner(tmp_path, _owner(tmp_path), "hello", delivery_id=delivery_id, author=author)- assert mailbox.read_delivery_result(tmp_path, delivery_id) == queued- assert [params.get("author") for _home, params in authority.calls] == [author, author]+ polled = mailbox.read_delivery_result(tmp_path, delivery_id)+ assert all(polled[key] == value for key, value in queued.items())+ assert polled['author'] == author+ assert [params.get("author") for _home, params in authority.calls] == [author]@pytest.mark.parametrize("terminal_status", ["settled", "failed", "cancelled"])diff --git a/tests/tools/test_bot_mode_dm.py b/tests/tools/test_bot_mode_dm.pyindex bfa9ffe79aa..d4d2091ca29 100644--- a/tests/tools/test_bot_mode_dm.py+++ b/tests/tools/test_bot_mode_dm.py@@ -572,7 +572,7 @@ def test_delivery_pins_the_hermes_entrypoint_beside_this_interpreter(tmp_path, massert result["status"] == "queued"mode, _dm_file, transport_argv, _profile_home = _runner_parts(calls[0]["command"])assert mode == "query-file"- assert transport_argv[0] == str(hermes_entry)+ assert Path(transport_argv[0]) == hermes_entry# Local delivery is admitted through the authority; the argv only names the profile.assert transport_argv[1:] == ["-p", "researcher"]@@ -582,7 +582,8 @@ def test_delivery_pins_the_hermes_entrypoint_beside_this_interpreter(tmp_path, massert result2["status"] == "queued"mode, _dm_file, transport_argv, _profile_home = _runner_parts(calls[1]["command"])assert mode == "stdin"- assert transport_argv == [str(hermes_entry), "-p", "default", "peer", "dm", "spark"]+ assert Path(transport_argv[0]) == hermes_entry+ assert transport_argv[1:] == ["-p", "default", "peer", "dm", "spark"]def test_peer_delivery_author_carries_the_sender_hostname_and_local_stays_bare(tmp_path, monkeypatch):diff --git a/tests/tools/test_bot_receipt_read_lock.py b/tests/tools/test_bot_receipt_read_lock.pynew file mode 100644index 00000000000..49cadc430f5--- /dev/null+++ b/tests/tools/test_bot_receipt_read_lock.py@@ -0,0 +1,37 @@+"""Receipt polling joins the writer's short lock even when replacement rewrites in place."""+from concurrent.futures import ThreadPoolExecutor, TimeoutError+import json+import threading++import pytest++from tools.bot_live_delivery import _locked, _write, read_delivery_result+++def test_reader_never_observes_a_contended_partial_rewrite(tmp_path):+ key = 'a' * 32+ record = dict(delivery_id=key, admission_id='owned', status='queued', reply='')+ with _locked(tmp_path) as root:+ _write(root / f'{key}.json', record)+ writing, finish = threading.Event(), threading.Event()+ completed = dict(record, status='settled', reply='complete owner reply')+ encoded = json.dumps(completed)+ def rewrite():+ with _locked(tmp_path) as root, (root / f'{key}.json').open('w', encoding='utf-8') as stream:+ middle = len(encoded) // 2+ stream.write(encoded[:middle])+ stream.flush()+ writing.set()+ assert finish.wait(10)+ stream.write(encoded[middle:])+ with ThreadPoolExecutor(2) as pool:+ writer = pool.submit(rewrite)+ assert writing.wait(5)+ reader = pool.submit(read_delivery_result, tmp_path, key)+ try:+ with pytest.raises(TimeoutError):+ reader.result(timeout=2)+ finally:+ finish.set()+ writer.result(timeout=5)+ assert reader.result(timeout=5) == completeddiff --git a/tools/bot_live_delivery.py b/tools/bot_live_delivery.pyindex e4b9e5d698b..65aff261a89 100644--- a/tools/bot_live_delivery.py+++ b/tools/bot_live_delivery.py@@ -315,16 +315,17 @@ def cancel_queued_delivery(def read_delivery_result(profile_home: Path | str, delivery_id: str) -> dict[str, Any] | None:"""Read admission/claim/terminal state without waiting or deleting its receipt."""- record = _read(_root(profile_home) / f"{_delivery_id(delivery_id)}.json")- if record is not None and record.get('admission_id'):- home = Path(profile_home).resolve()- # Readback replays the immutable envelope; dropping category or author conflicts.- category = ({'notification_category': record['notification_category']}- if 'notification_category' in record else {})- # The receipt carries the envelope's category so a producer can detect a changed retry.- return {**authority_delivery(home, dict(id=delivery_id,- profile=home.name if home.parent.name == 'profiles' else 'default', message=record['message'],- **({'author': dict(record['author'])} if record.get('author') else {}), **category)), **category}+ key = _delivery_id(delivery_id)+ if not _root(profile_home).is_dir():+ return None+ # atomic_replace can fall back to an in-place rewrite on Windows. Use the writer's+ # short lock so local pollers never open a partially rewritten or sharing-locked file.+ with _locked(profile_home) as root:+ record = _read(root / f'{key}.json')+ if record is not None and record.get('admission_id') and record.get('status') == 'canonical':+ # Older owners used this transitional spelling. Publication/recovery updates it;+ # a reader never dials the owner or replays an admission just to inspect its receipt.+ return {**record, 'status': 'queued'}return record