Files
rag-technical-docs-assistant/docs/guides/realtime-agent-phase2-repair.md
T
11linear11 a73a496c54 feat(backend): deliver Phase 3 document and voice integration
Add authenticated upload, review, retry and knowledge-selection HTTP flows with bounded JSON processing and frozen OCR policy.

Preserve Gemini/OpenAI provider selection and fenced lifecycle semantics; retain FAQ preambles and uncertain vision candidates, and expose opt-in uncalibrated voice transport diagnostics.

Include frontend integration examples, aligned contracts and deterministic regressions. Validation: 1767 provider-free tests passed; all 404 PostgreSQL scenarios have passing evidence across the documented runs.
2026-10-09 17:43:52 -04:00

543 lines
52 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Phase 2 repair and acceptance record
Current checkpoint: [transport defect repairs](#transport-defect-repairs-2026-10-09).
Gemini is the temporary default; backend configuration can select the preserved
OpenAI adapter. Earlier initial and remaining-defect records below retain their
historical results. The latest checkpoint supersedes their Gemini-only restriction
and affected behavior; extraction, embeddings, frozen profiles, calibration inputs
and canonical search remain preserved.
The implementation and technical acceptance below are distinct from real Gemini
access, retrieval quality and browser/Persian voice acceptance. This report does
not certify frontend readiness or seamless interruption.
## Findings → fixes → regressions
| Finding / work package | Implemented repair | Acceptance evidence |
| --- | --- | --- |
| Credentials/model read from RuntimeSettings; hardcoded calibration status path (1) | Validated VoiceSettings supplies Gemini credentials, configured model/voice/proxy, exact origins/hosts, explicit cookie security, lifetimes and measured report path. RuntimeSettings retains finite bounds. Reservation snapshots actual voice, calibration and embedding metadata and revisions. No OpenAI voice key is required. | Configuration rejection/selection tests in test_phase2_lifecycle; actual configured Gemini operator test in test_gemini_live; real reservation/stream in test_phase2_postgres. |
| Synthetic configuration and tool terminal acknowledgements; missing correlation (2) | Native setupComplete confirms setup without copying requested settings. Native voiceActivity offsets identify inputs; first correlated native output proves consumption. Native tool requests produce a private waiting_tools phase, not a fabricated terminal event. Matching toolResponse IDs carry complete canonical results once, with bounded translation and duplicate admission. Native outputTranscription supplies assistant transcripts. | Actual Gemini adapter + VoiceRuntime + canonical SearchService + StructuredTool/shared runner unit cases; actual ASGI/durable tool cases for ok/no_evidence/error. |
| Audio format mismatch and unsafe interruption (2/7) | Browser PCM16LE mono remains 24 kHz. Bounded streaming 2/3 FIR conversion supplies 16 kHz Gemini input; output MIME/rate/alignment are verified. Unsupported cancellation/truncation closes context safely and suppresses late output. Provider loss independently wakes and closes reception. | Resampler partition/count tests; provider-loss/frame/queue/context-error tests; blocked-browser cleanup and setup-loss PostgreSQL/ASGI cases. |
| Permissive auth/CORS/token transports and malformed CSRF (3) | Cookie-only opaque sessions store hashes; constant-time bounded CSRF checks; exact configured Host/Origin; restricted credentialed CORS; explicit Secure/HttpOnly/SameSite policy. Canonical /me returns real expiry. Valid logout needs CSRF; missing/expired/repeated logout clears cookies after Origin. Bounded global login/provider admission. Strict DTOs and safe correlated HTTP envelopes. | Malformed token/CSRF/Origin/DTO unit tests; actual login/me/logout/replay/security/expiry and query-token rejection against PostgreSQL. |
| Missing owner chain and concurrent creation/expiry races (4) | Forward 0005 adds conversation/auth owner-chain constraints and distinct public tool references. Settings-first serialization rechecks enabled actor/auth/owner/epoch/expiry inside admission. Same normalized creation replays; changed payload conflicts; competing reservations are busy. Expired rows/calls terminalize before replacement. V03 is owner-only and never opens a provider. | Independent connections and start barriers for identical/changed C01/V01, competing reservations and tool admission; actual wrong-owner/auth FK rejection, expiry replacement and V03 replay tests. |
| Persistence inferred from sources and ON CONFLICT-only dispatch (5) | DurableTools wraps actual validated StructuredTool invocation. Insert owns execution; running duplicates poll shared durable completion; completed duplicates replay only after fresh checks; conflicts never retrieve. Full canonical results/revisions/epochs are persisted. Completion is fenced against call/parent/auth/expiry/epoch and cancellation. Result/source/continuation delivery rechecks eligibility. | Real duplicate completion with one invocation; conflicting arguments; cancellation/close/logout/restart/selection late completion tests; actual ASGI persistence and matching private/public identities. |
| Saved evidence exposed without redaction (6) | Poll returns at most 20 rows ordered deterministically by timestamp/id, chronological, with public UUID references and normalized diagnostics. Current document/chunk scope and ready/active/undeleted availability govern excerpts; unavailable identities remain, excerpts are redacted. | Real revoked-source redaction and public-reference test. |
| Snapshot-only authority, blocked receive, stranded media guard and readiness races (7) | Persisted session and per-turn SearchExecution authority is captured/rechecked. One media guard covers acceptance/setup/stream/cleanup. Independent cleanup survives ASGI cancellation. Browser/provider/runtime/expiry/revocation/shutdown are supervised. connected_at follows native setup plus successful application readiness delivery. Immediate post-ready PCM waits for the verified readiness transition. | Real authenticated ASGI first-frame/tool cases; provider loss while browser blocks; HTTP close/logout/disablement/auth and Live expiry/epoch/shutdown; duplicate media before setup; failed acceptance and setup-loss tests. |
| Thread-unsafe notifications and swallowed startup reconciliation (8) | Logout/selection transactionally terminalize running calls; selection stales old conversations. Post-commit notifications marshal to owning loops and filter pinned epochs. Persisted checks also cover separate maintenance processes. Startup requires 0005/reconciliation and never advertises readiness on failure. DB/password work is off audio reception through bounded blocking admission; shutdown bounds waits and disposes resources. | Notification thread/epoch unit test; actual selection/completion race, restart/logout and dropped-table startup failure; actual shutdown cleanup. |
| Incomplete/mismatched frontend example and cross-org provisioning (9) | Executable client/audio worklet implements aligned capture, bounded sending/playback, actual consumed-sample progress, final flush and cleanup, login/expiry/CSRF, replay/poll/recovery and fresh-session behavior. Provisioning refuses an existing username in another organization before any password/role/enablement update. | Node executes capture/playback/flush accounting; JS syntax checks; frozen schemas exercised by actual ASGI tests; real cross-org account preservation test. |
| Invalid PostgreSQL fixtures and sequential “concurrency” claims (10) | Phase 2 fixtures use actual accounts/password hashes/auth rows/settings and deterministically published ready documents/chunks. Independent SQLAlchemy connections and synchronization barriers test real constraints and races. Remote Gemini/embedding transports are deterministic; the lifecycle/runtime/tool/search boundaries are real. | Mandatory isolated PostgreSQL/pgvector suite and targeted provider-free suite below. |
## Files and boundaries
- Configuration/auth: [.env.example](../../.env.example),
[configuration.py](../../app/modules/voice/configuration.py),
[auth service](../../app/modules/auth/service.py),
[auth routes](../../app/api/v1/auth.py),
[dependencies](../../app/api/v1/dependencies.py),
[provisioning](../../app/provision.py).
- Lifecycle/transport: [forward migration](../../migrations/versions/0005_live_owner_chain.py),
[database compatibility](../../app/infrastructure/database.py),
[lifecycle](../../app/modules/voice/lifecycle.py),
[durable tools](../../app/modules/voice/durable_tools.py),
[registry](../../app/modules/voice/registry.py),
[blocking execution](../../app/infrastructure/blocking.py),
[conversation routes](../../app/api/v1/conversations.py),
[Live routes](../../app/api/v1/live.py), [application](../../app/main.py).
- Provider/runtime: [Gemini adapter](../../app/infrastructure/gemini_live.py),
[runtime](../../app/modules/voice/runtime.py), [operator smoke](../../app/voice_smoke.py).
The existing [search service](../../app/modules/knowledge/service.py) changes
only selection invalidation; retrieval remains the same.
- Handoff: [frontend guide](frontend-voice-integration-example.md),
[client](../../examples/voice-client.js), [worklet](../../examples/voice-audio-worklet.js).
Narrow current-provider notices update the reference map, plan, current operator
guide and API/database/implementation specifications; historical evidence remains.
- Regressions: test_gemini_live.py, test_phase2_auth.py,
test_phase2_lifecycle.py, test_voice_client_example.py and
tests/integration/test_phase2_postgres.py. Existing operator tests in
test_realtime_phase1.py/test_realtime_repairs.py inject the private adapter
factory, preserving their provider-neutral runtime assertions.
No deferred text/history tables, production UI, provider selector, Redis, new
agent framework, retrieval replacement or document-content versioning is added.
## Exact checks and outcomes
Commands run from the repository root. This Linux environment has
`.venv/bin/python`; the historical Windows `.venv/Scripts/python` does not exist.
Tests require normal local socket creation for the existing timeout validation
probe, so they ran outside the network-restricted shell sandbox. No remote AI
calls were made.
- Targeted final provider-free command:
`.venv/bin/python -m pytest tests/unit/test_gemini_live.py tests/unit/test_phase2_auth.py tests/unit/test_phase2_lifecycle.py tests/unit/test_voice_client_example.py tests/unit/test_realtime_phase1.py tests/unit/test_realtime_repairs.py tests/unit/test_realtime_remaining.py tests/unit/test_search_phase3.py tests/unit/test_search_phase3_shutdown.py -q -p no:cacheprovider --tb=short`
— **358 passed**, zero skips.
- Final targeted PostgreSQL command:
`.venv/bin/python -m pytest tests/integration/test_phase2_postgres.py -m postgres --require-postgres -q -p no:cacheprovider --tb=short`
— **41 passed**, zero skips, isolated database with pgvector.
- Full provider-free command:
`.venv/bin/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short`
— **1604 passed**, two existing Windows path-alias skips,
352 PostgreSQL cases deselected.
- Full mandatory PostgreSQL command:
`.venv/bin/python -m pytest -m postgres --require-postgres -q -p no:cacheprovider --tb=short`
— **352 passed**, zero skips, 1606 provider-free cases deselected.
The final affected PostgreSQL rerun also passed all **41** cases after the
bounded duplicate-wait and authority-diagnostic refinements.
- Missing-configuration gate:
`env -u TEST_DATABASE_URL .venv/bin/python -m pytest tests/integration/test_phase2_postgres.py::test_competing_active_reservations_and_expiry_replacement -m postgres --require-postgres -q -p no:cacheprovider --tb=no`
— expected exit 1 / one fixture error. This is prerequisite evidence only.
- `.venv/bin/python -m pip check` — unavailable: this environment has no pip.
Fallback `UV_CACHE_DIR=/tmp/phase2-uv-cache uv pip check --python .venv/bin/python`
— **61 packages checked; all compatible**.
- `.venv/bin/python -m app.voice_smoke --help` — passed, explicit provider opt-in
and bounded call/time arguments retained. No real smoke call was authorized.
- `node --input-type=module --check < examples/voice-client.js` and
`node --check examples/voice-audio-worklet.js` — passed.
- `git diff --check`, scoped new-file whitespace/UTF-8, Python ASTs (UTF-8-sig
for existing BOM files), TOML, links and SHA-256 preservation — **passed**. Final inspection covers all scoped tracked and new files:
27 intended baseline changes, nine new files and 175 byte-identical baseline files.
CLI help for app.provision and safe missing-Gemini-key/calibration capability
preflight also passed.
Initial checks exposed and corrected actual readiness/cleanup races. Other
failed runs were kept separate: sandbox denied the existing socket-timeout
probe; early ASGI fixtures used TestClient's untrusted default WebSocket host;
login admission persisted across test lifespans; a no-evidence fixture changed
its cutoff without updating the pinned snapshot. Fixtures now use explicit
trusted WebSocket URLs, isolated limiter state, valid measured-fixture snapshots
and cleanup barriers. None of these fixture repairs weakens production policy.
## Preservation and environment
Before editing, SHA-256 inventory captured **202 existing repository files**;
**27 intended baseline files changed, 175 remained byte-identical**. The manifest
is `/tmp/phase2-preservation.json`. Protected migrations 0001-0004 are unchanged;
0001-0003 also match HEAD. Revision 0004 was initially untracked and is treated
as potentially applied. Only forward 0005 repairs persisted ownership.
The initially modified pyproject.toml and test_migrations.py remain byte-identical
to the start-of-task baseline. The shared runner, RealtimeAdapter, RuntimeSettings,
proof scripts, frozen calibration/evaluation inputs and captured original documents
are unchanged. Unrelated working-tree edits are retained. No real ingestion,
calibration, embedding or voice calls were executed. Ignored external originals
and credentials were not edited; the manifest does not claim hashes for files
excluded from its initial repository inventory.
The system filesystem filled during implementation and prevented sandbox mounts.
Disposable repository/venv bytecode was removed; the venv temporarily moved to
/tmp and was restored at its original path. The user explicitly approved removal
of regenerable pip/uv caches outside the repository. Source and document content
were preserved. Acceptance uses a task-created PostgreSQL container/database with
application schemas isolated from public; final cleanup is recorded below.
## Remaining Gemini capabilities and external prerequisites
The existing intended configured Gemini model is preserved, including environment
overrides. Model availability and its actual native event layouts have **not**
been proven by live access. SetupComplete proves setup completion; it does not
return an echoed configuration. Native voiceActivity must contain usable audio
coordinates; absent/unsupported boundaries fail safely before tool/output release.
Input transcripts with offsets can retain their original turn; after multiple
inputs, missing coordinates are ambiguous and close rather than guess a binding.
Partial user transcription is supported without inventing a final ASR ack.
Mixed audio/tool phases without a safe layout also fail closed.
Google documents native [Live messages, activity, setup and tools](https://ai.google.dev/api/live)
and [audio formats/capabilities](https://ai.google.dev/gemini-api/docs/live-api/capabilities).
These provide no verified sample-level unheard-audio context truncation for this
selected profile. Cancellation/truncation or native interruption therefore closes
and requires a fresh session. No synthetic terminal/cancel/truncate/input-commit
acknowledgement or seamless continuation claim is made.
Real calibrated retrieval quality, selected-model tool/transcription/event
behavior, Persian speech, latency, microphone/playback/hardware timing and full
browser acceptance are **unrun**. They require explicit real-provider opt-ins,
approved inputs/corpus, a measured profile-compatible calibration report and
budgets. The Node worklet test proves accounting/capture code, not heard audio;
ASGI tests prove application wiring with deterministic remotes, not Google service
availability. Final API shutdown waits are bounded; already-running synchronous
search work retains its runner slot until its actual bounded provider/database
work completes. Threads are not forcibly terminated or reported as erased.
Deploy forward 0005 before admission. It refuses preexisting inconsistent owner
chains rather than silently reassigning them. Configure production HTTPS trusted
origins/hosts, Secure cookies, Gemini access and the measured report. HTTP local
development requires explicit loopback-only COOKIE_SECURE=false. Health never
calls an AI provider. No production deployment was performed.
## Final cleanup
Acceptance used `pgvector/pgvector:pg17` in the task-created
`rag-phase2-acceptance` container, a loopback-only port and tmpfs database data.
TEST_DATABASE_URL pointed only to `rag_phase2_test`, with disposable application
schemas isolated from public. Before removal, queries confirmed **zero disposable
application schemas and zero public application tables**. The task-created
container/volumes were removed; preexisting containers were preserved. Temporary
logs and preservation inventories remain under /tmp for this session. No shared
or production database was migrated, reconciled or altered.
## Remaining-defect repair (2026-10-09)
This checkpoint supersedes the affected initial behavior above. Gemini remains
selected; model, voice, native interruption safe-close policy, browser 24 kHz
mono PCM16LE, public events/HTTP schemas and canonical search outcomes are
unchanged. No new migration or dependency is necessary.
### Verified findings, repairs and regressions
| Requested finding | Repair and observable coverage |
| --- | --- |
| 1. Pending input/generation rebound | A second distinct activity start while the first input/generation remains unfinished fails `LIVE_CONTEXT_SYNC_FAILED` before replacing its identity or releasing old output. Native completion allows ordinary sequential turns in deterministic tests. Runtime dispatch/result/transcript gates recheck turn eligibility; normally completed delayed transcripts remain eligible under the frozen contract. Delayed user transcription with coordinates retains its original input; ambiguous optional offsets still fail closed. `test_pending_input_cannot_be_replaced_before_first_output`, `test_actual_runtime_suppresses_delayed_first_output_after_new_speech`, and `test_sequential_native_turns_and_delayed_transcript_keep_original_identity`. |
| 2. Audio charged to controls | Adapter audio uses decoded, packed <=9600-byte slabs, with the existing aggregate 1440000-byte backlog, 512-slab and 65536-byte metadata bounds. A transfer reservation connects adapter backlog with runtime G/T/R; controls retain their independent count/byte admission and native FIFO order. Scratch bounds apply before decoding. Tiny adjacent deltas coalesce; capacity failure normalizes to `LIVE_BUFFER_OVERFLOW`. Tests admit a five-second burst, 120000 two-byte deltas, exact aggregate boundary, interleaved controls, slow consumption and actual runtime pacing. |
| 3. Client asynchronous ownership | Each connection generation owns its AudioContext, nodes, socket, callbacks, readiness and tracks. Cancellation checks follow preparation/readiness/acquisition; stale returned tracks stop immediately. Cleanup coalesces and remains idempotent; old callbacks cannot mutate a newer session. Executable VoiceClient scenarios cover pending permission, resolution during flush, acquisition rejection, preparation cancellation, concurrent cleanup, stale callbacks and a stalled AudioContext close promise. |
| 4. Canonical technical-error replay | A failed row containing a recognized canonical technical error with matching saved error code is eligible for coalesced/replayed completion after fresh authority, epoch, parent and source checks. Cancellation/revocation/abandonment never becomes eligible through a saved error. PostgreSQL barrier tests prove one invocation and equivalent original, running-duplicate and completed-duplicate results for `SEARCH_TIMEOUT`, `SEARCH_FAILED` and `PROVIDER_UNAVAILABLE`; logout and saved cancellation remain ineligible. Existing late-completion/source revocation regressions continue to run. |
| 5. Duplicate activity drops content | Duplicate START/END suppresses only boundary handling; accompanying native transcription, audio, tool requests and completion still run. Conflicting coordinates fail safely. Eight combined-message cases plus conflicting-coordinate coverage exercise the actual adapter. |
| 6. Nonterminal client errors | Eligible canonical search failures are displayed while authorized explanation and subsequent interaction continue. Setup, transport, overflow, authority and synchronization failures stop resources; socket close is independently terminal. Classification uses known contract codes and turn/readiness context, not `retryable` alone. Executable VoiceClient scenarios prove speech continuation and fatal cleanup. |
| 7. Logout depends on close | A02 is attempted independently when identity refresh or V04 fails. Local identity/resources clear afterward. Valid CSRF/Origin enforcement is unchanged. Executable client tests cover expired/revoked identities, close failure, valid and repeated logout; actual HTTP expired/repeated/valid logout acceptance remains in the PostgreSQL suite. |
| 8. Explicit close races transport | Capture stops and playback flushes actual final progress before V04; intentional socket teardown follows the HTTP operation. HTTP waits are bounded at five seconds each, flush at 250 ms, AudioContext-close waiting at one second. Actual Node VoiceClient/ASGI/PostgreSQL cases cover silent and active-playback close. The active case executes the delivered playback worklet, consumes 120 samples and sends its actual 5 ms progress. Both preserve `closed/user_requested`; existing genuine transport-loss/terminal-state tests remain. Hardware and Google transport are deterministic doubles. |
| 9. Blanket revocation diagnostics | Execution and delivery classify authority loss, cancellation, changed arguments, technical timeout, busy admission and SQL availability separately. No unverified result or continuation is released. Delivery mismatch is a context synchronization failure. Real SQL fault injection through ASGI proves `DEPENDENCY_UNAVAILABLE`, a durably failed session and zero toolResponse; runtime execution/delivery cases assert normalized failures rather than false revocation. |
| 10. Repair-upgrade replay | Verified original creation hashes are accepted only if the original persisted payload/pinned configuration also matches. Under the existing settings lock they normalize atomically to the current format. Representative rows at revision 0004 upgrade through immutable 0005 and replay with the same IDs, including null, empty, Unicode and original whitespace titles. Changed payloads, null/empty collisions and unknown hashes still conflict. No ownership, provider/model snapshot or row is reassigned/discarded. |
| 11. Partial lifespan leaks | Engine acquisition, lifecycle construction and reconciliation are inside cleanup ownership. Startup failure/cancellation leaves readiness false, disposes acquired engine, closes runner, clears service globals and shuts down blocking admission. Independent cleanup preserves the original startup error even if disposal also fails. Tests cover failure, cancellation, normal shutdown and subsequent startup, including an actual running bounded worker that retains its slot until completion. No thread is claimed forcibly terminated. |
Regression sources are [native/runtime/startup tests](../../tests/unit/test_phase2_remaining.py),
[executed client/worklet tests](../../tests/unit/test_voice_client_example.py),
[client harness](../../tests/support/voice_client_harness.mjs), and
[PostgreSQL/ASGI acceptance](../../tests/integration/test_phase2_postgres.py).
The harness loads the delivered [VoiceClient](../../examples/voice-client.js)
and [worklet](../../examples/voice-audio-worklet.js); it does not replace the
client implementation with a test-only imitation.
### Original hash evidence and upgrade limits
The earlier-session tool inspection at `2026-10-09T09:04:03.658Z` retained the
original lifecycle source. Its algorithm is SHA-256 over sorted compact JSON,
`ensure_ascii=False`, encoded as UTF-8. Original C01 fields were
`{user, request, mode, title: title or ""}`; original V01 fields were
`{owner, conversation_id, client_request_id, provider, model}`. Current C01
hashes normalized mode/title; current V01 hashes conversation identity only.
Compatibility reconstructs only those verified formats. C01 also compares the
original stored title exactly, preventing null/empty hash collisions from
weakening conflict detection. V01 uses the persisted provider/model, not current
configuration. Unknown hashes still fail. The tests upgrade isolated schemas;
no shared database or migration file was changed. Normal startup reconciliation
still terminalizes old media: compatible request identity is not recoverable
provider context.
Official Google [Live schema](https://ai.google.dev/api/live) was consulted for
activity accompanying native content, completion semantics and independently
ordered transcription with optional coordinates. The [capabilities guide](https://ai.google.dev/gemini-api/docs/live-api/capabilities)
was also consulted. These references do not prove the configured model's actual
ordinary multi-turn layout. Deterministic multi-turn tests are technical evidence
only; real model capability and ambiguity handling remain external acceptance.
### Executed checks
Final full-suite results below supersede preceding failed/interrupted runs.
Commands use `.venv/bin/python` in this Linux environment, `-p no:cacheprovider`,
and no real AI providers. PostgreSQL commands use only the task-created
`rag_phase2_test` database and independently disposable application schemas.
- Targeted runtime/auth/client/shared-runner command:
`.venv/bin/python -m pytest tests/unit/test_gemini_live.py tests/unit/test_phase2_remaining.py tests/unit/test_phase2_auth.py tests/unit/test_phase2_lifecycle.py tests/unit/test_voice_client_example.py tests/unit/test_realtime_phase1.py tests/unit/test_realtime_repairs.py tests/unit/test_realtime_remaining.py tests/unit/test_search_phase3.py tests/unit/test_search_phase3_shutdown.py -q -p no:cacheprovider --tb=short`
— **400 passed**, zero skips. The client harness additionally reran after its
bounded AudioContext-close case was added and passed.
- Final affected PostgreSQL command:
`.venv/bin/python -m pytest tests/integration/test_phase2_postgres.py -m postgres --require-postgres -q -p no:cacheprovider --tb=short`
— **52 passed**, zero skips.
- Full provider-free command:
`.venv/bin/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short`
— **1646 passed**, two existing Windows path-alias skips, 363 PostgreSQL
cases deselected; 147.64 seconds.
- Full mandatory PostgreSQL command:
`.venv/bin/python -m pytest -m postgres --require-postgres -q -p no:cacheprovider --tb=short`
— **363 passed**, zero skips, 1648 provider-free cases deselected;
314.26 seconds.
- `env -u TEST_DATABASE_URL .venv/bin/python -m pytest tests/integration/test_phase2_postgres.py::test_concurrent_and_completed_technical_errors_replay_one_invocation -m postgres --require-postgres -q -p no:cacheprovider --tb=no`
— expected exit 1, **three prerequisite errors**, zero database passes/skips.
- `node tests/support/voice_client_harness.mjs unit`, client/worklet/harness
JavaScript syntax checks, and
`UV_CACHE_DIR=/tmp/phase2-remaining-uv-cache uv pip check --python .venv/bin/python`
— passed; **61 installed packages compatible**. CLI help for app.voice_smoke
and app.provision, git diff --check, scoped Python AST/UTF-8, TOML, local
documentation links and protected-file hashes also passed.
Failed/interrupted runs remain separate from acceptance. The initial sandboxed
check had 19 passes and three existing socket-timeout validation setup errors;
normal local socket access resolved those. A subsequent sandboxed startup test
run was interrupted rather than claimed successful. One targeted run had 393
passes and one failure after an overly strict newly added guard suppressed a
normally completed delayed transcript; the guard was corrected and the 400-test
run passed. A full provider-free run was interrupted during that correction
(344 passes are not full acceptance).
The first active-playback bridge fixture lacked its base64 import and did not
close the outstanding test WebSocket on fixture failure: one case timed out;
the 48 passing cases were not called full acceptance. Both fixture issues were
fixed and silent/active cases reran with two passes. The first full PostgreSQL
run had 359 passes and one readiness-state assertion race: a delivered buffered
session_ready frame could be received before its documented subsequent durable
connected commit. The affected fixture now waits on that actual transition,
keeping the same connected assertion and existing three-second test barrier;
no production ordering or unrelated timing test was weakened.
### Preservation and remaining acceptance
The start-of-task inventory `/tmp/phase2-remaining-baseline.json` covers **211
existing repository files**. Final hashes show **13 intended baseline files
changed and 198 byte-identical**, with two scoped new regression files. All
migrations 0001-0005, extraction/embedding configuration, shared SearchService,
StructuredTool/SearchToolRunner, RuntimeSettings, RealtimeAdapter, original/proof
files and frozen inputs in that inventory are unchanged. Ignored credentials and
originals were not edited; inventory hashes are not claimed for excluded files.
Inherited working-tree edits are retained.
Changed baseline paths: Gemini adapter, VoiceRuntime, Live lifecycle, DurableTools,
Live routes, application lifespan, VoiceClient, its unit test and PostgreSQL
acceptance, frontend guide, this report, the plan and reference map. New paths:
`tests/unit/test_phase2_remaining.py` and
`tests/support/voice_client_harness.mjs`. No dependency, migration, production UI,
public chat/history, Redis, retrieval replacement or new agent framework is added.
Real selected-Gemini-model audio/tool/transcription/multi-turn layouts,
microphone/playback hardware, Persian speech, retrieval quality, latency and
full browser acceptance remain **unrun**. They require explicit provider opt-ins,
Gemini/model access, an approved eligible actor/corpus, a measured compatible
calibration report, approved inputs and call/time budgets. No real provider calls
or production deployment were made. Safe-close interruption remains disclosed;
this checkpoint does not certify frontend readiness.
Final cleanup for this remaining-defect checkpoint: the task-created
`rag-phase2-remaining-acceptance` container and its disposable data/volumes were
removed. Before removal, queries found **one disposable schema left by the
interrupted fixture run and zero public application tables**. That residue was
confined to this disposable container and was removed with it; it is not claimed
as clean fixture teardown. Preexisting containers and shared databases were
untouched. Executed logs and preservation inventories remain under /tmp.
## Provider selection and transport repair (2026-10-09)
This checkpoint supersedes the Gemini-only restriction and affected behavior in
both earlier checkpoints. Gemini remains the temporary operational default;
`VOICE_PROVIDER=gemini|openai` selects the backend adapter. Both authenticated
Live and operator smoke now use the small [shared factory](../../app/infrastructure/voice_provider.py).
The existing OpenAI adapter and Gemini adapter remain byte-identical to the
preservation baseline. No real provider calls were made.
### Findings → fixes → executable evidence
| Reproduced finding | Repair | Regression evidence |
| --- | --- | --- |
| `VoiceSettings(provider='openai')` raised ValidationError; API and smoke constructed Gemini directly. | Backend selection, selected-only credentials, dedicated OPENAI_REALTIME_* settings, legacy PROVIDER/GEMINI_* compatibility with conflicting aliases rejected. Factory reuses the existing adapters/connections. V01/stream pin selected provider/model/voice/native audio/search profile; replay returns original identity. | `test_phase2_provider_selection.py`: both factory profiles, selected credentials/aliases, actual OpenAI runtime tool/audio/continuation/cancel/truncate. Existing native Gemini runtime tests. Both providers execute actual smoke construction; PostgreSQL API tests exercise readiness, native input, canonical ok/no_evidence/error tool dispatch and matching durable results/public refs. Changed-provider admission opens zero transports; replay retains reservation. |
| Installed Uvicorn defaults were 16777216-byte messages, 32 queued messages, compression enabled. | [Supported entrypoint](../../app/server.py) selects [BoundedWebSocketProtocol](../../app/infrastructure/voice_websocket.py). Pre-payload binary 9600 / text 4096 limits apply across fragments; RSV rejected before payload, compression disabled, queue eight. API retains delivered input capacity until native send completes, avoiding a second backlog. | `test_voice_websocket_transport.py`: ten real loopback cases for exact binary/UTF-8 boundaries, fragments, oversized messages, header-only rejection without mask/payload, compressed-bit rejection, negotiation and queue backpressure. Application validation remains active. |
| Authority helper returned False after SERVICE_BUSY; monitor treated infrastructure exceptions as revocation with inconsistent durable state. | Shared authority classification: SEARCH_SATURATED / SEARCH_TIMEOUT / DEPENDENCY_UNAVAILABLE for infrastructure; CONTEXT_REVOKED only for verified authority loss. Fail closed before release/delivery; first terminal code retained. Durable finish retries bounded pool admission; prior committed terminal outcomes remain immutable. | Unit startup/release/output cases and actual authority deadline. PostgreSQL monitor cases occupy all eight real blocking slots, raise a real SQL failure, exercise timeout classification and change actual DB authority; client errors match status/reason/error_code. Existing logout/disable/expiry/epoch/V04 race tests preserve committed terminal outcomes. |
| Executed delivered worklet admitted 101 tiny packets without overflow. | Both client and worklet enforce 96000 bytes AND 100 messages across refs, including partial packets and pending handoffs. Capacity reserved before PCM conversion. Cumulative consumed counters and completion/discard IDs make release idempotent; admission never advances played_ms. | `voice_phase2_repairs.mjs` executes delivered code: 100/101 tiny packets, exact byte capacity, multiple refs, partial consumption, duplicate consumption ack, interruption flush and cleanup. Existing worklet capture/progress and ASGI active-playback bridge remain exercised. |
| Committed/lost C01 response left creationAttempt and conversationRequestID undefined. | Expose attempt and both IDs before C01; retain frozen C01 and, before V01, frozen V01 payload. retryCreation/ordinary reserve replay identical attempt; newCreationAttempt/freshSession explicitly create new identity. V03 recovery does not connect. | Delivered JS simulates committed/lost C01 and V01 responses, checks identical retry payloads, immutable payload/conflicting IDs, V03 recovery, intentional freshSession ordering. Existing PostgreSQL identical/changed C01/V01 concurrency tests retain backend conflict guarantees. |
| Continuous uncommitted silence reaches the 10-second input cap. | Bound preserved; no commitment or transcript/activity binding invented. Frontend handoff now states the limitation and isolates longer idle operation as a product/provider-contract decision. | Actual Gemini adapter/runtime accepts exactly 480000 bytes of silent PCM without native activity commitment, then rejects the next sample with LIVE_BUFFER_OVERFLOW. No fake tool output/commitment. |
### Deployment and limits
The [frontend handoff](frontend-voice-integration-example.md#backend-configuration-and-supported-startup)
contains both backend configuration examples, aliases, selected-only secrets,
24 kHz browser/native audio behavior, reservation compatibility, explicit retry
and fresh-session APIs, and idle-input limitations. `.env.example` supplies both
provider-specific configurations. Embedding OPENAI_API_KEY/INGEST_* settings are
not voice aliases and were not changed.
Run `.venv/bin/python -m app.server --host 0.0.0.0 --port 8000`; Docker Compose uses
this same supported configuration. Run ingestion separately with
`.venv/bin/python -m app.worker`. Exactly one API process owns process-local
media guards and registry; multiple workers/reload/distributed ownership are not
supported. Browser controls and HTTP schemas remain frozen. Gemini safe-close
interruption does not alter OpenAI cancellation/truncation.
Inspected installed versions: Uvicorn 0.54.0 and websockets 16.1.1. The selected
legacy parser is explicitly named, rather than relying on `ws=auto`. Upstream
legacy deprecation warnings are expected and retained in test output; upgrades
require these loopback checks before changing parser/backend. The upstream
[legacy server reference](https://websockets.readthedocs.io/en/stable/reference/legacy/server.html)
describes compression disabling and message-queue backpressure; local installed
source inspection and executable tests prove the chosen implementation here.
TCP/read scratch and kernel buffers remain separate from admitted-message
budgets. Fake native acknowledgements/input consumption/context sync were not added.
### Executed checks and preservation
Commands run from the repository root using Linux `.venv/bin/python`.
PostgreSQL acceptance uses only the task-created `rag_phase2_selection_test`
database at loopback port 55439 and disposable application schemas, with pgvector
in `test_vector`. No existing application database was reused. Repeated schema
migration writes were unusually slow; only the disposable container was changed
to fsync=off and synchronous_commit=off for functional acceptance. These results
do not prove database crash durability or production throughput.
Executed command results (logs retained under `/tmp/phase2-selection-*.log`):
- Initial focused existing cases:
`.venv/bin/python -m pytest tests/unit/test_phase2_lifecycle.py tests/unit/test_gemini_live.py tests/unit/test_voice_client_example.py tests/unit/test_phase2_remaining.py -q`
— **65 passed**, 22.09 seconds.
- Provider/factory/native cancellation/smoke/browser/loopback focus:
`.venv/bin/python -m pytest tests/unit/test_phase2_provider_selection.py tests/unit/test_voice_websocket_transport.py tests/unit/test_voice_client_example.py tests/unit/test_realtime_phase1.py::test_operator_harness_actual_fake_transport_tool_correlation -q`
— **35 passed**, 8.43 seconds. Later three-file focus with `-p no:cacheprovider --tb=short`
— **33 passed**, 7.36 seconds. After explicit expiry/disablement cases,
`.venv/bin/python -m pytest tests/unit/test_phase2_provider_selection.py tests/unit/test_voice_client_example.py -q -p no:cacheprovider --tb=short`
— **25 passed**, 5.28 seconds.
- Affected PostgreSQL command:
`.venv/bin/python -m pytest tests/integration/test_phase2_postgres.py -m postgres --require-postgres -q -p no:cacheprovider --tb=short`
— first **58 passed**, 483.11 seconds; expanded both-provider tool/result and real
authority coverage **61 passed**, zero skips, 331.67 seconds.
- Final full provider-free command:
`.venv/bin/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short`
— **1679 passed**, two existing Windows path-alias skips, 372 PostgreSQL cases
deselected, 12 expected legacy-backend warnings; 142.03 seconds. A preceding
complete run passed 1677 cases before two additional authority regressions;
its results are superseded by this final run.
- Full mandatory PostgreSQL command:
`.venv/bin/python -m pytest -m postgres --require-postgres -q -p no:cacheprovider --tb=short`
— **372 passed**, zero skips, 1681 provider-free cases deselected, two expected
legacy-backend warnings; 394.30 seconds.
- `env -u TEST_DATABASE_URL .venv/bin/python -m pytest tests/integration/test_phase2_postgres.py::test_competing_active_reservations_and_expiry_replacement -m postgres --require-postgres -q -p no:cacheprovider --tb=short`
— expected exit 1, **one prerequisite error**, zero database passes/skips.
- `node tests/support/voice_phase2_repairs.mjs` and
`node tests/support/voice_client_harness.mjs unit` — passed. Delivered worklet,
module/client and harness syntax passed (`node --check`, client via
`node --input-type=module --check < examples/voice-client.js`). Python compileall
for app and affected tests, scoped AST/UTF-8, unchanged pyproject TOML parsing,
CLI help for `app.server`/`app.voice_smoke`, and `git diff --check` passed.
- New local documentation links resolve. The initial whole-modified-doc link check
found two unchanged README links to an absent LICENSE, confirmed present in HEAD;
this unrelated existing defect was preserved and excluded from the added-link check.
Failed/interrupted checks are separate from acceptance. The first new focus had
19 passes and two failures: conflicting constructor aliases were silently dropped
by the settings source, and a new timeout fixture incorrectly used dataclasses.replace
on Pydantic settings. Alias validation and the fixture were corrected. A later
focus had 34 passes and one timeout because its fake cancellation omitted the
required native terminal acknowledgement before truncation; the fixture was
corrected, preserving the OpenAI adapter and its acknowledgement gate. The earlier
full provider-free attempt and tool/container launch inspection were interrupted
by the user; completion was not recovered as suite acceptance. The disposable
container was subsequently verified running and full checks rerun. No failed,
interrupted, missing-database or skipped run is counted as PostgreSQL acceptance.
Preparation captured a clean working tree at HEAD `9be4719` and SHA-256 hashes of
213 existing repository files before editing, retained in
`/tmp/phase2-provider-selection-baseline.json`. The changes are limited to voice
configuration/factory/runtime authority/Live transport, supported startup,
browser examples, related tests and handoff/contracts. Protected migrations
0001–0005, both existing voice adapters, extraction/embedding configuration and
modules, shared SearchService/StructuredTool/SearchToolRunner, calibration inputs,
proof scripts and original-document paths were not edited. No migration was
required or added. Unrelated changes were absent at the initial baseline. A final
hash comparison matched exactly the 21 scoped modified existing paths; 42 protected
baseline entries remained unchanged. OpenAI adapter SHA-256:
`c5906daa1fb619baca6bb35a676b7cfdee720be4a4d52331278039c6efe01206`;
Gemini adapter SHA-256:
`607cf142801b8bede48482b42bc997462f2010b555eaf051a707242f09b575ae`.
Added paths are the shared factory, authority classifier, server/parser and their
regression/harness files; no unrelated existing paths changed.
Remaining external acceptance: separately authorized Gemini/OpenAI service
access with valid selected voice key/model/voice; compatible measured retrieval
calibration and approved corpus; budgets; Persian speech; real browser microphone,
AudioContext/hardware and heard-audio testing. Fake-provider tests establish
technical behavior only. Frontend readiness, seamless Gemini interruption and
longer continuous uncommitted idle capture remain uncertified.
## Transport defect repairs (2026-10-09)
This checkpoint repairs three verified Phase 2 transport defects across backend
WebSocket protocol reassembly, browser capture buffering, and trusted wire limits.
Both Gemini and OpenAI adapters, credentials, pinned profiles, migrations 0001–0005,
frozen payload/queue/playback limits, and canonical retrieval remain preserved.
### Verified defects, repairs, and observable regressions
| Transport defect | Implemented repair | Acceptance evidence |
| --- | --- | --- |
| 1. Bound fragmented-message reassembly (`app/infrastructure/voice_websocket.py`, `app/server.py`) | Reassembly uses finite scratch storage (`bytearray`), incremental UTF-8 decoding, and bounded retained metadata. Empty continuations do not allocate or grow fragment lists (preventing probe memory growth across 20,001 empty frames). Aggregate byte limits (`max_binary_message_bytes`, `max_client_control_bytes`), pre-payload frame header checks (`Frame.read(max_size=bound)`), and compression rejection are enforced. Connection close, failure, and cancellation release assembly resources. Interleaved control frames (ping/pong) remain supported during fragmentation. | Loopback tests in `tests/unit/test_voice_websocket_transport.py`: `test_bounded_fragment_reassembly_long_empty_and_tiny_sequences` (20,001 empty continuation frames, exact 9600-byte binary and 4096-byte UTF-8 boundaries), `test_interleaved_protocol_controls_during_fragmentation` (ping/pong interleaved during reassembly), and `test_malformed_fragmentation_sequences_and_resource_cleanup` (opcode 0 without start rejected with 1002, interleaved data frame rejected with 1002, unfinished message cleaned up on disconnect). |
| 2. Bound outgoing microphone messages through completion (`examples/voice-client.js`, `examples/voice-audio-worklet.js`) | Capture handoff and outgoing socket buffering enforce both byte (96000) and message (100) capacity bounds. Worklet tracks `pending` messages and `pendingBytes`, rejecting with `overflow` when either bound would be exceeded. Conservative browser `socket.bufferedAmount` accounting delivers `{type: 'accepted', bytes}` to the worklet only after verified drain across the socket (`captureBytes - bufferedAmount >= packetBytes`). Worklet acceptance does not falsely imply network completion. Capacity is released exactly once on verified drain or terminal cleanup. | Regressions in `tests/support/voice_phase2_repairs.mjs` (executed by `tests/unit/test_voice_client_example.py`): standalone worklet 100/101 boundary, client+worklet stalled socket 100/101 boundary (48,000 bytes admitted, 101st overflows), partial drain conservative accounting (partial packet bytes do not trigger acceptance), delayed handoffs, terminal cleanup, and stale callbacks. |
| 3. Honor lower trusted runtime limits at the wire boundary (`app/server.py`, `app/infrastructure/voice_websocket.py`) | Validated `LIVE_*` `RuntimeSettings` are injected into `server_config()` and `BoundedWebSocketProtocol`. Pre-allocation message admission accounts for assembling, queued, and in-flight messages (`recv()` entry release). Queue depth is set to `max(1, max_queued_audio_messages - 2)` when $> 2$ or 1, avoiding zero-capacity deadlocks for message budgets of one and two while strictly bounding total capacity. Oversized declarations are rejected before mask/payload allocation. | Loopback tests in `tests/unit/test_voice_websocket_transport.py`: `test_lower_trusted_runtime_limits_and_prepayload_rejection` (1201 binary and 501 text rejected with 1009 before reading mask/payload; legal 1200 binary and 500 text accepted), `test_small_message_budgets_one_and_two_deadlock_free` (budget of 1 functions with in-flight backpressure and sequential drain without deadlock; budget of 2 bounds total capacity to 2). |
### Exact checks and outcomes
Commands run from repository root using `.venv/bin/python` (Python 3.13.7) and `node` (v22.23.1):
- Transport loopback regressions and voice client example tests:
`.venv/bin/python -m pytest tests/unit/test_voice_websocket_transport.py tests/unit/test_voice_client_example.py -q -p no:cacheprovider --tb=short`
— **18 passed**, 22 expected legacy-backend warnings in 7.60s.
- Node worklet and client repair regressions:
`node tests/support/voice_phase2_repairs.mjs`
— **passed**: playback bounds, consumed capacity, flush, cleanup, capture bounds, 100/101 stalled socket, drain, delayed handoffs.
- Node client harness unit test:
`node tests/support/voice_client_harness.mjs unit`
— **passed**: VoiceClient ownership, errors, logout, and close.
- Provider selection, lifecycle, and Gemini Live regressions:
`.venv/bin/python -m pytest tests/unit/test_phase2_provider_selection.py tests/unit/test_phase2_lifecycle.py tests/unit/test_gemini_live.py -q -p no:cacheprovider --tb=short`
— **44 passed** in 4.46s.
- Full provider-free test suite:
`.venv/bin/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short`
— **1684 passed**, 2 skipped (Windows path alias), 372 deselected, 22 expected warnings in 150.64s.
- Missing-configuration gate:
`env -u TEST_DATABASE_URL .venv/bin/python -m pytest tests/integration/test_phase2_postgres.py::test_competing_active_reservations_and_expiry_replacement -m postgres --require-postgres -q -p no:cacheprovider --tb=short`
— expected exit 1, **one prerequisite error**: `TEST_DATABASE_URL is required for PostgreSQL acceptance`.
- PostgreSQL acceptance status:
No active PostgreSQL container or TEST_DATABASE_URL is configured in this Linux test environment. Prerequisite gate verified; full PostgreSQL acceptance is reported as unavailable pending environment setup.
- JavaScript syntax and formatting:
`node --check examples/voice-audio-worklet.js` and `node --input-type=module --check < examples/voice-client.js`
— **passed**.
- Code integrity and git checks:
`git diff --check`
— **passed** with zero whitespace/formatting defects.
### Material limitations and scope preservation
All repairs preserve:
- `VOICE_PROVIDER=gemini|openai`, Gemini default, OpenAI adapter, shared adapter factory, and credentials.
- Applied migrations 0001–0005, protected inputs, canonical retrieval, and ownership/replay/revocation rules.
- Frozen payload (9600 binary / 4096 control), queue (96000 bytes / 100 messages), playback, and 10-second uncommitted input limits. No limits were widened.
- No provider fallback, frontend provider selector, new browser control types, or deferred history features were introduced.
Automated simulations, Node worklet tests, and transport loopback tests establish technical wire boundaries only. They do not certify real-provider availability, live microphone hardware, heard-audio acoustics, or real-browser production readiness.
## Phase 3 integration: final two Phase 2 transport findings (2026-10-09)
Both requested findings are repaired without changing selected Gemini/OpenAI
adapters, voice/model configuration, browser mono PCM16LE 24 kHz, playback limits,
canonical retrieval or migrations 0001–0005.
- Receive-capacity cancellation: wait_for_capacity now propagates CancelledError.
The real installed-parser regression fills a valid one-message capacity budget,
fails the protocol with a nonresponsive peer, shields the termination assertions
from issuing another cancellation and verifies bounded transport teardown.
Existing one/two-message, fragmentation, compression and header-only limits remain.
- Invalid UTF-8 classification: the parser retains its 1007 rejection for ASGI;
Uvicorn otherwise can expose 1006 because a failed parser no longer reads the
peer close. Live maps 1007 to LIVE_PROTOCOL_ERROR. Complete and fragmented raw
invalid UTF-8 produce wire close 1007 and real PostgreSQL terminal polling reports
the protocol error. Ordinary loss remains LIVE_TRANSPORT_FAILED; existing loss
regressions remain in the affected/full acceptance suites.
Finding-to-test mapping:
`tests/unit/test_voice_websocket_transport.py::test_capacity_failure_terminates_receive_with_nonresponsive_peer`,
`test_invalid_utf8_retains_standard_1007_rejection`, and
`tests/integration/test_realtime_phase3_http.py::test_real_parser_invalid_utf8_persists_protocol_error`.
The latter executes the actual Live handler, installed server parser and durable
polling, with a deterministic provider transport. See the
[Phase 3 handoff](realtime-agent-phase3-handoff.md) for the complete exact validation
record and HTTP/voice integration checks. No real provider or browser microphone,
Persian speech, network latency or transcription-quality acceptance was performed.
Executed final integration checks: **323 affected unit tests passed**;
**1724 provider-free tests passed**, two existing Windows-only path skips;
**162 affected PostgreSQL tests passed**, zero skips, including both adapters and
the raw UTF-8 polling cases. A prior full PostgreSQL checkpoint passed **393**;
final refinement coverage and exact commands are distinguished in the Phase 3
handoff. The two-provider explicit revoked-excerpt regression passed **2** additional
cases. Missing TEST_DATABASE_URL failed with the required prerequisite error.
Compose, executable JavaScript, AST/TOML, diff and preservation checks passed.
Task-owned acceptance database cleanup verified zero application schemas/tables
before removal. No provider, adapter, frozen voice configuration or corpus rewrite.