Runtime Topology
Backend Startup Sequence
1. Loads env vars
2. Configures logging and binds the TCP listener for `PORT` early
3. Parse and validate runtime config from env vars for search, chat, Databricks analytics, Google TTS, local ASR, security, and Ollama
4. Configures Google Cloud clients with Application Default Credentials
5. Connects to the GCS data bucket
6. Restores the local libSQL snapshot from GCS
7. Initializes libSQL schema, builds the store, reconciles SQL cache rows, and may publish a fresh snapshot
8. Builds shared runtime services and `AppState`
9. Starts search progress hydration
10. Starts FTS hydration when the keyword index is empty
11. Starts background worker loops
12. Builds the Axum router and serves the listenerShared Runtime State
AppState is the boundary shared by Axum handlers, services, chat generation, and background workers.
| Area | AppState owns |
|---|---|
| Storage | GCS object store, local libSQL store, read cache |
| Security | runtime auth config, request rate limiter, mobile auth handoff sessions |
| Search | auto-create-vector-index flag, projection lock, progress tracker, FTS index, search service |
| Chat | chat service, input guardrail service, active chats tracker, chat store lock, anonymous chat quota |
| Source services | YouTube service, OpenAlex planner/service, podcast feed service, website ingestion, transcript client |
| Model services | optional Google TTS service, summarizer service, summary evaluator service |
| Observability | optional Databricks analytics sink |
| Cooldowns | cloud, YouTube quota, and transcript dependency trackers |
| Activity gating | user activity tracker |
AppState is process-wide. The backend builds it once at startup and shares it across all requests and worker loops.
AccessContext is separate request-scoped state. Auth middleware attaches it to each HTTP request. Handlers read AppState for shared services and AccessContext for caller-specific access data.
AccessContext field | Used for |
|---|---|
user_id | authenticated user scope for chats, highlights, and library |
auth_state | distinguishes authenticated and anonymous request paths |
access_role | enables operator-only behavior |
allowed_channel_ids | bounds visible channel scope |
allowed_other_video_ids | bounds explicit video access outside subscribed channels |
Parallel Worker Loops
The hosted backend (PROCESSING_ROLE=remote) starts five worker loops in parallel. The local app (PROCESSING_ROLE=local-fetcher) runs only the YouTube transcript fetcher. Standalone development can use PROCESSING_ROLE=combined to run the original pipeline.
| Worker | Runtime role |
|---|---|
| Queue worker | advances transcript work before summary work |
| Refresh worker | fetches latest videos for subscribed channels |
| Gap scan worker | backfills missing historical videos |
| Summary evaluation worker | scores summaries and can queue low-quality regeneration |
| Search index worker | backfills, indexes, reconciles, prunes, and syncs FTS |
All five hosted loops skip scheduled work when there is no recent active user. Model and external-service failures can also activate a cooldown for the affected path.
Cloud Run also gives the backend CPU only while a request is in flight. So that new videos arrive without anyone reading, Cloud Scheduler calls POST /api/internal/catch-up every 4 hours. The call counts as activity, refreshes every channel, and stays open while pending transcripts and summaries are processed, for at most 10 minutes. It accepts only an OIDC token from the scheduler service account (terraform/scheduler.tf). Worker cadence, batch sizes, and cooldown values live in Runtime Limits.
The search index worker also:
1. performs initial backfill, reconcile, prune, and vector-index checks before its loop
2. reconciles stale search rows on its configured cadence
3. retries ANN vector-index creation on its configured cadence
4. logs indexing rounds with batch and embedding countsConcurrency Controls
YouTube Transcript Handoff
The hosted queue writes missing transcript requests to youtube-transcript-requests/ in GCS. It does not run YouTube caption extraction. The local worker checks these requests every minute, downloads at most four per round, and writes results under youtube-transcript-results/. It runs whenever the local backend is running, without browser activity.
The hosted process imports completed transcripts into its own video state and search index, then generates and evaluates the articles. Catch-up keeps CPU available for pending evaluations as well as generation. Requests waiting on the local machine do not consume failure retries or block other ready jobs. If the hosted service is idle, completed results wait until a reader request or the next scheduled catch-up (every four hours).
Each request has a unique identity. Resetting or deleting a video cancels its request; late results from a previous request cannot replace a new one. Temporary fetch failures store a 15-minute retry deadline in youtube-transcript-retries/, which survives local restarts.
The local fetcher reads GCS job objects directly, so its SQL cache can be older than the hosted cache without losing jobs. It does not publish SQL snapshots or update hosted video metadata. The hosted process owns status changes and snapshot publication. Podcast transcription, channel discovery, summarization, evaluation, and indexing remain on the hosted backend.
Projection Lock
Search rebuilds and index maintenance coordinate through a RwLock. Destructive projection resets, normal search reads, and indexing writes share that lock.
AI Model Request Concurrency
To keep concurrency bounded, the backend uses separate semaphores per lane:
- summary/evaluator/chat/guardrails/planner share one lane (applies only to local models, cloud-tagged models skip that check)
- search embedding/rerank/HyDE share another lane
Semaphore sizes live in Runtime Limits.
Runtime Throttles
HTTP handlers share the request rate limiter from AppState. Cloud-model calls, YouTube quota failures, and transcript dependency failures each have their own cooldown tracker. Rate and cooldown values live in Runtime Limits.
Client Processes
The frontend and Tauri shell call the backend through the configured API base.