Skip to content

Runtime Topology ​

Backend Startup Sequence ​

text
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 listener
Startup flow: bind the backend port first, initialize storage and services, hydrate search state in background tasks, start worker loops, then serve HTTP routes.

Shared Runtime State ​

AppState is the boundary shared by Axum handlers, services, chat generation, and background workers.

AreaAppState owns
StorageGCS object store, local libSQL store, read cache
Securityruntime auth config, request rate limiter, mobile auth handoff sessions
Searchauto-create-vector-index flag, projection lock, progress tracker, FTS index, search service
Chatchat service, input guardrail service, active chats tracker, chat store lock, anonymous chat quota
Source servicesYouTube service, OpenAlex planner/service, podcast feed service, website ingestion, transcript client
Model servicesoptional Google TTS service, summarizer service, summary evaluator service
Observabilityoptional Databricks analytics sink
Cooldownscloud, YouTube quota, and transcript dependency trackers
Activity gatinguser 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 fieldUsed for
user_idauthenticated user scope for chats, highlights, and library
auth_statedistinguishes authenticated and anonymous request paths
access_roleenables operator-only behavior
allowed_channel_idsbounds visible channel scope
allowed_other_video_idsbounds 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.

WorkerRuntime role
Queue workeradvances transcript work before summary work
Refresh workerfetches latest videos for subscribed channels
Gap scan workerbackfills missing historical videos
Summary evaluation workerscores summaries and can queue low-quality regeneration
Search index workerbackfills, 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:

text
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 counts

Concurrency 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.

Concurrency boundaries: workers share AppState, search projection changes coordinate through a read/write lock, and model-heavy paths are rate-limited separately.

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:

  1. summary/evaluator/chat/guardrails/planner share one lane (applies only to local models, cloud-tagged models skip that check)
  2. 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.