Files
rag-technical-docs-assistant/docs/guides/voice-input-accounting-repair.md
amirhosein mazaheri 9e6864ae2a 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
2026-10-12 18:51:06 +03:30

147 lines
9.2 KiB
Markdown

# Voice input accounting repair — 2026-10-10
The confirmed defect is a cumulative accounting error: continuously forwarded
microphone silence increased admitted-minus-committed input until the next sample
exceeded 480000 bytes. That counter describes an absolute stream prefix, not
retained local PCM. This explains the reproducible false overflow; it does not
identify the cause of every historical LIVE_BUFFER_OVERFLOW / 1013 incident.
## Contract adjustment and provider evidence
API catalog 7.1.3 previously explicitly bounded all input since commitment,
including forwarded PCM. That requirement conflicts with continuous microphone
capture during silence. Its input row now bounds **detected uncommitted speech**
instead, without increasing the 480000-byte default or changing the wire format.
The frontend integration handoff is aligned. Earlier Phase 2 idle-overflow
evidence is historical and superseded by this scoped amendment.
[OpenAI server-event reference](https://platform.openai.com/docs/api-reference/realtime-server-events/response/output_audio_transcript/delta?lang=node)
defines speech-start coordinates relative to all session input audio, including
prefix padding, correlated speech-stop/item identity, and stop coordinates
including silence padding. Server VAD still emits activity events when automatic
response creation and interruption are disabled. These are speech boundaries,
not acknowledgments that arbitrary preceding silence has been discarded.
[Gemini Live reference](https://ai.google.dev/api/live) defines voiceActivity
start/end and audioOffset relative to the audio stream. Continuous realtime input
is processed incrementally; automatic activity detection distinguishes speech
from inactivity for activity-only turn coverage. Transcription has independent
ordering. None of this proves a hard provider memory bound or acknowledges each
silent frame. The existing adapter still requires verified native boundaries,
maps them into application time, and uses native model/tool output as its
input-consumption evidence. No synthetic silence acknowledgment was introduced.
## Counters and state
| State | Meaning and release |
| --- | --- |
| input_transport_bytes / count | Locally queued and in-flight PCM; 96000 bytes and 100 messages. Released only after completed send or terminal teardown. Existing dispatch/send deadlines remain. |
| input_admitted_total | Absolute accepted application PCM position; monotonically increases, including silence. |
| input_dispatched_total | Absolute prefix whose send was started; provider stop coordinates cannot exceed it. |
| input_forwarded_total | Absolute prefix whose send completed; transport completion is not provider consumption. |
| input_committed_total | Maximum correlated committed stop boundary. Duplicate/late commitment only acknowledges that turn's known prefix. |
| input_buffer_bytes / forwarded_buffer_bytes | Legacy absolute uncommitted-prefix arithmetic retained for evidence/tests; neither is local memory occupancy or measured provider memory. |
| uncommitted_speech_bytes | Aggregate detected intervals not yet committed: start to admitted position while active, start to stop boundary once stopped. Silence outside these intervals is excluded. |
Admission checks the prospective speech total and existing transport reservations
independently. A delayed start identifying an already over-limit interval fails
immediately. Each genuine start installs one fixed wall deadline:
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.
Correlated stop freezes the interval and retains the existing 15-second commit
deadline. Early commit remains pending until the validated stop boundary exists.
Absolute offsets never reset. Start coordinates must be nonnegative, ordered and
within dispatched input. Replay fencing, private current-turn tokens, old-prefix
commit fencing, authority/epoch checks and interruption release barriers remain.
The ASR capacity fixture now sends real PCM before emitting its positions.
There is no local VAD, RMS gate, input-buffer clear, added dependency, migration,
or provider configuration change. The 24 kHz mono PCM16LE browser format remains.
Provider-specific resampling and native consumption semantics remain in adapters.
Gemini interruption still closes safely where native context truncation is
unverified; this repair does not add seamless Gemini interruption.
If speech-start is entirely absent, this runtime cannot distinguish undetected
speech from silence. It retains no cumulative PCM history: queues, sender scratch,
event/input mappings and sends remain bounded. Existing provider connection-loss
handling, WebSocket liveness and application session expiry remain the outer
protection. A missing stop/commit after detected activity has explicit deadlines.
This is not a promise of provider memory reclamation during indefinite silence.
## Diagnostics
Every runtime overflow branch now records a stable internal reason, application
session ID, bounded numeric occupancy/limits and phase. Capture transport,
uncommitted speech, speech-stop deadline, provider/client control capacity,
provider events, input/output mappings, response intents, tool calls, output
backlog/slabs and playback stalls are distinguishable. Playback stall records sent
bytes, acknowledged played_ms and elapsed time. Gemini exceptions supply stable
private backlog/slab/metadata/control/mapping reasons and numeric bounds.
Only necessary numeric fields were added to the allowlist. No audio, transcripts,
private input IDs, credentials or full payloads are logged.
## Changed files
- app/modules/voice/runtime.py, settings.py, diagnostics.py
- app/infrastructure/gemini_live.py
- tests/unit/test_voice_input_accounting.py (new)
- tests/unit/test_realtime_repairs.py, test_realtime_remaining.py,
test_phase2_provider_selection.py
- docs/specifications/RAG-Phase1-API-Catalog.md
- docs/guides/frontend-voice-integration-example.md
- docs/agent-reference-map.md and this report
The old overflow-without-commit regression now starts a genuine speech interval
and still proves the byte bound. Replacement silence tests exercise real runtime
sender/event paths. Seven new cases cover 30-second silence before/during/between
turns, absolute commitment positions, duplicate/late events, fixed missing-event
deadlines, queued saturation, long speech and safe branch diagnostics. Native
Gemini coverage sends 30 seconds through its actual adapter, then verifies native
activity/output commitment at the correct absolute stop boundary. Existing tests
cover in-flight send stalls, interruption/rapid turns, provider loss, output
backlog and playback barriers.
## Executed verification
Commands used Python 3.14.6 in the existing .venv; all provider interactions were
fake/local. Focused commands used -q -p no:cacheprovider.
1. Realtime repairs/Phase 1/context sync/Gemini focused: **161 passed**.
2. Expanded focused run including incident unit/integration sources:
**197 passed, 11 PostgreSQL skipped**. Skips are not database acceptance.
3. Affected provider-selection/remaining/input-accounting/extraction-timeout
follow-up: **205 passed**.
4. `.venv/Scripts/python -m pytest -m "not postgres"`:
**1834 passed, 3 skipped, 415 deselected, 25 warnings in 265.41 seconds**.
The skips are existing Windows file/directory symlink permission cases;
warnings are existing WebSocket deprecations. The nested environment-isolation
suite also passed.
5. Final diagnostic-unit/native-Gemini-boundary refinements were followed by
provider selection/remaining/Gemini/input-accounting focused verification:
**80 passed in 29.16 seconds**. The full suite was not repeated after these
narrowly scoped refinements.
6. `git diff --check`: passed; Git only reported pre-existing CRLF notices.
Intermediate results are not hidden: the first new test run had a wrong helper
name (1 failed, 3 passed), corrected before its 4-case passing recheck. The first
full run had **4 failed, 1827 passed, 3 skipped**: the obsolete Gemini silence
assertion, an impossible ASR position fixture, a consequent nested-suite failure,
and an extraction timeout under concurrent test contention. A stop-first run
confirmed the obsolete assertion. The standalone affected follow-up and full
recheck passed; unrelated extraction implementation was not changed.
Database behavior and applied migrations were untouched, so PostgreSQL acceptance
was not required or run. Existing unrelated working-tree changes were preserved.
## Remaining live acceptance and deployment
No paid provider call, API restart, image build or operational deployment occurred.
No real browser/microphone or funded-provider acceptance is claimed.
After separately authorized API deployment, verify readiness/source-image
correspondence and use a fresh voice session: silence 30 seconds, speak, listen
through the complete response, pause 30 seconds, speak again, interrupt, stop.
Check positions, branch diagnostics, safety bounds and consistent terminal state.
Real provider activity ordering, silence handling and resource behavior remain
acceptance obligations; synthetic success alone is not complete incident closure.