Files
rag-technical-docs-assistant/docs/evaluation/local-s2s/phase-01.md
T
amirhosein mazaheri 8d348f0ba1 feat(voice): add isolated Local S2S v3 candidate and acceptance evidence
Extract the provider boundary while retaining OpenAI/Gemini contracts. Add
an opt-in isolated Local S2S adapter, pinned engine extension, bounded
component gateway and frozen effective configuration profiles.

Enforce request token limits, zero retries, local asset validation,
connection deadlines, disconnect ownership, bounded cleanup and signals.
Include regression coverage, pinned source fixtures, operator guidance,
asset fingerprints and guarded disposable PostgreSQL acceptance tooling.
Preserve immutable fixture bytes across Git line-ending conversion.

Validation recorded in the reports:
- 74 repair, 107 combined and 242 preservation checks passed.
- Fresh PostgreSQL local checks: 2 passed.
- Expanded PostgreSQL: 57 passed, 6 documented baseline failures.
- Compose configurations, staged whitespace and fixture hashes passed.

Phase 1 live listening and Phase 2 complete engine/SDK/POSIX, real component
audio and Persian browser acceptance remain pending. No operational switch,
paid call, model download or Phase 3 implementation is included.
2026-10-15 12:28:17 +03:30

203 lines
14 KiB
Markdown

# Local S2S Phase 1 report
Date: 2026-10-15. Status: **offline_complete_live_pending**; Phase 1 is not accepted and Phase 2 has not started.
The internal provider boundary is implemented. OpenAI cancellation and truncation
keep their native requests, identities, acknowledgement checks, deadlines and
replay fingerprints. Gemini still refuses unsupported history repair. No new
provider, browser event, schema, profile revision or dependency was introduced.
## Changes and responsibility split
- `app/modules/voice/provider.py`: small structural provider port, shared strict
JSON/error helpers, immutable history-repair target and native receipt.
- `app/modules/voice/runtime.py`: uses the port for cancellation and repair;
freezes session/turn-generation/response/operation/item/part/played coordinates
and rejects a receipt rebound to another target. Retains authorization,
playback accounting, deadlines, evidence lifetime and next-response release.
- `app/infrastructure/realtime.py`: owns native cancel/truncate framing and repair
confirmation. Existing imports of the JSON/error helpers remain compatible.
- `app/infrastructure/gemini_live.py`: implements the same repair operations while
preserving conservative failure. `voice_provider.py` types the existing factory.
- `tests/unit/test_local_s2s_boundary.py`: deterministic before/after replay and
native adapter conformance. Existing test assertions were not weakened.
Generation-stop proof remains the correlated native terminal response. A no-active
cancel error alone never releases a turn. History-repair proof is independent:
one dispatched, frozen item/part/position must match a native acknowledgement
before retirement. Fully played audio needs no mutation. Only runtime releases a
new response after these gates, playback settlement and authority revalidation.
OpenAI provides no operation echo or applied history revision in its truncate
acknowledgement: the receipt records that limitation, not a fabricated revision.
The local engine will need its own actual mutation receipt; flags cannot bypass it.
## Preserved deployment (observed, unchanged)
Repository base: `872e5f25cbe2870d3fc3c66c8a4ab9c697d3d894`; implementation is an
uncommitted working-tree diff. Unrelated `.gitignore` edits and extraction artifacts
were present before work and retained.
| Role | Container ID | Image identity |
| --- | --- | --- |
| Running `rag-api-mini`, port 8080 | `4130f6de6e2a94e66befcb334badb6790fd22a1cdb1ab1a7d8ccfd6e0cd45043` | `rag-api-brief-answers:20261014`, `sha256:8c99722cd6d7a870ac0990e1781b3d49fc38ddf8c9a58eb9ad9f17f0a97a51d3` |
| Stopped original `rag-api` | `65c9fa765c150467bde2d6336b09fb46d5ffe451d1117eb1ab93a7bacff1037d` | `rag-technical-docs-assistant-api`, `sha256:6f9b1bc3e0eeb76e0143fb33e2773f3fe3e639fbc3c4b2c11139aaabb58ea028` |
Read-only container configuration inspection confirmed OpenAI, `gpt-realtime-2.1`,
`marin`, speed 1.3, reasoning low, max output tokens 2048, standard capacity;
ASR `gpt-transcribe`, languages fa/en; server VAD threshold 0.5, prefix 300 ms,
silence 500 ms, automatic response and interruption both false, noise reduction
null. Browser/provider PCM remains mono 24 kHz. Effective setup SHA-256:
`c5ae10c57660c9d051bb04b18d1b0feb55f3eaf10ac913563ddcdf0fcfe88182`.
This was computed inside the existing image from settings and adapter setup,
without opening a provider connection; it is not a new live setup acknowledgement
or inspection of any active reservation. No credentials were recorded.
Containers/images were retained in place; no build, restart, switch, database
write or second API was performed. Container writable-layer inspection reported
only `/app/docs/calibration` additions beneath `/app/docs`. Rollback was not
exercised. Retaining these IDs does not prove a successful restoration.
## Pinned upstream audit
[Source/build-input manifest](upstream-pin.json) pins
`huggingface/speech-to-speech` at
[`619e3fe4f71d1c6f35c15870d588a3638de34722`](https://github.com/huggingface/speech-to-speech/tree/619e3fe4f71d1c6f35c15870d588a3638de34722),
with SHA-256 and Git blob fingerprints for 17 inspected source/build/test inputs.
Patch revision: none (audit only). This is static compatibility evidence, not
upstream test execution or a built/validated engine.
| Concern | Pinned source evidence | Compatibility / remaining work |
| --- | --- | --- |
| Setup | `handlers/session.py`, `runtime_config.py` deep-merge session settings | Compare authoritative effective configuration; request echo is insufficient |
| Input consumption | `handlers/audio.py` emits committed input items on speech lifecycle | Preserve native item/turn correlation; transcript alone is not commit proof |
| Manual turns | `runtime_config.py`, `handlers/response.py` expose create/interrupt flags and explicit response creation | Both automatic flags must be disabled; verify in engine conformance |
| Identities | `handlers/response.py` preserves response metadata and native response/item IDs | Carry runtime intent and raw fingerprints; no fabricated IDs/acks |
| Tools | conversation/response handlers accept function outputs and terminal output items | Use existing trusted backend dispatcher and terminal validation in Phase 3 |
| Audio | `handlers/audio.py`, `service.py`: 16 kHz internal pipeline, stateful input/output conversion | Verify configured 24 kHz PCM boundary and actual HTTP STT/TTS formats |
| Terminal | `handlers/response.py` handles cancel/finish and structured status | Generation completion differs from browser playback completion |
| History repair | `websocket_router.py` truncate branch logs acceptance without mutation or ack; Realtime README confirms this | **Incompatible** with our repair gate; requires a versioned real mutation and receipt |
| Completed, unplayed output | History/generation lifecycle finishes before playback; truncate performs no repair | Next real LLM request must exclude unheard sentinel while preserving valid context; unproven |
| Remote work | STT/TTS handler/docs show HTTP stage lifecycle, progressive cumulative STT and streaming conversion | Final-only STT initially; separately measure obsolete work/cost and late output suppression |
| Build inputs | Pinned `pyproject.toml` and Dockerfile; CUDA 12.8.1 Ubuntu 24.04 tag, mutable apt/uv, ranged dependencies, NLTK downloads | No upstream Python lockfile; dependency lock, base-image digest and asset hashes remain required **before Phase 2 build** |
No weights/dependencies were installed and no engine was built. No exact Persian
heard-prefix alignment, engine repair revision, OpenRouter model/voice support,
quality, latency or cost claim is established. The no-op truncate and
completed-but-unplayed cases remain explicit Phase 3 hard gates; no weaker
whole-turn or duration-ratio policy was adopted.
## Checks and evidence
Commands ran from the repository root with the existing Windows virtualenv.
`-p no:cacheprovider` avoids pytest cache writes. No real providers were called.
1. Focused baseline, before source changes:
`.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 -p no:cacheprovider`
— **215 passed in 29.48 s**.
2. Same replay fixture before refactor:
`.venv/Scripts/python -m pytest tests/unit/test_local_s2s_boundary.py -q -s -p no:cacheprovider`
— **12 passed in 2.73 s**. Active and completed-unplayed generation; correct,
duplicate, wrong-item, wrong-position, missing, late and conflicting acks.
3. After initial extraction, focused baseline plus the same 12 replay cases:
— **227 passed in 30.12 s**.
4. Final focused suite, adding `tests/unit/test_local_s2s_boundary.py` and
`tests/unit/test_gemini_live.py` to command 1:
— **242 passed in 32.52 s**. Includes Gemini refusal and wrong-generation receipt rejection.
5. `.venv/Scripts/python -m pytest -m "not postgres" -q -p no:cacheprovider`
? **2,079 passed, 5 failed, 3 skipped, 465 deselected in 305.56 s**.
This run collected the initial 12 replay cases before the final three
conformance cases and cancellation-routing edit; check 4 covers that final edit.
Four underlying failures also reproduce against the original HEAD modules:
- `test_openai_speech_configuration.py::test_transcript_ordering_repeated_words_delayed_completion_and_release`: waits for two transcript delta emissions; times out.
- `test_voice_search_interruption.py::test_profile_cancellation_diagnostics[shimmer-False]` and `[coral-False]`: expect an absent profile-specific diagnostic field.
- The same test's `[coral-True]`: expects profile-specific cancellation rejection inconsistent with the existing classifier.
- `test_test_environment.py::test_ordinary_suite_ignores_ambient_ingestion_configuration` reruns the suite and fails because of those same cases.
These tests were not changed. The three skips are unavailable Windows symlink privileges, not database acceptance.
6. Targeted failure comparison (current source):
`.venv/Scripts/python -m pytest tests/unit/test_openai_speech_configuration.py::test_transcript_ordering_repeated_words_delayed_completion_and_release tests/unit/test_voice_search_interruption.py::test_profile_cancellation_diagnostics -q --tb=short -p no:cacheprovider`
? **4 failed, 1 passed in 4.65 s**. Immutable HEAD module comparison below:
**same 4 failed, 1 passed in 4.32 s**. No files were reverted or rewritten.
7. Final visible replay command below ? **15 passed in 2.84 s**.
8. `git diff --check -- app docs tests` ? passed. Repository-wide
`git diff --check` reports the pre-existing `.gitignore:91` blank line at EOF;
that unrelated edit is preserved. New files were inspected separately.
9. `docker inspect --format '{{.Id}} {{.Image}} {{.State.Status}}' rag-api-mini rag-api`
? original IDs/images unchanged; running/stopped state unchanged.
`Invoke-RestMethod http://localhost:8080/health/ready` ? **ready / available**;
this is readiness, not a voice acceptance check.
To reproduce the original-module comparison without changing the working tree:
```powershell
@'
import subprocess, sys, types
from pathlib import Path
for name, path in (
('app.infrastructure.realtime', 'app/infrastructure/realtime.py'),
('app.infrastructure.gemini_live', 'app/infrastructure/gemini_live.py'),
('app.infrastructure.voice_provider', 'app/infrastructure/voice_provider.py'),
('app.modules.voice.runtime', 'app/modules/voice/runtime.py'),
):
source = subprocess.check_output(['git', 'show', 'HEAD:' + path]).decode('utf-8')
module = types.ModuleType(name)
module.__file__ = str(Path(path).resolve())
module.__package__ = name.rpartition('.')[0]
sys.modules[name] = module
exec(compile(source, module.__file__, 'exec'), module.__dict__)
import pytest
raise SystemExit(pytest.main([
'tests/unit/test_openai_speech_configuration.py::test_transcript_ordering_repeated_words_delayed_completion_and_release',
'tests/unit/test_voice_search_interruption.py::test_profile_cancellation_diagnostics',
'-q', '--tb=short', '-p', 'no:cacheprovider',
]))
'@ | .venv/Scripts/python -
```
The replays are **simulated native events with a controlled clock**. They prove
runtime ordering and unchanged cleanup behavior, not actual engine history
mutation or successful real speech. The matching path releases exactly one next
response after cleanup; missing/wrong/late proof closes safely. A later conflicting
replay closes the session even if a previous valid proof already released work.
Not run: real OpenAI interaction/human listening against the changed source;
engine build/upstream tests; OpenRouter calls; PostgreSQL acceptance (no persistence
contract changed); operational switch/rollback. No bounded paid-call authorization
or consent-controlled speech fixture was supplied for this task.
## See the result
Run this offline, from the repository root:
```powershell
.venv/Scripts/python -m pytest tests/unit/test_local_s2s_boundary.py -q -s -p no:cacheprovider
```
The trace prints `generation stopped; repair matched at 100ms; duplicate ignored;
exactly one next response`, then safe-close outcomes for bad/missing receipts.
It covers both active and already-completed generation. All 15 final cases should pass.
The existing OpenAI UI/deployment is unchanged. This phase adds an internal
boundary, so there is no new local voice option to click. Do not start a second
API on the operational database to try the source changes. A real changed-source
OpenAI demonstration needs an isolated candidate DB/storage/browser identity or
a separately authorized operational switch; use a short greeting, interrupt it,
and verify the next answer and normal close. Paid usage must be bounded first.
Verdict: offline implementation and deterministic acceptance evidence are delivered.
Required real OpenAI preservation acceptance remains open. Phase 2 must wait for
Phase 1 acceptance, and its build must resolve the recorded dependency/image pins.
## Acceptance prerequisite recheck (2026-10-15)
Phase 1 remains **offline_complete_live_pending**, not accepted. The later Phase 2
v3 preparation found the sibling Angular checkout and prepared an isolated
changed-source OpenAI recipe with read-only app mounts on the cached immutable API
image, masked inherited data and dedicated candidate DB/storage. See the
[acceptance checklist](phase-02-acceptance-checklist.md#phase-1-gate-prepared-source-only-candidate-not-launched).
The recipe was parsed and its isolation checked, not launched. A server-side OpenAI
key is configured, but no bounded live approval/consented speech or actual
interaction/listening evidence was supplied. Historical replay results remain
unchanged and do not close the listening gate. No operational container/image,
provider selection, reservation or database was changed.