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,7 +41,10 @@ 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:
|
||||
entry.runtime.fail(code)
|
||||
if code == "user_requested":
|
||||
entry.runtime.stop_requested()
|
||||
else:
|
||||
entry.runtime.fail(code)
|
||||
for entry in selected:
|
||||
if not entry.loop.is_closed():
|
||||
entry.loop.call_soon_threadsafe(lambda e=entry: asyncio.create_task(fail(e)))
|
||||
|
||||
+219
-48
@@ -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)
|
||||
await self._close_provider()
|
||||
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)
|
||||
|
||||
Reference in New Issue
Block a user