Files
rag-technical-docs-assistant/docs/guides/phase4-backend-operations.md
11linear11 42f5b9e854 fix(ops): harden backend startup and worker recovery
Install modular API, voice and embedding extras and use the supported single-process server entrypoint. Drain worker SIGTERM shutdown within the Compose grace period.

Add isolated HTTPS embedding fixtures, bounded intake execution and reproducible account, publication, restart, lease-recovery and shutdown acceptance. Eight operational scenarios passed with zero real-provider calls.
2026-10-09 17:44:04 -04:00

10 KiB
Raw Permalink Blame History

Phase 4 backend startup and recovery

This guide describes the modular document/voice backend. The older prototype chat instructions in README are not its deployment procedure. Provider readiness, measured retrieval quality and actual browser acceptance are separate gates. See the acceptance report for executed results, correlations, actual failures and remaining prerequisites.

Isolated provider-free deployment verification

The harness uses the actual Dockerfile, online Alembic migrations, application lifespan, opaque-cookie authentication, HTTP upload/review/retry/selection and worker. It creates one API process, a separate worker, PostgreSQL/pgvector and persistent named original/extraction/database volumes. A deterministic HTTP embedding fixture exercises the real embedding adapter. It certifies operations, never retrieval quality or human approval. Generated fixture decisions are explicitly synthetic and never apply to the four approved originals.

The API/DB publish only loopback ports 18080/55459. The worker and embedding fixture use only the internal network. API/DB additionally join a bridge for host access; no real keys are supplied and no deployment .env is read. The fixture embedding profile is intentionally separate from the frozen real profile. Never repoint the harness at an existing database, reuse its fixture account in production, or replace an operational profile with this fixture profile. The fixture uses HTTPS with a generated two-day certificate and a test-only trusted CA; normal hostname/certificate verification stays enabled. This internal fixture TLS does not certify public HTTPS/WSS deployment.

From repository root, with Docker, OpenSSL and the existing .venv:

.venv/bin/python -m tests.phase4_operations --prepare --env-file /tmp/rag-phase4-ops.env
export ACCEPTANCE_ENV_FILE=/tmp/rag-phase4-ops.env
export ACCEPTANCE_TLS_DIRECTORY=/tmp/rag-phase4-ops-tls
docker compose -p rag-phase4-ops -f tests/support/phase4-compose.yml build migrations
docker compose -p rag-phase4-ops -f tests/support/phase4-compose.yml up -d db embedding migrations api worker
.venv/bin/python -m tests.phase4_operations --verify --env-file /tmp/rag-phase4-ops.env --output /tmp/phase4-operations.json
docker compose -p rag-phase4-ops -f tests/support/phase4-compose.yml down

Use unused ports/project names or stop on a collision; do not stop existing services to make room. --prepare and --verify require new file paths. Verify requires an empty fixture organization/database, so a complete second run needs a new isolated database/project or removal of only this harness's volumes after retaining its evidence. down preserves named volumes. Service recreation within the verification run must preserve them. Never use down -v on an operational project; removing task-owned volumes after acceptance is test cleanup only.

Timing uses monotonic clocks: scenario elapsed time includes the actions named in the scenario, polling and service recreation. It is not per-turn speech or search latency. Reports include real HTTP request IDs, actor/document/job/live IDs, terminal outcomes, fixture-call counts and zero real-provider calls. They omit passwords, cookies, CSRF and provider tokens, source bodies and audio.

Operational configuration and startup

Install .[api,voice,embedding] for this backend, or build the repository Dockerfile. Set the actual frozen embedding provider/endpoint/model/dimension/preprocessing and request limits, INGEST_DATABASE_URL, and durable original/extraction paths. Configured endpoint/model request limits must be established before real embedding work; do not invent limits or change a persisted profile to bypass validation. Verify the canonical embedding endpoint is reachable from each actual API/worker process. Host localhost:11434 is not container localhost. A host Ollama inventory probe alone cannot establish container reachability. Preserve the frozen endpoint identity when choosing the deployment topology; do not silently rewrite profiles or database comments to switch to a different host address. Configure VOICE_PROVIDER=gemini for the temporary Gemini selection and the corresponding server-side key/model/voice. OpenAI remains selectable with its separate key/profile and no automatic fallback. A key is not call authorization.

Authentication has no session-secret setting. It generates random opaque tokens, stores token hashes in PostgreSQL and derives CSRF with HMAC keyed by the session token. Provision enabled accounts through app.bootstrap / app.provision; do not manually mint cookies or put provider keys in the frontend.

For loopback direct HTTP on 8080:

TRUSTED_HOSTS=["localhost:8080","127.0.0.1:8080"]
TRUSTED_ORIGINS=["http://localhost:8080","http://127.0.0.1:8080"]
COOKIE_SECURE=false
INGEST_OCR_REVIEW_REQUIRED=true

For the developer UI proxy, also configure its exact Host/Origin as explained in the connection handoff. Use Secure cookies and explicit HTTPS Origin/Host in deployment. The API process must use app.server, which selects the bounded parser; generic Uvicorn defaults are not the supported voice transport admission path.

alembic upgrade head
python -m app.bootstrap --organization-name "Example" --username admin --assistant-name "Assistant" --instruction "Answer from authorized documents."
python -m app.provision --username acceptance-user --role user
python -m app.server --host 0.0.0.0 --port 8080
# Separate process, only against an approved queue and within ingestion budget:
python -m app.worker

Password commands prompt securely; automation can use --password-stdin from a secure pipe. Bootstrap is only for a new installation and refuses to reset an existing organization. Never downgrade or edit applied migrations 0001–0005.

Existing production Compose starts migrations before one API and the separate worker, with shared durable original/extraction directories. Build with docker compose build; start DB/migrations/API explicitly while ingestion authorization is absent. Start worker only once its queue and call budget are approved. The worker itself has no budget CLI: --once caps jobs, not provider requests; one PDF can require multiple paid calls. Do not use it as a call cap.

/health/live checks process transport and /health/ready checks the lifespan readiness flag after reconciliation. They never call providers. Database-ready HTTP may be usable while capabilities.voice=false / CALIBRATION_REQUIRED correctly prevents an ungrounded voice session.

Shutdown and recovery

SIGTERM tells the worker to stop claiming new jobs and wakes idle polling. An already owned job completes through the existing claim/heartbeat/fencing path; the worker then disposes its database engine. Production Compose allows 90 seconds for this drain. If a long job exceeds the grace period, forced termination is recovered by lease expiry/reclaim; never manually publish partial chunks or reset claim tokens. The harness kills a blocked fixture embedding request and verifies a second fenced attempt publishes one complete chunk, with no duplicate.

The API completes application lifespan cleanup on shutdown. Uvicorn may then re-raise SIGTERM (container exit 143 / subprocess -15); that alone is not a cleanup failure. Require the shutdown-complete evidence and reject a forced SIGKILL. On recreation, startup reconciliation marks abandoned live sessions/tools failed before readiness. Reauthenticate as needed and create a new voice session. Resolve ambiguous create/upload/review/retry results by replaying the retained key/payload; do not silently reconnect or switch providers.

Ready documents remain inactive until explicit K02 selection. Complete genuine pending extraction decisions and independent factual approval before same-job retry. OCR policy defaults true and is frozen per job; false does not waive factual or legacy review. Do not invent human checks, calibrate against held-out questions, or rewrite originals to make failed acceptance pass.

Remaining frontend and deployment checks

The frontend developer must execute these through the actual UI with approved accounts/corpus and separately bounded provider authorization:

  • Login/reload/logout, safe errors and request ID display; server permissions, trusted Origin/Host, cookie and CSRF behavior.
  • Upload uncertainty/replay, polling cancellation, review evidence/preview and genuine decisions; explicit same-job retry and complete-set selection conflicts.
  • Persian speech recognition, audible playback, transcripts and source display; factual questions, follow-ups, topic changes, ambiguity and unsupported evidence.
  • Microphone/worklet ownership, actual played-sample progress, interruption during search/playback, provider loss, logout/revocation and API restart recovery.
  • Confirm the UI has no provider selector, secrets or automatic approval/retry.

HTTPS/WSS deployment needs an authorized endpoint, domain/certificate, reverse proxy upgrade/timeouts, exact Origin/Host, Secure cookies and durable volumes. Run external browser TLS/WSS, disconnect, audio and recovery checks there. Missing TLS infrastructure is a deployment prerequisite, not a UI dependency.

Explicit uncalibrated connectivity testing: set VOICE_TRANSPORT_TESTING=true and restart the API. Configure a compatible embedding adapter, credentials and bounded request limits first. Pending/missing calibration then permits voice reservation and provider streaming; create/recovery/poll report calibration_status: "uncalibrated". F01 also reports the policy and calibration status. Treat this as connectivity testing: shared search still returns CALIBRATION_REQUIRED with no sources. Disable the policy for strict admission; existing reservations remain pinned and may require a new session after policy or calibration changes. No automatic provider switch, calibration or paid call occurs when enabling the policy. Existing client examples tolerate the additive metadata; the actual developer UI should display the status.