Files
rag-technical-docs-assistant/docs/specifications/RAG-Phase1-Implementation-Guide.md
T
amirhosein mazaheri 18e595ac93 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.
2026-10-13 14:09:20 +03:30

39 KiB

RAG Assistant — Phase 1 Implementation Guide

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 operator smoke share the selected model/voice/profile. Only the selected voice key is required; there is no fallback or frontend provider selector. Legacy PROVIDER and existing GEMINI_* settings remain supported; conflicting provider aliases fail configuration. Dedicated OPENAI_REALTIME_* settings do not change embedding credentials. Browser PCM16LE remains mono 24 kHz in both directions. Pinned reservations cannot switch providers on connection or replay. Gemini interruption requiring unverified context truncation closes safely; OpenAI keeps its existing native cancellation/truncation contract. Canonical search, original documents, frozen profiles and owner/replay/revocation rules remain unchanged. See Phase 2 repair report.

Version 1.3 · 2026-10-07 · Current Live document MVP implementation baseline; planned mechanisms are not completion evidence.

Phase 0 amendment (2026-10-08): OpenAI Realtime replaces Gemini Live for voice only. The Realtime MVP plan supplies the current backend phase sequence and conditional 3-5 day estimate; prior four-day schedule is historical. See Phase 0 prerequisites and results. Extraction/embeddings and HTTP/search contracts are unchanged.

1. Purpose and authority

Implement the conditional four-day Live document MVP in RAG-AI-Phase1-Delivery-Plan.md. API/database specifications govern their contracts. The English RAG-Phase1-MVP-Scenarios.md supplies acceptance walkthroughs; the older Persian report is historical context.

One organization, pre-created users, one API instance and one separate worker. Reuse ingestion Phases 1-4, including the current hosted embedding/staging implementation and reviewed repairs. Phase 5 worker/publication/retry and retained review/resume backend services, plus Phase 6 ingestion validation/handoff, are implemented. Authenticated D06/D07 transport and HTTP/search/Live/UI integrations remain pending. The four supplied files are required examples, not the accepted corpus or a filename allowlist. New documents within declared format/structure/resource limits must run without developer changes.

2. Decisions for this implementation

Topic Current MVP decision
Backend Modular FastAPI API and separate worker from the same codebase
Framework LangChain for retriever/tool integration; keep provider-neutral application services
Existing embeddings Preserve EmbeddingProvider.embed, OpenAICompatibleEmbeddings and stage_document; a thin Embeddings wrapper is optional
UI Same-origin HTTPS login plus one voice workspace with an admin Documents area
Identity Opaque cookie sessions, admin/user roles, owned voice conversations; no signup
Jobs PostgreSQL polling, current-claim lease fencing and complete atomic publication
Upload New bounded PDF/DOCX/JPEG/PNG/Markdown documents; unknown future total count
QC Retain exact review candidates, evidence-bound admin decisions and same-job retry; no new document state
Retrieval Scoped pgvector semantic search plus exact normalized identifiers; reranker/ANN conditional on measured need
Voice Backend-selected Gemini Live/OpenAI Realtime audio over WSS; shared LangChain knowledge tool
Evidence Current-session provider transcripts/sources; durable owned session/tool diagnostics
Deferred Full text chat/history, settings editor, rich management/delete UI, recording, seamless reconnect, CTI
Settings Fixed server profiles and seeded instruction/name; retain revisions and expose read-only capabilities

3. Modules and ports

Module / path Responsibility
app/api/v1/ DTOs, cookie/Origin/CSRF validation and safe HTTP errors
modules/identity/ Login, sessions and trusted actor context
modules/documents/ Existing intake/extraction/chunking/embedding; review, status, retry and selection
modules/knowledge/ One scoped search/evidence service and bounded query embedding
modules/conversations/ Minimal owned voice conversation identity/epoch; text execution deferred
modules/live/ Session reservation, audio relay, trusted tool dispatch, cancellation and lifecycle
infrastructure/ Existing SQL/file/provider adapters plus a small LangChain integration boundary
app/worker.py Fenced claim, heartbeat, processing, review interruption, publication and recovery

Application services retain provider-neutral values. LangChain Documents carry faithful chunk text plus document_id/chunk_id/title/location metadata, but neither a Document nor model metadata grants scope. A custom retriever invokes the shared search service with authenticated backend context. The registered search_knowledge tool exposes only query and optional resolved context.

If a LangChain component requires Embeddings, map embed_query and bounded embed_documents to the existing provider. Respect per-input/token/batch limits, frozen model/dimension/preprocessing identity and float32 validation. Handle empty document lists at the wrapper boundary; do not call an adapter that requires a nonempty batch. Bound aggregate requests and preserve input order. Do not add internal retries, truncation, fresh normalization or provider defaults. Async calls must run existing blocking I/O off the audio/event loop with bounded concurrency/deadlines; cancellation cannot recall a blocking network request.

Ingestion continues to use stage_document and its publication contract. Do not replace it with a framework vector-store insertion helper that bypasses staging, authorization, IDs, profile checks or atomic publication. A custom retriever is sufficient; using LangChain does not require a new vector database, LangGraph rewrite or a separate text-model inference on each audio turn.

4. Implementation order and deliverables

Work package Work and completion proof
WP1 - Early provider proof Real Persian audio/transcripts plus one backend-executed tool call on target network; configure fixed funded profiles
WP2 - Identity and upload Secure sessions and bounded multipart transport reuse intake; new upload persists and duplicate key replays
WP3 - Worker and review Continue ingestion Phase 5; fence claims, candidates/decisions, artifact reuse, retries and complete publication
WP4 - Shared search Compatible query vectors, exact identifier matching and eligibility joins; independently marked evidence evaluation
WP5 - LangChain and Live Expose the same search tool, reserve owned sessions, relay PCM, correlate tools/transcripts/sources and suppress cancellation
WP6 - UI/deployment/acceptance Minimal workspace, all four examples plus unseen uploads, provider/restart/revocation checks and actual HTTPS rehearsal

Map these packages to Days 1-4 in the delivery plan. WP1 is an early risk gate, not work postponed until the other packages finish. A developer can progress independent worker/API work while provider validation is unresolved; no agent delegation, parallel staffing or completed proof is assumed.

Recommended first implementation task: complete WP3 using existing Phases 1-4 and forward schema changes for retained review state, while running WP1 early. Keep the original migration byte-for-byte and report actual check outcomes.

5. Identity and request context

Login verifies a stored password hash using a maintained password-hashing implementation. Generate an unpredictable session token; store only its hash. Cookie rag_session is HttpOnly, Secure and SameSite=Lax. Restrict Origin on login and mutations. Return a session CSRF token after login and through /me; require X-CSRF-Token on authenticated mutations. Configure session expiry at deployment; no business retention period is assumed here.

Resolve (user_id, organization_id, role) exclusively from the session. Check owner for conversation/turn/live endpoints, including administrator requests: admin status does not automatically grant access to other users' chats. Return 404 for hidden resource IDs, 403 for an authenticated non-admin calling an admin-only collection operation. Rate-limit login/provider operations with conservative single-instance limits.

6. Document upload and ingestion

  1. Authenticate admin and validate upload idempotency key, bounded bytes, actual type/signature/package structure and safe display title/filename. Never read an unbounded multipart body or use a filename as a storage path.
  2. Reuse the intake service/ports with bounded temporary input where needed. Preserve the replay digest of bytes and normalized title; no new model/profile or client organization fields enter the request. Repeated same key/input returns the original document/job. A new key creates an independent document.
  3. Save the immutable original and create document/job/audit in a short transaction. Hash/reconcile files outside long transactions. New document is inactive.
  4. Claim eligible work with token/lease, attempts and documented lock order. Provider work runs outside long transactions. Heartbeat throughout slow calls.
  5. Dispatch existing frozen-profile extraction/normalization/chunking and embedding components. Validate original checksum and actual provider identity. A legacy profile is dispatched explicitly, never silently reinterpreted.
  6. Retain exact extraction output for review/reuse, then stage every embedding. The current PageBlockExtractor requires review for direct PDF pages and, by default, OCR/vision output; this is an actual implementation gate, not an optional UI decoration.
  7. Publish all chunks and ready/succeeded state in one fenced transaction. Verify token, unexpired lease, original/profile, non-deletion, complete vectors, ordinals and eligibility; keep is_active=false. Never republish a ready document.

6.1 Exact-output review and resume

A ReviewRequired outcome is mapped by the new worker to a bounded, non-automatically-retried failed attempt with EXTRACTION_REVIEW_REQUIRED. It is distinct from a malformed/permanently unreadable source. Persist trusted references to the exact bounded image/block candidate, source/extraction identity, locator, digest and progress under the current claim before releasing the lease. Unreviewed candidates are not complete validated artifacts and cannot be indexed. Crash recovery must not attach uncommitted or stale candidates.

D06 shows retained candidates to the admin. D07 records approval/rejection of the exact evidence digest and required checks. New OCR output has a different review identity and requires a new decision when the frozen supervisor gate or independent validation requires review. Server validates/recomputes digests; client supplied text, paths, profile identity and reviewer identity are forbidden. Use job/document locks and current failed-candidate identity for decisions. Decisions neither activate nor mark a document ready.

After approval, D04 requeues the same eligible job once per key. Resume using the retained inspected page/block output; do not rerun vision and assume the new response was approved. Additional pages may need further review. Rejecting a candidate keeps it failed/unsearchable with zero publication. Never hold a lease waiting for a person. No waiting_review lifecycle status is introduced.

The implementation must persist complete extraction independently of vectors. On validated complete-artifact reuse, check original digest, extraction identity, coverage, warnings and trusted attachment. Chunk/embedding changes alone are not a reason to repeat OCR. Partial review candidates can resume QC but cannot bypass complete-artifact validation or create partial publication.

6.2 Factual FAQ gate

Existing chunking requires approved_factual for Q&A. New uploaded FAQs need an explicit admin approval route, not a hardcoded filename exemption or CLI-only flag. D06 exposes factual-corpus review bound to the extraction digest and groups. D07 can record whole Q&A groups excluded because they are behavioral scenarios, placeholders or unapproved facts. Never split a question from its answer.

Preserve the complete faithful extraction/original. Store an inclusion decision separately with reviewer, digest and excluded group IDs. Only approved factual groups form chunk drafts, with original locators; placeholders cannot become answers by virtue of approval. If no reliable groups remain, fail visibly. Existing validation stays enabled; any new manifest-aware preparation boundary requires regression tests. Numeric/source fidelity and authority are distinct.

Factual preparation validates the whole retained source structure before selecting groups. Explicit heading ancestry associates governing headings and introductory conditions with each descendant Q&A pair; existing whole-group context stays exclusive to that pair. Preserve conditions, negation, exceptions and their real locators in every affected draft. Leading unheaded titles/preambles are top-level document context and accompany each approved pair, including pairs under later headings. Detached prose after pairs or unresolved relationships still fail visibly. Factual review exposes that context from the same immutable complete artifact. Reviewer identity/checks/note are bounded review metadata, not machine quality warnings; administrator prose never changes extraction readability decisions.

6.3 Retry, recovery and capacity

Transient network/rate-limit errors use bounded backoff/jitter and the existing retry budget. Permanent malformed input fails immediately. Review-required work waits as failed for a valid decision, without automatic provider loops. Manual retry resets attempts and increments retry_generation on the same job once per key. Source modifications require a new upload.

Maintain file reconciliation and safe redacted diagnostics. Unknown document count requires durable backlog, pagination, disk/quota observation and bounded processing/admission. Configured defaults are deployment choices, not capacity proof. Physical purging and retention periods remain unresolved.

7. Selection, revisions and revocation

organization_settings has three counters: revision for assistant configuration, knowledge_revision for selected-set changes, and access_epoch for knowledge removals. All begin at 1.

Selection update locks the settings row, checks expected_revision against knowledge_revision, validates every selected document is ready/not deleted, and updates the selected flags atomically. If the set changes, increment knowledge_revision. If any document is removed, increment access_epoch too. A no-op preserves counters. Activation alone does not invalidate old conversations; new turns use the current selected set.

Each conversation records access_epoch on creation. For simple safe Phase 1 revocation, any active-document removal invalidates ALL older organization conversations for new turns. Close running live sessions and fail/stop running text turns; preserve old history for authorized viewing. UI asks the user to start a new conversation. No full history is copied into it.

Use settings-row serialization when creating/finalizing turns and initiating live sessions. Text finalization rechecks epoch while holding that row lock; commits before a removal are historical answers, and commits after it must fail as stale. Live tool results are rechecked before sending. Direct audio already sent cannot be recalled; provider close is best effort and must be tested. Logout and session expiry also close owned active live sessions.

8. Deferred text turn execution

This section preserves the follow-up text contract; it is not required by the current Live MVP. No new public text chat or durable message history is required. The internal query harness invokes the SAME scoped search service without implementing this turn lifecycle.

In that follow-up milestone, the UI creates a mode=text conversation, then sends POST /chat with a UUID client_request_id.

In a short transaction: authenticate, lock settings/conversation consistently, verify active conversation/current epoch, resolve the request key, reject another running turn, insert running turn and user message. Set a processing deadline. Then release database locks before provider calls.

Build model context from completed authorized turns within the token budget. Add assistant instruction, tool schema and current question. Treat document text as untrusted evidence, not instructions. A search query argument contains only query text; the server determines organization and selection.

Loop within configured tool-call and time limits. Store normalized tool results and correlate call IDs. Assign source references uniquely across the entire text turn (not separately as S1 for every search); remap tool evidence before returning it to the model. Persist the actual organization instruction in the execution snapshot so a later settings change does not destroy traceability. For substantive document claims, require current search evidence. Validate each cited source against evidence returned during this turn. Structural validation does not prove semantic accuracy; the reference evaluation set checks factual support.

At completion recheck epoch, write assistant message/citations and terminal turn status in one transaction. Terminal statuses: answered, needs_clarification, insufficient_information, failed. Search/provider errors produce failed, not insufficient_information.

If the browser times out, it queries the turn by client request ID. Retrying the same payload returns the existing result or 202 running state. Same key plus different payload returns 409. No automatic regeneration after an ambiguous provider timeout. An interrupted run is marked failed; a new user retry uses a new key. On API restart mark its interrupted running turns failed; periodic deadline cleanup handles stalled tasks. This is intentionally simpler than a durable text job queue.

9. Live lifecycle

Create a fresh owned mode=voice conversation. Persist a session reservation before remote setup, then connect the backend to the pinned Gemini Live/OpenAI Realtime WSS profile, install Persian instructions and search_knowledge, and enable provider transcription. The browser receives an application stream path, never SDP or a persistent provider credential. Authenticate/validate trusted Origin, owner/auth session and access epoch at the stream handshake.

Use the SAME search service and fixed compatible embedding profile as the internal text-query harness and any later text chat. Dispatch search_knowledge through the LangChain integration boundary; do not route native audio through the old text agent. Provider call IDs/hash deduplicate tool events; running duplicates wait, completed duplicates revalidate scope before replay, changed payloads conflict. Store recent evidence for polling. Live answers may use evidence directly; no mandatory extra text-model call. Current-session transcript/source events are specified in API Section 7; durable full voice transcripts are deferred. Persist voice tool records without a dependency on deferred text turns/messages/citations.

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. 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 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 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.

Capture/resample client audio and convert returned PCM for playback as specified in architecture Section 8.5. Test real Persian names, dates, percentages and amounts. CTI/Asterisk is outside this web MVP and would need an explicitly commissioned audio bridge.

10. Internal search contract

Use the canonical proposed search_knowledge schema/outcomes in API catalog Section 7.2. Required query plus optional resolved context; no model-supplied scope. Proposed backend defaults remain top 5 chunks and maximum 12000 evidence characters, to calibrate against the corpus.

Return actual document/chunk identities and nullable source locators. Distinguish ok, no_evidence, error; similarity alone does not prove sufficient evidence. Use semantic pgvector search plus normalized exact identifier/date/article matching as the initial baseline. Full hybrid fusion, reranking and ANN are conditional on measured failures; adding them must preserve all eligibility checks and the deadline must be re-estimated if required. No new vector store.

Queries and all text-derived chunks share a compatible fixed profile. A changed embedding model requires a controlled isolated reindex/cutover; no ready-document republishing through retry or content versioning. Preserve extracted text so OCR need not repeat.

Separate approved factual FAQs from behavioral evaluation/configuration and live-data placeholders. Retrieved instructions are untrusted source data. Without approved live-data tools, explicitly state that current tariffs, land availability, balances and case status cannot be verified; offer an authorized organizational contact/process without claiming an automated transfer.

11. Deployment and configuration

Deploy UI/reverse proxy, one API process, one worker process and PostgreSQL. Mount persistent originals, extraction artifacts and database volumes. Configure HTTPS, cookie domain/origin, provider secrets, approved file formats, size cap, model profile IDs, embedding dimension, tool limits, request deadlines, job lease/retry budget and session TTL. Do not commit secrets. File-size/retention/session durations are deployment choices, not silently approved organization policy.

Readiness checks DB/schema/vector availability and writable/available required storage; report worker heartbeat age as a degraded ingestion indicator. For the single-host release, the worker can update a small heartbeat file on the shared durable volume; a separate heartbeat table is unnecessary. Liveness does not call AI providers. Provider failure must not make login/history unavailable by design. Log request/turn/job/session IDs and redacted error categories; avoid document bodies, audio payloads, prompts, cookies and keys.

12. Tests and handoff

Test group Required evidence
Access/replay Admin/user permissions, voice ownership, Origin/CSRF, forged scope, upload/review/retry/create replay and changed-payload conflict
Worker/database Real PostgreSQL claims, expired/stale leases, heartbeat, failed final batch, rollback, ambiguous commit and restart without duplicate publication
Review/FAQ Trusted retained candidate/digest, stale approval rejection, whole-group inclusion, resume same inspected output and zero chunks before complete approval
Selection Revision conflict, inactive/deleted exclusion and removal closing old context
LangChain Query/document adapter limits/order/compatible preprocessing if wrapper used; tool schema cannot inject identity; same retrieval implementation
Files Both PDFs, infographic, DOCX pair associations plus previously unseen supported files through browser upload
Grounding Independently marked evidence, unsupported/conflicting questions, placeholders and prompt-like source content
Real voice Persian audio/transcripts, actual knowledge tool, follow-up/topic switch/interrupt, provider loss/logout/expiry and fresh-session recovery
Deployment Target HTTPS/microphone/speaker/network and durable file/DB mapping

Map results to MVP-01 through MVP-14 in the delivery plan. Ordinary provider-free tests do not prove hosted model quality; configured PostgreSQL acceptance must not skip missing infrastructure. Existing recorded results are historical, not checks executed by this documentation revision. Run necessary affected checks during implementation; do not extend unrelated component repairs.

Hand off startup/migration/seed/worker/retry commands, configuration, format/ structural bounds, reference questions/unseen-file results, actual latency/ provider evidence, known failures and release revision. Public text/history acceptance stays deferred.

13. Decisions still requiring confirmation

Actual file/page/storage/corpus admission and session limits; factual authority and reviewer availability; fixed funded extraction/embedding/Live identities and vector dimension; account/quotas/Persian capability proof; hosting/connectivity; session TTL, retention/purge, quantitative quality/latency targets and actual presentation date. General browser upload, all four example structures, LangChain, existing embedding reuse and direct OpenAI Realtime are confirmed direction.

Exact-output retention/review, FAQ inclusion decisions and their forward schema/ HTTP mechanisms in this revision are implementation proposals made concrete for review, not already implemented behavior or approval of every fact in a file.

OCR supervisor deployment policy (2026-10-09)

INGEST_OCR_REVIEW_REQUIRED defaults to true and is backend-only. New ingestion jobs freeze the boolean in processing_profile.extraction.ocr_review_required (the existing immutable document-owned snapshot for its one job). Workers and retries use that snapshot; absent fields in legacy profiles mean true. Preserve existing profile bytes/digests; do not backfill applied records. False permits clean OCR/vision output that passes existing automatic validation without a human extraction decision. It never waives non-OCR review, warning/integrity/coverage checks, independent factual-corpus approval, or explicit knowledge selection. Automatic extraction remains quality_decision=passed; mixed inspected/automatic PDFs use partially_reviewed with annotations only for inspected locators. Neither automatic OCR nor its portions in mixed PDFs creates a human review annotation/audit record. Ready publication remains inactive. Retained pending or rejected candidates still block retry; deployment changes cannot waive them. F01 capabilities.ocr_review_required is current deployment policy; D03 reports frozen ocr_review_required, review_state and extraction_quality_decision. See Phase 3 handoff.

Phase 3/4 recognition and transport-testing amendment (2026-10-09)

Vision complete=false and recognition warnings preserve nonempty legible candidate blocks with their diagnostics. They force exact-output extraction review even when the job's frozen OCR supervisor policy is false. They are not complete validated artifacts until genuine review approves completeness and the other required checks. Malformed/empty/truncated native output, invalid provenance/relationships, unreadable source text and bounded input/output violations remain fatal. Warning wording alone is not evidence of corrupt source text. Retained approved candidates resume without repeating vision; separate factual approval and explicit knowledge selection remain.

VOICE_TRANSPORT_TESTING defaults false. Explicit true permits authenticated voice transport testing without finalized calibration, after configured embedding adapter construction validates credentials, identity and request limits without inference. Uncalibrated reservations pin transport_testing and embedding identity in the existing execution_profile JSON and expose calibration_status=uncalibrated through create, recovery and poll. Shared canonical retrieval still returns CALIBRATION_REQUIRED with no evidence; no arbitrary threshold or synthetic calibration is installed. Current policy/profile must still match the reservation on stream admission; policy changes cannot silently upgrade, downgrade or switch a reserved provider. Health remains provider-free. Real voice/retrieval quality acceptance remains separate.

OpenAI limited-answer workflow (2026-10-12)

Apply the voice API generation-limit amendment to existing Live machinery. Pin and acknowledge the server per-response budget for new sessions, including tool continuations. Do not backfill old execution profiles. OpenAI calls stage until validated successful terminal output; a cut-off tool phase fails safely. Validated audio-only max_output_tokens termination remains incomplete/limited, drains existing output credit, and retains normal interruption/truncation and 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.

Live declared-source amendment ? 2026-10-13

search_knowledge and reuse_last_evidence still give the model the complete eligible evidence bundle. They no longer publish every retrieval candidate as an answer citation. Before a document answer, the model calls internal report_used_sources with exactly {"source_refs":["S1","S3"]} (or an empty list when no passage supports the answer). Labels must be unique, bounded and belong to successful evidence already delivered to the same turn. Backend-owned document/chunk identities and excerpts are resolved from those originals; forged labels, scope/identity fields and prior-turn labels without revalidated reuse are rejected. No source report creates a durable retrieval row.

Only declared labels are emitted through the existing sources event, grouped by their real retrieval's tool_call_id. Revalidate original durable results before report output, source delivery and answer continuation; interrupted or revoked evidence must never become citations. Missing/invalid reports do not fall back to displaying every candidate. Multiple reports add to the set of sources declared during the turn; event/call replay remains idempotent. Polling recent_tool_results remains explicitly retrieval diagnostics, not declared answer citations. Declaration is model attribution, not independent proof of claim-level support or which spoken words were heard. No new public endpoint, database table or durable transcript is introduced.

New reservations pin evidence_policy_revision=same-session-evidence-selected-v2; OpenAI delivery style is iranian-persian-professional-v5. An optional pre-tool acknowledgement is only «یه لحظه…», at most once per turn. No acknowledgement is needed when the answer can start directly. Suppression of longer preambles is an instruction, not a guarantee inferred from synthetic tests. Existing pinned reservations are never rewritten; use a new session after this deployment.

Source-report recovery - 2026-10-13

Invalid report_used_sources arguments are recoverable provider-tool feedback, not browser error events. Unknown-label feedback includes server-derived available_source_refs for the current turn; an empty set requires revalidated reuse or a fresh search (or an empty report after no_evidence). Invalid reports still emit no citations, never fall back to all candidates and cannot widen scope. Other tool/runtime errors retain their browser error behavior. Current new reservations use evidence policy same-session-evidence-selected-v3 and OpenAI delivery iranian-persian-conversational-v6. Existing pins are preserved. Numeric source-report traces record requested/available/rejected counts only.

Abandoned OpenAI tool resolution - 2026-10-13

After interruption terminal confirmation and existing audio cleanup barriers, the OpenAI adapter supplies a private function_call_output with status cancelled and empty sources for each interrupted call whose output was never sent. These metadata-only outputs precede the next current-turn response.create and undergo current authority and supersession checks. They do not validate or disclose old evidence, create retrieval rows, resume the old response or rewrite durable tool status. Delivered tool outputs are not emitted again; late retrieval results remain suppressed. Gemini retains its existing native interruption behavior. Existing bounded send/correlation failures remain terminal; no blind send retry. New sessions use evidence policy same-session-evidence-selected-v4.

Official wire reference: https://developers.openai.com/api/reference/resources/realtime/client-events (function_call_output accepts a string associated with the original call_id).

Session provider-event replay capacity - 2026-10-13

Finite LIVE_MAX_EVENTS default and validated upper bound are now 32768, replacing 4096. This counts all unique provider event IDs over the session, including audio/transcript deltas; it is not an outstanding audio buffer. The full ID-to-digest ledger remains retained: identical replay is ignored, changed-payload replay fails, and cap exhaustion still closes with LIVE_BUFFER_OVERFLOW. No eviction or duplicate audio replay is introduced. Only this metadata capacity increases; other audio, message, identity and turn bounds remain independent. This increases maximum replay-ledger memory eightfold; it does not establish unlimited duration or deployment concurrency acceptance.

Retain one same-topic search across speech interruption - 2026-10-13

This user-authorized amendment supersedes cancellation of the retained search on ordinary speech interruption. Playback/old response cancellation remains immediate under the existing terminal, audio cleanup and authority gates. The latest real search has a separate cancellation token and its original deadline; interruption of a turn or a reuse waiter does not cancel that search or reset its time budget. Keep its result private until explicitly reused/revalidated for a current turn. turn_interrupted.cancelled_tool_call_ids excludes the retained search; other cancelled operations retain their existing semantics.

reuse_last_evidence still accepts only {}. For a repeated question or clear same-topic continuation, it awaits the retained search if necessary, then revalidates the original durable row against current identity/session, access epoch, knowledge revision and document eligibility. It retains document/chunk IDs and the actual public retrieval reference, and assigns source labels using the new turn's backend execution. It creates no retrieval row. Reporting sources still selects only current delivered labels. No old response resumes or emits its late evidence. Technical errors do not become fabricated no-evidence answers.

A fresh search in a later turn for a different query discards/cancels the old retained search and starts a new topic. An exactly identical validated search argument object in a later turn can coalesce through the same revalidation path, even if the model chooses search rather than reuse. Semantic equivalence of differently phrased queries remains the model's explicit reuse decision; the backend performs no fuzzy scope or question matching. Session stop, failure or close cancels independent searches. Expiry/revocation still fails safely; this is not cross-session caching or reuse of assistant prose. At most the latest search is retained for continuation; existing tool/task/session bounds apply.

The OpenAI interruption function output closes the old private response's call with empty metadata and directs same-topic continuation to reuse. Its cancelled status does not declare cancellation of the separately retained backend search. Gemini continues to use its native interruption transport. New reservations use evidence_policy_revision=same-session-evidence-retained-v5; existing pins are not rewritten. No schema/table migration or new public endpoint is introduced.