28 KiB
Live Conversation Reliability and Quality Repair Plan
Date: 2026-10-12
Status: Proposed implementation plan; implementation and live acceptance are pending.
1. Findings and agreed product behavior
This plan is based on inspection of the backend, the Angular frontend, governing contracts, targeted tests, and logs from the running rag-api container. The investigation did not change application code. Creating this document does not implement the repairs.
Repositories:
- Backend:
D:\raymand\projects\rag-technical-docs-assistant - Frontend:
D:\raymand\projects\faq_chatbot_frontend
User-confirmed requirements
- Support 60 seconds of continuous user speech.
- Give a concise but complete initial answer. Do not defer essential conditions, exceptions, numbers, or required parts of an answer until the user asks again.
- “Continue” should expand the current topic using existing evidence when that evidence remains valid and sufficient. It must not automatically trigger another retrieval.
- Evaluate follow-ups and continuation on the same live connection.
- Do not use automatic chains of responses as the default way to work around generation limits.
Findings
| # | Reported issue | Investigation result |
|---|---|---|
| 1 | Session closes after more than 10 seconds of speech | Confirmed in session b4273838…: UNCOMMITTED_SPEECH_BYTES, prospective occupancy 480192 bytes against a 480000-byte limit, with an empty transport queue. This is the uncommitted-speech limit, not transport queue exhaustion. |
| 2 | Choppy model audio | Observed behavior; the complete cause remains unproven. The worklet waits for an 80 ms prebuffer when restarting after an underrun. Its effect must be measured against actual arrival timing. |
| 3 | Answer ends mid-sentence | The default max_output_tokens=256 is confirmed. A token limit does not guarantee a natural sentence ending. Attribution of each incident requires that response's terminal event. |
| 4 | Audio ends before the displayed text | The complete cause remains unproven. The frontend does not declare or reconcile the existing sent_bytes field on audio_ended. Generated text and confirmed playback must be tracked separately. |
| 5 | UI returns to listening too early | Confirmed. onPlaybackIdle can finish the turn after 700 ms. The turnEnded branch can also finish without requiring the audio stream to be sealed. |
| 6 | Incomplete support for limited answers | Confirmed. The actual frontend lacks limited transcript status and answer_limited handling. |
| 7 | Repeated answer text | Confirmed reconciliation defect. Only completed explicitly replaces accumulated text. A final limited snapshot can be appended instead. |
| 8 | Session closes when cancelling an already-ended response | Confirmed in c9abc00f…. The error signature matched, but the adapter only accepts the race for gpt-realtime-mini/shimmer, not the reported gpt-realtime-2.1/shimmer profile. |
| 9 | Cancellation acknowledgement deadline expires | Independently confirmed in 751070c1… as CANCELLATION_ACK_DEADLINE. Fixing issue 8 does not establish that this issue is fixed. |
| 10 | Unrelated response to “continue” | Current instructions and the implementation guide require fresh retrieval for document follow-ups. The requested behavior requires an explicit contract change as well as correct topic continuity. The reported relevance failure still needs same-connection reproduction. |
| 11 | Output backlog overflows on longer answers | The current aggregate limit represents 30 seconds of outstanding audio. Lowering the token budget is not a duration or capacity guarantee. The inspected logs also contain a distinct playback-progress stall; overflow reasons must not be conflated. |
| 12 | Cleanup timeout after failure | Confirmed after the primary errors in the reported sessions. The implementation has nested close deadlines and waits for task termination. Cleanup timeout is a secondary failure, not the original cause of those disconnects. |
Additional log evidence: session 9be88836… recorded PLAYBACK_PROGRESS_STALL with sent_bytes=364800, played_ms=7599, and 48 outstanding bytes after 5001 ms. Preserve the existing 24 kHz playback accounting repair and do not present this historical stall as proof that the generated-output backlog is still overflowing.
Main implementation references
- Backend voice runtime: input accounting, deadlines, output delivery, cancellation, playback retirement, and shutdown.
- OpenAI adapter: provider setup, terminal classification, and no-active-response classification.
- Frontend
src/app/services/voice-stream/voice-stream.service.ts: playback lifecycle and transcript reconciliation. - Frontend
src/app/services/voice-stream/voice-stream.types.ts: application event types. - Frontend
public/assets/worklets/pcm-playback.worklet.js: bounded playback, resampling, progress, and tail handling. - Reference map, API catalog, and implementation guide: governing contracts and workflow rules.
The official OpenAI reference states that cancelling when no response is active returns an error without inherently invalidating the provider session. It also documents faster-than-realtime audio generation and acknowledgement through conversation.item.truncated. This does not independently prove a particular model profile's error signature; the incident evidence supplies that profile-specific observation. Official Realtime client events
Checks already executed during investigation
- 119 targeted backend tests passed: input accounting, output limits, context synchronization, session incidents, and old-turn search cancellation.
- 44 frontend tests passed: voice service and actual playback worklet.
git diff --checkpassed in both repositories.- No real microphone/provider acceptance, PostgreSQL acceptance, or full regression suite was run during this investigation.
- Existing working-tree changes and the two earlier repairs were preserved.
Backend command:
.venv/Scripts/python -m pytest tests/unit/test_voice_input_accounting.py tests/unit/test_openai_output_limit.py tests/unit/test_live_context_sync.py tests/unit/test_voice_session_incident.py tests/unit/test_voice_search_interruption.py -m "not postgres" -q -p no:cacheprovider
Frontend command:
npm.cmd test -- --watch=false --include=src/app/services/voice-stream/voice-stream.service.spec.ts --include=src/app/services/voice-stream/pcm-playback.worklet.spec.ts
Passing the existing tests does not resolve the incidents. Some existing tests explicitly assert that the 10-second limit closes the session.
2. Execution order and shared rules
Implementation sequence
- Add bounded numeric diagnostics to distinguish audio-path failures.
- Implement confirmed backend repairs for 1, 8, and 12.
- Implement coordinated frontend repairs for 5, 6, and 7.
- Reproduce and correct 2, 4, and 9 using correlated evidence.
- Coordinate output capacity and answer-quality repairs for 11 and 3.
- Implement the evidence-reuse contract and continuation behavior for 10.
- Complete browser and provider acceptance on the same connection.
Overlapping items should share one implementation. Separate prompts define responsibilities; they are not instructions to create competing state machines or duplicate fixes.
Diagnostic prerequisite
Extend existing diagnostics; do not introduce another monitoring service or dependency.
For each application session, turn, and audio reference, capture:
- Relative timing of provider chunk receipt, backend send, browser receipt, and worklet consumption.
- Generated, queued, sent, received, consumed, and discarded amounts, with a reason for discards.
- Underrun count and duration while generation remains open.
- Audio end, terminal response status, limitation reason, and every clear/flush reason.
- Cancellation enqueue, dispatch, send completion, terminal receipt, and truncation acknowledgement timing.
Log only necessary application identifiers and bounded numeric values. Do not log audio, document text, credentials, or complete provider payloads. Browser and backend monotonic clocks are independent: correlate by identity and ordering rather than subtracting their timestamps directly.
Shared prefix for every implementation prompt
Attach this prefix to each numbered prompt below:
Backend:
D:\raymand\projects\rag-technical-docs-assistant
Frontend:
D:\raymand\projects\faq_chatbot_frontend
Read AGENTS.md, docs/agent-reference-map.md, and applicable nested instructions.
Use the current working tree as the baseline and preserve existing changes.
Implement only the requested part and add regression coverage for its root cause.
Preserve the earlier old-turn search cancellation and 24 kHz playback repairs.
Identity, authorization scope, access_epoch, and document eligibility must remain
backend-owned and revalidated.
Change contracts only for product changes explicitly described in this plan.
Do not equate synthetic test success with browser or real-provider acceptance.
Report the cause, changes, executed checks, and remaining acceptance obligations.
3. Repairs and implementation prompts
1. Support 60 seconds of continuous speech
Severity: High. Cause confirmed.
Separate the supported speech interval from transport memory occupancy. Keep the transport queue at 96000 bytes. Changing only 480000 is insufficient because the current speech deadline is derived from that byte limit.
The product target is 60 seconds of actual speech. Allow up to four additional seconds for the maximum configured OpenAI prefix/silence padding: 64 seconds / 3072000 bytes for the detected interval, and a fixed 65-second speech-stop deadline. These are proposed engineering bounds, not provider guarantees. The user-facing promise remains 60 seconds.
Implementation prompt:
Implement issue 1 in RuntimeSettings, input accounting, and check_deadlines.
Support 60 seconds of actual continuous speech. Set the detected-interval bound
to 3072000 bytes and the fixed speech-stop deadline to 65 seconds.
Keep that deadline independent of transport capacity; duplicate starts must not
extend it.
Preserve the 96000-byte transport queue, frame bounds, absolute offsets, and
commit fencing. Do not invent commits, speech stops, or provider consumption.
Align the contract, configuration example, and obsolete limit assertions.
Test 10/30/60-second speech with padding, 30-second silence, delayed starts,
missing stop, missing commit, transport saturation, and genuine limit exhaustion.
Exceeding the new hard bound must still produce a bounded, explicit failure.
2. Diagnose and repair choppy model audio
Severity: High. Complete cause requires measurement.
Identify whether each gap originates at the provider, backend delivery, or browser playback. Increasing the prebuffer without evidence may only add latency.
Implementation prompt:
Reproduce issue 2 with a numeric provider-to-runtime-to-browser-to-worklet trace.
For each gap, identify the first stage that lacked data or delivered it late.
Exercise worklet rates of 24000, 44100, and 48000 Hz and restart after underrun.
Compare prebuffer values of 80/120/160/240 ms against the same fixed trace.
Select the smallest value that passes the acceptance trace without
buffer-induced underruns, and report its startup-latency cost.
Do not claim that extra buffering fixes a real provider generation pause.
Preserve the two-second queue bound, progress based only on consumed samples,
and end-of-audio tail flushing.
Cover bursts, jitter, gaps over 700 ms, and tails smaller than the prebuffer.
3. Prevent ordinary answers from ending mid-sentence
Severity: High. Confirmed contributing configuration; per-incident attribution requires terminal evidence.
A concise answer must still answer the question completely. Asking the user to repeatedly say “continue” must not compensate for an inadequate generation budget.
Implementation prompt:
Implement issue 3 together with the capacity outcome of issue 11.
Change delivery instructions to require a concise but complete answer in the
current turn. Preserve essential quantities, conditions, exceptions, and all
necessary parts of the question.
Do not treat 256 tokens as a natural-ending guarantee or raise the budget before
capacity is addressed.
In acceptance, compare 512/1024/2048/4096-token budgets using the fixed question
set. Select the smallest budget that passes all quality and capacity criteria.
Cover both tool generation and the spoken answer.
Classify limited output only from a validated terminal event; never relabel it
completed.
Update style revision, instruction digest, and newly created session profiles.
If no candidate passes, block release of this repair and record the result.
Automatic response chaining or omitting essential facts is not an accepted
workaround in this phase.
4. Locate audio lost before the displayed answer ends
Severity: High. Complete cause remains open.
Generated transcript text and confirmed playback are different facts. Reconcile counters to determine where audio is missing.
Implementation prompt:
Investigate issue 4 by reconciling generated, sent, received, enqueued, consumed,
and discarded audio.
Add sent_bytes to the frontend audio_ended type and processing. Compare it with
the received PCM total for that audio_ref; it does not prove playback.
On normal completion, prove complete consumption and tail draining with actual
worklet sample counters.
For interruption, record discarded audio separately and never credit it as played.
Record a reason for every clearPlayback and flushPlayback.
Test final transcript before final audio, final audio before transcript, limited
responses, interruption during the tail, 44.1/48 kHz rates, and send failure.
Do not invent word-level audio alignment or a transcript of exactly what was heard.
Fix the first stage that produces an unauthorized accounting discrepancy.
5. Stop premature transitions to listening
Severity: High. Confirmed code defect.
Normal playback completion requires the matching audio reference to be explicitly sealed and its playback to drain. A temporarily empty queue is insufficient.
Implementation prompt:
Implement issue 5 in VoiceStreamService.
Remove settleMs=700 as a normal answer-completion heuristic.
Associate audio sealing and playback drain state with the relevant audio_ref
and turn_ref.
Idle while audio is still open must not trigger LISTENING or finalize text.
A completed transcript alone is also insufficient to finish audio.
The matching audio_ended plus actual drain may finish playback.
Missing transcript must not block already-completed playback or cause fabricated
text completion.
Stale and duplicate events must not reset counters or change a newer response.
Test 701 ms and two-second gaps during generation, early completed transcript,
late audio_ended, drain before end, and interruption.
6. Support limited answers throughout the frontend
Severity: Medium. Confirmed code defect.
Implementation prompt:
Implement issue 6 in event types, VoiceStreamService, and transcript rendering.
Add limited to TranscriptStatus and answer_limited to VoiceServerEvent with
turn_ref and reason=output_token_limit.
Attach the limited state to the correct message and show a Persian notice
meaning "The answer was left incomplete."
Neither answer_limited nor transcript[limited] may clear playback or close the
session. Drain all already-generated audio normally.
Continuation requires a genuine user request and follows issue 10.
Test both event orders, absent transcript, duplicates, limited arriving after
interruption, and buffered audio still awaiting playback.
7. Eliminate duplicated final transcript text
Severity: Medium. Confirmed code defect.
Implementation prompt:
Implement issue 7 in transcript reconciliation.
Treat completed and limited final text as the final snapshot for that message.
Replace provisional text even when the final text does not start with the
previous accumulated value.
After finalization, late partials must not reopen or append to the message.
Repeated final events must be idempotent; interruption takes precedence over
late updates.
Coordinate this change with the limited-state handling in issue 6.
Test final-word corrections, spacing and Persian half-space differences,
repeated source phrases, duplicate limited events, partial-after-final, and
isolation between two turns.
Do not remove repeated phrases using regex or linguistic guesses.
8. Accept the verified already-ended cancellation race
Severity: High. Confirmed by code and incident logs.
Implementation prompt:
Implement issue 8 in RealtimeAdapter.is_no_active.
Extend the narrow verified-profile handling to gpt-realtime-2.1/shimmer for:
type=invalid_request_error,
code=response_cancel_not_active,
param=null.
Do not allow every model or every provider error.
Preserve runtime correlation of error.event_id to the exact cancellation intent
and response.
This error is neither terminal confirmation nor truncation acknowledgement, and
does not authorize the next response.
Test terminal before and after the error, wrong event_id, unsupported profile,
different error, duplicates, and outstanding unheard audio.
Update the profile acceptance evidence and applicable contract documentation.
9. Investigate cancellation acknowledgement deadline failures
Severity: High. Incident confirmed; delay source unresolved.
Keep the current five-second deadline initially. Distinguish internal processing delays from a genuinely missing provider terminal event.
Implementation prompt:
Investigate issue 9 independently of issue 8.
Record cancellation enqueue, dispatch, send completion, response.done receipt,
and response.done processing times.
Reproduce under audio backlog, slow sends, and tool load. Check whether terminal
processing is blocked behind internal work or a long-held lock.
Start the deadline at the single real dispatch; duplicates must not extend it.
If internal blocking is found, fix that wait or scheduling path while preserving
required provider ordering and terminal validation.
Test terminal at 4.9 seconds, no terminal after five seconds, no-active without
terminal, early terminal, and three rapid interruptions.
A genuinely missing terminal must still fail safely.
Increasing timeout alone or assuming cancellation succeeded is not a repair.
10. Continue the same topic without unnecessary retrieval
Severity: High for answer quality. Explicit product and contract change.
Retain the most recent valid evidence bundle for the current topic within the live session. Do not use prior assistant claims as evidence or build a general-purpose cache.
Add an internal reuse_last_evidence tool with no scope or identity arguments. The backend selects and revalidates the reusable evidence. Canonical search remains responsible for new topics or insufficient evidence.
Implementation prompt:
Implement issue 10 with an explicit amendment to the fresh-retrieval-for-every-
follow-up rule.
Retain the latest successful evidence bundle for the current topic in the same
session's memory. Include the real tool execution reference, query, and
document/chunk/source references.
Add an internal reuse_last_evidence tool with an empty argument schema.
Before reuse, the backend must recheck owner, session, access_epoch,
knowledge_revision, and every source document's eligibility.
An unchanged epoch alone is insufficient: a changed knowledge revision also
invalidates reuse.
Continue the same topic with sufficient valid evidence without a new embedding
or retrieval call.
Use fresh search for a new topic or insufficient evidence; ask for clarification
when the intended reference is ambiguous.
Handle revocation using the existing invalid-session contract, not a hidden
replacement search.
Attach sources to the new turn using their real identities. Never record a
retrieval that did not happen.
Prior assistant prose, unheard generated prose, and cancelled tool results are
not valid evidence.
Clear the bundle when the session ends. Add no durable conversation history or
cross-session cache.
Require PostgreSQL tests for selection changes, deletion/deactivation, and
access revocation.
In real same-connection acceptance, "continue" must remain on topic and must not
increase the retrieval execution count when valid sufficient evidence exists.
11. Handle longer output without confusing backlog and playback stalls
Severity: High. Known capacity boundary; complete repair is unproven.
Preserve three independent limits:
| Layer | Planned behavior |
|---|---|
| Browser and transport queues | Keep the existing two-second bound. |
| Playback-based delivery credit | Keep 72000 bytes. |
| Generated, outstanding audio reservoir | For the OpenAI profile under repair, test a finite 120-second / 5760000-byte aggregate bound. |
The proposed reservoir increase is an explicit capacity change, not a guarantee against unlimited output. Accept it only together with measured answer budgets and memory behavior. Do not silently change Gemini settings without separate acceptance.
Implementation prompt:
Implement issue 11 while distinguishing OUTPUT_BACKLOG_CAPACITY from
PLAYBACK_PROGRESS_STALL.
For the OpenAI profile in this repair, set aggregate output backlog capacity to
5760000 bytes.
Account for adapter/runtime data, reservations, credit, and unresolved audio
references in the same aggregate budget.
Keep transport, frame, browser queue, and delivery-credit limits unchanged.
Explicitly update the existing 30-second contract and configuration validation
for this profile.
Do not pause provider control reception to throttle audio generation; doing so
can trap cancellation acknowledgements behind audio.
Test bursts exceeding 30 seconds, multiple references, healthy playback, genuine
playback stalls, new-bound exhaustion, and cancellation under load.
Record peak memory and backlog alongside issue 3's token-budget measurements.
Acceptance requires complete benchmark answers and peak backlog below 80 percent
of the configured bound.
Silent audio drops, fabricated playback progress, and unbounded memory are
prohibited.
12. Bound cleanup and preserve the primary failure
Severity: Medium. Confirmed secondary failure.
The objective is reliable resource release and accurate reporting of the original failure, not suppressing timeout messages.
Implementation prompt:
Implement issue 12 across runtime.close, provider close, and the Live route's
finally path.
Keep a single shared shutdown owner and compatible bounded budgets for task
termination and transport closure.
Do not allow an unbounded gather or let an outer timeout abandon shared cleanup.
After graceful-close expiry, use the existing transport's abort capability and
record its result separately. Extend the adapter interface only as needed.
Preserve the primary error, such as LIVE_BUFFER_OVERFLOW or
LIVE_CONTEXT_SYNC_FAILED.
Ensure terminal persistence is attempted and registry/ACTIVE_MEDIA_SESSIONS
entries are released independently of graceful-close success. The frontend must
stop the microphone and close its socket on terminal failure.
Test an unresponsive provider, blocked send, simultaneous Stop/disconnect/error,
cancelled close waiter, and repeated close calls.
Do not report incomplete cleanup as success or create competing cleanup owners.
4. Contract changes and acceptance
Interface and contract changes
- Support a 60-second speech target with explicit detection padding and an independent deadline.
- Support
answer_limitedandtranscript.status=limitedin the actual frontend. - Add the already-contracted
sent_bytesfield to frontend event typing and validation. - Derive playback completion from
audio_endedplus real sample consumption, not an idle timer. - Introduce internal
reuse_last_evidenceand the narrowly scoped exception allowing continuation from valid existing evidence. - Record the OpenAI output capacity and measured generation budget in applicable configuration/contracts; pin generation settings in new profiles and never rewrite existing reservations.
- No new public REST endpoint, document-content versioning, or database migration is required by this design.
Synthetic and regression acceptance
Cover:
- 10-, 30-, and 60-second speech, prolonged silence, and actual hard-bound exhaustion.
- Valid orderings of transcript, terminal response,
audio_ended, and playback drain. - 24, 44.1, and 48 kHz playback; tails, jitter, and interruptions.
- Natural completion, output limitation, provider error, and network loss.
- Cancellation of active, completed, and superseded responses; missing terminal and missing truncation acknowledgements.
- Both earlier repairs using their existing regression tests.
- Backend provider-free suite and frontend tests/build.
- PostgreSQL evidence-reuse cases against an isolated database using
--require-postgres. Skips do not count as acceptance.
Backend broad regression command:
.venv/Scripts/python -m pytest -m "not postgres"
Run the affected PostgreSQL tests with -m postgres --require-postgres and an isolated TEST_DATABASE_URL. Missing configuration must fail database acceptance.
Frontend checks:
npm.cmd test -- --watch=false
npm.cmd run build
Real answer-quality acceptance
Prepare a fixed set of 20 questions covering simple facts, multi-part questions, numbers/dates, conditions/exceptions, insufficient evidence, ambiguity, and follow-ups. Define the essential facts for each answer before evaluating generation budgets. Evaluate each candidate budget with three repetitions.
Select the smallest candidate that satisfies all of the following:
- Answers finish naturally and include every essential fact.
- With sufficient evidence, the user is not forced to say “continue” to receive an essential part of the answer.
- Deliberately limited cases show the correct status and play all admitted audio.
- There is no unexplained audio sample loss.
- Healthy scenarios produce no overflow or context synchronization failure.
- Peak outstanding audio remains below 80 percent of the selected reservoir bound.
These are acceptance requirements, not guarantees inferred from token counts or unit tests.
Same-connection conversation acceptance
Repeat this sequence at least three times without reconnecting within a sequence:
- Remain silent for 30 seconds.
- Ask a question using 60 seconds of continuous speech.
- Hear the complete answer.
- Say “continue” about the same topic; confirm no additional retrieval execution when existing evidence is valid and sufficient.
- Change topics; confirm fresh retrieval.
- Interrupt the assistant and continue after confirmed context cleanup.
- Ask a question requiring conditions and exceptions.
- End the session and verify resource release.
Record application session/turn references, selected model/voice/profile, terminal reasons, retrieval counts, audio accounting, backlog peaks, and the observed outcome for each run.
Rollout and completion reporting
Deploy the frontend's compatible handling of existing events first. Then accept backend changes and the revised response profile with newly created sessions. Do not rewrite pinned reservations or use reconnection to hide a same-connection failure.
Track each issue separately as:
- Code repair implemented.
- Synthetic/regression checks passed.
- Real browser/provider acceptance passed.
Keep issues 2, 4, and 9 open until their cause is traced and the relevant reproduction passes. Do not close issue 11 merely because a limit was increased or short tests passed. If no budget/capacity candidate meets the defined quality and safety criteria, retain the failed acceptance evidence and do not claim the repair is complete.