feat(voice): support evidence reuse, 120s output capacity, and input ASR coalescing

- Add internal reuse_last_evidence tool for continuing existing topic without repeated retrieval
- Expand OpenAI output capacity to 120s / 5,760,000 bytes and add delivery fairness
- Coalesce adjacent user ASR transcript deltas to prevent client control queue overflow
- Add server-side OPENAI_REALTIME_SPEED configuration and update style to v4
- Add extensive unit and integration regressions for evidence reuse, capacity, and fairness
This commit is contained in:
11linear11
2026-10-12 17:57:27 -04:00
parent 9e6864ae2a
commit 111710c47c
33 changed files with 1189 additions and 55 deletions
+6
View File
@@ -1,5 +1,11 @@
# Phase 1 agent reference map
Live repair diagnostics (2026-10-12): see [numeric trace guide](guides/live-conversation-traces.md)
for the opt-in runtime timeline, frontend consumed/discarded sample accounting,
and the provider-free fixed worklet trace command. Current Linux checks use
`.venv/bin/python`; historical `.venv/Scripts/python` commands below refer to
the Windows environment. Traces and synthetic checks do not close live incidents.
Current voice configuration (2026-10-09): **VOICE_PROVIDER=gemini|openai selects
one backend adapter. Gemini remains the temporary default because an OpenAI
Realtime voice key is unavailable.** Reservation, authenticated stream and
+65 -1
View File
@@ -308,6 +308,14 @@ acknowledgment. Gemini instructions remain unchanged. Voice changes require fres
sessions; candidate voices remain unverified until listening/interruption acceptance.
See [Phase 2 handoff](../guides/openai-persian-delivery-phase2.md).
OpenAI playback-speed configuration is server-only: `OPENAI_REALTIME_SPEED`
(default 1.0, finite range 0.25..1.5) is frozen as
`execution_profile.audio_output_speed` and acknowledged as `audio.output.speed`
before readiness. Changing it requires a new reservation; replay retains the
original snapshot and old/mismatched snapshots fail stream admission. PCM remains
24 kHz and playback credit uses actual provider-generated sample duration.
Gemini profiles and public events are unchanged.
OpenAI Phase 3 freezes optional `execution_profile.reasoning`: null when omitted,
or `{"effort":"low"}` / `{"effort":"medium"}` for the explicitly supported
`gpt-realtime-2.1` and `gpt-realtime-2.1-mini` candidates. Unsupported explicit
@@ -549,6 +557,32 @@ Locators use existing `location.page/section`. DOCX and image use page null, wit
Deduplicate by parent session/turn plus provider call ID and normalized argument hash. Same running call waits; same completed call replays only after fresh eligibility/epoch checks; changed payload conflicts. Cancelled/closed/stale-parent results are not sent back to generate a new answer. No tool request becomes a public REST upload/search endpoint. The MVP persists voice tool_calls independently of deferred text turns/messages/citations. Cancelled work is terminal failed with a cancellation reason and cannot be replayed to resume speech.
### 7.3 Internal continuation tool — `reuse_last_evidence`
The 2026-10-12 Live repair amendment permits an unambiguous same-topic
continuation from the latest successful, delivered evidence bundle in the same
connection. The model supplies exactly `{}`; identity, scope, session and source
selection remain backend-owned. Prior assistant prose is never evidence. New
topics or insufficient evidence require canonical `search_knowledge`; ambiguous
references require clarification. Automatic response chaining remains excluded.
Before reuse and again before delivery/continuation, revalidate the owner/auth
session, active Live session, access epoch, knowledge revision, and each original
document/chunk's ready/active/undeleted/unpurged eligibility. A selection addition
can change knowledge revision without changing access epoch and still invalidates
reuse. Revocation follows the invalid-session contract; it never triggers a
hidden replacement search. Without a reusable bundle, return `no_evidence` with
`warnings:["fresh_search_required"]`, allowing an explicit model search.
Attach evidence to the new turn using real document/chunk identities and
turn-local source labels. Its `sources.tool_call_id` identifies the original
retrieval; reuse creates no `tool_calls` row or embedding/retrieval execution.
Revalidate the original saved result before every delivery. Interrupted/cancelled
tool results are excluded. Fresh search replaces the topic bundle; failure and
session termination clear it. No durable conversation history or cross-session
cache is introduced. New reservations pin `evidence_policy_revision` and the
effective instruction profile; existing reservations are never rewritten.
## 8. Health
H01: 200 `{"status":"ok"}` when the process is alive. H02: 200 `{"status":"ready","ingestion":"available"}` or degraded ingestion marker if worker heartbeat is stale; 503 `{"status":"not_ready"}` for required DB/schema/storage failure. Health responses never disclose connection strings or provider keys. Provider outages surface in relevant business operations, not liveness.
@@ -638,7 +672,37 @@ it. New execution_profile snapshots freeze max_output_tokens and revised OpenAI
instruction revision/digest. Missing/mismatched old snapshots fail existing stream
admission without rewriting reservation identities or profiles. Gemini is unchanged.
This budget includes tool calls and is not a measured PCM-duration guarantee.
All existing reservoir, credit, transport/browser and timeout bounds remain.
Credit, transport/browser and timeout bounds remain. The OpenAI reservoir is
amended below.
### OpenAI output-capacity amendment (2026-10-12)
For the selected OpenAI Live repair profile, aggregate undrained backlog defaults
to **5760000 bytes / 120 seconds**, with a finite 664 packed-slab accounting cap
(600 full slabs plus partial slabs across at most 64 unretired references).
`LIVE_MAX_OUTPUT_BACKLOG_BYTES` may select a smaller aligned bound. Values above
5760000 fail configuration validation. Gemini retains its 1440000-byte / 512-slab
baseline and rejects the OpenAI capacity profile before opening its provider.
The earlier 30-second examples and memory total describe the baseline profile;
this amendment supersedes only their OpenAI reservoir/slab values.
New OpenAI reservation snapshots freeze `output_backlog_bytes` and
`output_slab_limit`; replay never rewrites them and missing/mismatched profiles
fail admission. Aggregate accounting includes runtime PCM, adapter PCM,
reservations, delivery credit and all unresolved references. Both byte and slab
admission checks run before decoding/extending PCM. Exhaustion remains
`LIVE_BUFFER_OVERFLOW` with `OUTPUT_BACKLOG_CAPACITY` or `OUTPUT_SLAB_CAPACITY`;
a genuine missing-playback deadline remains `PLAYBACK_PROGRESS_STALL`.
Frame size 9600, transport/browser queues 96000, delivery credit 72000, deadlines
and control reception remain unchanged. No provider receive throttling, silent
audio discard, fabricated progress or automatic response chaining is added.
Raw/scratch/copy/metadata payload allowance becomes 6380288 bytes per OpenAI
session under the existing scratch/copy/metadata caps; Python/process overhead
must be measured separately. This finite capacity amendment does not select an
answer token budget or establish real-provider quality/memory acceptance.
### Validated limited-answer behavior
A validated OpenAI response.done with status=incomplete,
status_details.type=incomplete and reason=max_output_tokens, no error, and matching
@@ -336,6 +336,12 @@ UNIQUE(conversation_id,sequence_no), UNIQUE(turn_id,role). Both roles may exist
UNIQUE(live_session_id,external_call_id); scoped FK to live_sessions.
CHECK terminal iff completed_at is non-null; CHECK tool_name='search_knowledge'.
The 2026-10-12 continuation amendment adds no table or migration: internal
`reuse_last_evidence` revalidates and references the original successful retrieval
row without inserting a new `tool_calls` row. It requires both its saved access
epoch and knowledge revision to match current settings, and rechecks every
document/chunk. New turn source events retain that retrieval's public reference;
session-local reuse state is discarded on session termination.
No turn_id or FK to deferred turns/messages/citations is required in this
migration. A later text extension must explicitly add its parent/constraint
design; it is not implicit scope for this MVP.
@@ -491,7 +497,11 @@ See [Phase 3 handoff](../guides/realtime-agent-phase3-handoff.md).
### OpenAI generation-limit profile amendment (2026-10-12)
New OpenAI live_sessions.execution_profile JSON freezes max_output_tokens (default
256) alongside audio_input, reasoning, style_revision and instruction digest.
256) alongside audio_input, audio_output_speed (default 1.0), reasoning,
style_revision and instruction digest. The OpenAI repair profile additionally
freezes `output_backlog_bytes` (default 5760000) and `output_slab_limit` (664).
Gemini retains its existing capacity/profile fields. These are JSON profile
amendments; no schema migration or existing-row backfill is permitted.
Existing reservation profiles/request hashes are immutable: replay returns the
original identity, and missing/mismatched profile fields reject stream admission.
No schema/migration or session status enum changes. A limited audio answer keeps
@@ -238,7 +238,7 @@ Use the SAME search service and fixed compatible embedding profile as the intern
States: `creating → connecting → connected → closed`; any nonterminal state may fail/close. Adapter-confirmed setup defines connected, not client assertions. Use deadlines, bounded audio buffers and TTL; provider calls occur outside database transactions. Restart marks previous nonterminal sessions failed and attempts cleanup.
Follow-up questions resolve the last unambiguous document/article, but retrieve fresh evidence. New topics clear old anchors; ambiguous references prompt clarification. Missing/conflicting support is disclosed; tool/provider failure is a technical error. On actual interruption flush playback, mark affected unfinished assistant output partial/interrupted, cancel response-specific work and discard late assistant/tool results. A normally completed exchange stays completed; delayed authorized user transcripts retain their original turn. Logout/expiry/removal close sessions. Reconnect requires reconciliation and a new session; provider context recovery is not promised.
Follow-up questions resolve the last unambiguous document/article. The 2026-10-12 repair amendment (API 7.3) permits `reuse_last_evidence({})` for same-topic continuation with sufficient successful, delivered session-local evidence. Recheck owner/session, access epoch, knowledge revision and every source document before reuse and each delivery; unchanged epoch alone is insufficient. Reuse retains the original retrieval reference and creates no retrieval record. New topics or insufficient support require fresh canonical search; missing bundles return `fresh_search_required`, while revoked context closes via the existing invalid-session contract. Clear bundles on interrupted work, fresh search, failure and session end. No cross-session cache or durable history is added. New topics clear old anchors; ambiguous references prompt clarification. Missing/conflicting support is disclosed; tool/provider failure is a technical error. On actual interruption flush playback, mark affected unfinished assistant output partial/interrupted, cancel response-specific work and discard late assistant/tool results. A normally completed exchange stays completed; delayed authorized user transcripts retain their original turn. Logout/expiry/removal close sessions. Reconnect requires reconciliation and a new session; provider context recovery is not promised.
Apply the frozen [API Section 7.1](RAG-Phase1-API-Catalog.md) lifecycle/bounds before runtime acceptance: retain refs through queued playback, accept final reports within the bounded interruption window, await private cleanup acknowledgement before continuation, and close on synchronization/overflow failures. The [Phase 0 report](../guides/realtime-agent-phase0.md) records actual whisper-1/fa configuration, retirement dates and read-only calibration preflight; no automatic provider migration. Use both VAD flags false and backend-only targeted cancellation; a narrowly correlated no-active-response race is benign by itself but still requires terminal confirmation and cleanup. Separate the 30 s generated/undrained backlog from paced 1500 ms delivery credits and two-second transport/browser buffers; keep provider controls responsive. Only eligible open/sealed refs have playback-stall timers; finalization atomically invalidates their identities, queued callbacks recheck current state/identity, and each new eligible interval starts fresh. Acknowledged retirement releases remaining credit exactly once while preserving generated/sent/played evidence; final-progress/cancellation/cleanup deadlines and all release barriers remain independent. API 7.1.6 gates exactly-once response/continuation admission on correlated current input commitment, valid authority/epoch and every cleanup barrier. Genuine later speech advances a private current-turn token; old cleanup callbacks cannot release superseded work. These are documentation obligations, not implemented runtime evidence.
@@ -352,3 +352,12 @@ current-input/authority release gates. No automatic continuation is authorized.
Final OpenAI transcript completion waits for terminal classification within the
existing control budget. Consumer integration and separate funded/browser
acceptance are in docs/guides/openai-output-limit-repair.md.
Apply the API's OpenAI output-capacity amendment with this workflow: select
provider-specific runtime limits at stream/smoke admission, freeze the new
OpenAI capacity fields in reservations, and reject mismatches before opening.
Keep current authority, transport credit, cancellation and playback deadlines;
admit byte/slab capacity before decoding PCM. The 120-second finite reservoir
allows token-budget evaluation; it does not authorize unlimited output or select
the final budget. Gemini retains its baseline. Real benchmark acceptance still
requires complete essential facts and peak backlog below 80% of the frozen bound.