The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): a turn that failed before it ran settles failed on every surface, not only the API
Tekniumc25163b08597
diff --git a/gateway/run_turn_persistence.py b/gateway/run_turn_persistence.pyindex 551b54bdd68..8f05035f686 100644--- a/gateway/run_turn_persistence.py+++ b/gateway/run_turn_persistence.py@@ -529,7 +529,8 @@ class GatewayTurnPersistenceMixin:# Context overflow / payload too large: a deterministic rejection (#107567), and the same# no-grow rule as the persist path (#1630) — nothing is written into an oversized session.from gateway.run import _context_overflow_reply- return _context_overflow_reply()+ from gateway.session_results import record_unexecuted_failure+ return record_unexecuted_failure(_context_overflow_reply())# Replay can coalesce inputs; only this input's durable marker establishes ownership.try:if prepared.message_text is not None and session_entry is not None:@@ -569,9 +570,10 @@ class GatewayTurnPersistenceMixin:status_hint = t("gateway.errors.hint_usage_limit")elif status_code == 400:status_hint = t("gateway.errors.hint_rejected")- return self._hmwa_add_failed_turn_notice(+ from gateway.session_results import record_unexecuted_failure+ return record_unexecuted_failure(self._hmwa_add_failed_turn_notice(t("gateway.errors.generic_failed_with_hint", hint=status_hint), PARTIAL_FAILED_TURN_NOTICE,- )+ ))def _hmwa_discard_stale_result(self, source, _quick_key, run_generation):"""A newer run generation superseded this turn: drop its deferred post-delivery callback."""diff --git a/gateway/run_turn_prepare.py b/gateway/run_turn_prepare.pyindex 822f9120092..ba76040bfdc 100644--- a/gateway/run_turn_prepare.py+++ b/gateway/run_turn_prepare.py@@ -687,7 +687,8 @@ class GatewayTurnPrepareMixin:)except TranscriptReadError:self._clear_session_env(_session_env_tokens)- return t("gateway.errors.history_unavailable"), _session_env_tokens+ from gateway.session_results import record_unexecuted_failure+ return record_unexecuted_failure(t("gateway.errors.history_unavailable")), _session_env_tokensawait self._hmwa_first_contact_notes(source, history, turn_sidecar_notes, event.text, internal=event.internal)diff --git a/gateway/session_ingress.py b/gateway/session_ingress.pyindex 4afcc2d9c69..7e60b81b95a 100644--- a/gateway/session_ingress.py+++ b/gateway/session_ingress.py@@ -126,9 +126,11 @@ async def execute_admission(authority, ref, row):response = await authority.runner._handle_message(event)result = captured.get('result')if result is None:- # No TurnRunner result means the handler answered without executing the turn- # (agent initialization failure, refusal notice). An API caller asked for work,- # so its receipt is a failure, never a completed turn with an apology as output.+ # No TurnRunner result means the handler answered without executing the turn.+ # A turn that never ran because it failed (agent initialization raised, history+ # unreadable) recorded its own failure via ``record_unexecuted_failure`` on every+ # surface; any other reply here is a deliberate notice. An API caller asked for+ # work, so its receipt is a failure either way, never a completed apology.result = {'final_response': response or '', 'messages': []}if is_api:result = {'final_response': '', 'messages': [], 'failed': True, 'completed': False,diff --git a/gateway/session_results.py b/gateway/session_results.pyindex 870d543240d..0c834c058ee 100644--- a/gateway/session_results.py+++ b/gateway/session_results.py@@ -8,6 +8,17 @@ execution_result: ContextVar[dict | None] = ContextVar("execution_result", defaufrom hermes_state_terminal import RESULT_PREFIX as _RESULT_PREFIX+def record_unexecuted_failure(reply):+ """The admitted turn never ran because it failed (agent initialization raised, history+ unreadable): commit a failed result for the executing admission, so no surface settles it+ ``completed`` with the apology as the turn's output. Returns ``reply`` unchanged."""+ captured = execution_result.get()+ if captured is not None and 'result' not in captured:+ captured['result'] = {'final_response': '', 'messages': [], 'failed': True, 'completed': False,+ 'error': str(reply or 'The admitted turn failed.')}+ return reply++def _redacted(value):"""The stored result is a state.db copy of the model's answer and history: redacted at thisstorage boundary like every transcript row (``security.redact_secrets``). The live viewerdiff --git a/tests/gateway/test_admission_results.py b/tests/gateway/test_admission_results.pyindex 8060f045d3f..80a53e2c6ff 100644--- a/tests/gateway/test_admission_results.py+++ b/tests/gateway/test_admission_results.py@@ -53,3 +53,56 @@ def test_stale_result_cannot_overwrite_settled_or_unknown_claim(tmp_path):assert newer != epochfinally:db.close()++[email protected]('fails', [True, False], ids=['agent-raised', 'plain-reply'])+async def test_a_turn_that_failed_before_running_settles_failed_on_every_surface(tmp_path, monkeypatch, fails):+ """A non-API admission whose agent turn raised before producing a TurnRunner result (agent+ initialization failure) must not settle ``completed`` with the apology as its output: ACP would+ answer the editor ``end_turn`` and a finite CLI run would exit 0. A handler reply that is not a+ failure (a notice, a command answer) still completes."""+ import asyncio+ from types import SimpleNamespace+ from gateway.config import Platform+ from gateway.platforms.event import MessageEvent+ from gateway.run import GatewayRunner+ from gateway.session import SessionSource+ from gateway.session_authority import LiveSession, SessionAuthority+ from gateway.session_contract import Principal, SessionRef, Submission+ from hermes_state_runtime import get_session_admission++ monkeypatch.setenv('HERMES_HOME', str(tmp_path))+ db = SessionDB(tmp_path / 'state.db')+ db.create_session('s', source='telegram')+ gateway = object.__new__(GatewayRunner)++ async def stop_typing(event, source):+ return None+ gateway._hmwa_stop_typing_for_turn = stop_typing+ source = SessionSource(platform=Platform.TELEGRAM, chat_id='c', user_id='human')++ async def handle(event):+ if not fails:+ return 'Noted.'+ # The production except-body of the agent turn (agent construction raised).+ return await gateway._hmwa_agent_error_reply(RuntimeError('provider init failed'), event, source, None,+ 'k', gateway._PreparedTurn([], '', None, None, None, None))+ runner = SimpleNamespace(_draining=False, config=SimpleNamespace(multiplex_profiles=False),+ _adapter_for_source=lambda source: None, _handle_message=handle)+ authority = SessionAuthority(runner, profile_id='p', instance_id='owner', db=db,+ epoch=begin_runtime_epoch(db, instance_id='owner'))+ authority.sessions['s'] = LiveSession(source, 'route')+ frames = []+ authority.sessions['s'].event_stream.observers.add(frames.append)+ try:+ receipt = await authority.submit(Principal('human', 'p', frozenset({'session:submit'}), 't'),+ Submission('r1', SessionRef('p', 's'), {'text': 'hello'}, 'queue'))+ await asyncio.wait_for(authority.sessions['s'].task, 10)+ outcome = 'failed' if fails else 'completed'+ assert get_session_admission(db, admission_id=receipt.admission_id)['outcome'] == outcome+ complete = [f['params']['payload'] for f in frames if f['params']['type'] == 'message.complete']+ assert complete[-1]['outcome'] == outcome+ assert complete[-1]['status'] == ('error' if fails else 'complete')+ finally:+ db.close()