Files
rag-technical-docs-assistant/docs/plans/archive/local-s2s-eight-phase/plan.md
T

459 lines
26 KiB
Markdown

# Local speech-to-speech adapter: phased implementation plan
Date: 2026-10-15. Status: **planned; implementation and live acceptance not started**.
## 1. Outcome and scope
Add `local_s2s` alongside OpenAI and Gemini. Keep the OpenAI implementation usable,
preserve its behavior, and retain the original operational API container/image for
rollback. Initially run orchestration/VAD locally and obtain STT, a tool-capable
text LLM and TTS through OpenRouter. Local orchestration is not offline inference.
Replacing individual stages with local models is a later independent optimization.
This is a plan, not authorization to switch the running application, download
weights or perform unbounded paid evaluation. Each phase has a tangible demo,
acceptance criteria, evidence and a copy-ready English prompt. No phase has run.
## 2. Target architecture
```mermaid
flowchart LR
Browser[Existing Angular browser] <-->|Application PCM and JSON| API[FastAPI and VoiceRuntime]
API --> Tools[Existing tools and SearchService]
Tools --> Data[(Authorized knowledge)]
API --> Boundary[Small internal provider boundary]
Boundary <--> OA[Existing OpenAI adapter]
Boundary <--> GE[Existing Gemini adapter]
Boundary <--> LA[New local_s2s adapter]
LA <--> Engine[Pinned speech-to-speech service]
Engine --> VAD[Local VAD]
Engine --> STT[OpenRouter STT]
Engine --> LLM[OpenRouter text LLM]
Engine --> TTS[OpenRouter TTS]
```
The engine emits tool requests; our backend executes them. It receives no separate
database authority. Browser clients continue to use our API, never a public engine
endpoint or an OpenRouter key.
| Concern | Owner |
| --- | --- |
| Identity, organization, permissions and revisions | Existing application services |
| Turn ownership, deadlines, playback credits, evidence lifetime, next-turn release | VoiceRuntime |
| Native wire events/requests, error classification and configuration proof | Provider adapter |
| Actual local cancellation/history mutation and authoritative receipt | Pinned engine plus a minimal versioned extension when necessary |
| Recognition, text generation and synthesis | OpenRouter initially |
| Search/reuse, document eligibility and used-source validation | Existing knowledge services and DurableTools |
| Browser PCM and JSON contract | Existing application API contract |
### Boundary design
Normalize semantic events/operations actually required by runtime: effective
setup, consumed input, speech boundaries, generation identity, audio/transcript,
tool request and terminal outcome. Preserve native identity/provenance and replay
fingerprints. Do not turn an arbitrary transcript into a fake input-commit ack.
Interruption has separate generation-stop and history-repair progress. Runtime
supplies the response/item, session generation and final played coordinates; the
adapter establishes the actual result and runtime retains authority to release
the next turn. The receipt must identify the operation and applied state revision.
A boolean success flag, elapsed timer or sent request is insufficient proof.
Keep OpenAI's cancel/terminal/truncate/ack behavior intact behind this boundary.
Gemini's unsupported repair remains fail-closed. Prefer a small protocol/data model
to a plugin registry, event bus or wholesale state-machine rewrite.
## 3. Upstream evidence and hard compatibility gaps
Upstream documents a cascade and a core Realtime interface, not full OpenAI API
equivalence. Its documented conversation.item.truncate is a no-op without an ack.
Pin a commit and inspect its actual implementation/tests; changing the endpoint
URL alone cannot meet our cleanup contract. Sources:
[repository](https://github.com/huggingface/speech-to-speech),
[Realtime contract](https://github.com/huggingface/speech-to-speech/blob/main/src/speech_to_speech/api/openai_realtime/README.md).
HTTP STT progressive updates can repeatedly upload cumulative utterances. Remote
TTS cancellation can stop local publication without proving remote compute stopped.
These affect cost and late-result handling. Sources:
[STT backend](https://github.com/huggingface/speech-to-speech/blob/main/docs/openai-compatible-stt.md),
[TTS backend](https://github.com/huggingface/speech-to-speech/blob/main/docs/openai-compatible-tts.md).
OpenRouter documents separate STT/TTS endpoints and LLM tool calling. Model IDs,
voices, Persian behavior, supported parameters and rates require actual checks:
[STT](https://openrouter.ai/docs/guides/overview/multimodal/stt),
[TTS](https://openrouter.ai/docs/guides/overview/multimodal/tts),
[tools](https://openrouter.ai/docs/guides/features/tool-calling).
### Critical case: completed generation, unplayed audio
A model can finish text/audio while the browser has heard only the beginning.
Cancel may then do nothing, leaving unheard assistant prose in engine history.
Test the actual next LLM request, not only audio queue state or terminal flags.
Closing HTTP, clearing playback and returning response.done do not establish repair.
Do not infer a text prefix from audio-duration ratios or character counts. If
reliable heard-prefix alignment is unavailable, keep the gate open. Dropping an
entire interrupted assistant turn or retaining only fully played segments is a
weaker alternative policy requiring explicit acceptance and documentation; never
silently present it as exact heard-prefix preservation.
## 4. Invariants
1. OpenAI remains available. No automatic cross-provider fallback, new UI provider
selector or mid-session provider switch. Freeze effective configuration.
2. Keep original API containers/images and unrelated changes. No database reset,
pruning, compose down, rewriting old snapshots or document-content versioning.
3. Keep browser PCM16LE mono 24 kHz in both directions and existing public events.
4. One canonical search implementation, calibrated cutoff, document/chunk identity,
ready/active/authorized/undeleted filtering and final delivery revalidation.
5. Used-source membership validation is not full factual-entailment verification.
6. Generation completion differs from playback completion. Retained searches have
a lifetime independent of speech cancellation and retain their original deadline.
7. Bound queues, bytes, concurrency, deadlines and retry counts across all stages.
Do not stack automatic retries at multiple layers or conceal latency with buffers.
8. Secrets stay server-side. Default logs contain fixed categories/numeric state,
not complete provider payloads or real speech/document text.
9. Separate offline tests, isolated PostgreSQL acceptance, provider smokes and human
listening. Mock success or skipped checks do not prove live acceptance.
10. Never start a second API against the operational database. app/main.py invokes
lifecycle.reconcile_startup, which reconciles active sessions globally. A
different HTTP port alone is not isolation.
## 5. Phase overview
| Phase | Visible result | Operational effect |
| --- | --- | --- |
| 0 | Baseline and protocol compatibility report | None |
| 1 | Existing OpenAI interruption replay still passes through the new boundary | None; refactor only |
| 2 | Independent Persian audio -> text -> response -> playable audio demo | Isolated engine only |
| 3 | Existing browser greets and closes through local_s2s | Isolated test API/database only |
| 4 | Real interruption and coherent continuation; verified repaired history | No promotion until proof |
| 5 | Document answers, retained search and correct source subset | Isolated end-to-end RAG |
| 6 | Paired OpenAI/local quality, latency and cost scorecard | Promotion decision evidence |
| 7 | Authorized deployment switch and demonstrated OpenAI rollback | Controlled opt-in switch |
Phases run in order. Phase 2 engine preparation may proceed independently of Phase
1 when it does not depend on application changes. Never accept a later gate merely
because code exists. Do not combine the OpenAI refactor and operational switch.
## 6. Phase 0 - Baseline and immutable upstream audit
**Visible outcome:** Open a report showing OpenAI baseline, upstream support,
required changes and proof tests side by side. Replay an existing offline trace.
**Work:**
- Read applicable instructions, reference map and governing API/database/workflow
sections. Inspect current source and deployment; historical defaults are stale.
- Record active/preserved container IDs, image digests, selected profile, ports and
storage mounts without keys/full environment dumps. Do not recreate containers.
- Pin an upstream SHA and build inputs; record license and patch policy.
- Audit effective session config, input acceptance, VAD/commit boundaries, manual
response control, metadata/identity, tools, audio rates, terminal states,
transcripts, cancellation and history repair against actual source/tests.
- Run focused baseline tests; distinguish existing failures from new defects.
- Prepare Persian fixture questions and expected answers against an authorized
frozen test corpus. Record outstanding product/implementation decisions.
**Accept when:** baseline/rollback identities exist; each required behavior is
verified, requires a specified patch, or is explicitly unverified; every live
prerequisite is visible. No runtime/data changes occurred.
**Stop/narrow:** unknown upstream behavior remains unknown. Missing credentials
block live checks, not read-only inspection or deterministic preparation.
**Prompt:** [Phase 0](local-s2s-adapter-prompts/phase-00.md).
## 7. Phase 1 - Small provider boundary, OpenAI preserved
**Visible outcome:** Replay the same interruption before/after extraction: old
output stops, the same played position is respected and exactly one next response
is released. OpenAI remains the selected provider.
**Work:**
- Implement minimal typed operations/events; runtime keeps turn/authority/release,
playback bounds and evidence state. Adapters own provider wire interpretation.
- Move OpenAI native cancel/terminal/truncate mechanics behind the boundary without
changing semantics. Do not lose raw event fingerprints/correlation on normalization.
- Represent interruption with an operation ID, response/item/session identity,
generation-stop and applied-history progress, and finite deadlines.
- Do not introduce capability switches that waive cleanup. Unsupported capabilities
reject admission or fail safely. Preserve Gemini's conservative behavior.
- Add controlled-clock replay and regression tests. Document the internal contract
amendment; browser wire contracts remain unchanged.
**Accept when:** existing OpenAI tests retain assertions and pass; terminal/error
orderings, missing/wrong acknowledgements, duplicates, late events, incomplete
responses and bounds remain covered. Shared control has no model/voice branches.
Run isolated PostgreSQL cases if persisted profiles/lifecycle behavior is touched.
**Stop/narrow:** no full runtime rewrite or blanket provider-error suppression.
**Prompt:** [Phase 1](local-s2s-adapter-prompts/phase-01.md).
## 8. Phase 2 - Isolated engine with OpenRouter stages
**Visible outcome:** Submit a Persian recording to the independent smoke, inspect
its explicitly requested test transcript, hear a WAV response and see stage usage
and timing. The application remains untouched.
**Work:**
- Build the pinned engine in a separate image/environment with local VAD, HTTP
STT, Chat Completions LLM and HTTP TTS. No default local model downloads.
- Discover/pin available models/voices and validate Persian hints, tool support,
endpoint fields, rates and audio formats. Models are independently configurable.
- Keep the key inside the engine. Custom endpoints must not accidentally receive
another provider's credentials. Keep engine access behind the application boundary.
- Start with final-utterance STT, not cumulative HTTP retranscription.
- Verify actual multipart/JSON STT and TTS stream_format/PCM compatibility; add only
a narrow observed-mismatch shim if necessary.
- Bound and meter startup probes, generation, response sizes, retries/concurrency
and close. Provide deterministic stubs and an opt-in bounded live smoke.
**Accept when:** with live prerequisites all stages complete and audio is valid;
otherwise mark live-pending. Bad key/model/voice/rate fails setup accurately. Save
sanitized timing/usage and consented fixture outputs, not secrets or raw user logs.
**Stop/narrow:** do not install every optional model/GPU dependency. Credential or
model availability gaps do not authorize fabricated success.
**Prompt:** [Phase 2](local-s2s-adapter-prompts/phase-02.md).
## 9. Phase 3 - Local adapter and normal browser session
**Visible outcome:** In an isolated test app, open the existing browser, say hello,
hear a Persian answer, see a transcript, and close cleanly. Show a local_s2s pinned
profile. This milestone is development-only, not production parity.
**Work:**
- Add local_s2s configuration/factory selection while keeping openai/gemini.
- Freeze engine/patch revision, internal protocol revision, STT/LLM/TTS identities,
voice, input policy, rates and effective instruction/config digest. No secrets
or credential-derived hashes belong in database execution profiles.
- Define the expected configuration and compare to authoritative engine state.
A reachable socket or echoed request is insufficient setup proof.
- Map actual consumed input, manual response identity/metadata, audio/transcript,
terminal and tool events. No invented native commits/acknowledgements.
- Preserve browser 24 kHz PCM; use stateful bounded conversion where required,
including correct playback-position units.
- Preserve owner/Origin/cookie/CSRF/replay/epoch checks. Inspect schema/DTO/provider
constraints; use a new migration only if necessary, never edit an applied one.
- Use disposable database/storage and isolated test browser identity/origin.
Until Phase 4, unsupported interruption must fail safely and be labelled as such.
**Accept when:** ready/audio/transcript/close work; bad configuration, wrong owner,
old epoch, mismatched profile, malformed terminal and disconnect cannot pass
silently. Existing profiles are not rewritten; a new session pins new settings.
**Stop/narrow:** a second port with the same operational DB is prohibited. No
promotion or hidden fallback before interruption and RAG gates.
**Prompt:** [Phase 3](local-s2s-adapter-prompts/phase-03.md).
## 10. Phase 4 - Verified interruption and history repair
**Visible outcome:** Interrupt a long answer, ask a follow-up, and get a coherent
reply without stale audio. In a controlled test, show the actual next LLM input
contains no unheard sentinel that was generated later in the interrupted answer.
**Work:**
- Implement a real correlated engine operation/extension if the pinned version
cannot repair history. Keep a reproducible versioned patch with independent tests.
- Cover active generation AND completed generation with unplayed buffered audio.
- Track item/response/segment/session identities, final consumed position and
reliable assistant text/audio alignment. Never use character/duration ratios.
- Keep valid prior turns/user/tool state; remove unheard assistant continuation
from future generation input. Expose applied history revision/digest as proof.
- If exact repair is unavailable, stop this acceptance gate. Conservative whole-turn
rollback or fully-played-segment-only history needs explicit policy acceptance.
- Admit a receipt only after mutation; reject stale, conflicting, wrong-identity
or missing receipts. Runtime retains deadlines and final authority to continue.
- Suppress late STT/LLM/TTS results even if remote computation cannot be cancelled.
Keep latest backend retrieval independent from speech cancellation.
- Repeat OpenAI regressions; the new local proof must not weaken native OpenAI gates.
**Accept when:** no next turn before generation stop, real repair and playback gates;
active and completed-unplayed cases pass; late work cannot reach another turn;
missing/wrong proof fails safely. No fake conversation.item.truncated event.
**Stop/narrow:** this is the highest-risk phase. Audio stopping or a stock-SDK
compatibility claim does not prove our context semantics. Keep promotion blocked.
**Prompt:** [Phase 4](local-s2s-adapter-prompts/phase-04.md).
## 11. Phase 5 - Existing RAG tools and used sources
**Visible outcome:** Ask hours/Thursday, the planning deputy in the specific letter,
and the incentive percentage/dates/exclusions. Interrupt a pending search and
repeat the question; show one retrieval plus revalidation and relevant UI sources.
**Work:**
- Expose search_knowledge, reuse_last_evidence and report_used_sources to the new
LLM. Execute through existing dispatch/ToolContext/DurableTools/SearchService.
- Preserve backend identity, calibrated retrieval, document/chunk references and
handoff/delivery eligibility. Engine gets no independent retrieval path.
- Validate streamed arguments after successful terminal validation; correlate
response/item/call identities and deduplicate repeats/replays.
- Reuse same-topic pending results within original deadline, revalidate, and discard
changed-topic results. Never use earlier assistant prose as document evidence.
- Validate current-turn source labels and correct invalid reports privately. Do
not show every candidate or persist metadata reports as extra retrievals.
- Exercise ok/no_evidence/error, token-limited tools, interrupted delivery,
revocation/deactivation and all known Mini factual failure cases.
**Accept when:** all three tools retain existing authority; no stale evidence or
extra retrieval on same-topic reuse; used subset has original document/chunk
identity. Correct citation membership is not claimed as full factual verification.
**Stop/narrow:** no weakened cutoff/filter or second search implementation to hide
model-quality problems.
**Prompt:** [Phase 5](local-s2s-adapter-prompts/phase-05.md).
## 12. Phase 6 - Persian quality, latency, cost and resilience
**Visible outcome:** A paired OpenAI/local scorecard and audio samples show the
actual trade-off. Demonstrate a controlled provider failure without contamination.
**Work:**
- Evaluate the same authorized frozen corpus and paired Persian audio/question
fixtures. Keep exact baseline/candidate component profiles and sample counts.
- Cover names/roles, numbers/dates, natural pauses, noise, self-correction,
ambiguity, continuation, topic switch, no evidence and document conflicts.
- Measure speech-end-to-first-audible-sample, tool time, first text/audio,
interruption-to-stop, underruns, duplicates, disconnects and task completion.
- Count cached/input/output usage when available, STT duration, TTS billed units,
startup probes, failures and abandoned work. Missing usage stays unknown. Compare
cost per successful task, not only successful API requests.
- Fault-inject slow/down providers, quotas, stream loss, restart and saturation.
Prove bounded queues, late-result suppression and no stacked retry storms.
- Change one component at a time. Human listening is separate from transport tests;
do not claim that a better LLM repairs bad transcription.
**Accept when:** all critical factual fixture assertions pass with zero invented
names/numbers/dates/conditions; all intended interruption cases pass or fail safely
as specified; results assess predeclared targets and expose all failures.
Provisional goals, to accept or revise explicitly BEFORE evaluation: p95 first
audible response <= baseline + 1 second, no persistent underruns, and cost per
successful task <= 70% of baseline for a cost-saving promotion. These are targets,
not measurements or universal guarantees. If quality/cost goals fail, keep OpenAI.
**Stop/narrow:** missing actual provider/human evidence leaves the gate open. Do
not broaden prompts/buffers or silently change thresholds after seeing results.
**Prompt:** [Phase 6](local-s2s-adapter-prompts/phase-06.md).
## 13. Phase 7 - Controlled switch and demonstrated rollback
**Visible outcome:** Demonstrate a local document interaction, then stop the
candidate, start the preserved OpenAI API without rebuild, and repeat the question.
Leave the selected provider in the final state explicitly requested by the user.
**Work:**
- Finalize opt-in Compose and .env.example; OpenAI stays default until an explicit
operational switch. No automatic fallback or UI provider selector.
- Verify original container/image/config retention. Candidate gets separate tags;
never prune, remove, overwrite or rebuild the original rollback target.
- Check effective setup, health, secrets, bounds and database compatibility before
switching. An incompatible migration blocks simple old-container rollback.
- Drain/close current sessions, stop the existing API, then start the candidate on
the operational DB. Never two application APIs against that DB simultaneously.
- Test a fresh browser session: greeting, RAG, used sources, interruption and close.
- Actually exercise rollback and verify readiness plus a fresh OpenAI session.
Container rollback is not database/filesystem rollback or media-session resume.
- Record commands, identities, fingerprints, checks, final state and limitations.
**Accept when:** preserved OpenAI restoration succeeds; user/ingestion data is
preserved; one API owns the operational lifecycle at a time; session profiles stay
pinned. Health readiness alone is not speech/RAG acceptance.
**Stop/narrow:** prepare all reviewable work first. Without the operational switch
authorization, compatibility or live evidence, stop before changing the service.
**Prompt:** [Phase 7](local-s2s-adapter-prompts/phase-07.md).
## 14. Configuration, data and deployment contract
Proposed names below must be finalized before implementation and documented with
units/defaults. Do not create unvalidated option bags or leak credentials to LLMs.
| Scope | Proposed configuration |
| --- | --- |
| Selection | VOICE_PROVIDER=openai / gemini / local_s2s |
| Engine access | LOCAL_S2S_ENDPOINT and optional server-to-server credential |
| Identity | LOCAL_S2S_ENGINE_REVISION, adapter contract revision, effective config digest |
| Models | LOCAL_S2S_STT_MODEL, LOCAL_S2S_LLM_MODEL, LOCAL_S2S_TTS_MODEL, LOCAL_S2S_TTS_VOICE |
| Policy | STT language/final-only mode, LLM limits, TTS rate/format and verified options |
| Credentials | OpenRouter key only in engine component clients; never in database profile |
| Bounds | Connect/request/repair/close deadlines, queue bytes/items/concurrency |
Start with fixed component identities per engine configuration. Reservation
expectations must match authoritative engine state; never silently mutate shared
global models on every session.update. Later multi-profile concurrency requires a
separate isolation design.
Candidate API acceptance uses an isolated PostgreSQL/pgvector database and storage.
Cookies are not port-isolated: use a dedicated test hostname/browser profile and
credentials with matching trusted Origin. Do not copy production auth sessions
into a parallel test browser. Operational switching runs only one application API.
No schema migration is assumed. Inspect provider constraints/DTOs/profile replay
in Phases 0/3; use a new migration only if required and verify rollback image
compatibility. Do not add document_versions/version_id/version_no.
## 15. Validation commands and evidence
Verify paths and side effects at execution time. Focused baseline command:
```powershell
.venv/Scripts/python -m pytest tests/unit/test_live_context_sync.py tests/unit/test_realtime_repairs.py tests/unit/test_voice_retained_search.py tests/unit/test_voice_reported_sources.py tests/unit/test_openai_output_limit.py tests/unit/test_phase2_provider_selection.py tests/unit/test_openai_persian_style.py -q
```
Broaden when shared behavior changes justify it:
```powershell
.venv/Scripts/python -m pytest -m "not postgres"
git diff --check
```
Only with a verified disposable TEST_DATABASE_URL:
```powershell
.venv/Scripts/python -m pytest -m postgres --require-postgres
```
Existing timing/Windows failures must be recorded, not hidden by weakening tests.
Ordinary-suite skips do not establish PostgreSQL acceptance. Future local smoke
and conformance commands are phase deliverables, not existing verified commands.
Each phase produces docs/evaluation/local-s2s/phase-NN.md with scoped diff/commits,
exact commands, results, counts, fingerprints, visible demo, actual vs simulated
observations, not-run checks, blockers and rollback relevance. No keys/raw real
conversation logs. Save audio/transcripts only as explicitly consented evaluation
artifacts. Upstream CI success is not our runtime compatibility evidence.
Progress ledger: [local-s2s-adapter-progress.md](local-s2s-adapter-progress.md).
Prompt index: [local-s2s-adapter-prompts/README.md](local-s2s-adapter-prompts/README.md).
States: not_started, in_progress, offline_complete_live_pending, blocked, accepted.
Only accepted closes a required gate. Missing paid authorization blocks dependent
live work, not independent preparation. Reuse existing bounded authorization; do
not ask the user to approve the same action repeatedly.
## 16. Decisions to resolve and definition of done
- Upstream SHA, dependency/build lock and maintained patch provenance: Phase 0.
- Effective profile/config attestation and concurrent engine isolation: Phase 3.
- Real heard-prefix mapping/receipt: Phase 4 hard gate; weaker policy requires an
explicit product decision and intentional API/workflow documentation.
- Available OpenRouter models/voices, Persian quality, hardware footprint and
latency/cost: measure, do not infer from default local-model examples.
- Any future local weight licensing is checked for the chosen model separately.
- Candidate promotion follows evidence, not an assumption that local is cheaper.
Done means independently selectable local_s2s, working OpenAI, unchanged trusted
RAG authority, browser compatibility, real correlated history repair, bounded
failure handling and recorded Persian quality/latency/cost acceptance. Restoring
the compatible preserved OpenAI container has actually worked. Missing real or
human acceptance remains a blocker, not a completed implementation.