Files
rag-technical-docs-assistant/services/local_s2s
11linear11 a94b8cd3ea feat(voice): implement local S2S retained history and provider selection
Add pinned CPU engine dependencies, retained interrupted-response history, provider admission, offline evaluation and isolated browser tooling.

Record Phase 2 acceptance and Phase 3/4 preparation, bounded paid-test accounting and interruption incident findings. Human interruption acceptance, paired OpenAI evaluation and rollback remain pending.
2026-10-16 17:09:27 -04:00
..

Phase 2 local engine (development only)

Current preparation (2026-10-16): Phase 4 frontend/provider selection and paired evaluation tooling. Phase 3 retains interrupted answers as explicitly unheard drafts per the user's revised policy; real barge-in/RAG/factual acceptance remains pending. Phase 4 is prepared for isolated testing, not deployed or accepted. No new paid request, audio tuning or operational switch. Earlier checkpoints below are historical.

Current verdict (2026-10-16): Phase 2 accepted for isolated development-only normal Persian browser voice. Final evidence and machine-readable results: 125 local + 258 preservation + 63 PostgreSQL tests passed; actual browser response fully played and closed normally. Conservative cost exposure $0.420504399, below the same $1 cap; final invoice details remain unresolved with full reserves held. Paid engine stopped normally. No buffer/speed change or operational promotion. Phase 3/4 remain not_started. Earlier checkpoints below are historical and are superseded where they describe open Phase 2 gates.

Current incident follow-up: first browser-turn initialization stall repaired. User session failed after transcription. Native snapshots identified first-reply Lingua model preload; same cache now warms before listener readiness. Three full proxy/API/native continuous-input fixture sessions and98 focused tests pass. Fixed image a51167d1952a; no buffer/speed/timeout change. Repair handoff carries all prior attempts; cumulative reservation ceiling $0.995118333 of the same$1. Human browser acceptance remains open; earlier ready checkpoints below are historical.

Current browser handoff (2026-10-16): isolated browser is ready. Angular/API/login and actual proxied WebSocket session_ready/normal close passed; no inference in connection check. Three real startup probes passed. Human microphone/ reply/transcript acceptance remains open. Same $1 authorization; reconciled prior exposure $0.689118333, cumulative ceiling $0.901118333, startup reserve $0.748118333. Private login file and 30-minute engine watchdog documented. No tuning/operational change.

Latest actual run (2026-10-16): real native Persian round trip passed. Six actual requests succeeded, 2.528s reply audio, successful terminal/normal release and clean shutdown. Cumulative reservation is $0.998 of the same $1; final billing remains unresolved, so no further paid request. User accepted native output; browser/microphone remains open; earlier memory blocker below is historical. No operational switch or audio tuning change.

Latest preparation (2026-10-16): bounded real native session. Single-sample pronunciation accepted by the user. Cumulative reservation ceiling is $0.998 including the retained $0.56; no new paid request. Real launch awaits

5GiB host headroom. Budget/runner checks and actual native fixture pass; browser and real session acceptance remain open. Audio tuning and operations unchanged.

This stack is isolated from operational OpenAI. Phase 1 live acceptance passed on the isolated Linux candidate; see the current evidence below. Local engine conformance/assets and bounded live authorization remain separate activation gates. Offline tests do not prove real local_s2s Persian voice.

Offline result now

Real component follow-up 2026-10-16: authorized $1 component evidence. Actual PCM TTS/Kore, Whisper STT and GPT-4.1 mini succeeded after an initial WAV HTTP400. Generated Persian audio is 5.16s; human listening is pending. Four attempts, $0.56 retained reservation; STT+LLM reported about $0.00033833, TTS/final billing not yet verified. Do not bypass the exclusive paid ledger to rerun. Real browser/native integration remains open; no engine startup, tuning or operational change occurred.

Native session 2026-10-16: actual session/audio/signals and memory incident. Candidate phase2-session-fix-v2, immutable ID sha256:89c7295e521903c16b8ab72f8049b8166ceeb718ac7d531b815dd5d7613dea7b, passed normal native PCM/transcript/intent/close, setup mismatch, OS-signal and fixture-provider failure checks. 110 focused tests pass. Gateway/client shutdown now precedes dependent waits. Run the report's guarded sequential runner; earlier parallel 4GiB tests coincided with an actual IDE OOM kill. Audio limits/tuning and existing deadlines are unchanged. Cold/one-core failures remain disclosed; real component/Persian browser acceptance remains pending. No paid calls or downloads.

Queue repair 2026-10-16: corrected candidate evidence. The type-compatible subclass resolves Queue[Any] construction without changing the 256-item bound or overflow stop. Separate image phase2-queue-fix, ID sha256:6ad4a6a418ef3122923724760b9b2fa8e55cd7db10189614492f5e2b1dc23a74, passed actual asset-backed construction, three fixture warmups, typed queue/FIFO/ overflow and cleanup checks. 109 targeted tests passed. The original image/tag and Compose defaults are preserved; native-session/audio/POSIX gates remain open.

Authorized asset acquisition 2026-10-16: actual evidence and constructor failure. The required resources now exist under .local-s2s-build/assets-linux/; the 14-file Linux manifest is docs/evaluation/local-s2s/phase-02-linux-assets.json, SHA-256 869eb6be1f444ecded8908b9339078cc5845df367207a63ed28173c4974dca26. Actual NLTK POS and Silero JIT/silence checks pass in the image. Full construction fails because the Queue lambda cannot serve upstream Queue[Any] annotations. No runtime fix applied during downloading; resolve this before real startup.

Follow-up 2026-10-16: asset inventory and Linux signal subset. Four actual SIGINT/SIGTERM checks passed against lifecycle/gateway with fixture runtime/provider I/O. Existing punkt data loaded inside the image; NLTK POS tagger and Silero source/JIT resources are still missing. This does not close full-engine or native-worker signal acceptance. The report includes the repeatable offline command; no runtime edits, downloads or paid calls occurred.

Latest 2026-10-16 result: image rag-local-s2s-candidate:phase2 built successfully, ID sha256:5c80c77c54da4641318e69cdb8fff092391cd746e491fa8029280c2999ce27d1. 15 native imports, six actual-handler/SDK controlled-I/O scenarios, two startup guards and 423 provider-free regression checks passed. See docs/evaluation/local-s2s/phase-02-image-build-20261016.md for exact evidence and limitations, including the unused CUDA-tagged upstream TTS wheel. Earlier missing build/native-import statements below are historical. Do not start paid engine initialization as a health check; real NLTK/VAD resources and full-engine tests remain prerequisites. No operational provider or voice tuning changed.

Latest Linux preparation: Phase 1 OpenAI preservation acceptance is recorded in docs/evaluation/local-s2s/phase-01-linux-preparation.md. A full 134-package Python 3.11/Linux CPU hash lock and wheel-only dry run are now available; see docs/evaluation/local-s2s/phase-02-dependency-lock.md and the adjacent requirements-linux-cpu.in, cpu-constraints.txt, requirements-linux-cpu.lock. This supersedes the older missing-lock/base/source statements below. Engine build/import/conformance/live acceptance remain open. Use the report's verified trixie amd64 base digest, not the earlier Windows digest. The CPU constraints pin two exact official wheel URLs; other packages resolve only from PyPI.

For a fresh build workspace, run the existing preparation helper with the report's base digest; compare its generated requirements.in with requirements-linux-cpu.in, then copy the reviewed requirements-linux-cpu.lock to .local-s2s-build/requirements.lock. Preserve an existing prepared workspace; do not overwrite it or re-resolve silently during a build. Actual image build and provider startup are not authorized by dependency resolution alone.

From the repository root:

.venv/Scripts/python -m pytest tests/unit/test_local_s2s_phase2.py tests/unit/test_local_s2s_engine.py -q -p no:cacheprovider
.venv/Scripts/python -m app.local_s2s_smoke --output temp/local-s2s-stub.wav

Use a fresh output name when re-running. Play the WAV in any audio player. It is an explicit 440 Hz test tone, not synthesized Persian. No network or paid requests occur in stub mode. Both multipart and JSON STT framing are covered by HTTP fixtures. --live is a separate opt-in and never a health check.

Build preparation (not executed in this checkpoint)

  1. Obtain an authorized clean source checkout at 619e3fe4f71d1c6f35c15870d588a3638de34722. Obtain a Python 3.11 slim registry digest and a separately provisioned local Silero source/model bundle. The launcher refuses remote Torch Hub model loading and disables Smart Turn.

  2. Prepare immutable source/dependency inputs:

    .venv/Scripts/python services/local_s2s/prepare_build.py --checkout <clean-upstream-checkout> --base-image python:3.11-slim@sha256:<registry-digest>
    
  3. In an authorized dependency-resolution environment with uv installed, create a Linux hash lock; do not resolve it from the Windows virtualenv:

    uv pip compile .local-s2s-build/requirements.in --python-version 3.11 --python-platform x86_64-unknown-linux-gnu --generate-hashes -o .local-s2s-build/requirements.lock
    

    Review dependency size/licensing and CPU PyTorch selection before installing. Source pinning alone is not a dependency lock. No lock/base digest is claimed in this checkpoint. Keep the resolved lock and resulting image digest as evaluation provenance. The recipe installs hashes and performs no weight fetch.

  4. Build the separate image (after build/download authorization):

    docker build -f services/local_s2s/Dockerfile --build-arg ENGINE_BASE_IMAGE=python:3.11-slim@sha256:<same-digest> -t rag-local-s2s-candidate:phase2 .
    

    A Dockerfile-specific ignore file excludes .env, operational data and tests. The same image runs the separate engine and application API. The engine receives no database credential or application identity. No operational image is rebuilt.

Activation and browser demonstration (still pending)

Use only docker-compose.local-s2s-test.yml; it never extends the operational Compose file. docker compose ... config --quiet is a safe syntax check; do not print rendered configuration when secrets are set.

Set explicit model/voice identities and a preprovisioned VAD path. Current catalogue inspection found openai/whisper-large-v3 and openai/gpt-4.1-mini. The configured TTS candidate is google/gemini-3.8-flash-lite-tts, voice Kore; its Persian quality and 24 kHz PCM compatibility have not been measured. OpenAI TTS IDs were absent from the observed speech catalogue. Do not silently fall back if a model fails.

LOCAL_S2S_ENABLE_CANDIDATE=true enables the development API. Set LOCAL_S2S_ALLOW_PAID_STARTUP=true only after authorization: upstream STT, LLM and TTS initialization can make paid warmup/probe requests. Their counts are printed at startup/close. They are separate from the smoke command's three requests. OPENROUTER_API_KEY belongs only in the engine process environment; an optional LOCAL_S2S_TOKEN authenticates API-to-engine access and must match both services. Never put keys in a profile, command-line argument, browser or committed file.

After the gates above:

docker compose -f docker-compose.local-s2s-test.yml up -d candidate_db candidate_migrations local-s2s-engine candidate_api
docker compose -f docker-compose.local-s2s-test.yml exec -it candidate_api python -m app.bootstrap --organization-name Local-S2S-Test --username local-s2s-admin --assistant-name Local-S2S-Test --instruction "Answer briefly in Persian"

Bootstrap prompts for a new test-only password. It does not copy an operational account. API URL: http://127.0.0.2:8091; use a fresh browser profile. Repoint the existing Angular client's backend/proxy to this isolated URL using its own checkout's configuration. That Angular source is not present in this repository, so no frontend build/repointing was performed here. Ensure the browser uses the trusted Origin http://127.0.0.2:8091, or configure the explicit isolated frontend Origin and Host in the candidate only. Cookies are not isolated by port.

The configured embedding endpoint deliberately refuses inference: this is a greeting/transport-only candidate, not a RAG quality demo. It cannot reuse operational documents, sessions or calibrated search credentials. Phase 3 owns shared RAG acceptance and exact interruption repair. Until then, interruption requiring cleanup closes the local session; it does not continue unsafely.

For a separately consented real-stage WAV (three requests, no automatic retries):

python -m app.local_s2s_smoke --live --input <consented-mono24k-PCM16.wav> --output <new-evaluation.wav> --save-evaluation-audio

The input is limited to 10 seconds, the LLM to 128 output tokens/300 answer characters, and retained PCM to 10 seconds. Stream cutoff bounds local data; it cannot prove remote compute/billing stopped. Meter actual usage separately. No default conversation logging or automatic speech artifact collection exists.

Limits and provenance

One initialized pipeline; final-only STT; 10-second VAD segments; bounded pipeline queues (256 items each, overflow stops the candidate); component gateway admits at most three requests with four pending sockets; request/response byte bounds are in components.py; HTTP deadline defaults to 30 seconds; no SDK/transport retry. Partial/oversized streams omit the final HTTP chunk so consumers observe failure. Component startup counts are not a monetary cost measurement.

The extension confirms component identities from initialized handlers and projects post-application native session state onto the setup contract. It never treats a request echo as proof of active global models. Credentials must be configured and startup probes succeed before admission. A configuration mismatch prevents setup; no history receipt is fabricated. Engine construction/conformance against the real pinned dependencies remains unexecuted and may reveal compatibility repairs.

Stop only this candidate with docker compose -f docker-compose.local-s2s-test.yml stop. Do not run compose down, delete volumes or stop/rebuild either preserved OpenAI container. A candidate container rollback is not a data rollback.

Phase 2 repair checkpoint: extension v2

rag-local-s2s-phase2-v2 changes the local extension behavior. New profiles pin v2; existing v1 reservations are never rewritten and cannot silently use v2. The private browser PCM/events, canonical retrieval, identities and unsupported interruption policy are unchanged. No live acceptance or deployment switch occurred.

The request client policy is installed before handler construction. It puts max_tokens=LOCAL_S2S_MAX_OUTPUT_TOKENS on every Chat Completions request, including normal STT-derived text turns and the constructor's warmup, and forces zero retries even when pinned warmup asks with_options(max_retries=6) (see the provenance correction below; the earlier isolated harness supplied 10). The configured request deadline also enters the actual base setup before warmup; attestation reads the active client policy, not gen_kwargs (unused by that upstream text path).

Provision tokenizer assets in a separate, explicitly authorized staging environment. Copy unpacked punkt_tab English data and averaged_perceptron_tagger_eng into LOCAL_S2S_NLTK_SOURCE. Required relative files:

  • tokenizers/punkt_tab/english/{abbrev_types.txt,collocations.tab,sent_starters.txt,ortho_context.tab}
  • taggers/averaged_perceptron_tagger_eng/averaged_perceptron_tagger_eng.{weights,classes,tagdict}.json

The local Silero bundle must contain hubconf.py, src/silero_vad/data/silero_vad.jit, and all source files its hub entry point uses. The whole supplied bundle is fingerprinted. No symlinks or unlisted extra files are accepted (Git metadata and Python caches are ignored). Neither this repair nor engine startup downloads any of these resources. Original NLTK sentence/POS functions are retained; there is no fallback tokenizer.

Fingerprint already-provisioned local assets, placing the manifest outside both roots:

python -m services.local_s2s.assets --nltk-root <unpacked-nltk-data> --vad-root <local-silero-bundle> --output <new-assets.json>

Review/archive the printed SHA-256 and manifest, then set the three Compose host path variables and LOCAL_S2S_ASSET_MANIFEST_SHA256. The engine mounts the resources at /assets/nltk, /vad/silero-vad, and manifest /assets/assets.json, read-only. Preflight verifies every file and the expected manifest SHA, then actually loads NLTK sentence/POS resources before the gateway or paid probes exist. Missing, corrupt or unusable assets produce LOCAL_ENGINE_ASSET_VALIDATION_FAILED and zero provider calls. Runtime NLTK downloader entry points are blocked. Build preparation removes upstream's import-time download blocks and replaces them with local validation. Previously prepared build inputs must be freshly prepared for v2; do not reuse an old v1 source tree/image under the new revision.

Gateway bounds now start at connection acceptance. At most three connections own slots; headers are capped at 16 KiB and must finish within min(5 s, total). Body reads, upstream headers/reads and downstream drains have that same inactivity bound. A separate total deadline (default 30 s) covers the entire exchange; small trickled SSE/PCM is forwarded without 8192-byte accumulation and cannot extend it. Unsupported content encoding fails before decoding. On timeout or disconnect, the downstream socket closes immediately, upstream work is cancelled, and closure has at most a further 0.5 s per owned transport. Failed partial responses omit the terminating HTTP chunk, so consumers observe an incomplete stream. Local cancellation is not proof that remote inference/billing stopped.

Construction/probes have a 90 s owner deadline; the asset fingerprint walk has a 30 s check budget, 4096 files and 512 MiB total limits. Probe counters count one admitted attempt even on provider failure. Runtime stop, gateway shutdown, socket close and joining are independently guarded (2 s each); a stop exception or hang cannot skip later cleanup or the final numeric counters. Nonzero cleanup outcomes fail the process. SIGINT/SIGTERM handlers signal the owned stop event and previous handlers are restored. Pinned upstream wait() can itself call stop() and raise; the independent final cleanup still runs in that case.

Offline repair conformance (no providers/models/dependency installs):

python -m pytest tests/unit/test_local_s2s_repairs.py -q --tb=short -p no:cacheprovider

The harness executes hash-checked pinned setup, normal text process, request, warmup and stop methods with isolated I/O/history dependencies. Outgoing HTTPX JSON payloads and attempt counts are inspected. This is stronger than attribute-only fixtures, but the complete OpenAI SDK/ML engine image remains unbuilt/unverified. Windows signal tests dispatch the installed handlers; they do not claim OS-level POSIX signal delivery. Real engine, component audio and isolated Persian browser greeting/transcripts/normal close evidence are still required for live acceptance.

Phase 2 remaining repairs: extension v3

Current behavior is rag-local-s2s-phase2-v3, with the v1 private contract shape. Fresh profiles and prepared build manifests use v3; v1/v2 reservations remain frozen and fail revision mismatch instead of being rewritten. Preserve earlier build inputs and prepare a fresh workspace for v3. The five v2 repairs remain. No browser events, PCM24k, retrieval authority or interruption capability changed.

After the complete request body, an owned downstream watcher runs concurrently with upstream header acquisition and streaming. It does not need response data or a failed write to notice closure. Ordinary downstream EOF/reset cancels the upstream operation. Response/client closure and task joining share a one-second cleanup window, followed by slot release; stalled close operations are cancelled and the downstream transport is aborted when that window expires. Existing total and inactivity limits remain. Failed partial responses never gain a successful terminal HTTP chunk. Cancellation does not prove remote inference/billing stopped.

TCP FIN alone cannot reveal whether a peer fully closed or only called SHUT_WR. The private component gateway therefore defines the following explicit policy:

  • Ordinary clients keep their send side open until completion. EOF is cancellation by contract, even when that peer could still receive. SDK requests follow this path.
  • A client intentionally stopping its send side while retaining its receive side must send X-Local-S2S-Half-Close: receive-response before the body. After a complete body, FIN then allows the bounded response to finish. A reset/transport error still cancels. A subsequent graceful full close is indistinguishable from the declared half-close and remains bounded by the original request deadlines.
  • Other header values fail before provider admission; extra request bytes/pipelining are unsupported. The half-close header is private, is not forwarded upstream and does not change the browser protocol. The gateway closes its send side at completion.

Real loopback tests exercise both downstream and upstream TCP sockets for disconnect before headers and after headers with no further upstream output. They assert local upstream socket closure, HTTP transport closure and slot release within the cleanup window plus scheduling tolerance, before the five-second test request deadline. Separate tests cover normal success, declared half-close success, undeclared FIN cancellation and a stalled transport close. They require no external services.

The local identifier validator now has a distinct method name so VoiceSettings inherits it alongside its existing OpenAI/Gemini validator. All four local model/ voice fields reject whitespace, controls and non-ASCII before assets, construction or probes. Valid identifiers and existing provider validation are retained.

Provenance correction: the hash-checked pinned base.py.source defines WARMUP_MAX_RETRIES = 6 at line 66; Chat Completions imports that constant. The v2 harness injected 10 as an isolated override and incorrectly described it as the pinned value. Its historical 31/107/242 execution results remain unchanged, but that description was wrong. Current warmup tests read 6 from the verified source AST and test both retryable HTTP and connection failures with exactly one attempt. The full OpenAI SDK/ML engine still has not been executed.

Final offline checks for v3: 74 repair, 107 combined and 242 preservation tests passed, using -p no:cacheprovider. Compose configuration validation and git diff --check passed. Exact commands/timings and the scoped patch are in the Phase 2 report. No paid calls, downloads, image builds, operational changes or PostgreSQL acceptance were performed here. Phase 2 remains in_progress/live acceptance pending until real-engine, component-audio and isolated Persian browser greeting/transcripts/ normal-close evidence exists, alongside the existing Phase 1 prerequisite.

Acceptance runbook and newly located resources

See the acceptance checklist for exact preparation/live commands, isolation boundaries, proposed request ceilings, stop rules and actual outcomes. The checklist separates already authorized offline preparation/DB tests from unapproved downloads/builds/paid calls; its examples are not permission. v3 implementation and behavior are unchanged.

A 201-file local NLTK/Silero manifest now exists, SHA-256 8d740c51b979a1d4f92c2bd259e9c6f30497679fcf7ef9e8f31e7767320c5cd8. NLTK 3.10.3 sentence/POS loading passed in the existing sibling Windows environment with downloads blocked. These host assets still need review and Linux validation. The immutable Linux Python base is cached; full pinned source, reviewed dependency lock and candidate image are still absent. Do not use the dirty sibling engine checkout at a different revision as a substitute.

The sibling Angular checkout was located at D:/raymand/projects/faq_chatbot_frontend; its original LAN proxy/package edit were preserved. The prepared browser override uses Origin http://127.0.0.2:4201 and a separate proxy file, retaining same-origin browser API/WS calls. Nothing was launched. The Phase 1 override can run changed API source read-only on a cached immutable image using isolated candidate DB/storage and masked inherited data, without an engine build. Actual OpenAI listening still requires bounded live consent.

Fresh DB checks: 2 local passed; expanded 57 passed/6 existing baseline failures, all with --require-postgres against a verified disposable DB. The guarded runner restored its stopped state. No runtime assertion was relaxed. Phase 2 remains NOT ACCEPTED until complete engine/SDK/POSIX, component audio and Persian browser evidence exists along with Phase 1 acceptance. There were no paid calls, downloads, image builds or operational changes in this preparation checkpoint.