Skip to content

The agent that grows with you

fix(gateway): keep legacy Bot tickets FIFO behind an unresolved pre-admission pin

unsupportedpastelsc4efb79c9c40
diff --git a/gateway/session_bot.py b/gateway/session_bot.py
index c3f0cf8af71..539d6150730 100644
--- a/gateway/session_bot.py
+++ b/gateway/session_bot.py
@@ -114,19 +114,37 @@ async def _scan_owner_receipts(authority, home):
one: the scan stops warning and a same-id resend admits once. A pin laid over a legacy ticket
(``owner``) is that never-run message's only copy: it is requeued instead, for ``_migrate`` to
admit once under the same id. A pin whose admission committed stays the explicit unknown record
- and keeps its warning."""
- pins = []
+ and keeps its warning.
+
+ Also returns the FIFO barrier: the lowest ``_legacy_order`` of a legacy pin of this home that is
+ still unresolved (inside the grace window, or its requeue lost to a concurrent change). No
+ legacy ticket ordered after it may be admitted by this pass. It holds for one scan only: past
+ the grace window the pin is requeued and released, and a failed requeue is re-read by the next
+ scan (gone, admitted or a ticket again), so the barrier never outlives the pin."""
+ pins, barrier = [], None
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
+ if (record['profile_home'] != str(home)
+ or _admission_at(authority, record['session_id'], 'bot:' + key) is not None):
+ _warn_malformed(path, _record_shape_error(path, record))
+ continue
+ if (age < _PIN_GRACE_SECONDS
or not await (_requeue(home, key, path, records) if 'owner' in record else withdraw_pin(home, key))):
+ if 'owner' in record:
+ barrier = min(_legacy_order(path, record), barrier or _legacy_order(path, record))
_warn_malformed(path, _record_shape_error(path, record))
continue
logging.getLogger(__name__).info('%s Bot delivery %s pre-admission pin (age %ds): nothing was admitted',
'Requeued' if 'owner' in record else 'Withdrew', key, age)
- return root, records
+ return root, records, barrier
+
+
+def _legacy_order(path, record):
+ """``_migrate``'s FIFO key of a legacy ticket, or of the pin laid over one (it keeps the ticket's
+ fields). A pin without an integer order holds every legacy ticket until it resolves."""
+ order = record.get('sequence', record.get('created_at'))
+ return (order, path.name) if isinstance(order, int) and not isinstance(order, bool) else (float('-inf'), '')
async def _requeue(home, key, path, records):
@@ -461,14 +479,17 @@ def relay_operation(connection, operation, params):
async def _migrate(authority, actor, home, root):
- root, records = await _scan_owner_receipts(authority, home)
+ # FIFO: a legacy ticket queued after an unresolved legacy pin waits for that pin's requeue. An
+ # owner-state refusal below raises out of the pass, so nothing after the refused ticket runs.
+ root, records, barrier = await _scan_owner_receipts(authority, home)
legacy = [(path, record) for path, record in records
if record and 'owner' in record and not record.get('admission_id')
- and record['status'] in {'queued', 'claimed'}]
+ and record['status'] in {'queued', 'claimed'}
+ and (barrier is None or _legacy_order(path, record) < barrier)]
if not legacy:
return
ref, live, entry = await _target(authority, actor)
- for path, record in sorted(legacy, key=lambda item: (item[1].get('sequence', item[1]['created_at']), item[0].name)):
+ for path, record in sorted(legacy, key=lambda item: _legacy_order(*item)):
owner = record['owner']
if owner['profile_home'] != str(home):
continue
@@ -491,7 +512,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_owner_receipts(authority, 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'):
continue
diff --git a/tests/gateway/test_bot_receipt_pin_fifo.py b/tests/gateway/test_bot_receipt_pin_fifo.py
new file mode 100644
index 00000000000..54e262414f2
--- /dev/null
+++ b/tests/gateway/test_bot_receipt_pin_fifo.py
@@ -0,0 +1,116 @@
+"""Legacy Bot mailbox tickets keep FIFO order across a pre-admission pin (#139138).
+
+A legacy ticket whose ``_migrate`` admission was refused for owner state stays a pin until the
+owner scan requeues it past the grace window. While that pin is unresolved no legacy ticket
+ordered after it is admitted; tickets ordered before it, and pins whose admission committed,
+never hold the queue."""
+import pytest
+
+from hermes_state_runtime import RuntimeStoreError
+from tests.gateway.test_bot_receipt_refusal import _refuse
+from tests.gateway.test_bot_receipt_stale_pin import HOUR, KEY, OTHER, _age, _legacy, _pin, _rows
+
+pytest_plugins = ['tests.gateway.test_session_bot_retry']
+
+THIRD = 'd' * 32
+
+
+def _status(bot, key):
+ from tools.bot_live_delivery import _locked, _read
+ with _locked(bot.home) as root:
+ return (_read(root / f'{key}.json') or {}).get('status')
+
+
+async def test_a_ticket_queued_after_an_unresolved_pin_waits_for_it(bot, monkeypatch):
+ """Recovery inside the grace window admits nothing behind the pin; past it the order holds."""
+ from gateway.session_bot import recover_bot_deliveries
+ bot.authority._schedule = lambda ref: None
+ path = _legacy(bot, KEY, 1, 'first')
+ _legacy(bot, OTHER, 2, 'second')
+ refusing = _refuse(monkeypatch, 'runtime_draining')
+ with pytest.raises(RuntimeStoreError, match='runtime_draining'):
+ await recover_bot_deliveries(bot.authority)
+ refusing.clear()
+ await recover_bot_deliveries(bot.authority)
+ assert _rows(bot) == []
+ assert (_status(bot, KEY), _status(bot, OTHER)) == ('ambiguous', 'queued')
+ _age(path, HOUR)
+ await recover_bot_deliveries(bot.authority)
+ assert _rows(bot) == ['bot:' + KEY, 'bot:' + OTHER]
+
+
+async def test_a_ticket_queued_before_an_unresolved_pin_is_still_admitted(bot):
+ from gateway.session_bot import recover_bot_deliveries
+ bot.authority._schedule = lambda ref: None
+ _legacy(bot, KEY, 1, 'first')
+ _pin(bot, OTHER, id=OTHER, created_at=2, sequence=2, owner=dict(
+ profile_home=str(bot.home.resolve()), session_id=bot.chat, lease_id='departed', live_session_id='old-native'))
+ _legacy(bot, THIRD, 3, 'third')
+ await recover_bot_deliveries(bot.authority)
+ assert _rows(bot) == ['bot:' + KEY]
+ assert (_status(bot, OTHER), _status(bot, THIRD)) == ('ambiguous', 'queued')
+
+
+async def test_a_pin_whose_admission_committed_does_not_hold_the_queue(bot, monkeypatch):
+ from gateway.session_bot import recover_bot_deliveries
+ bot.authority._schedule = lambda ref: None
+ real, failing = type(bot.authority).admit_automation, [True]
+ async def committed_then_refused(self, *args):
+ receipt = await real(self, *args)
+ if failing:
+ raise RuntimeStoreError('stale_epoch')
+ return receipt
+ monkeypatch.setattr(type(bot.authority), 'admit_automation', committed_then_refused)
+ _legacy(bot, KEY, 1, 'first')
+ _legacy(bot, OTHER, 2, 'second')
+ with pytest.raises(RuntimeStoreError, match='stale_epoch'):
+ await recover_bot_deliveries(bot.authority)
+ assert _status(bot, KEY) == 'ambiguous'
+ failing.clear()
+ await recover_bot_deliveries(bot.authority)
+ assert _rows(bot) == ['bot:' + KEY, 'bot:' + OTHER]
+
+
+async def test_an_owner_state_refusal_mid_pass_stops_the_pass(bot, monkeypatch):
+ """The refused ticket becomes the barrier: nothing after it runs until it is requeued."""
+ from gateway.session_bot import recover_bot_deliveries
+ bot.authority._schedule = lambda ref: None
+ real, refusing = type(bot.authority).admit_automation, [True]
+ async def full_for_other(self, adapter, event, identity):
+ if refusing and identity == 'bot:' + OTHER:
+ raise RuntimeStoreError('queue_full')
+ return await real(self, adapter, event, identity)
+ monkeypatch.setattr(type(bot.authority), 'admit_automation', full_for_other)
+ _legacy(bot, KEY, 1, 'first')
+ path = _legacy(bot, OTHER, 2, 'second')
+ _legacy(bot, THIRD, 3, 'third')
+ with pytest.raises(RuntimeStoreError, match='queue_full'):
+ await recover_bot_deliveries(bot.authority)
+ assert _rows(bot) == ['bot:' + KEY]
+ assert (_status(bot, OTHER), _status(bot, THIRD)) == ('ambiguous', 'queued')
+ refusing.clear()
+ await recover_bot_deliveries(bot.authority)
+ assert _rows(bot) == ['bot:' + KEY]
+ _age(path, HOUR)
+ await recover_bot_deliveries(bot.authority)
+ assert _rows(bot) == ['bot:' + KEY, 'bot:' + OTHER, 'bot:' + THIRD]
+
+
+async def test_a_delivery_waits_behind_an_unresolved_legacy_pin(bot, monkeypatch):
+ """The delivery-triggered ``_migrate`` holds the same barrier as owner recovery."""
+ from gateway.session_bot import deliver, recover_bot_deliveries
+ bot.authority._schedule = lambda ref: None
+ _legacy(bot, KEY, 1, 'first')
+ _legacy(bot, OTHER, 2, 'second')
+ refusing = _refuse(monkeypatch, 'runtime_draining')
+ with pytest.raises(RuntimeStoreError, match='runtime_draining'):
+ await recover_bot_deliveries(bot.authority)
+ refusing.clear()
+ await deliver(bot.connection, dict(id=THIRD, profile='default', message='fresh'))
+ assert 'bot:' + OTHER not in _rows(bot)
+ assert (_status(bot, KEY), _status(bot, OTHER)) == ('ambiguous', 'queued')