Files
rag-technical-docs-assistant/docs/guides/voice-session-termination-repair.md
T
amirhosein mazaheri a769196bfa 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.
2026-10-10 17:41:11 +03:30

14 KiB

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 describes assistant item content as output_audio and shows it in response.done. The runtime expected internal audio. RealtimeAdapter.normalize_output_item 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 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 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 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 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: 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: 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):

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:

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.