The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): persist inactivity timeouts as failed admissions
David Dudok de Witc55cd732c887
diff --git a/gateway/run_turn.py b/gateway/run_turn.pyindex 35cbd6a6886..fc9622b6067 100644--- a/gateway/run_turn.py+++ b/gateway/run_turn.py@@ -1589,6 +1589,7 @@ class GatewayTurnMixin(GatewayTurnPrepareMixin, GatewayTurnHygieneMixin, Gateway"""Synthetic failed run dict for an inactivity timeout, with the activity-tracker diagnostic;interrupts the agent if it is still running so the thread pool worker is freed."""from gateway.run import _INTERRUPT_REASON_TIMEOUT, _INTERRUPT_TOOL_REASON_TIMEOUT, request_hard_interrupt+ from gateway.session_results import record_terminal_failuresession_key, result_holder, tools_holder = turn_ctx.session_key, turn_ctx.result_holder, turn_ctx.tools_holder_timed_out_agent = turn_ctx.agent_holder[0]_activity = self._agent_activity_summary(_timed_out_agent)@@ -1618,14 +1619,14 @@ class GatewayTurnMixin(GatewayTurnPrepareMixin, GatewayTurnHygieneMixin, Gateway"gateway.progress.timeout_last_activity",activity=_last_desc, seconds=f"{_secs_ago:.0f}", progress=_iter_progress))_diag_lines.append(t("gateway.progress.timeout_hint"))- return {+ return record_terminal_failure({"final_response": "\n".join(_diag_lines),"messages": result_holder[0].get("messages", []) if result_holder[0] else [],"api_calls": _iter_n,"tools": tools_holder[0] or [],"history_offset": 0,"failed": True,- }+ })async def _run_agent_await_turn_worker(self, worker: "GatewayRunner._RunAgentWorker", turn_ctx: TurnContext,diff --git a/gateway/session_ingress.py b/gateway/session_ingress.pyindex 981ee7bb255..b3c28d3fb99 100644--- a/gateway/session_ingress.py+++ b/gateway/session_ingress.py@@ -127,7 +127,7 @@ async def execute_admission(authority, ref, row):event.allow_gateway_control = Falseevent.internal = True # trust comes from the private binding and preclaim, never client JSONresponse = await authority.runner._handle_message(event)- result = captured.get('result')+ result = captured.get('terminal_result', captured.get('result'))if result is None:# No TurnRunner result means the handler answered without executing the turn.# A turn that never ran because it failed (agent initialization raised, historydiff --git a/gateway/session_results.py b/gateway/session_results.pyindex 0c834c058ee..e133da71e1a 100644--- a/gateway/session_results.py+++ b/gateway/session_results.py@@ -19,6 +19,14 @@ def record_unexecuted_failure(reply):return reply+def record_terminal_failure(result):+ """Retain an owner-side failure even if an abandoned executor returns while delivery unwinds."""+ captured = execution_result.get()+ if captured is not None:+ captured['terminal_result'] = result+ return result++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_inactivity_timeout_receipt.py b/tests/gateway/test_inactivity_timeout_receipt.pynew file mode 100644index 00000000000..b1572941626--- /dev/null+++ b/tests/gateway/test_inactivity_timeout_receipt.py@@ -0,0 +1,74 @@+"""A watchdog timeout remains failed when the handler projects its diagnostic as text."""+from types import SimpleNamespace+import time++import pytest++from gateway.config import Platform+from gateway.session import SessionSource+from gateway.session_authority import LiveSession+from gateway.session_contract import SessionRef+from hermes_state_runtime import admit_session_input, claim_session_input, get_session_admission++[email protected]('platform', [Platform.LOCAL, Platform.TELEGRAM])[email protected]('late_result', [False, True])+async def test_timeout_diagnostic_keeps_failed_receipt_after_string_projection(owner, platform, late_result):+ from gateway.run import GatewayRunner+ from gateway.run_turn_persistence import GatewayTurnPersistenceMixin+ from gateway.session_ingress import execute_admission+ from gateway.session_results import execution_result, finish_result, admission_result+ from gateway.turn_context import TurnContext+ owner.db.create_session('s', source='cli')+ source = SessionSource(platform, 's', user_id='human')+ owner.sessions['s'] = LiveSession(source, 'route')+ owner.runner._adapter_for_source = lambda source: None+ owner.runner._agent_activity_summary = lambda agent: {'seconds_since_activity': 1800}+ owner.runner._is_intentional_silence = lambda *args: False+ diagnostic = []++ async def handle(event):+ raw = GatewayRunner._run_agent_timeout_result(owner.runner,+ SimpleNamespace(agent_timeout=1800), TurnContext(session_key='route'))+ response, _, _ = await GatewayTurnPersistenceMixin._hmwa_shape_agent_response(+ owner.runner, raw, source, [], SimpleNamespace(session_id='s'), None,+ None, 1, 's', platform.value, time.time())+ diagnostic.append(response)+ if late_result:+ # The abandoned executor shares the capture dict and can return while the handler+ # is still unwinding. Its later value cannot replace the owner's timeout verdict.+ execution_result.get()['result'] = {'final_response': 'late worker answer', 'completed': True}+ return response++ owner.runner._handle_message = handle+ admitted = admit_session_input(owner.db, epoch=owner.epoch, principal_id='human',+ session_id='s', request_id='timeout', payload={'text': 'work'})+ row = claim_session_input(owner.db, epoch=owner.epoch, session_id='s')+ response = await execute_admission(owner, SessionRef(owner.profile_id, 's'), row)+ finish_result(owner.db, epoch=owner.epoch, row=row, response=response, outcome='completed',+ result=owner.pending_results[admitted['admission_id']])+ saved = admission_result(owner.db, admitted['admission_id'])['result']+ assert get_session_admission(owner.db, admission_id=admitted['admission_id'])['outcome'] == 'failed'+ assert saved['failed'] is True and saved['completed'] is False+ assert saved['final_response'] == response == diagnostic[0]+++async def test_owner_notice_without_execution_is_still_completed(owner):+ from gateway.session_ingress import execute_admission+ from gateway.session_results import finish_result+ owner.db.create_session('notice', source='telegram')+ source = SessionSource(Platform.TELEGRAM, 'notice', user_id='human')+ owner.sessions['notice'] = LiveSession(source, 'notice-route')+ owner.runner._adapter_for_source = lambda source: None+ async def notice(event):+ return 'Gateway is paused by the operator.'+ owner.runner._handle_message = notice+ admitted = admit_session_input(owner.db, epoch=owner.epoch, principal_id='human',+ session_id='notice', request_id='notice', payload={'text': 'work'})+ row = claim_session_input(owner.db, epoch=owner.epoch, session_id='notice')+ response = await execute_admission(owner, SessionRef(owner.profile_id, 'notice'), row)+ finish_result(owner.db, epoch=owner.epoch, row=row, response=response, outcome='completed',+ result=owner.pending_results[admitted['admission_id']])+ assert get_session_admission(owner.db, admission_id=admitted['admission_id'])['outcome'] == 'completed'