The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): withdraw stale Bot receipt pins whose admission never committed
unsupportedpastelsadea52053043
diff --git a/gateway/session_bot.py b/gateway/session_bot.pyindex 92f613046b6..53d4843faa2 100644--- a/gateway/session_bot.py+++ b/gateway/session_bot.py@@ -7,6 +7,7 @@ import asynciofrom functools import partialimport loggingfrom pathlib import Path+import timefrom agent.turn_author import parse_turn_author@@ -71,22 +72,61 @@ def _record_shape_error(path, record):return 'unknown receipt schema'-def _scan_records(root):- """Bulk mailbox scan: isolate unreadable/malformed records; exact-id reads still fail closed."""+def _is_pre_admission_pin(path, record):+ """The ``ambiguous`` pin ``_admit`` writes before it admits: no admission id, never refused."""+ return (record.get('status') == 'ambiguous' and 'admission_id' not in record and 'refused' not in record+ and _canonical_record_error(path, record, ('profile_home', 'session_id', 'principal_id')) is None)+++def _warn_malformed(path, problem):+ logging.getLogger(__name__).warning("Skipping malformed Bot mailbox receipt %s (%s)", path, problem)+++def _scan_records(root, pins=None):+ """Bulk mailbox scan: isolate unreadable/malformed records; exact-id reads still fail closed.+ An owner scan passes ``pins``: pre-admission pins land there with their mtime, unwarned, since+ only the owner can tell whether their admission committed (``_scan_owner_receipts``)."""for path in root.glob('*.json'):try:record = _read(path)problem = None if record is None else _record_shape_error(path, record)+ if problem is not None and pins is not None and _is_pre_admission_pin(path, record):+ pins.append((path, record, path.stat().st_mtime))+ continueexcept (OSError, ValueError) as exc:record, problem = None, str(exc)if problem is not None:- logging.getLogger(__name__).warning(- "Skipping malformed Bot mailbox receipt %s (%s)", path, problem)+ _warn_malformed(path, problem)continueif record is not None:yield path, record+# An ``_admit`` pins, commits and withdraws under the mailbox lock in well under a second: a+# pre-admission pin older than this is no in-flight admission, and the owner scan may withdraw it.+_PIN_GRACE_SECONDS = 300+++async def _scan_owner_receipts(authority, home):+ """The owner's bulk scan, under the mailbox lock ``_admit`` holds. A pre-admission pin past the+ grace window whose ``bot:<key>`` never committed (refused by an older build, a death before the+ commit, a transient refusal on the legacy migration path) is withdrawn as ``_admit`` withdraws+ one: the scan stops warning and a same-id resend admits once. A pin whose admission committed+ stays the explicit unknown record and keeps its warning."""+ pins = []+ root, records = await scan_receipts(home, pins)+ for path, record, mtime in pins:+ key, age = record['delivery_id'], time.time() - mtime+ if (age < _PIN_GRACE_SECONDS or record['profile_home'] != str(home)+ or _admission_at(authority, record['session_id'], 'bot:' + key) is not None+ or not await withdraw_pin(home, key)):+ _warn_malformed(path, _record_shape_error(path, record))+ continue+ logging.getLogger(__name__).info(+ 'Withdrew Bot delivery %s pre-admission pin (age %ds): nothing was admitted', key, age)+ return root, records++def _home(authority, actor, profile):from gateway.session_authorities import served_profile_namehome = Path(authority.db.db_path).parent.resolve()@@ -410,7 +450,7 @@ def relay_operation(connection, operation, params):async def _migrate(authority, actor, home, root):- root, records = await scan_receipts(home)+ root, records = await _scan_owner_receipts(authority, 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'}]@@ -440,7 +480,7 @@ async def recover_bot_deliveries(authority):"""Rebuild derivative replies and queued legacy admissions at owner startup."""home = Path(authority.db.db_path).parent.resolve()async with mailbox_lock(authority):- root, records = await scan_receipts(home)+ root, records = await _scan_owner_receipts(authority, home)for path, record in records:if not record or record.get('profile_home') != str(home) or not record.get('admission_id'):continuediff --git a/gateway/session_bot_mailbox.py b/gateway/session_bot_mailbox.pyindex 7d91875755c..58de9bc2a20 100644--- a/gateway/session_bot_mailbox.py+++ b/gateway/session_bot_mailbox.py@@ -80,10 +80,10 @@ async def write_receipt(home, record, *, expect=_UNCHECKED):return await _mailbox_io(_write_receipt, home, record, expect)-def _scan_receipts(home):+def _scan_receipts(home, pins=None):from gateway.session_bot import _scan_recordswith _locked(home) as root:- return root, list(_scan_records(root))+ return root, list(_scan_records(root, pins))def _withdraw_pin(home, key):@@ -92,6 +92,8 @@ def _withdraw_pin(home, key):current = _read(path)if current is not None and current.get('status') == 'ambiguous' and not current.get('admission_id'):path.unlink()+ return True+ return Falseasync def withdraw_pin(home, key):@@ -117,8 +119,9 @@ async def refuse_pin(home, key):return await _mailbox_io(_refuse_pin, home, key)-async def scan_receipts(home):- return await _mailbox_io(_scan_receipts, home)+async def scan_receipts(home, pins=None):+ """Bulk scan; an owner scan passes ``pins`` to collect pre-admission pins instead of warning."""+ return await _mailbox_io(_scan_receipts, home, pins)def remember_receipt(authority, home, record):diff --git a/tests/gateway/test_bot_receipt_stale_pin.py b/tests/gateway/test_bot_receipt_stale_pin.pynew file mode 100644index 00000000000..129e9d604ec--- /dev/null+++ b/tests/gateway/test_bot_receipt_stale_pin.py@@ -0,0 +1,133 @@+"""A pre-admission pin left on disk by an older build (or by a transient refusal on the legacy+migration path) whose ``bot:<key>`` admission never committed is withdrawn by the owner's scan+once past the grace window, so the scan stops warning and a same-id resend admits (#139138).+A pin inside the grace window, or one whose admission committed, is left as it is."""+import logging+import os+import time++import pytest++from hermes_state_runtime import RuntimeStoreError, list_session_admissions+from tests.gateway.test_bot_receipt_refusal import _refuse, _scan_warnings++pytest_plugins = ['tests.gateway.test_session_bot_retry']++KEY = 'f' * 32+HOUR = 3600+++def _pin(bot, key=KEY, **extra):+ """The pin ``_admit`` writes before it admits, as an older build left it after a refusal."""+ from tools.bot_live_delivery import _locked, _write+ with _locked(bot.home) as root:+ path = root / f'{key}.json'+ _write(path, dict(extra, delivery_id=key, profile_home=str(bot.home.resolve()), session_id=bot.chat,+ principal_id=bot.connection.actor.subject, message='secret text', status='ambiguous'))+ return path+++def _age(path, seconds):+ then = time.time() - seconds+ os.utime(path, (then, then))+++def _rows(bot):+ return [row['request_id'] for row in+ list_session_admissions(bot.authority.db, session_id=bot.chat, pending_only=False)]+++async def test_an_old_pin_with_no_admission_is_withdrawn_and_the_resend_admits_once(bot, caplog):+ from gateway.session_bot import deliver, recover_bot_deliveries+ path = _pin(bot)+ _age(path, HOUR)+ with caplog.at_level(logging.DEBUG, logger='gateway.session_bot'):+ await recover_bot_deliveries(bot.authority)+ assert not path.exists()+ assert not _scan_warnings(caplog, KEY)+ withdrawn = [r.getMessage() for r in caplog.records if r.levelno == logging.INFO and KEY in r.getMessage()]+ assert len(withdrawn) == 1 and 'secret text' not in withdrawn[0], withdrawn+ receipt = await deliver(bot.connection, dict(id=KEY, profile='default', message='secret text'))+ assert receipt['admission_id'] and not receipt.get('refused'), receipt+ await deliver(bot.connection, dict(id=KEY, profile='default', message='secret text'))+ assert _rows(bot) == ['bot:' + KEY]+++async def test_a_pin_inside_the_grace_window_is_left_alone(bot, caplog):+ """An ``_admit`` between its pin and its commit must never lose its pin."""+ from gateway.session_bot import deliver, recover_bot_deliveries+ path = _pin(bot)+ with caplog.at_level(logging.DEBUG, logger='gateway.session_bot'):+ await recover_bot_deliveries(bot.authority)+ assert path.exists()+ with pytest.raises(RuntimeStoreError, match='unknown_execution'):+ await deliver(bot.connection, dict(id=KEY, profile='default', message='secret text'))+ assert _rows(bot) == []+++async def test_an_old_pin_whose_admission_committed_stays_and_still_warns(bot, monkeypatch, caplog):+ from gateway.session_bot import deliver, recover_bot_deliveries+ from tools.bot_live_delivery import read_delivery_result+ real = type(bot.authority).admit_automation+ async def committed_then_refused(self, *args):+ await real(self, *args)+ raise RuntimeStoreError('stale_epoch')+ monkeypatch.setattr(type(bot.authority), 'admit_automation', committed_then_refused)+ bot.authority._schedule = lambda ref: None+ with pytest.raises(RuntimeStoreError, match='stale_epoch'):+ await deliver(bot.connection, dict(id=KEY, profile='default', message='ping'))+ before = read_delivery_result(bot.home, KEY)+ _age(bot.home / 'runtime' / 'bot_live_delivery' / f'{KEY}.json', HOUR)+ with caplog.at_level(logging.DEBUG, logger='gateway.session_bot'):+ await recover_bot_deliveries(bot.authority)+ assert read_delivery_result(bot.home, KEY) == before+ assert before['status'] == 'ambiguous' and 'admission_id' not in before+ assert _scan_warnings(caplog, KEY)+ assert _rows(bot) == ['bot:' + KEY]+++async def test_a_legacy_migration_pin_left_by_a_transient_refusal_is_cleaned_once_past_grace(+ bot, monkeypatch, caplog):+ """``_migrate`` keeps the pin on an owner-state refusal (``legacy=``): a later owner scan past+ the grace window withdraws it instead of warning about it forever."""+ from gateway.session_bot import recover_bot_deliveries+ from tools.bot_live_delivery import _locked, _read, _write+ home = str(bot.home.resolve())+ with _locked(bot.home) as root:+ path = root / f'{KEY}.json'+ _write(path, dict(id=KEY, delivery_id=KEY, status='queued', created_at=1, sequence=1, message='legacy',+ owner=dict(profile_home=home, session_id=bot.chat, lease_id='departed',+ live_session_id='old-native')))+ refusing = _refuse(monkeypatch, 'runtime_draining')+ with pytest.raises(RuntimeStoreError, match='runtime_draining'):+ await recover_bot_deliveries(bot.authority)+ with _locked(bot.home) as root:+ pin = _read(path)+ assert pin['status'] == 'ambiguous' and 'admission_id' not in pin and 'owner' in pin, pin+ refusing.clear()+ with caplog.at_level(logging.DEBUG, logger='gateway.session_bot'):+ await recover_bot_deliveries(bot.authority)+ assert path.exists() # still inside the grace window+ _age(path, HOUR)+ caplog.clear()+ with caplog.at_level(logging.DEBUG, logger='gateway.session_bot'):+ await recover_bot_deliveries(bot.authority)+ assert not path.exists()+ assert not _scan_warnings(caplog, KEY)+ assert _rows(bot) == []+++async def test_a_scan_outside_the_owner_withdraws_nothing(bot, caplog):+ """The bare mailbox scan has no authority to ask for the admission row: it only reads."""+ from gateway.session_bot_mailbox import scan_receipts+ path = _pin(bot)+ _age(path, HOUR)+ with caplog.at_level(logging.DEBUG, logger='gateway.session_bot'):+ await scan_receipts(bot.home)+ assert path.exists()+ assert _scan_warnings(caplog, KEY)