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
+3
View File
@@ -118,6 +118,9 @@ TRUSTED_HOSTS=["localhost:8000","127.0.0.1:8000"]
COOKIE_SECURE=false COOKIE_SECURE=false
AUTH_SESSION_SECONDS=28800 AUTH_SESSION_SECONDS=28800
LIVE_SESSION_SECONDS=600 LIVE_SESSION_SECONDS=600
# 60 seconds of speech plus up to 4 seconds of VAD padding; independent 65-second stop deadline.
LIVE_MAX_INPUT_BUFFER_BYTES=3072000
LIVE_SPEECH_STOP_TIMEOUT_SECONDS=65
# Path to a measured, profile-compatible calibrated report; never a status placeholder. # Path to a measured, profile-compatible calibrated report; never a status placeholder.
# SEARCH_CALIBRATION_REPORT=/absolute/path/measured-report.json # SEARCH_CALIBRATION_REPORT=/absolute/path/measured-report.json
# Explicit connectivity testing only; no uncalibrated document evidence is admitted. # Explicit connectivity testing only; no uncalibrated document evidence is admitted.
+6 -2
View File
@@ -292,7 +292,11 @@ async def handle_stream_websocket(websocket, session_id, auth_service, lifecycle
try: try:
for task in children: for task in children:
task.cancel() 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: try:
# Saturation must not strand the durable terminal outcome once admission frees. # Saturation must not strand the durable terminal outcome once admission frees.
deadline = asyncio.get_running_loop().time() + 6 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) exc=exc, code=outcome)
try: try:
if runtime: if runtime:
await asyncio.wait_for(runtime.close(), 6) await runtime.close()
elif adapter: elif adapter:
await asyncio.wait_for(adapter.close(), 6) await asyncio.wait_for(adapter.close(), 6)
except Exception as exc: except Exception as exc:
+7
View File
@@ -439,6 +439,13 @@ class GeminiLiveAdapter:
def is_no_active(self, error): def is_no_active(self, error):
return False 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): async def close(self):
if self._close_task is None: if self._close_task is None:
async def cleanup(): async def cleanup():
+8 -1
View File
@@ -156,7 +156,7 @@ class RealtimeAdapter:
# Selected-profile probe: docs/guides/live-context-sync-repair.md. # Selected-profile probe: docs/guides/live-context-sync-repair.md.
# The runtime separately requires the cancellation intent event_id, # The runtime separately requires the cancellation intent event_id,
# terminal response confirmation, and heard-position truncation. # 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 isinstance(error, dict)
and error.get("type") == "invalid_request_error" and error.get("type") == "invalid_request_error"
and error.get("code") == "response_cancel_not_active" and error.get("code") == "response_cancel_not_active"
@@ -164,6 +164,13 @@ class RealtimeAdapter:
except Exception: except Exception:
return False 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): async def close(self):
await self.transport.close() 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", "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", "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", "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): 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 return self._provider_close_task
async def _bounded_provider_close(self): 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: try:
await asyncio.wait_for(self.adapter.close(), self.settings.send_timeout_seconds) aborted = self.adapter.abort()
except Exception as exc: except Exception:
# Return failures through shielded ownership. Python 3.14 otherwise aborted = False
# logs raw exception text when a shield waiter was cancelled. diagnostic(self.session_id, "provider_close", "CLEANUP_ABORT",
return exc code=self.failure, abort_succeeded=int(aborted))
return TimeoutError("Provider close deadline")
def _provider_close_finished(self, task): def _provider_close_finished(self, task):
if not task.cancelled(): if not task.cancelled():
exc = task.result() exc = task.result()
@@ -501,7 +509,7 @@ class VoiceRuntime:
speech_bytes=self.uncommitted_speech_bytes) speech_bytes=self.uncommitted_speech_bytes)
if reason == "SPEECH_STOP_DEADLINE" and turn is not None: if reason == "SPEECH_STOP_DEADLINE" and turn is not None:
state["elapsed_ms"] = int((self.clock() - turn.speech_deadline + 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: if audio is not None:
state.update(sent_bytes=audio.sent, played_ms=audio.played, state.update(sent_bytes=audio.sent, played_ms=audio.played,
elapsed_ms=int((self.clock() - audio.stall_deadline + elapsed_ms=int((self.clock() - audio.stall_deadline +
@@ -1336,7 +1344,7 @@ class VoiceRuntime:
if not self.usable: if not self.usable:
return return
self.current.start_position = start 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(): if not self.check_deadlines():
return return
elif self.inputs[item].start_position != start: elif self.inputs[item].start_position != start:
@@ -1768,8 +1776,15 @@ class VoiceRuntime:
tasks = [*self._workers, *self.tasks] tasks = [*self._workers, *self.tasks]
for task in tasks: for task in tasks:
task.cancel() 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: try:
await self._close_provider() await self._close_provider()
except Exception as exc: except Exception as exc:
return 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_bytes: int = Field(default=96000, gt=0, le=96000)
max_queued_audio_messages: int = Field(default=100, gt=0, le=100) max_queued_audio_messages: int = Field(default=100, gt=0, le=100)
# Detected uncommitted speech bytes; excludes silence outside VAD intervals. # 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) max_output_backlog_bytes: int = Field(default=1440000, gt=0, le=1440000)
output_credit_window_bytes: int = Field(default=72000, ge=48, le=72000) output_credit_window_bytes: int = Field(default=72000, ge=48, le=72000)
max_control_messages: int = Field(default=64, ge=2, le=64) max_control_messages: int = Field(default=64, ge=2, le=64)
+10
View File
@@ -186,3 +186,13 @@ selection was not changed. Deploy only when separately authorized, then verify
corrected adapter/runtime files and readiness inside the running API and use a 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 fresh voice session. This incident is not claimed fully resolved without historical
attribution or the remaining deployed browser validation. attribution or the remaining deployed browser validation.
## Additional observed profile (2026-10-12)
The live-conversation incident plan records the same structured
`invalid_request_error` / `response_cancel_not_active` / null-param signature
for `gpt-realtime-2.1/shimmer`. The adapter accepts this exact profile and
signature alongside the previously probed `gpt-realtime-mini/shimmer`.
Runtime event-ID, terminal response, and unheard-audio truncation gates remain
mandatory. The incident observation is profile-specific evidence; this change
does not establish that cancellation acknowledgement deadlines are resolved.
+1 -1
View File
@@ -46,7 +46,7 @@ input-consumption evidence. No synthetic silence acknowledgment was introduced.
Admission checks the prospective speech total and existing transport reservations Admission checks the prospective speech total and existing transport reservations
independently. A delayed start identifying an already over-limit interval fails independently. A delayed start identifying an already over-limit interval fails
immediately. Each genuine start installs one fixed wall deadline: immediately. Each genuine start installs one fixed wall deadline:
max_input_buffer_bytes / 48000 seconds (10 by default). Duplicate starts cannot an independent 65 seconds. The detected interval allows 64 seconds / 3072000 bytes by default, including VAD padding. Duplicate starts cannot
restart it. Missing stop therefore fails even if no further PCM arrives. restart it. Missing stop therefore fails even if no further PCM arrives.
Correlated stop freezes the interval and retains the existing 15-second commit Correlated stop freezes the interval and retains the existing 15-second commit
deadline. Early commit remains pending until the validated stop boundary exists. deadline. Early commit remains pending until the validated stop boundary exists.
@@ -0,0 +1,68 @@
# Live conversation repair handoff
Date: 2026-10-12
Status: **Paused at user request.** This records the uncommitted working tree after work on [the repair plan](live-conversation-repair-plan.md). It is a progress record, not completion or release acceptance.
## Repositories and scope
- Backend: `D:\raymand\projects\rag-technical-docs-assistant`
- Frontend: `D:\raymand\projects\faq_chatbot_frontend`
- Both working trees were clean before this repair began. The changes listed below are uncommitted. No migrations, provider calls, deployment, or PostgreSQL tests were performed.
## What changed
### Backend
- **Issue 1, continuous speech:** `RuntimeSettings.max_input_buffer_bytes` is now fixed at 3,072,000 bytes (64 seconds at 24 kHz PCM16), and an independent, fixed 65-second speech-stop deadline replaces the old deadline derived from the byte bound. The 96,000-byte transport queue and input offset/commit logic remain. The API contract, operator guide, and `.env.example` were aligned. Tests now exercise 10, 30, and 60 seconds with four seconds of padding, hard-bound exhaustion, late starts, missing stop/commit, and transport saturation.
- **Issue 8, already-ended cancellation:** the exact `invalid_request_error` / `response_cancel_not_active` / null-param classifier now also accepts `gpt-realtime-2.1/shimmer`. Other model/voice pairs and signatures remain rejected. Runtime event-ID, response terminal, and truncation gates were not relaxed. A guide addendum records the observed profile and limits of that evidence.
- **Issue 12, cleanup:** route child-task and runtime worker termination waits are bounded. Runtime close retains one shared owner; provider graceful-close expiry attempts the existing transport's abort capability through each adapter. Cleanup diagnostics record pending task count and abort result. The route still attempts terminal persistence and registry release after a task timeout. A regression covers a task that resists cancellation while preserving the original failure.
- The backend edits are in `app/modules/voice/{settings,runtime,diagnostics}.py`, `app/infrastructure/{realtime,gemini_live}.py`, `app/api/v1/live.py`, `.env.example`, the API catalog and two guides, plus the three affected unit-test files.
### Frontend
- **Issue 5, premature listening:** normal completion no longer uses the 700 ms idle heuristic or a completed transcript alone. It requires a matching `audio_ended` and a worklet idle event for the audio reference. Idle while generation remains open is treated as an underrun. Duplicate final transcripts no longer re-flush playback.
- **Issue 4, accounting instrumentation:** the existing `audio_ended.sent_bytes` field is typed and validated when present. The service compares sent and received bytes at sealing, then compares sent bytes with worklet-reported consumed milliseconds at drain, allowing for the sub-millisecond reporting remainder. It logs bounded numeric discrepancies; it does not yet establish or repair the cause of the reported audio/text mismatch.
- Audio-reference tagging now passes through the playback worklet and engine. Duplicate `audio_started` events no longer reset byte accounting; stale seals and old-turn interruptions are guarded. The remaining 700 ms timer is limited to a limited response with no audio reference.
- **Issues 6 and 7** were already implemented in the clean frontend baseline: limited-answer rendering and final transcript snapshot replacement. Their existing tests were exercised; no new implementation for those items was needed in this pass.
- Frontend edits are under `src/app/services/voice-stream/` and `public/assets/worklets/pcm-playback.worklet.js`, including tests. No other frontend paths were edited.
## Plan position
| Plan item | Position at pause |
| --- | --- |
| 1. 60-second speech | Code and targeted regressions pass; real microphone/provider acceptance pending. |
| 2. Choppy audio | Open. No correlated provider-to-worklet trace or prebuffer comparison yet. |
| 3. Complete initial answers | Open. Existing style already requests concise completeness, but the 256-token budget was not changed or evaluated. |
| 4. Audio shorter than text | Instrumentation only. No measured discrepancy attribution or root-cause fix. |
| 5. Premature listening | Code and focused frontend regressions pass; browser playback acceptance pending. |
| 6. Limited answer UI | Present in baseline and focused tests pass; browser acceptance pending. |
| 7. Repeated final text | Present in baseline and focused tests pass; browser acceptance pending. |
| 8. Cancellation race | Narrow classifier change and targeted tests pass; same-connection provider acceptance pending. |
| 9. Cancellation acknowledgement deadline | Open. No timing trace or root-cause fix. |
| 10. Same-topic evidence reuse | Open. No contract amendment, reuse tool, authorization/revision recheck, or PostgreSQL tests were implemented. Current fresh-retrieval rule remains. |
| 11. Longer output capacity | Open. The 30-second bound remains; the proposed 120-second OpenAI bound and token budgets were not measured or selected. |
| 12. Cleanup timeout | Backend code and targeted tests pass; blocked-transport/ASGI and real-provider acceptance pending. |
The plan's diagnostic prerequisite is only partly met. The new audio counters and cleanup numbers do not provide a full provider-to-browser timeline, underrun duration, or cancellation enqueue/dispatch/terminal trace.
## Checks actually run
- Backend focused command: `.venv/Scripts/python -m pytest tests/unit/test_voice_input_accounting.py tests/unit/test_live_context_sync.py tests/unit/test_voice_session_incident.py tests/integration/test_voice_session_incident.py -m "not postgres" -q -p no:cacheprovider` — **69 passed, 11 PostgreSQL cases deselected**.
- Frontend focused command: `npm.cmd test -- --watch=false --include=src/app/services/voice-stream/voice-stream.service.spec.ts --include=src/app/services/voice-stream/voice-event.validator.spec.ts --include=src/app/services/voice-stream/pcm-playback.worklet.spec.ts` — **81 passed**.
- `npm.cmd run build` — passed; existing `moment-jalaali` CommonJS optimization warning.
- Backend broad suite: one parallel run reported failures and was interrupted after stalling near its end. A solo `-x` rerun stopped at the unchanged `test_transport_capacity_survives_timeout_and_recovers_without_late_results[False]` 50 ms timing case after **755 passed, 1 skipped**. Both cases of that test passed when rerun alone. **No clean broad-suite result is claimed.**
- Frontend full suite was run before the final duplicate-flush test assertion was updated: **137 passed, 6 failed**. One failure expected the removed duplicate flush and passes in the later 81-test focused run. The other five were outside edited voice paths: three `localStorage` failures in app/auth/theme tests and two call-center/chat-question rendering assertions. The full suite was not rerun after the correction.
- `git diff --check` passed in both repositories. Git printed only LF/CRLF working-copy notices.
`TEST_DATABASE_URL` was absent. PostgreSQL acceptance, actual browser/microphone playback, same-connection provider runs, and the plan's 20-question answer-quality benchmark have not been performed. Synthetic tests and the build do not establish release readiness.
## Where to resume
1. Review the uncommitted diffs in both repositories and run `git diff --check` again. Preserve these edits; do not treat the handoff as a commit or a completed rollout.
2. Finish and test the remaining cleanup and audio-accounting edge cases, especially unresponsive real transport abort, route finalization, and real worklet consumption at 24/44.1/48 kHz. Keep issue 4 open until an actual trace identifies the first loss point.
3. Instrument and reproduce issues 2 and 9 on the same live connection. Compare fixed 80/120/160/240 ms prebuffer traces; retain the five-second cancellation deadline unless internal blocking is demonstrated.
4. Implement issue 10 as an explicit contract change with session-local evidence, backend-owned eligibility/owner/access-epoch/knowledge-revision revalidation, real source identities, and isolated PostgreSQL tests. Do not infer validity from the current epoch alone.
5. Evaluate issues 3 and 11 together using the plan's fixed 20-question set and measured 512/1024/2048/4096-token candidates. Only then select the OpenAI reservoir and generation budget; keep Gemini bounds separate.
6. Run focused and broad checks again, followed by the plan's browser/provider same-connection acceptance. Record implementation, synthetic checks, and real acceptance separately for each issue.
The active work immediately before the pause was the final diff/contract check. That check returned clean whitespace results and the file inventories above; no further implementation was started.
@@ -432,7 +432,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 | | 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 | | 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 | | Browser output backlog | 96000 bytes AND 100 messages across all refs, including currently playing remainder and scheduled buffers; independently enforced by browser |
| 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 | | Detected uncommitted speech | 3072000 bytes (64 seconds) across trusted speech intervals, allowing 60 seconds of user speech plus up to four seconds of VAD padding; silence outside those intervals is excluded. Active intervals have an independent 65-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 | | 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 | | Send completion deadline | 5 seconds per message; uncertain/failed send fails session, does not increment confirmed sent_bytes |
+13
View File
@@ -286,3 +286,16 @@ def test_terminal_technical_failure_is_not_accepted_as_cancellation_race(
finally: finally:
await runtime.close() await runtime.close()
asyncio.run(scenario()) asyncio.run(scenario())
@pytest.mark.parametrize("model,voice,accepted", [
("gpt-realtime-mini", "shimmer", True),
("gpt-realtime-2.1", "shimmer", True),
("gpt-realtime-2.1", "alloy", False),
("gpt-realtime-2.1-mini", "shimmer", False),
])
def test_no_active_classifier_is_profile_and_signature_bounded(model, voice, accepted):
from app.infrastructure.realtime import RealtimeAdapter
adapter = RealtimeAdapter(object(), model=model, voice=voice)
assert adapter.is_no_active(CAPTURED_NO_ACTIVE) is accepted
assert not adapter.is_no_active(dict(CAPTURED_NO_ACTIVE, code="other"))
assert not adapter.is_no_active(dict(CAPTURED_NO_ACTIVE, param="response_id"))
+29 -3
View File
@@ -121,7 +121,7 @@ def test_capacity_diagnostics_identify_the_failure_without_payloads(runner, pers
await runtime.input_audio(bytes(9600)) await runtime.input_audio(bytes(9600))
reason = "CAPTURE_TRANSPORT_CAPACITY" reason = "CAPTURE_TRANSPORT_CAPACITY"
elif branch == "late_start": elif branch == "late_start":
await stream(runtime, 1500, now) await stream(runtime, 3300, now)
await runtime.handle(dict(type="input_audio_buffer.speech_started", await runtime.handle(dict(type="input_audio_buffer.speech_started",
item_id="private-input-id", audio_start_ms=0)) item_id="private-input-id", audio_start_ms=0))
reason = "UNCOMMITTED_SPEECH_BYTES" reason = "UNCOMMITTED_SPEECH_BYTES"
@@ -129,12 +129,12 @@ def test_capacity_diagnostics_identify_the_failure_without_payloads(runner, pers
await runtime.handle(dict(type="input_audio_buffer.speech_started", await runtime.handle(dict(type="input_audio_buffer.speech_started",
item_id="private-input-id", audio_start_ms=0)) item_id="private-input-id", audio_start_ms=0))
# Fixed clock isolates the byte bound from the independent wall deadline. # Fixed clock isolates the byte bound from the independent wall deadline.
for _ in range(50): for _ in range(320):
await runtime.input_audio(bytes(9600)) await runtime.input_audio(bytes(9600))
async with asyncio.timeout(3): async with asyncio.timeout(3):
while runtime.input_transport_count: while runtime.input_transport_count:
await asyncio.sleep(0) await asyncio.sleep(0)
assert runtime.uncommitted_speech_bytes == 480000 assert runtime.uncommitted_speech_bytes == 3072000
await runtime.input_audio(bytes(2)) await runtime.input_audio(bytes(2))
reason = "UNCOMMITTED_SPEECH_BYTES" reason = "UNCOMMITTED_SPEECH_BYTES"
assert runtime.failure == "LIVE_BUFFER_OVERFLOW" and runtime.close_code == 1013 assert runtime.failure == "LIVE_BUFFER_OVERFLOW" and runtime.close_code == 1013
@@ -146,3 +146,29 @@ def test_capacity_diagnostics_identify_the_failure_without_payloads(runner, pers
finally: finally:
await runtime.close() await runtime.close()
asyncio.run(scenario()) asyncio.run(scenario())
@pytest.mark.parametrize("speech_seconds", [10, 30, 60])
def test_continuous_speech_with_padding_reaches_new_bound(runner, persisted, speech_seconds):
async def scenario():
now = [0.]
runtime, _, _ = await make(SimpleNamespace(engine=None), runner, persisted,
clock=lambda: now[0])
try:
await runtime.handle(dict(type="input_audio_buffer.speech_started",
item_id="u1", audio_start_ms=0))
turn = runtime.current
assert turn.speech_deadline == 65
# Four seconds covers the maximum configured VAD prefix/silence padding.
for _ in range((speech_seconds + 4) * 5):
await runtime.input_audio(bytes(9600))
await until(lambda: runtime.input_transport_count == 0)
now[0] += .2
assert runtime.usable
assert runtime.uncommitted_speech_bytes == (speech_seconds + 4) * 48000
await runtime.handle(dict(type="input_audio_buffer.speech_stopped",
item_id="u1", audio_end_ms=(speech_seconds + 4) * 1000))
await runtime.handle(dict(type="input_audio_buffer.committed", item_id="u1"))
assert turn.committed and runtime.uncommitted_speech_bytes == 0
finally:
await runtime.close()
asyncio.run(scenario())
+30
View File
@@ -202,3 +202,33 @@ def test_provider_decode_failure_has_safe_specific_reason(caplog, raw, reason):
assert reason in caplog.text assert reason in caplog.text
assert raw not in caplog.text assert raw not in caplog.text
asyncio.run(scenario()) asyncio.run(scenario())
def test_close_deadline_does_not_strand_provider_cleanup(runner, persisted, caplog):
async def scenario():
runtime, wire, _ = await make(SimpleNamespace(engine=None), runner, persisted)
runtime.settings = RuntimeSettings(_env_file=None, send_timeout_seconds=.03)
release = asyncio.Event()
started = asyncio.Event()
async def stubborn():
started.set()
while not release.is_set():
try:
await release.wait()
except asyncio.CancelledError:
continue
task = asyncio.create_task(stubborn())
runtime.tasks.add(task)
await started.wait()
runtime.fail("LIVE_PROVIDER_PROTOCOL_ERROR", writable=False)
try:
with pytest.raises(TimeoutError):
await runtime.close()
assert runtime.failure == "LIVE_PROVIDER_PROTOCOL_ERROR"
assert runtime._provider_close_task.done()
assert "pending_tasks=1" in caplog.text
finally:
release.set()
await task
asyncio.run(scenario())