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:
- WAL & Integrity Pragmas (
app/core/db.py): Every SQLite connection enforcesPRAGMA journal_mode=WAL,PRAGMA foreign_keys=ON,PRAGMA busy_timeout=5000, andPRAGMA synchronous=NORMAL, with0700permissions on the local data directory. - Typed SQLModel Schema & Alembic (
alembic/versions/0001_phase2_initial_schema.py): Tables coverUser,AuthIdentity,EmailOtpCode,AuthSession,PairedDevice,ConversationSession,MessageTurn,GrammarCorrection,PronunciationScore,RoleplayPreset, andUserSettings, with cascading account deletion (DELETE /api/me) removing both DB rows and stored audio clips. - Deterministic Catalog Seeder (
app/sessions/seeds.py):speakon seedpopulates 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 withsecrets, salted with HMAC-SHA256 usingSPEAKON_SECRET_KEY, limited to 5 verification attempts per challenge and rate-limited per IP and email. Out of the box,docker compose up -d mailpitruns Mailpit (127.0.0.1:1025SMTP /127.0.0.1:8025UI) for zero-cost local OTP testing, with optional Resend delivery when configured online. .env-Gated Apple & Google OAuth (app/auth/oauth.py): SettingSPEAKON_APPLE_CLIENT_IDorSPEAKON_GOOGLE_CLIENT_IDSautomatically activatesSign in with AppleandSign in with GoogleinGET /api/auth/providersusing 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 verifiedX-SpeakOn-Devicepairing header issued viaPOST /api/pairing/devices(with terminal QR code rendering for LAN Wi-Fi or USBadb 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 Largeon oversize input), decoded, transcribed viaSTTProvider, evaluated with heuristic word-confidence pronunciation scoring (app/pipeline/pronunciation.py), answered byLLMProvider, synthesized in sentence-sized chunks viaTTSProvider, and saved atomically underSPEAKON_DATA_DIR/audio/. GET /api/audio/{turn_id}enforces strict ownership checks and HTTP206 Partial ContentRangerequests for smooth scrubbing in browsers and mobile players.- Over WebSockets, speech/text triggers emit ordered
stt.final,llm.reply, interleavedtts.chunkmetadata + binary WAV frames, andturn.done—while an incomingbarge_inframe cancels in-flight generation immediately so learners can interrupt the tutor mid-sentence.
Four Production Bugs Caught During Verification#
sqlmodel==0.0.50Strict UTC Enforcement: Passing naivedatetime.utcnow()timestamps toUTCDateTime()columns throwsValueError: Datetime values must have timezone information. Switchingutc_now()todatetime.now(UTC)fixed all timestamp writes cleanly.- Detached ORM Instances in ASGI Middleware: Reading
device.idafter exitingwith Session(engine) as db:raisedDetachedInstanceErrorbecauseverify_device_headercommitted inside the context manager. Extracting scalardevice_idinside theSessionscope eliminated the crash. - SQLite
os.replaceRestore vs. Pooled File Descriptors: Even after an atomicsqlite3.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. - Docker Compose Inactive Profile Variable Validation: Placing
${SPEAKON_POSTGRES_PASSWORD:?...}inside aprofiles: ["postgres"]service still causesdocker compose up -d mailpitto 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, andmypy app(54files) all passed with zero errors;scripts/export_openapi.py --checkconfirmedopenapi.jsonmatches the live FastAPI contract. - Automated Test Suite:
uv run pytest -m "not gpu" -vpassed 30 / 30 CPU contract, auth/security, WebSocket voice/barge-in, analytics, and backup/restore tests (9GPU 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 liveuvicorn(/health/ready200on RTX 3070 + Ollama + SQLite WAL) delivering a real 6-digit OTP to Mailpit and authenticating/api/me. - Security Scanning & CI:
gitleaks protect --staged, full-historygitleaks detect, and GitHub Actions (CIandGitleaks Secret Scanondevelop) 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.
