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.
This commit is contained in:
11linear11
2026-10-09 17:43:52 -04:00
parent 9be47191d6
commit a73a496c54
67 changed files with 5988 additions and 234 deletions
+230 -5
View File
@@ -1,10 +1,11 @@
# Phase 2 repair and acceptance record
Initial repair checkpoint: 2026-10-09. The [remaining-defect repair](#remaining-defect-repair-2026-10-09)
below supersedes affected behavior and validation totals. Gemini Live is the temporary sole voice provider
because an OpenAI Realtime voice key is unavailable. This decision changes voice
only. Extraction, embeddings, frozen profiles, calibration inputs, the canonical
search pipeline and the shared bounded SearchToolRunner are preserved.
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
@@ -315,3 +316,227 @@ 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.