feat(voice): add bounded Realtime knowledge runtime

Connect OpenAI Realtime to the existing async StructuredTool and shared
SearchToolRunner with backend-owned authority and per-turn source references.
Add an operator-only smoke harness with persisted actor and provider opt-in.

Enforce confirmed readiness delivery, strict function identity, canonical
results and once-only continuations. Bound and pace generated audio, preserve
turn correlation, and require acknowledged cleanup before response release.
Handle Unicode arguments, UTF-8 replay budgets and user-ASR completion replays.

Validate with 318 voice/runner/shutdown tests and 1563 provider-free tests.
Three Windows symlink tests skip; 311 PostgreSQL tests are deselected.
Real-provider, browser playback and PostgreSQL acceptance remain unrun.
This commit is contained in:
amirhosein mazaheri
2026-10-08 18:06:03 +03:30
parent b50c920bfc
commit 9dac244590
13 changed files with 5303 additions and 0 deletions
+173
View File
@@ -1626,3 +1626,176 @@ outside this repair. It was left untouched; all other unrelated baseline files
were unchanged. All three applied migrations match HEAD byte-for-byte. Local
documentation links and new-file inspection passed. Existing intentional Markdown
hard breaks were preserved. Temporary original-image inspection files were removed.
## OpenAI Realtime Phase 1 runtime checkpoint (2026-10-08)
[Operator/runtime guide](guides/realtime-agent-phase1.md) documents the private
[Realtime adapter](../app/infrastructure/realtime.py),
[voice runtime](../app/modules/voice/runtime.py),
[operator command](../app/voice_smoke.py) and
[fake-provider regressions](../tests/unit/test_realtime_phase1.py).
The voice optional extra in pyproject.toml uses LangChain core and websockets;
no new agent framework, retrieval implementation, API route or migration is added.
Runtime receives setup acknowledgement with both VAD auto-response/cancel flags
false. Backend SearchExecution/reference state is shared per voice turn, with
actual StructuredTool async dispatch through one caller-owned SearchToolRunner.
Persisted authority checks, retrieval and socket sends remain off serialized
provider reception. Input-item/response/output-item/call/intent correlation,
strict query/context validation, canonical result serialization, terminal
call-set verification and once-only continuations are session-local and bounded.
Client tool references are backend-generated; private provider IDs appear only
in the operator diagnostic correlation report.
Generated reservoir, paced progress credits, successful-send accounting, eligible
stall timer identities, final-progress/terminal/truncation deadlines, acknowledged
retirement and latest committed-turn release gates implement API 7.1.2/7.1.5/7.1.6.
Normal tails preserve completion; delayed authorized user ASR keeps its original
turn; superseded assistant/tool work is suppressed. The narrowly correlated
no-active race classifier fails closed by default pending selected-profile proof.
Actual checks:
- 59 new voice regressions plus actual LangChain/runner/shutdown checks:
114 passed, zero skips, via .venv/Scripts/python -m pytest
tests/unit/test_realtime_phase1.py tests/unit/test_search_phase3.py
tests/unit/test_search_phase3_shutdown.py -q -p no:cacheprovider.
- Final .venv/Scripts/python -m pytest -m "not postgres" -p no:cacheprovider -q:
1359 passed, three existing Windows symlink skips, 311 PostgreSQL deselected.
- One preceding full run failed inside its nested environment rerun in the
unchanged test_running_timeout_retains_slot_and_suppresses_late_result[False].
Selecting that existing 50 ms case alone also failed before worker entry:
its deadline includes cold LangChain import/tool construction. The entire
unchanged test_search_phase3.py file reran with 41 passed; final full rerun
passed. Neither the runner nor this existing test was changed. This timing
sensitivity is reported rather than silently widening its deadline.
- CLI help, pip check, AST/manifest parsing, tracked and new-file whitespace,
guide links and proof/all applied migration byte comparison against HEAD passed.
- Actual fake-wire operator smoke used the canonical service/StructuredTool:
provider call real-fake-c belongs to real-fake-r1, output matches its call ID;
continuation real-fake-r2 supplies the final transcript. Fixture evidence
retains document UUID(int=100), chunk UUID(int=1) and S1. Empty fixture evidence
remains no_evidence; technical results remain distinct canonical errors.
No fixture identity is presented as a production corpus identity.
No real provider calls were authorized or executed; no measured calibrated
approved actor/corpus bindings were supplied. TEST_DATABASE_URL is absent:
isolated PostgreSQL acceptance was not run and deselection is not DB evidence.
No real Persian speech/browser playback or Phase 1 grounded-provider exit
criterion is claimed. Harness playback is explicitly unverified and never
fabricates progress. Selected-model acknowledgements/cancellation classification,
real truncation/layouts, transport send/playback behavior, allocator/global
capacity and Phase 2 identity/durable lifecycle remain separate acceptance.
The original proof, existing mock script, applied migrations, frozen calibration
inputs and unrelated working-tree changes were not edited by this task.
## OpenAI Realtime Phase 1 repair checkpoint (2026-10-08)
The [repaired operator guide](guides/realtime-agent-phase1.md) supersedes the
initial Phase 1 validation totals above. Current inventory adds
[validated runtime settings](../app/modules/voice/settings.py),
[bounded serialization](../app/modules/voice/serialization.py), and
[67 repair regressions](../tests/unit/test_realtime_repairs.py).
Repairs reject new audio after terminal generation while preserving legitimate
delayed transcripts; correlate assistant response/item/output/content identities
and string payloads, including provider-announced items; require healthy current
turn, completed final response, delivered transcript and confirmed matching tool
outputs/continuation chain for smoke success. Input reserves raw queued/in-flight
bytes and counts before encoding and retains forwarded input until correlated
prefix commitment. Output controls reserve encoded bytes/count through send,
preserve entire fields and retain terminal-error capacity.
Serialized event decisions reject expired setup/input/response/cancel/truncate
acknowledgements before ticker execution. Dispatch deadlines start at actual
dispatch with independent queue/send bounds. Cleanup failure keeps the affected
old turn; provider protocol/availability, transport and context-sync failures are
distinct and private IDs never enter client errors. Close is bounded/coalesced,
input/control reservations release once, and cancellation remains backend-owned.
LIVE_ configuration implements the Phase 0 defaults (including 30-second setup)
and rejects inconsistent bounds before provider connection. No model/voice,
ingestion/search, migration, route or framework change was introduced.
Executed repair checks (2026-10-08):
- `.venv/Scripts/python -m pytest tests/unit/test_realtime_phase1.py tests/unit/test_realtime_repairs.py tests/unit/test_search_phase3.py tests/unit/test_search_phase3_shutdown.py -q -p no:cacheprovider --tb=short`: 181 passed (59 existing voice + 67 repair + 55 runner/shutdown), no skips.
- `.venv/Scripts/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short`: 1426 passed, three existing Windows symlink skips, 311 PostgreSQL tests deselected.
- `.venv/Scripts/python -m pip check`: no broken requirements.
- `.venv/Scripts/python -m app.voice_smoke --help`: passed; required actor, provider opt-in and bounded seconds/call options remain.
- Seven affected Python AST parses, TOML manifest parse, strict UTF-8/local links, new-file whitespace and `git diff --check`: passed.
- Baseline SHA-256 preservation: only the seven intended existing implementation/test/documentation files changed; the other 176 baseline files remain byte-identical, including proof/mock scripts, applied migrations, original documents, shared search/runner and frozen calibration/evaluation inputs. Three scoped files were added: runtime settings, bounded serialization and repair tests.
The earlier cold-construction 50 ms runner timing failure is recorded in the
reference map's initial checkpoint. This repair did not change that test or
runner; the targeted and full repair runs passed without that timing failure.
These fake-provider results establish state/correlation behavior, including
real-fake-c -> real-fake-r1 -> real-fake-r2 and delivered final transcript,
not real provider/corpus quality or heard audio.
TEST_DATABASE_URL is not configured. No isolated PostgreSQL or real provider
call was executed; no real voice opt-in or approved calibrated actor/corpus
binding was supplied. Selected-model acknowledgement shapes, cancellation-race
classifier, Persian speech, actual truncation/latency, browser progress/transport
fragment admission and allocator/global-session capacity remain unverified.
The classifier and missing calibration remain fail-closed. Blocking search can
retain a shared runner slot until actual completion and make final shutdown
outlast the bounded smoke interaction. Phase 2 endpoints/authentication/durable
lifecycle remain outside this repair.
## Five remaining Phase 1 defects repair (2026-10-08)
The current runtime adds independently bounded/coalesced provider cleanup,
one-to-one function item/call bindings, exact immutable adapter-wire reservations,
common nested call-ID validation and completed zero-sample audio retirement.
[48 new regression cases](../tests/unit/test_realtime_remaining.py) use fake
transport barriers and the actual async StructuredTool/shared runner for dispatch.
See the [operator checkpoint and exact checks](guides/realtime-agent-phase1.md#five-remaining-defects-repair-2026-10-08).
This checkpoint: 229 targeted tests passed; full provider-free suite 1474 passed,
three existing Windows symlink skips and 311 PostgreSQL tests deselected.
Dependency, AST/TOML, whitespace, local-link and baseline preservation checks passed.
Seven intended baseline files changed, 179 stayed byte-identical, one test file
was added; protected files, shared search and the unrelated 50 ms runner test
were preserved. Earlier checkpoint results above remain historical.
No real provider or isolated PostgreSQL acceptance was run; approved actor/corpus,
explicit opt-in, compatible database/profile access and measured calibration remain
required. Existing runtime/real-browser limits in the operator guide still apply.
## Readiness and Unicode Phase 1 repair (2026-10-08)
The runtime now distinguishes private provider configuration acknowledgement from
successful application session_ready delivery; pending readiness admits no client
audio/control payload. Malformed Unicode function arguments receive canonical
INVALID_TOOL_ARGUMENTS with bounded safe hashing and zero retrieval. Provider
framing/correlation remains strict.
See [operator checkpoint and exact checks](guides/realtime-agent-phase1.md#readiness-and-unicode-repair-2026-10-08)
and [52 added regression cases](../tests/unit/test_realtime_remaining.py).
Executed for this checkpoint: 281 targeted voice/runner/shutdown tests passed;
1526 provider-free tests passed, three existing Windows symlink skips and 311
PostgreSQL tests deselected. Dependencies, eight Python AST parses, TOML,
whitespace, local documentation links and preservation checks passed. Seven
intended baseline files changed; 180 remain byte-identical; no files added/removed.
Shared search/runner, protected files and the existing 50 ms runner test remain
unchanged. Earlier results above are historical. Real provider/browser/Persian
speech and isolated PostgreSQL acceptance remain unrun with prerequisites and
fail-closed calibration/cancellation limits recorded in the operator guide.
## Provider replay and user ASR Phase 1 repair (2026-10-08)
Provider replay hashing now streams bounded canonical UTF-8 after depth/scalar/work
validation; actual provider wire-byte admission remains at RealtimeAdapter.receive.
Completed user-ASR is coalesced per mapped input/content index, while conflicting
completions fail and repeated partial text remains incremental.
See [operator behavior, exact checks and failure/rerun record](guides/realtime-agent-phase1.md#provider-replay-and-user-asr-repair-2026-10-08)
and [37 added regressions](../tests/unit/test_realtime_remaining.py).
Final targeted voice/runner/shutdown result: 318 passed. Full provider-free:
1563 passed, three existing Windows symlink skips, 311 PostgreSQL tests deselected.
Dependency, eight Python AST parses, TOML, whitespace, documentation-link and
SHA-256 preservation checks passed. Six intended baseline files changed; 181
remain byte-identical; no files added/removed. Shared search/runner, protected
inputs and the unrelated 50 ms runner test remain unchanged. Initial reproduction
and fixture-correction reruns are recorded separately in the guide.
Real provider, browser playback/Persian speech and isolated PostgreSQL acceptance
remain unrun. Existing authorization, actor/corpus/profile/calibration gates and
fail-closed cancellation classification still apply; no Phase 2 work was added.