docs(voice): freeze OpenAI Realtime Phase 0 contracts

Align voice specifications and the MVP plan with OpenAI Realtime.
Document audio admission, bounded playback, cancellation ownership,
turn correlation, cleanup barriers and calibration prerequisites.
Preserve historical checkpoints and record unrun acceptance gates.
This commit is contained in:
amirhosein mazaheri
2026-10-08 18:07:38 +03:30
parent 9dac244590
commit 6f0561c490
10 changed files with 834 additions and 48 deletions
+135 -8
View File
@@ -50,7 +50,7 @@ Proposed field limits: deferred text message 8000 characters; assistant name 120
Delivery labels define the current MVP. Deferred sections preserve future contracts, not routes required to ship now. F01 is read-only settings/capabilities; C01 only accepts mode=voice in this milestone. The old prototype POST /chat is not a scoped MVP consumer and must not be exposed as an authenticated replacement.
The inventory above lists application HTTP endpoints only. Proposed application Live WSS: `/api/v1/voice/sessions/{session_id}/stream` (authenticated upgrade, Section 7); this is distinct from the backend/provider Gemini WSS connection. Internal model tools have no public REST route.
The inventory above lists application HTTP endpoints only. Proposed application Live WSS: `/api/v1/voice/sessions/{session_id}/stream` (authenticated upgrade, Section 7); this is distinct from the backend/provider OpenAI Realtime WSS connection. Internal model tools have no public REST route.
Health paths are outside `/api/v1`. Register `/voice/sessions/by-request/...` before dynamic routes if the router needs that ordering. `search_knowledge` is internal and has no public HTTP route.
@@ -265,9 +265,9 @@ Scope key `(conversation_id,client_request_id)`. Changed message under same key:
Path uses the original client request UUID, allowing recovery even if the POST response was lost. 200 returns T01 shape, including running/failed. 404 if no committed turn exists. If 404 after an ambiguous client timeout, retry the SAME POST/key; uniqueness handles races. Never generate a new key merely because a response was lost.
## 7. Voice contract — direct Gemini Live; proposed application WSS
## 7. Voice contract — OpenAI Realtime; frozen application audio/events
The initial provider is direct Gemini Live managed by the backend. This replaces revision 1.1's provisional SDP contract before frontend implementation. HTTP creation/poll/close, application WSS audio/events and internal model tools are separate contracts. None is verified as implemented. Audio/event field names below are proposed application names, not provider-native event names.
The initial provider is direct OpenAI Realtime managed by the backend. This replaces revision 1.1's provisional SDP contract before frontend implementation. HTTP creation/poll/close, application WSS audio/events and internal model tools are separate contracts. None is verified as implemented. Phase 0 freezes the application audio/event fields below; implementation remains pending. These are application names, not provider-native event names. Provider events, response/item/call IDs, session objects and credentials remain private to the adapter; tool_call_id is an application correlation ID.
### V01 — Create session (HTTP)
@@ -303,12 +303,12 @@ No body. 200 `{session_id,status:"closed",close_reason:"user_requested"}`. Alrea
Proposed WSS upgrade on the V01 `stream_path`: authenticate cookie, trusted Origin, owner, auth session, current epoch and unexpired reservation before accepting. HTTP creation requires normal CSRF; the browser WebSocket handshake uses cookie/Origin validation, not an assumed arbitrary CSRF header. Reject extra caller/model scope. One media connection per session; an additional connection is refused and does not open another provider session.
Proposed binary client frames carry mono PCM16 little-endian at 16 kHz; server audio frames carry PCM16 at 24 kHz. These rates and bounded frame/buffer limits are agreed at stream setup. JSON control/events are distinguished from binary audio. Bridge/transcoding is backend/client work, not a public provider key flow.
Binary frames in both directions carry raw mono signed PCM16LE at 24 kHz (pcm_s16le, one channel, 48,000 bytes/second), without WAV headers or compressed audio. Rates are fixed, not negotiated by callers. Client capture must resample to 24 kHz. JSON controls/events are separate from binary audio. Engineering defaults and deterministic transport admission/close behavior are specified in 7.1.3; all remain runtime implementation obligations.
Illustrative proposed control/event shapes:
Frozen application control/event shapes (illustrative IDs):
```json
{"type":"session_ready","session_id":"a0000000-0000-4000-8000-000000000001","input_audio":{"encoding":"pcm_s16le","sample_rate":16000,"channels":1},"output_audio":{"encoding":"pcm_s16le","sample_rate":24000,"channels":1}}
{"type":"session_ready","session_id":"a0000000-0000-4000-8000-000000000001","input_audio":{"encoding":"pcm_s16le","sample_rate":24000,"channels":1},"output_audio":{"encoding":"pcm_s16le","sample_rate":24000,"channels":1}}
```
```json
@@ -327,9 +327,136 @@ Illustrative proposed control/event shapes:
{"type":"error","turn_ref":"live-turn-2","error":{"code":"SEARCH_TIMEOUT","message":"Knowledge retrieval timed out.","request_id":"req-example","retryable":true}}
```
Transcript status is partial, completed or interrupted. The adapter must prove turn/event correlation for the selected provider; `turn_ref` is an application correlation field, not a new database identity contract. UI retains available transcript and sources for the current session, marks missing transcript unavailable and labels retrieval-only sources accurately. No raw recording or guaranteed durable full transcript is introduced.
Additional server events and the client playback control:
On interruption, flush audio buffers, mark partial output, cancel outstanding calls when possible and suppress late results. On disconnection/restart, mark old session unusable and start a new one after reconciliation; seamless reconnect/context restoration is deferred. Do not replay audio/tool events as fresh turns. Use bounded buffers, idle/creation/tool deadlines and existing session TTL; values require deployment validation.
```json
{"type":"user_speech_started","turn_ref":"live-turn-2"}
{"type":"audio_started","turn_ref":"live-turn-1","audio_ref":"live-audio-1"}
{"type":"playback_progress","audio_ref":"live-audio-1","played_ms":120}
```
#### 7.1.1 Audio coordinates and reference lifecycle
An output segment is exactly one provider assistant output item/audio content part, from its first sample to provider generation completion or cancellation. Allocate one backend-generated audio_ref per such part, unique and never reused in a session. Provider item/response IDs and content indices stay private. Do not split a part into multiple audio_ref values in this MVP: splitting would require a separately reviewed private sample-offset mapping. Splitting a segment into transport messages does not create a new reference. The adapter must support the documented truncatable audio content index (currently 0); unexpected layouts fail safely, never guess a mapping.
Emit audio_started before the first binary message for that reference. Binary messages belong to the last audio_started; serialize output parts without interleaving their bytes. Seal the prior part with audio_ended before the next audio_started, unless turn_interrupted has sealed it. Duplicate audio_started with identical turn_ref/audio_ref is a no-op and must not reset playback; a conflicting reuse is a protocol error. Generation completion does not mean playback completion. Add this end delimiter, since neither transcript completion nor another audio_started reliably seals the last part:
```json
{"type":"audio_ended","turn_ref":"live-turn-1","audio_ref":"live-audio-1","sent_bytes":48000}
```
audio_ended is server-only and occurs after all successfully sent messages of a normally completed segment. sent_bytes is a nonnegative even integer counting only raw PCM payload bytes whose application WebSocket send completed successfully. It excludes provider-generated bytes still queued, discarded on cancellation, JSON and framing overhead. It is not a claim that the browser received or heard those bytes. Exact duplicate audio_ended is a no-op; changed totals are a protocol error. No audio_ended is required for an interrupted segment: turn_interrupted seals all its audio references. Send uncertainty makes the session unusable; do not continue with ambiguous accounting.
Reference states are open (may send), sealed (no further bytes, browser may still play), finalizing (cleanup owns the reference; interrupted refs accept bounded final progress), and retired (no progress can alter provider context). Finalizing also covers normal submillisecond-tail cleanup without relabeling the exchange interrupted. Only open/sealed refs can be playback-stall eligible under 7.1.5; finalizing/interrupted/retired refs cannot. Retain sealed mappings and last valid progress even after provider response completion and while newer segments play. At most 64 unretired references per session is an engineering default; exceeding it fails the session rather than evicting an unresolved reference. After interruption cleanup acknowledgement, retire all affected references, retaining their frozen last progress as tombstones until session close. At most 256 references including tombstones per session is an engineering default; fail safely on exhaustion. Session close retires everything. A normally completed reference may retire without truncation only after provider terminal generation, audio_ended, all sends completed, generated_bytes == sent_bytes == 48 * last_valid_played_ms and a whole-millisecond total: every sample is then confirmed by the report. A normal submillisecond-tail cleanup follows 7.1.6 without relabeling an otherwise complete exchange interrupted. Otherwise retain it for interruption cleanup. Do not retire on transcript completion or a rounded progress value alone.
played_ms is a JSON integer token (not boolean, fractional/exponent-form number, string, NaN or infinity), cumulative duration actually played from the start of that reference, excluding queued audio. The browser computes floor(played_samples / 24) at 24 kHz; the backend computes max_sent_ms = floor(sent_bytes / 48). Accept only 0 <= played_ms <= max_sent_ms and monotonic values within that session/reference; equal duplicates are no-ops. For example, 50 sent bytes = 25 samples: max_sent_ms is 1, never rounded to 2. Provider audio_end_ms is the accepted integer played_ms, equivalent to 24 * played_ms sample positions from the part's start. No public/provider offset conversion is needed. Round down; submillisecond uncertainty is discarded from provider context, not claimed heard. Never silently clamp excessive input to a believable value.
Send progress once every 100 ms during playback (engineering cadence default) and once at segment completion and immediately after stop/flush. Repeated equal values are allowed. FIFO browser playback spans multiple references; every queued-but-unplayed segment has confirmed progress zero. Progress is a playback assertion subject to validation, never authority or proof of human comprehension.
#### 7.1.2 Interruption, final reporting and provider continuation
On genuine trusted user speech detection, first classify prior work using normal-completion versus actual-interruption rules in 7.1.6. For actually unfinished old output, atomically transfer affected refs to finalizing and invalidate their playback-stall timer identities before emitting interruption/stop controls; stop admission/delivery of its audio/tool results, cancel under the ownership rule below, seal sent-byte counters and start the final reporting window. Cleanup now owns those refs: the final-progress, cancellation/terminal and cleanup-ack deadlines below remain enforceable, but stopped/flushed playback has no stall obligation. Final reports never rearm it. Emit turn_interrupted only for affected unfinished old output, before user_speech_started for the new turn. A normally completed exchange retains its completed state; pending input with no assistant output can be superseded internally without inventing an interrupted answer. Duplicate interruption of an already finalizing/retired turn neither restarts timers nor sends cancellation/cleanup twice. A serialized send already completed before interruption is counted; queued unsent bytes are removed and never counted. Suppress all late old-turn audio, audio_started/audio_ended, completed tool results/continuations and assistant transcript completion updates. Delayed user-input transcripts follow 7.1.6 and are not suppressed merely because a newer turn exists. Retain already delivered sources/transcripts only as interrupted display evidence, never claim an exact spoken transcript.
On turn_interrupted (or user_speech_started while old playback remains), the browser immediately stops currently playing old-turn audio, samples the played position at stop, cancels scheduled playback and flushes every old-turn queued segment. It sends final playback_progress for every retained affected reference, including zero for never-played segments and the last completed position for earlier segments. It stops even if provider generation was already completed. Identical interruption notifications must not resume audio or reset progress. Socket close/error uses the same stop/flush behavior without assuming final reports will arrive.
The server accepts valid old-reference progress arriving after turn_interrupted while the window is open. Proposed engineering default LIVE_FINAL_PROGRESS_WINDOW_MS is 1000, measured by backend monotonic time from interruption detection, not receipt by the browser. Validate/process fully admitted messages strictly before the deadline in connection order; messages still queued at expiry cannot extend the window. At or after the deadline freeze all last valid values. No extra final flag or acknowledgement is added to playback_progress, so wait the bounded window rather than guessing the last report. Auth expiry/revocation bypasses this wait and closes; progress never renews access. Reports after freezing cannot amend truncation: an equal duplicate against a known frozen/retired value is ignored, changed late/retired or unknown-reference progress is rejected by the error policy below.
At window expiry use the last valid progress for each part; missing progress means zero, not all sent audio. Coalesce the old response's cancellation request sent at interruption; cancellation alone does not remove unheard context. Privately count all received provider-generated samples, including unsent/cancelled deltas, without delivering late output. Wait for provider terminal generation/cancellation before deciding the final generated total and dispatching cleanup; final played values remain frozen. Privately truncate every affected part with unconfirmed playback, including earlier/later generated parts and parts with zero application sends. Only a terminal part with generated_bytes == sent_bytes == 48 * confirmed_played_ms is fully confirmed and needs no truncation; unsent generated audio and any remaining fraction of a millisecond require cleanup. If the provider cannot truncate a mapped part or remove wholly unheard later output with confirmed cleanup, fail/close the session; do not continue with that context. No invented shortened transcript is returned.
Require provider-confirmed cancellation/terminal generation within 5 seconds of the one cancellation dispatch, then matching cleanup acknowledgements (item/content/audio_end_ms), with all cleanup acknowledgements received within LIVE_TRUNCATION_ACK_TIMEOUT_SECONDS = 5 after cleanup dispatch (engineering default). Cancellation timeout uses that same configured 5-second bound. Thus the final-report/cancellation barriers have finite deadlines even if the provider never terminates generation. An already-completed response needs no cancel acknowledgement; its unplayed audio still needs cleanup. Coalesce identical pending cleanup and acknowledgements. A conflicting cleanup acknowledgement, truncation/provider failure (apart from the narrowly correlated no-active-response cancellation race below), lost connection or timeout yields normalized LIVE_CONTEXT_SYNC_FAILED, retires the session and requires reconciliation/fresh session. Never infer success from sending truncate or receiving response completion.
The backend is the sole cancellation and response-creation owner. Configure private VAD create_response=false AND interrupt_response=false and require provider configuration acknowledgement; VAD still reports speech/commit events. The proof's defaults are not evidence of this configuration. For a known active old response, send at most one response.cancel with that specific private response_id and a unique private event_id mapped to the cancellation intent; never issue a bare cancel that could hit a newer response. Record terminal response.done state by response identity. If completion or provider cancellation was already observed for that response, skip cancellation and proceed to required playback/context cleanup.
A completion/cancellation racing after the backend's active-state check can produce a no-active-response cancellation error. Only an adapter-verified no-active-response classification tied by error event_id to that one cancellation intent/response is benign by itself: it does not fail the session, retry cancellation or satisfy the terminal/cleanup barrier. Independently require a correlated terminal response.done (completed/cancelled; failed/incomplete handled as technical failure) within the bounded cancellation deadline, then complete all required context cleanup. A terminal event already recorded satisfies this test; missing terminal confirmation times out and fails. A response identity mismatch, generic/unrelated error, bad arguments, authentication failure or truncation error is not this exception and remains fatal under its normal policy. Official docs establish the benign behavior but not a stable named error code; an exact structured classifier must be proved with the selected provider profile before race acceptance, never infer it from a free-text substring or swallow all cancellation errors.
Keep both VAD flags disabled throughout the session. Unexpected automatic generation/cancellation is an observable configuration/protocol deviation; correlate any actual terminal event for cleanup, suppress unintended output and fail if the controlled state cannot be established. The independent response-release gate in 7.1.6 applies even after all cleanup acknowledgements arrive. This is a future runtime obligation, not proof-script behavior.
#### 7.1.3 Transport admission, queues and terminal errors
These finite engineering defaults are frozen for initial integration and configurable by trusted deployment only. Product owners still need to approve capacity/latency targets; missing runtime enforcement blocks runtime acceptance, not this documentation checkpoint.
| Boundary | Limit / accounting |
| --- | --- |
| Application binary message, either direction | 9600 raw bytes (200 ms), nonempty and even-length; each message ends on a complete PCM16 sample |
| Client JSON control message | 4096 UTF-8 bytes before parsing; one object, only playback_progress with exact documented fields; ref strings 1-128 ASCII characters |
| Server JSON event message | 65536 UTF-8 bytes; build within a bounded serialization budget; preserve whole evidence/source fields or fail, never truncate them silently |
| Application transport audio queues | 96000 raw bytes (2 seconds) AND 100 queued messages per direction; count queues/in-flight sends until completion. Output scheduling also obeys the smaller 72000-byte T+R credit window in 7.1.5 |
| Provider-generated reservoir / aggregate undrained output | 1440000 bytes (30 seconds) across G+T+R, 512 packed slabs, bounded descriptors/scratch/metadata; 7.1.5 distinguishes storage from delivery/playback |
| Browser output backlog | 96000 bytes AND 100 messages across all refs, including currently playing remainder and scheduled buffers; independently enforced by browser |
| Input since last commit | 480000 bytes (10 seconds), including forwarded provider-buffered PCM; fail if not committed within this bound |
| Control/event queues | 64 messages and 262144 encoded bytes per direction; ordered relative to audio markers |
| Send completion deadline | 5 seconds per message; uncertain/failed send fails session, does not increment confirmed sent_bytes |
Application message limits apply to reassembled WebSocket messages as well as individual wire fragments: fragmentation cannot bypass the bound. Reject oversized headers before payload allocation; configure transport maximum reassembled size and bounded receive queues, disable compression and reject RSV/compressed frames. Before UTF-8 decoding, JSON parsing, PCM conversion or queue append reserve size/count capacity. Browser code checks byteLength before copying/decoding. Provider receive messages require an independent 262144-byte cap, checked before JSON/base64 decode; decoded audio must be sample-aligned and fit the generated-reservoir/scratch admission in 7.1.5 before allocation/enqueue; it need not fit immediately into the much smaller transport queue. Divide admitted PCM into <=9600-byte even messages. Do not allocate an unbounded delta and then check it.
Before session_ready, browser capture/send is disabled; backend accepts no application audio/control payload, buffers none, and forwards none to provider. Setup acknowledgement precedes session_ready and any output audio. Early audio/control is LIVE_NOT_READY and closes with 1008. Ping/pong/close protocol frames remain transport concerns. Server emits no binary output without a preceding audio_started. Schema errors, unknown controls, malformed UTF-8/JSON, empty/odd PCM, invalid progress and conflicting reference reuse fail with LIVE_PROTOCOL_ERROR and close 1008. A reference tombstone's equal duplicate is the only accepted post-retirement progress.
Oversized messages use LIVE_FRAME_TOO_LARGE and close 1009. Capacity exhaustion uses LIVE_BUFFER_OVERFLOW and close 1013. Provider malformed output, send uncertainty, or context synchronization failure uses the corresponding normalized error (LIVE_PROVIDER_PROTOCOL_ERROR, LIVE_TRANSPORT_FAILED, LIVE_CONTEXT_SYNC_FAILED) and close 1011. Stop admissions, cancel work, flush queues and mark the session failed/unusable. Use the existing error envelope with the affected application turn_ref (null before any turn), safe request_id and retryable=false for this unusable session; recovery requires reconciliation and a fresh session. Attempt one bounded error send only if reserved control capacity and a writable socket exist; otherwise close directly. Overflow must not block on enqueueing its own error. Browser detects close even when no JSON error can be delivered and immediately stops/flushes.
Use queue accounting across references, not a fresh allowance per segment. Unsent canceled bytes may be discarded only while sealing/interruption/terminal failure; never silently drop output and keep generating/counting it as delivered. A genuinely stalled client or exhausted generated backlog fails explicitly under 7.1.5; a healthy generation burst is admitted and paced, not mistaken for transport overflow. Progress acknowledgements do not free server memory for an uncompleted send or expand any limit. Server queue bounds and client playback bounds are separate; neither proves the other.
#### 7.1.4 Contract walkthroughs (documentation acceptance only)
| Case | Required sequence / result |
| --- | --- |
| Final progress after interruption | Ref A last reported 300 ms, 1000 ms sent; interrupt at t=0, browser stops at 420 ms and reports at t=0.2 s. Accept 420 within the 1 s window, truncate privately to 420, wait matching ack, then retire A/allow new response. A later 430 is a protocol error; equal 420 duplicate is ignored. |
| Generation done, playback queued | audio_ended seals A at 48000 bytes, but browser has played 200 ms and queued 800 ms. Keep mapping; interruption stops/flushes and final progress governs cleanup. Generation/transcript completion never means 1000 ms heard. |
| Later segment interrupted | A and B map to distinct private items/content parts; A sent/played 1000 ms, B sent 800 ms/played 250 ms, later C generated but unheard. Keep A, truncate B to 250 in B's own coordinates, remove/truncate C to zero and wait all required acknowledgements. No A offset is added to B. Unsupported multi-part cleanup closes, rather than retaining C as heard context. |
| Duplicates and bad progress | Identical A=250 while open/finalizing or against retired frozen A=250 is a no-op. Unknown A, retired A=251, fractional 250.5, regression 249, boolean, exponent token or value beyond floor(sent_bytes/48) is LIVE_PROTOCOL_ERROR/1008. Timers/calls never restart on duplicates. |
| Missing progress | At deadline no valid A report: use zero. Invalid reports never become a default or no_evidence; protocol violations close. Disconnected client prevents continuation, regardless of last progress. |
| Oversized/overflowing frames | 9602-byte PCM is LIVE_FRAME_TOO_LARGE/1009; 3-byte PCM is LIVE_PROTOCOL_ERROR/1008. A would-be 96002-byte aligned queue exceeds budget: fail LIVE_BUFFER_OVERFLOW/1013 before append, cancel/flush; unsent bytes are not counted. Before readiness even valid PCM fails LIVE_NOT_READY/1008. |
| Six seconds generated in one second | 288000 PCM bytes arrive in multiple provider messages within the per-message cap. Admit into G under the 1440000-byte aggregate limit; T+R never exceeds 72000 bytes. After 1 s of valid real-time playback, 48000 bytes are confirmed and B is about 240000 bytes (plus <1 ms rounding uncertainty). Pace remaining delivery using progress; six-second generation completion neither overflows a healthy browser nor emits audio_ended before the last send. |
| Stalled browser reaches the bound | With no increasing progress, only 72000 bytes can enter T/R. G grows until aggregate B reaches 1440000 bytes; the next aligned delta fails LIVE_BUFFER_OVERFLOW/1013 before allocation. If generation stops below that cap, the 5 s no-progress deadline still terminates the stalled session. Cancel/flush, never count unsent audio as delivered. |
| Cancel versus terminal response | Backend reserves cancel for old response R1; R1 completes or is cancelled before request reaches provider. A correlated verified no-active-response error is benign only by itself. Record R1's terminal response.done, finish required final-progress/truncation cleanup, then evaluate current-turn release; no cancel retry or blanket provider-error suppression. |
| Delayed user transcription | T1 input committed, T2 begins, then ASR completion for T1's private input item arrives. If current authorization/epoch is valid, emit transcript(role=user, turn_ref=T1, status=completed); do not label T2 or release T1. A late assistant completion for interrupted T1 remains suppressed. |
| Cleanup while T2 still speaks | T1 truncation ack clears T1 barrier while T2 is speaking. No response.create: T2 still needs its own speech-stop and committed input confirmation. Duplicate T1 ack cannot bypass these conditions. |
| T3 before earlier cleanup completes | T2 is pending behind T1 cleanup. A new input item/start for T3 advances the private generation token and supersedes T2; replay of T2 start does not. T1 ack clears only T1's barrier; it cannot release T2, and T3 waits for its own commitment, valid authority and every applicable cleanup. |
| Cleanup outlasts former stall deadline | Interrupt A at t=0: atomically finalizing, stall identity invalidated, browser stops/flushes. Final progress at 0.2 s is accepted; freeze at 1.0 s. Cancellation dispatched at 0; correlated terminal confirmation at 4.8 s satisfies its 5 s deadline. Dispatch cleanup at 4.8 s; matching ack at 9.6 s is within 5 s of dispatch (deadline 9.8). Retire/release remaining credit once without claiming discarded audio heard. No playback timeout at 5 s; response release still requires every 7.1.6 gate. |
| Stall callback races finalization | A's deadline callback is queued while interruption acquires the serialized state decision. Finalization invalidates A's timer identity first; the callback rechecks state/identity and does nothing. If the callback instead wins with A eligible and its deadline actually expired, stall failure is terminal. Neither ordering permits double failure/retirement or reviving the session. |
| Fresh output after cleanup | A retires after acknowledged cleanup with its frozen evidence retained and remaining credit released once. Once current input/authority/all barriers permit B, B's first reportable successful send at t=10 s starts B's own deadline at 15 s; no A timestamp or callback applies. B's increasing progress renews only B's eligible timer. |
| Genuine active-playback stall | A remains open/sealed with 48000 sent bytes, zero valid played_ms and no interruption/cleanup ownership. First reportable send at t=0 starts deadline 5 s. Equal zero reports do not renew it. At t=5 s the matching callback confirms A is still eligible and expires it: LIVE_BUFFER_OVERFLOW/1013, terminal failure/stop/flush. Cleanup exclusion does not excuse a genuinely stalled browser. |
#### 7.1.5 Generated backlog and paced delivery
The provider can generate audio faster than real-time playback. The two-second application transport/browser buffers are not a limit on an entire generated response. Keep three distinct counters across all output refs: G = admitted provider-generated PCM not yet scheduled for delivery; T = PCM reserved in the application output queue/in-flight send; R = the outstanding delivery-credit balance for successfully sent PCM not yet confirmed played or explicitly released at retirement/terminal teardown. R is not the retained sent-minus-played evidence counter. A sample moves G -> T -> R without double counting; generated_bytes, sent_bytes and confirmed played bytes remain separate per-reference counters. Never count generated or queued bytes as sent. R is a delivery-credit ledger and need not retain PCM after successful send.
Initial trusted engineering defaults: maximum aggregate undrained backlog B = G + T + R is 1440000 bytes (30 seconds); at most 512 packed PCM slabs and 64 unretired ref descriptors. Pack provider deltas into bounded <=9600-byte even slabs, preserving ref/order; coalescing tiny deltas prevents provider event count alone exhausting the slab budget. Empty/slab metadata is bounded to 65536 bytes, not a per-delta history. Audio storage G+T cannot exceed B; transport copies are separately limited to 96000 bytes; one provider encoded-message scratch buffer is capped at 262144 bytes and one decoded scratch at 196608 bytes, reserved before decoding. Thus maximum raw/scratch/copy/metadata payload memory is 2060288 bytes per session (object/allocator overhead must also be bounded and measured in later runtime acceptance). Count caps apply before allocation, not after a burst. This supports at most 30 seconds of outstanding generated-but-unconfirmed audio, not arbitrary response duration or unlimited API-process concurrency. Global session admission/memory capacity remains a deployment decision.
Output scheduler reserves a 72000-byte (1500 ms) sliding delivery window: T + R + next_message_bytes <= 72000, plus transport byte/count capacity. It transfers admitted PCM from G only when credits permit; it never dumps a generation burst into the browser. The remaining margin to the browser's 96000-byte limit covers scheduling/report cadence. Browser backlog retains its independent 96000-byte AND 100-message limit. A progress increase releases only 48 * delta_played_ms bytes from that ref's R after validating it against sent_bytes; rounded fractions remain conservatively outstanding. Identical reports release no credits. Transfer reservations to sent accounting atomically on send completion and release failed/cancelled reservations exactly once. At acknowledged retirement (or terminal session teardown), release that ref's remaining R exactly once through a private retirement-credit marker; atomically mark it released and subtract only its then-outstanding ledger balance. Valid final progress may first reduce R; retirement releases only the remainder. Duplicate progress, cleanup acknowledgements, retirement or teardown cannot release it again. This credit release is capacity bookkeeping, not playback evidence: retain frozen generated_bytes, sent_bytes and last_valid_played_ms in the bounded tombstone, including discarded/unconfirmed amounts. Never set played equal to sent/generated or zero evidence counters to manufacture confirmation. Discard cancelled G/T once under their reservation ownership without changing sent/played counters. Normal fully confirmed retirement has zero remaining R and needs no cleanup acknowledgement under 7.1.1; any retirement with unconfirmed audio while continuing a usable session requires acknowledged cleanup; terminal teardown may release resources but never permits continuation. Do not release R merely on interruption, window expiry, terminal generation or cleanup dispatch. Credit release cannot satisfy any missing cleanup/authorization/commitment barrier or itself trigger response.create; 7.1.6 must independently pass. Reported progress cannot free an uncompleted send, widen any cap or grant authority.
Delivery messages normally pack up to 9600 bytes; cap queued/in-flight output messages at 100 and scheduler reservations at 64 descriptors. Per-connection ingress/egress/control count limits remain as in 7.1.3. Scheduler waits off the provider receive loop for credit; provider control, speech-start, commitment, cancellation and cleanup events continue to be processed while audio waits. Retain a bounded control lane with interruption/terminal controls ahead of unsent audio, preserving ordering for already sent bytes and audio markers. Socket sends have deadlines and must not block the provider receiver. Do not stop reading provider events as flow control: there is no assumed provider-side generation pause command. Decode/admit each delta only within reservoir/scratch limits; fail safely on exhaustion while still attempting bounded cancellation/close.
Playback-stall detection is per reference, only while its state is open or sealed, playback has not been interrupted/stopped for cleanup, and successfully sent bytes contain at least one reportable unplayed whole millisecond (floor(sent_bytes / 48) > last_valid_played_ms). Finalizing, interrupted and retired refs are ineligible even if their retained sent/played evidence differs. On entering eligibility, initialize a fresh backend monotonic 5-second deadline and unique private timer identity for that ref; do not inherit another ref's send time, progress time or deadline. A first send with only a submillisecond remainder is not eligible; a later successful send that makes a whole millisecond outstanding starts the deadline then. Strictly increasing valid progress for that eligible ref renews its own deadline with a new timer identity if it remains eligible; reaching no reportable remainder invalidates the timer. Newly reportable output after that point starts a new identity/deadline. Another ref's progress, provider generation and equal reports cannot renew it; pause/mute cannot extend it indefinitely. A genuinely eligible ref with no increasing progress for 5 seconds fails LIVE_BUFFER_OVERFLOW/1013.
Interruption ownership and the state transition to finalizing must atomically invalidate the timer identity with stopping admission/delivery, before browser stop/flush controls. Normal-tail cleanup also invalidates it when cleanup takes ownership. Do not carry a playback-stall deadline into final reporting or cancellation/context cleanup, and do not rearm it on final progress or a duplicate interruption. Each queued timer callback must reenter the same serialized state decision and verify session usability, matching ref/timer identity, current eligibility and actual monotonic deadline expiry before failing. If finalization wins that decision, an already queued callback is a no-op; if a genuine eligible stall failure wins first, the session stays failed and later interruption cannot revive it. Stale callbacks from retirement, a progress renewal or a previous eligibility interval are no-ops. These timer identities remain private.
An unreportable <1 ms tail consumes credit/backlog until conservative cleanup/retirement, but cannot trigger stalled-playback failure. Finalizing refs retain their R ledger pending acknowledged retirement and the independent final-progress/cancellation/cleanup deadlines in 7.1.2; a cleanup timeout still fails LIVE_CONTEXT_SYNC_FAILED. In-flight T remains subject to its separate 5 s send deadline; interruption does not excuse send uncertainty or relax transport limits. A healthy 100 ms reporter playing at real time frees credits even if generation finishes early. At B's 30-second/slab/descriptor limit, refuse the next delta before allocation, cancel the correlated response, stop admissions/delivery and fail LIVE_BUFFER_OVERFLOW/1013. Unsupported output beyond the bounded backlog is a terminal capacity failure; do not misreport it as browser slowness. Provider-message, input and control caps retain their independent errors. Never silently drop audio while the session continues. On interruption, discard unsent G/T as cancelled, preserve exact sent/played/generated counters for acknowledged context cleanup, and suppress late old output.
#### 7.1.6 Transcript classes, turn eligibility and response release
User transcription is independent ASR of committed input, not assistant response completion. Map private input item identity to its original application turn at speech-start/commit. A delayed authorized user transcript emits the existing transcript shape with role=user, original turn_ref and the provider's partial/completed state even when a newer turn is active or the older request was superseded. It must not change current-turn eligibility, resurrect old work, trigger response creation or be displayed under the newest turn. Revalidate session/actor/access epoch before delivery; revoked/closed-session transcripts are suppressed. Retain input mappings/tombstones until session close with at most 256 input turns per session (engineering default); fail rather than guess an expired mapping or evict a pending transcript. Unknown input correlation is an observable protocol failure. Identical transcription events are no-ops; do not synthesize text on ASR failure.
Assistant transcripts/audio/tool output use private response/item/call-to-turn correlation. An assistant transcript done event is not proof of successful generation or audible completion: it may occur on cancellation. After actual interruption/supersession, suppress late assistant partial/done/completed events and tool outputs; they cannot restore completed display state or output audio. Already visible interrupted assistant text stays marked interrupted, without invented precise truncation. Delayed user transcripts are expressly exempt from that assistant-only suppression rule.
Normal exchange completion requires a terminal successful response, no pending tool/continuation or unsent G/T, and valid progress confirming all whole-millisecond output. An unconfirmed submillisecond tail receives conservative private cleanup before subsequent response release without automatically relabeling an otherwise completed exchange interrupted. For that normal tail, no active response needs cancellation and no interruption/final-report window is restarted; freeze its existing maximum reportable progress, transition the ref to finalizing with its stall timer invalidated, acknowledge private truncation, then retire the ref before subsequent response release. A new user turn after normal completion emits user_speech_started only; completed transcripts/sources retain their state. Actual interruption means unfinished generation/tool work, unsent audio or meaningful unplayed audio existed when genuine new speech started. Emit turn_interrupted only for that affected old turn. A pending request superseded before any assistant output is cancelled internally; do not fabricate an interrupted answer/transcript. Completed generation with queued playback is still interruptible.
Use a private monotonic current-turn generation token independent of access_epoch. A genuine speech start advances it, establishes a speaking input turn, makes older unfinished/pending work ineligible and adds every affected older response to the session cleanup set. Duplicate provider event IDs, or repeated speech-start for the same mapped input item/start position, do not advance it or restart cleanup. Distinct authenticated provider input item/start identities in forward media order are genuine subsequent speech; a known older item or delayed older start is not a new turn. Contradictory identities/ordering fail safely. Replays do not become genuine simply because their event_id differs. None of these private IDs/tokens is sent to the browser.
For every initial response.create, one serialized backend release decision must establish: (1) session_ready and usable session; (2) current input turn is the unsuperseded token holder; (3) correlated speech-stop and provider input_audio_buffer.committed confirmation identify its input item, not a commit for an earlier utterance; (4) actor/session/ownership/expiry/current authorization and pinned access epoch still match; (5) all older generation-terminal, final-progress, cancellation and context-cleanup barriers in the session cleanup set are satisfied; and (6) no conflicting active response or previously consumed initial-create intent exists. Input transcription completion is not a release prerequisite. The operator-only diagnostic text harness instead requires a provider-confirmed created input item; this exemption neither relaxes audio commitment nor adds a public text route. Cleanup finishing while input is still speaking or uncommitted clears only that barrier; it does not create a response.
Reserve/consume one initial-create intent per current turn before sending, privately correlate response.created to it (serialized single outstanding creation and backend-only metadata), and never blindly retry an uncertain send/acknowledgement. Uncertain creation closes the session; it cannot generate a second response. This is application exactly-once admission within the session, not a claim of provider network idempotency. Duplicate commit, stop, terminal, tool or cleanup events only reevaluate the gate.
A tool continuation is distinct from initial creation: authorize the existing canonical result once for its owning current-turn token and completed private call ID/hash, wait for the originating response's terminal tool-call state, send its matching function result once, then consume one continuation intent for that completed authorized call set. All input/authorization/cleanup/current-turn gates still apply. Multiple calls in one response produce one continuation after that authorized call set completes; duplicates never produce parallel responses or repeat results. The intent/result ledger is bounded to 256 entries per session; exhaustion fails explicitly. Late results from superseded turns are suppressed, not fed into new context. No public event shape or canonical tool output changes.
If T3 genuinely starts while T1 cleanup is pending and T2 has not been released, supersede T2, cancel its admitted retrieval/creation intents, and make T3 current. Continue existing T1 cleanup with unchanged deadlines and add any T2-generated output requiring cleanup; never restart old windows on the new turn. Bound the pending cleanup set by existing response/ref/intent limits. Cleanup callbacks record only their own response/barrier identity and cannot capture a turn to release later. Reevaluate the shared gate against the latest token and all outstanding barriers; T1's acknowledgement cannot release T2. If T3 is speaking, wait; if only T2 is committed, wait for T3's commitment. Retain superseded user input for authorized display/context as mapped user speech, without executing a response to it. Provider commitment ordering/correlation and late-event behavior are assumptions to prove in later authorized runtime acceptance.
Transcript status is partial, completed or interrupted. The backend assigns turn_ref at trusted user speech start and retains original-turn correlation for delayed events. The adapter must prove turn/event correlation for the selected provider; `turn_ref` is an application correlation field, not a new database identity contract. UI retains available transcript and sources for the current session, marks missing transcript unavailable and labels retrieval-only sources accurately. No raw recording or guaranteed durable full transcript is introduced.
Interruption, final progress, acknowledged context cleanup and late-output suppression follow 7.1.2; generation completion is not playback completion. On disconnection/restart, mark old session unusable and start a new one after reconciliation; seamless reconnect/context restoration is deferred. Do not replay audio/tool events as fresh turns. Use bounded buffers, idle/creation/tool deadlines and existing session TTL; values require deployment validation.
### 7.2 Internal model tool — `search_knowledge`