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:
@@ -176,19 +176,21 @@ failures persist `failed` with matching close reason/error code; committed termi
|
||||
logout/V04/expiry outcomes remain intact. Persistence retries bounded admission
|
||||
saturation, but a database outage can still prevent a durable write and is logged.
|
||||
|
||||
## Continuous idle input limitation
|
||||
## Continuous microphone input
|
||||
|
||||
The example continuously sends microphone PCM after readiness, including silence.
|
||||
The frozen input-since-commit budget is 480000 bytes (10 seconds at 24 kHz PCM16LE).
|
||||
Without verified native commitment, exactly 480000 bytes are accepted; the next
|
||||
sample fails LIVE_BUFFER_OVERFLOW and closes. Native input consumption/transport
|
||||
send is not commitment. This behavior is deterministic for an idle Gemini fake
|
||||
with no activity boundary and applies to uncommitted admission for either adapter.
|
||||
The example continuously sends 24 kHz mono PCM16LE after readiness, including
|
||||
silence. The 2026-10-10 [input-accounting repair](voice-input-accounting-repair.md)
|
||||
supersedes the earlier deterministic 10-second idle overflow.
|
||||
The 480000-byte limit now bounds trusted detected uncommitted speech intervals,
|
||||
including VAD padding. Local queued/in-flight input remains bounded to 96000 bytes
|
||||
and 100 messages, with existing send deadlines. Silence outside detected speech
|
||||
does not consume the speech allowance. A completed send releases local transport
|
||||
storage only; it is neither provider consumption nor commitment.
|
||||
|
||||
Longer continuous idle operation remains a product/provider-contract decision.
|
||||
This example does not gate silence, fabricate commitment or add browser activity
|
||||
controls. Use explicit stop/close and a fresh eligible session after overflow;
|
||||
do not assume uninterrupted idle capture or seamless Gemini barge-in is supported.
|
||||
Keep sending the original timeline; no RMS gate, new VAD, buffer clear or invented
|
||||
silence acknowledgment is required. Genuine long speech, missing stop/commit,
|
||||
transport saturation and expiry still fail safely. Browser/provider acceptance
|
||||
remains necessary; seamless Gemini context truncation remains unsupported.
|
||||
|
||||
Automated fake-provider/loopback/worklet results prove technical boundaries only.
|
||||
Real provider access, measured retrieval quality, Persian speech, microphone,
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
# OpenAI Live context synchronization repair - 2026-10-10
|
||||
|
||||
The local OpenAI cancellation-race defect is reproduced and corrected. This is
|
||||
not proof that the historical browser incident had this branch or that the
|
||||
deployed browser/API is repaired. No operational rebuild or restart was performed.
|
||||
|
||||
## Confirmed cause and evidence
|
||||
|
||||
[RealtimeAdapter.is_no_active](../../app/infrastructure/realtime.py) previously
|
||||
returned false unless a separately injected classifier was supplied.
|
||||
[create_adapter](../../app/infrastructure/voice_provider.py) supplies no classifier.
|
||||
A response can finish between the runtime's active-state check and provider
|
||||
processing of its response-specific cancellation. The correlated no-active error
|
||||
therefore reached the cancellation-provider-error branch in
|
||||
[VoiceRuntime.handle](../../app/modules/voice/runtime.py), which called
|
||||
LIVE_CONTEXT_SYNC_FAILED even when response.done had already confirmed completion.
|
||||
|
||||
Current [official client-event documentation](https://developers.openai.com/api/reference/resources/realtime/client-events)
|
||||
says cancelling without an active response returns an error and leaves the
|
||||
provider session unaffected. That establishes the semantics, not a stable
|
||||
structured error-code spelling. The governing API catalog Section 7.1.6 requires
|
||||
selected-profile verification before accepting a structured cancellation race.
|
||||
|
||||
After explicit user authorization, one isolated OpenAI connection produced
|
||||
two short responses using the existing gpt-realtime-mini/shimmer configuration.
|
||||
The first completed; its response-specific cancellation returned the exact
|
||||
structured fields type=invalid_request_error, code=response_cancel_not_active,
|
||||
param=null, correlated to that cancellation event_id. Truncation of that
|
||||
completed audio at zero milliseconds was then confirmed by matching item,
|
||||
content_index=0 and audio_end_ms=0. During the second response cancellation was
|
||||
dispatched after an audio delta; response.done reported completed, so this does
|
||||
not prove provider status=cancelled or all active-generation interruption behavior.
|
||||
The [sanitized probe evidence](../calibration/live-context-sync-probe.json)
|
||||
contains no raw audio, transcripts, full provider events, messages, identities,
|
||||
credentials or tool data. The probe's bounded three-second transport-close
|
||||
operation timed out and the isolated process exited; cleanup timeout remains an
|
||||
observed limitation, not a successful close-handshake claim.
|
||||
|
||||
The three captured-provider synthetic regressions failed before the classifier
|
||||
fix with CANCELLATION_PROVIDER_ERROR and LIVE_CONTEXT_SYNC_FAILED. Their controlled
|
||||
sequences covered terminal-before-error, terminal-after-error, and absent terminal
|
||||
confirmation. After correction, both confirmed-terminal orderings safely complete
|
||||
truncation and release the next response; the absent-terminal case still times out.
|
||||
|
||||
The available tail of operational diagnostics did not contain application session
|
||||
ce371f61-6bed-4863-a091-61fe116f1be1 or identify its branch. Historical browser
|
||||
events and the public error code cannot establish that this defect caused that
|
||||
specific incident. During inspection the running API selected Gemini; its
|
||||
dedicated OpenAI settings remained gpt-realtime-mini/shimmer with a configured
|
||||
key. An initial probe guard exited before any connection because the selected
|
||||
provider was Gemini. The authorized probe then used the dedicated OpenAI settings
|
||||
directly without changing the API's selected provider or model configuration.
|
||||
|
||||
## Correction and safety
|
||||
|
||||
The adapter now recognizes only the verified gpt-realtime-mini/shimmer profile
|
||||
and exact structured type/code with a null or absent param. No provider message
|
||||
substring is inspected. Other profiles and error types/codes/parameters remain
|
||||
unaccepted. Existing trusted classifier injection remains available for separately
|
||||
verified profiles and deterministic fixtures.
|
||||
|
||||
The runtime independently requires error.event_id to match one dispatched
|
||||
response-specific cancellation intent. This error neither retries cancellation
|
||||
nor substitutes for terminal confirmation, final playback position, or truncation
|
||||
acknowledgment. Generic/unrelated errors, truncation errors, missing terminal events,
|
||||
mismatched cleanup, changed late progress and transport uncertainty remain fatal.
|
||||
Failed/incomplete terminal responses retain LIVE_PROVIDER_UNAVAILABLE; protocol
|
||||
and send failures retain their existing technical categories. Public errors,
|
||||
PCM layout, authorization/epochs, retrieval, replay fencing, buffer bounds and
|
||||
production deadlines are unchanged. Applied migrations and unrelated working-tree
|
||||
edits were preserved.
|
||||
|
||||
Causal synthetic sequence:
|
||||
|
||||
1. Trusted speech starts; unfinished old output is superseded, delivery stops,
|
||||
refs enter finalizing and cancellation is queued once. turn_interrupted precedes
|
||||
user_speech_started for the next turn.
|
||||
2. Final browser progress is accepted while the original reporting window is open.
|
||||
Tests advance heard position from 100 to 420 ms without restarting the window.
|
||||
3. The old response's response.done and no-active cancellation error can arrive in
|
||||
either order. A verified error is benign only under its mapped cancellation;
|
||||
independent terminal confirmation remains required.
|
||||
4. At window expiry progress freezes. All generated but unconfirmed audio still
|
||||
requires conversation.item.truncate at the frozen position.
|
||||
5. Only a matching item/content/position acknowledgment retires the ref. Input
|
||||
stop/commit plus completed old work then permit the next response.
|
||||
6. Duplicate acknowledgments and late old cancellation errors do not alter the new
|
||||
response. Missing terminal confirmation and unsafe cleanup fail closed.
|
||||
|
||||
## Private diagnostic coverage
|
||||
|
||||
[Runtime.sync_failed](../../app/modules/voice/runtime.py) records the first
|
||||
accepted synchronization failure before retiring state.
|
||||
[Diagnostics](../../app/modules/voice/diagnostics.py) allowlist numeric fields and
|
||||
clamp each to a signed 32-bit range. Records contain application session ID,
|
||||
runtime phase, stable reason, allowlisted provider event type, exception class,
|
||||
public failure category, deadline remaining milliseconds where applicable,
|
||||
pending command/response/audio counts and outstanding input bytes; audio-related
|
||||
branches also record sent_bytes and accepted played_ms where a part is known.
|
||||
Unknown event types, arbitrary exception text, provider messages and payloads are
|
||||
never logged.
|
||||
|
||||
| Failure branch | Internal reason |
|
||||
| --- | --- |
|
||||
| Response creation acknowledgment deadline | RESPONSE_ACK_DEADLINE |
|
||||
| Input commit/consumption deadline | INPUT_COMMIT_DEADLINE |
|
||||
| Cancellation terminal acknowledgment deadline | CANCELLATION_ACK_DEADLINE |
|
||||
| Truncation acknowledgment deadline | TRUNCATION_ACK_DEADLINE |
|
||||
| Truncation item/content mismatch | TRUNCATION_ACK_IDENTITY_MISMATCH |
|
||||
| Truncation heard-position mismatch | TRUNCATION_ACK_POSITION_MISMATCH |
|
||||
| Unaccepted correlated cancellation error | CANCELLATION_PROVIDER_ERROR |
|
||||
| Correlated truncation error | TRUNCATION_PROVIDER_ERROR |
|
||||
| Unrelated provider error during cleanup | UNRELATED_PROVIDER_ERROR_DURING_SYNC |
|
||||
| Receive transport loss during cleanup | PROVIDER_TRANSPORT_LOST_DURING_SYNC |
|
||||
| Adapter receive/send context capability failure | ADAPTER_CONTEXT_UNSUPPORTED / ADAPTER_CONTEXT_COMMAND_UNSUPPORTED |
|
||||
| Tool continuation before its outputs are sent | TOOL_CONTINUATION_OUTPUT_UNSENT |
|
||||
| Provider queue/send deadline | PROVIDER_COMMAND_QUEUE_DEADLINE / PROVIDER_COMMAND_SEND_DEADLINE |
|
||||
| Client audio/control send deadline | CLIENT_AUDIO_SEND_DEADLINE / CLIENT_CONTROL_SEND_DEADLINE |
|
||||
| Provider send exception | PROVIDER_SEND_FAILED |
|
||||
|
||||
Transport deadlines retain LIVE_TRANSPORT_FAILED; detailed reasons do not change
|
||||
the public error envelope or overwrite the immutable first failure.
|
||||
|
||||
## Executed validation
|
||||
|
||||
New [controlled-clock regressions](../../tests/unit/test_live_context_sync.py)
|
||||
cover captured cancellation errors before/after terminal completion, missing
|
||||
terminal confirmation, exact classifier negatives/profile restrictions, active
|
||||
audio interruption, completed generation with undrained playback, final progress,
|
||||
truncation position, duplicate acknowledgments, late errors after a new response,
|
||||
all four synchronization deadlines, privacy/bounds, transport/protocol categories,
|
||||
failed/incomplete response classification and concurrent runtime close.
|
||||
|
||||
The existing focused suite additionally covers rapid/repeated speech starts,
|
||||
normal/late progress, identity/replay fencing, cancellation send races, unsafe
|
||||
synchronization, authority and bounded resource ownership.
|
||||
[Database incident tests](../../tests/integration/test_voice_session_incident.py)
|
||||
now include LIVE_CONTEXT_SYNC_FAILED in the concurrent-close persistence cases.
|
||||
|
||||
| Command | Actual outcome |
|
||||
| --- | --- |
|
||||
| git diff --check | Passed, including final report changes. Existing Git CRLF conversion warnings remain. |
|
||||
| .venv/Scripts/python -m pytest tests/unit/test_live_context_sync.py -q -p no:cacheprovider --tb=short | Final 25 passed in 3.57 s. |
|
||||
| .venv/Scripts/python -m pytest tests/unit/test_live_context_sync.py tests/unit/test_voice_session_incident.py tests/unit/test_realtime_phase1.py tests/unit/test_realtime_repairs.py tests/unit/test_realtime_remaining.py -q -p no:cacheprovider --tb=short | 313 passed in 31.23 s before four final category regressions were added; final full run below includes them. |
|
||||
| .venv/Scripts/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short | Final 1827 passed, 3 Windows symlink skips, 415 PostgreSQL cases deselected, 25 existing deprecation warnings, 253.84 s. |
|
||||
| .venv/Scripts/python -m pytest tests/integration/test_voice_session_incident.py -m postgres --require-postgres -q -p no:cacheprovider --tb=short | 11 passed in 33.67 s, zero skips. |
|
||||
|
||||
Database acceptance used only task-created container
|
||||
rag-context-sync-20261010-test, loopback port 55439 and dedicated database
|
||||
rag_context_sync_test with Psycopg. TEST_DATABASE_URL was set only in that
|
||||
PowerShell process. Fixtures apply existing immutable migrations to disposable
|
||||
schemas; they do not use operational/public application tables. The verified
|
||||
task-owned container and anonymous test storage were removed after acceptance.
|
||||
No full 415-case PostgreSQL acceptance run was executed for this adapter/runtime
|
||||
change; durable implementation and migrations were not changed.
|
||||
|
||||
Intermediate evidence: captured-provider regressions failed 3/3 before correction.
|
||||
Initial diagnostic tests passed 11/11. An earlier full ordinary run had
|
||||
1812 passed, 3 skips and one unrelated
|
||||
test_real_large_escaped_json_keeps_concurrent_loop_active[10000] failure
|
||||
(max heartbeat gap 144.03 ms against 100 ms). A focused suite ran concurrently
|
||||
during that earlier run. The final full run was not paired with another test suite
|
||||
and passed this unchanged test. The timing failure is recorded, not removed,
|
||||
weakened, or asserted to have a definitively established cause.
|
||||
|
||||
## Frontend and deployment handoff
|
||||
|
||||
Only data/temp frontend copies were found; no accessible authoritative Angular
|
||||
workspace was found. Inspection confirms clearPlayback discards queued/deferred
|
||||
audio, and audio_ended requests a drain. The prior whole-second synthetic test
|
||||
does not establish browser interruption/progress ordering or audio_ref ownership.
|
||||
No frontend file was edited and no deployed frontend repair is claimed. Missing
|
||||
zero progress remains conservatively zero in the backend; real per-reference
|
||||
final reports and timing still need browser acceptance.
|
||||
|
||||
No frontend patch is required by the reproduced backend classifier defect.
|
||||
Browser acceptance must still verify normal turns, interruption during generation,
|
||||
interruption after generation before playback drains, two rapid utterances,
|
||||
manual stop, accurate truncation, stable terminal state and one cleanup request.
|
||||
The authorized provider probe is not microphone/Persian/browser acceptance and
|
||||
did not exercise the corrected application stream against OpenAI.
|
||||
|
||||
Changes are prepared locally. No docker compose build api or docker compose up
|
||||
was executed, no deployed source-match/readiness claim is made, and provider
|
||||
selection was not changed. Deploy only when separately authorized, then verify
|
||||
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
|
||||
attribution or the remaining deployed browser validation.
|
||||
@@ -0,0 +1,146 @@
|
||||
# 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:
|
||||
max_input_buffer_bytes / 48000 seconds (10 by default). 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.
|
||||
@@ -0,0 +1,196 @@
|
||||
# Browser voice termination repair — 2026-10-10
|
||||
|
||||
Local backend corrections are implemented. Historical incident attribution and real
|
||||
browser/provider acceptance remain unverified. No paid provider calls were made.
|
||||
|
||||
## Findings and evidence
|
||||
|
||||
| Finding | Evidence and correction |
|
||||
| --- | --- |
|
||||
| OpenAI terminal item mismatch — confirmed code defect | The unchanged HEAD runtime rejects a synthetic documented sequence: correlated response, assistant transcript delta/completion, audio completion, then an assistant message whose single content part has type `output_audio`. The deployed runtime, lifecycle and OpenAI adapter matched local pre-edit SHA-256 hashes. OpenAI's current [server-event reference](https://developers.openai.com/api/reference/resources/realtime/server-events) describes assistant item content as `output_audio` and shows it in `response.done`. The runtime expected internal `audio`. [RealtimeAdapter.normalize_output_item](../../app/infrastructure/realtime.py) now normalizes only that documented item field; runtime validates the normalized layout in both item and response terminal events. Original wire values still govern event replay hashes. |
|
||||
| Backend failure lost to frontend close — confirmed code defect | `finish_session` originally persisted whichever terminal request acquired the settings lock first; the stream persisted only after provider cleanup. A browser receiving a backend error could therefore persist `user_requested` first. [Lifecycle](../../app/modules/voice/lifecycle.py) now checks the owning runtime's immutable first failure inside the existing scoped transaction when an active session receives user cleanup. The stream attempts terminal persistence before provider cleanup. Already terminal rows remain immutable. |
|
||||
| Manual stop reported as revocation — confirmed code defect | Every `finish_session` notification previously used registry's default `CONTEXT_REVOKED`, including ordinary /close. [Registry](../../app/modules/voice/registry.py) now propagates the actual committed reason; genuine user stop wakes the stream and stops media without manufacturing an authority error. |
|
||||
| Authority masking — suspected mechanism not reproduced | Existing `fail()` already ignores later failures, so secondary `fail("CONTEXT_REVOKED")` calls did not overwrite a previously accepted technical error. [Runtime.check_authority](../../app/modules/voice/runtime.py) now owns classification for exceptions and genuine invalidation. Redundant release/delivery revocation calls were removed; timeout, database failure and saturation retain `SEARCH_TIMEOUT`, `DEPENDENCY_UNAVAILABLE` and `SEARCH_SATURATED`. All authority checks remain fail closed. |
|
||||
| Cleanup ownership/privacy — regression-confirmed defect | Concurrent close waiters now share one runtime shutdown and one bounded provider-close task. Cancellation of a waiter does not cancel shared cleanup. A new test exposed Python 3.14 logging raw provider exception text through a cancelled shield waiter. Owned shutdown tasks now return exceptions privately to their waiters, which re-raise them after shielding; safe diagnostics distinguish timeout from other failure. No deadline was increased. |
|
||||
|
||||
The historical session IDs and post-failure database snapshots do not establish
|
||||
which authority predicate failed or which provider event was rejected at the time.
|
||||
The output type defect reproduces the observed protocol symptom, but cannot be
|
||||
assigned conclusively to session fc99a461 without its failing event/condition.
|
||||
The historical generic cleanup warning did not distinguish timeout from provider
|
||||
exception, so its original cause also remains unknown. Likewise, the close notification defect does not prove why session 90a4ce96 first
|
||||
received CONTEXT_REVOKED.
|
||||
|
||||
Read-only deployed inspection found `VOICE_PROVIDER=openai`,
|
||||
`OPENAI_REALTIME_MODEL=gpt-realtime-mini`, and a configured credential.
|
||||
No credential value was printed, and credential presence is not spending
|
||||
authorization. No operational database acceptance tests, migrations, deployment
|
||||
or operational application session mutations were performed.
|
||||
|
||||
## Diagnostic and contract behavior
|
||||
|
||||
[diagnostics.py](../../app/modules/voice/diagnostics.py) logs application session
|
||||
ID, phase, an allowlisted event type, exception class, stable internal reason and
|
||||
failure code. Unknown event types become `unknown`; arbitrary exception text,
|
||||
provider payloads, audio, transcripts, tool inputs/results, headers and credentials
|
||||
are excluded. Protocol errors such as unsupported output layout, replay conflict,
|
||||
PCM alignment and identity rebound have distinct safe reason codes.
|
||||
Provider-close timeout and exception have `CLEANUP_TIMEOUT` and
|
||||
`CLEANUP_FAILED`; stream cleanup and terminal-persistence failures have their own
|
||||
phases. Public stream/error envelopes are unchanged.
|
||||
|
||||
V04 remains owner-scoped and idempotent. Genuine user stop remains
|
||||
`closed/user_requested/error_code=NULL`. Technical backend failure remains
|
||||
`failed/<causal code>/<causal code>` even if browser cleanup follows it.
|
||||
CONTEXT_REVOKED retains the existing closed-session classification, with
|
||||
`close_reason=CONTEXT_REVOKED` and `error_code=NULL`.
|
||||
A late failure cannot replace a genuinely committed user closure.
|
||||
|
||||
No applied migration, provider secret location, authorization predicate, search
|
||||
scope, input/output PCM format, cancellation/truncation acknowledgement,
|
||||
ordering, correlation or memory limit was changed. Gemini has no OpenAI item
|
||||
normalizer. Unrelated working-tree edits were retained, including concurrent
|
||||
changes outside this repair.
|
||||
|
||||
## Validation
|
||||
|
||||
New regressions:
|
||||
- [Unit incident cases](../../tests/unit/test_voice_session_incident.py):
|
||||
authority categories at startup/release/delivery; genuine revocation;
|
||||
GA OpenAI terminal sequence and replay; text/extra-part/role/identity rejection;
|
||||
diagnostic privacy; normal stop; concurrent close cancellation, exception,
|
||||
timeout and ownership; adapter separation.
|
||||
- [PostgreSQL incident cases](../../tests/integration/test_voice_session_incident.py):
|
||||
backend failure versus concurrent close; repeated close; late failure after
|
||||
genuine user closure; actual authenticated ASGI cleanup with both adapters,
|
||||
provider timeout/exception, durable terminal state and registry/media release.
|
||||
- Existing interruption, native Gemini, OpenAI, authorization, transport and
|
||||
lifecycle regressions were exercised. The existing Gemini oversized-frame
|
||||
case now has a bounded test ID; its 262 KB ID previously prevented pytest
|
||||
setup/teardown on Windows (32,767-character environment limit).
|
||||
|
||||
All PostgreSQL runs used task-created container
|
||||
`rag-voice-incident-20261010-test`, dedicated database
|
||||
`rag_voice_incident_test`, port `127.0.0.1:55438`, and Psycopg.
|
||||
The fixtures validate the dedicated name, create unique disposable schemas,
|
||||
and remove those schemas. They do not fall back to operational/public tables. The interrupted
|
||||
broad run left a disposable schema; the task-owned container and its anonymous
|
||||
test volume were removed after final affected acceptance, including that residue.
|
||||
The operational containers and volumes were left intact.
|
||||
|
||||
| Command | Outcome |
|
||||
| --- | --- |
|
||||
| `git diff --check` | Passed; repeated after final documentation. |
|
||||
| `.venv/Scripts/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short` | Final run: **1795 passed**, 3 Windows symlink skips, 414 PostgreSQL cases deselected, 25 existing deprecation warnings, **265.17 s**. Earlier successful run before the parser additions: 1792 passed, 253.16 s. |
|
||||
| `.venv/Scripts/python -m pytest tests/unit/test_voice_session_incident.py tests/unit/test_gemini_live.py tests/unit/test_realtime_remaining.py tests/unit/test_realtime_repairs.py tests/unit/test_realtime_phase1.py -m "not postgres" -q -p no:cacheprovider --tb=short` | 302 passed in 33.86 s after parser diagnostic refinement. |
|
||||
| `.venv/Scripts/python -m pytest -m postgres --require-postgres -q -p no:cacheprovider --tb=short` | **Incomplete/interrupted**. Progress reached beyond 69%, then stopped producing output while the Python process continued consuming CPU near the unrelated large-review cases in collection order. Interruption returned exit 1 without a final summary or stack. Its exact cause was not established; this run is not full acceptance proof. |
|
||||
| `.venv/Scripts/python -m pytest tests/integration/test_voice_session_incident.py tests/integration/test_phase2_postgres.py -m postgres --require-postgres -q -p no:cacheprovider --tb=short` | Final affected acceptance: **71 passed in 246.24 s**, zero skips. |
|
||||
| `.venv/Scripts/python -m pytest tests/integration/test_voice_session_incident.py -m postgres --require-postgres -q -p no:cacheprovider --tb=short` | **10 passed in 50.50 s**, both provider adapters and all new incident database cases. |
|
||||
| `.venv/Scripts/python -m pytest tests/unit/test_test_environment.py::test_acceptance_mode_requires_database_configuration -q -p no:cacheprovider --tb=short` | 1 passed in 4.92 s; confirms absent TEST_DATABASE_URL fails acceptance. |
|
||||
|
||||
For the database commands above, TEST_DATABASE_URL was set only in their
|
||||
PowerShell process to the dedicated `rag_voice_incident_test` database on
|
||||
port 55438.
|
||||
|
||||
Initial failures were retained as evidence: 288 focused unit passes plus one
|
||||
Python 3.14 shutdown privacy failure, corrected; 70 focused database passes plus
|
||||
one new fixture readiness failure, corrected. The fixture now waits for actual
|
||||
runtime readiness before failure injection and uses a 500 ms synthetic cleanup
|
||||
deadline instead of 50 ms; production deadlines remain unchanged. The first full
|
||||
ordinary run had 1790 passes, three skips, two Windows oversized-ID setup errors
|
||||
and an isolation subprocess failure caused by those same errors.
|
||||
|
||||
The documented output sequence was also executed against HEAD source loaded in
|
||||
memory without replacing working-tree files: its completion assertion failed as
|
||||
expected (one selected case), confirming baseline rejection. The corrected
|
||||
initial incident unit run passed all 26 cases; the final full ordinary run also includes the three added parser cases.
|
||||
|
||||
## Frontend handoff
|
||||
|
||||
No `voice-transport.ts` or `voice-stream.service.ts` was found in the repository
|
||||
or under `D:/raymand/projects`. The delivered JavaScript example is not evidence
|
||||
that the actual Angular implementation is fixed. Update the Angular transport
|
||||
and service together:
|
||||
|
||||
1. Capture immutable session ID and connection generation in every callback.
|
||||
Store cleanup ownership per session, not in a mutable global current-session
|
||||
field.
|
||||
2. Route server error, WebSocket close and manual Stop through the same
|
||||
`cleanupOnce` promise. Assign the promise before the first asynchronous step,
|
||||
so racing callbacks share it. Send at most one POST /close per session.
|
||||
3. Save the first server error before starting cleanup. Keep it as the primary
|
||||
UI reason; socket code 1011 and cleanup HTTP errors must not replace it.
|
||||
A normal server-confirmed manual stop should remain a normal stopped state.
|
||||
4. Stop owned capture/playback/worklet, timers and socket once. Old-generation
|
||||
callbacks may release their own resources and close their own session, but
|
||||
must never clear a new connection, update its UI or send /close for its ID.
|
||||
5. Do not automatically reconnect or create another session in an error/onclose
|
||||
loop. A fresh user connection uses a fresh reservation after reconciliation.
|
||||
|
||||
Example ownership pattern (adapt resource cleanup to the existing frontend):
|
||||
|
||||
```ts
|
||||
const owner = {
|
||||
sessionId, generation,
|
||||
serverError: undefined as VoiceError | undefined,
|
||||
cleanup: undefined as Promise<void> | undefined
|
||||
};
|
||||
|
||||
function cleanupOnce(): Promise<void> {
|
||||
return owner.cleanup ??= Promise.resolve().then(async () => {
|
||||
try { await stopOwnedMedia(owner); }
|
||||
finally { await closeVoiceSession(owner.sessionId); }
|
||||
});
|
||||
}
|
||||
|
||||
function onServerError(error: VoiceError): void {
|
||||
owner.serverError ??= error;
|
||||
if (isCurrent(owner)) showVoiceError(owner.serverError);
|
||||
void cleanupOnce().catch(() => {
|
||||
if (isCurrent(owner) && !owner.serverError) showCleanupFailure();
|
||||
});
|
||||
}
|
||||
// onclose and manual Stop call the same cleanupOnce(); they retain serverError.
|
||||
```
|
||||
|
||||
Verify error -> onclose -> repeated Stop races with spies/network capture:
|
||||
one close request, one resource teardown, original server reason preserved.
|
||||
Reconnect to a fresh session before delivering a stale callback; assert the
|
||||
new session remains active and no request targets its ID. Preserve
|
||||
session_ready admission, PCM24k mono, played-sample progress and interruption
|
||||
handling already required by the frontend integration guide.
|
||||
|
||||
## Deployment and browser acceptance
|
||||
|
||||
Review the scoped repair alongside existing local edits. No migration or new
|
||||
dependency is required. For the current Compose deployment:
|
||||
|
||||
```powershell
|
||||
docker compose build api
|
||||
docker compose up -d --no-deps api
|
||||
curl.exe http://localhost:8080/health/ready
|
||||
```
|
||||
|
||||
Use the configured API port if it differs. Keep one API process and the supported
|
||||
`python -m app.server` entrypoint. Restart ends old voice sessions; start a fresh
|
||||
conversation/session after readiness. The ingestion worker and database require
|
||||
no repair-specific restart. Deployment was not executed.
|
||||
|
||||
With authorized provider spending and real browser hardware:
|
||||
- Login; verify /me and configuration; connect and receive session_ready.
|
||||
- Speak several turns, including a document question and follow-up; verify
|
||||
transcripts, audible PCM playback, evidence and no unexpected terminal error.
|
||||
- Interrupt while speech is playing; verify old playback flushes, cancellation
|
||||
and truncation finish, and the next turn proceeds.
|
||||
- Stop manually; verify one cleanup request, normal stop, and consistent
|
||||
closed/user_requested state.
|
||||
- Exercise a controlled backend failure in a nonproduction session; verify the
|
||||
primary server code survives UI cleanup and polling, close remains idempotent,
|
||||
and provider timeout/exception does not strand media ownership.
|
||||
|
||||
If unexpected termination remains, collect the safe `Voice diagnostic` line
|
||||
for its application session: phase, event type, exception class, reason and
|
||||
code, plus terminal polling state. Do not collect full provider payloads,
|
||||
credentials, audio or transcripts. Actual Angular fixes, historical incident
|
||||
attribution, funded OpenAI/Gemini multi-turn speech, Persian quality and browser
|
||||
hardware/HTTPS acceptance remain outstanding.
|
||||
Reference in New Issue
Block a user