Files
rag-technical-docs-assistant/docs/guides/realtime-agent-phase3-handoff.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

39 KiB
Raw Blame History

Phase 3 document and knowledge HTTP handoff

The modular API exposes D01-D04, D06 preview/D07, K01/K02 and read-only F01 under /api/v1. It uses the existing immutable intake, fenced worker, exact-output review and atomic selection services. It preserves selected Gemini/OpenAI voice configuration and the Phase 2 repairs. Production UI, text chat, settings editing, deletion and real-provider certification remain outside this delivery.

Startup and development origin

Install the API extra (including the bounded multipart parser) and the worker's configured embedding/vision extras using the repository manifest. Apply migrations and provision an enabled administrator as described in foundation setup. Applied migrations 0001–0005 remain unchanged.

Direct run vs. Docker Compose ports

For local development matching the Vite development proxy (http://localhost:8080) and Docker Compose port mapping:

  • Docker Compose: The API container listens internally on port 8000 and exposes host port 8080 via ${API_PORT:-8080}:8000. Start docker compose up -d db migrations api; start worker separately only for an approved ingestion queue and budget. See the Phase 4 operational procedure.
  • Direct run: Start the API process with: python -m app.server --host 0.0.0.0 --port 8080 (or --port 8000 if matching container-internal default or behind a reverse proxy mapping host 8080 to container 8000), and start a separate worker with: python -m app.worker. Docker Compose forwards the OCR setting to API and worker; both mount the same original and extraction directories. Use .env.example for actual embedding identity, dimensions and provider credentials; they remain server-side.

Proxy and trusted Host/Origin configuration

Use the same-origin Vite proxy example in the frontend's existing configuration. The Vite dev server runs at http://localhost:5173 and proxies /api to the backend at http://localhost:8080.

  • Vite proxy with changeOrigin: false (recommended for development): The proxy preserves browser headers (Host: localhost:5173 and Origin: http://localhost:5173) and forwards both HTTP and WebSocket paths (ws: true for /api/v1/live). Set: TRUSTED_HOSTS=["localhost:5173"], TRUSTED_ORIGINS=["http://localhost:5173"], COOKIE_SECURE=false (for loopback HTTP development only).
  • Direct API access (no frontend proxy): When accessing the API directly on port 8080 without a frontend proxy, set: TRUSTED_HOSTS=["localhost:8080"], TRUSTED_ORIGINS=["http://localhost:8080"]. HTTPS production uses Secure cookies and explicit trusted endpoints. Never use wildcard credentialed CORS. Cross-origin configured clients can preflight PATCH and Idempotency-Key; correlation/replay headers are exposed.

Executable browser sequence

Use DocumentClient with the existing VoiceClient. Run in the frontend module context; inspectEvidence is the frontend developer’s human review interaction, never an automatic approval helper:

import {VoiceClient} from './voice-client.js';
import {DocumentClient} from './document-client.js';
const voice = new VoiceClient(event => console.log(event));
await voice.login(username, password);
const documents = new DocumentClient(voice);
const configuration = await documents.configuration();
const uploadKey = crypto.randomUUID(); // retain until the upload outcome is resolved
const uploaded = await documents.upload(fileInput.files[0], 'Policy', uploadKey);
async function waitForProcessing(id) {
  for (;;) {
    const current = await documents.poll(id);
    if (!['queued', 'processing'].includes(current.status)) return current;
    await new Promise(resolve => setTimeout(resolve, 2000));
  }
}
let document = await waitForProcessing(uploaded.document_id);
while (document.review_required) {
  const evidence = await documents.review(document.id);
  for (const item of evidence.items) {
    // Frontend-owned human inspection: show blocks and authenticated preview_path.
    // This returns the person's decision, checked fields, note and whole-group exclusions.
    const humanDecision = await inspectEvidence(item);
    await documents.decide(document.id, {
      ...humanDecision, evidence_sha256: item.evidence_sha256
    }, crypto.randomUUID()); // retain each decision/key if its outcome is ambiguous
  }
  document = await documents.poll(document.id);
  if (document.review_required) continue; // fetch the next still-pending page
  if (!document.job.can_retry) throw new Error(document.review_state);
  await documents.retry(document.id, crypto.randomUUID()); // retain retry key
  document = await waitForProcessing(document.id);
}
if (document.status !== 'ready') throw new Error(document.job.error?.code);
// Ready remains inactive and unsearchable until this explicit replacement.
const selection = await documents.selection();
await documents.replace(selection.revision, [...new Set([...selection.document_ids, document.id])]);
// Voice admission additionally requires configured credentials and measured calibration.
await voice.reserve();
await voice.connect();

The snippets use real server-returned UUIDs/digests. Branch on processing state; do not execute review with an empty candidate list. Keep the exact File/title and upload key on ambiguous timeout, then replay the same upload. Retain decision and retry keys similarly; replay headers are Idempotency-Replayed: true. A changed payload under an existing key returns 409 IDEMPOTENCY_CONFLICT. New keys create independent documents even when bytes match. Titles are normalized by intake. Known replay retains its accepted byte bound even if the current new-upload limit is lower; changed bytes/length still conflict. The helper leaves FormData Content-Type/boundary to the browser. Upload has one file and optional title; caller-supplied organizations, profiles or model selectors are rejected. Retry accepts no body.

Lists return items, next_cursor and knowledge_revision. Document lists use limit 20 by default, max 100, stable descending created_at/id, and opaque cursors. Review pagination defaults to 10, max 20; pass the returned evidence cursor unchanged. Invalid/unknown cursors return 422. Detail never exposes private storage keys, original paths, leases, raw provider messages or credential-bearing profiles. Admin documents/review/selection are organization-scoped; hidden/deleted IDs are 404. Authenticated non-admin collection access is 403. F01 is available to both roles.

OCR supervisor policy and truthful review state

INGEST_OCR_REVIEW_REQUIRED=true is a backend-only deployment setting, default true. API enqueue freezes it as processing_profile.extraction.ocr_review_required in the immutable one-document/one-job snapshot. Workers use that snapshot; a later environment change affects only new uploads. Same-job retry preserves it. Existing profiles lacking the field retain mandatory OCR review and their original digests. No migration, backfill or profile rewrite is needed.

False admits OCR/vision transcription only after existing automatic validation passes: identity/model, readable complete blocks, source relationships, byte/pixel/ page/character budgets, faithful normalization, original integrity and coverage. Warning-bearing OCR still requires inspection; unreadable/invalid output fails. Direct PDF and other non-OCR review requirements remain. Factual Q&A inclusion requires its own retained-evidence human approval regardless of OCR policy. Approvals never enqueue or activate. Publication is atomic, ready and inactive; K02 is the only delivered activation route.

F01 capabilities.ocr_review_required reports the current deployment policy. D03 ocr_review_required reports the document's frozen policy. D03 review_state is not_evaluated, not_required, pending, approved or rejected and describes retained required decisions. review_required means a current candidate lacks a decision; rejection separately prevents retry. extraction_quality_decision is null before a complete artifact, passed for automatic validation, reviewed when all extraction requiring inspection was actually inspected, or partially_reviewed for mixed inspected pages and automatically admitted OCR. An automatically admitted extraction creates no human approval annotation or audit event. approved factual review does not change passed extraction into reviewed. Only inspected locators carry human annotations; automatic pages never do. Factual candidates can remain pending independently of any extraction outcome.

D06 returns exact server-owned evidence and check lists; preview URLs require the same admin cookie and return no-store validated image bytes. Preview cannot accept a storage path. D07 requires a nonblank note and exact required checks for approval. For factual candidates, exclusions are whole existing Q&A group IDs and cannot include placeholders or leave no factual groups. Rejection stays failed with zero chunks. Stale/removed evidence returns REVIEW_STALE; a new conflicting decision on already-decided evidence returns REVIEW_ALREADY_DECIDED. Pending reviews prevent retry even after changing the deployment default. Retry reuses the same failed job and retained output rather than obtaining a new OCR response under an old approval.

Selection, voice and errors

K02 replaces the full selected set using expected_revision; duplicate IDs return 422, unready IDs return DOCUMENT_NOT_READY with rejected IDs, and stale revision returns REVISION_CONFLICT. After ambiguous timeout or conflict, read K01 before constructing the next replacement. Additions increment revision without changing epoch; no-op preserves both. Removal increments access_epoch, stales conversations, closes older Live sessions, fails running tools and notifies the local runtime after commit. Polling redacts revoked evidence. Stop ineligible output and create a fresh conversation; never copy revoked context into recovery.

Cookie-only authentication, trusted Host/Origin and X-CSRF-Token apply to mutations. Refresh the CSRF token through /me. Safe failures carry error.code, message, request_id and retryable; X-Request-ID matches that correlation.

Bounded request-body admission before parsing

D07 extraction-review decisions and K02 knowledge-selection authenticate BEFORE consuming or accumulating request bodies:

  • Unauthenticated requests are rejected immediately with 401 (or 403 for non-admins) with zero bytes read from the network stream, preventing unauthenticated denial-of-service via unbounded payload buffering.
  • Finite receive-byte limits are enforced during streaming accumulation:
    • MAX_DECISION_BYTES = 60,151,072 bytes for D07 decisions, accommodating all supported DTO values: 10,000 exclusions and 16 checks of 500 characters, a 2,000-character note, 12 bytes per character for escaped surrogate pairs, three bytes per array entry for quotes/comma, and 1,024 bytes for fixed fields and formatting. This finite cap admits raw UTF-8 and escaped JSON without reducing semantic eligibility. Capacity is checked before buffer extension.
    • MAX_SELECTION_BYTES = 1 MiB (1,048,576 bytes) for K02 selection, accommodating up to 10,000 document UUID selections (~360 KiB).
  • Actual received bytes are counted dynamically; absent or misleading Content-Length headers cannot bypass bounds. Payloads exceeding limits return 413 PAYLOAD_TOO_LARGE.
  • Finite receive-time deadline: 15 seconds (JSON_RECEIVE_SECONDS = 15). Stalled or timed-out body receives return 503 DEPENDENCY_UNAVAILABLE and clean up.
  • D04 retry enforces a finite 5-second deadline (RETRY_RECEIVE_SECONDS = 5) and rejects any nonempty body with 422 VALIDATION_ERROR. Stalled streams, client disconnects, or cancellations release request resources immediately and cannot invoke retry afterward.

Upload admission and temporary spool separation

Upload intake decouples user-facing display filenames from filesystem temporary storage:

  • Spooled upload bytes are written to a bounded, server-controlled temporary filename (payload) in an isolated temporary directory (UploadSpool(path, filename, title)).
  • The original validated display filename (up to 255 characters, valid extension, no traversal) is preserved in spool.filename and passed explicitly to import_document.
  • This eliminates Linux filesystem NAME_MAX (255 byte) collisions for long multibyte UTF-8 filenames (e.g. 128 Arabic characters س + .md = 259 bytes), which previously raised OSError: File name too long (503 DEPENDENCY_UNAVAILABLE).
  • Default normalized title derivation, replay hash idempotency semantics, CLI intake compatibility, upload bounds, and temporary file cleanup on completion/cancellation remain fully preserved.
  • Upload admission uses request max = configured file bytes + 16 KiB, file max = configured bytes, two parts, 4 KiB headers per part, 800 UTF-8 title bytes, a 60-second receive deadline and four concurrent disk spools. Invalid/malformed input is INVALID_FILE (422), too large is FILE_TOO_LARGE (413), unsupported format is 415, and capacity is RATE_LIMITED (429). Stalled receive returns DEPENDENCY_UNAVAILABLE (503) after its deadline. Partial multipart, rejection and disconnect clean temporary resources. Uncertain original commits retain candidates for existing reconciliation rather than deleting evidence.

F01 voice/captions indicate configured credential/calibration prerequisites, not verified provider/Persian quality. See the voice handoff for mono PCM16LE 24 kHz, application events, playback_progress, audio_ended, interruption and ten-second uncommitted input behavior. Native UTF-8 rejection retains wire close 1007 and is persisted as LIVE_PROTOCOL_ERROR; ordinary loss remains LIVE_TRANSPORT_FAILED. Reconcile V03/poll, close the old reservation and use fresh IDs before reconnecting.

Validation checkpoint

Executed checks and remaining external prerequisites are recorded below after implementation validation. Deterministic providers, simulated browser requests and local parser tests do not establish real provider quality or browser hardware readiness.

Executed checks (2026-10-09)

  • Repair regression test suite: .venv/bin/python -m pytest tests/unit/test_phase3_repairs.py tests/unit/test_upload_boundary.py -q -p no:cacheprovider --tb=short — 23 passed (9 repair tests in test_phase3_repairs.py, 14 in test_upload_boundary.py), 0.65 seconds.
  • Bounded admission, upload spool, and document client unit tests: .venv/bin/python -m pytest tests/unit/test_phase3_repairs.py tests/unit/test_upload_boundary.py tests/unit/test_intake.py tests/unit/test_document_client_example.py -q -p no:cacheprovider --tb=short — 36 passed, 0.74 seconds.
  • Provider-free regression suite: .venv/bin/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short — 1680 passed, 2 skipped (Windows path alias semantics), 395 PostgreSQL tests deselected, 154.21 seconds. No real provider calls.
  • PostgreSQL integration acceptance with isolated container (rag-phase3-repair-acceptance on loopback port 54930, tmpfs): .venv/bin/python -m pytest tests/integration/test_realtime_phase3_http.py -m postgres --require-postgres -q -p no:cacheprovider --tb=short — 23 passed, zero skips, 55.79 seconds; includes test_unicode_filename_upload_persistence_and_replay.
  • PostgreSQL acceptance suite with intake: .venv/bin/python -m pytest tests/integration/test_realtime_phase3_http.py tests/integration/test_intake.py -m postgres --require-postgres -q -p no:cacheprovider --tb=short — 77 passed, zero skips, 78.07 seconds.
  • Required PostgreSQL acceptance configuration check: env -u TEST_DATABASE_URL .venv/bin/python -m pytest tests/integration/test_realtime_phase3_http.py::test_unicode_filename_upload_persistence_and_replay -m postgres --require-postgres -q -p no:cacheprovider --tb=short — expected exit 1 with prerequisite error: TEST_DATABASE_URL is required for PostgreSQL acceptance. Missing configuration fails acceptance rather than passing.
  • Node syntax and contract checks: node --check examples/document-client.js examples/vite-proxy.config.js examples/voice-client.js examples/voice-audio-worklet.js: passed.
  • Formatting, git diff, and whitespace checks: git diff --check: passed. Zero trailing whitespace or merge conflict markers.

Acceptance coverage and focused integration review

Area Evidence
Auth and scope Actual cookie login, admin/user roles, Host/Origin/CSRF checks, cross-organization 404 for detail/review/preview/retry/selection, safe shared correlation/error envelopes
Bounded request admission D07 decisions (60,151,072-byte bound) and K02 selection (1 MiB bound) authenticate before body accumulation (0 bytes consumed unauthenticated); dynamic receive-byte counts prevent bypass via missing/misleading Content-Length; 15s receive deadline returns 503; D04 retry empty body deadline (5s) rejects nonempty payload and releases resources on timeout/cancellation without invoking retry
Upload intake & spools Spooling writes to bounded server-controlled disk path (payload) decoupling Linux NAME_MAX (255 byte) limit from original display filename; 128 Arabic characters (س * 128 + .md = 259 bytes) accepted without filesystem error; display filename, extension validation, default normalized title derivation, exact replay hash idempotency, CLI intake, and cleanup on disconnect/finish preserved
Startup & proxy Direct run on port 8080 (python -m app.server --host 0.0.0.0 --port 8080), Docker Compose port mapping (${API_PORT:-8080}:8000), and Vite proxy configuration (http://localhost:8080, changeOrigin: false, ws: true) reconciled and documented with corresponding trusted Host/Origin settings
Review/retry Exact retained source previews, required checks and forged reviewer rejection, stale digest, approval/rejection and replay/conflict, approval alone leaves failed, same-job/generation replay, retained OCR reuse
Frozen OCR True/false new profiles, legacy missing setting, deployment changes after enqueue, JPEG/PNG/scanned PDF, unreadable/model/placeholder/warning failures, independent factual inclusion, truthful passed/partially_reviewed outcomes, zero synthetic human records
Publication/selection Ready but inactive after actual fenced publication, unready/duplicate/revision rejection, no-op and addition epoch rules, authenticated K02 removal closing both provider paths, revoked excerpts redacted, blocked actual runtime search cancelled without late sources/provider output
Transport Filled capacity with a nonresponsive peer terminates without another cancel; complete and fragmented UTF-8 retain native 1007 and persist LIVE_PROTOCOL_ERROR through actual installed parser/Live handler

Final integration review confirmed that all three Phase 3 findings are repaired without altering Phase 1 architecture, data migrations, provider abstractions, or unrelated working tree changes.

Preservation checks confirm:

  • Existing Gemini and OpenAI Realtime adapters remain intact and configurable; Gemini remains the default provider without fallback.
  • OCR supervisor policy defaults to true and remains frozen per job; legacy profiles retain mandatory review.
  • Independent uploads, immutable originals, same-job retry, ready-but-inactive publication, explicit K02 selection, and shared retrieval are preserved.
  • Database migrations 0001–0005 and protected corpus inputs are untouched.
  • No production UI, public search endpoint, settings editor, background service, or extra external dependency was added.

Real OCR/transcription quality, funded provider calls, Persian voice, browser microphone/playback, production HTTPS/proxy deployment, and frontend UI acceptance remain explicitly unverified. Setting the OCR supervisor gate false is not quality certification.

Before cleanup, the temporary test database contained zero disposable application schemas and zero public application tables. The test container rag-phase3-repair-acceptance was stopped and automatically removed.

Four verified findings repair (2026-10-09)

K02 submits its unchanged synchronous atomic service to the existing eight-slot blocking pool. Exhaustion maps to 429 RATE_LIMITED; a six-second wait timeout maps to 503 DEPENDENCY_UNAVAILABLE. A timed-out transaction can still commit, retaining its slot until completion and issuing the existing post-commit notification. Resolve ambiguous outcomes through K01 before submitting a new expected revision.

Finding Exact regression coverage
Selection blocking tests/unit/test_phase3_http_repairs.py::test_blocked_selection_keeps_event_loop_responsive, test_selection_blocking_safe_errors; PostgreSQL tests/integration/test_realtime_phase3_http.py::test_authenticated_selection_removal_closes_active_voice_and_redacts_polling (Gemini and OpenAI), test_http_selection_removal_cancels_running_runtime_tool, test_selection_addition_preserves_active_epoch_and_noop_revision
Overwritten ingestion suite tests/unit/test_phase3_repairs.py restored byte-for-byte from commit 9be4719: all 55 DOCX fidelity, FAQ association, chunking, budgets and deadline regressions; the nine existing HTTP tests moved intact to tests/unit/test_phase3_http_repairs.py with cap-dependent fixtures updated
Decision admission budget HTTP suite test_decision_budget_covers_multibyte_and_escaped_identifiers, test_json_capacity_checked_before_buffer_extension, test_streamed_oversized_json_rejection, test_absent_and_misleading_content_length, test_slow_body_receive_timeout, test_unauthenticated_admission_zero_bytes_consumed, test_csrf_rejection_consumes_no_decision_body; PostgreSQL test_large_eligible_review_persists_and_replays generates 9,000 retained blocks/4,500 groups, excludes 4,499 and resumes one eligible pair without repeated provider calls (ASCII and escaped Unicode variants)
D04 handoff HTTP suite test_retry_admission_and_cancellation: nonempty body returns 422 VALIDATION_ERROR; stalled receive returns 503 and cancellation never invokes retry

The new decision bound is 60,151,072 bytes. Existing semantic limits, review eligibility, authentication/CSRF ordering and 15-second receive deadlines remain. JSON with excessive formatting can exceed the finite admission budget even if its parsed DTO would otherwise be valid; compact valid DTO encodings fit.

Executed repair checks (Linux .venv/bin/python; local socket access required):

.venv/bin/python -m pytest tests/unit/test_phase3_repairs.py tests/unit/test_phase3_http_repairs.py -q -p no:cacheprovider --tb=short
# 71 passed in 5.55s: 55 restored ingestion + 16 HTTP cases.
.venv/bin/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short
# 1740 passed, 2 failed, 2 existing Windows-path skips, 397 deselected in 209.23s.
.venv/bin/python -m pytest tests/unit/test_gemini_live.py -q -p no:cacheprovider --tb=short
# 9 passed, 1 failed in 15.33s; same tool-response timeout reproduces alone.
TEST_DATABASE_URL=postgresql+psycopg://postgres:fixture@127.0.0.1:55439/rag_repairs_test .venv/bin/python -m pytest tests/integration/test_realtime_phase3_http.py -k 'large_eligible or selection' -m postgres --require-postgres -q -p no:cacheprovider --tb=short
# 6 passed, 1 failed, 18 deselected in 644.49s; zero skips.
TEST_DATABASE_URL=postgresql+psycopg://postgres:fixture@127.0.0.1:55439/rag_repairs_test .venv/bin/python -m pytest tests/integration/test_realtime_phase3_http.py -k large_eligible -m postgres --require-postgres -x -q -p no:cacheprovider --tb=short
# 2 passed, 23 deselected in 477.99s; zero skips.
env -u TEST_DATABASE_URL .venv/bin/python -m pytest tests/integration/test_realtime_phase3_http.py::test_large_eligible_review_persists_and_replays -m postgres --require-postgres -q -p no:cacheprovider --tb=short
# Expected failure: 2 setup errors, TEST_DATABASE_URL required; zero skips.
git diff --check
# Passed; four affected Python AST parses and restored-suite byte comparison passed.

Full provider-free failures: unchanged test_native_tool_correlation_canonical_result_and_once_only_continuation[rows0-ok] times out waiting for Gemini toolResponse; test_ordinary_suite_ignores_ambient_ingestion_configuration runs the suite in a subprocess and encounters that same failure. The independent Gemini run reproduces it. No failing test or runtime was weakened or changed. Focused PostgreSQL failure: test_http_selection_removal_cancels_running_runtime_tool times out at entered.wait(3) before invoking K02. Both provider variants of post-commit active-session closure/redaction passed, as did selection revision, addition/no-op and large-decision persistence/replay/same-job resume.

A broader command with the same isolated URL, .venv/bin/python -m pytest tests/integration/test_realtime_phase3_http.py -m postgres --require-postgres -q -p no:cacheprovider --tb=short, was interrupted after 498.32s: 19 passed, two unchanged test_real_parser_invalid_utf8_persists_protocol_error timeout failures; it is not a completed acceptance run. Initial sandboxed unit/database runs encountered existing socket-based timeout-validator setup errors; the checks above ran with local socket access. An earlier focused unit checkpoint passed 69 cases before the final two admission tests were added.

This repair edits only knowledge transport, JSON admission, the restored/separate unit suites, generated HTTP integration cases, this handoff and the reference map. All unrelated working-tree edits are retained. Neither provider adapter, OCR policy/profile semantics, immutable originals, migrations 0001–0005, protected inputs, shared retrieval, Phase 2 implementation, manifest or Compose changed. No production UI, executor abstraction, dependency or service was added. Remaining prerequisites include investigation of the recorded unchanged voice/ parser failures and actual funded provider, Persian speech, browser hardware and HTTPS deployment acceptance. These tests use generated evidence and mocked providers and certify none of those external behaviors.

The task-owned rag-four-findings-test container used pgvector/pgvector:pg16, loopback port 55439 and the isolated rag_repairs_test database. Final inspection found zero public tables and two disposable schemas left by the interrupted run. Stopping the --rm container removed the database and remaining schemas; no existing database/container was modified.

Large JSON responsiveness and completed acceptance repair (2026-10-09)

This record supersedes the incomplete acceptance above for the affected final code. D07 retains its 60,151,072-byte budget and all supported DTO semantics; K02, all 55 restored ingestion cases, D04's 422 VALIDATION_ERROR and the separate HTTP regression suite remain intact.

receive_json admits at most two requests before allocating/consuming their body. It checks actual remaining byte capacity before each chunk, copies at most 64 KiB per iteration and yields even for a stream that never suspends. Bodies above 64 KiB spill to private temporary files instead of growing an API buffer. UTF-8 decoding, standard-library json.loads and full DTO validation run in a short-lived local child process, with a separate GIL. The parent receives only trusted child-validated field batches (at most 256 KiB each), yielding between batches, and constructs the already-validated DTO without repeating validation. Client data never enters a pickle loader; only the application's local child produces the internal result frames. No provider credentials leave the server. No external service, dependency, custom JSON parser or executor pool was added.

The 15-second JSON deadline now covers receive, parsing and result reconstruction. Authentication and CSRF still precede consumption. Capacity exhaustion maps to 429 RATE_LIMITED, a receive/processing timeout to 503 DEPENDENCY_UNAVAILABLE, and malformed encoding/JSON/DTOs to 422 VALIDATION_ERROR through the existing correlated error envelope. A cancelled/timed-out caller cancels the independent owner; admission remains held until pending disk writes finish, any child (including one still being created) is killed/reaped, and the spool is removed. At most two capped input spools and two decoder children can coexist. Normalized D07 DTOs also have a separate two-transaction bound; model serialization stays with the database work. Caller cancellation cannot recall a committing decision: its worker retains admission and DTO ownership until actual completion. Replay with the same decision/key resolves that ambiguous outcome as before.

Wait investigation and cause evidence

Temporary test-only timestamp/stack diagnostics, outside the repository, observed:

  • Fresh Gemini suite: 10 passed; first create_search_tool took 484.81 ms, subsequent construction 0.12 ms, and the canonical worker completed promptly.
  • Isolated PostgreSQL parser/running-tool diagnostic: both parser tests passed, but the running-tool test failed at entered.wait(3). At 2.5 seconds the API thread stack was importing langchain_core callbacks/manager/stdout and utility modules through StructuredTool. First tool construction took 3,366.14 ms; the test thread's three-second provider-entry wait expired before the framework coroutine entered the search worker. The worker ran only after the failed fixture began teardown. This is cold initialization crossing the fixture's synchronization deadline, not evidence of a blocked embedding provider or selection transaction. The unit Gemini wait for toolResponse has the same first-framework-invocation placement; its nested-suite failure simply reran the failing unit case and was not a separate configuration defect.
  • API startup now prepares the existing optional framework through the bounded blocking pool before reconciliation/readiness, so cold imports precede voice admission and tool execution. The shared voice unit fixture follows the same ordering. No wait was lengthened, assertion weakened or test skipped. The framework remains optional for document-only installations; broken installed dependencies still fail startup rather than being silently ignored.
  • The historical parser failures stalled at connected-state observation (one case) and the server's shutdown wait (the other). They did not reproduce in the diagnostic or completed acceptance runs. Their original cause remains unresolved: the interrupted, concurrently loaded earlier run does not provide sufficient evidence to classify them as runtime, fixture, leaked work or environment failures. No parser/transport runtime or assertion was changed. Passing repetitions do not certify an intermittent parser defect fixed.

Actual processing measurements and regression mapping

The generated transport tests cover 4,499 and 10,000 unique 500-character IDs including escaped surrogate pairs, plus a 2,000-character Unicode note. A 10 ms heartbeat runs across the actual receive/spool/decode/loads/validate/transfer path; its maximum gap must stay below 100 ms, well below the reproduced old stalls. No sleeping parser mock is used for this responsiveness assertion.

Finding/invariant Exact test source
Decoder/GIL responsiveness for actual 26.8/59.5 MB valid bodies tests/unit/test_json_processing.py::test_real_large_escaped_json_keeps_concurrent_loop_active (4,499/10,000 IDs)
Timeout/cancellation retains admission and spool ownership through actual disk completion test_admission_retained_until_cancelled_disk_work_and_spool_release (cancel/timeout)
Cancellation during process creation reaps the eventual real child before release test_cancel_during_child_creation_reaps_child_before_releasing_admission
Malformed large JSON, invalid UTF-8, invalid DTO test_large_malformed_or_invalid_dto_is_safe (three cases)
Cancelled review transaction retains normalized DTO and admission until completion test_cancelled_decision_keeps_normalized_dto_admitted_until_transaction_finishes
Cold framework preparation precedes live admission, outside the loop; optional dependency preserved tests/unit/test_phase3_acceptance_repairs.py::test_framework_prepared_off_loop_before_reconciliation_and_readiness, test_document_only_installation_keeps_framework_optional
First real Gemini tool correlation and canonical result Both variants of tests/unit/test_gemini_live.py::test_native_tool_correlation_canonical_result_and_once_only_continuation; complete ten-case Gemini suite
Real provider-entry/revocation synchronization, parser and large-review persistence Complete tests/integration/test_realtime_phase3_http.py (25 cases), including test_http_selection_removal_cancels_running_runtime_tool, both test_real_parser_invalid_utf8_persists_protocol_error variants and both test_large_eligible_review_persists_and_replays variants
Prior repairs, streamed oversize/pre-extension rejection, zero unauthenticated/CSRF consumption, receive/retry timeouts Unchanged cases in tests/unit/test_phase3_http_repairs.py; all 55 original tests/unit/test_phase3_repairs.py remain byte-identical to 9be4719

Observed baseline on this machine using the same actual JSON and ReviewDecision validator: inline maximum heartbeat gaps 219.08/431.75 ms; a thread still produced 215.07/336.19 ms gaps. This directly supports using a separate GIL rather than claiming that thread offload proves voice responsiveness. The final focused child processing run measured 26,784,224 bytes in 1,069.90 ms (103 heartbeat ticks, maximum gap 14.03 ms) and 59,504,172 bytes in 1,329.13 ms (130 ticks, maximum gap 11.64 ms). These are measured scheduler gaps and end-to-end processing latency, not an SLA or real speech/hardware certification. Smaller intermediate focused runs measured gaps of 10.71–13.42 ms; they are not substituted for the final run.

Exact final commands and outcomes

All pytest commands used the existing Linux environment and local socket access; there were no real provider calls. Final focused measurements above came from:

.venv/bin/python -m pytest tests/unit/test_json_processing.py tests/unit/test_phase3_acceptance_repairs.py tests/unit/test_phase3_http_repairs.py tests/unit/test_phase3_repairs.py tests/unit/test_gemini_live.py -q -s -p no:cacheprovider --tb=short
# 92 passed in 11.37s; includes all 55 restored ingestion cases and ten Gemini cases.
.venv/bin/python -m pytest -m "not postgres" -q -p no:cacheprovider --tb=short
# FINAL: 1753 passed, 2 existing Windows-path skips, 397 PostgreSQL cases deselected;
# 161.89s. Includes the nested full-suite ambient-configuration acceptance driver.
TEST_DATABASE_URL=postgresql+psycopg://postgres:fixture@127.0.0.1:55439/rag_json_test .venv/bin/python -m pytest tests/integration/test_realtime_phase3_http.py -m postgres --require-postgres -q -p no:cacheprovider --tb=short
# FINAL completed run: 25 passed, zero skips, 369.84s.
env -u TEST_DATABASE_URL .venv/bin/python -m pytest tests/integration/test_realtime_phase3_http.py::test_large_eligible_review_persists_and_replays -m postgres --require-postgres -q -p no:cacheprovider --tb=short
# Expected exit 1: two setup errors, TEST_DATABASE_URL required, 0.57s; zero skips.
git diff --check
# Passed. Eight affected Python AST parses and new-file whitespace checks passed.

Diagnostic/intermediate commands and outcomes are preserved rather than silently replaced by final successes:

PYTHONPATH=/tmp:. .venv/bin/python -m pytest tests/unit/test_gemini_live.py -q -s -p no:cacheprovider -p phase3_wait_diagnostics --tb=short
# Temporary timestamp/stack plugin: 10 passed in 1.82s; 484.81 ms cold construction.
.venv/bin/python -m pytest tests/unit/test_gemini_live.py -q -p no:cacheprovider --tb=short
# Without diagnostic wrappers: 10 passed in 1.50s, before the repair.
PYTHONPATH=/tmp:. TEST_DATABASE_URL=postgresql+psycopg://postgres:fixture@127.0.0.1:55439/rag_json_test .venv/bin/python -m pytest tests/integration/test_realtime_phase3_http.py -k 'running_runtime_tool or real_parser' -m postgres --require-postgres -q -s -p no:cacheprovider -p phase3_wait_diagnostics --tb=short
# Before framework preparation: 2 passed, 1 failed, 22 deselected in 30.47s;
# 3366.14 ms cold import with live stack evidence; no interruptions/skips.
TEST_DATABASE_URL=postgresql+psycopg://postgres:fixture@127.0.0.1:55439/rag_json_test .venv/bin/python -m pytest tests/integration/test_realtime_phase3_http.py -k 'running_runtime_tool or real_parser' -m postgres --require-postgres -q -p no:cacheprovider --tb=short
# After preparation: 3 passed, 22 deselected, zero skips in 19.04s.
PYTHONPATH=. .venv/bin/python /tmp/phase3-thread-measure.py
# Temporary generated-body comparison: same decision_bytes(4499/10000) fixture,
# actual validate_json(raw, ReviewDecision), inline versus asyncio.to_thread,
# concurrent 10 ms monotonic heartbeat; measurements recorded above.

The temporary diagnostic plugin and comparison script live outside the repository. An initial focused JSON run had 78 passes and one test-harness spawn error: pytest's automatically generated name for 70,000 invalid bytes made PYTEST_CURRENT_TEST exceed the OS environment-entry limit. Explicit short parameter IDs corrected that harness error without changing payloads/assertions. A 67-case HTTP/Gemini/startup checkpoint passed. Focused checkpoints passed 90 and 91 cases as lifetime and optional-framework regressions were added; complete provider-free checkpoints passed 1,751 and 1,752 cases before the final 1,753-case run. An earlier completed affected PostgreSQL run passed all 25 cases in 365.18s before the final retained-DTO lifetime pass. No acceptance run in this follow-up was interrupted or counted as success while unfinished.

At task start 238 repository files were hashed. Only seven baseline files changed: app/api/v1/dependencies.py, app/api/v1/documents.py, app/main.py, app/modules/knowledge/langchain_tool.py, tests/unit/test_realtime_phase1.py, this handoff and the reference map. The other 231 remain byte-identical, including all 55 restored ingestion regressions, both provider adapters/selection, OCR profiles and independent factual approval, original/protected inputs, shared retrieval and applied migrations 0001–0005. Three scoped files were added: app/infrastructure/json_processing.py, tests/unit/test_json_processing.py and tests/unit/test_phase3_acceptance_repairs.py. Unrelated prior working-tree edits were retained. No production UI, dependency, external service, parser replacement or unrelated refactor was introduced.

The only unresolved historical wait cause is the earlier parser connected-state/ shutdown stall; its origin is not inferred from later green runs. This follow-up has completed affected acceptance, not real-provider quality certification. Funded Gemini/OpenAI selected-model acceptance, Persian speech, browser microphone/playback hardware, actual frontend UI and production HTTPS/proxy acceptance remain unrun and require their respective credentials, opt-in, approved corpus/calibration and deployment/hardware prerequisites.

Final database cleanup: rag-phase3-json-test was created with docker run --rm -d --name rag-phase3-json-test --tmpfs /var/lib/postgresql/data -e POSTGRES_PASSWORD=fixture -e POSTGRES_DB=rag_json_test -p 127.0.0.1:55439:5432 pgvector/pgvector:pg16. After completed acceptance, SQL inspection found zero application test schemas (excluding the intended test_vector extension namespace) and zero public tables. docker stop rag-phase3-json-test removed the container and its tmpfs database. No existing database/container was modified.