The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): keep a Bot delivery refused for owner state resendable
unsupportedpastels0b76ea80274b
diff --git a/gateway/session_bot.py b/gateway/session_bot.pyindex 01b51aa3960..92f613046b6 100644--- a/gateway/session_bot.py+++ b/gateway/session_bot.py@@ -23,6 +23,15 @@ _CANONICAL_RECEIPT_STATUSES = frozenset({'canonical', 'queued', 'claimed', 'ambiguous', 'settled', 'failed', 'cancelled',})_BOT_DM_MAX_CHARS = 16200+# Admission refusals about the owner's state, not the delivery: with nothing committed the pin is+# withdrawn and a same-id resend admits once it clears (a full FIFO, a drain for restart/update or+# retirement, a fenced epoch or generation, storage, a live CLI holding the session, or a target+# that moved before the write: the resend resolves it again). Every other refusal (permission_denied,+# invalid_params, admission_conflict, profile_mismatch, ...) is final for that delivery: ``refuse_pin``.+_OWNER_STATE_REFUSALS = frozenset({+ 'queue_full', 'runtime_draining', 'runtime_retired', 'stale_epoch', 'stale_generation',+ 'storage_unavailable', 'runtime_coordination_required', 'session_busy', 'not_found',+})_PRODUCER_MAX_CHARS = 1024 * 1024@@ -571,11 +580,13 @@ async def _admit(authority, actor, home, root, key, message, ref, live, entry, atry:receipt = await authority.admit_automation(authority.runner._adapter_for_source(live.source), event, 'bot:' + key)except RuntimeStoreError as exc:- if exc.reason == 'queue_full':+ if _admission_at(authority, ref.session_id, 'bot:' + key) is not None:+ raise # committed after all: the pin stays the explicit unknown record+ if exc.reason in _OWNER_STATE_REFUSALS:if legacy is None:- # Refused inside the admit transaction before any INSERT: nothing to recover.+ # Refused before any INSERT, not for the delivery itself: the same-id resend admits.await withdraw_pin(home, key)- elif _admission_at(authority, ref.session_id, 'bot:' + key) is None:+ else:# 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)diff --git a/tests/gateway/test_bot_receipt_refusal.py b/tests/gateway/test_bot_receipt_refusal.pyindex 90aeef0deb7..f27c3738100 100644--- a/tests/gateway/test_bot_receipt_refusal.py+++ b/tests/gateway/test_bot_receipt_refusal.py@@ -52,6 +52,70 @@ async def test_refused_delivery_leaves_a_terminal_receipt_the_scan_accepts(bot,assert list_session_admissions(bot.authority.db, session_id=bot.chat, pending_only=False) == [][email protected]('reason', ['invalid_params', 'admission_conflict'])+async def test_a_final_refusal_answers_every_resend_with_its_receipt(bot, monkeypatch, reason):+ """A refusal about the delivery itself is final for that id, like ``permission_denied``."""+ from gateway.session_bot import deliver+ params = dict(id=KEY, profile='default', message='ping')+ refusing = _refuse(monkeypatch, reason)+ with pytest.raises(RuntimeStoreError, match=reason):+ await deliver(bot.connection, params)+ refusing.clear()+ again = await deliver(bot.connection, params)+ assert (again['status'], again['refused'], again['reason']) == ('failed', True, 'agent_blocked'), again+ assert list_session_admissions(bot.authority.db, session_id=bot.chat, pending_only=False) == []++[email protected]('reason', ['runtime_draining', 'storage_unavailable', 'stale_epoch'])+async def test_a_transient_refusal_leaves_the_same_id_resendable(bot, monkeypatch, reason):+ """An owner-state refusal (a drain for restart/update, storage, a fenced epoch) says nothing+ about the delivery: no receipt is kept, and the same-id resend once it clears admits once."""+ from gateway.session_bot import deliver+ from tools.bot_live_delivery import read_delivery_result+ params = dict(id=KEY, profile='default', message='ping')+ refusing = _refuse(monkeypatch, reason)+ with pytest.raises(RuntimeStoreError, match=reason):+ await deliver(bot.connection, params)+ assert read_delivery_result(bot.home, KEY) is None+ refusing.clear()+ again = await deliver(bot.connection, params)+ assert not again.get('refused') and again['admission_id'], again+ rows = list_session_admissions(bot.authority.db, session_id=bot.chat, pending_only=False)+ assert [row['request_id'] for row in rows] == ['bot:' + KEY]+++async def test_a_cron_report_parked_across_a_drain_is_delivered_on_the_next_tick(bot, monkeypatch):+ """``cron/bot_chat_legacy`` keeps a record queued when the door raises and replays the same id+ next tick: a drain during a gateway restart must not turn into a transferred refusal."""+ import asyncio+ import json+ from cron.bot_chat_legacy import drain_legacy_pending+ from gateway.session_bot import deliver+ from tools import bot_live_delivery as mailbox+ loop = asyncio.get_running_loop()+ monkeypatch.setattr(mailbox, 'authority_delivery', lambda home, params: asyncio.run_coroutine_threadsafe(+ deliver(bot.connection, params), loop).result())+ monkeypatch.setattr(mailbox, 'find_canonical_live_owner', lambda home: dict(+ profile_home=str(bot.home.resolve()), session_id='', lease_id='fixture', live_session_id=''))+ root = bot.home / 'cron' / 'bot_chat_pending'+ root.mkdir(parents=True)+ path = root / f'{KEY}.json'+ path.write_text(json.dumps(dict(id=KEY, status='queued', job={'id': 'digest', 'name': 'Digest'},+ content='the report', home=str(bot.home), for_failure=False, sequence=1)))+ refusing = _refuse(monkeypatch, 'runtime_draining')+ await asyncio.to_thread(drain_legacy_pending)+ assert json.loads(path.read_text())['status'] == 'queued'+ refusing.clear()+ await asyncio.to_thread(drain_legacy_pending)+ record = json.loads(path.read_text())+ assert record['status'] == 'transferred' and record['receipt_status'] != 'failed', record+ rows = list_session_admissions(bot.authority.db, session_id=bot.chat, pending_only=False)+ assert [row['request_id'] for row in rows] == ['bot:' + KEY]++def _rpc_connection(bot):"""The relay Desktop's own connection: ``bot_relay.deliver`` crosses the contract-checked dispatch."""from gateway.session_controls import AuthorityConnection