Skip to content

The agent that grows with you

fix: recover bot mailbox receipts and migrate queued inputs at owner startup

Teknium76a6044139c1
diff --git a/gateway/run_runtime.py b/gateway/run_runtime.py
index 7cee21d1529..6030e28ec77 100644
--- a/gateway/run_runtime.py
+++ b/gateway/run_runtime.py
@@ -40,6 +40,8 @@ async def start_gateway_runtime_api(runner):
runner.session_runtime_descriptor['api_origin'] = runner.session_api.api_origin
from gateway.session_local_recovery import recover_local_sessions
recover_local_sessions(runner.session_authority, schedule=True)
+ from gateway.session_bot import recover_bot_deliveries
+ await recover_bot_deliveries(runner.session_authority)
def publish_gateway_runtime_ready(runner):
diff --git a/gateway/session_bot.py b/gateway/session_bot.py
index 283555e840c..82934b02a90 100644
--- a/gateway/session_bot.py
+++ b/gateway/session_bot.py
@@ -6,7 +6,7 @@ admission is the only consumer; unknown execution is never retried as inference.
import asyncio
from pathlib import Path
-from gateway.session_contract import SessionRef
+from gateway.session_contract import Principal, SessionRef
from gateway.config import Platform
from gateway.platforms.event import MessageEvent
from hermes_state_runtime import RuntimeStoreError, get_session_admission
@@ -114,6 +114,39 @@ async def _migrate(authority, actor, home, root):
record['message'], ref, live, entry, legacy=record)
+async def recover_bot_deliveries(authority):
+ """Rebuild derivative replies and queued legacy admissions at owner startup."""
+ home = Path(authority.db.db_path).parent.resolve()
+ with _locked(home) as root:
+ records = [(path, _read(path)) for path in root.glob('*.json')]
+ for path, record in records:
+ if not record or record.get('profile_home') != str(home) or not record.get('admission_id'):
+ continue
+ record.update(_result(authority, record))
+ _write(path, record)
+ if record['status'] in {'queued', 'claimed'}:
+ _watch_reply(authority, home, record['delivery_id'], record['admission_id'])
+ row = authority.db.get_session_by_title('Bot Chat')
+ if row is None:
+ return
+ target = authority.db.get_session(authority.db.get_compression_tip(row['id']))
+ if target is None or not str(target.get('chat_id') or '').startswith('local-'):
+ return # Historical binding migration belongs to the session owner.
+ actor = Principal(target['user_id'], authority.profile_id,
+ frozenset({'session:submit'}), 'bot-owner-recovery')
+ await _migrate(authority, actor, home, root)
+
+
+def _watch_reply(authority, home, key, admission_id):
+ future = authority.waiters.setdefault(admission_id, asyncio.get_running_loop().create_future())
+ task = asyncio.create_task(_record_reply(authority, home, key, future))
+ tasks = getattr(authority, '_bot_receipt_tasks', None)
+ if tasks is None:
+ tasks = authority._bot_receipt_tasks = set()
+ tasks.add(task)
+ task.add_done_callback(tasks.discard)
+
+
async def deliver(connection, params):
authority, actor = connection.authority, connection.actor
home = _home(authority, actor, params.get('profile'))
@@ -158,12 +191,5 @@ async def _admit(authority, actor, home, root, key, message, ref, live, entry, l
record.update(status='canonical', admission_id=receipt.admission_id)
_write(path, record)
if receipt.status in {'queued', 'started'}:
- future = authority.waiters.setdefault(receipt.admission_id, asyncio.get_running_loop().create_future())
- task = asyncio.create_task(_record_reply(authority, home, key, future))
- # Keep receipt publication independent of the requesting WebSocket.
- tasks = getattr(authority, '_bot_receipt_tasks', None)
- if tasks is None:
- tasks = authority._bot_receipt_tasks = set()
- tasks.add(task)
- task.add_done_callback(tasks.discard)
+ _watch_reply(authority, home, key, receipt.admission_id)
return _result(authority, record)
\ No newline at end of file
diff --git a/tests/gateway/fixtures/bot_authority_peer.py b/tests/gateway/fixtures/bot_authority_peer.py
index 74f100c3956..a5f56af4a75 100644
--- a/tests/gateway/fixtures/bot_authority_peer.py
+++ b/tests/gateway/fixtures/bot_authority_peer.py
@@ -104,15 +104,40 @@ def probe(base):
assert sum('LEGACY_QUEUED_ONCE' in str(t) for t in texts) == 1, texts
assert not any('LEGACY_CLAIMED_NEVER' in str(t) for t in texts), texts
print(json.dumps({'ledger': rows(), 'inputs': texts, 'lost_ack': True, 'same_target': sid}))
+ return sid
try:
with daemon(root, home, env, barrier=False) as (proc, desc):
try:
- asyncio.run(run(desc))
+ sid = asyncio.run(run(desc))
print(json.dumps({'ordinary_daemon_pid': proc.pid}))
except BaseException:
print((home / 'restart.log').read_text()[-10000:], file=sys.stderr)
raise
+ # Model the exact post-settlement/pre-mailbox-publication crash boundary.
+ # Keep the actual admission/result, remove only the derivative reply receipt.
+ from tools.bot_live_delivery import _locked, _read, _write
+ with _locked(home) as mailbox:
+ path = mailbox / ('a' * 32 + '.json')
+ record = _read(path)
+ record.update(status='canonical', reply='')
+ _write(path, record)
+ owner = dict(profile_home=str(home), session_id=sid, lease_id='departed', live_session_id='old')
+ _write(mailbox / ('d' * 32 + '.json'), dict(delivery_id='d' * 32, id='d' * 32,
+ owner=owner, **owner, status='queued', message='STARTUP_LEGACY_ONCE', created_at=2, sequence=2))
+ async def restarted(desc):
+ def read_delivery_result(home, key):
+ return _read(home / 'runtime' / 'bot_live_delivery' / (key + '.json'))
+ await wait(lambda: read_delivery_result(home, 'a' * 32)['status'] == 'settled')
+ recovered = read_delivery_result(home, 'a' * 32)
+ assert recovered['admission_id'] == record['admission_id']
+ assert recovered['reply'] == 'AUTOMATION_ACK', recovered
+ await wait(lambda: read_delivery_result(home, 'd' * 32)['status'] == 'settled')
+ assert sum('STARTUP_LEGACY_ONCE' in r['payload_json'] for r in rows()) == 1
+ print(json.dumps({'restart_receipt': recovered, 'startup_migration': True}))
+ with daemon(root, home, env, barrier=False) as (proc, desc):
+ asyncio.run(restarted(desc))
+ print(json.dumps({'restart_daemon_pid': proc.pid}))
finally:
model.release.set(); model.shutdown(); model.server_close()