Engineering BlueprintFastAPISQLiteSecurityAuthWebSocketsSpeakOnReliabilityDocker

SpeakOn Phase 2: Local-First Orchestrator with SQLite WAL, Passwordless OTP Auth, and Barge-In Voice Streaming

Designing the Phase 2 FastAPI desktop orchestrator for SpeakOn: SQLite WAL + Alembic, Mailpit passwordless OTP and OAuth JWKS, X-SpeakOn-Device LAN pairing…

Célio Vieira809 words5 min read

Key Takeaways (TL;DR)

Summary
  • Turning an AI Pipeline into a Stateful Local-First Server — A fast speech-to-speech pipeline is only a demo until it persists sessions safely, authenticates clients without…
  • Storage & Schema: SQLite WAL, Foreign Keys, and Alembic — SpeakOn stores all learner state on the user's machine with zero mandatory cloud database:
  • Passwordless Authentication & LAN Device Isolation — SpeakOn has zero password fields anywhere in its schema, API, or logs:
  • Voice Pipeline, Pronunciation Feedback, and Barge-In — Both POST /api/sessions/{id}/turn and /ws/sessions/{id}/voice run the complete local loop cleanly:

Turning an AI Pipeline into a Stateful Local-First Server#

A fast speech-to-speech pipeline is only a demo until it persists sessions safely, authenticates clients without storing passwords, isolates LAN devices from loopback callers, and survives restarts or corrupt writes cleanly.

In Phase 2 of SpeakOn, we built the production FastAPI desktop orchestrator inside speakon-services (develop), wiring SQLite in WAL mode, Alembic migrations, three passwordless authentication providers, WebSocket and REST voice pipelines, learning analytics, and crash-safe CLI tooling.

Storage & Schema: SQLite WAL, Foreign Keys, and Alembic#

SpeakOn stores all learner state on the user's machine with zero mandatory cloud database:

  1. WAL & Integrity Pragmas (app/core/db.py): Every SQLite connection enforces PRAGMA journal_mode=WAL, PRAGMA foreign_keys=ON, PRAGMA busy_timeout=5000, and PRAGMA synchronous=NORMAL, with 0700 permissions on the local data directory.
  2. Typed SQLModel Schema & Alembic (alembic/versions/0001_phase2_initial_schema.py): Tables cover User, AuthIdentity, EmailOtpCode, AuthSession, PairedDevice, ConversationSession, MessageTurn, GrammarCorrection, PronunciationScore, RoleplayPreset, and UserSettings, with cascading account deletion (DELETE /api/me) removing both DB rows and stored audio clips.
  3. Deterministic Catalog Seeder (app/sessions/seeds.py): speakon seed populates 22 idempotent roleplay presets across Tier 1 (en, es, zh) and Tier 2 (pt, de, it, fr) languages.

Passwordless Authentication & LAN Device Isolation#

SpeakOn has zero password fields anywhere in its schema, API, or logs:

  • Passwordless Email + 6-Digit OTP (app/auth/): Codes are generated with secrets, salted with HMAC-SHA256 using SPEAKON_SECRET_KEY, limited to 5 verification attempts per challenge and rate-limited per IP and email. Out of the box, docker compose up -d mailpit runs Mailpit (127.0.0.1:1025 SMTP / 127.0.0.1:8025 UI) for zero-cost local OTP testing, with optional Resend delivery when configured online.
  • .env-Gated Apple & Google OAuth (app/auth/oauth.py): Setting SPEAKON_APPLE_CLIENT_ID or SPEAKON_GOOGLE_CLIENT_IDS automatically activates Sign in with Apple and Sign in with Google in GET /api/auth/providers using live JWKS signature verification and automatic identity linking.
  • Rotating Refresh Families & Reuse Detection: Rotating a refresh token invalidates the prior token in the family; presenting a revoked token revokes the entire token family immediately.
  • Loopback vs. Paired Mobile LAN Guard (LANDeviceAuthMiddleware): Loopback requests work cleanly for the local web UI, whereas any non-loopback request (speakon run --lan) must present a verified X-SpeakOn-Device pairing header issued via POST /api/pairing/devices (with terminal QR code rendering for LAN Wi-Fi or USB adb reverse).

Voice Pipeline, Pronunciation Feedback, and Barge-In#

Both POST /api/sessions/{id}/turn and /ws/sessions/{id}/voice run the complete local loop cleanly:

  • Incoming audio uploads are streamed in chunks and bounded at SPEAKON_MAX_AUDIO_BYTES (413 Payload Too Large on oversize input), decoded, transcribed via STTProvider, evaluated with heuristic word-confidence pronunciation scoring (app/pipeline/pronunciation.py), answered by LLMProvider, synthesized in sentence-sized chunks via TTSProvider, and saved atomically under SPEAKON_DATA_DIR/audio/.
  • GET /api/audio/{turn_id} enforces strict ownership checks and HTTP 206 Partial Content Range requests for smooth scrubbing in browsers and mobile players.
  • Over WebSockets, speech/text triggers emit ordered stt.final, llm.reply, interleaved tts.chunk metadata + binary WAV frames, and turn.done—while an incoming barge_in frame cancels in-flight generation immediately so learners can interrupt the tutor mid-sentence.

Four Production Bugs Caught During Verification#

  1. sqlmodel==0.0.50 Strict UTC Enforcement: Passing naive datetime.utcnow() timestamps to UTCDateTime() columns throws ValueError: Datetime values must have timezone information. Switching utc_now() to datetime.now(UTC) fixed all timestamp writes cleanly.
  2. Detached ORM Instances in ASGI Middleware: Reading device.id after exiting with Session(engine) as db: raised DetachedInstanceError because verify_device_header committed inside the context manager. Extracting scalar device_id inside the Session scope eliminated the crash.
  3. SQLite os.replace Restore vs. Pooled File Descriptors: Even after an atomic sqlite3.Connection.backup() + os.replace, an existing SQLAlchemy connection pool still holds file descriptors bound to the unlinked pre-restore inode. Disposing the engine (engine.dispose()) after restore ensures subsequent reads immediately see restored data.
  4. Docker Compose Inactive Profile Variable Validation: Placing ${SPEAKON_POSTGRES_PASSWORD:?...} inside a profiles: ["postgres"] service still causes docker compose up -d mailpit to abort during global YAML interpolation. Defaulting to ${SPEAKON_POSTGRES_PASSWORD:-} allows SQLite + Mailpit startup with zero boilerplate while PostgreSQL still fails fast if started without a password.

Verification & Quality Gates#

  • Static Analysis & Schema: ruff check, ruff format --check, and mypy app (54 files) all passed with zero errors; scripts/export_openapi.py --check confirmed openapi.json matches the live FastAPI contract.
  • Automated Test Suite: uv run pytest -m "not gpu" -v passed 30 / 30 CPU contract, auth/security, WebSocket voice/barge-in, analytics, and backup/restore tests (9 GPU tests deselected for CPU CI).
  • Live E2E & CLI Lifecycle: Verified idempotent alembic upgrade head, speakon seed (22 presets), speakon backup + SHA-256 manifest + speakon restore, and live uvicorn (/health/ready 200 on RTX 3070 + Ollama + SQLite WAL) delivering a real 6-digit OTP to Mailpit and authenticating /api/me.
  • Security Scanning & CI: gitleaks protect --staged, full-history gitleaks detect, and GitHub Actions (CI and Gitleaks Secret Scan on develop) all passed cleanly.

Next up in Phase 3: building the consolidated Web UI in aldeon/app/src/routes/speakon/ with zero backend code inside the web app.

Célio Vieira

Célio Vieira

Founder & Architect

Engineering applied AI systems, distributed cloud platforms, and the Aldeon umbrella venture ecosystem.

Related Technical Dispatches

View all 90