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:
amirhosein mazaheri
2026-10-10 17:41:11 +03:30
parent b06eaf59f4
commit a769196bfa
23 changed files with 1809 additions and 92 deletions
+25 -8
View File
@@ -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)
+25 -3
View File
@@ -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