fix(voice): preserve interrupted searches and report used sources

Retain and revalidate interrupted searches, resolve abandoned provider calls, recover invalid source reports privately, and expose only declared sources. Improve Persian delivery and provider event replay capacity. Include regression coverage and contract updates.
This commit is contained in:
amirhosein mazaheri
2026-10-13 14:09:20 +03:30
parent 9cc9f0bc01
commit 18e595ac93
21 changed files with 1346 additions and 60 deletions
@@ -741,3 +741,231 @@ request, all four reviewed frontend files were committed on `feat/backend-change
as **52202c2** (`Add live voice playback diagnostics and sample accounting`).
The frontend working tree is clean. No push was performed. Backend changes
remain uncommitted, and live acceptance remains paused until tomorrow.
## Windows microphone replay and query-name repair — 2026-10-13
Acceptance resumed from the beginning on Windows after the user's Git pull.
Backend is the local `rag-api` container on port 8080; port 8000 belongs to
another project. Local overrides enable numeric traces and retain OpenAI
`gpt-realtime-2.1` / `shimmer`, budget 2048 and speed 1.15. These remain
experimental settings, not production budget acceptance.
- 30-second silence: session `36120006-b089-40eb-92d0-db8555679829` records
32739 ms between ready and first speech; response completed successfully.
- One-minute natural speech: session `93e9b3ff-0885-4b0c-86e1-6acd8a49089c`
succeeded according to the user, but VAD split input into separate turns.
The continuous 60-second single-input boundary remains unverified.
- Continuation replay: `52473ab0-7b6f-42ce-b995-ae6d8acd3472` has one durable
retrieval for the entire call, completed continuation and final playback
progress. Earlier unintended interruption in `9d542f89-12e0-41d0-8ec5-3cc71ffc8713`
followed provider speech-start while the user reported silence and possible
environmental noise. Its noise/echo origin remains unresolved.
- Topic change: `e85e00a2-b54b-472b-8fee-f1a444f1081c` has two successful
retrievals with different topics. User feedback is positive; intentional
close prevents independent confirmation of full final-audio drain.
- Intentional interruption: `29ac4995-821a-48d0-bfcb-866d77bb00f9` stopped old
playback, acknowledged truncation and answered the new topic. The old response
had already completed generation; this is not an active-generation cancellation
test. The user confirms manually closing the new answer.
- Water conditions: the answer states that available land does not guarantee
water supply. Interruption in `4183884f-68b9-4d24-b042-ce925a746d6c` was caused
by actual user speech, confirmed by the user. Provider close timed out and
transport abort succeeded; clean graceful shutdown remains unaccepted.
- Reconnect initially failed while Docker Desktop was unavailable and health
timed out. After an approved Desktop restart, `601ce736-9998-44f8-ab7c-2f75babbeb4a`
closed and `fd36f56d-bbb7-4568-b094-ba6fda880d6a` admitted and answered.
No cleanup diagnostic appeared in that replay.
Missing-price session `fff4acf6-8fb2-4f05-91fb-82f1c222c98b` gave a supported
answer without inventing a price, completed generation and reported final
playback progress. However, the UI user transcript says Mahmoudabad while the
single durable tool query says Baharestan. The returned S1 happens to concern
Mahmoudabad. Correct evidence by chance does not validate the substituted name.
The numeric trace does not prove whether the audio model's interpretation or
its query formulation caused the substitution.
The shared voice policy now explicitly requires preserving user-stated entity
names and document identifiers when shortening queries and asking for clarification
rather than guessing an unclear name. No place-specific substitutions, search
heuristics or corpus changes were added. OpenAI's existing instruction digest
pins this change in newly created sessions; delivery style remains v4.
This is an instruction correction, not deterministic prevention or live proof.
Validation: `.venv/Scripts/python -B -m pytest tests/unit/test_openai_persian_style.py tests/unit/test_voice_evidence_reuse.py tests/unit/test_realtime_phase1.py -m "not postgres" -q -p no:cacheprovider`
passed 74 tests in 17.81 seconds; `git diff --check` passed. No full-suite,
PostgreSQL, budget matrix or exact browser worklet-sample conservation check is
claimed at this checkpoint. The name-preservation microphone replay remains pending.
### Name-preservation microphone replay — 2026-10-13
Latest session `8c487241-f29e-43cc-8695-3837aecd98e9` has one succeeded
durable retrieval with query `شهرک صنعتی محمودآباد قیمت زمین`. The previously
substituted place name is preserved in this replay. Answer generation completed
without output limitation; the final audio reference generated and sent 1087902
bytes and reported 22664 ms playback, leaving 30 bytes below the one-millisecond
reporting resolution. Peak aggregate backlog was 1043838 bytes. No diagnostic
error was observed for this call. Exact worklet sample conservation was not
independently collected. Mark this individual replay passed for query-name
preservation; one prompt-driven success does not establish deterministic or
general entity-preservation reliability. The user reports completing the test.
### Follow-up, conditions and deliberate limitation — 2026-10-13
- `883f649a-701c-48fc-be8e-4ad5f453a9da`: both durable queries preserve
Mahmoudabad (`قیمت زمین شهرک صنعتی محمودآباد`, `قیمت واحد زمین محمودآباد`).
The thousand-square-metre follow-up retains the place and does not invent
an unavailable unit price. It performs fresh retrieval; this does not pass
the no-additional-search continuation criterion. The initial playback is
interrupted at the follow-up speech start. Final full drain is unverified.
- `0814242e-956f-499d-8641-83bc8638e3ba`: search for `مشوق واگذاری زمین دهه فجر 1404`
succeeds. The supplied answer correctly includes the 10% reduction of the cash
down payment, 12 Bahman through end Bahman 1404, and cancellation/auction
exclusions. Response completes without limitation. Final audio generates and
sends 1192126 bytes and reports 24835 ms playback (46 sub-millisecond bytes
remain in integer-ms accounting). This individual factual scenario passes.
- `3169c4a0-5402-4704-a919-5ab1a4d6d31c`: temporarily pin budget 128 for a
deliberate limited-output test. Validated terminal is limited, not completed;
`answer_limited` is sent and the user supplies the displayed limited notice
without duplicated final text. All 184452 generated bytes are sent, final
progress is 3842 ms (36 sub-millisecond bytes). No diagnostic error appears.
Zero durable retrievals were executed: generation stops during the preamble,
so this is limited-state delivery evidence, not grounded-answer quality.
The user closes the call; continued usability after limitation is unverified.
Local candidate budget is restored to 2048 after the scenario. No new code
change is made for this test. Exact browser sample conservation remains unrun.
Combined same-connection acceptance (three repetitions), a single continuous
60-second input, the full answer-budget matrix, and clean graceful provider
shutdown remain outstanding; these isolated scenarios do not complete the plan.
### Selected-source reporting and short acknowledgement - 2026-10-13
User-authorized change: retrieved candidates remain available privately to the
model, while browser sources are emitted only after `report_used_sources`
selects current-turn source labels. Unknown labels, duplicate labels and extra
scope/identity fields are rejected; no report means no candidate-list fallback.
Both provider adapters advertise the internal reporting tool. Original retrieval
identities and metadata are retained; delivery revalidates authorization and
reused knowledge revisions. Metadata reporting creates no retrieval rows.
New sessions use `same-session-evidence-selected-v2` and OpenAI delivery v5.
The optional acknowledgement is only the user's requested short phrase, once per
turn; instruction adherence and actual grounding require microphone validation.
Validation:
- 98 focused provider-free tests passed in 15.84s (reported sources, reuse,
OpenAI style, Gemini and Realtime runtime).
- 22 isolated PostgreSQL tests passed in 71.81s, including source-report delivery
after deactivation, deletion, epoch change and reuse revision change.
- Full provider-free suite: 2005 passed, 3 host-symlink skips, 2 failures.
The ASR repeated-word ordering test timed out; the environment-isolation test
fails because its nested suite encounters the same timeout. Loading the
unchanged HEAD runtime in memory reproduces the individual failure; this is
a pre-existing issue, not accepted as passing or changed in this feature.
- `git diff --check` passed. Task-owned PostgreSQL container was stopped and
automatically removed. Frontend event contract remains compatible; no
frontend change was needed.
Local API rebuilt for microphone verification using the existing diagnostic
2048-token override. Actual provider source-report compliance, spoken phrase,
and audible latency remain pending a fresh voice session.
### Conversational delivery candidate - 2026-10-13
User reports slow, artificial delivery. OpenAI style revision is now
`iranian-persian-conversational-v6`: everyday spoken Iranian Persian, warm
matter-of-fact tone, natural intonation and short clause pauses, with clear
numbers/dates and faithful evidence retained. Local diagnostic override changes
server playback speed from 1.15 to 1.30; the global default stays 1.0 and new
sessions pin the effective speed and instruction digest. This is a candidate
pending microphone comparison, not verified Persian voice quality.
48 focused style/speech-configuration tests passed in 3.58s; the known baseline
ASR ordering failure was explicitly deselected. `git diff --check` passed.
Official reference: https://developers.openai.com/api/docs/guides/voice-prompting
(playback-rate adjustment and model speaking cadence are separate controls).
### Source-report repair after turn changes - 2026-10-13
User reports INVALID_TOOL_ARGUMENTS request dd2be480-9543-4996-860b-4238b4d17973.
Nearby trace session a24ec65a-c992-4eed-87b0-dcd88189ba4c contains an error in
live-turn-4 after rapid turn changes; search occurs in turn 3 before turn 4
supersedes it. Exact report arguments were not logged, so stale labels are a
plausible explanation, not a proven payload attribution. The definite bug was
publishing recoverable citation metadata validation errors as browser errors.
Invalid reports now remain private tool feedback, include current allowed labels
when labels are unknown, and prompt silent retrieval/revalidation before retry.
Authority validation, no invalid citations and no all-candidate fallback remain.
99 focused provider-free tests passed in 13.80s, including invalid-then-valid
report recovery without a browser error, old-turn rejection and source revocation.
No PostgreSQL persistence behavior changed in this follow-up; no new database or
full-suite run is claimed. Numeric report diagnostics added; microphone replay
remains pending a fresh session. Local API rebuild follows this checkpoint.
### Search waiting loop after interruption - 2026-10-13
Session 8a908ca2-855c-4085-9c74-607a5d27ad04: one office-hours search starts at
08:31:06 UTC in turn 2 and finishes with five sources at 08:31:10. Turn 3 starts
at 08:31:07 and turn 4 at 08:31:09, before result completion. Later turns contain
no new search in the collected trace; caller reports repeated claims of waiting.
Inspection finds the interrupted private function call is left without output,
consistent with the waiting loop. Provider reasoning is not independently known.
Repair resolves abandoned OpenAI calls with metadata-only cancellation output
before the next response. Late evidence remains withheld; current authority and
existing audio/terminal barriers remain enforced. Prompt explicitly requires a
fresh call after cancellation when a clear question still needs evidence.
100 focused tests passed in 15.93s, including interrupted slow search followed by
new successful retrieval. Broader interruption/repair/remaining run initially
had 220 passes and five old no-output expectations; tests now distinguish empty
cancellation metadata from prohibited old evidence. All 21 search-interruption
cases passed in 3.95s after updating those expectations. No full-suite or new
PostgreSQL acceptance is claimed for this runtime-only follow-up. Actual provider
replay remains pending a fresh session. See API/implementation amendment.
### Provider event limit incident - 2026-10-13
Session b74383ed-a657-4015-bc9c-d92f3de583db closes at turn 26 after 317265ms.
Diagnostic explicitly reports PROVIDER_EVENT_CAPACITY, occupancy_count=4096,
limit_count=4096, transport_bytes=0, transport_messages=0. This is cumulative
provider replay-ledger exhaustion, not evidence of an overflowing audio queue.
Source reports in this session have zero rejected labels; interrupted-tool
resolution also appears at turn 26. Shutdown still reports CLEANUP_TIMEOUT,
which remains a separate open incident.
Replay-event default and maximum increase to 32768 while retaining all digests
and failing safely at the configured cap. 69 surrounding runtime/repair tests
passed on first run; one new test had the wrong expected provider-protocol error
code, corrected to the existing LIVE_PROVIDER_PROTOCOL_ERROR. All three new
capacity/replay tests then passed in 1.61s. They cover more than 4096 events,
idempotent replay, conflicting replay and finite cap validation/exhaustion.
No full-suite, PostgreSQL or long real-session acceptance is claimed here.
Local API rebuild uses the new default; replay remains pending a fresh session.
### Retained search across repeated follow-ups - 2026-10-13
User authorizes separating playback interruption from retrieval cancellation.
The latest search now has an independent token and original deadline. It is
retained across interrupted turns; explicit reuse awaits and revalidates its
original durable row for the new turn. Identical later search args also coalesce.
New-topic queries cancel/discard retained older searches. Session termination
cancels all independent tokens. Old-turn results remain private. Retained search
refs are omitted from the cancelled-tool list emitted on speech interruption.
Private OpenAI interruption metadata now directs continuation to reuse.
Validation:
- 70 focused unit tests passed in 15.50s (sources, reuse, interruption, style,
Gemini and retained-search cases), followed by an additional deadline case.
- 272 Realtime/repair/remaining/retained-search tests passed in 48.67s, including
repeated waiters not resetting the original search deadline.
- 26 PostgreSQL evidence-reuse/stream-authority tests passed in 104.51s on a
disposable isolated database. Four new runtime cases verify a pending row stays
running after interruption, successful reuse creates only one row, and changed
knowledge revision, inactive document or access epoch blocks publication.
- Tests cover pending/completed results, three repeated follow-ups, direct exact
search-call coalescing, changed topic, current authority loss and session stop.
Older cancellation expectations were updated for the intentional amendment;
unrelated technical failures remain terminal. `git diff --check` passed.
Real provider same-question interpretation and microphone replay remain pending.
Semantic equivalents require explicit reuse by the model; only exact validated
query args are automatically coalesced. No full-suite, frontend or migration run
is claimed at this checkpoint. Earlier baseline ASR failure and graceful provider
shutdown incident remain separate. API local rebuild uses a fresh v5 reservation.