From 15558fd8502ce9eb1f614cb6e749662ac73714bd Mon Sep 17 00:00:00 2001 From: amirhosein mazaheri Date: Tue, 13 Oct 2026 14:59:48 +0330 Subject: [PATCH] fix(voice): attribute provider terminal failures safely --- app/modules/voice/diagnostics.py | 26 ++++++++++++++++++ app/modules/voice/runtime.py | 12 ++++++++- docs/guides/live-context-sync-repair.md | 21 +++++++++++++++ tests/unit/test_live_context_sync.py | 35 ++++++++++++++++++++++++- tests/unit/test_openai_output_limit.py | 4 ++- 5 files changed, 95 insertions(+), 3 deletions(-) diff --git a/app/modules/voice/diagnostics.py b/app/modules/voice/diagnostics.py index 9264b6e..52de570 100644 --- a/app/modules/voice/diagnostics.py +++ b/app/modules/voice/diagnostics.py @@ -118,6 +118,7 @@ NUMERIC_FIELDS = frozenset({ "generated_bytes", "queued_bytes", "reserved_bytes", "credit_bytes", "discarded_bytes", "chunk_bytes", "lock_wait_ms", "backlog_bytes", "peak_backlog_bytes", "received_elapsed_ms", "terminal_completed", "terminal_cancelled", "terminal_limited", + "terminal_failed", "terminal_incomplete", "terminal_tool_calls", "terminal_output_items", "authority_ms", "emit_ms", "queued_controls", "cancellation_type_match", "cancellation_code_match", "cancellation_param_match", "cancellation_profile_2_1_shimmer", "transport_limit_bytes", "transport_limit_messages", "occupancy_count", "limit_count", "occupancy_bytes", "limit_bytes", "transport_bytes", "transport_messages", @@ -162,3 +163,28 @@ def protocol_reason(exc): def terminal_failed(code): return code.startswith("LIVE_") or code in ( "SEARCH_TIMEOUT", "SEARCH_SATURATED", "DEPENDENCY_UNAVAILABLE", "SEARCH_CANCELLED") + + +def terminal_failure_reason(response): + """Classify structured terminal details without retaining provider text.""" + status = response.get("status") + details = response.get("status_details") + if isinstance(details, dict): + error = details.get("error") + if status == "failed" and isinstance(error, dict): + code = error.get("code") + if isinstance(code, str): + reason = { + "server_error": "PROVIDER_RESPONSE_SERVER_ERROR", + "rate_limit_exceeded": "PROVIDER_RESPONSE_RATE_LIMIT", + "insufficient_quota": "PROVIDER_RESPONSE_QUOTA", + }.get(code) + if reason: + return reason + if status == "incomplete" and details.get("reason") == "content_filter": + return "PROVIDER_RESPONSE_CONTENT_FILTER" + if status == "failed": + return "PROVIDER_RESPONSE_FAILED" + if status == "incomplete": + return "PROVIDER_RESPONSE_INCOMPLETE" + return "PROVIDER_RESPONSE_UNEXPECTED_STATUS" diff --git a/app/modules/voice/runtime.py b/app/modules/voice/runtime.py index 38a9359..1ffc84d 100644 --- a/app/modules/voice/runtime.py +++ b/app/modules/voice/runtime.py @@ -15,7 +15,7 @@ from app.modules.knowledge.langchain_tool import ToolContext, create_search_tool from app.modules.knowledge.service import SearchInput, authority, transaction from app.infrastructure.realtime import canonical_json, strict_json, ProviderProtocolError from app.modules.voice.settings import RuntimeSettings -from app.modules.voice.diagnostics import diagnostic, protocol_reason, trace +from app.modules.voice.diagnostics import diagnostic, protocol_reason, terminal_failure_reason, trace from app.modules.voice.serialization import bounded_json, json_size, bounded_json_digest def identity(): @@ -721,6 +721,8 @@ class VoiceRuntime: self.sync_failed("PROVIDER_TRANSPORT_LOST_DURING_SYNC", phase="provider_receive", exc=exc, turn=self.cleanup_owner()) else: + diagnostic(self.session_id, "provider_receive", "PROVIDER_TRANSPORT_LOST", + exc=exc, code="LIVE_PROVIDER_UNAVAILABLE") self.fail("LIVE_PROVIDER_UNAVAILABLE") async def _sender(self): @@ -1542,11 +1544,19 @@ class VoiceRuntime: return limited = bool(getattr(self.adapter, "token_limited", lambda _: False)(wire)) if wire["status"] not in ("completed", "cancelled", "waiting_tools") and not limited: + diagnostic(self.session_id, "provider_terminal", terminal_failure_reason(wire), + event_type=kind, code="LIVE_PROVIDER_UNAVAILABLE", + terminal_failed=int(wire["status"] == "failed"), + terminal_incomplete=int(wire["status"] == "incomplete"), + terminal_tool_calls=len(response.calls), terminal_output_items=len(wire["output"])) self.fail("LIVE_PROVIDER_UNAVAILABLE", turn=response.turn) return # Unfinished tool context cannot safely be reused; fail before execution. if limited and (response.calls or any( item.get("type") != "message" for item in wire["output"])): + diagnostic(self.session_id, "provider_terminal", "TOKEN_LIMIT_WITH_UNFINISHED_TOOLS", + event_type=kind, code="LIVE_PROVIDER_UNAVAILABLE", terminal_limited=1, + terminal_tool_calls=len(response.calls), terminal_output_items=len(wire["output"])) self.fail("LIVE_PROVIDER_UNAVAILABLE", turn=response.turn) return terminal_calls = set() diff --git a/docs/guides/live-context-sync-repair.md b/docs/guides/live-context-sync-repair.md index c3d90ee..3fdc63d 100644 --- a/docs/guides/live-context-sync-repair.md +++ b/docs/guides/live-context-sync-repair.md @@ -214,3 +214,24 @@ Verification: four new regression assertions failed before the fix; 114 focused synchronization, interruption and retained-search tests passed afterward. A default-disabled trace test now isolates the operator .env. Post-fix real microphone acceptance remains pending a fresh Marin session. + + +### Terminal failure attribution (2026-10-13) + +Session 9401d451-6d91-44bb-bf01-82eef13fe3aa acknowledged turn 18 +cancellation and both audio truncations. Turn 19 terminal receipt was followed +by LIVE_PROVIDER_UNAVAILABLE before terminal processing. The original trace +did not retain status_details, so the precise provider cause remains unknown. + +Rejected terminal responses now emit a bounded provider_terminal diagnostic: +fixed categories distinguish server_error, rate_limit_exceeded, +insufficient_quota, content_filter, generic failed/incomplete, and token limits +with unfinished tools. Unknown provider fields are never logged. Numeric flags +record failed/incomplete/limited states and output/tool counts. Transport loss +outside context synchronization receives a separate PROVIDER_TRANSPORT_LOST +category with exception class only. Public error envelopes, cleanup gates, +voice configuration and retry behavior remain unchanged. No automatic retry is +introduced. Real-provider attribution requires a new occurrence after deployment. + +Validation: 122 focused synchronization, interruption and retained-search tests +passed, including eight terminal failure/redaction cases. diff --git a/tests/unit/test_live_context_sync.py b/tests/unit/test_live_context_sync.py index abf2054..e947f87 100644 --- a/tests/unit/test_live_context_sync.py +++ b/tests/unit/test_live_context_sync.py @@ -6,7 +6,7 @@ from types import SimpleNamespace import pytest from tests.unit.test_realtime_phase1 import ( - runner, persisted, make, input_turn, response, delta, done, until, commands, + runner, persisted, make, input_turn, response, delta, done, until, commands, terminal, ) from tests.unit.test_realtime_repairs import Clock, without_ticker @@ -368,3 +368,36 @@ def test_no_active_classifier_is_profile_and_signature_bounded(model, voice, acc assert adapter.is_no_active(CAPTURED_NO_ACTIVE) is accepted assert not adapter.is_no_active(dict(CAPTURED_NO_ACTIVE, code="other")) assert not adapter.is_no_active(dict(CAPTURED_NO_ACTIVE, param="response_id")) + + +@pytest.mark.parametrize("status,details,reason", [ + ("failed", {"error": {"code": "server_error"}}, "PROVIDER_RESPONSE_SERVER_ERROR"), + ("failed", {"error": {"code": "rate_limit_exceeded"}}, "PROVIDER_RESPONSE_RATE_LIMIT"), + ("failed", {"error": {"code": "insufficient_quota"}}, "PROVIDER_RESPONSE_QUOTA"), + ("incomplete", {"reason": "content_filter"}, "PROVIDER_RESPONSE_CONTENT_FILTER"), + ("incomplete", {"reason": "PRIVATE_PAYLOAD"}, "PROVIDER_RESPONSE_INCOMPLETE"), + ("failed", {"error": {"code": ["PRIVATE_PAYLOAD"]}}, "PROVIDER_RESPONSE_FAILED"), + ("failed", {"error": {"code": "PRIVATE_PAYLOAD"}}, "PROVIDER_RESPONSE_FAILED"), + ("failed", None, "PROVIDER_RESPONSE_FAILED"), +]) +def test_terminal_failure_attribution_does_not_log_provider_payload( + runner, persisted, caplog, status, details, reason): + async def scenario(): + runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted) + try: + await input_turn(runtime) + await response(runtime, transport) + event = terminal(status=status) + event["response"]["status_details"] = details + event["response"]["private_text"] = "PRIVATE_PAYLOAD" + if isinstance(details, dict): + details["message"] = "PRIVATE_PAYLOAD" + await runtime.handle(event) + assert runtime.failure == "LIVE_PROVIDER_UNAVAILABLE" + assert f"reason={reason} " in caplog.text + assert f"terminal_{status}=1" in caplog.text + assert "PRIVATE_PAYLOAD" not in caplog.text + assert "PRIVATE_PAYLOAD" not in str(out) + finally: + await runtime.close() + asyncio.run(scenario()) diff --git a/tests/unit/test_openai_output_limit.py b/tests/unit/test_openai_output_limit.py index 218af12..07517f8 100644 --- a/tests/unit/test_openai_output_limit.py +++ b/tests/unit/test_openai_output_limit.py @@ -124,7 +124,7 @@ def test_other_terminal_outcomes_fail(runner, persisted, status, details): @pytest.mark.parametrize('raw', ['{"query":', '{"query":"q"}']) @pytest.mark.parametrize('argument_done', [False, True]) -def test_limited_tools_never_execute_or_continue(runner, persisted, raw, argument_done): +def test_limited_tools_never_execute_or_continue(runner, persisted, raw, argument_done, caplog): async def scenario(): service = SimpleNamespace(engine=None, search=lambda *_: pytest.fail('Cut-off tool executed')) runtime, transport, out = await make(service, runner, persisted) @@ -135,6 +135,8 @@ def test_limited_tools_never_execute_or_continue(runner, persisted, raw, argumen item = dict(type='function_call', id=event['item_id'], call_id='c1', name='search_knowledge', arguments=raw, status='incomplete') await runtime.handle(limited(output=[item])) + assert 'reason=TOKEN_LIMIT_WITH_UNFINISHED_TOOLS ' in caplog.text + assert 'terminal_limited=1' in caplog.text assert runtime.failure == 'LIVE_PROVIDER_UNAVAILABLE' assert runner._active == runner._admitted == 0 assert not commands(transport, 'conversation.item.create')