Skip to content

The agent that grows with you

fix(gateway): requeue a stale legacy Bot pin instead of deleting its message

unsupportedpastels7e54f67ef9df
diff --git a/gateway/session_bot.py b/gateway/session_bot.py
index 53d4843faa2..c3f0cf8af71 100644
--- a/gateway/session_bot.py
+++ b/gateway/session_bot.py
@@ -17,7 +17,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, refuse_pin)
+ scan_receipts, remember_receipt, track_receipt_task, withdraw_pin, refuse_pin, requeue_pin)
_CANONICAL_RECEIPT_STATUSES = frozenset({
@@ -111,22 +111,33 @@ 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."""
+ 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 = []
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)):
+ or not await (_requeue(home, key, path, records) if 'owner' in record else 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)
+ 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
+async def _requeue(home, key, path, records):
+ """Requeue a legacy pin and hand the ticket to this scan's records, as if it had been read so."""
+ ticket = await requeue_pin(home, key)
+ if ticket is None or _record_shape_error(path, ticket) is not None:
+ return False
+ records.append((path, ticket))
+ return True
+
+
def _home(authority, actor, profile):
from gateway.session_authorities import served_profile_name
home = Path(authority.db.db_path).parent.resolve()
diff --git a/gateway/session_bot_mailbox.py b/gateway/session_bot_mailbox.py
index 58de9bc2a20..bd20721f31f 100644
--- a/gateway/session_bot_mailbox.py
+++ b/gateway/session_bot_mailbox.py
@@ -102,6 +102,30 @@ async def withdraw_pin(home, key):
return await _mailbox_io(_withdraw_pin, home, key)
+# What ``_admit`` lays over a legacy ticket when it pins it (``legacy=``); the ticket never had them.
+_PIN_FIELDS = ('profile_home', 'session_id', 'principal_id', 'operator')
+
+
+def _requeue_pin(home, key):
+ with _locked(home) as root:
+ path = root / f'{key}.json'
+ current = _read(path)
+ if (current is None or current.get('status') != 'ambiguous' or current.get('admission_id')
+ or 'owner' not in current):
+ return None
+ ticket = {k: v for k, v in current.items() if k not in _PIN_FIELDS}
+ ticket['status'] = 'queued'
+ _write(path, ticket)
+ return ticket
+
+
+async def requeue_pin(home, key):
+ """Restore the queued legacy ticket a pre-admission pin was laid over (nothing committed), only
+ while it is still that pin: its id, message, sequence and created_at are kept, so ``_migrate``
+ admits it once in its FIFO place. Returns the ticket, or None when the pin is gone or changed."""
+ return await _mailbox_io(_requeue_pin, home, key)
+
+
def _refuse_pin(home, key):
from tools.bot_failure_reasons import AGENT_BLOCKED
with _locked(home) as root:
diff --git a/tests/gateway/test_bot_receipt_stale_pin.py b/tests/gateway/test_bot_receipt_stale_pin.py
index 129e9d604ec..5310e2a1a2c 100644
--- a/tests/gateway/test_bot_receipt_stale_pin.py
+++ b/tests/gateway/test_bot_receipt_stale_pin.py
@@ -89,36 +89,50 @@ async def test_an_old_pin_whose_admission_committed_stays_and_still_warns(bot, m
assert _rows(bot) == ['bot:' + KEY]
+OTHER = 'e' * 32
+
+
+def _legacy(bot, key, sequence, message):
+ from tools.bot_live_delivery import _locked, _write
+ ticket = dict(id=key, delivery_id=key, status='queued', created_at=sequence, sequence=sequence, message=message,
+ owner=dict(profile_home=str(bot.home.resolve()), session_id=bot.chat, lease_id='departed',
+ live_session_id='old-native'))
+ with _locked(bot.home) as root:
+ _write(root / f'{key}.json', ticket)
+ return root / f'{key}.json'
+
+
@pytest.mark.asyncio
-async def test_a_legacy_migration_pin_left_by_a_transient_refusal_is_cleaned_once_past_grace(
+async def test_a_legacy_migration_pin_left_by_a_transient_refusal_is_requeued_and_admitted_once(
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."""
+ """``_migrate`` keeps the pin on an owner-state refusal (``legacy=``), and that pin is the only
+ copy of a never-run message: a later owner scan past the grace window restores the queued
+ ticket (never deletes it), and ``_migrate`` admits it once, ahead of the ticket queued after it."""
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')))
+ from tools.bot_live_delivery import _locked, _read
+ path = _legacy(bot, KEY, 1, 'never-run text')
+ _legacy(bot, OTHER, 2, 'later')
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)
+ with _locked(bot.home):
+ pin = _read(path) or {}
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 path.exists()
assert not _scan_warnings(caplog, KEY)
- assert _rows(bot) == []
+ assert not [r for r in caplog.records if 'never-run text' in r.getMessage()]
+ assert _rows(bot) == ['bot:' + KEY, 'bot:' + OTHER]
+ with _locked(bot.home):
+ receipt = _read(path) or {}
+ assert receipt['message'] == 'never-run text' and receipt['admission_id'], receipt
+ assert receipt['sequence'] == 1 and receipt['owner']['lease_id'] == 'departed', receipt
+ await recover_bot_deliveries(bot.authority)
+ assert _rows(bot) == ['bot:' + KEY, 'bot:' + OTHER]
@pytest.mark.asyncio