Skip to content

The agent that grows with you

fix: the Bot Chat owner retries a transiently failed DM delivery once

Tekniumf879c0c627ed
diff --git a/agent/session_persistence.py b/agent/session_persistence.py
index 8c0f6e79785..cf7ae48981e 100644
--- a/agent/session_persistence.py
+++ b/agent/session_persistence.py
@@ -149,13 +149,11 @@ def adopt_unanswered_turn(history: List[Dict[str, Any]], query: Any, agent: Any)
A dispatcher's re-run of a failed delivery turn resumes the DM its first attempt already persisted
instead of appending it again. Rows loaded from the store are born durable (``_rows_to_conversation``),
so handing the tail row back as ``agent._pending_cli_user_message`` makes ``_stage_turn_user_message``
- reuse it as this turn's user dict and the flush writes no second row. What differs per lane is only HOW
- the dispatcher knows the DM is unanswered:
-
- * ``hermes_cli.quiet_single_query.adopt_unanswered_turn`` — the delivery lanes' re-run is a fresh CLI
- process, told so through ``tools.bot_relay.RESUME_UNANSWERED_TURN_ENV``.
- * ``gateway.platforms.api_server`` — the peer-DM lane re-runs the turn in-process and calls this
- directly on the agent it just built for the re-run (#115325).
+ reuse it as this turn's user dict and the flush writes no second row. The one caller is
+ ``gateway.platforms.api_server`` (``resume_unanswered_turn``): the peer-DM lane re-runs the turn
+ in-process and calls this on the agent it just built for the re-run (#115325). The owner-side Bot
+ Chat retry (``gateway.session_bot._maybe_retry``) does not adopt: its failed turn is already closed
+ by the durable failed-turn boundary, which this function declines by design.
The DM is not always the literal tail: a turn that died mid-way persisted its tool scaffolding — assistant
``tool_calls`` rows and their ``tool`` results — behind the DM before the failure text was built, and the
diff --git a/gateway/session_bot.py b/gateway/session_bot.py
index fdb813c1945..a88bca74756 100644
--- a/gateway/session_bot.py
+++ b/gateway/session_bot.py
@@ -115,8 +115,9 @@ def _create_bot_chat(authority, actor):
return ref
-def _result(authority, record):
- row = get_session_admission(authority.db, admission_id=record['admission_id'])
+def _admission_outcome(authority, admission_id, fallback=None):
+ """``(status, reply)`` of one admission, read from its committed result, never transcript recency."""
+ row = get_session_admission(authority.db, admission_id=admission_id)
if row is None:
raise RuntimeStoreError('storage_unavailable')
# A terminal row without a result blob is still definitive when the outcome says the
@@ -124,10 +125,9 @@ def _result(authority, record):
# durable unknown state and for missing evidence (completed/interrupted without result).
status = {'queued': 'queued', 'started': 'claimed', 'unknown': 'ambiguous',
'terminal': {'cancelled': 'cancelled', 'rejected': 'failed', 'failed': 'failed'}.get(row['outcome'], 'ambiguous')}[row['status']]
- # Read only this admission's committed result, never transcript recency.
from gateway.session_results import admission_result
- saved = admission_result(authority.db, record['admission_id'])
- reply = record.get('reply', '')
+ saved = admission_result(authority.db, admission_id)
+ reply = (fallback or {}).get('reply', '')
if saved is not None:
reply = saved['result'].get('final_response', '')
status = 'settled' if row['outcome'] == 'completed' else 'failed'
@@ -137,11 +137,99 @@ def _result(authority, record):
from gateway.response_filters import is_intentional_silence_response
if status == 'settled' and is_intentional_silence_response(reply):
reply = ''
- elif record.get('status') in {'settled', 'failed'}:
- status = record['status']
+ elif fallback is not None and fallback.get('status') in {'settled', 'failed'}:
+ status = fallback['status']
+ return status, reply
+
+
+def _retry_admission(authority, record):
+ """The delivery's one retry admission id, read from the FIFO by its derived identity, so every
+ reader (an in-memory record, the receipt file, an owner restart) follows the same retry."""
+ with authority.db._read_ctx() as conn:
+ row = conn.execute('SELECT admission_id FROM session_admissions WHERE target_session_id=? AND request_id=?',
+ (record['session_id'], _retry_identity(record['delivery_id']))).fetchone()
+ return row[0] if row else None
+
+
+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``)."""
+ retry_id = _retry_admission(authority, record)
+ if retry_id:
+ status, reply = _admission_outcome(authority, retry_id)
+ else:
+ status, reply = _admission_outcome(authority, record['admission_id'], record)
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).items()}
+ admission_id=record['admission_id'], message=record['message'], reply=reply,
+ retry_admission_id=retry_id).items() if v is not None}
+
+
+def _retry_identity(key):
+ return 'bot:' + key + ':retry'
+
+
+def _retry_eligible(authority, record):
+ """Exactly the main-lane gate (``tools.bot_failure_reasons.result_retry_action``): the original
+ admission SETTLED ``failed`` with a committed result whose error classifies transient (429/5xx/
+ context overflow). queued/started/unknown admissions never qualify — unknown execution is never
+ replayed — and the retry itself is never retried."""
+ if (record.get('retry') or {}).get('refused') or _retry_admission(authority, record):
+ return False
+ row = get_session_admission(authority.db, admission_id=record['admission_id'])
+ if row is None or row['status'] != 'terminal' or row['outcome'] != 'failed':
+ return False
+ from gateway.session_results import admission_result
+ saved = admission_result(authority.db, record['admission_id'])
+ if saved is None:
+ return False
+ from tools.bot_failure_reasons import RETRY_NONE, result_retry_action
+ return result_retry_action(saved['result']) != RETRY_NONE
+
+
+async def _maybe_retry(authority, home, path, record):
+ """Admit the delivery's one retry under a DERIVED identity recorded on the same receipt, so a
+ repeated deliver(), an owner restart or a second settle re-reads that admission instead of
+ minting another. The identity is written before the admission: a death in that two-store window
+ re-admits the SAME identity, which the FIFO answers with the existing row (never a second turn).
+
+ No user-row adoption: a transient owner-side failure persists the DM row and then CLOSES it with the
+ durable failed-turn boundary (``agent.conversation_loop._close_durable_failed_turn`` /
+ ``_hmwa_close_failed_turn``, #107070), so ``agent.session_persistence.adopt_unanswered_turn`` would
+ decline by contract (a plain assistant row follows the DM) and the retry is a fresh turn after that
+ boundary. A failure that left the DM as an OPEN tail (the context-pressure classes skip the closer)
+ is not retried: the owner execution has no adoption seam, and the retry's DM would merge into it."""
+ if not _retry_eligible(authority, record):
+ return
+ identity = _retry_identity(record['delivery_id'])
+ actor = Principal(record['principal_id'], authority.profile_id, frozenset({'session:submit', 'session:read'}),
+ 'bot-delivery-retry')
+ try:
+ authority._require_admission_open()
+ ref, live, entry = _target(authority, actor)
+ if ref.session_id != record['session_id']:
+ raise RuntimeStoreError('admission_conflict')
+ if authority.db.latest_conversation_role(entry.session_id) == 'user':
+ raise RuntimeStoreError('open_user_tail')
+ except RuntimeStoreError as exc:
+ if exc.reason == 'runtime_draining':
+ return # nothing recorded: the restarted owner's recovery re-evaluates the same gate
+ record['retry'] = {'identity': identity, 'refused': exc.reason}
+ _write(path, record)
+ return
+ event = MessageEvent(text=record['message'], source=live.source, internal=True,
+ message_id=identity, metadata={'gateway_session_key': live.route, 'gateway_session_id': entry.session_id})
+ from gateway.session_automation import automation_notification_metadata
+ event.metadata.update(automation_notification_metadata(record))
+ if record.get('author') is not None:
+ event.metadata['turn_author'] = dict(record['author'])
+ record['retry'] = {'identity': identity}
+ _write(path, record)
+ receipt = await authority.admit_automation(authority.runner._adapter_for_source(live.source), event, identity)
+ record.update(_result(authority, record))
+ _write(path, record)
+ if receipt.status in {'queued', 'started'}:
+ _watch_reply(authority, home, record['delivery_id'], receipt.admission_id)
async def _record_reply(authority, home, key, future):
@@ -151,6 +239,7 @@ async def _record_reply(authority, home, key, future):
record = _read(path)
record.update(_result(authority, record))
_write(path, record)
+ await _maybe_retry(authority, home, path, record)
def relay_operation(connection, operation, params):
@@ -215,7 +304,10 @@ async def recover_bot_deliveries(authority):
record.update(_result(authority, record))
_write(path, record)
if record['status'] in {'queued', 'claimed'}:
- _watch_reply(authority, home, record['delivery_id'], record['admission_id'])
+ _watch_reply(authority, home, record['delivery_id'],
+ record.get('retry_admission_id') or record['admission_id'])
+ else:
+ await _maybe_retry(authority, home, path, record)
row = authority.db.get_session_by_title('Bot Chat')
if row is None:
return
@@ -271,6 +363,7 @@ async def deliver(connection, params):
or record.get('notification_category', 'result') != category):
raise RuntimeStoreError('admission_conflict')
authority.authorize(actor, SessionRef(authority.profile_id, record['session_id']), 'session:submit')
+ await _maybe_retry(authority, home, path, record)
return _result(authority, record)
await _migrate(authority, actor, home, root)
record = _read(path)
@@ -280,6 +373,7 @@ async def deliver(connection, params):
or record.get('notification_category', 'result') != category):
raise RuntimeStoreError('admission_conflict')
authority.authorize(actor, SessionRef(authority.profile_id, record['session_id']), 'session:submit')
+ await _maybe_retry(authority, home, path, record)
return _result(authority, record)
if record is not None:
raise RuntimeStoreError('unknown_execution')
diff --git a/tests/gateway/test_session_bot_retry.py b/tests/gateway/test_session_bot_retry.py
new file mode 100644
index 00000000000..67b9fa45e29
--- /dev/null
+++ b/tests/gateway/test_session_bot_retry.py
@@ -0,0 +1,118 @@
+"""The owner retries a transiently failed Bot DM delivery exactly once, never unknown execution.
+
+``gateway/session_bot.py`` admits a Bot Chat delivery into the authority FIFO. When that admission
+SETTLES ``failed`` with a committed result whose error classifies transient
+(``tools.bot_failure_reasons.result_retry_action``), one retry is admitted under the derived
+identity ``bot:<id>:retry``; the delivery's receipt follows it. A repeated ``deliver`` of the same
+id or an owner restart (``recover_bot_deliveries``) re-reads that admission instead of minting
+another, and an unknown/non-transient admission is never replayed.
+"""
+import asyncio
+from types import SimpleNamespace
+
+import pytest
+import pytest_asyncio
+
+from gateway.session_contract import Principal
+from hermes_state_runtime import list_session_admissions
+
+KEY = 'c' * 32
+
+
+@pytest_asyncio.fixture
+async def bot(tmp_path, monkeypatch):
+ from gateway import run
+ from gateway.config import GatewayConfig
+ from gateway.session import SessionStore
+ from gateway.session_authority import initialize_session_authority
+ from gateway.session_local import create_local_session
+ from gateway.session_local_title import title_new_session
+ from hermes_state import SessionDB
+
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'platform_toolsets': {'cli': []}})
+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())
+ store._db = SessionDB(db_path=tmp_path / 'state.db')
+ runner = SimpleNamespace(session_store=store, _session_db=store._db, adapters={}, _draining=False,
+ _evict_cached_agent=lambda route: None)
+ runner._adapter_for_source = lambda source: runner.adapters.get(source.platform)
+ authority = await initialize_session_authority(runner, profile_id='default', instance_id='fixture')
+ owner = Principal('uid:1000', 'default', frozenset({'session:create', 'session:read', 'session:submit'}), 'native')
+ chat = create_local_session(authority, owner, {'request_id': 'bot', 'source': 'gui', 'cwd': str(tmp_path),
+ 'model': 'fixture', 'toolsets': []})
+ title_new_session(authority, chat, 'Bot Chat')
+ errors = []
+
+ async def execute(authority, ref, row):
+ error = errors.pop(0) if errors else None
+ if error is None:
+ return 'pong'
+ authority.pending_results[row['admission_id']] = {
+ 'result': {'final_response': '', 'messages': [], 'failed': True, 'error': error}, 'usage': {}}
+ return ''
+
+ monkeypatch.setattr('gateway.session_finite.execute_finite_admission', execute)
+ try:
+ yield SimpleNamespace(authority=authority, chat=chat.session_id, errors=errors, home=tmp_path,
+ connection=SimpleNamespace(authority=authority, actor=owner))
+ finally:
+ store._db.close()
+
+
+def _admissions(bot):
+ return list_session_admissions(bot.authority.db, session_id=bot.chat, pending_only=False)
+
+
+async def _settled(bot, count):
+ from gateway.session_bot import _result
+ from tools.bot_live_delivery import _read, _root
+ for _ in range(200):
+ await asyncio.sleep(0.02)
+ rows = _admissions(bot)
+ if len(rows) >= count and all(r['status'] == 'terminal' for r in rows):
+ await asyncio.sleep(0.05) # let the receipt task observe the settle
+ return _result(bot.authority, _read(_root(bot.home) / f'{KEY}.json'))
+ raise AssertionError(f'admissions never settled: {_admissions(bot)}')
+
+
+async def test_transient_failure_retries_exactly_once_and_the_receipt_follows_the_retry(bot):
+ from gateway.session_bot import deliver, recover_bot_deliveries
+ params = dict(id=KEY, profile='default', message='ping')
+ bot.errors[:] = ['Error code: 429 - rate limit exceeded']
+ first = await deliver(bot.connection, params)
+ receipt = await _settled(bot, 2)
+ assert receipt['status'] == 'settled' and receipt['reply'] == 'pong', receipt
+ assert receipt['admission_id'] == first['admission_id'] and receipt['retry_admission_id']
+ assert [r['request_id'] for r in _admissions(bot)] == ['bot:' + KEY, 'bot:' + KEY + ':retry']
+ # A repeated delivery of the same id and an owner restart re-read the one retry; never a third.
+ again = await deliver(bot.connection, params)
+ assert again['status'] == 'settled' and again['reply'] == 'pong'
+ await recover_bot_deliveries(bot.authority)
+ await asyncio.sleep(0.05)
+ assert len(_admissions(bot)) == 2
+
+
+async def test_retry_that_fails_again_and_non_transient_failures_are_never_replayed(bot):
+ from gateway.session_bot import deliver, recover_bot_deliveries
+ # The retry itself fails transiently: the sender sees that failure, no second retry.
+ bot.errors[:] = ['HTTP 503 server error', 'HTTP 503 server error']
+ 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']
+ await deliver(bot.connection, dict(id=KEY, profile='default', message='ping'))
+ await recover_bot_deliveries(bot.authority)
+ await asyncio.sleep(0.1)
+ assert len(_admissions(bot)) == 2
+ # Auth failures do not classify transient: settled failed, never retried.
+ other = 'd' * 32
+ bot.errors[:] = ['Error code: 401 - invalid api key']
+ await deliver(bot.connection, dict(id=other, profile='default', message='auth'))
+ for _ in range(100):
+ await asyncio.sleep(0.02)
+ if all(r['status'] == 'terminal' for r in _admissions(bot)) and len(_admissions(bot)) == 3:
+ break
+ await recover_bot_deliveries(bot.authority)
+ await asyncio.sleep(0.1)
+ assert [r['request_id'] for r in _admissions(bot)][2:] == ['bot:' + other]
diff --git a/tools/bot_relay.py b/tools/bot_relay.py
index 144d7b458d5..018bd1dfad3 100644
--- a/tools/bot_relay.py
+++ b/tools/bot_relay.py
@@ -41,9 +41,10 @@ LOCKS_DIR = "locks"
# Config fallbacks (real knobs: ``bot_mode.turn_wait_seconds`` / ``bot_mode.envelope_ttl_seconds``).
TURN_WAIT_SECONDS_FALLBACK = 120
DEFAULT_ENVELOPE_TTL_SECONDS = 900 # older envelopes are refused at drain with 'queued_expired'
-# Per-attempt turn timeout and attempt ceiling for bot_relay.deliver (tui_gateway/methods_bot_relay.py).
+# Per-attempt turn budget and attempt ceiling of one relayed delivery: the owner admits the turn and, when it
+# settles failed with a transient error, ONE retry under a derived identity (``gateway.session_bot._maybe_retry``).
TURN_ATTEMPT_TIMEOUT_SECONDS = 600
-TURN_MAX_ATTEMPTS = 2 # first attempt + the policy-gated re-run
+TURN_MAX_ATTEMPTS = 2 # first admission + the owner's one transient-failure retry (gateway.session_bot)
# Mirrors RELAY_DELIVER_TIMEOUT_MS in apps/desktop/src/plugins/hermes-bots/relay-budget.ts; both test suites pin it.
DESKTOP_DELIVER_SETTLEMENT_MARGIN_SECONDS = 180
DESKTOP_DELIVER_TIMEOUT_SECONDS = (
diff --git a/tui_gateway/methods_bot_relay.py b/tui_gateway/methods_bot_relay.py
index f9fbba85b89..d77f200e538 100644
--- a/tui_gateway/methods_bot_relay.py
+++ b/tui_gateway/methods_bot_relay.py
@@ -23,9 +23,9 @@ def _relay_root() -> Path:
return _hermes_root(Path(_default_home()))
-# Historical Desktop deadline mirrors; no subprocess retry is performed here.
-# Remove with the renderer relay deadline/receipt migration.
-TURN_MAX_ATTEMPTS = 2 # first attempt + the policy-gated re-run
+# Desktop deadline mirror; no retry runs here. The owner gateway retries a transiently failed
+# admission once (``gateway.session_bot._maybe_retry``). Remove with the renderer relay deadline migration.
+TURN_MAX_ATTEMPTS = 2 # first admission + the owner's one transient-failure retry (gateway.session_bot)
@method("bot_relay.roster.sync")