Files
rag-technical-docs-assistant/app/modules/voice/diagnostics.py
T

191 lines
9.4 KiB
Python

"""Bounded allowlisted voice diagnostics; never log exception text or payloads."""
import logging
import re
from json import JSONDecodeError
from app.infrastructure.realtime import ProviderProtocolError
logger = logging.getLogger(__name__)
PROTOCOL_REASONS = {
"Provider frame bound": "PROVIDER_FRAME_BOUND",
"Duplicate JSON key": "DUPLICATE_PROVIDER_JSON_KEY",
"Nonfinite JSON": "NONFINITE_PROVIDER_JSON",
"Invalid Unicode scalar": "INVALID_UNICODE_SCALAR",
"JSON byte limit": "PROVIDER_JSON_BYTE_LIMIT",
"JSON string limit": "PROVIDER_JSON_STRING_LIMIT",
"JSON depth limit": "PROVIDER_JSON_DEPTH_LIMIT",
"JSON integer limit": "PROVIDER_JSON_INTEGER_LIMIT",
"JSON string keys required": "PROVIDER_JSON_KEY_TYPE",
"JSON value required": "PROVIDER_JSON_VALUE_TYPE",
'Assistant transcript layout': 'ASSISTANT_TRANSCRIPT_LAYOUT',
'Audio after terminal generation': 'AUDIO_AFTER_TERMINAL_GENERATION',
'Audio item type': 'AUDIO_ITEM_TYPE',
'Audio scratch bound': 'AUDIO_SCRATCH_BOUND',
'Base64 size': 'BASE64_SIZE',
'Bounded diagnostic text required': 'BOUNDED_DIAGNOSTIC_TEXT_REQUIRED',
'Call rebound to another function item': 'CALL_REBOUND_TO_ANOTHER_FUNCTION_ITEM',
'Conflicting completed input transcript': 'CONFLICTING_COMPLETED_INPUT_TRANSCRIPT',
'Conflicting completed transcript': 'CONFLICTING_COMPLETED_TRANSCRIPT',
'Conflicting event replay': 'CONFLICTING_EVENT_REPLAY',
'Conflicting input start': 'CONFLICTING_INPUT_START',
'Conflicting input stop': 'CONFLICTING_INPUT_STOP',
'Conflicting terminal': 'CONFLICTING_TERMINAL',
'Control schema': 'CONTROL_SCHEMA',
'Diagnostic item confirmation mismatch': 'DIAGNOSTIC_ITEM_CONFIRMATION_MISMATCH',
'Event before readiness': 'EVENT_BEFORE_READINESS',
'Event type required': 'EVENT_TYPE_REQUIRED',
'Forged/rebound call': 'FORGED_REBOUND_CALL',
'Function item rebound to another call': 'FUNCTION_ITEM_REBOUND_TO_ANOTHER_CALL',
'Function item type rebound': 'FUNCTION_ITEM_TYPE_REBOUND',
'Input ordering': 'INPUT_ORDERING',
'Input stop boundary': 'INPUT_STOP_BOUNDARY',
'Input transcript layout': 'INPUT_TRANSCRIPT_LAYOUT',
'Invalid backend tool deadline/call bound': 'INVALID_BACKEND_TOOL_DEADLINE_CALL_BOUND',
'Invalid native tool phase': 'INVALID_NATIVE_TOOL_PHASE',
'Late audio': 'LATE_AUDIO',
'Late unknown tool': 'LATE_UNKNOWN_TOOL',
'Output identity capacity': 'OUTPUT_IDENTITY_CAPACITY',
'Output item position rebound': 'OUTPUT_ITEM_POSITION_REBOUND',
'Output item rebound': 'OUTPUT_ITEM_REBOUND',
'Output position': 'OUTPUT_POSITION',
'Output position rebound': 'OUTPUT_POSITION_REBOUND',
'Output type rebound': 'OUTPUT_TYPE_REBOUND',
'PCM alignment': 'PCM_ALIGNMENT',
'Provider error object required': 'PROVIDER_ERROR_OBJECT_REQUIRED',
'Provider identity bound': 'PROVIDER_IDENTITY_BOUND',
'Provider object required': 'PROVIDER_OBJECT_REQUIRED',
'Raw control bytes required': 'RAW_CONTROL_BYTES_REQUIRED',
'Reference capacity': 'REFERENCE_CAPACITY',
'Repeated terminal call': 'REPEATED_TERMINAL_CALL',
'Repeated terminal item': 'REPEATED_TERMINAL_ITEM',
'Response creation identity conflict': 'RESPONSE_CREATION_IDENTITY_CONFLICT',
'Terminal call-set mismatch': 'TERMINAL_CALL_SET_MISMATCH',
'Terminal output-item set mismatch': 'TERMINAL_OUTPUT_ITEM_SET_MISMATCH',
'Tool argument bound': 'TOOL_ARGUMENT_BOUND',
'Transcript delta after completion': 'TRANSCRIPT_DELTA_AFTER_COMPLETION',
'Transcript string required': 'TRANSCRIPT_STRING_REQUIRED',
'Unacknowledged setup': 'UNACKNOWLEDGED_SETUP',
'Unexpected cancellation': 'UNEXPECTED_CANCELLATION',
'Unknown function': 'UNKNOWN_FUNCTION',
'Unknown response': 'UNKNOWN_RESPONSE',
'Unknown terminal output item': 'UNKNOWN_TERMINAL_OUTPUT_ITEM',
'Unsolicited response': 'UNSOLICITED_RESPONSE',
'Unsupported audio layout': 'UNSUPPORTED_AUDIO_LAYOUT',
'Unsupported native adapter event': 'UNSUPPORTED_NATIVE_ADAPTER_EVENT',
'Unsupported output item': 'UNSUPPORTED_OUTPUT_ITEM',
'Unsupported output layout': 'UNSUPPORTED_OUTPUT_LAYOUT',
'Unsupported output type': 'UNSUPPORTED_OUTPUT_TYPE',
'Validated runtime settings required': 'VALIDATED_RUNTIME_SETTINGS_REQUIRED',
}
EVENT_TYPES = frozenset({
'error',
'response.content_part.added',
'response.content_part.done',
'conversation.item.input_audio_transcription.delta',
'conversation.item.input_audio_transcription.completed',
'conversation.item.input_audio_transcription.failed',
'conversation.item.added',
'conversation.item.create',
'conversation.item.created',
'conversation.item.truncate',
'conversation.item.truncated',
'input_audio_buffer.append',
'input_audio_buffer.committed',
'input_audio_buffer.speech_started',
'input_audio_buffer.speech_stopped',
'provider.input_consumed',
'provider.input_consumed_text',
'provider.tools_requested',
'response.cancel',
'response.create',
'response.created',
'response.done',
'response.function_call_arguments.done',
'response.output_audio.delta',
'response.output_audio.done',
'response.output_audio_transcript.delta',
'response.output_audio_transcript.done',
'response.output_item.added',
'response.output_item.done',
'session.created',
'session.update',
'session.updated',
})
NUMERIC_FIELDS = frozenset({
"reported_source_count", "available_source_count", "rejected_source_count",
"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",
"speech_bytes", "elapsed_ms", "deadline_remaining_ms", "sent_bytes", "played_ms", "pending_commands",
"pending_responses", "pending_audio", "pending_tasks", "abort_succeeded", "input_bytes", "http_status",
})
def trace(session_id, stage, *, turn_ref=None, audio_ref=None, **state):
"""Opt-in INFO timeline, using application references and numeric counters only."""
if not logger.isEnabledFor(logging.INFO):
return
def reference(value, pattern):
return value if isinstance(value, str) and re.fullmatch(pattern, value) else "none"
numbers = " ".join(f"{key}={max(-2147483648, min(value, 2147483647))}"
for key, value in sorted(state.items())
if key in NUMERIC_FIELDS and type(value) is int)
logger.info("Voice trace session=%s stage=%s turn=%s audio=%s state=%s",
reference(session_id, r"[a-fA-F0-9-]{1,36}"), stage,
reference(turn_ref, r"live-turn-[0-9]{1,10}"),
reference(audio_ref, r"live-audio-[a-f0-9]{32}"), numbers)
def diagnostic(session_id, phase, reason, *, event_type=None, exc=None, code=None, **state):
# Unknown event types and exception messages can contain private provider data.
numbers = " ".join(f"{key}={max(-2147483648, min(value, 2147483647))}"
for key, value in sorted(state.items())
if key in NUMERIC_FIELDS and type(value) is int)
logger.warning("Voice diagnostic session=%s phase=%s event=%s exception=%s reason=%s code=%s state=%s",
session_id, phase, event_type if isinstance(event_type, str) and event_type in EVENT_TYPES else "unknown",
type(exc).__name__[:64] if exc is not None else "none", reason, code or "none", numbers)
def protocol_reason(exc):
if isinstance(exc, ProviderProtocolError) and exc.__cause__ is not None:
exc = exc.__cause__
if isinstance(exc, JSONDecodeError):
return "MALFORMED_PROVIDER_JSON"
if isinstance(exc, ValueError):
return PROTOCOL_REASONS.get(str(exc), "INVALID_PROVIDER_EVENT")
if isinstance(exc, KeyError):
return "MISSING_PROVIDER_FIELD"
return "INVALID_PROVIDER_EVENT"
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"