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.
+449
View File
@@ -0,0 +1,449 @@
# Realtime Phase 1 operator/runtime integration
Phase 1 adds the private [wire adapter](../../app/infrastructure/realtime.py),
[application runtime](../../app/modules/voice/runtime.py),
[operator smoke command](../../app/voice_smoke.py) and
[fake-provider acceptance](../../tests/unit/test_realtime_phase1.py).
The original proof is unchanged. Search/ingestion and applied migrations are unchanged.
No public HTTP, text-chat or authenticated stream route is added.
Durable sessions, authentication/Origin/CSRF and durable tool replay belong to Phase 2.
## Integration
Install the declared optional dependencies with
`.venv/Scripts/python -m pip install -e ".[voice,test]"`.
This checkpoint used already installed langchain-core 1.6.7 and websockets 17.2;
no dependency installation was required.
Create one SearchToolRunner for the owning process; pass that same instance to
every VoiceRuntime. A runtime never creates or closes the shared runner.
Pass the canonical SearchService, persisted backend user UUID, private
RealtimeAdapter and async normalized-event/PCM sink. Call start(), run
receive_loop() concurrently, and close() in finally. Lifecycle callers own
the receiver task and must cancel/join it. Close the runner from a control
thread after caller loops drain; its existing blocking work retains slots
until actual completion.
Each voice turn has one backend SearchExecution and cancellation Event.
Every search uses create_search_tool(...).ainvoke with an absolute monotonic
deadline through the actual StructuredTool. Only query and optional context
are model arguments. Validated arguments are canonically hashed for replay.
Provider call IDs and output item IDs are bound to one response/turn; completed
response output confirms the full call set. Duplicate IDs/events share results,
one function-output send and one continuation per completed response call set.
Queued output intent and confirmed transport send are distinct.
The default authority callback reads enabled persisted actor/scope and pins the
session access epoch. A future authenticated owner must supply a backend async
authority_check(execution) covering session ownership/expiry as well; it must
return bool, validate/capture trusted scope/epoch, and never accept model inputs.
Authority I/O, retrieval and socket sends run outside serialized provider reception.
Their callbacks reenter state and check current turn identity before release.
Configuration acknowledgement verifies the requested setup including both false
VAD flags, PCM24k, fixed shimmer, fa/whisper-1, instructions and strict tool schema.
Unsolicited generation is cancelled by its response ID and fails the runtime.
The normalized sink receives documented dictionaries and <=9600-byte even PCM
messages. Pass admitted browser PCM to input_audio and raw UTF-8 control bytes to
client_control. The latter accepts only the exact bounded playback_progress
schema and rejects exponent/fraction/bool tokens. Audio marker ordering and
successful-send accounting are runtime-owned. A sink must complete only after
its actual send succeeds, and must never fabricate playback reports.
Provider control remains schedulable while retrieval/authority/send I/O waits.
## Bounded audio and cleanup
Generated PCM uses packed per-part byte reservoirs under the 1440000-byte
aggregate G+T+R bound and 512 packed-slab equivalent cap. One send reservation
at a time enforces the smaller 72000-byte T+R window. Credit releases only on
validated progress or once at acknowledged retirement/terminal teardown.
Generated/sent/played counters survive retirement; released credit is not
heard audio. Per-message scratch/ref/tombstone/control/event/intent ledgers
are finite (64 unresolved refs, 256 audio/input/output-item/intent records,
4096 event digests, 64 provider commands and 64 pending client controls).
Only eligible open/sealed refs have five-second stall identities. Increasing
progress renews their own interval; equal reports do not. Finalization invalidates
the identity atomically; queued callbacks recheck state/identity/expiry. Final
progress has its independent one-second window, targeted cancellation has a
five-second terminal deadline, and truncation has a separate five-second
acknowledgement deadline from dispatch. Every affected audio part requires
matching item/index/played-ms cleanup confirmation. Only content index zero is
supported; unsupported layouts fail. Normal submillisecond-tail cleanup preserves
completed display state. Delayed authorized user ASR retains its original turn.
Initial creation and continuation require current committed/stopped input and
all older cleanup barriers; stale callbacks never release a superseded turn.
No stable official structured no-active-response error code is assumed.
The adapter fails closed unless a trusted no_active_classifier has separately
been proved for the selected provider profile. A verified error must correlate
by event_id to the one targeted cancellation; it never replaces terminal
response.done or cleanup acknowledgements. Fake classifier tests establish
state-machine behavior only. See the
[official conversation flow](https://developers.openai.com/api/docs/guides/realtime-conversations)
and [client event reference](https://developers.openai.com/api/reference/resources/realtime/client-events).
## Authorized operator smoke
Prerequisites: compatible persisted PostgreSQL/pgvector profile, enabled actor,
approved ready/active document selection and required human reviews, a successful
profile-specific measured calibration report, funded Realtime model/account
access, and separate authorization for voice plus query embedding calls.
Missing prerequisites remain closed; no cutoff or evidence is invented.
Ingestion/calibration opt-ins do not authorize this command.
Set backend-only OPENAI_API_KEY, OPENAI_REALTIME_MODEL (initially
gpt-realtime-mini), optional OPENAI_PROXY, SEARCH_CALIBRATION_REPORT, and existing
INGEST settings in the environment/.env. No key is accepted from model input.
After prerequisites and explicit voice authorization exist, set $userId to the enabled persisted actor UUID and $approvedQuestion to the approved question:
~~~powershell
.venv/Scripts/python -m app.voice_smoke --user-id $userId --query $approvedQuestion --allow-provider-calls --seconds 90 --max-tool-calls 4
~~~
The actor is explicit and checked before opening Realtime. Database connect,
statement and lock timeouts are five seconds each. Embedding timeout must be
<=75 seconds. The Realtime interaction, including setup, has a 1..600-second
budget; the 1..10-call budget counts admitted unique tool calls. Shutdown still
joins actual blocking search work under the existing runner contract, so it can
outlast the network interaction budget. No automatic provider retry is added.
Diagnostic text requires confirmed conversation.item.added/created before
response.create. The harness prints normalized events and an operator-only
smoke_correlation with matching provider response/call IDs, canonical statuses
and retrieved document/chunk/source identities. It requires terminal final
response and that response's provider-supplied completed transcript.
Technical results exit nonzero; no_evidence remains distinct from technical error.
The harness discards audio without asserting progress and reports
audio_playback_verified:false. This is a retrieval/transcript smoke, not
Persian pronunciation or browser playback acceptance. Its lack of playback
progress can hit the genuine five-second stall bound on a long response.
## Initial validation and remaining limits (2026-10-08; repair results below)
Targeted provider-free command:
`.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`.
59 new voice tests plus shared runner regressions pass (114 total).
Fake transport smoke uses the actual LangChain adapter/canonical search and
fixture document/chunk identities, including ok/no_evidence. It is not evidence
of a real persisted corpus or model quality.
Full provider-free and final preservation results are recorded in the reference
map at this checkpoint. CLI help, pip check and whitespace/AST checks are separate.
No isolated PostgreSQL acceptance (TEST_DATABASE_URL absent) or real provider
smoke was run. No provider-call authorization/approved calibrated corpus was
supplied for a real run.
Limits still requiring runtime acceptance: selected account/model access and
acknowledgement shapes, exact cancellation-race classifier, Persian speech,
real delta distribution, multi-item truncation behavior, browser progress and
send/cancel races, allocator overhead and global session capacity.
Transport reassembly/fragment admission, HTTP identity/Origin/CSRF, durable replay,
revocation notifications, restart reconciliation and authenticated session TTL
are not a Phase 1 endpoint claim. The owner must bound session lifetime and
configure authenticated transports before browser exposure. No live readiness
or grounded real-provider Phase 1 exit criterion is claimed from fake tests.
## Backend runtime configuration
[RuntimeSettings](../../app/modules/voice/settings.py) reads backend-only LIVE_
environment variables/.env and is validated before the operator opens a provider
connection. Inject the same validated settings into connect, RealtimeAdapter and
VoiceRuntime. The fixed PCM24k/shimmer profile and extraction/embedding settings
are unchanged.
| Environment setting | Default and constraint |
| --- | --- |
| LIVE_CONNECT_TIMEOUT_SECONDS / LIVE_SETUP_TIMEOUT_SECONDS | 15 / 30 seconds |
| LIVE_TOOL_TIMEOUT_SECONDS | 75 seconds maximum, including runner queue time |
| LIVE_SEND_TIMEOUT_SECONDS / LIVE_DISPATCH_WAIT_TIMEOUT_SECONDS | 5 / 5 seconds; send and queued dispatch have separate bounds |
| LIVE_RESPONSE_ACK_TIMEOUT_SECONDS / LIVE_INPUT_COMMIT_TIMEOUT_SECONDS | 15 / 15 seconds |
| LIVE_AUTHORITY_TIMEOUT_SECONDS | 5 seconds |
| LIVE_TRUNCATION_ACK_TIMEOUT_SECONDS | 5 seconds; targeted cancellation uses this same configured bound |
| LIVE_FINAL_PROGRESS_WINDOW_MS / LIVE_PLAYBACK_STALL_TIMEOUT_SECONDS | 1000 ms maximum / 5 seconds |
| LIVE_MAX_BINARY_MESSAGE_BYTES | 9600 maximum, nonempty even PCM messages |
| LIVE_MAX_CLIENT_CONTROL_BYTES / LIVE_MAX_SERVER_EVENT_BYTES | 4096 / 65536 byte maxima |
| LIVE_MAX_QUEUED_AUDIO_SECONDS | 2 seconds maximum; derives the raw-byte queue allowance |
| LIVE_MAX_QUEUED_AUDIO_BYTES / LIVE_MAX_QUEUED_AUDIO_MESSAGES | 96000 / 100 maxima, including sends in flight |
| LIVE_MAX_INPUT_BUFFER_BYTES | 480000 maximum, including forwarded uncommitted input |
| LIVE_MAX_OUTPUT_BACKLOG_BYTES / LIVE_OUTPUT_CREDIT_WINDOW_BYTES | 1440000 / 72000 maxima |
| LIVE_MAX_CONTROL_MESSAGES / LIVE_MAX_CONTROL_BYTES | 64 / 262144 maxima per direction, including sends in flight |
| LIVE_MAX_PROVIDER_MESSAGE_BYTES | 262144 maximum |
| LIVE_MAX_UNRETIRED_REFS / LIVE_MAX_REFS | 64 / 256 maxima |
| LIVE_MAX_INPUT_TURNS / LIVE_MAX_INTENTS / LIVE_MAX_EVENTS / LIVE_MAX_TOOL_CALLS | 256 / 256 / 4096 / 256 maxima |
Durations must be finite, positive and representable by runtime timeouts. PCM
byte limits must be even. Message <= credit window <= queue <= backlog, the
credit window must hold at least one reportable millisecond, and the provider
envelope must fit an admitted encoded input frame. Reference counts must agree.
The control byte allowance must hold a maximum server event plus the reserved
1024-byte terminal error. Lowering one limit can require lowering its dependent
limits; inconsistent settings fail before provider calls. No Phase 2 identity,
Origin, TTL or durable lifecycle settings are introduced here.
Input admission reserves raw bytes/count before base64 encoding or enqueueing.
Successful provider sends release only the transport reservation. Correlated
commitment releases only the stopped item's known input prefix; newer input
remains counted. The provider stop coordinate includes configured silence;
the implementation uses the session audio timeline documented by the
[official speech-stopped schema](https://developers.openai.com/api/reference/typescript/__sdk_schema?declaration=%28resource%29+realtime+%3E+%28model%29+input_audio_buffer_speech_stopped_event+%3E+%28schema%29&selected=%28resource%29+realtime).
Setup, response-intent, diagnostic input, cancellation and truncation deadlines
start at dispatch; VAD input commitment starts at the correlated speech stop.
Every serialized event decision checks expiry before consuming acknowledgements,
including duplicates. The ticker provides wakeups and cannot rescue late acks.
Server controls use [bounded_json](../../app/modules/voice/serialization.py),
which preflights depth, Unicode scalars and escaped UTF-8 size before serialization.
It preserves complete fields or fails. Controls remain reserved through actual
send completion; one message and 1024 bytes are reserved for terminal failure.
Owners serializing normalized events must use the same compact bounded serializer.
Supply a backend close_client(code) callback when integrating a browser transport;
an unwritable or full error lane closes directly. Provider close is coalesced and
survives cancellation of a failure task.
Client readiness and frame size are checked before parsing. Client schema/progress
errors use LIVE_PROTOCOL_ERROR/1008; oversized frames use LIVE_FRAME_TOO_LARGE/1009;
capacity failures use LIVE_BUFFER_OVERFLOW/1013. Malformed provider events use
LIVE_PROVIDER_PROTOCOL_ERROR, provider availability failures use
LIVE_PROVIDER_UNAVAILABLE, uncertain sends use LIVE_TRANSPORT_FAILED and cleanup
failures use LIVE_CONTEXT_SYNC_FAILED, with close 1011. Unusable-session errors
carry a safe message, affected application turn_ref (null before a turn), and
retryable:false. Cleanup failure retains the old affected turn even if new speech
has arrived.
## Phase 1 repair acceptance
Terminal generation cannot admit new playable audio. Delayed authorized user
ASR and normal completed assistant transcripts retain their original turn.
Assistant transcript completion requires string payloads and consistent response,
output item, output position and content index; provider-announced items cannot
be rebound or converted from function output into audio transcripts.
Smoke success also requires a healthy intended current turn, status=completed,
actual transcript delivery and confirmed function-output sends along the final
response's continuation chain. Its report includes final_response_id,
transcript_delivered and each call's continuation_response_id. Failed/incomplete
responses, supersession, session failure or uncertain transcript delivery exit
nonzero even if a completed transcript was received earlier. Canonical
ok/no_evidence/error results are preserved.
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 guide 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 defects repair (2026-10-08)
This checkpoint follows the earlier repair results above.
Failure cleanup now attempts provider close independently of client-close errors,
timeouts, and cancellation, including cancellation before failure handling starts.
Each close has its own timeout; concurrent and cancelled waiters share one provider
close task. Cancellation still propagates, the original failure remains observable,
and network cleanup runs outside the runtime lock.
Function output items and call IDs are bound one-to-one before dispatch. The common
dispatch boundary validates nonempty ASCII IDs of at most 128 characters, including
terminal-discovered calls. All terminal function identities are checked before any
of those calls can build a tool. Existing response/item/argument-hash bindings,
identical duplicate coalescing, and canonical INVALID_TOOL_ARGUMENTS remain intact.
Commands reserve the UTF-8 byte length of the adapter's actual immutable JSON wire
value and transmit that same value. Reservations include an in-flight send and
release once. Escaping boundaries include DEL under ASCII serialization. Limits
and canonical evidence contents are unchanged.
Successful zero-sample audio parts send balanced audio_started/audio_ended markers
with sent_bytes=0 and retire after actual marker delivery and confirmed terminal
completion. They do not make a completed exchange interrupted when new speech
arrives before marker delivery. They create no PCM, playback progress, heard time,
or cleanup acknowledgement; unfinished parts remain interruptible.
[Remaining-defect regression tests](../../tests/unit/test_realtime_remaining.py)
add 48 cases. Dispatch coverage uses the actual async StructuredTool and shared
SearchToolRunner. Four complete 12000-character Persian canonical evidence results
retain shared source_ref S1, their provider call/output correlation, and one response
continuation while a send is blocked. A second call ID for the same output item
cannot invoke a second search. Invalid nested terminal IDs build no tool and perform
no retrieval. These are fake-provider correlation results, not real speech evidence.
Executed checks for this checkpoint:
- `.venv/Scripts/python -m pytest tests/unit/test_realtime_remaining.py 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`: 229 passed in 14.91 s, no skips.
- `.venv/Scripts/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short`: 1474 passed, three existing Windows symlink skips, 311 PostgreSQL tests deselected in 101.22 s.
- `.venv/Scripts/python -m pip check`: no broken requirements.
- `.venv/Scripts/python -m app.voice_smoke --help`: passed; persisted actor, explicit provider opt-in and bounded execution options remain.
- Five affected Python AST parses, TOML manifest parse, UTF-8/local documentation links, affected-file whitespace and `git diff --check`: passed.
- SHA-256 comparison with this repair's 186-file starting baseline: seven intended existing code/test/operator/progress files changed, 179 remain byte-identical, and one regression test file was added. Proof/mock scripts, migrations, original documents, frozen inputs, embedding profiles, shared search/runner, and unrelated changes were preserved. The existing 50 ms runner test was not changed.
No known defect among these five remains after these checks. No real provider call
or isolated PostgreSQL acceptance was run. Explicit real-call authorization and
approved actor/corpus bindings with compatible database/profile access and measured
calibration remain prerequisites. The previously recorded selected-model, Persian
speech, cancellation classification, browser delivery and capacity acceptance
limitations still apply. Calibration and cancellation classification remain
fail-closed; no Phase 2 capability or real grounded-provider exit criterion is claimed.
## Readiness and Unicode repair (2026-10-08)
This checkpoint follows the five-defect checkpoint above; its results are separate.
The private provider_ready flag records confirmed configuration. The application
ready flag becomes true only after the session_ready sink send succeeds within
its deadline and the serialized completion decision still finds a usable session.
Duplicate setup acknowledgements publish readiness once. Valid private provider
events can be processed after configuration while application readiness is pending;
initial responses and continuations still require application readiness and all
existing commitment, authority, cleanup and current-turn gates.
Until readiness delivery completes, input_audio and client_control reject all
application payloads as LIVE_NOT_READY/1008 before validation or reservation.
They buffer no early input and send no provider audio append. Readiness send
failure, timeout, cancellation (including delivery cancellation before its first
step), expiry or late completion after session failure cannot open admission.
The sink must return only after actual successful delivery, as required above.
Unpaired Unicode surrogates in model query/context or rejected extra keys/values
now produce canonical INVALID_TOOL_ARGUMENTS without building a tool or performing
retrieval. Argument strings remain bounded to the existing 8192-byte admission
limit. Rejected payload fingerprints use fixed-size SHA-256 over bounded bytes
with explicit surrogate encoding; errors contain only the existing safe message.
Valid arguments retain schema-normalized canonical hashing.
Provider event replay hashing tolerates rejected Unicode only at recognized
function-argument positions, including response.done.output and announced function
items. Its internal scalar replacement preserves the ASCII JSON size budget, with
original argument digests preventing replacement or changed-payload collisions.
This internal representation never replaces arguments passed to validation.
Other provider framing/correlation fields remain strict and fail with
LIVE_PROVIDER_PROTOCOL_ERROR. One-to-one call identity, duplicate coalescing,
matching canonical outputs and one continuation remain enforced.
[Voice remaining tests](../../tests/unit/test_realtime_remaining.py) add 52 cases
for this checkpoint. Explicit sink barriers verify zero input reservations/appends
before readiness, successful once-only readiness, independent private event
processing, failures/timeouts/cancellation and late/expired completion. Actual
adapter-received JSON covers high/low surrogates in query/context/extra keys/values,
identical event and semantic replays, terminal discovery, replacement collisions,
changed-argument conflicts, valid surrogate pairs and Persian. Each rejected c1
call in r1 sends one matching canonical function output and admits one continuation
with zero tool construction/retrieval; valid Unicode uses the actual async
StructuredTool and the existing shared SearchToolRunner. Existing malformed JSON,
forged scope, unknown-tool, playback, cleanup and smoke gates passed.
Executed checks for this checkpoint:
- `.venv/Scripts/python -m pytest tests/unit/test_realtime_remaining.py 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`: 281 passed in 18.71 s, no skips.
- `.venv/Scripts/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short`: 1526 passed, three existing Windows symlink skips, 311 PostgreSQL tests deselected in 104.00 s.
- `.venv/Scripts/python -m pip check`: no broken requirements.
- `.venv/Scripts/python -m app.voice_smoke --help`: passed; persisted actor, explicit provider opt-in and bounded execution remain required.
- Eight inspected runtime/adapter/settings/serialization/harness/voice-test AST parses, TOML manifest parse, strict UTF-8/local documentation links, affected-file whitespace and `git diff --check`: passed.
- SHA-256 comparison with this repair's 187-file baseline: seven intended existing runtime/test/operator/progress files changed, 180 remain byte-identical, and no file was added or removed. The adapter, settings, serializer, smoke harness, proof/mock scripts, applied migrations, original documents, frozen calibration/evaluation inputs, embedding profiles, shared search/runner, unrelated existing changes and the 50 ms runner test were preserved.
No known defect among these two remains after these checks. No real provider call
or isolated PostgreSQL acceptance was run; TEST_DATABASE_URL is not configured.
Explicit authorization, approved actor/corpus bindings, compatible database/profile
access and measured calibration remain required. Selected-provider acknowledgement
and correlation, Persian speech/quality, actual browser playback/progress/fragment
admission, latency and global capacity remain unverified. Missing calibration and
unproved cancellation classification stay fail-closed. Existing blocking search
can retain runner slots until actual completion, so shutdown may outlast the
bounded smoke interaction. These fake-provider results do not establish the
real grounded-provider Phase 1 exit criterion or authorize Phase 2 work.
## Provider replay and user ASR repair (2026-10-08)
This later checkpoint supersedes the ASCII-expanded replay budget behavior recorded
in the preceding checkpoint. Historical test results above remain unchanged.
The adapter continues to enforce the existing 262144-byte cap on actual received
UTF-8 before parsing. Replay hashing now streams deterministic canonical UTF-8
after strict scalar, depth (16), structure/string and numeric-work preflight.
Canonical encoding is not subjected to the transport wire cap again: Persian
ASCII expansion and normalized numeric spelling cannot reject an admitted wire.
The hashing work remains bounded using the existing cap; no deployment limit was
raised. Outbound bounded_json and immutable command wire accounting remain exact.
Argument-only surrogate normalization and original fixed-size argument digests
still distinguish rejected raw payloads from literal replacement characters.
Invalid Unicode retains canonical INVALID_TOOL_ARGUMENTS, while invalid provider
framing/correlation/depth remains LIVE_PROVIDER_PROTOCOL_ERROR. Canonically
equivalent valid calls still share one result and continuation.
Each mapped input Turn now retains a SHA-256 completion fingerprint by content
index. Current supported layout is index zero only, so this adds at most one
32-byte completion per retained input mapping (maximum 256 under existing
settings), with no transcript text copy. Identical completions under same, new
or absent event IDs return without emitting again, invoking retrieval, reevaluating
release, advancing tokens or restarting deadlines. Different completed text is
an observable provider protocol failure and cannot replace the first completion.
Partial deltas retain event-ID replay protection, but distinct deltas are not
deduplicated merely for containing identical text. Delayed authorized completions
retain the original turn even after supersession; delivery still revalidates
actor/epoch outside the runtime lock.
[Remaining voice regressions](../../tests/unit/test_realtime_remaining.py) add 37
cases for this checkpoint. Actual RealtimeAdapter.receive and the runtime accept
a 92793-byte terminal containing twelve 7625-byte Persian argument strings and
an exact 262144-byte wire, including a float whose canonical spelling expands.
262145-byte overflow fails at the adapter before tool work. Sink barriers test
identical/new-ID and semantic call replays while function output is in flight;
changed same-ID replay is fatal without additional retrieval/output. The actual
async StructuredTool and one shared production-sized SearchToolRunner deliver
twelve matching call-ID outputs (a through l, originating response r1), canonical
ok/no_evidence outcomes, shared source_ref S1 where evidence exists and exactly
one continuation. Exact-boundary mixed batches invoke eleven valid searches and
send one matching canonical INVALID_TOOL_ARGUMENTS result for rejected high/low
surrogate arguments, preserving replacement collision protection.
ASR barriers cover completion replay before/after delivery, conflicts, delayed
superseded-turn completion, actor/epoch revocation, bounded mappings, unsupported
content indexes and two legitimate equal partial deltas followed by one completion.
Existing readiness, cancellation, cleanup, audio retirement, budgets, identity,
deadlines and smoke-success checks passed.
Executed checks and reruns for this checkpoint:
- Initial reproduction: `.venv/Scripts/python -m pytest tests/unit/test_realtime_remaining.py -k "provider_utf8 or wire_hash or asr_" -q -p no:cacheprovider --tb=short`: 23 failed, 10 passed, 100 deselected in 20.40 s. This included two fixture-size failures and an unpinned epoch-test fixture alongside the product reproductions.
- After implementation, the same command: 3 failed, 30 passed, 100 deselected in 19.34 s. Remaining failures were those fixture issues: the requested-size terminal fixture was 67 bytes too large; the revocation test had not captured the old turn's epoch. Corrected fixture identities/padding and pinned authority before the revocation barrier; limits and expected product behavior were not relaxed.
- Corrected scoped rerun: same command, 33 passed, 100 deselected in 4.96 s. Four exact-boundary mixed valid/surrogate cases were then added.
- `.venv/Scripts/python -m pytest tests/unit/test_realtime_remaining.py 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`: 318 passed in 23.75 s, no skips.
- `.venv/Scripts/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short`: 1563 passed, three existing Windows symlink skips, 311 PostgreSQL tests deselected in 112.50 s.
- `.venv/Scripts/python -m pip check`: no broken requirements.
- `.venv/Scripts/python -m app.voice_smoke --help`: passed; explicit persisted actor, provider opt-in and bounded execution remain required.
- Eight runtime/adapter/settings/serializer/harness/voice-test AST parses, TOML manifest parse, strict UTF-8/local documentation links, affected-file whitespace and `git diff --check`: passed.
- SHA-256 comparison with this repair's 187-file baseline: six intended runtime/serializer/test/operator/progress files changed, 181 remain byte-identical, no files added or removed. Proof/mock scripts, applied migrations, originals, frozen calibration/evaluation inputs, embedding profiles, shared search/runner, unrelated existing changes and the 50 ms runner test were preserved.
No real provider or isolated PostgreSQL acceptance was run; TEST_DATABASE_URL is
not configured. Explicit authorization, approved actor/corpus bindings, compatible
database/profile access and measured calibration remain required. Selected-provider
acknowledgement/correlation, Persian speech/quality, browser playback/progress and
fragment admission, latency and global capacity remain unverified. Missing
calibration and unproved cancellation classification remain fail-closed. Only
content index zero is supported. Shared blocking retrieval can retain a runner slot
until actual completion and make shutdown outlast the bounded smoke interaction.
These fake-provider results establish the two requested repairs, not the real
grounded-provider exit criterion or any Phase 2 capability.
+59
View File
@@ -405,3 +405,62 @@ For each material failure, record the scenario, expected behavior, correlated ID
- **Real-call limits:** retain the existing ten-call calibration and 26-query evaluation bounds. Use a separately opted-in voice smoke run capped at ten minutes total. Ingestion has its own explicit budget.
- **External prerequisites:** approved originals/document bindings, required human review, compatible database/provider access, and frontend availability. Missing prerequisites block their dependent acceptance only.
- **Markdown artifact:** this plan is stored as `docs/plans/realtime-agent-mvp-plan.md`. Add links to phase completion reports as implementation progresses. This document records the proposed work; it does not claim implementation or runtime acceptance.
## Phase 1 repair checkpoint (2026-10-08)
Implemented the scoped existing-runtime repairs; see
[operator configuration, behavior, exact checks and remaining acceptance](../guides/realtime-agent-phase1.md#phase-1-repair-acceptance).
The original proof/mock scripts, shared canonical search/StructuredTool/runner,
migrations and frozen inputs remain unchanged.
Targeted fake-provider/shared-runner/shutdown acceptance: 181 passed.
Final provider-free acceptance: 1426 passed, three existing Windows symlink
skips and 311 PostgreSQL tests deselected. Dependency, AST, manifest, whitespace,
guide-link and baseline preservation checks passed. Real provider/Persian
speech/browser playback and isolated PostgreSQL acceptance remain unrun; missing
opt-in/calibrated corpus bindings and TEST_DATABASE_URL are not filled with
invented evidence. The cancellation classifier remains fail-closed. This
checkpoint does not claim the real grounded-provider Phase 1 exit criterion.
## Five remaining Phase 1 defects checkpoint (2026-10-08)
Repaired independent failure cleanup, one-to-one function identity, exact adapter
wire accounting, common call-ID validation and successful empty-audio lifecycle.
See [behavior, regression evidence and exact executed checks](../guides/realtime-agent-phase1.md#five-remaining-defects-repair-2026-10-08).
This later checkpoint passed 229 targeted tests and 1474 provider-free tests
(three existing Windows symlink skips; 311 PostgreSQL tests deselected).
Protected inputs and unrelated changes remain preserved; shared retrieval and
the existing 50 ms runner test are unchanged. Real provider, speech, browser
playback and isolated PostgreSQL acceptance remain unrun with the prerequisites
and fail-closed limits recorded in the operator guide. Scope remains Phase 1.
## Readiness and Unicode Phase 1 checkpoint (2026-10-08)
Repaired application admission to require successful session_ready delivery,
separate from provider-confirmed setup. Malformed Unicode model arguments now
receive canonical INVALID_TOOL_ARGUMENTS with safe bounded replay fingerprints,
while provider framing/correlation remains strict.
See [operator behavior, evidence and exact checks](../guides/realtime-agent-phase1.md#readiness-and-unicode-repair-2026-10-08).
This later checkpoint adds 52 regressions: 281 targeted tests passed; the full
provider-free suite passed 1526 tests with three existing Windows symlink skips
and 311 PostgreSQL tests deselected. Protected files and unrelated changes were
preserved. Real provider/speech/browser and isolated PostgreSQL acceptance remain
unrun; missing calibration and unproved cancellation classification remain
fail-closed. Historical results above are unchanged. Scope remains Phase 1.
## Provider replay and user ASR Phase 1 checkpoint (2026-10-08)
Repaired replay hashing to retain the provider's actual UTF-8 wire admission
without applying that cap to ASCII expansion or canonical numeric spelling.
Completed user-ASR is coalesced by mapped input/content identity, with conflicts
failing observably and legitimate repeated partial text preserved.
See [operator evidence, failures/reruns and exact checks](../guides/realtime-agent-phase1.md#provider-replay-and-user-asr-repair-2026-10-08).
This checkpoint adds 37 cases: 318 targeted tests passed; 1563 provider-free tests
passed with three existing Windows symlink skips and 311 PostgreSQL tests
deselected. Protected files, unrelated changes, shared search/runner and the
existing 50 ms test remain preserved. Historical results above remain distinct.
Real provider/speech/browser and isolated PostgreSQL acceptance remain unrun,
subject to authorization/calibrated actor/corpus prerequisites and fail-closed
calibration/cancellation classification. Scope remains Phase 1.