Skip to content

The agent that grows with you

fix: hermes peer dm follows the Bot DM retry; failed receipts carry a typed reason

Tekniumb62f3f44ef7c
diff --git a/gateway/platforms/api_server_bot_chat.py b/gateway/platforms/api_server_bot_chat.py
index 2199aa5859d..38eca94ff8c 100644
--- a/gateway/platforms/api_server_bot_chat.py
+++ b/gateway/platforms/api_server_bot_chat.py
@@ -69,37 +69,36 @@ async def await_live_delivery(adapter, home, record, timeout, *, should_stop=Non
async def await_peer_receipt(authority, record, timeout, *, should_stop=None):
- """The admission's current receipt after it settles, *timeout* lapses, or *should_stop* says so."""
- from gateway.session_bot import _result
- admission_id = record['admission_id']
+ """The delivery's receipt after it settles for good, *timeout* lapses, or *should_stop* says so.
+
+ Each pass re-reads which admission is live (``peer_wait_admission``): after a transient failure
+ the owner admits ONE retry, whose id is the only future that fires again; the original's interim
+ ``failed`` (retry still eligible) reads as pending, never as the answer."""
+ from gateway.session_bot import peer_wait_admission
if record['status'] not in _PENDING:
return record
loop = asyncio.get_running_loop()
- # Register the waiter BEFORE re-reading: a settle between the two either shows in the read
- # or resolves this future; a settle before both would otherwise leave a future nobody pops.
- waiter = authority.waiters.setdefault(admission_id, loop.create_future())
- current = _receipt(authority, record)
deadline = None if timeout is None else loop.time() + timeout
- while current['status'] in _PENDING and not waiter.done():
- if should_stop is not None and should_stop():
- break
+ while True:
+ live, interim = peer_wait_admission(authority, record)
+ # Register the waiter BEFORE re-reading: a settle between the two either shows in the read
+ # or resolves this future; a settle before both would otherwise leave a future nobody pops.
+ waiter = None if live is None or interim else authority.waiters.setdefault(live, loop.create_future())
+ current = _receipt(authority, record)
+ if interim:
+ current['status'] = 'claimed' # the retry is being admitted
+ if live is None or current['status'] not in _PENDING or (should_stop is not None and should_stop()):
+ return current
remaining = None if deadline is None else deadline - loop.time()
if remaining is not None and remaining <= 0:
- break
- tick = 0.5 if should_stop is not None else remaining
- await asyncio.wait([waiter], timeout=tick if remaining is None else min(tick, remaining))
- current = _receipt(authority, record)
- return current
+ return current
+ tick = 0.05 if interim else (0.5 if should_stop is not None else remaining)
+ if waiter is None:
+ await asyncio.sleep(tick if remaining is None else min(tick, remaining))
+ else:
+ await asyncio.wait([waiter], timeout=tick if remaining is None else min(tick, remaining))
def _receipt(authority, record):
from gateway.session_bot import _result
- from gateway.session_results import admission_result
- current = {**record, **_result(authority, record)}
- if current['status'] == 'failed' and not current.get('error'):
- saved = admission_result(authority.db, record['admission_id'])
- error = (saved or {}).get('result', {}).get('error')
- if error:
- from tools.bot_failure_reasons import classify_agent_error
- current.update(error=error, reason=classify_agent_error(error))
- return current
+ return {**record, **_result(authority, record)}
diff --git a/gateway/session_bot.py b/gateway/session_bot.py
index a88bca74756..637dcc782f6 100644
--- a/gateway/session_bot.py
+++ b/gateway/session_bot.py
@@ -153,16 +153,55 @@ def _retry_admission(authority, record):
def _result(authority, record):
"""The delivery's receipt. Once the one transient-failure retry was admitted, the sender's
- outcome is the retry's: ``status``/``reply`` follow it (``retry_admission_id``)."""
+ outcome is the retry's: ``status``/``reply`` follow it (``retry_admission_id``).
+
+ A ``failed`` receipt carries ``error`` + a typed ``reason`` (``tools.bot_failure_reasons``):
+ the relay's Desktop forwards ``res.reason`` to the sender, which cannot re-derive it from a
+ reply that lacks the provider text."""
retry_id = _retry_admission(authority, record)
+ current = retry_id or record['admission_id']
if retry_id:
status, reply = _admission_outcome(authority, retry_id)
else:
status, reply = _admission_outcome(authority, record['admission_id'], record)
+ error = reason = None
+ if status == 'failed':
+ error, reason = _failure(authority, current)
return {k: v for k, v in dict(status=status, delivery_id=record['delivery_id'],
profile_home=record['profile_home'], session_id=record['session_id'],
admission_id=record['admission_id'], message=record['message'], reply=reply,
- retry_admission_id=retry_id).items() if v is not None}
+ retry_admission_id=retry_id, error=error, reason=reason).items() if v is not None}
+
+
+def _failure(authority, admission_id):
+ """``(error, reason)`` of a failed admission from its committed result: the raw provider error
+ and the turn loop's typed verdict, classified like every other Bot lane. A refusal that never
+ ran (no result) has no provider text: ``unknown``."""
+ from gateway.session_results import admission_result
+ from tools.bot_failure_reasons import classify_agent_error, turn_failure_text
+ saved = (admission_result(authority.db, admission_id) or {}).get('result') or {}
+ error = saved.get('error') or saved.get('final_response') or 'Bot Chat delivery failed'
+ return error, classify_agent_error(turn_failure_text(saved.get('error'), saved.get('failure_reason')) or error)
+
+
+def peer_wait_admission(authority, record):
+ """``(admission_id, interim)`` a live waiter must follow; ``(None, False)`` once the delivery
+ settled for good. The retry, once admitted, is the only admission whose future fires again.
+ An original that failed while its one retry is still eligible is ``interim``: pending, never
+ the answer, while the owner's receipt task admits the retry (or records why it would not;
+ the receipt file is re-read for that, the caller's in-memory record is stale)."""
+ from tools.bot_live_delivery import _read, _root
+ retry_id = _retry_admission(authority, record)
+ if retry_id:
+ return (retry_id, False) if _admission_outcome(authority, retry_id)[0] in {'queued', 'claimed'} else (None, False)
+ status = _admission_outcome(authority, record['admission_id'], record)[0]
+ if status in {'queued', 'claimed'}:
+ return record['admission_id'], False
+ if status == 'failed':
+ saved = _read(_root(record['profile_home']) / f"{record['delivery_id']}.json") or record
+ if _retry_eligible(authority, {**record, 'retry': saved.get('retry')}):
+ return record['admission_id'], True
+ return None, False
def _retry_identity(key):
diff --git a/tests/gateway/test_session_bot_retry.py b/tests/gateway/test_session_bot_retry.py
index 67b9fa45e29..52995dbb8c9 100644
--- a/tests/gateway/test_session_bot_retry.py
+++ b/tests/gateway/test_session_bot_retry.py
@@ -101,6 +101,8 @@ async def test_retry_that_fails_again_and_non_transient_failures_are_never_repla
await deliver(bot.connection, dict(id=KEY, profile='default', message='ping'))
receipt = await _settled(bot, 2)
assert receipt['status'] == 'failed' and receipt['retry_admission_id']
+ # The relay's Desktop forwards ``reason`` to the sender verbatim (relay.ts postReply).
+ assert receipt['reason'] == 'provider_server_error' and '503' in receipt['error'], receipt
await deliver(bot.connection, dict(id=KEY, profile='default', message='ping'))
await recover_bot_deliveries(bot.authority)
await asyncio.sleep(0.1)
@@ -116,3 +118,67 @@ async def test_retry_that_fails_again_and_non_transient_failures_are_never_repla
await recover_bot_deliveries(bot.authority)
await asyncio.sleep(0.1)
assert [r['request_id'] for r in _admissions(bot)][2:] == ['bot:' + other]
+ from gateway.session_bot import _result
+ from tools.bot_live_delivery import _read, _root
+ auth = _result(bot.authority, _read(_root(bot.home) / f'{other}.json'))
+ assert (auth['status'], auth['reason']) == ('failed', 'provider_auth_or_access'), auth
+
+
+async def test_context_overflow_retries_once_unless_the_failed_dm_is_still_an_open_tail(bot):
+ """Main re-ran an overflowed delivery once (compress-then-resume: the re-run's own preflight
+ compaction does the compress). The owner retry keeps that for an overflow that left no open DM
+ row, and refuses (recorded, typed) when the DM is still the durable tail: the owner execution has
+ no adoption seam, and a second copy would merge into the unanswered one."""
+ from gateway.session_bot import deliver
+ from tools.bot_live_delivery import _read, _root
+ bot.errors[:] = ["This model's maximum context length is 200000 tokens"]
+ await deliver(bot.connection, dict(id=KEY, profile='default', message='ping'))
+ receipt = await _settled(bot, 2)
+ assert (receipt['status'], receipt['reply']) == ('settled', 'pong'), receipt
+
+ other = 'e' * 32
+ bot.errors[:] = ["This model's maximum context length is 200000 tokens"]
+ bot.authority.db.append_message(bot.chat, 'user', content='overflowed dm')
+ await deliver(bot.connection, dict(id=other, profile='default', message='overflowed dm'))
+ for _ in range(100):
+ await asyncio.sleep(0.02)
+ record = _read(_root(bot.home) / f'{other}.json')
+ if (record.get('retry') or {}).get('refused'):
+ break
+ assert record['retry']['refused'] == 'open_user_tail' and len(_admissions(bot)) == 3
+ assert (record['status'], record['reason']) == ('failed', 'context_overflow'), record
+
+
+async def test_peer_dm_waiter_follows_the_retry_admission_to_its_answer(bot):
+ """``hermes peer dm`` waits on the delivery, not on the original admission id: once that
+ fails transiently its future never fires again, and the answer is the retry's."""
+ from gateway.platforms.api_server_bot_chat import await_peer_receipt
+ from gateway.session_bot import deliver
+ gate = asyncio.Event()
+ import gateway.session_finite as finite
+ execute = finite.execute_finite_admission
+
+ async def held(authority, ref, row):
+ if row['request_id'].endswith(':retry'):
+ await gate.wait()
+ return await execute(authority, ref, row)
+
+ finite.execute_finite_admission = held
+ try:
+ bot.errors[:] = ['Error code: 429 - rate limit exceeded']
+ first = await deliver(bot.connection, dict(id=KEY, profile='default', message='ping'))
+ waiting = asyncio.create_task(await_peer_receipt(bot.authority, first, 20))
+ for _ in range(200):
+ await asyncio.sleep(0.02)
+ if len(_admissions(bot)) == 2:
+ break
+ await asyncio.sleep(0.1)
+ assert not waiting.done(), waiting.result()
+ gate.set()
+ receipt = await asyncio.wait_for(waiting, 5)
+ finally:
+ finite.execute_finite_admission = execute
+ assert (receipt['status'], receipt['reply']) == ('settled', 'pong'), receipt
+ assert receipt['retry_admission_id']