Skip to content

The agent that grows with you

fix(gateway): settle a definitely refused Bot delivery as a terminal receipt

unsupportedpastels1c76d7d53e3f
diff --git a/gateway/session_bot.py b/gateway/session_bot.py
index 73961d10c0e..1688b89480e 100644
--- a/gateway/session_bot.py
+++ b/gateway/session_bot.py
@@ -16,7 +16,7 @@ from gateway.platforms.event import MessageEvent
from hermes_state_runtime import RuntimeStoreError, get_session_admission
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, withdraw_pin)
+ scan_receipts, remember_receipt, track_receipt_task, withdraw_pin, refuse_pin)
_CANONICAL_RECEIPT_STATUSES = frozenset({
@@ -26,7 +26,7 @@ _BOT_DM_MAX_CHARS = 16200
_PRODUCER_MAX_CHARS = 1024 * 1024
-def _canonical_record_error(path, record):
+def _canonical_record_error(path, record, required_strings=('admission_id', 'profile_home', 'session_id', 'principal_id')):
"""Return why an admission-backed receipt is unsafe for bulk recovery."""
delivery_id = record.get('delivery_id')
if not isinstance(delivery_id, str) or delivery_id != path.stem:
@@ -35,7 +35,6 @@ def _canonical_record_error(path, record):
_delivery_id(delivery_id)
except ValueError:
return 'delivery id is invalid'
- required_strings = ('admission_id', 'profile_home', 'session_id', 'principal_id')
missing = [key for key in required_strings
if not isinstance(record.get(key), str) or not record[key]]
if missing:
@@ -49,7 +48,12 @@ def _canonical_record_error(path, record):
def _record_shape_error(path, record):
- """Validate the known canonical or legacy receipt shape for directory scans."""
+ """Validate the known canonical, refused or legacy receipt shape for directory scans."""
+ if record.get('refused') is True and 'admission_id' not in record:
+ # ``refuse_pin``: the canonical pin fields, terminal ``failed``, never admitted.
+ if record.get('status') != 'failed':
+ return 'refused receipt is not failed'
+ return _canonical_record_error(path, record, ('profile_home', 'session_id', 'principal_id'))
if 'admission_id' in record or record.get('status') == 'canonical' or 'principal_id' in record:
return _canonical_record_error(path, record)
if 'owner' in record:
@@ -183,9 +187,13 @@ def _admission_outcome(authority, admission_id, fallback=None):
def _retry_admission(authority, record):
"""The delivery's one retry admission id, read from the FIFO by its derived identity, so every
reader (an in-memory record, the receipt file, an owner restart) follows the same retry."""
+ return _admission_at(authority, record['session_id'], _retry_identity(record['delivery_id']))
+
+
+def _admission_at(authority, session_id, request_id):
with authority.db._read_ctx() as conn:
row = conn.execute('SELECT admission_id FROM session_admissions WHERE target_session_id=? AND request_id=?',
- (record['session_id'], _retry_identity(record['delivery_id']))).fetchone()
+ (session_id, request_id)).fetchone()
return row[0] if row else None
@@ -515,6 +523,11 @@ async def _deliver(connection, params):
authority.authorize(actor, SessionRef(authority.profile_id, record['session_id']), 'session:submit')
await _maybe_retry(authority, home, path, record)
return await _publish_result(authority, home, record)
+ if record is not None and record.get('refused') is True:
+ if record['message'] != message or record['principal_id'] != actor.subject:
+ raise RuntimeStoreError('admission_conflict')
+ return {k: record[k] for k in ('status', 'delivery_id', 'profile_home', 'session_id', 'message',
+ 'reply', 'error', 'reason')}
if record is not None:
raise RuntimeStoreError('unknown_execution')
ref, live, entry = await _target(authority, actor)
@@ -550,9 +563,14 @@ async def _admit(authority, actor, home, root, key, message, ref, live, entry, a
try:
receipt = await authority.admit_automation(authority.runner._adapter_for_source(live.source), event, 'bot:' + key)
except RuntimeStoreError as exc:
- if exc.reason == 'queue_full' and legacy is None:
- # Refused inside the admit transaction before any INSERT: nothing to recover.
- await withdraw_pin(home, key)
+ if exc.reason == 'queue_full':
+ if legacy is None:
+ # Refused inside the admit transaction before any INSERT: nothing to recover.
+ await withdraw_pin(home, key)
+ elif _admission_at(authority, ref.session_id, 'bot:' + key) is None:
+ # Refused for good with nothing committed: a terminal receipt, not an unknown pin.
+ logging.getLogger(__name__).info('Bot Chat delivery %s refused (%s)', key, exc.reason)
+ await refuse_pin(home, key)
raise
record.update(status='canonical', admission_id=receipt.admission_id)
record.update(_result(authority, record))
diff --git a/gateway/session_bot_mailbox.py b/gateway/session_bot_mailbox.py
index ab7bb05dbcf..7d91875755c 100644
--- a/gateway/session_bot_mailbox.py
+++ b/gateway/session_bot_mailbox.py
@@ -100,6 +100,23 @@ async def withdraw_pin(home, key):
return await _mailbox_io(_withdraw_pin, home, key)
+def _refuse_pin(home, key):
+ from tools.bot_failure_reasons import AGENT_BLOCKED
+ with _locked(home) as root:
+ path = root / f'{key}.json'
+ current = _read(path)
+ if current is not None and current.get('status') == 'ambiguous' and not current.get('admission_id'):
+ current.update(status='failed', refused=True, reply='', error='Bot Chat delivery was refused',
+ reason=AGENT_BLOCKED)
+ _write(path, current)
+
+
+async def refuse_pin(home, key):
+ """Settle a pre-admission pin the FIFO definitely refused for good (nothing committed) as a
+ terminal ``failed`` receipt, only while it is still that pin: never re-sent, nothing unknown."""
+ return await _mailbox_io(_refuse_pin, home, key)
+
+
async def scan_receipts(home):
return await _mailbox_io(_scan_receipts, home)
diff --git a/tests/gateway/test_bot_receipt_refusal.py b/tests/gateway/test_bot_receipt_refusal.py
new file mode 100644
index 00000000000..866d486deac
--- /dev/null
+++ b/tests/gateway/test_bot_receipt_refusal.py
@@ -0,0 +1,74 @@
+"""A Bot Chat delivery the FIFO definitely refused (nothing committed, e.g. ``permission_denied``)
+turns its pre-admission pin into a terminal ``failed`` receipt the bulk scan reads without a
+warning and never re-sends (#139138). A pin with no such proof stays a malformed record."""
+import logging
+
+import pytest
+
+from hermes_state_runtime import RuntimeStoreError, list_session_admissions
+
+pytest_plugins = ['tests.gateway.test_session_bot_retry']
+
+KEY = 'e' * 32
+
+
+def _refuse(monkeypatch, reason):
+ """Refuse at the snapshot check, before any FIFO write, until the returned switch is cleared."""
+ from gateway import session_automation
+ real, refusing = session_automation.snapshot_automation, [True]
+ def snapshot(*args, **kwargs):
+ if refusing:
+ raise RuntimeStoreError(reason)
+ return real(*args, **kwargs)
+ monkeypatch.setattr(session_automation, 'snapshot_automation', snapshot)
+ return refusing
+
+
+def _scan_warnings(caplog, key):
+ return [r for r in caplog.records if r.levelno >= logging.WARNING and key in r.getMessage()]
+
+
+async def test_refused_delivery_leaves_a_terminal_receipt_the_scan_accepts(bot, monkeypatch, caplog):
+ from gateway.session_bot import deliver, recover_bot_deliveries
+ from gateway.session_bot_mailbox import scan_receipts
+ from tools.bot_live_delivery import read_delivery_result
+ params = dict(id=KEY, profile='default', message='ping')
+ refusing = _refuse(monkeypatch, 'permission_denied')
+ with pytest.raises(RuntimeStoreError, match='permission_denied'):
+ await deliver(bot.connection, params)
+ receipt = read_delivery_result(bot.home, KEY)
+ assert (receipt['status'], receipt['reason']) == ('failed', 'agent_blocked'), receipt
+ assert 'admission_id' not in receipt and 'permission' not in receipt['error']
+ with caplog.at_level(logging.DEBUG, logger='gateway.session_bot'):
+ _, records = await scan_receipts(bot.home)
+ await recover_bot_deliveries(bot.authority)
+ assert [record['delivery_id'] for _, record in records] == [KEY]
+ assert not _scan_warnings(caplog, KEY)
+ # The same id answers its refusal receipt; it is never re-sent, not even once the refusal is gone.
+ refusing.clear()
+ again = await deliver(bot.connection, params)
+ assert (again['status'], again['reason']) == ('failed', 'agent_blocked'), again
+ assert list_session_admissions(bot.authority.db, session_id=bot.chat, pending_only=False) == []
+
+
+async def test_a_pin_without_refusal_proof_still_warns(bot, monkeypatch, caplog):
+ """A refusal raised after the admission row committed is not a refusal: the pin stays the
+ explicit unknown record, and the bulk scan keeps warning about it."""
+ from gateway.session_bot import deliver
+ from gateway.session_bot_mailbox import scan_receipts
+ 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'))
+ receipt = read_delivery_result(bot.home, KEY)
+ assert receipt['status'] == 'ambiguous' and 'admission_id' not in receipt, receipt
+ with caplog.at_level(logging.DEBUG, logger='gateway.session_bot'):
+ await scan_receipts(bot.home)
+ assert _scan_warnings(caplog, KEY)