fix(voice): correct input accounting and session termination
Separate detected speech limits from continuous microphone silence while preserving transport bounds and absolute commit fencing. Handle verified OpenAI cancellation races and terminal items, preserve causal close outcomes, and share bounded cleanup ownership with safe diagnostics. Add regression coverage and align the API contract and frontend handoff. Validation: 61 focused unit tests passed; staged diff whitespace checks passed. Live browser acceptance remains outstanding.
This commit is contained in:
+19
-11
@@ -19,6 +19,7 @@ from app.modules.voice.durable_tools import DurableTools
|
||||
from app.modules.voice import registry
|
||||
from app.infrastructure.voice_provider import create_adapter
|
||||
from app.modules.voice.authority import authority_failure_code
|
||||
from app.modules.voice.diagnostics import diagnostic, terminal_failed
|
||||
from app.modules.knowledge.calibration import load_cutoff
|
||||
from app.modules.knowledge.evidence import RETRIEVAL_POLICY
|
||||
from app.modules.documents.settings import IngestionSettings
|
||||
@@ -232,7 +233,9 @@ async def handle_stream_websocket(websocket, session_id, auth_service, lifecycle
|
||||
await blocking(lifecycle_service.validate_stream, user, session_id)
|
||||
except Exception as exc:
|
||||
async with runtime.lock:
|
||||
runtime.fail(authority_failure_code(exc))
|
||||
code = authority_failure_code(exc)
|
||||
diagnostic(str(session_id), "authority_monitor", "AUTHORITY_CHECK_FAILED", exc=exc, code=code)
|
||||
runtime.fail(code)
|
||||
return
|
||||
children = [asyncio.create_task(browser()), asyncio.create_task(runtime.receive_loop()),
|
||||
asyncio.create_task(monitor()), asyncio.create_task(runtime.failure_signal.wait())]
|
||||
@@ -249,7 +252,9 @@ async def handle_stream_websocket(websocket, session_id, auth_service, lifecycle
|
||||
except TimeoutError:
|
||||
pass
|
||||
outcome = runtime.failure
|
||||
failed = outcome.startswith('LIVE_') or outcome in ('SEARCH_TIMEOUT','SEARCH_SATURATED','DEPENDENCY_UNAVAILABLE','SEARCH_CANCELLED')
|
||||
failed = terminal_failed(outcome)
|
||||
elif not runtime.usable and runtime.close_code == 1000:
|
||||
outcome, failed = "user_requested", False
|
||||
except WebSocketDisconnect:
|
||||
outcome = 'LIVE_TRANSPORT_FAILED'
|
||||
failed = True
|
||||
@@ -265,13 +270,6 @@ async def handle_stream_websocket(websocket, session_id, auth_service, lifecycle
|
||||
for task in children:
|
||||
task.cancel()
|
||||
await asyncio.gather(*children, return_exceptions=True)
|
||||
try:
|
||||
if runtime:
|
||||
await asyncio.wait_for(runtime.close(), 6)
|
||||
elif adapter:
|
||||
await asyncio.wait_for(adapter.close(), 6)
|
||||
except Exception:
|
||||
logger.warning('Bounded provider cleanup incomplete')
|
||||
try:
|
||||
# Saturation must not strand the durable terminal outcome once admission frees.
|
||||
deadline = asyncio.get_running_loop().time() + 6
|
||||
@@ -283,8 +281,18 @@ async def handle_stream_websocket(websocket, session_id, auth_service, lifecycle
|
||||
if str(exc) != 'SERVICE_BUSY' or asyncio.get_running_loop().time() >= deadline:
|
||||
raise
|
||||
await asyncio.sleep(.025)
|
||||
except Exception:
|
||||
logger.warning('Live terminal persistence unavailable')
|
||||
except Exception as exc:
|
||||
diagnostic(str(session_id), "terminal_persistence", "TERMINAL_PERSISTENCE_FAILED",
|
||||
exc=exc, code=outcome)
|
||||
try:
|
||||
if runtime:
|
||||
await asyncio.wait_for(runtime.close(), 6)
|
||||
elif adapter:
|
||||
await asyncio.wait_for(adapter.close(), 6)
|
||||
except Exception as exc:
|
||||
diagnostic(str(session_id), "stream_cleanup",
|
||||
"CLEANUP_TIMEOUT" if isinstance(exc, TimeoutError) else "CLEANUP_FAILED",
|
||||
exc=exc, code=outcome)
|
||||
await asyncio.wait_for(close_client(runtime.close_code or 1000 if runtime else 1011), 5)
|
||||
finally:
|
||||
registry.unregister(session_id)
|
||||
|
||||
@@ -23,6 +23,18 @@ class GeminiContextError(ProviderProtocolError):
|
||||
class GeminiOverflow(ProviderProtocolError):
|
||||
overflow = True
|
||||
|
||||
def __init__(self, message, *, occupancy=0, limit=0):
|
||||
super().__init__(message)
|
||||
self.reason = {
|
||||
'Gemini generated backlog overflow': 'GEMINI_OUTPUT_BACKLOG_CAPACITY',
|
||||
'Gemini audio slab overflow': 'GEMINI_OUTPUT_SLAB_CAPACITY',
|
||||
'Gemini control overflow': 'GEMINI_CONTROL_CAPACITY',
|
||||
'Gemini control message overflow': 'GEMINI_CONTROL_MESSAGE_CAPACITY',
|
||||
'Gemini audio metadata overflow': 'GEMINI_OUTPUT_METADATA_CAPACITY',
|
||||
'Gemini input mapping bound': 'GEMINI_INPUT_MAPPING_CAPACITY',
|
||||
}.get(message, 'PROVIDER_ADAPTER_CAPACITY')
|
||||
self.occupancy, self.limit = occupancy, limit
|
||||
|
||||
class PCM24To16:
|
||||
"""Streaming rational 2/3 FIR resampler with bounded history and antialias filtering."""
|
||||
def __init__(self):
|
||||
@@ -113,12 +125,12 @@ class GeminiLiveAdapter:
|
||||
if estimate < 0 or estimate > 196608 or estimate % 2:
|
||||
raise ProviderProtocolError('Gemini PCM alignment')
|
||||
if self._audio_bytes + self._leased_audio + self.backlog() + estimate > self.settings.max_output_backlog_bytes:
|
||||
raise GeminiOverflow('Gemini generated backlog overflow')
|
||||
raise GeminiOverflow('Gemini generated backlog overflow', occupancy=self._audio_bytes + self._leased_audio + self.backlog() + estimate, limit=self.settings.max_output_backlog_bytes)
|
||||
pcm = base64.b64decode(encoded, validate=True)
|
||||
if len(pcm) != estimate or len(pcm) % 2:
|
||||
raise ProviderProtocolError('Gemini PCM alignment')
|
||||
if self._audio_bytes + self._leased_audio + self.backlog() + len(pcm) > self.settings.max_output_backlog_bytes:
|
||||
raise GeminiOverflow('Gemini generated backlog overflow')
|
||||
raise GeminiOverflow('Gemini generated backlog overflow', occupancy=self._audio_bytes + self._leased_audio + self.backlog() + estimate, limit=self.settings.max_output_backlog_bytes)
|
||||
key = {k:v for k,v in event.items() if k != 'delta'}
|
||||
queue = self._inbound_events._queue
|
||||
tail = queue[-1] if queue else None
|
||||
@@ -127,8 +139,10 @@ class GeminiLiveAdapter:
|
||||
capacity = 9600 - len(tail[1])
|
||||
slabs = (max(0, len(pcm)-capacity) + 9599)//9600
|
||||
metadata = len(self.serialize(key).encode('utf-8'))
|
||||
if self._audio_slabs + slabs > 512 or self._audio_metadata + slabs * metadata > 65536:
|
||||
raise GeminiOverflow('Gemini audio slab overflow')
|
||||
if self._audio_slabs + slabs > 512:
|
||||
raise GeminiOverflow('Gemini audio slab overflow', occupancy=self._audio_slabs + slabs, limit=512)
|
||||
if self._audio_metadata + slabs * metadata > 65536:
|
||||
raise GeminiOverflow('Gemini audio metadata overflow', occupancy=self._audio_metadata + slabs * metadata, limit=65536)
|
||||
self._audio_bytes += len(pcm)
|
||||
self._audio_metadata += slabs * metadata
|
||||
if capacity:
|
||||
@@ -138,8 +152,10 @@ class GeminiLiveAdapter:
|
||||
self._audio_slabs += 1
|
||||
return
|
||||
size = len(self.serialize(event).encode('utf-8'))
|
||||
if self._control_count >= self.settings.max_control_messages or self._queued_bytes + size > self.settings.max_control_bytes:
|
||||
raise GeminiOverflow('Gemini control overflow')
|
||||
if self._control_count >= self.settings.max_control_messages:
|
||||
raise GeminiOverflow('Gemini control message overflow', occupancy=self._control_count, limit=self.settings.max_control_messages)
|
||||
if self._queued_bytes + size > self.settings.max_control_bytes:
|
||||
raise GeminiOverflow('Gemini control overflow', occupancy=self._queued_bytes + size, limit=self.settings.max_control_bytes)
|
||||
self._queued_bytes += size
|
||||
self._control_count += 1
|
||||
self._inbound_events.put_nowait((event,size,False))
|
||||
@@ -298,7 +314,7 @@ class GeminiLiveAdapter:
|
||||
self._input, self._input_end = 'gemini-input-'+uuid4().hex, None
|
||||
self._input_consumed = self._generation_complete = False
|
||||
if len(self._inputs) >= self.settings.max_input_turns:
|
||||
raise GeminiOverflow('Gemini input mapping bound')
|
||||
raise GeminiOverflow('Gemini input mapping bound', occupancy=len(self._inputs), limit=self.settings.max_input_turns)
|
||||
self._inputs.append({'id':self._input, 'start':milliseconds, 'end':None})
|
||||
self._input_text = ''
|
||||
self._put(dict(type='input_audio_buffer.speech_started',item_id=self._input,audio_start_ms=milliseconds))
|
||||
@@ -444,7 +460,8 @@ async def connect_gemini(api_key, model='gemini-2.0-flash-exp', proxy=None, sett
|
||||
raise ValueError('LIVE_PROVIDER_UNAVAILABLE')
|
||||
settings = settings or RuntimeSettings()
|
||||
from websockets.asyncio.client import connect
|
||||
endpoint = 'wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent'
|
||||
version = 'v1alpha' if ('3.8' in model or 'live' in model or 'v1alpha' in model) else 'v1beta'
|
||||
endpoint = f'wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.{version}.GenerativeService.BidiGenerateContent'
|
||||
return await connect(endpoint+'?key='+quote(api_key,safe=''), proxy=proxy,compression=None,
|
||||
max_size=settings.max_provider_message_bytes,max_queue=16,open_timeout=settings.connect_timeout_seconds,
|
||||
close_timeout=settings.send_timeout_seconds,ping_interval=20,ping_timeout=20)
|
||||
|
||||
@@ -40,8 +40,8 @@ class RealtimeAdapter:
|
||||
if not isinstance(self.settings, RuntimeSettings):
|
||||
raise ValueError("Validated runtime settings required")
|
||||
self.transport, self.model, self.voice = transport, model, voice
|
||||
# Fail closed by default: no stable documented structured race code.
|
||||
# Only install a classifier after separate selected-profile acceptance.
|
||||
# The default classifier is restricted to the empirically verified
|
||||
# OpenAI profile below. Other profiles require separate acceptance.
|
||||
self.no_active_classifier = no_active_classifier
|
||||
|
||||
def setup(self):
|
||||
@@ -93,9 +93,31 @@ class RealtimeAdapter:
|
||||
except (ValueError, TypeError, UnicodeError, RecursionError) as exc:
|
||||
raise ProviderProtocolError("Malformed provider event") from exc
|
||||
|
||||
def normalize_output_item(self, item):
|
||||
# GA assistant items use output_audio; internal/Gemini events use audio.
|
||||
# Keep replay hashing on the original wire value and normalize only this
|
||||
# documented item field. Runtime still validates role/layout/identities.
|
||||
if isinstance(item, dict) and item.get("type") == "message":
|
||||
content = item.get("content")
|
||||
if isinstance(content, list):
|
||||
return dict(item, content=[
|
||||
dict(part, type="audio")
|
||||
if isinstance(part, dict) and part.get("type") == "output_audio"
|
||||
else part for part in content])
|
||||
return item
|
||||
|
||||
def is_no_active(self, error):
|
||||
try:
|
||||
return self.no_active_classifier is not None and self.no_active_classifier(error) is True
|
||||
if self.no_active_classifier is not None:
|
||||
return self.no_active_classifier(error) is True
|
||||
# Selected-profile probe: docs/guides/live-context-sync-repair.md.
|
||||
# The runtime separately requires the cancellation intent event_id,
|
||||
# terminal response confirmation, and heard-position truncation.
|
||||
return (self.model == "gpt-realtime-mini" and self.voice == "shimmer"
|
||||
and isinstance(error, dict)
|
||||
and error.get("type") == "invalid_request_error"
|
||||
and error.get("code") == "response_cancel_not_active"
|
||||
and error.get("param") is None)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
"""Bounded allowlisted voice diagnostics; never log exception text or payloads."""
|
||||
import logging
|
||||
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({
|
||||
"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", "input_bytes",
|
||||
})
|
||||
|
||||
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")
|
||||
@@ -5,6 +5,7 @@ import json
|
||||
from uuid import UUID, uuid4
|
||||
from sqlalchemy import text
|
||||
from app.modules.knowledge.service import SearchInput, authority, transaction, KnowledgeError
|
||||
from app.modules.voice.diagnostics import terminal_failed
|
||||
|
||||
ACTIVE = ('creating', 'connecting', 'connected')
|
||||
TECHNICAL_ERRORS = frozenset(('SEARCH_TIMEOUT','SEARCH_FAILED','SEARCH_SATURATED',
|
||||
@@ -216,10 +217,15 @@ class LiveLifecycleService:
|
||||
dict(id=session_id, org=user.organization_id, owner=user.id)).mappings().first()
|
||||
if row is None:
|
||||
raise ValueError('SESSION_NOT_FOUND')
|
||||
if reason == "user_requested" and row["status"] in ACTIVE:
|
||||
from app.modules.voice.registry import failure_outcome
|
||||
causal_failure = failure_outcome(session_id)
|
||||
if causal_failure:
|
||||
reason, failed = causal_failure, terminal_failed(causal_failure)
|
||||
self._terminal(conn, session_id, reason, failed=failed)
|
||||
row = conn.execute(text('SELECT * FROM live_sessions WHERE id=:id'), {'id': session_id}).mappings().one()
|
||||
from app.modules.voice.registry import notify
|
||||
notify(session_id=session_id)
|
||||
notify(session_id=session_id, code="user_requested" if row["close_reason"] == "user_requested" else row["close_reason"])
|
||||
return dict(session_id=str(session_id), status=row['status'], close_reason=row['close_reason'])
|
||||
|
||||
def close_live_session(self, user, session_id, reason='user_requested'):
|
||||
|
||||
@@ -25,6 +25,13 @@ def unregister(session_id):
|
||||
if entry:
|
||||
entry.finished.set()
|
||||
|
||||
def failure_outcome(session_id):
|
||||
# Called from the durable close transaction. Failure is an immutable first
|
||||
# outcome published on the owner loop before any error reaches the browser.
|
||||
with _LOCK:
|
||||
entry = ENTRIES.get(session_id)
|
||||
return entry.runtime.failure if entry else None
|
||||
|
||||
def notify(*, organization_id=None, new_epoch=None, auth_session_id=None, session_id=None, code='CONTEXT_REVOKED'):
|
||||
with _LOCK:
|
||||
selected = [e for sid, e in ENTRIES.items()
|
||||
@@ -34,6 +41,9 @@ def notify(*, organization_id=None, new_epoch=None, auth_session_id=None, sessio
|
||||
and (session_id is None or sid == session_id)]
|
||||
async def fail(entry):
|
||||
async with entry.runtime.lock:
|
||||
if code == "user_requested":
|
||||
entry.runtime.stop_requested()
|
||||
else:
|
||||
entry.runtime.fail(code)
|
||||
for entry in selected:
|
||||
if not entry.loop.is_closed():
|
||||
|
||||
+218
-47
@@ -15,6 +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
|
||||
from app.modules.voice.serialization import bounded_json, json_size, bounded_json_digest
|
||||
|
||||
def identity():
|
||||
@@ -79,6 +80,7 @@ class Turn:
|
||||
intent: str | None = None
|
||||
cancelled: Event = field(default_factory=Event)
|
||||
diagnostic: str | None = None
|
||||
speech_deadline: float | None = None
|
||||
start_position: int | None = None
|
||||
input_deadline: float | None = None
|
||||
commit_ack: bool = False
|
||||
@@ -196,6 +198,7 @@ class VoiceRuntime:
|
||||
self.close_code = None
|
||||
self._provider_closed = False
|
||||
self._provider_close_task = None
|
||||
self._close_task = None
|
||||
self.failure_error_pending = False
|
||||
self.controls = deque()
|
||||
self.tasks = set()
|
||||
@@ -237,15 +240,18 @@ class VoiceRuntime:
|
||||
valid = await asyncio.wait_for(self.authority_check(
|
||||
turn.execution if turn else self.session_execution), self.settings.authority_timeout_seconds)
|
||||
except Exception as exc:
|
||||
self.fail(authority_failure_code(exc))
|
||||
valid = False
|
||||
code = authority_failure_code(exc)
|
||||
diagnostic(self.session_id, "authority", "AUTHORITY_CHECK_FAILED", exc=exc, code=code)
|
||||
self.fail(code, turn=turn)
|
||||
return False
|
||||
if not valid:
|
||||
diagnostic(self.session_id, "authority", "AUTHORITY_INVALIDATED", code="CONTEXT_REVOKED")
|
||||
self.fail("CONTEXT_REVOKED", turn=turn)
|
||||
return valid
|
||||
|
||||
async def authorized(self, turn=None):
|
||||
# Used only from startup; provider reception has not begun.
|
||||
valid = await self.check_authority(turn)
|
||||
if not valid:
|
||||
self.fail("CONTEXT_REVOKED")
|
||||
return valid
|
||||
|
||||
def command(self, event, *, pcm=None, input_end=None):
|
||||
@@ -271,10 +277,10 @@ class VoiceRuntime:
|
||||
return None
|
||||
if pcm is None and (self.command_count >= self.settings.max_control_messages or
|
||||
self.command_bytes + size > self.settings.max_control_bytes):
|
||||
self.fail("LIVE_BUFFER_OVERFLOW", turn=owner)
|
||||
self.overflow("PROVIDER_CONTROL_CAPACITY", turn=owner)
|
||||
return None
|
||||
if self.commands.full():
|
||||
self.fail("LIVE_BUFFER_OVERFLOW", turn=owner)
|
||||
self.overflow("PROVIDER_COMMAND_CAPACITY", turn=owner)
|
||||
return None
|
||||
cmd = Command(event, size, owner,
|
||||
self.clock() + self.settings.dispatch_wait_timeout_seconds, pcm, input_end,
|
||||
@@ -316,7 +322,7 @@ class VoiceRuntime:
|
||||
if (self.control_count + 1 > self.settings.max_control_messages - reserve_count or
|
||||
self.control_bytes + size > self.settings.max_control_bytes - reserve_bytes):
|
||||
if not terminal:
|
||||
self.fail("LIVE_BUFFER_OVERFLOW", turn=response.turn if response else None)
|
||||
self.overflow("CLIENT_CONTROL_CAPACITY", turn=response.turn if response else None)
|
||||
return None
|
||||
# Freeze a bounded event so later producer mutation cannot widen its reservation.
|
||||
entry = Control(strict_json(wire), size, response, completed_transcript)
|
||||
@@ -326,6 +332,17 @@ class VoiceRuntime:
|
||||
self.wake.set()
|
||||
return entry
|
||||
|
||||
def stop_requested(self):
|
||||
# HTTP close has already committed its terminal state. It is a normal
|
||||
# stop, not evidence that authority was revoked.
|
||||
if self.usable:
|
||||
self.usable = False
|
||||
self.close_code = 1000
|
||||
for turn in self.inputs.values():
|
||||
turn.cancelled.set()
|
||||
self.failure_signal.set()
|
||||
self.wake.set()
|
||||
|
||||
def fail(self, code, *, turn=None, writable=True):
|
||||
if not self.usable:
|
||||
return
|
||||
@@ -369,14 +386,26 @@ class VoiceRuntime:
|
||||
def _ensure_provider_close(self):
|
||||
# Event-loop-local creation is atomic; the close task outlives its waiters.
|
||||
if self._provider_close_task is None:
|
||||
self._provider_close_task = asyncio.create_task(asyncio.wait_for(
|
||||
self.adapter.close(), self.settings.send_timeout_seconds))
|
||||
self._provider_close_task = asyncio.create_task(self._bounded_provider_close())
|
||||
self._provider_close_task.add_done_callback(self._provider_close_finished)
|
||||
return self._provider_close_task
|
||||
|
||||
async def _bounded_provider_close(self):
|
||||
try:
|
||||
await asyncio.wait_for(self.adapter.close(), self.settings.send_timeout_seconds)
|
||||
except Exception as exc:
|
||||
# Return failures through shielded ownership. Python 3.14 otherwise
|
||||
# logs raw exception text when a shield waiter was cancelled.
|
||||
return exc
|
||||
|
||||
def _provider_close_finished(self, task):
|
||||
if not task.cancelled():
|
||||
self._provider_closed = task.exception() is None
|
||||
exc = task.result()
|
||||
self._provider_closed = exc is None
|
||||
if exc is not None:
|
||||
diagnostic(self.session_id, "provider_close",
|
||||
"CLEANUP_TIMEOUT" if isinstance(exc, TimeoutError) else "CLEANUP_FAILED",
|
||||
exc=exc, code=self.failure)
|
||||
|
||||
def _failure_finished(self, task):
|
||||
self.tasks.discard(task)
|
||||
@@ -384,7 +413,9 @@ class VoiceRuntime:
|
||||
self._ensure_provider_close()
|
||||
|
||||
async def _close_provider(self):
|
||||
await asyncio.shield(self._ensure_provider_close())
|
||||
result = await asyncio.shield(self._ensure_provider_close())
|
||||
if isinstance(result, Exception):
|
||||
raise result
|
||||
|
||||
async def _finish_failure(self, writable):
|
||||
try:
|
||||
@@ -415,6 +446,74 @@ class VoiceRuntime:
|
||||
response = next((r for r in self.responses.values() if r.interrupted and not r.terminal), None)
|
||||
return response.turn if response else None
|
||||
|
||||
def sync_failed(self, reason, *, turn=None, phase="context_sync",
|
||||
event_type=None, exc=None, audio=None, deadline=None):
|
||||
if not self.usable:
|
||||
return
|
||||
state = dict(pending_commands=len(self.pending_commands),
|
||||
pending_responses=sum(not r.terminal for r in self.responses.values()),
|
||||
pending_audio=sum(a.state == "finalizing" for a in self.audio.values()),
|
||||
input_bytes=self.input_forwarded_total - self.input_committed_total)
|
||||
if audio is not None:
|
||||
state.update(sent_bytes=audio.sent, played_ms=audio.played)
|
||||
if deadline is not None:
|
||||
state["deadline_remaining_ms"] = int((deadline - self.clock()) * 1000)
|
||||
diagnostic(self.session_id, phase, reason, event_type=event_type,
|
||||
exc=exc, code="LIVE_CONTEXT_SYNC_FAILED", **state)
|
||||
self.fail("LIVE_CONTEXT_SYNC_FAILED", turn=turn)
|
||||
|
||||
def overflow(self, reason, *, turn=None, occupancy=0, limit=0, audio=None):
|
||||
counts = {
|
||||
"PROVIDER_CONTROL_CAPACITY": (self.command_count, self.settings.max_control_messages),
|
||||
"PROVIDER_COMMAND_CAPACITY": (self.commands.qsize(), self.commands.maxsize),
|
||||
"CLIENT_CONTROL_CAPACITY": (self.control_count, self.settings.max_control_messages),
|
||||
"INPUT_TURN_CAPACITY": (len(self.inputs), self.settings.max_input_turns),
|
||||
"RESPONSE_INTENT_CAPACITY": (self.intent_count, self.settings.max_intents),
|
||||
"OUTPUT_IDENTITY_CAPACITY": (len(self.output_items), self.settings.max_refs),
|
||||
"OUTPUT_REFERENCE_CAPACITY": (len(self.audio), self.settings.max_refs),
|
||||
"PROVIDER_EVENT_CAPACITY": (len(self.events), self.settings.max_events),
|
||||
"OUTPUT_SLAB_CAPACITY": (sum((len(a.data) + 9599) // 9600 for a in self.audio.values()), 512),
|
||||
"TOOL_CALL_CAPACITY": (len(self.calls), self.max_calls),
|
||||
}
|
||||
occupancy_count, limit_count = counts.get(reason, (0, 0))
|
||||
if reason in ("GEMINI_OUTPUT_SLAB_CAPACITY", "GEMINI_INPUT_MAPPING_CAPACITY",
|
||||
"GEMINI_CONTROL_MESSAGE_CAPACITY"):
|
||||
occupancy_count, limit_count = occupancy, limit
|
||||
occupancy = limit = 0
|
||||
if reason == "PROVIDER_CONTROL_CAPACITY":
|
||||
occupancy, limit = self.command_bytes, self.settings.max_control_bytes
|
||||
elif reason == "CLIENT_CONTROL_CAPACITY":
|
||||
occupancy, limit = self.control_bytes, self.settings.max_control_bytes
|
||||
phase = ("playback" if audio else "capture_transport" if reason == "CAPTURE_TRANSPORT_CAPACITY"
|
||||
else "speaking" if any(t.start_position is not None and not t.stopped
|
||||
for t in self.inputs.values())
|
||||
else "awaiting_commit" if self.uncommitted_speech_bytes else "idle")
|
||||
state = dict(occupancy_count=occupancy_count, limit_count=limit_count,
|
||||
transport_limit_bytes=self.settings.max_queued_audio_bytes,
|
||||
transport_limit_messages=self.settings.max_queued_audio_messages,
|
||||
occupancy_bytes=occupancy, limit_bytes=limit,
|
||||
transport_bytes=self.input_transport_bytes,
|
||||
transport_messages=self.input_transport_count,
|
||||
speech_bytes=self.uncommitted_speech_bytes)
|
||||
if reason == "SPEECH_STOP_DEADLINE" and turn is not None:
|
||||
state["elapsed_ms"] = int((self.clock() - turn.speech_deadline +
|
||||
self.settings.max_input_buffer_bytes / 48000) * 1000)
|
||||
if audio is not None:
|
||||
state.update(sent_bytes=audio.sent, played_ms=audio.played,
|
||||
elapsed_ms=int((self.clock() - audio.stall_deadline +
|
||||
self.settings.playback_stall_timeout_seconds) * 1000))
|
||||
diagnostic(self.session_id, phase, reason,
|
||||
code='LIVE_BUFFER_OVERFLOW', **state)
|
||||
self.fail('LIVE_BUFFER_OVERFLOW', turn=turn)
|
||||
|
||||
@property
|
||||
def uncommitted_speech_bytes(self):
|
||||
# A speech interval is lifecycle metadata, not retained provider PCM.
|
||||
return sum(max(0, (t.stop_boundary if t.stopped else self.input_admitted_total)
|
||||
- t.start_position * 48)
|
||||
for t in self.inputs.values()
|
||||
if t.start_position is not None and not t.committed)
|
||||
|
||||
def check_deadlines(self):
|
||||
if not self.usable:
|
||||
return False
|
||||
@@ -423,33 +522,53 @@ class VoiceRuntime:
|
||||
self.fail("LIVE_PROVIDER_UNAVAILABLE")
|
||||
return False
|
||||
if self.intent_deadline is not None and now >= self.intent_deadline:
|
||||
self.fail("LIVE_CONTEXT_SYNC_FAILED",
|
||||
turn=self.pending_create[1] if self.pending_create else None)
|
||||
self.sync_failed("RESPONSE_ACK_DEADLINE",
|
||||
turn=self.pending_create[1] if self.pending_create else None,
|
||||
deadline=self.intent_deadline)
|
||||
return False
|
||||
if self.uncommitted_speech_bytes > self.settings.max_input_buffer_bytes:
|
||||
self.overflow('UNCOMMITTED_SPEECH_BYTES',
|
||||
occupancy=self.uncommitted_speech_bytes, limit=self.settings.max_input_buffer_bytes)
|
||||
return False
|
||||
for turn in self.inputs.values():
|
||||
if not turn.stopped and turn.speech_deadline is not None and now >= turn.speech_deadline:
|
||||
self.overflow('SPEECH_STOP_DEADLINE', turn=turn,
|
||||
occupancy=self.uncommitted_speech_bytes, limit=self.settings.max_input_buffer_bytes)
|
||||
return False
|
||||
if turn.input_deadline is not None and not turn.committed and now >= turn.input_deadline:
|
||||
self.fail("LIVE_CONTEXT_SYNC_FAILED", turn=turn)
|
||||
self.sync_failed("INPUT_COMMIT_DEADLINE", turn=turn, deadline=turn.input_deadline)
|
||||
return False
|
||||
for response in self.responses.values():
|
||||
if response.cancel_deadline is not None and not response.terminal and now >= response.cancel_deadline:
|
||||
self.fail("LIVE_CONTEXT_SYNC_FAILED", turn=response.turn)
|
||||
self.sync_failed("CANCELLATION_ACK_DEADLINE", turn=response.turn, deadline=response.cancel_deadline)
|
||||
return False
|
||||
for audio in self.audio.values():
|
||||
if audio.cleanup_deadline is not None and now >= audio.cleanup_deadline:
|
||||
self.fail("LIVE_CONTEXT_SYNC_FAILED", turn=audio.response.turn)
|
||||
self.sync_failed("TRUNCATION_ACK_DEADLINE", turn=audio.response.turn, audio=audio, deadline=audio.cleanup_deadline)
|
||||
return False
|
||||
if self.eligible(audio) and audio.timer and now >= audio.stall_deadline:
|
||||
self.fail("LIVE_BUFFER_OVERFLOW", turn=audio.response.turn)
|
||||
self.overflow("PLAYBACK_PROGRESS_STALL", turn=audio.response.turn, audio=audio, occupancy=audio.sent - audio.played * 48, limit=self.settings.output_credit_window_bytes)
|
||||
return False
|
||||
for cmd in list(self.pending_commands.values()):
|
||||
deadline = cmd.send_deadline if cmd.dispatched else cmd.queue_deadline
|
||||
if deadline is not None and now >= deadline:
|
||||
diagnostic(self.session_id, "provider_send",
|
||||
"PROVIDER_COMMAND_SEND_DEADLINE" if cmd.dispatched else "PROVIDER_COMMAND_QUEUE_DEADLINE",
|
||||
event_type=cmd.event["type"], code="LIVE_TRANSPORT_FAILED",
|
||||
deadline_remaining_ms=int((deadline - now) * 1000),
|
||||
pending_commands=len(self.pending_commands))
|
||||
self.fail("LIVE_TRANSPORT_FAILED", turn=cmd.owner)
|
||||
return False
|
||||
if self.audio_send_deadline is not None and now >= self.audio_send_deadline:
|
||||
diagnostic(self.session_id, "client_send", "CLIENT_AUDIO_SEND_DEADLINE",
|
||||
code="LIVE_TRANSPORT_FAILED",
|
||||
deadline_remaining_ms=int((self.audio_send_deadline - now) * 1000))
|
||||
self.fail("LIVE_TRANSPORT_FAILED", turn=self.audio_send_owner, writable=False)
|
||||
return False
|
||||
if self.active_control and self.active_control.send_deadline is not None and now >= self.active_control.send_deadline:
|
||||
diagnostic(self.session_id, "client_send", "CLIENT_CONTROL_SEND_DEADLINE",
|
||||
event_type=self.active_control.event["type"], code="LIVE_TRANSPORT_FAILED",
|
||||
deadline_remaining_ms=int((self.active_control.send_deadline - now) * 1000))
|
||||
self.fail("LIVE_TRANSPORT_FAILED", writable=False)
|
||||
return False
|
||||
return True
|
||||
@@ -529,13 +648,23 @@ class VoiceRuntime:
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except (ProviderProtocolError, ValueError, TypeError, RecursionError) as exc:
|
||||
diagnostic(self.session_id, "provider_receive", protocol_reason(exc), exc=exc)
|
||||
async with self.lock:
|
||||
self.fail("LIVE_BUFFER_OVERFLOW" if getattr(exc, "overflow", False) else
|
||||
"LIVE_CONTEXT_SYNC_FAILED" if getattr(exc, "context_sync", False) else "LIVE_PROVIDER_PROTOCOL_ERROR")
|
||||
except Exception:
|
||||
if getattr(exc, "overflow", False):
|
||||
self.overflow(getattr(exc, "reason", "PROVIDER_ADAPTER_CAPACITY"),
|
||||
occupancy=getattr(exc, "occupancy", 0), limit=getattr(exc, "limit", 0))
|
||||
elif getattr(exc, "context_sync", False):
|
||||
self.sync_failed("ADAPTER_CONTEXT_UNSUPPORTED",
|
||||
phase="provider_receive", exc=exc)
|
||||
else:
|
||||
self.fail("LIVE_PROVIDER_PROTOCOL_ERROR")
|
||||
except Exception as exc:
|
||||
async with self.lock:
|
||||
self.fail("LIVE_CONTEXT_SYNC_FAILED" if self.context_pending()
|
||||
else "LIVE_PROVIDER_UNAVAILABLE", turn=self.cleanup_owner())
|
||||
if self.context_pending():
|
||||
self.sync_failed("PROVIDER_TRANSPORT_LOST_DURING_SYNC",
|
||||
phase="provider_receive", exc=exc, turn=self.cleanup_owner())
|
||||
else:
|
||||
self.fail("LIVE_PROVIDER_UNAVAILABLE")
|
||||
|
||||
async def _sender(self):
|
||||
cmd = None
|
||||
@@ -561,7 +690,7 @@ class VoiceRuntime:
|
||||
continue
|
||||
if kind in ("response.create", "conversation.item.create") and owner:
|
||||
valid = await self.check_authority(owner)
|
||||
failure = "CONTEXT_REVOKED"
|
||||
failure = self.failure or "CONTEXT_REVOKED"
|
||||
if valid and self.tool_store:
|
||||
try:
|
||||
if kind == "conversation.item.create" and event["item"]["type"] == "function_call_output":
|
||||
@@ -587,7 +716,7 @@ class VoiceRuntime:
|
||||
if kind == "response.create":
|
||||
origin = self.origin_intents.get(event["response"]["metadata"]["voice_intent"])
|
||||
if origin and not all(c["sent"] for c in self.responses[origin].calls.values()):
|
||||
self.fail("LIVE_CONTEXT_SYNC_FAILED", turn=owner)
|
||||
self.sync_failed("TOOL_CONTINUATION_OUTPUT_UNSENT", turn=owner, phase="provider_send", event_type=kind)
|
||||
continue
|
||||
async with self.lock:
|
||||
if not self.begin_dispatch(cmd):
|
||||
@@ -615,7 +744,15 @@ class VoiceRuntime:
|
||||
raise
|
||||
except Exception as exc:
|
||||
async with self.lock:
|
||||
self.fail("LIVE_CONTEXT_SYNC_FAILED" if getattr(exc, "context_sync", False) else "LIVE_TRANSPORT_FAILED", turn=cmd.owner if cmd else None)
|
||||
if getattr(exc, "context_sync", False):
|
||||
self.sync_failed("ADAPTER_CONTEXT_COMMAND_UNSUPPORTED",
|
||||
phase="provider_send", event_type=cmd.event["type"] if cmd else None,
|
||||
exc=exc, turn=cmd.owner if cmd else None)
|
||||
else:
|
||||
diagnostic(self.session_id, "provider_send", "PROVIDER_SEND_FAILED",
|
||||
event_type=cmd.event["type"] if cmd else None, exc=exc,
|
||||
code="LIVE_TRANSPORT_FAILED")
|
||||
self.fail("LIVE_TRANSPORT_FAILED", turn=cmd.owner if cmd else None)
|
||||
finally:
|
||||
if cmd:
|
||||
async with self.lock:
|
||||
@@ -636,7 +773,7 @@ class VoiceRuntime:
|
||||
audio = self.audio[ref]
|
||||
if (self.eligible(audio) and audio.timer == timer and
|
||||
self.clock() >= audio.stall_deadline):
|
||||
self.fail("LIVE_BUFFER_OVERFLOW", turn=audio.response.turn)
|
||||
self.overflow("PLAYBACK_PROGRESS_STALL", turn=audio.response.turn, audio=audio, occupancy=audio.sent - audio.played * 48, limit=self.settings.output_credit_window_bytes)
|
||||
|
||||
async def _ticker(self):
|
||||
while True:
|
||||
@@ -669,6 +806,7 @@ class VoiceRuntime:
|
||||
|
||||
@property
|
||||
def input_buffer_bytes(self):
|
||||
# Absolute uncommitted stream prefix; not memory occupancy or speech.
|
||||
return 0 if self.input_released else self.input_admitted_total - self.input_committed_total
|
||||
|
||||
@property
|
||||
@@ -688,9 +826,16 @@ class VoiceRuntime:
|
||||
elif not self.check_deadlines():
|
||||
return
|
||||
elif (self.input_transport_bytes + len(pcm) > self.settings.max_queued_audio_bytes or
|
||||
self.input_transport_count + 1 > self.settings.max_queued_audio_messages or
|
||||
self.input_buffer_bytes + len(pcm) > self.settings.max_input_buffer_bytes):
|
||||
self.fail("LIVE_BUFFER_OVERFLOW")
|
||||
self.input_transport_count + 1 > self.settings.max_queued_audio_messages):
|
||||
self.overflow("CAPTURE_TRANSPORT_CAPACITY",
|
||||
occupancy=self.input_transport_bytes + len(pcm),
|
||||
limit=self.settings.max_queued_audio_bytes)
|
||||
elif (self.uncommitted_speech_bytes + len(pcm) * sum(
|
||||
t.start_position is not None and not t.stopped and not t.committed
|
||||
for t in self.inputs.values()) > self.settings.max_input_buffer_bytes):
|
||||
self.overflow("UNCOMMITTED_SPEECH_BYTES",
|
||||
occupancy=self.uncommitted_speech_bytes + len(pcm),
|
||||
limit=self.settings.max_input_buffer_bytes)
|
||||
else:
|
||||
self.input_transport_bytes += len(pcm)
|
||||
self.input_transport_count += 1
|
||||
@@ -724,7 +869,7 @@ class VoiceRuntime:
|
||||
if item in self.inputs:
|
||||
return self.inputs[item]
|
||||
if len(self.inputs) >= self.settings.max_input_turns:
|
||||
self.fail("LIVE_BUFFER_OVERFLOW")
|
||||
self.overflow("INPUT_TURN_CAPACITY")
|
||||
return
|
||||
old = self.current
|
||||
if old and not self.normal(old):
|
||||
@@ -787,7 +932,6 @@ class VoiceRuntime:
|
||||
if not self.check_deadlines():
|
||||
return
|
||||
if not valid:
|
||||
self.fail("CONTEXT_REVOKED")
|
||||
return
|
||||
if turn is not self.current or turn.token != self.token:
|
||||
await self.release()
|
||||
@@ -830,7 +974,7 @@ class VoiceRuntime:
|
||||
|
||||
async def create_response(self, turn, *, origin=None):
|
||||
if self.intent_count >= self.settings.max_intents:
|
||||
self.fail("LIVE_BUFFER_OVERFLOW")
|
||||
self.overflow("RESPONSE_INTENT_CAPACITY")
|
||||
return
|
||||
self.intent_count += 1
|
||||
intent = identity()
|
||||
@@ -970,8 +1114,6 @@ class VoiceRuntime:
|
||||
if owner and (audio or event["type"] in ("sources", "transcript", "audio_started", "audio_ended")):
|
||||
valid = await self.check_authority(owner)
|
||||
async with self.lock:
|
||||
if not valid:
|
||||
self.fail("CONTEXT_REVOKED", turn=owner)
|
||||
if self.usable:
|
||||
self.check_deadlines()
|
||||
suppressed = (not self.usable or
|
||||
@@ -1062,7 +1204,7 @@ class VoiceRuntime:
|
||||
raise ValueError("Output item rebound")
|
||||
if previous is None:
|
||||
if len(self.output_items) >= self.settings.max_refs:
|
||||
self.fail("LIVE_BUFFER_OVERFLOW")
|
||||
self.overflow("OUTPUT_IDENTITY_CAPACITY")
|
||||
raise ValueError("Output identity capacity")
|
||||
self.output_items[item] = response
|
||||
|
||||
@@ -1092,7 +1234,7 @@ class VoiceRuntime:
|
||||
key = (response.id, item, index)
|
||||
if key not in self.parts:
|
||||
if len(self.audio) >= self.settings.max_refs or sum(a.state != "retired" for a in self.audio.values()) >= self.settings.max_unretired_refs:
|
||||
self.fail("LIVE_BUFFER_OVERFLOW")
|
||||
self.overflow("OUTPUT_REFERENCE_CAPACITY")
|
||||
raise ValueError("Reference capacity")
|
||||
audio = Audio("live-audio-" + identity(), response, item, index)
|
||||
if response.interrupted:
|
||||
@@ -1151,7 +1293,7 @@ class VoiceRuntime:
|
||||
raise ValueError("Conflicting event replay")
|
||||
return
|
||||
if len(self.events) >= self.settings.max_events:
|
||||
self.fail("LIVE_BUFFER_OVERFLOW")
|
||||
self.overflow("PROVIDER_EVENT_CAPACITY")
|
||||
return
|
||||
self.events[event_id] = digest
|
||||
kind = event["type"]
|
||||
@@ -1174,13 +1316,16 @@ class VoiceRuntime:
|
||||
elif kind == "input_audio_buffer.speech_started":
|
||||
item, start = event["item_id"], event["audio_start_ms"]
|
||||
if item not in self.inputs:
|
||||
if type(start) is not int or start <= self.last_start:
|
||||
if type(start) is not int or start < 0 or start <= self.last_start or start * 48 > self.input_dispatched_total:
|
||||
raise ValueError("Input ordering")
|
||||
self.last_start = start
|
||||
await self.new_turn(item)
|
||||
if not self.usable:
|
||||
return
|
||||
self.current.start_position = start
|
||||
self.current.speech_deadline = self.clock() + self.settings.max_input_buffer_bytes / 48000
|
||||
if not self.check_deadlines():
|
||||
return
|
||||
elif self.inputs[item].start_position != start:
|
||||
raise ValueError("Conflicting input start")
|
||||
elif kind == "input_audio_buffer.speech_stopped":
|
||||
@@ -1192,6 +1337,7 @@ class VoiceRuntime:
|
||||
raise ValueError("Conflicting input stop")
|
||||
if not turn.stopped:
|
||||
turn.stopped = True
|
||||
turn.speech_deadline = None
|
||||
turn.stop_boundary = end * 48
|
||||
turn.input_deadline = self.clock() + self.settings.input_commit_timeout_seconds
|
||||
if turn.commit_ack:
|
||||
@@ -1233,6 +1379,8 @@ class VoiceRuntime:
|
||||
raise ValueError("Response creation identity conflict")
|
||||
elif kind in ("response.output_item.added", "response.output_item.done"):
|
||||
response, item = self.correlated_response(event), event["item"]
|
||||
if hasattr(self.adapter, "normalize_output_item"):
|
||||
item = self.adapter.normalize_output_item(item)
|
||||
item_type = item["type"]
|
||||
if item_type not in ("message", "function_call"):
|
||||
raise ValueError("Unsupported output item")
|
||||
@@ -1270,6 +1418,8 @@ class VoiceRuntime:
|
||||
raise ValueError("Repeated terminal call")
|
||||
terminal_calls.add(item["call_id"])
|
||||
for position, item in enumerate(wire["output"]):
|
||||
if hasattr(self.adapter, "normalize_output_item"):
|
||||
item = self.adapter.normalize_output_item(item)
|
||||
self.output_position(dict(item_id=item["id"], output_index=position), response)
|
||||
item_type = item["type"]
|
||||
old_type = self.item_types.get(item["id"])
|
||||
@@ -1315,7 +1465,7 @@ class VoiceRuntime:
|
||||
raise ValueError("PCM alignment")
|
||||
backlog = sum(len(a.data) + a.reserved + a.credit for a in self.audio.values())
|
||||
if audio.state != "finalizing" and backlog + estimate + getattr(self.adapter, "_audio_bytes", 0) > self.settings.max_output_backlog_bytes:
|
||||
self.fail("LIVE_BUFFER_OVERFLOW", turn=response.turn)
|
||||
self.overflow("OUTPUT_BACKLOG_CAPACITY", turn=response.turn, occupancy=backlog + estimate + getattr(self.adapter, "_audio_bytes", 0), limit=self.settings.max_output_backlog_bytes)
|
||||
return
|
||||
decoded = base64.b64decode(encoded, validate=True)
|
||||
if len(decoded) != estimate:
|
||||
@@ -1328,7 +1478,7 @@ class VoiceRuntime:
|
||||
raise ValueError("Late audio")
|
||||
audio.data.extend(decoded)
|
||||
if sum((len(a.data) + 9599) // 9600 for a in self.audio.values()) > 512:
|
||||
self.fail("LIVE_BUFFER_OVERFLOW", turn=response.turn)
|
||||
self.overflow("OUTPUT_SLAB_CAPACITY", turn=response.turn)
|
||||
else:
|
||||
audio.done = True
|
||||
self.wake.set()
|
||||
@@ -1390,7 +1540,10 @@ class VoiceRuntime:
|
||||
if (len(matches) != 1 or type(event["content_index"]) is not int
|
||||
or type(event["audio_end_ms"]) is not int
|
||||
or event["audio_end_ms"] != matches[0].played):
|
||||
self.fail("LIVE_CONTEXT_SYNC_FAILED")
|
||||
self.sync_failed("TRUNCATION_ACK_IDENTITY_MISMATCH" if len(matches) != 1
|
||||
or type(event["content_index"]) is not int
|
||||
else "TRUNCATION_ACK_POSITION_MISMATCH", phase="provider_handle",
|
||||
event_type=kind, audio=matches[0] if len(matches) == 1 else None)
|
||||
return
|
||||
audio = matches[0]
|
||||
audio.cleanup_deadline = None
|
||||
@@ -1406,15 +1559,21 @@ class VoiceRuntime:
|
||||
if a.cleanup_dispatched and a.cleanup == error.get("event_id")), None)
|
||||
if len(matches) == 1:
|
||||
if not self.adapter.is_no_active(error):
|
||||
self.fail("LIVE_CONTEXT_SYNC_FAILED", turn=matches[0].turn)
|
||||
self.sync_failed("CANCELLATION_PROVIDER_ERROR", turn=matches[0].turn, phase="provider_handle", event_type=kind)
|
||||
elif cleanup:
|
||||
self.fail("LIVE_CONTEXT_SYNC_FAILED", turn=cleanup.response.turn)
|
||||
self.sync_failed("TRUNCATION_PROVIDER_ERROR", turn=cleanup.response.turn, phase="provider_handle", event_type=kind, audio=cleanup)
|
||||
else:
|
||||
self.fail("LIVE_CONTEXT_SYNC_FAILED" if self.context_pending()
|
||||
else "LIVE_PROVIDER_UNAVAILABLE", turn=self.cleanup_owner())
|
||||
if self.context_pending():
|
||||
self.sync_failed("UNRELATED_PROVIDER_ERROR_DURING_SYNC",
|
||||
phase="provider_handle", event_type=kind, turn=self.cleanup_owner())
|
||||
else:
|
||||
self.fail("LIVE_PROVIDER_UNAVAILABLE")
|
||||
await self.maintain()
|
||||
await self.release()
|
||||
except (KeyError, TypeError, ValueError, UnicodeError, RecursionError):
|
||||
except (KeyError, TypeError, ValueError, UnicodeError, RecursionError) as exc:
|
||||
diagnostic(self.session_id, "provider_handle", protocol_reason(exc),
|
||||
event_type=event.get("type") if isinstance(event, dict) else None,
|
||||
exc=exc, code="LIVE_PROVIDER_PROTOCOL_ERROR")
|
||||
self.fail("LIVE_PROVIDER_PROTOCOL_ERROR", turn=affected)
|
||||
|
||||
async def dispatch(self, response, call_id, name, raw, item_id):
|
||||
@@ -1439,7 +1598,7 @@ class VoiceRuntime:
|
||||
if response.continued or response.terminal:
|
||||
raise ValueError("Late unknown tool")
|
||||
if len(self.calls) >= self.max_calls:
|
||||
self.fail("LIVE_BUFFER_OVERFLOW")
|
||||
self.overflow("TOOL_CALL_CAPACITY")
|
||||
return
|
||||
call = dict(hash=fingerprint, result=None, sent=False, output_queued=False,
|
||||
name=name, raw=raw, item=item_id, ref=str(uuid4()))
|
||||
@@ -1491,6 +1650,15 @@ class VoiceRuntime:
|
||||
await self.release()
|
||||
|
||||
async def close(self):
|
||||
# All concurrent waiters share worker cancellation and provider ownership.
|
||||
# Route cancellation must not cancel the shared shutdown.
|
||||
if self._close_task is None:
|
||||
self._close_task = asyncio.create_task(self._close())
|
||||
result = await asyncio.shield(self._close_task)
|
||||
if isinstance(result, Exception):
|
||||
raise result
|
||||
|
||||
async def _close(self):
|
||||
async with self.lock:
|
||||
self.usable = False
|
||||
for turn in self.inputs.values():
|
||||
@@ -1509,4 +1677,7 @@ class VoiceRuntime:
|
||||
for task in tasks:
|
||||
task.cancel()
|
||||
await asyncio.gather(*tasks, return_exceptions=True)
|
||||
try:
|
||||
await self._close_provider()
|
||||
except Exception as exc:
|
||||
return exc
|
||||
|
||||
@@ -22,6 +22,7 @@ class RuntimeSettings(BaseSettings):
|
||||
max_queued_audio_seconds: float = Field(default=2, gt=0, le=2, allow_inf_nan=False)
|
||||
max_queued_audio_bytes: int = Field(default=96000, gt=0, le=96000)
|
||||
max_queued_audio_messages: int = Field(default=100, gt=0, le=100)
|
||||
# Detected uncommitted speech bytes; excludes silence outside VAD intervals.
|
||||
max_input_buffer_bytes: int = Field(default=480000, gt=0, le=480000)
|
||||
max_output_backlog_bytes: int = Field(default=1440000, gt=0, le=1440000)
|
||||
output_credit_window_bytes: int = Field(default=72000, ge=48, le=72000)
|
||||
|
||||
@@ -2065,3 +2065,38 @@ passed in the initial full run deselected. All 404 current database scenarios ha
|
||||
passing executed evidence across these runs. Protected inputs/migrations and the
|
||||
restored 55-case source remained byte-identical. Exact timings, reproduction,
|
||||
intermediate failures, JUnit path and cleanup are in the scoped repair report.
|
||||
|
||||
|
||||
## Browser voice termination repair (2026-10-10)
|
||||
|
||||
The [incident repair and frontend handoff](guides/voice-session-termination-repair.md)
|
||||
records the confirmed OpenAI output-item normalization, terminal-close race and
|
||||
manual-stop notification fixes, safe diagnostic fields, shared bounded shutdown
|
||||
ownership, regression checks and deployment/browser acceptance steps. Source
|
||||
locations: `app/modules/voice/diagnostics.py`, existing runtime/lifecycle/registry,
|
||||
`app/infrastructure/realtime.py`, and `app/api/v1/live.py`. New regression sources:
|
||||
`tests/unit/test_voice_session_incident.py` and
|
||||
`tests/integration/test_voice_session_incident.py`. Historical incident attribution,
|
||||
actual Angular cleanup and funded provider/browser acceptance remain unverified.
|
||||
No applied migration or public error envelope changed. See the report for exact
|
||||
completed checks; earlier checkpoints do not establish this repair's acceptance.
|
||||
|
||||
|
||||
## OpenAI cancellation/context synchronization repair (2026-10-10)
|
||||
|
||||
The [scoped repair and acceptance report](guides/live-context-sync-repair.md)
|
||||
records one explicitly authorized OpenAI probe (two short responses), the captured
|
||||
gpt-realtime-mini/shimmer structured no-active cancellation error, its pre-fix
|
||||
synthetic failure and the profile-restricted adapter correction. Terminal and
|
||||
heard-position truncation barriers remain mandatory. Runtime diagnostics now
|
||||
distinguish every synchronization failure branch with bounded numeric state.
|
||||
Final checks: 1827 provider-free passed (three Windows symlink skips) and 11
|
||||
isolated PostgreSQL incident tests passed (zero skips). Applied migrations,
|
||||
public contracts, provider/model configuration and unrelated changes remain.
|
||||
Historical incident attribution, corrected live application/browser acceptance
|
||||
and deployment are unverified; the currently inspected API selected Gemini.
|
||||
|
||||
|
||||
## Continuous microphone input accounting repair (2026-10-10)
|
||||
|
||||
The [scoped repair report](guides/voice-input-accounting-repair.md) supersedes the historical 10-second silence overflow requirement. API 7.1.3 now bounds detected uncommitted speech independently of queued/in-flight transport; absolute positions and commitment fencing remain. Fixed speech-stop and existing commit/send deadlines protect missing events. Stable overflow diagnostics distinguish input, output, playback and control branches. Verification: 1834 provider-free passed (three existing Windows symlink skips); final adapter/diagnostic follow-up 80 passed. No database behavior or migration changed; no deployment or paid provider calls. Real-provider/browser acceptance remains unverified. See the report for exact commands, intermediate failures, counter definitions and provider evidence.
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"active_cancel_dispatched_response_1": true,
|
||||
"api_restarted": false,
|
||||
"application_sessions_modified": false,
|
||||
"authorization": "User explicitly approved one at-most-60-second OpenAI probe with two short generated responses.",
|
||||
"browser_acceptance": "not_run",
|
||||
"cleanup_exception": "TimeoutError",
|
||||
"cleanup_timeout_seconds": 3,
|
||||
"completed_audio_truncation_confirmed": true,
|
||||
"completed_cancel_error": {
|
||||
"cancellation_event_id_matched": true,
|
||||
"code": "response_cancel_not_active",
|
||||
"param": null,
|
||||
"type": "invalid_request_error"
|
||||
},
|
||||
"connections": 1,
|
||||
"date": "2026-10-10",
|
||||
"generated_responses": 2,
|
||||
"historical_incident_attribution": "unconfirmed",
|
||||
"model": "gpt-realtime-mini",
|
||||
"probe_process_exited": true,
|
||||
"provider": "openai",
|
||||
"response_0_terminal": "completed",
|
||||
"response_1_terminal": "completed",
|
||||
"synthetic_text_input": true,
|
||||
"truncation_audio_end_ms": 0,
|
||||
"voice": "shimmer"
|
||||
}
|
||||
@@ -176,19 +176,21 @@ failures persist `failed` with matching close reason/error code; committed termi
|
||||
logout/V04/expiry outcomes remain intact. Persistence retries bounded admission
|
||||
saturation, but a database outage can still prevent a durable write and is logged.
|
||||
|
||||
## Continuous idle input limitation
|
||||
## Continuous microphone input
|
||||
|
||||
The example continuously sends microphone PCM after readiness, including silence.
|
||||
The frozen input-since-commit budget is 480000 bytes (10 seconds at 24 kHz PCM16LE).
|
||||
Without verified native commitment, exactly 480000 bytes are accepted; the next
|
||||
sample fails LIVE_BUFFER_OVERFLOW and closes. Native input consumption/transport
|
||||
send is not commitment. This behavior is deterministic for an idle Gemini fake
|
||||
with no activity boundary and applies to uncommitted admission for either adapter.
|
||||
The example continuously sends 24 kHz mono PCM16LE after readiness, including
|
||||
silence. The 2026-10-10 [input-accounting repair](voice-input-accounting-repair.md)
|
||||
supersedes the earlier deterministic 10-second idle overflow.
|
||||
The 480000-byte limit now bounds trusted detected uncommitted speech intervals,
|
||||
including VAD padding. Local queued/in-flight input remains bounded to 96000 bytes
|
||||
and 100 messages, with existing send deadlines. Silence outside detected speech
|
||||
does not consume the speech allowance. A completed send releases local transport
|
||||
storage only; it is neither provider consumption nor commitment.
|
||||
|
||||
Longer continuous idle operation remains a product/provider-contract decision.
|
||||
This example does not gate silence, fabricate commitment or add browser activity
|
||||
controls. Use explicit stop/close and a fresh eligible session after overflow;
|
||||
do not assume uninterrupted idle capture or seamless Gemini barge-in is supported.
|
||||
Keep sending the original timeline; no RMS gate, new VAD, buffer clear or invented
|
||||
silence acknowledgment is required. Genuine long speech, missing stop/commit,
|
||||
transport saturation and expiry still fail safely. Browser/provider acceptance
|
||||
remains necessary; seamless Gemini context truncation remains unsupported.
|
||||
|
||||
Automated fake-provider/loopback/worklet results prove technical boundaries only.
|
||||
Real provider access, measured retrieval quality, Persian speech, microphone,
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
# OpenAI Live context synchronization repair - 2026-10-10
|
||||
|
||||
The local OpenAI cancellation-race defect is reproduced and corrected. This is
|
||||
not proof that the historical browser incident had this branch or that the
|
||||
deployed browser/API is repaired. No operational rebuild or restart was performed.
|
||||
|
||||
## Confirmed cause and evidence
|
||||
|
||||
[RealtimeAdapter.is_no_active](../../app/infrastructure/realtime.py) previously
|
||||
returned false unless a separately injected classifier was supplied.
|
||||
[create_adapter](../../app/infrastructure/voice_provider.py) supplies no classifier.
|
||||
A response can finish between the runtime's active-state check and provider
|
||||
processing of its response-specific cancellation. The correlated no-active error
|
||||
therefore reached the cancellation-provider-error branch in
|
||||
[VoiceRuntime.handle](../../app/modules/voice/runtime.py), which called
|
||||
LIVE_CONTEXT_SYNC_FAILED even when response.done had already confirmed completion.
|
||||
|
||||
Current [official client-event documentation](https://developers.openai.com/api/reference/resources/realtime/client-events)
|
||||
says cancelling without an active response returns an error and leaves the
|
||||
provider session unaffected. That establishes the semantics, not a stable
|
||||
structured error-code spelling. The governing API catalog Section 7.1.6 requires
|
||||
selected-profile verification before accepting a structured cancellation race.
|
||||
|
||||
After explicit user authorization, one isolated OpenAI connection produced
|
||||
two short responses using the existing gpt-realtime-mini/shimmer configuration.
|
||||
The first completed; its response-specific cancellation returned the exact
|
||||
structured fields type=invalid_request_error, code=response_cancel_not_active,
|
||||
param=null, correlated to that cancellation event_id. Truncation of that
|
||||
completed audio at zero milliseconds was then confirmed by matching item,
|
||||
content_index=0 and audio_end_ms=0. During the second response cancellation was
|
||||
dispatched after an audio delta; response.done reported completed, so this does
|
||||
not prove provider status=cancelled or all active-generation interruption behavior.
|
||||
The [sanitized probe evidence](../calibration/live-context-sync-probe.json)
|
||||
contains no raw audio, transcripts, full provider events, messages, identities,
|
||||
credentials or tool data. The probe's bounded three-second transport-close
|
||||
operation timed out and the isolated process exited; cleanup timeout remains an
|
||||
observed limitation, not a successful close-handshake claim.
|
||||
|
||||
The three captured-provider synthetic regressions failed before the classifier
|
||||
fix with CANCELLATION_PROVIDER_ERROR and LIVE_CONTEXT_SYNC_FAILED. Their controlled
|
||||
sequences covered terminal-before-error, terminal-after-error, and absent terminal
|
||||
confirmation. After correction, both confirmed-terminal orderings safely complete
|
||||
truncation and release the next response; the absent-terminal case still times out.
|
||||
|
||||
The available tail of operational diagnostics did not contain application session
|
||||
ce371f61-6bed-4863-a091-61fe116f1be1 or identify its branch. Historical browser
|
||||
events and the public error code cannot establish that this defect caused that
|
||||
specific incident. During inspection the running API selected Gemini; its
|
||||
dedicated OpenAI settings remained gpt-realtime-mini/shimmer with a configured
|
||||
key. An initial probe guard exited before any connection because the selected
|
||||
provider was Gemini. The authorized probe then used the dedicated OpenAI settings
|
||||
directly without changing the API's selected provider or model configuration.
|
||||
|
||||
## Correction and safety
|
||||
|
||||
The adapter now recognizes only the verified gpt-realtime-mini/shimmer profile
|
||||
and exact structured type/code with a null or absent param. No provider message
|
||||
substring is inspected. Other profiles and error types/codes/parameters remain
|
||||
unaccepted. Existing trusted classifier injection remains available for separately
|
||||
verified profiles and deterministic fixtures.
|
||||
|
||||
The runtime independently requires error.event_id to match one dispatched
|
||||
response-specific cancellation intent. This error neither retries cancellation
|
||||
nor substitutes for terminal confirmation, final playback position, or truncation
|
||||
acknowledgment. Generic/unrelated errors, truncation errors, missing terminal events,
|
||||
mismatched cleanup, changed late progress and transport uncertainty remain fatal.
|
||||
Failed/incomplete terminal responses retain LIVE_PROVIDER_UNAVAILABLE; protocol
|
||||
and send failures retain their existing technical categories. Public errors,
|
||||
PCM layout, authorization/epochs, retrieval, replay fencing, buffer bounds and
|
||||
production deadlines are unchanged. Applied migrations and unrelated working-tree
|
||||
edits were preserved.
|
||||
|
||||
Causal synthetic sequence:
|
||||
|
||||
1. Trusted speech starts; unfinished old output is superseded, delivery stops,
|
||||
refs enter finalizing and cancellation is queued once. turn_interrupted precedes
|
||||
user_speech_started for the next turn.
|
||||
2. Final browser progress is accepted while the original reporting window is open.
|
||||
Tests advance heard position from 100 to 420 ms without restarting the window.
|
||||
3. The old response's response.done and no-active cancellation error can arrive in
|
||||
either order. A verified error is benign only under its mapped cancellation;
|
||||
independent terminal confirmation remains required.
|
||||
4. At window expiry progress freezes. All generated but unconfirmed audio still
|
||||
requires conversation.item.truncate at the frozen position.
|
||||
5. Only a matching item/content/position acknowledgment retires the ref. Input
|
||||
stop/commit plus completed old work then permit the next response.
|
||||
6. Duplicate acknowledgments and late old cancellation errors do not alter the new
|
||||
response. Missing terminal confirmation and unsafe cleanup fail closed.
|
||||
|
||||
## Private diagnostic coverage
|
||||
|
||||
[Runtime.sync_failed](../../app/modules/voice/runtime.py) records the first
|
||||
accepted synchronization failure before retiring state.
|
||||
[Diagnostics](../../app/modules/voice/diagnostics.py) allowlist numeric fields and
|
||||
clamp each to a signed 32-bit range. Records contain application session ID,
|
||||
runtime phase, stable reason, allowlisted provider event type, exception class,
|
||||
public failure category, deadline remaining milliseconds where applicable,
|
||||
pending command/response/audio counts and outstanding input bytes; audio-related
|
||||
branches also record sent_bytes and accepted played_ms where a part is known.
|
||||
Unknown event types, arbitrary exception text, provider messages and payloads are
|
||||
never logged.
|
||||
|
||||
| Failure branch | Internal reason |
|
||||
| --- | --- |
|
||||
| Response creation acknowledgment deadline | RESPONSE_ACK_DEADLINE |
|
||||
| Input commit/consumption deadline | INPUT_COMMIT_DEADLINE |
|
||||
| Cancellation terminal acknowledgment deadline | CANCELLATION_ACK_DEADLINE |
|
||||
| Truncation acknowledgment deadline | TRUNCATION_ACK_DEADLINE |
|
||||
| Truncation item/content mismatch | TRUNCATION_ACK_IDENTITY_MISMATCH |
|
||||
| Truncation heard-position mismatch | TRUNCATION_ACK_POSITION_MISMATCH |
|
||||
| Unaccepted correlated cancellation error | CANCELLATION_PROVIDER_ERROR |
|
||||
| Correlated truncation error | TRUNCATION_PROVIDER_ERROR |
|
||||
| Unrelated provider error during cleanup | UNRELATED_PROVIDER_ERROR_DURING_SYNC |
|
||||
| Receive transport loss during cleanup | PROVIDER_TRANSPORT_LOST_DURING_SYNC |
|
||||
| Adapter receive/send context capability failure | ADAPTER_CONTEXT_UNSUPPORTED / ADAPTER_CONTEXT_COMMAND_UNSUPPORTED |
|
||||
| Tool continuation before its outputs are sent | TOOL_CONTINUATION_OUTPUT_UNSENT |
|
||||
| Provider queue/send deadline | PROVIDER_COMMAND_QUEUE_DEADLINE / PROVIDER_COMMAND_SEND_DEADLINE |
|
||||
| Client audio/control send deadline | CLIENT_AUDIO_SEND_DEADLINE / CLIENT_CONTROL_SEND_DEADLINE |
|
||||
| Provider send exception | PROVIDER_SEND_FAILED |
|
||||
|
||||
Transport deadlines retain LIVE_TRANSPORT_FAILED; detailed reasons do not change
|
||||
the public error envelope or overwrite the immutable first failure.
|
||||
|
||||
## Executed validation
|
||||
|
||||
New [controlled-clock regressions](../../tests/unit/test_live_context_sync.py)
|
||||
cover captured cancellation errors before/after terminal completion, missing
|
||||
terminal confirmation, exact classifier negatives/profile restrictions, active
|
||||
audio interruption, completed generation with undrained playback, final progress,
|
||||
truncation position, duplicate acknowledgments, late errors after a new response,
|
||||
all four synchronization deadlines, privacy/bounds, transport/protocol categories,
|
||||
failed/incomplete response classification and concurrent runtime close.
|
||||
|
||||
The existing focused suite additionally covers rapid/repeated speech starts,
|
||||
normal/late progress, identity/replay fencing, cancellation send races, unsafe
|
||||
synchronization, authority and bounded resource ownership.
|
||||
[Database incident tests](../../tests/integration/test_voice_session_incident.py)
|
||||
now include LIVE_CONTEXT_SYNC_FAILED in the concurrent-close persistence cases.
|
||||
|
||||
| Command | Actual outcome |
|
||||
| --- | --- |
|
||||
| git diff --check | Passed, including final report changes. Existing Git CRLF conversion warnings remain. |
|
||||
| .venv/Scripts/python -m pytest tests/unit/test_live_context_sync.py -q -p no:cacheprovider --tb=short | Final 25 passed in 3.57 s. |
|
||||
| .venv/Scripts/python -m pytest tests/unit/test_live_context_sync.py tests/unit/test_voice_session_incident.py tests/unit/test_realtime_phase1.py tests/unit/test_realtime_repairs.py tests/unit/test_realtime_remaining.py -q -p no:cacheprovider --tb=short | 313 passed in 31.23 s before four final category regressions were added; final full run below includes them. |
|
||||
| .venv/Scripts/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short | Final 1827 passed, 3 Windows symlink skips, 415 PostgreSQL cases deselected, 25 existing deprecation warnings, 253.84 s. |
|
||||
| .venv/Scripts/python -m pytest tests/integration/test_voice_session_incident.py -m postgres --require-postgres -q -p no:cacheprovider --tb=short | 11 passed in 33.67 s, zero skips. |
|
||||
|
||||
Database acceptance used only task-created container
|
||||
rag-context-sync-20261010-test, loopback port 55439 and dedicated database
|
||||
rag_context_sync_test with Psycopg. TEST_DATABASE_URL was set only in that
|
||||
PowerShell process. Fixtures apply existing immutable migrations to disposable
|
||||
schemas; they do not use operational/public application tables. The verified
|
||||
task-owned container and anonymous test storage were removed after acceptance.
|
||||
No full 415-case PostgreSQL acceptance run was executed for this adapter/runtime
|
||||
change; durable implementation and migrations were not changed.
|
||||
|
||||
Intermediate evidence: captured-provider regressions failed 3/3 before correction.
|
||||
Initial diagnostic tests passed 11/11. An earlier full ordinary run had
|
||||
1812 passed, 3 skips and one unrelated
|
||||
test_real_large_escaped_json_keeps_concurrent_loop_active[10000] failure
|
||||
(max heartbeat gap 144.03 ms against 100 ms). A focused suite ran concurrently
|
||||
during that earlier run. The final full run was not paired with another test suite
|
||||
and passed this unchanged test. The timing failure is recorded, not removed,
|
||||
weakened, or asserted to have a definitively established cause.
|
||||
|
||||
## Frontend and deployment handoff
|
||||
|
||||
Only data/temp frontend copies were found; no accessible authoritative Angular
|
||||
workspace was found. Inspection confirms clearPlayback discards queued/deferred
|
||||
audio, and audio_ended requests a drain. The prior whole-second synthetic test
|
||||
does not establish browser interruption/progress ordering or audio_ref ownership.
|
||||
No frontend file was edited and no deployed frontend repair is claimed. Missing
|
||||
zero progress remains conservatively zero in the backend; real per-reference
|
||||
final reports and timing still need browser acceptance.
|
||||
|
||||
No frontend patch is required by the reproduced backend classifier defect.
|
||||
Browser acceptance must still verify normal turns, interruption during generation,
|
||||
interruption after generation before playback drains, two rapid utterances,
|
||||
manual stop, accurate truncation, stable terminal state and one cleanup request.
|
||||
The authorized provider probe is not microphone/Persian/browser acceptance and
|
||||
did not exercise the corrected application stream against OpenAI.
|
||||
|
||||
Changes are prepared locally. No docker compose build api or docker compose up
|
||||
was executed, no deployed source-match/readiness claim is made, and provider
|
||||
selection was not changed. Deploy only when separately authorized, then verify
|
||||
corrected adapter/runtime files and readiness inside the running API and use a
|
||||
fresh voice session. This incident is not claimed fully resolved without historical
|
||||
attribution or the remaining deployed browser validation.
|
||||
@@ -0,0 +1,146 @@
|
||||
# Voice input accounting repair — 2026-10-10
|
||||
|
||||
The confirmed defect is a cumulative accounting error: continuously forwarded
|
||||
microphone silence increased admitted-minus-committed input until the next sample
|
||||
exceeded 480000 bytes. That counter describes an absolute stream prefix, not
|
||||
retained local PCM. This explains the reproducible false overflow; it does not
|
||||
identify the cause of every historical LIVE_BUFFER_OVERFLOW / 1013 incident.
|
||||
|
||||
## Contract adjustment and provider evidence
|
||||
|
||||
API catalog 7.1.3 previously explicitly bounded all input since commitment,
|
||||
including forwarded PCM. That requirement conflicts with continuous microphone
|
||||
capture during silence. Its input row now bounds **detected uncommitted speech**
|
||||
instead, without increasing the 480000-byte default or changing the wire format.
|
||||
The frontend integration handoff is aligned. Earlier Phase 2 idle-overflow
|
||||
evidence is historical and superseded by this scoped amendment.
|
||||
|
||||
[OpenAI server-event reference](https://platform.openai.com/docs/api-reference/realtime-server-events/response/output_audio_transcript/delta?lang=node)
|
||||
defines speech-start coordinates relative to all session input audio, including
|
||||
prefix padding, correlated speech-stop/item identity, and stop coordinates
|
||||
including silence padding. Server VAD still emits activity events when automatic
|
||||
response creation and interruption are disabled. These are speech boundaries,
|
||||
not acknowledgments that arbitrary preceding silence has been discarded.
|
||||
|
||||
[Gemini Live reference](https://ai.google.dev/api/live) defines voiceActivity
|
||||
start/end and audioOffset relative to the audio stream. Continuous realtime input
|
||||
is processed incrementally; automatic activity detection distinguishes speech
|
||||
from inactivity for activity-only turn coverage. Transcription has independent
|
||||
ordering. None of this proves a hard provider memory bound or acknowledges each
|
||||
silent frame. The existing adapter still requires verified native boundaries,
|
||||
maps them into application time, and uses native model/tool output as its
|
||||
input-consumption evidence. No synthetic silence acknowledgment was introduced.
|
||||
|
||||
## Counters and state
|
||||
|
||||
| State | Meaning and release |
|
||||
| --- | --- |
|
||||
| input_transport_bytes / count | Locally queued and in-flight PCM; 96000 bytes and 100 messages. Released only after completed send or terminal teardown. Existing dispatch/send deadlines remain. |
|
||||
| input_admitted_total | Absolute accepted application PCM position; monotonically increases, including silence. |
|
||||
| input_dispatched_total | Absolute prefix whose send was started; provider stop coordinates cannot exceed it. |
|
||||
| input_forwarded_total | Absolute prefix whose send completed; transport completion is not provider consumption. |
|
||||
| input_committed_total | Maximum correlated committed stop boundary. Duplicate/late commitment only acknowledges that turn's known prefix. |
|
||||
| input_buffer_bytes / forwarded_buffer_bytes | Legacy absolute uncommitted-prefix arithmetic retained for evidence/tests; neither is local memory occupancy or measured provider memory. |
|
||||
| uncommitted_speech_bytes | Aggregate detected intervals not yet committed: start to admitted position while active, start to stop boundary once stopped. Silence outside these intervals is excluded. |
|
||||
|
||||
Admission checks the prospective speech total and existing transport reservations
|
||||
independently. A delayed start identifying an already over-limit interval fails
|
||||
immediately. Each genuine start installs one fixed wall deadline:
|
||||
max_input_buffer_bytes / 48000 seconds (10 by default). Duplicate starts cannot
|
||||
restart it. Missing stop therefore fails even if no further PCM arrives.
|
||||
Correlated stop freezes the interval and retains the existing 15-second commit
|
||||
deadline. Early commit remains pending until the validated stop boundary exists.
|
||||
|
||||
Absolute offsets never reset. Start coordinates must be nonnegative, ordered and
|
||||
within dispatched input. Replay fencing, private current-turn tokens, old-prefix
|
||||
commit fencing, authority/epoch checks and interruption release barriers remain.
|
||||
The ASR capacity fixture now sends real PCM before emitting its positions.
|
||||
|
||||
There is no local VAD, RMS gate, input-buffer clear, added dependency, migration,
|
||||
or provider configuration change. The 24 kHz mono PCM16LE browser format remains.
|
||||
Provider-specific resampling and native consumption semantics remain in adapters.
|
||||
Gemini interruption still closes safely where native context truncation is
|
||||
unverified; this repair does not add seamless Gemini interruption.
|
||||
|
||||
If speech-start is entirely absent, this runtime cannot distinguish undetected
|
||||
speech from silence. It retains no cumulative PCM history: queues, sender scratch,
|
||||
event/input mappings and sends remain bounded. Existing provider connection-loss
|
||||
handling, WebSocket liveness and application session expiry remain the outer
|
||||
protection. A missing stop/commit after detected activity has explicit deadlines.
|
||||
This is not a promise of provider memory reclamation during indefinite silence.
|
||||
|
||||
## Diagnostics
|
||||
|
||||
Every runtime overflow branch now records a stable internal reason, application
|
||||
session ID, bounded numeric occupancy/limits and phase. Capture transport,
|
||||
uncommitted speech, speech-stop deadline, provider/client control capacity,
|
||||
provider events, input/output mappings, response intents, tool calls, output
|
||||
backlog/slabs and playback stalls are distinguishable. Playback stall records sent
|
||||
bytes, acknowledged played_ms and elapsed time. Gemini exceptions supply stable
|
||||
private backlog/slab/metadata/control/mapping reasons and numeric bounds.
|
||||
Only necessary numeric fields were added to the allowlist. No audio, transcripts,
|
||||
private input IDs, credentials or full payloads are logged.
|
||||
|
||||
## Changed files
|
||||
|
||||
- app/modules/voice/runtime.py, settings.py, diagnostics.py
|
||||
- app/infrastructure/gemini_live.py
|
||||
- tests/unit/test_voice_input_accounting.py (new)
|
||||
- tests/unit/test_realtime_repairs.py, test_realtime_remaining.py,
|
||||
test_phase2_provider_selection.py
|
||||
- docs/specifications/RAG-Phase1-API-Catalog.md
|
||||
- docs/guides/frontend-voice-integration-example.md
|
||||
- docs/agent-reference-map.md and this report
|
||||
|
||||
The old overflow-without-commit regression now starts a genuine speech interval
|
||||
and still proves the byte bound. Replacement silence tests exercise real runtime
|
||||
sender/event paths. Seven new cases cover 30-second silence before/during/between
|
||||
turns, absolute commitment positions, duplicate/late events, fixed missing-event
|
||||
deadlines, queued saturation, long speech and safe branch diagnostics. Native
|
||||
Gemini coverage sends 30 seconds through its actual adapter, then verifies native
|
||||
activity/output commitment at the correct absolute stop boundary. Existing tests
|
||||
cover in-flight send stalls, interruption/rapid turns, provider loss, output
|
||||
backlog and playback barriers.
|
||||
|
||||
## Executed verification
|
||||
|
||||
Commands used Python 3.14.6 in the existing .venv; all provider interactions were
|
||||
fake/local. Focused commands used -q -p no:cacheprovider.
|
||||
|
||||
1. Realtime repairs/Phase 1/context sync/Gemini focused: **161 passed**.
|
||||
2. Expanded focused run including incident unit/integration sources:
|
||||
**197 passed, 11 PostgreSQL skipped**. Skips are not database acceptance.
|
||||
3. Affected provider-selection/remaining/input-accounting/extraction-timeout
|
||||
follow-up: **205 passed**.
|
||||
4. `.venv/Scripts/python -m pytest -m "not postgres"`:
|
||||
**1834 passed, 3 skipped, 415 deselected, 25 warnings in 265.41 seconds**.
|
||||
The skips are existing Windows file/directory symlink permission cases;
|
||||
warnings are existing WebSocket deprecations. The nested environment-isolation
|
||||
suite also passed.
|
||||
5. Final diagnostic-unit/native-Gemini-boundary refinements were followed by
|
||||
provider selection/remaining/Gemini/input-accounting focused verification:
|
||||
**80 passed in 29.16 seconds**. The full suite was not repeated after these
|
||||
narrowly scoped refinements.
|
||||
6. `git diff --check`: passed; Git only reported pre-existing CRLF notices.
|
||||
|
||||
Intermediate results are not hidden: the first new test run had a wrong helper
|
||||
name (1 failed, 3 passed), corrected before its 4-case passing recheck. The first
|
||||
full run had **4 failed, 1827 passed, 3 skipped**: the obsolete Gemini silence
|
||||
assertion, an impossible ASR position fixture, a consequent nested-suite failure,
|
||||
and an extraction timeout under concurrent test contention. A stop-first run
|
||||
confirmed the obsolete assertion. The standalone affected follow-up and full
|
||||
recheck passed; unrelated extraction implementation was not changed.
|
||||
|
||||
Database behavior and applied migrations were untouched, so PostgreSQL acceptance
|
||||
was not required or run. Existing unrelated working-tree changes were preserved.
|
||||
|
||||
## Remaining live acceptance and deployment
|
||||
|
||||
No paid provider call, API restart, image build or operational deployment occurred.
|
||||
No real browser/microphone or funded-provider acceptance is claimed.
|
||||
After separately authorized API deployment, verify readiness/source-image
|
||||
correspondence and use a fresh voice session: silence 30 seconds, speak, listen
|
||||
through the complete response, pause 30 seconds, speak again, interrupt, stop.
|
||||
Check positions, branch diagnostics, safety bounds and consistent terminal state.
|
||||
Real provider activity ordering, silence handling and resource behavior remain
|
||||
acceptance obligations; synthetic success alone is not complete incident closure.
|
||||
@@ -0,0 +1,196 @@
|
||||
# Browser voice termination repair — 2026-10-10
|
||||
|
||||
Local backend corrections are implemented. Historical incident attribution and real
|
||||
browser/provider acceptance remain unverified. No paid provider calls were made.
|
||||
|
||||
## Findings and evidence
|
||||
|
||||
| Finding | Evidence and correction |
|
||||
| --- | --- |
|
||||
| OpenAI terminal item mismatch — confirmed code defect | The unchanged HEAD runtime rejects a synthetic documented sequence: correlated response, assistant transcript delta/completion, audio completion, then an assistant message whose single content part has type `output_audio`. The deployed runtime, lifecycle and OpenAI adapter matched local pre-edit SHA-256 hashes. OpenAI's current [server-event reference](https://developers.openai.com/api/reference/resources/realtime/server-events) describes assistant item content as `output_audio` and shows it in `response.done`. The runtime expected internal `audio`. [RealtimeAdapter.normalize_output_item](../../app/infrastructure/realtime.py) now normalizes only that documented item field; runtime validates the normalized layout in both item and response terminal events. Original wire values still govern event replay hashes. |
|
||||
| Backend failure lost to frontend close — confirmed code defect | `finish_session` originally persisted whichever terminal request acquired the settings lock first; the stream persisted only after provider cleanup. A browser receiving a backend error could therefore persist `user_requested` first. [Lifecycle](../../app/modules/voice/lifecycle.py) now checks the owning runtime's immutable first failure inside the existing scoped transaction when an active session receives user cleanup. The stream attempts terminal persistence before provider cleanup. Already terminal rows remain immutable. |
|
||||
| Manual stop reported as revocation — confirmed code defect | Every `finish_session` notification previously used registry's default `CONTEXT_REVOKED`, including ordinary /close. [Registry](../../app/modules/voice/registry.py) now propagates the actual committed reason; genuine user stop wakes the stream and stops media without manufacturing an authority error. |
|
||||
| Authority masking — suspected mechanism not reproduced | Existing `fail()` already ignores later failures, so secondary `fail("CONTEXT_REVOKED")` calls did not overwrite a previously accepted technical error. [Runtime.check_authority](../../app/modules/voice/runtime.py) now owns classification for exceptions and genuine invalidation. Redundant release/delivery revocation calls were removed; timeout, database failure and saturation retain `SEARCH_TIMEOUT`, `DEPENDENCY_UNAVAILABLE` and `SEARCH_SATURATED`. All authority checks remain fail closed. |
|
||||
| Cleanup ownership/privacy — regression-confirmed defect | Concurrent close waiters now share one runtime shutdown and one bounded provider-close task. Cancellation of a waiter does not cancel shared cleanup. A new test exposed Python 3.14 logging raw provider exception text through a cancelled shield waiter. Owned shutdown tasks now return exceptions privately to their waiters, which re-raise them after shielding; safe diagnostics distinguish timeout from other failure. No deadline was increased. |
|
||||
|
||||
The historical session IDs and post-failure database snapshots do not establish
|
||||
which authority predicate failed or which provider event was rejected at the time.
|
||||
The output type defect reproduces the observed protocol symptom, but cannot be
|
||||
assigned conclusively to session fc99a461 without its failing event/condition.
|
||||
The historical generic cleanup warning did not distinguish timeout from provider
|
||||
exception, so its original cause also remains unknown. Likewise, the close notification defect does not prove why session 90a4ce96 first
|
||||
received CONTEXT_REVOKED.
|
||||
|
||||
Read-only deployed inspection found `VOICE_PROVIDER=openai`,
|
||||
`OPENAI_REALTIME_MODEL=gpt-realtime-mini`, and a configured credential.
|
||||
No credential value was printed, and credential presence is not spending
|
||||
authorization. No operational database acceptance tests, migrations, deployment
|
||||
or operational application session mutations were performed.
|
||||
|
||||
## Diagnostic and contract behavior
|
||||
|
||||
[diagnostics.py](../../app/modules/voice/diagnostics.py) logs application session
|
||||
ID, phase, an allowlisted event type, exception class, stable internal reason and
|
||||
failure code. Unknown event types become `unknown`; arbitrary exception text,
|
||||
provider payloads, audio, transcripts, tool inputs/results, headers and credentials
|
||||
are excluded. Protocol errors such as unsupported output layout, replay conflict,
|
||||
PCM alignment and identity rebound have distinct safe reason codes.
|
||||
Provider-close timeout and exception have `CLEANUP_TIMEOUT` and
|
||||
`CLEANUP_FAILED`; stream cleanup and terminal-persistence failures have their own
|
||||
phases. Public stream/error envelopes are unchanged.
|
||||
|
||||
V04 remains owner-scoped and idempotent. Genuine user stop remains
|
||||
`closed/user_requested/error_code=NULL`. Technical backend failure remains
|
||||
`failed/<causal code>/<causal code>` even if browser cleanup follows it.
|
||||
CONTEXT_REVOKED retains the existing closed-session classification, with
|
||||
`close_reason=CONTEXT_REVOKED` and `error_code=NULL`.
|
||||
A late failure cannot replace a genuinely committed user closure.
|
||||
|
||||
No applied migration, provider secret location, authorization predicate, search
|
||||
scope, input/output PCM format, cancellation/truncation acknowledgement,
|
||||
ordering, correlation or memory limit was changed. Gemini has no OpenAI item
|
||||
normalizer. Unrelated working-tree edits were retained, including concurrent
|
||||
changes outside this repair.
|
||||
|
||||
## Validation
|
||||
|
||||
New regressions:
|
||||
- [Unit incident cases](../../tests/unit/test_voice_session_incident.py):
|
||||
authority categories at startup/release/delivery; genuine revocation;
|
||||
GA OpenAI terminal sequence and replay; text/extra-part/role/identity rejection;
|
||||
diagnostic privacy; normal stop; concurrent close cancellation, exception,
|
||||
timeout and ownership; adapter separation.
|
||||
- [PostgreSQL incident cases](../../tests/integration/test_voice_session_incident.py):
|
||||
backend failure versus concurrent close; repeated close; late failure after
|
||||
genuine user closure; actual authenticated ASGI cleanup with both adapters,
|
||||
provider timeout/exception, durable terminal state and registry/media release.
|
||||
- Existing interruption, native Gemini, OpenAI, authorization, transport and
|
||||
lifecycle regressions were exercised. The existing Gemini oversized-frame
|
||||
case now has a bounded test ID; its 262 KB ID previously prevented pytest
|
||||
setup/teardown on Windows (32,767-character environment limit).
|
||||
|
||||
All PostgreSQL runs used task-created container
|
||||
`rag-voice-incident-20261010-test`, dedicated database
|
||||
`rag_voice_incident_test`, port `127.0.0.1:55438`, and Psycopg.
|
||||
The fixtures validate the dedicated name, create unique disposable schemas,
|
||||
and remove those schemas. They do not fall back to operational/public tables. The interrupted
|
||||
broad run left a disposable schema; the task-owned container and its anonymous
|
||||
test volume were removed after final affected acceptance, including that residue.
|
||||
The operational containers and volumes were left intact.
|
||||
|
||||
| Command | Outcome |
|
||||
| --- | --- |
|
||||
| `git diff --check` | Passed; repeated after final documentation. |
|
||||
| `.venv/Scripts/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short` | Final run: **1795 passed**, 3 Windows symlink skips, 414 PostgreSQL cases deselected, 25 existing deprecation warnings, **265.17 s**. Earlier successful run before the parser additions: 1792 passed, 253.16 s. |
|
||||
| `.venv/Scripts/python -m pytest tests/unit/test_voice_session_incident.py tests/unit/test_gemini_live.py tests/unit/test_realtime_remaining.py tests/unit/test_realtime_repairs.py tests/unit/test_realtime_phase1.py -m "not postgres" -q -p no:cacheprovider --tb=short` | 302 passed in 33.86 s after parser diagnostic refinement. |
|
||||
| `.venv/Scripts/python -m pytest -m postgres --require-postgres -q -p no:cacheprovider --tb=short` | **Incomplete/interrupted**. Progress reached beyond 69%, then stopped producing output while the Python process continued consuming CPU near the unrelated large-review cases in collection order. Interruption returned exit 1 without a final summary or stack. Its exact cause was not established; this run is not full acceptance proof. |
|
||||
| `.venv/Scripts/python -m pytest tests/integration/test_voice_session_incident.py tests/integration/test_phase2_postgres.py -m postgres --require-postgres -q -p no:cacheprovider --tb=short` | Final affected acceptance: **71 passed in 246.24 s**, zero skips. |
|
||||
| `.venv/Scripts/python -m pytest tests/integration/test_voice_session_incident.py -m postgres --require-postgres -q -p no:cacheprovider --tb=short` | **10 passed in 50.50 s**, both provider adapters and all new incident database cases. |
|
||||
| `.venv/Scripts/python -m pytest tests/unit/test_test_environment.py::test_acceptance_mode_requires_database_configuration -q -p no:cacheprovider --tb=short` | 1 passed in 4.92 s; confirms absent TEST_DATABASE_URL fails acceptance. |
|
||||
|
||||
For the database commands above, TEST_DATABASE_URL was set only in their
|
||||
PowerShell process to the dedicated `rag_voice_incident_test` database on
|
||||
port 55438.
|
||||
|
||||
Initial failures were retained as evidence: 288 focused unit passes plus one
|
||||
Python 3.14 shutdown privacy failure, corrected; 70 focused database passes plus
|
||||
one new fixture readiness failure, corrected. The fixture now waits for actual
|
||||
runtime readiness before failure injection and uses a 500 ms synthetic cleanup
|
||||
deadline instead of 50 ms; production deadlines remain unchanged. The first full
|
||||
ordinary run had 1790 passes, three skips, two Windows oversized-ID setup errors
|
||||
and an isolation subprocess failure caused by those same errors.
|
||||
|
||||
The documented output sequence was also executed against HEAD source loaded in
|
||||
memory without replacing working-tree files: its completion assertion failed as
|
||||
expected (one selected case), confirming baseline rejection. The corrected
|
||||
initial incident unit run passed all 26 cases; the final full ordinary run also includes the three added parser cases.
|
||||
|
||||
## Frontend handoff
|
||||
|
||||
No `voice-transport.ts` or `voice-stream.service.ts` was found in the repository
|
||||
or under `D:/raymand/projects`. The delivered JavaScript example is not evidence
|
||||
that the actual Angular implementation is fixed. Update the Angular transport
|
||||
and service together:
|
||||
|
||||
1. Capture immutable session ID and connection generation in every callback.
|
||||
Store cleanup ownership per session, not in a mutable global current-session
|
||||
field.
|
||||
2. Route server error, WebSocket close and manual Stop through the same
|
||||
`cleanupOnce` promise. Assign the promise before the first asynchronous step,
|
||||
so racing callbacks share it. Send at most one POST /close per session.
|
||||
3. Save the first server error before starting cleanup. Keep it as the primary
|
||||
UI reason; socket code 1011 and cleanup HTTP errors must not replace it.
|
||||
A normal server-confirmed manual stop should remain a normal stopped state.
|
||||
4. Stop owned capture/playback/worklet, timers and socket once. Old-generation
|
||||
callbacks may release their own resources and close their own session, but
|
||||
must never clear a new connection, update its UI or send /close for its ID.
|
||||
5. Do not automatically reconnect or create another session in an error/onclose
|
||||
loop. A fresh user connection uses a fresh reservation after reconciliation.
|
||||
|
||||
Example ownership pattern (adapt resource cleanup to the existing frontend):
|
||||
|
||||
```ts
|
||||
const owner = {
|
||||
sessionId, generation,
|
||||
serverError: undefined as VoiceError | undefined,
|
||||
cleanup: undefined as Promise<void> | undefined
|
||||
};
|
||||
|
||||
function cleanupOnce(): Promise<void> {
|
||||
return owner.cleanup ??= Promise.resolve().then(async () => {
|
||||
try { await stopOwnedMedia(owner); }
|
||||
finally { await closeVoiceSession(owner.sessionId); }
|
||||
});
|
||||
}
|
||||
|
||||
function onServerError(error: VoiceError): void {
|
||||
owner.serverError ??= error;
|
||||
if (isCurrent(owner)) showVoiceError(owner.serverError);
|
||||
void cleanupOnce().catch(() => {
|
||||
if (isCurrent(owner) && !owner.serverError) showCleanupFailure();
|
||||
});
|
||||
}
|
||||
// onclose and manual Stop call the same cleanupOnce(); they retain serverError.
|
||||
```
|
||||
|
||||
Verify error -> onclose -> repeated Stop races with spies/network capture:
|
||||
one close request, one resource teardown, original server reason preserved.
|
||||
Reconnect to a fresh session before delivering a stale callback; assert the
|
||||
new session remains active and no request targets its ID. Preserve
|
||||
session_ready admission, PCM24k mono, played-sample progress and interruption
|
||||
handling already required by the frontend integration guide.
|
||||
|
||||
## Deployment and browser acceptance
|
||||
|
||||
Review the scoped repair alongside existing local edits. No migration or new
|
||||
dependency is required. For the current Compose deployment:
|
||||
|
||||
```powershell
|
||||
docker compose build api
|
||||
docker compose up -d --no-deps api
|
||||
curl.exe http://localhost:8080/health/ready
|
||||
```
|
||||
|
||||
Use the configured API port if it differs. Keep one API process and the supported
|
||||
`python -m app.server` entrypoint. Restart ends old voice sessions; start a fresh
|
||||
conversation/session after readiness. The ingestion worker and database require
|
||||
no repair-specific restart. Deployment was not executed.
|
||||
|
||||
With authorized provider spending and real browser hardware:
|
||||
- Login; verify /me and configuration; connect and receive session_ready.
|
||||
- Speak several turns, including a document question and follow-up; verify
|
||||
transcripts, audible PCM playback, evidence and no unexpected terminal error.
|
||||
- Interrupt while speech is playing; verify old playback flushes, cancellation
|
||||
and truncation finish, and the next turn proceeds.
|
||||
- Stop manually; verify one cleanup request, normal stop, and consistent
|
||||
closed/user_requested state.
|
||||
- Exercise a controlled backend failure in a nonproduction session; verify the
|
||||
primary server code survives UI cleanup and polling, close remains idempotent,
|
||||
and provider timeout/exception does not strand media ownership.
|
||||
|
||||
If unexpected termination remains, collect the safe `Voice diagnostic` line
|
||||
for its application session: phase, event type, exception class, reason and
|
||||
code, plus terminal polling state. Do not collect full provider payloads,
|
||||
credentials, audio or transcripts. Actual Angular fixes, historical incident
|
||||
attribution, funded OpenAI/Gemini multi-turn speech, Persian quality and browser
|
||||
hardware/HTTPS acceptance remain outstanding.
|
||||
@@ -403,7 +403,7 @@ These finite engineering defaults are frozen for initial integration and configu
|
||||
| Application transport audio queues | 96000 raw bytes (2 seconds) AND 100 queued messages per direction; count queues/in-flight sends until completion. Output scheduling also obeys the smaller 72000-byte T+R credit window in 7.1.5 |
|
||||
| Provider-generated reservoir / aggregate undrained output | 1440000 bytes (30 seconds) across G+T+R, 512 packed slabs, bounded descriptors/scratch/metadata; 7.1.5 distinguishes storage from delivery/playback |
|
||||
| Browser output backlog | 96000 bytes AND 100 messages across all refs, including currently playing remainder and scheduled buffers; independently enforced by browser |
|
||||
| Input since last commit | 480000 bytes (10 seconds), including forwarded provider-buffered PCM; fail if not committed within this bound |
|
||||
| Detected uncommitted speech | 480000 bytes (10 seconds) across trusted speech intervals, including VAD padding; silence outside those intervals is excluded. Active intervals also have a 10-second wall deadline from receipt of speech-start; stopped intervals require commitment within 15 seconds. These are lifecycle bounds, not claims about provider-retained PCM |
|
||||
| Control/event queues | 64 messages and 262144 encoded bytes per direction; ordered relative to audio markers |
|
||||
| Send completion deadline | 5 seconds per message; uncertain/failed send fails session, does not increment confirmed sent_bytes |
|
||||
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
"""Durable close races on isolated PostgreSQL, with no paid provider."""
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
from uuid import UUID
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
|
||||
from app.modules.voice import registry
|
||||
from tests.integration.test_phase2_postgres import seeded_env, api, reserve, concurrent, session
|
||||
from tests.unit.test_realtime_phase1 import until
|
||||
|
||||
|
||||
@pytest.mark.parametrize("code", ["LIVE_PROVIDER_PROTOCOL_ERROR", "LIVE_CONTEXT_SYNC_FAILED", "DEPENDENCY_UNAVAILABLE",
|
||||
"SEARCH_TIMEOUT", "SEARCH_SATURATED", "CONTEXT_REVOKED"])
|
||||
def test_backend_failure_wins_following_close_without_rewriting_terminal(seeded_env, code):
|
||||
async def scenario():
|
||||
e = seeded_env
|
||||
_, sid = reserve(e)
|
||||
runtime = SimpleNamespace(failure=code, lock=asyncio.Lock(), fail=lambda _: None)
|
||||
registry.register(sid, e.org, 1, e.user.auth_session_id, runtime)
|
||||
try:
|
||||
results = await asyncio.to_thread(concurrent,
|
||||
lambda: e.lifecycle.close_live_session(e.user, sid),
|
||||
lambda: e.lifecycle.finish_session(e.user, sid, code, failed=code != "CONTEXT_REVOKED"))
|
||||
assert all(r["close_reason"] == code for r in results)
|
||||
assert e.lifecycle.close_live_session(e.user, sid)["close_reason"] == code
|
||||
with e.engine.connect() as conn:
|
||||
row = conn.execute(text("SELECT status,close_reason,error_code FROM live_sessions WHERE id=:id"),
|
||||
{"id": sid}).one()
|
||||
assert row == (("closed", code, None) if code == "CONTEXT_REVOKED" else ("failed", code, code))
|
||||
finally:
|
||||
registry.unregister(sid)
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_genuine_close_and_late_failure_are_idempotent(seeded_env):
|
||||
e = seeded_env
|
||||
_, sid = reserve(e)
|
||||
first = e.lifecycle.close_live_session(e.user, sid)
|
||||
assert first["close_reason"] == "user_requested"
|
||||
assert e.lifecycle.close_live_session(e.user, sid) == first
|
||||
assert e.lifecycle.finish_session(e.user, sid, "LIVE_PROVIDER_PROTOCOL_ERROR", failed=True) == first
|
||||
|
||||
|
||||
@pytest.mark.parametrize("api", ["gemini", "openai"], indirect=True)
|
||||
@pytest.mark.parametrize("cleanup", ["timeout", "exception"])
|
||||
def test_asgi_failure_then_browser_close_preserves_error_and_releases_guards(api, monkeypatch, caplog, cleanup):
|
||||
from app.api.v1 import live
|
||||
from app.modules.voice.settings import RuntimeSettings
|
||||
from app.infrastructure.realtime import RealtimeAdapter
|
||||
client, wire, _, e = api
|
||||
headers, result, _ = session(client, e)
|
||||
sid = UUID(result["session_id"])
|
||||
real_settings = RuntimeSettings
|
||||
monkeypatch.setattr(live, "RuntimeSettings", lambda: real_settings(_env_file=None, send_timeout_seconds=.5))
|
||||
close_calls = []
|
||||
async def close():
|
||||
close_calls.append(1)
|
||||
if cleanup == "timeout": await asyncio.Event().wait()
|
||||
raise ConnectionError("SECRET_PROVIDER_CLOSE")
|
||||
wire.close = close
|
||||
with client.websocket_connect("ws://localhost:8000"+result["stream_path"],
|
||||
headers={"Origin": "http://localhost:8000"}) as ws:
|
||||
ack = {"setupComplete": {}} if e.voice_config.provider == "gemini" else {
|
||||
"type": "session.updated", "session": RealtimeAdapter(wire).setup()["session"]}
|
||||
client.portal.call(wire.inbound.put, ack)
|
||||
assert ws.receive_json()["type"] == "session_ready"
|
||||
client.portal.call(until, lambda: registry.ENTRIES[sid].runtime.ready)
|
||||
# Fail runtime while the route and provider-close work are still live.
|
||||
async def fail():
|
||||
entry = registry.ENTRIES[sid]
|
||||
async with entry.runtime.lock:
|
||||
entry.runtime.fail("LIVE_PROVIDER_PROTOCOL_ERROR")
|
||||
client.portal.call(fail)
|
||||
error = ws.receive_json()
|
||||
assert error["error"]["code"] == "LIVE_PROVIDER_PROTOCOL_ERROR"
|
||||
for _ in range(3):
|
||||
response = client.post("/api/v1/voice/sessions/"+str(sid)+"/close", headers=headers)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["close_reason"] == "LIVE_PROVIDER_PROTOCOL_ERROR"
|
||||
client.portal.call(until, lambda: sid not in live.ACTIVE_MEDIA_SESSIONS)
|
||||
assert sid not in registry.ENTRIES and close_calls == [1]
|
||||
with e.engine.connect() as conn:
|
||||
row = conn.execute(text("SELECT status,close_reason,error_code FROM live_sessions WHERE id=:id"), {"id": sid}).one()
|
||||
assert row == ("failed", "LIVE_PROVIDER_PROTOCOL_ERROR", "LIVE_PROVIDER_PROTOCOL_ERROR")
|
||||
assert ("CLEANUP_TIMEOUT" if cleanup == "timeout" else "CLEANUP_FAILED") in caplog.text
|
||||
assert "SECRET_PROVIDER_CLOSE" not in caplog.text
|
||||
@@ -87,7 +87,8 @@ def test_native_tool_correlation_canonical_result_and_once_only_continuation(set
|
||||
asyncio.run(scenario())
|
||||
|
||||
@pytest.mark.parametrize('message', [ConnectionError('remote-private-detail'), 'x'*262145,
|
||||
{'serverContent':{'interrupted':True}}, {'goAway':{'timeLeft':'1s'}}])
|
||||
{'serverContent':{'interrupted':True}}, {'goAway':{'timeLeft':'1s'}}],
|
||||
ids=['provider_loss', 'oversized_frame', 'unexpected_interruption', 'goaway'])
|
||||
def test_provider_loss_and_limits_wake_runtime_and_close_once(runner,persisted,message):
|
||||
async def scenario():
|
||||
runtime,adapter,wire,out,receive=await make(SimpleNamespace(engine=None),runner,persisted)
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
"""Controlled-clock synchronization races and private branch attribution."""
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.unit.test_realtime_phase1 import (
|
||||
runner, persisted, make, input_turn, response, delta, done, until, commands,
|
||||
)
|
||||
from tests.unit.test_realtime_repairs import Clock, without_ticker
|
||||
|
||||
|
||||
@pytest.mark.parametrize("terminal_first", [False, True])
|
||||
@pytest.mark.parametrize("verified", [False, True])
|
||||
def test_cancel_error_requires_verified_classification_and_terminal(
|
||||
runner, persisted, caplog, terminal_first, verified):
|
||||
async def scenario():
|
||||
clock = Clock()
|
||||
runtime, transport, out = await make(SimpleNamespace(engine=None), runner,
|
||||
persisted, clock=clock,
|
||||
classifier=(lambda e: e.get("code") == "verified-fixture-race") if verified else None)
|
||||
await without_ticker(runtime)
|
||||
try:
|
||||
await input_turn(runtime)
|
||||
await response(runtime, transport)
|
||||
await runtime.handle(delta(48000))
|
||||
await until(lambda: next(iter(runtime.audio.values())).sent == 48000)
|
||||
audio = next(iter(runtime.audio.values()))
|
||||
await runtime.playback_progress(audio.ref, 100)
|
||||
await input_turn(runtime, "u2", 10)
|
||||
await until(lambda: commands(transport, "response.cancel"))
|
||||
await runtime.playback_progress(audio.ref, 420)
|
||||
if terminal_first:
|
||||
await done(runtime)
|
||||
await runtime.handle(dict(type="error", error=dict(
|
||||
event_id=runtime.responses["r1"].cancel_event,
|
||||
code="verified-fixture-race", message="SECRET_PROVIDER_ERROR")))
|
||||
if not verified:
|
||||
assert runtime.failure == "LIVE_CONTEXT_SYNC_FAILED"
|
||||
assert "reason=CANCELLATION_PROVIDER_ERROR" in caplog.text
|
||||
assert "SECRET_PROVIDER_ERROR" not in caplog.text
|
||||
return
|
||||
assert runtime.usable
|
||||
assert len(commands(transport, "response.create")) == 1
|
||||
if not terminal_first:
|
||||
await done(runtime)
|
||||
clock.advance(1)
|
||||
await runtime.tick()
|
||||
await until(lambda: commands(transport, "conversation.item.truncate"))
|
||||
truncation = commands(transport, "conversation.item.truncate")[0]
|
||||
assert truncation["audio_end_ms"] == 420
|
||||
assert audio.frozen
|
||||
ack = dict(type="conversation.item.truncated", item_id="a1",
|
||||
content_index=0, audio_end_ms=420)
|
||||
await runtime.handle(ack)
|
||||
await runtime.handle(dict(ack, event_id="duplicate-ack"))
|
||||
await runtime.playback_progress(audio.ref, 420)
|
||||
await until(lambda: len(commands(transport, "response.create")) == 2)
|
||||
assert runtime.usable and audio.state == "retired"
|
||||
assert len(commands(transport, "response.cancel")) == 1
|
||||
assert len(commands(transport, "conversation.item.truncate")) == 1
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("branch,reason", [
|
||||
("response", "RESPONSE_ACK_DEADLINE"),
|
||||
("input", "INPUT_COMMIT_DEADLINE"),
|
||||
("cancel", "CANCELLATION_ACK_DEADLINE"),
|
||||
("truncate", "TRUNCATION_ACK_DEADLINE"),
|
||||
])
|
||||
def test_deadline_diagnostic_identifies_branch(runner, persisted, caplog, branch, reason):
|
||||
async def scenario():
|
||||
clock = Clock()
|
||||
runtime, transport, out = await make(SimpleNamespace(engine=None), runner,
|
||||
persisted, clock=clock)
|
||||
await without_ticker(runtime)
|
||||
try:
|
||||
if branch == "input":
|
||||
await input_turn(runtime, commit=False)
|
||||
deadline = runtime.current.input_deadline
|
||||
else:
|
||||
await input_turn(runtime)
|
||||
await until(lambda: commands(transport, "response.create"))
|
||||
if branch == "response":
|
||||
deadline = runtime.intent_deadline
|
||||
else:
|
||||
await response(runtime, transport)
|
||||
await runtime.handle(delta(48000))
|
||||
await until(lambda: next(iter(runtime.audio.values())).sent == 48000)
|
||||
await input_turn(runtime, "u2", 10)
|
||||
await until(lambda: commands(transport, "response.cancel"))
|
||||
if branch == "cancel":
|
||||
deadline = runtime.responses["r1"].cancel_deadline
|
||||
else:
|
||||
await done(runtime, status="cancelled")
|
||||
clock.advance(1)
|
||||
await runtime.tick()
|
||||
await until(lambda: commands(transport, "conversation.item.truncate"))
|
||||
deadline = next(iter(runtime.audio.values())).cleanup_deadline
|
||||
clock.now = deadline
|
||||
await runtime.tick()
|
||||
assert runtime.failure == "LIVE_CONTEXT_SYNC_FAILED"
|
||||
assert runtime.session_id in caplog.text
|
||||
assert f"reason={reason}" in caplog.text
|
||||
assert "deadline_remaining_ms=0" in caplog.text
|
||||
assert "pending_commands=" in caplog.text
|
||||
if branch == "truncate":
|
||||
assert "sent_bytes=48000" in caplog.text
|
||||
assert "played_ms=0" in caplog.text
|
||||
before = caplog.text
|
||||
runtime.sync_failed("SECONDARY_FAILURE")
|
||||
assert caplog.text == before
|
||||
assert runtime.failure == "LIVE_CONTEXT_SYNC_FAILED"
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("position", [419, 421])
|
||||
def test_truncation_mismatch_diagnostic_remains_fail_closed(
|
||||
runner, persisted, caplog, position):
|
||||
async def scenario():
|
||||
clock = Clock()
|
||||
runtime, transport, out = await make(SimpleNamespace(engine=None), runner,
|
||||
persisted, clock=clock)
|
||||
await without_ticker(runtime)
|
||||
try:
|
||||
await input_turn(runtime)
|
||||
await response(runtime, transport)
|
||||
await runtime.handle(delta(48000))
|
||||
await until(lambda: next(iter(runtime.audio.values())).sent == 48000)
|
||||
audio = next(iter(runtime.audio.values()))
|
||||
await done(runtime)
|
||||
await input_turn(runtime, "u2", 10)
|
||||
assert not commands(transport, "response.cancel")
|
||||
await runtime.playback_progress(audio.ref, 420)
|
||||
clock.advance(1)
|
||||
await runtime.tick()
|
||||
await until(lambda: commands(transport, "conversation.item.truncate"))
|
||||
await runtime.handle(dict(type="conversation.item.truncated", item_id="a1",
|
||||
content_index=0, audio_end_ms=position))
|
||||
assert runtime.failure == "LIVE_CONTEXT_SYNC_FAILED"
|
||||
assert "reason=TRUNCATION_ACK_POSITION_MISMATCH" in caplog.text
|
||||
assert "played_ms=420" in caplog.text
|
||||
assert len(commands(transport, "response.create")) == 1
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_numeric_diagnostics_are_allowlisted_and_bounded(caplog):
|
||||
from app.modules.voice.diagnostics import diagnostic
|
||||
diagnostic("fixture-session", "context_sync", "TRUNCATION_PROVIDER_ERROR",
|
||||
sent_bytes=10**100, played_ms=True, transcript="SECRET_TRANSCRIPT",
|
||||
tool_result="SECRET_TOOL", pending_audio=3)
|
||||
assert "sent_bytes=2147483647" in caplog.text
|
||||
assert "pending_audio=3" in caplog.text
|
||||
assert "played_ms=" not in caplog.text
|
||||
assert "SECRET" not in caplog.text
|
||||
|
||||
|
||||
# Sanitized structured fields captured with gpt-realtime-mini/shimmer on
|
||||
# 2026-10-10; no raw provider events, audio, transcript, or credentials retained.
|
||||
CAPTURED_NO_ACTIVE = dict(type="invalid_request_error",
|
||||
code="response_cancel_not_active", param=None)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("terminal_order", ["before_error", "after_error", "missing"])
|
||||
def test_captured_selected_profile_cancellation_race(runner, persisted, terminal_order):
|
||||
async def scenario():
|
||||
clock = Clock()
|
||||
runtime, transport, out = await make(SimpleNamespace(engine=None), runner,
|
||||
persisted, clock=clock)
|
||||
await without_ticker(runtime)
|
||||
try:
|
||||
await input_turn(runtime)
|
||||
await response(runtime, transport)
|
||||
await runtime.handle(delta(48000))
|
||||
await until(lambda: next(iter(runtime.audio.values())).sent == 48000)
|
||||
audio = next(iter(runtime.audio.values()))
|
||||
await input_turn(runtime, "u2", 10)
|
||||
await until(lambda: commands(transport, "response.cancel"))
|
||||
await runtime.playback_progress(audio.ref, 420)
|
||||
error = dict(type="error", error=dict(CAPTURED_NO_ACTIVE,
|
||||
event_id=runtime.responses["r1"].cancel_event))
|
||||
if terminal_order == "before_error":
|
||||
await done(runtime)
|
||||
await runtime.handle(error)
|
||||
assert runtime.usable
|
||||
await runtime.handle(dict(error, event_id="replayed-cancel-error"))
|
||||
assert runtime.usable
|
||||
if terminal_order == "missing":
|
||||
clock.now = runtime.responses["r1"].cancel_deadline
|
||||
await runtime.tick()
|
||||
assert runtime.failure == "LIVE_CONTEXT_SYNC_FAILED"
|
||||
assert not commands(transport, "conversation.item.truncate")
|
||||
return
|
||||
if terminal_order == "after_error":
|
||||
await done(runtime)
|
||||
clock.advance(1)
|
||||
await runtime.tick()
|
||||
await until(lambda: commands(transport, "conversation.item.truncate"))
|
||||
assert commands(transport, "conversation.item.truncate")[0]["audio_end_ms"] == 420
|
||||
assert len(commands(transport, "response.create")) == 1
|
||||
await runtime.handle(dict(type="conversation.item.truncated", item_id="a1",
|
||||
content_index=0, audio_end_ms=420))
|
||||
await until(lambda: len(commands(transport, "response.create")) == 2)
|
||||
await response(runtime, transport, response_id="r2")
|
||||
# Late duplicate cancellation errors cannot cancel the new response.
|
||||
await runtime.handle(dict(error, event_id="late-cancel-error"))
|
||||
assert runtime.usable and audio.state == "retired"
|
||||
assert not runtime.responses["r2"].interrupted
|
||||
assert len(commands(transport, "response.cancel")) == 1
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mutation", [
|
||||
dict(code="other_error"), dict(type="server_error"), dict(param="response_id"),
|
||||
dict(code="response_cancel_not_active_EXTRA"),
|
||||
dict(message="response_cancel_not_active", code="invalid_argument"),
|
||||
])
|
||||
def test_captured_classifier_rejects_other_errors(mutation):
|
||||
from app.infrastructure.realtime import RealtimeAdapter
|
||||
from tests.unit.test_realtime_phase1 import Transport
|
||||
adapter = RealtimeAdapter(Transport())
|
||||
assert adapter.is_no_active(CAPTURED_NO_ACTIVE)
|
||||
assert not adapter.is_no_active(dict(CAPTURED_NO_ACTIVE, **mutation))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("profile", [
|
||||
dict(model="unverified-model"), dict(voice="unverified-voice"),
|
||||
])
|
||||
def test_captured_classifier_is_restricted_to_verified_profile(profile):
|
||||
from app.infrastructure.realtime import RealtimeAdapter
|
||||
from tests.unit.test_realtime_phase1 import Transport
|
||||
assert not RealtimeAdapter(Transport(), **profile).is_no_active(CAPTURED_NO_ACTIVE)
|
||||
|
||||
@pytest.mark.parametrize("failure", ["transport", "protocol"])
|
||||
def test_receive_failure_during_sync_keeps_category_and_private_reason(
|
||||
runner, persisted, caplog, failure):
|
||||
async def scenario():
|
||||
from app.infrastructure.realtime import ProviderProtocolError
|
||||
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
||||
try:
|
||||
await input_turn(runtime)
|
||||
await response(runtime, transport)
|
||||
await input_turn(runtime, "u2", 10)
|
||||
await until(lambda: commands(transport, "response.cancel"))
|
||||
async def broken():
|
||||
if failure == "transport":
|
||||
raise ConnectionError("SECRET_TRANSPORT")
|
||||
raise ProviderProtocolError("SECRET_PROTOCOL")
|
||||
runtime.adapter.receive = broken
|
||||
await runtime.receive_loop()
|
||||
expected = "LIVE_CONTEXT_SYNC_FAILED" if failure == "transport" else "LIVE_PROVIDER_PROTOCOL_ERROR"
|
||||
assert runtime.failure == expected
|
||||
assert "SECRET" not in caplog.text
|
||||
if failure == "transport":
|
||||
assert "reason=PROVIDER_TRANSPORT_LOST_DURING_SYNC" in caplog.text
|
||||
assert "exception=ConnectionError" in caplog.text
|
||||
await asyncio.gather(runtime.close(), runtime.close())
|
||||
assert runtime.failure == expected and transport.closed
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("status", ["failed", "incomplete"])
|
||||
def test_terminal_technical_failure_is_not_accepted_as_cancellation_race(
|
||||
runner, persisted, status):
|
||||
async def scenario():
|
||||
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
||||
try:
|
||||
await input_turn(runtime)
|
||||
await response(runtime, transport)
|
||||
await input_turn(runtime, "u2", 10)
|
||||
await until(lambda: commands(transport, "response.cancel"))
|
||||
await done(runtime, status=status)
|
||||
await runtime.handle(dict(type="error", error=dict(CAPTURED_NO_ACTIVE,
|
||||
event_id=runtime.responses["r1"].cancel_event)))
|
||||
assert runtime.failure == "LIVE_PROVIDER_UNAVAILABLE"
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
@@ -10,7 +10,7 @@ from app.infrastructure.gemini_live import GeminiLiveAdapter
|
||||
from app.infrastructure.realtime import RealtimeAdapter
|
||||
from app.modules.voice.runtime import VoiceRuntime
|
||||
from app.modules.voice.settings import RuntimeSettings
|
||||
from tests.unit.test_gemini_live import FakeGoogleTransport, make, cleanup
|
||||
from tests.unit.test_gemini_live import FakeGoogleTransport, make, cleanup, input_turn as gemini_input_turn
|
||||
from tests.unit.test_realtime_phase1 import runner, persisted, until
|
||||
|
||||
@pytest.mark.parametrize('provider,adapter,rate', [('gemini',GeminiLiveAdapter,16000),('openai',RealtimeAdapter,24000)])
|
||||
@@ -80,18 +80,30 @@ def test_actual_authority_check_deadline(runner):
|
||||
await r.start();assert r.failure=='SEARCH_TIMEOUT';await r.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
def test_ten_seconds_continuous_uncommitted_silence_keeps_frozen_bound(runner,persisted):
|
||||
def test_thirty_seconds_gemini_silence_keeps_transport_bounded(runner,persisted):
|
||||
async def scenario():
|
||||
r,adapter,wire,out,receive=await make(SimpleNamespace(engine=None),runner,persisted)
|
||||
try:
|
||||
for _ in range(100):
|
||||
for _ in range(300):
|
||||
await r.input_audio(bytes(4800))
|
||||
await until(lambda:r.input_transport_count==0 or not r.usable)
|
||||
async with asyncio.timeout(3):
|
||||
while r.input_transport_count and r.usable:
|
||||
await asyncio.sleep(0)
|
||||
assert r.usable,r.failure
|
||||
assert r.input_dispatched_total==480000
|
||||
assert r.input_dispatched_total==1440000
|
||||
assert r.uncommitted_speech_bytes == r.input_transport_bytes == 0
|
||||
assert not r.inputs and r.input_committed_total == 0
|
||||
await r.input_audio(bytes(2))
|
||||
assert r.failure=='LIVE_BUFFER_OVERFLOW'
|
||||
await until(lambda: r.input_transport_count == 0)
|
||||
assert r.usable and r.failure is None
|
||||
assert not any('toolResponse' in m for m in wire.sent)
|
||||
await gemini_input_turn(r, wire, start=30000)
|
||||
await wire.inbound.put({'serverContent': {'modelTurn': {'parts': [
|
||||
{'inlineData': {'mimeType': 'audio/pcm;rate=24000', 'data': 'AAA='}}
|
||||
]}}})
|
||||
await until(lambda: r.current is not None and r.current.committed or not r.usable)
|
||||
assert r.usable and r.current.stop_boundary == 30100 * 48
|
||||
assert r.input_committed_total == r.current.stop_boundary
|
||||
finally:await cleanup(r,receive)
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
@@ -1005,6 +1005,8 @@ def test_asr_completion_state_bounded_by_input_mapping_and_content_layout(runner
|
||||
limits = RuntimeSettings(_env_file=None, max_input_turns=2)
|
||||
runtime.settings = runtime.adapter.settings = limits
|
||||
try:
|
||||
await runtime.input_audio(bytes(144))
|
||||
await until(lambda: runtime.input_transport_count == 0)
|
||||
for n in range(2):
|
||||
await runtime.handle(dict(type="input_audio_buffer.speech_started",
|
||||
item_id="u" + str(n), audio_start_ms=n))
|
||||
|
||||
@@ -281,10 +281,12 @@ def test_input_buffer_survives_send_and_commit_releases_only_old_prefix(runner,
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
def test_forwarded_input_buffer_overflow_without_commit(runner, persisted):
|
||||
def test_detected_forwarded_speech_overflow_without_commit(runner, persisted):
|
||||
async def scenario():
|
||||
runtime, transport, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
||||
try:
|
||||
await runtime.handle(dict(type="input_audio_buffer.speech_started",
|
||||
item_id="bounded", audio_start_ms=0))
|
||||
for _ in range(50):
|
||||
await runtime.input_audio(bytes(9600))
|
||||
await until(lambda: runtime.input_transport_count == 0)
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
"""Silence and speech lifecycle bounds through real runtime sender/event paths."""
|
||||
import asyncio
|
||||
from types import SimpleNamespace
|
||||
import pytest
|
||||
|
||||
from tests.unit.test_realtime_phase1 import (
|
||||
make, until, input_turn, response, delta, done, runner, persisted,
|
||||
)
|
||||
|
||||
|
||||
async def stream(runtime, frames, now):
|
||||
for _ in range(frames):
|
||||
await runtime.input_audio(bytes(960))
|
||||
async with asyncio.timeout(3):
|
||||
while runtime.input_transport_count:
|
||||
await asyncio.sleep(0)
|
||||
now[0] += .02
|
||||
assert runtime.usable
|
||||
|
||||
|
||||
def test_silence_before_during_and_between_turns_preserves_absolute_positions(runner, persisted):
|
||||
async def scenario():
|
||||
now = [0.]
|
||||
runtime, transport, output = await make(SimpleNamespace(engine=None), runner, persisted,
|
||||
clock=lambda: now[0])
|
||||
try:
|
||||
await stream(runtime, 1500, now)
|
||||
assert runtime.input_forwarded_total == 1440000
|
||||
assert runtime.input_transport_bytes == runtime.uncommitted_speech_bytes == 0
|
||||
first = await input_turn(runtime, start=30000)
|
||||
assert first.stop_boundary == 30100 * 48
|
||||
assert runtime.input_committed_total == first.stop_boundary
|
||||
await response(runtime, transport)
|
||||
await runtime.handle(delta(48))
|
||||
await until(lambda: any(isinstance(e, bytes) for e in output))
|
||||
audio = next(iter(runtime.audio.values()))
|
||||
await runtime.playback_progress(audio.ref, 1)
|
||||
await stream(runtime, 1500, now)
|
||||
assert runtime.responses["r1"].terminal is False
|
||||
await done(runtime)
|
||||
await stream(runtime, 1500, now)
|
||||
start = runtime.input_dispatched_total // 48
|
||||
second = await input_turn(runtime, item="u2", start=start)
|
||||
assert second.stop_boundary == (start + 100) * 48
|
||||
assert second.committed and runtime.usable
|
||||
assert runtime.uncommitted_speech_bytes == 0
|
||||
assert all(cmd.pcm is None for cmd in runtime.pending_commands.values())
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("missing", ["stop", "commit"])
|
||||
def test_missing_speech_events_have_fixed_deadlines(runner, persisted, missing, caplog):
|
||||
async def scenario():
|
||||
now = [0.]
|
||||
runtime, transport, _ = await make(SimpleNamespace(engine=None), runner, persisted,
|
||||
clock=lambda: now[0])
|
||||
try:
|
||||
await stream(runtime, 1500, now)
|
||||
await runtime.handle(dict(type="input_audio_buffer.speech_started",
|
||||
item_id="u1", audio_start_ms=30000))
|
||||
turn = runtime.current
|
||||
if missing == "commit":
|
||||
await runtime.input_audio(bytes(9600))
|
||||
await until(lambda: runtime.input_transport_count == 0)
|
||||
await runtime.handle(dict(type="input_audio_buffer.speech_stopped",
|
||||
item_id="u1", audio_end_ms=30200))
|
||||
deadline = turn.input_deadline
|
||||
else:
|
||||
deadline = turn.speech_deadline
|
||||
await runtime.handle(dict(type="input_audio_buffer.speech_started",
|
||||
item_id="u1", audio_start_ms=30000))
|
||||
assert turn.speech_deadline == deadline
|
||||
now[0] = deadline + .001
|
||||
assert not runtime.check_deadlines()
|
||||
assert runtime.failure == ("LIVE_BUFFER_OVERFLOW" if missing == "stop"
|
||||
else "LIVE_CONTEXT_SYNC_FAILED")
|
||||
assert runtime.input_transport_bytes == 0
|
||||
assert ("SPEECH_STOP_DEADLINE" if missing == "stop" else
|
||||
"INPUT_COMMIT_DEADLINE") in caplog.text
|
||||
assert runtime.session_id in caplog.text
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_late_commit_does_not_release_new_speech_interval(runner, persisted):
|
||||
async def scenario():
|
||||
now = [0.]
|
||||
runtime, _, _ = await make(SimpleNamespace(engine=None), runner, persisted, clock=lambda: now[0])
|
||||
try:
|
||||
await stream(runtime, 1500, now)
|
||||
await input_turn(runtime, item="old", start=30000, commit=False)
|
||||
await runtime.handle(dict(type="input_audio_buffer.speech_started",
|
||||
item_id="new", audio_start_ms=30150))
|
||||
before = runtime.uncommitted_speech_bytes
|
||||
await runtime.handle(dict(type="input_audio_buffer.committed", item_id="old"))
|
||||
after = runtime.uncommitted_speech_bytes
|
||||
assert before - after == 100 * 48
|
||||
await runtime.handle(dict(type="input_audio_buffer.committed", item_id="old"))
|
||||
assert runtime.uncommitted_speech_bytes == after
|
||||
assert not runtime.current.committed
|
||||
await runtime.handle(dict(type="input_audio_buffer.speech_started",
|
||||
item_id="old", audio_start_ms=30000))
|
||||
assert runtime.current.input_id == "new" and runtime.token == 2
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("branch", ["transport", "speech", "late_start"])
|
||||
def test_capacity_diagnostics_identify_the_failure_without_payloads(runner, persisted, caplog, branch):
|
||||
async def scenario():
|
||||
now = [0.]
|
||||
runtime, _, _ = await make(SimpleNamespace(engine=None), runner, persisted, clock=lambda: now[0])
|
||||
try:
|
||||
if branch == "transport":
|
||||
# No sender scheduling: all admitted PCM remains queued.
|
||||
for _ in range(11):
|
||||
await runtime.input_audio(bytes(9600))
|
||||
reason = "CAPTURE_TRANSPORT_CAPACITY"
|
||||
elif branch == "late_start":
|
||||
await stream(runtime, 1500, now)
|
||||
await runtime.handle(dict(type="input_audio_buffer.speech_started",
|
||||
item_id="private-input-id", audio_start_ms=0))
|
||||
reason = "UNCOMMITTED_SPEECH_BYTES"
|
||||
else:
|
||||
await runtime.handle(dict(type="input_audio_buffer.speech_started",
|
||||
item_id="private-input-id", audio_start_ms=0))
|
||||
# Fixed clock isolates the byte bound from the independent wall deadline.
|
||||
for _ in range(50):
|
||||
await runtime.input_audio(bytes(9600))
|
||||
async with asyncio.timeout(3):
|
||||
while runtime.input_transport_count:
|
||||
await asyncio.sleep(0)
|
||||
assert runtime.uncommitted_speech_bytes == 480000
|
||||
await runtime.input_audio(bytes(2))
|
||||
reason = "UNCOMMITTED_SPEECH_BYTES"
|
||||
assert runtime.failure == "LIVE_BUFFER_OVERFLOW" and runtime.close_code == 1013
|
||||
assert runtime.input_transport_bytes == runtime.input_transport_count == 0
|
||||
assert reason in caplog.text and runtime.session_id in caplog.text
|
||||
assert "limit_bytes=" in caplog.text and "occupancy_bytes=" in caplog.text
|
||||
assert "phase=capture_transport" in caplog.text if branch == "transport" else "phase=speaking" in caplog.text
|
||||
assert "private-input-id" not in caplog.text and "delta=" not in caplog.text
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
@@ -0,0 +1,204 @@
|
||||
"""Incident regressions with sanitized synthetic provider events."""
|
||||
import asyncio
|
||||
from copy import deepcopy
|
||||
from types import SimpleNamespace
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from sqlalchemy.exc import OperationalError
|
||||
|
||||
from app.modules.voice import registry
|
||||
from app.modules.voice.settings import RuntimeSettings
|
||||
from tests.unit.test_realtime_phase1 import (
|
||||
runner, persisted, make, input_turn, response, terminal, until,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failure,code", [
|
||||
("timeout", "SEARCH_TIMEOUT"),
|
||||
("database", "DEPENDENCY_UNAVAILABLE"),
|
||||
("saturation", "SEARCH_SATURATED"),
|
||||
("revocation", "CONTEXT_REVOKED"),
|
||||
])
|
||||
@pytest.mark.parametrize("phase", ["startup", "release", "delivery"])
|
||||
def test_authority_category_survives_secondary_callers(runner, persisted, failure, code, phase):
|
||||
async def scenario():
|
||||
runtime, wire, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
||||
turn = await input_turn(runtime)
|
||||
await response(runtime, wire)
|
||||
runtime.settings = RuntimeSettings(_env_file=None, authority_timeout_seconds=.02)
|
||||
async def unavailable(_):
|
||||
if failure == "timeout":
|
||||
await asyncio.Event().wait()
|
||||
if failure == "database":
|
||||
raise OperationalError("private sql", {}, RuntimeError("private db"))
|
||||
if failure == "saturation":
|
||||
raise ValueError("SERVICE_BUSY")
|
||||
return False
|
||||
runtime.authority_check = unavailable
|
||||
try:
|
||||
if phase == "startup":
|
||||
assert not await runtime.authorized(turn)
|
||||
elif phase == "release":
|
||||
await runtime._authorize_release(turn)
|
||||
else:
|
||||
await runtime.handle(dict(type="response.output_audio_transcript.delta",
|
||||
response_id="r1", item_id="a1", output_index=0, content_index=0, delta="fixture"))
|
||||
await until(lambda: runtime.failure is not None)
|
||||
# Secondary failure paths must never replace the causal outcome.
|
||||
runtime.fail("CONTEXT_REVOKED")
|
||||
await until(lambda: any(isinstance(e, dict) and e["type"] == "error" for e in out))
|
||||
assert runtime.failure == code
|
||||
assert next(e["error"]["code"] for e in out if isinstance(e, dict) and e["type"] == "error") == code
|
||||
assert turn.cancelled.is_set()
|
||||
assert not any(isinstance(e, bytes) for e in out)
|
||||
assert not any(isinstance(e, dict) and e.get("role") == "assistant" for e in out)
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("invalid", [None, "text", "extra_part", "wrong_role", "rebound"])
|
||||
def test_openai_ga_output_item_after_transcript(runner, persisted, invalid):
|
||||
async def scenario():
|
||||
runtime, wire, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
||||
await input_turn(runtime)
|
||||
result = await response(runtime, wire)
|
||||
item = dict(id="a1", type="message", role="assistant", content=[])
|
||||
try:
|
||||
await runtime.handle(dict(type="response.output_item.added", response_id="r1", output_index=0, item=deepcopy(item)))
|
||||
await runtime.handle(dict(type="response.content_part.added", response_id="r1", item_id="a1",
|
||||
output_index=0, content_index=0, part=dict(type="audio", transcript="")))
|
||||
await runtime.handle(dict(type="response.output_audio_transcript.delta", response_id="r1",
|
||||
item_id="a1", output_index=0, content_index=0, delta="Synthetic answer"))
|
||||
await until(lambda: any(isinstance(e, dict) and e.get("role") == "assistant" for e in out))
|
||||
await runtime.handle(dict(type="response.output_audio_transcript.done", response_id="r1",
|
||||
item_id="a1", output_index=0, content_index=0, transcript="Synthetic answer"))
|
||||
await runtime.handle(dict(type="response.output_audio.done", response_id="r1",
|
||||
item_id="a1", output_index=0, content_index=0))
|
||||
item["content"] = [dict(type="output_audio", transcript="Synthetic answer")]
|
||||
if invalid == "text": item["content"][0]["type"] = "output_text"
|
||||
if invalid == "extra_part": item["content"].append(dict(type="output_audio"))
|
||||
if invalid == "wrong_role": item["role"] = "user"
|
||||
if invalid == "rebound": item["id"] = "other"
|
||||
wire_event = dict(type="response.output_item.done", response_id="r1", output_index=0,
|
||||
event_id="fixture-item-done", item=deepcopy(item))
|
||||
await runtime.handle(wire_event)
|
||||
if invalid is None:
|
||||
await runtime.handle(wire_event) # unchanged wire replay
|
||||
await runtime.handle(terminal(output=[item]))
|
||||
assert runtime.usable and result.terminal and result.status == "completed"
|
||||
assert wire_event["item"]["content"][0]["type"] == "output_audio"
|
||||
else:
|
||||
assert runtime.failure == "LIVE_PROVIDER_PROTOCOL_ERROR"
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_protocol_diagnostics_are_bounded_and_private(runner, persisted, caplog):
|
||||
async def scenario():
|
||||
runtime, wire, _ = await make(SimpleNamespace(engine=None), runner, persisted)
|
||||
await input_turn(runtime)
|
||||
await response(runtime, wire)
|
||||
try:
|
||||
await runtime.handle(dict(type="response.output_item.done", response_id="r1", output_index=0,
|
||||
item=dict(id="a1", type="message", role="assistant",
|
||||
content=[dict(type="output_text", text="SECRET_TRANSCRIPT")]),
|
||||
private="SECRET_CREDENTIAL"))
|
||||
assert runtime.failure == "LIVE_PROVIDER_PROTOCOL_ERROR"
|
||||
assert "phase=provider_handle" in caplog.text
|
||||
assert "event=response.output_item.done" in caplog.text
|
||||
assert "reason=UNSUPPORTED_OUTPUT_LAYOUT" in caplog.text
|
||||
assert "exception=ValueError" in caplog.text
|
||||
assert runtime.session_id in caplog.text
|
||||
assert "SECRET" not in caplog.text
|
||||
finally:
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("event_type", [{"private": "SECRET"}, "SECRET", None])
|
||||
def test_unknown_diagnostic_event_type_cannot_leak_or_raise(caplog, event_type):
|
||||
from app.modules.voice.diagnostics import diagnostic
|
||||
diagnostic(str(uuid4()), "provider_handle", "INVALID_PROVIDER_EVENT",
|
||||
event_type=event_type, exc=ValueError("SECRET"))
|
||||
assert "event=unknown" in caplog.text and "SECRET" not in caplog.text
|
||||
|
||||
|
||||
def test_http_stop_notification_is_normal_and_first_failure_stays_primary(runner, persisted):
|
||||
async def scenario():
|
||||
for failed in (False, True):
|
||||
runtime, _, out = await make(SimpleNamespace(engine=None), runner, persisted)
|
||||
sid = uuid4()
|
||||
registry.register(sid, "fixture", 1, uuid4(), runtime)
|
||||
try:
|
||||
if failed:
|
||||
runtime.fail("LIVE_PROVIDER_PROTOCOL_ERROR")
|
||||
registry.notify(session_id=sid, code="user_requested")
|
||||
await until(lambda: not runtime.usable)
|
||||
await asyncio.sleep(.01)
|
||||
assert runtime.failure == ("LIVE_PROVIDER_PROTOCOL_ERROR" if failed else None)
|
||||
if not failed:
|
||||
assert runtime.close_code == 1000
|
||||
assert not any(isinstance(e, dict) and e["type"] == "error" for e in out)
|
||||
finally:
|
||||
registry.unregister(sid)
|
||||
await runtime.close()
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ending", ["timeout", "exception", "success"])
|
||||
def test_concurrent_shutdown_has_one_owner_and_safe_diagnostics(runner, persisted, caplog, ending):
|
||||
async def scenario():
|
||||
runtime, wire, _ = await make(SimpleNamespace(engine=None), runner, persisted)
|
||||
runtime.settings = RuntimeSettings(_env_file=None, send_timeout_seconds=.03)
|
||||
started = asyncio.Event()
|
||||
calls = []
|
||||
async def close():
|
||||
calls.append(1)
|
||||
started.set()
|
||||
if ending == "timeout": await asyncio.Event().wait()
|
||||
if ending == "exception": raise ConnectionError("SECRET_CLOSE")
|
||||
wire.close = close
|
||||
runtime.fail("LIVE_PROVIDER_PROTOCOL_ERROR", writable=False)
|
||||
waiter = asyncio.create_task(runtime.close())
|
||||
await started.wait()
|
||||
waiter.cancel()
|
||||
await asyncio.gather(waiter, return_exceptions=True)
|
||||
results = await asyncio.gather(runtime.close(), runtime.close(), return_exceptions=True)
|
||||
assert calls == [1] and runtime.failure == "LIVE_PROVIDER_PROTOCOL_ERROR"
|
||||
assert all(t.done() for t in runtime._workers)
|
||||
assert runtime._provider_close_task.done() and runtime._close_task.done()
|
||||
if ending == "success":
|
||||
assert results == [None, None]
|
||||
else:
|
||||
assert all(isinstance(x, (TimeoutError, ConnectionError)) for x in results)
|
||||
assert ("CLEANUP_TIMEOUT" if ending == "timeout" else "CLEANUP_FAILED") in caplog.text
|
||||
assert "SECRET_CLOSE" not in caplog.text
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
def test_gemini_has_no_openai_item_normalization():
|
||||
from app.infrastructure.gemini_live import GeminiLiveAdapter
|
||||
from tests.unit.test_gemini_live import FakeGoogleTransport
|
||||
assert not hasattr(GeminiLiveAdapter(FakeGoogleTransport()), "normalize_output_item")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw,reason", [
|
||||
("{", "MALFORMED_PROVIDER_JSON"),
|
||||
('{"type":"error","type":"session.updated"}', "DUPLICATE_PROVIDER_JSON_KEY"),
|
||||
("x" * 262145, "PROVIDER_FRAME_BOUND"),
|
||||
], ids=["malformed_json", "duplicate_key", "oversized_frame"])
|
||||
def test_provider_decode_failure_has_safe_specific_reason(caplog, raw, reason):
|
||||
from app.infrastructure.realtime import RealtimeAdapter, ProviderProtocolError
|
||||
from app.modules.voice.diagnostics import diagnostic, protocol_reason
|
||||
async def scenario():
|
||||
async def recv(): return raw
|
||||
adapter = RealtimeAdapter(SimpleNamespace(recv=recv))
|
||||
with pytest.raises(ProviderProtocolError) as error:
|
||||
await adapter.receive()
|
||||
diagnostic(str(uuid4()), "provider_receive", protocol_reason(error.value), exc=error.value)
|
||||
assert reason in caplog.text
|
||||
assert raw not in caplog.text
|
||||
asyncio.run(scenario())
|
||||
Reference in New Issue
Block a user