fix(voice): expand speech buffer to 60s, handle 2.1 cancellation race, and bound cleanup

- Expand max_input_buffer_bytes to 3,072,000 (64s at 24kHz PCM16) with 65s fixed deadline
- Broaden response_cancel_not_active race classifier to include gpt-realtime-2.1/shimmer
- Add transport abort method and bound cleanup waits during websocket close
- Record repair progress in docs/plans/live-conversation-repair-progress.md
This commit is contained in:
amirhosein mazaheri
2026-10-12 18:51:06 +03:30
parent d493752b81
commit 9e6864ae2a
14 changed files with 203 additions and 19 deletions
+6 -2
View File
@@ -292,7 +292,11 @@ async def handle_stream_websocket(websocket, session_id, auth_service, lifecycle
try:
for task in children:
task.cancel()
await asyncio.gather(*children, return_exceptions=True)
if children:
_, pending_children = await asyncio.wait(children, timeout=5)
if pending_children:
diagnostic(str(session_id), "stream_cleanup", "CLEANUP_TIMEOUT",
code=outcome, pending_tasks=len(pending_children))
try:
# Saturation must not strand the durable terminal outcome once admission frees.
deadline = asyncio.get_running_loop().time() + 6
@@ -309,7 +313,7 @@ async def handle_stream_websocket(websocket, session_id, auth_service, lifecycle
exc=exc, code=outcome)
try:
if runtime:
await asyncio.wait_for(runtime.close(), 6)
await runtime.close()
elif adapter:
await asyncio.wait_for(adapter.close(), 6)
except Exception as exc:
+7
View File
@@ -439,6 +439,13 @@ class GeminiLiveAdapter:
def is_no_active(self, error):
return False
def abort(self):
transport = getattr(self.transport, "transport", None)
if transport is None:
return False
transport.abort()
return True
async def close(self):
if self._close_task is None:
async def cleanup():
+8 -1
View File
@@ -156,7 +156,7 @@ class RealtimeAdapter:
# 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"
return (self.model in ("gpt-realtime-mini", "gpt-realtime-2.1") and self.voice == "shimmer"
and isinstance(error, dict)
and error.get("type") == "invalid_request_error"
and error.get("code") == "response_cancel_not_active"
@@ -164,6 +164,13 @@ class RealtimeAdapter:
except Exception:
return False
def abort(self):
transport = getattr(self.transport, "transport", None)
if transport is None:
return False
transport.abort()
return True
async def close(self):
await self.transport.close()
+1 -1
View File
@@ -116,7 +116,7 @@ NUMERIC_FIELDS = frozenset({
"cancellation_type_match", "cancellation_code_match", "cancellation_param_match", "cancellation_profile_2_1_shimmer",
"transport_limit_bytes", "transport_limit_messages", "occupancy_count", "limit_count", "occupancy_bytes", "limit_bytes", "transport_bytes", "transport_messages",
"speech_bytes", "elapsed_ms", "deadline_remaining_ms", "sent_bytes", "played_ms", "pending_commands",
"pending_responses", "pending_audio", "input_bytes", "http_status",
"pending_responses", "pending_audio", "pending_tasks", "abort_succeeded", "input_bytes", "http_status",
})
def diagnostic(session_id, phase, reason, *, event_type=None, exc=None, code=None, **state):
+24 -9
View File
@@ -395,13 +395,21 @@ class VoiceRuntime:
return self._provider_close_task
async def _bounded_provider_close(self):
closing = asyncio.create_task(self.adapter.close())
done, _ = await asyncio.wait({closing}, timeout=self.settings.send_timeout_seconds)
if done:
if closing.cancelled():
return TimeoutError("Provider close cancelled")
return closing.exception()
closing.cancel()
closing.add_done_callback(lambda task: task.exception() if not task.cancelled() else None)
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
aborted = self.adapter.abort()
except Exception:
aborted = False
diagnostic(self.session_id, "provider_close", "CLEANUP_ABORT",
code=self.failure, abort_succeeded=int(aborted))
return TimeoutError("Provider close deadline")
def _provider_close_finished(self, task):
if not task.cancelled():
exc = task.result()
@@ -501,7 +509,7 @@ class VoiceRuntime:
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)
self.settings.speech_stop_timeout_seconds) * 1000)
if audio is not None:
state.update(sent_bytes=audio.sent, played_ms=audio.played,
elapsed_ms=int((self.clock() - audio.stall_deadline +
@@ -1336,7 +1344,7 @@ class VoiceRuntime:
if not self.usable:
return
self.current.start_position = start
self.current.speech_deadline = self.clock() + self.settings.max_input_buffer_bytes / 48000
self.current.speech_deadline = self.clock() + self.settings.speech_stop_timeout_seconds
if not self.check_deadlines():
return
elif self.inputs[item].start_position != start:
@@ -1768,8 +1776,15 @@ class VoiceRuntime:
tasks = [*self._workers, *self.tasks]
for task in tasks:
task.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
pending = set()
if tasks:
_, pending = await asyncio.wait(tasks, timeout=self.settings.send_timeout_seconds)
if pending:
diagnostic(self.session_id, "runtime_close", "CLEANUP_TIMEOUT",
code=self.failure, pending_tasks=len(pending))
try:
await self._close_provider()
except Exception as exc:
return exc
if pending:
return TimeoutError("Runtime task termination deadline")
+2 -1
View File
@@ -23,7 +23,8 @@ class RuntimeSettings(BaseSettings):
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_input_buffer_bytes: int = Field(default=3072000, ge=3072000, le=3072000)
speech_stop_timeout_seconds: float = Field(default=65, ge=65, le=65, allow_inf_nan=False)
max_output_backlog_bytes: int = Field(default=1440000, gt=0, le=1440000)
output_credit_window_bytes: int = Field(default=72000, ge=48, le=72000)
max_control_messages: int = Field(default=64, ge=2, le=64)