Skip to content

Production Deployment Guide

This guide describes how to deploy LLARS in a production environment.

Security note

Production deployments require additional security measures. This guide is a starting point — adapt it to your requirements.


Prerequisites

Hardware

Component Minimum Recommended
CPU 4 cores 8+ cores
RAM 16 GB 32+ GB
Storage 100 GB SSD 500+ GB NVMe
Network 100 Mbit/s 1 Gbit/s

Software

  • Docker 24.0+
  • Docker Compose 2.20+
  • Git
  • SSL certificate (Let's Encrypt or custom)

1. Prepare server

System updates

sudo apt update && sudo apt upgrade -y
sudo apt install -y docker.io docker-compose-v2 git curl

Docker without sudo

sudo usermod -aG docker $USER
newgrp docker

Firewall

sudo ufw allow 22/tcp    # SSH
sudo ufw allow 80/tcp    # HTTP
sudo ufw allow 443/tcp   # HTTPS
sudo ufw enable

2. Install LLARS

Clone repository

cd /var
sudo mkdir llars
sudo chown $USER:$USER llars
cd llars
git clone https://git.your-server.de/llars/llars.git .

Create production .env

cp .env.template.production .env

Important settings in .env:

# === PRODUCTION SETTINGS ===
FLASK_ENV=production
FLASK_DEBUG=False

# === SECRETS (CHANGE!) ===
SECRET_KEY=$(openssl rand -hex 32)
JWT_SECRET_KEY=$(openssl rand -hex 32)

# === DATABASE ===
MARIADB_USER=llars_prod
MARIADB_PASSWORD=$(openssl rand -hex 24)
MARIADB_ROOT_PASSWORD=$(openssl rand -hex 24)
MARIADB_DATABASE=llars_production

# === AUTHENTIK ===
AUTHENTIK_SECRET_KEY=$(openssl rand -hex 32)
AUTHENTIK_BOOTSTRAP_PASSWORD=$(openssl rand -hex 16)
AUTHENTIK_PUBLIC_URL=https://auth.your-domain.com

# === EXTERNAL ACCESS ===
NGINX_EXTERNAL_PORT=80
VITE_API_BASE_URL=https://llars.your-domain.com/api

# === LLM API ===
LITELLM_API_KEY=your-litellm-key
LITELLM_BASE_URL=https://your-litellm-proxy.com

# === PERFORMANCE ===
GUNICORN_WORKERS=4
GUNICORN_THREADS=4

3. SSL with reverse proxy

If an external Nginx/Traefik/Caddy is available:

# In .env
NGINX_EXTERNAL_PORT=80

Nginx config on the proxy:

server {
    listen 443 ssl http2;
    server_name llars.your-domain.com;

    ssl_certificate /etc/letsencrypt/live/llars.your-domain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/llars.your-domain.com/privkey.pem;

    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Strict-Transport-Security "max-age=31536000" always;

    location / {
        proxy_pass http://llars-server:80;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        # WebSocket support
        proxy_read_timeout 86400;
    }
}

server {
    listen 80;
    server_name llars.your-domain.com;
    return 301 https://$server_name$request_uri;
}

Option B: Internal SSL within LLARS

For standalone deployments without an external proxy:

# Install certbot
sudo apt install certbot

# Obtain certificate
sudo certbot certonly --standalone -d llars.your-domain.com

# Copy certificates into LLARS
sudo cp /etc/letsencrypt/live/llars.your-domain.com/fullchain.pem /var/llars/ssl/
sudo cp /etc/letsencrypt/live/llars.your-domain.com/privkey.pem /var/llars/ssl/

4. Start

First start

cd /var/llars
./start_llars.sh

Check status

docker compose ps
docker compose logs -f --tail=100

Health check

curl -s http://localhost/api/health | jq

5. Set up Authentik

1. Open Authentik admin panel

https://auth.your-domain.com/

Login: akadmin / AUTHENTIK_BOOTSTRAP_PASSWORD from .env

2. Create LLARS application

  1. Admin → Applications → Create
  2. Name: LLARS
  3. Slug: llars
  4. Create provider:
  5. Type: OAuth2/OpenID Provider
  6. Client ID: llars-frontend
  7. Client Secret: (generate and store in .env)
  8. Redirect URIs:
    https://llars.your-domain.com/auth/callback
    https://llars.your-domain.com/
    

3. Create backend provider

  1. Admin → Providers → Create
  2. Type: OAuth2/OpenID Provider
  3. Client ID: llars-backend
  4. For service account/API access

6. Set up backups

Automated database backup

# /var/llars/scripts/backup.sh
#!/bin/bash
BACKUP_DIR=/var/llars/backups
DATE=$(date +%Y%m%d_%H%M%S)

mkdir -p $BACKUP_DIR

# Database backup
docker exec llars_db_service mysqldump -u root -p$MARIADB_ROOT_PASSWORD \
  --all-databases > $BACKUP_DIR/db_$DATE.sql

# Compress
gzip $BACKUP_DIR/db_$DATE.sql

# ChromaDB backup
tar -czf $BACKUP_DIR/chroma_$DATE.tar.gz /var/llars/app/storage/chroma

# Uploads backup
tar -czf $BACKUP_DIR/uploads_$DATE.tar.gz /var/llars/app/storage/uploads

# Cleanup old backups (keep 30 days)
find $BACKUP_DIR -name "*.gz" -mtime +30 -delete

echo "Backup completed: $DATE"

Cron job

# Daily backup at 3:00 AM
echo "0 3 * * * /var/llars/scripts/backup.sh >> /var/log/llars-backup.log 2>&1" | crontab -

7. Monitoring

Docker stats

docker stats --no-stream

Log aggregation

# All logs into one file
docker compose logs -f > /var/log/llars/all.log 2>&1 &

# Errors only
docker compose logs -f 2>&1 | grep -i error > /var/log/llars/errors.log &

Matomo analytics

Already integrated in LLARS. Access via:

https://llars.your-domain.com/analytics/

8. Updates

Standard update

cd /var/llars

# Pull changes
git pull origin main

# Rebuild containers
docker compose build

# Restart
docker compose up -d

# Check logs
docker compose logs -f --tail=100

Update with downtime

cd /var/llars

# Enable maintenance mode (optional)
docker exec llars_flask_service flask maintenance on

# Create backup
./scripts/backup.sh

# Stop containers
docker compose down

# Update
git pull origin main

# Restart
docker compose up -d --build

# Disable maintenance mode
docker exec llars_flask_service flask maintenance off

9. Troubleshooting

502 Bad Gateway

# Check if containers are running
docker compose ps

# Check Nginx logs
docker logs llars_nginx_service

# Check Flask logs
docker logs llars_flask_service

Database connection failed

# MariaDB status
docker logs llars_db_service

# Connection test
docker exec llars_flask_service python -c "from db.db import db; print('OK')"

Authentik login fails

  1. Check AUTHENTIK_PUBLIC_URL in .env
  2. Check client ID and secret
  3. Check redirect URIs in Authentik

ChromaDB errors

# ChromaDB logs
docker logs llars_chromadb_service

# Check vector store
ls -la /var/llars/app/storage/chroma/

10. Security checklist

  • All default passwords in .env changed
  • SSL/TLS enabled
  • Firewall configured
  • Regular backups configured
  • Log rotation enabled
  • Authentik admin password changed
  • Docker socket access restricted to admins
  • No debug logs in production
  • Rate limiting configured (reverse proxy)
  • Security headers set

11. WSGI Server (Gunicorn + Gevent)

In production, LLARS uses Gunicorn with gevent-websocket for:

  • Real WebSocket support (no polling fallback)
  • Better Docker DNS compatibility than eventlet
  • Low idle resource usage (~0.04% CPU, ~380 MB RAM)

Development vs production mode

The PROJECT_STATE environment variable controls the mode:

Mode Server WebSocket Auto-reload
development Flask dev server Polling (threading) ✓
production Gunicorn + gevent Real WebSockets ✗
# In .env
PROJECT_STATE=production  # or development

Gunicorn configuration

Configuration is in docker/flask/gunicorn.conf.py:

# Server
bind = '0.0.0.0:8081'
workers = 1  # With gevent: 1 worker, greenlets handle concurrency

# Worker class for real WebSocket support
worker_class = 'geventwebsocket.gunicorn.workers.GeventWebSocketWorker'

# Timeouts for long LLM requests
timeout = 300  # 5 minutes
graceful_timeout = 30

# Memory leak prevention
max_requests = 1000
max_requests_jitter = 50

WSGI entry points

File Usage
wsgi_gevent.py Production (Gunicorn + gevent)
wsgi.py Eventlet (not recommended for Docker)

Important: gevent.monkey.patch_all() MUST be called before any other imports.

# wsgi_gevent.py
from gevent import monkey
monkey.patch_all()

from main import app, socketio

Async mode

Flask-SocketIO detects async_mode automatically via environment variable:

# Set in start_flask.sh
export SOCKETIO_ASYNC_MODE="gevent"    # Production
export SOCKETIO_ASYNC_MODE="threading" # Development

12. Performance tuning

Gunicorn workers

# In .env (for sync workers, not with gevent)
GUNICORN_WORKERS=4        # CPU cores * 2 + 1
GUNICORN_THREADS=4        # Per worker
GUNICORN_TIMEOUT=120      # For long requests

MariaDB

# my.cnf adjustments
innodb_buffer_pool_size = 4G      # 50-70% of RAM
innodb_log_file_size = 1G
max_connections = 200

ChromaDB

# For large collections
CHROMA_PERSIST_DIRECTORY=/fast-ssd/chroma

13. Load testing

LLARS includes a load test script at scripts/load_test.py.

Quick test

# Local
python scripts/load_test.py --quick --host localhost --port 8081

# In Docker container
docker exec llars_flask_service python3 /app/scripts/load_test.py --quick

Heavy load test

# 100 concurrent users, 20 requests per user, 50 WebSocket connections
python scripts/load_test.py \
  --users 100 \
  --requests 20 \
  --ws-connections 50 \
  --duration 60

Test types

Parameter Description
--test http HTTP API endpoints only
--test websocket WebSocket connections only
--test sustained Sustained load over time
--test all All tests (default)

Benchmark results (as of January 2026)

Server: Production with Gunicorn + gevent-websocket

Metric Value
HTTP Response Time (avg) 8-80 ms
HTTP Response Time (p95) 164 ms
HTTP Response Time (p99) 349 ms
Throughput ~100 req/s
WebSocket Connect Time 135-272 ms
WebSocket Success Rate 100%

Resources after heavy load (9,600 requests):

Container CPU RAM
Flask 0.04% 380 MB
MariaDB 0.02% 112 MB
nginx 0.00% 8 MB
Redis 0.63% 7 MB

Rate limiting

Flask-Limiter protects the API automatically:

  • Default: 1000 requests/hour per endpoint
  • Status code: 429 Too Many Requests
  • Log: ratelimit exceeded at endpoint: ...

14. Blue-Green Deployment

Since March 2026, LLARS uses Blue-Green Deployment for near-zero-downtime updates.

Concept

                    ┌─────────┐
                    │  NGINX  │
                    └────┬────┘
                         │
            ┌────────────┼────────────┐
            ▼                         ▼
    ┌───────────────┐        ┌───────────────┐
    │   BLUE (old)  │        │  GREEN (new)  │
    │  Flask+Vue+YJS│        │  Flask+Vue+YJS│
    └───────────────┘        └───────────────┘
  • Active color serves production traffic
  • Inactive color is built for the next deployment
  • Switching is done via Nginx config update (~2 seconds downtime)

Commands

# Show status
bash scripts/ci/manual_bluegreen_deploy.sh status

# Build inactive color + deploy to staging
bash scripts/ci/manual_bluegreen_deploy.sh prepare

# Run smoke tests against staging
bash scripts/ci/manual_bluegreen_deploy.sh test

# Switch to production
bash scripts/ci/manual_bluegreen_deploy.sh switch

Automated Deployment (CI/CD)

The development branch (dev) auto-deploys on every push to the dev server (llars-dev, 141.75.150.86). The production branch (main) deploys nightly Mon-Fri 02:00 CET via GitLab Pipeline Schedule.

Production nightly flow:

deploy:staging → test:e2e:nightly:tiles → smoke:staging → deploy:production → smoke:production

On failed smoke tests: automatic rollback.

Pipeline Controls

Trigger Staging Production Description
Normal push ✗ ✗ Lint + Tests only
[dryrun] in commit message ✓ ✗ Full staging flow, no prod deploy
DRY_RUN=true (CI variable) ✓ ✗ Same as [dryrun]
FORCE_DEPLOY=true (CI variable) ✓ ✓ Immediate full pipeline
Nightly schedule ✓ ✓ Mon-Fri 02:00 CET

Dry-Run verifies the nightly pipeline will succeed without touching production:

git commit -m "chore: pre-release check [dryrun]"
git push origin main

Rollback

# Instant rollback (~2s, switch Nginx back)
bash scripts/ci/rollback_bluegreen.sh

# Fallback rollback (DB restore + rebuild, 5-10 min)
bash scripts/ci/rollback_production.sh

Key files

File Description
docker-compose.prod-bluegreen.yml Compose override for Blue/Green
docker/nginx/active_upstream.conf Active color (production)
docker/nginx/active_upstream_staging.conf Staging upstream
.deploy/active_color Currently active color
scripts/ci/deploy_bluegreen.sh Deploy script
scripts/ci/rollback_bluegreen.sh Rollback script

Whisper service (voice notes)

Since T-23 (07.10.2026) a service of its own transcribes the voice notes of support tickets on the host CPU. It is called whisper-service, lives in docker-compose.yml behind the profile whisper and uses the image ghcr.io/speaches-ai/speaches:0.9.0-rc.3-cpu (faster-whisper, int8). The container is llars_whisper_service, the models live in the volume llars_whisper_models. The service belongs to no color: blue and green reach it through the network llars_default at http://whisper-service:8000/v1; it publishes no port. Only the loop in the worker container transcribes, one note at a time; the web tier merely stores notes as pending.

Setup. These lines go into /var/llars/.env:

TICKET_TRANSCRIPTION_MODEL=Systran/faster-whisper-large-v3
TICKET_TRANSCRIPTION_BASE_URL=http://whisper-service:8000/v1
TICKET_TRANSCRIPTION_TIMEOUT_SECONDS=600
WHISPER_MODEL=Systran/faster-whisper-large-v3
WHISPER_CPU_THREADS=6
COMPOSE_PROFILES=whisper

TICKET_TRANSCRIPTION_MODEL and WHISPER_MODEL carry the same id, because the service only loads WHISPER_MODEL at startup. The timeout of 600 seconds is generous until the measurement on the host is in; the default is 180. WHISPER_CPU_THREADS also sets the container's CPU limit. COMPOSE_PROFILES=whisper includes the service in start_llars.sh and scripts/server/llars_start_retry.sh. No key is needed because the service is only reachable inside the Docker network. An empty API_KEY would even make speaches reject every call with 403, which is why docker-compose.yml does not set it.

First start. The first start downloads the model from huggingface.co (large-v3 about 3 GB), so the health check waits up to 15 minutes:

cd /var/llars
docker compose -f docker-compose.yml -f docker-compose.prod.yml --profile whisper up -d --no-deps whisper-service
docker logs -f llars_whisper_service      # "Downloading model …" → "Successfully downloaded model …"
docker inspect --format '{{.State.Health.Status}}' llars_whisper_service   # starting → healthy

From then on the deploy takes over: ensure_whisper_service() in scripts/ci/deploy_bluegreen.sh starts or updates the service on every deploy once TICKET_TRANSCRIPTION_BASE_URL points to whisper-service. The step does not wait for "healthy" and never fails a deploy.

Switching LLARS over. The .env only applies to newly created containers. The clean way is the next deploy (nightly or with FORCE_DEPLOY=true), which creates Flask and the worker of the new color with the new values. If you do not want to wait, recreate only the worker of the active color:

COLOR=$(cat .deploy/active_color)
DEPLOY_COLOR=$COLOR docker compose --project-name llars-$COLOR \
  -f docker-compose.yml -f docker-compose.prod.yml -f docker-compose.prod-bluegreen.yml \
  up -d --no-deps --force-recreate backend-worker-service

Flask then stays without a model until the next deploy. New notes are briefly unavailable there, and the loop catches up on them in its next pass (15 seconds). Only POST /api/tickets/transcriptions/retry answers 409 until then.

Watching it.

docker logs -f llars_worker_$COLOR 2>&1 | grep '\[Tickets\]'
#   [Tickets] Anhang 41 (T-23, 183244 B): done in 63.4 s
docker stats --no-stream llars_whisper_service
docker exec llars_flask_$COLOR curl -fsS http://whisper-service:8000/health
docker exec llars_flask_$COLOR curl -fsS http://whisper-service:8000/v1/models
python3 scripts/agenten/tickets.py --env prod show T-23     # transcript on the attachment

The worker's log line names size, result and duration per note, which is how large-v3 can be measured against turbo.

Catching up on old notes. Notes uploaded without a model (unavailable) are caught up by the loop on its own as soon as its worker knows a model — including the note from T-23. Explicitly it works with python3 scripts/agenten/tickets.py --env prod transcribe T-23 (needs Flask with a model) or inside the worker with docker exec llars_worker_$COLOR python -m scripts.ticket_transcription. Failed notes (failed) are only retried by transcribe … --failed or --retry-failed.

Switching to turbo. Change both ids in the .env and recreate the service; it then downloads deepdml/faster-whisper-large-v3-turbo-ct2 (about 1.6 GB). Then recreate the worker (see above) or wait for the next deploy:

WHISPER_MODEL=deepdml/faster-whisper-large-v3-turbo-ct2
TICKET_TRANSCRIPTION_MODEL=deepdml/faster-whisper-large-v3-turbo-ct2
docker compose -f docker-compose.yml -f docker-compose.prod.yml --profile whisper up -d --no-deps whisper-service

Switching it off. Empty TICKET_TRANSCRIPTION_MODEL, let the containers be recreated and run docker stop llars_whisper_service. New notes are then unavailable and stay playable.

Smoke test. scripts/ci/smoke_test_tickets.sh uploads a short WAV note and waits up to 180 seconds for the transcript (SMOKE_TRANSCRIPTION, on by default). Without a model it only prints a notice. failed or a timeout are warnings unless SMOKE_STRICT_TRANSCRIPTION=1 is set, because on staging the worker of the new color is not running yet, and smoke:production would roll back on an error.

Pitfalls. The image is the release candidate 0.9.0-rc.3 from 27.12.2025; the stable 0.8.3 does not know PRELOAD_MODELS and STT_MODEL_TTL yet. If the download fails on the first start, speaches exits and restart: unless-stopped tries again — docker logs llars_whisper_service then shows the reason. docker restart does not re-read the .env, only up -d does. The service computes one note at a time; time spent waiting in its queue counts towards the timeout.

Preload GLiNER models (anonymization)

Since wave 2 of T-158 (2026-11-02, contract .claude/plans/t158-welle2-2026-11-02.md §3) anonymization (type 11 and the /Anonymize tool) detects with an ensemble: rules, Flair and two GLiNER models (naeyn/nobody-pii-de and urchade/gliner_multi_pii-v1, both Apache-2.0, revision pinned). All models run only in the NER process of the worker container; Flask and the case loop ask it over Redis. The NER process loads GLiNER only from the local cache under HF_HOME (default /app/storage/models in the volume llars_rag_storage, shared by blue, green and staging), never by download. Without the models it keeps detecting with rules and Flair, and every case carries the warning ENSEMBLE_UNAVAILABLE ("Detection without additional models").

Careful on the first deploy: docker-compose.yml sets ANONYMIZE_ENSEMBLE_ENABLED=${ANONYMIZE_ENSEMBLE_ENABLED:-true} for the worker, and Flask also defaults to true in code. The production template .env.template.production has false, but that only applies if the line is in /var/llars/.env. Until the memory measurement is done, add before deploying:

ANONYMIZE_ENSEMBLE_ENABLED=false

1. Preload (once per server, ≈ 2.2 GB into HF_HOME; locally and on kia-dev with llars_worker_service, on production with llars_worker_$COLOR):

docker exec -u flaskuser -w /app llars_worker_service python -c "from services.anonymize.gliner_detection import preload; print(preload())"

The output lists cache_dir, tokenizer and per model ready, not_cached, disabled or error:<class>. The command also works with the ensemble switched off; it loads both models itself as a test and needs memory on top of the running NER process for its run time, so run it in a quiet phase. Afterwards the running NER process loads the models within 600 s at the latest; immediately with docker restart llars_worker_service.

2. Measure memory. Flair-large needs up to 5.9 GB (the whole thread is one sentence), each GLiNER model about 1–1.5 GB on top; the NER process thus reaches about 8–9 GB. The worker container is limited to 12 GB for all its processes. Let one case be detected with the ensemble switched on and measure:

docker stats --no-stream llars_worker_$COLOR

If memory gets tight: ANONYMIZE_GLINER_ORG_MODEL= (empty) drops the organization model (measured 205 instead of 210 of 211 occurrences; the gap is organizations), and ANONYMIZE_NER_WORKER_PROCESSES stays at 1 — every further NER process loads all models again.

3. Switch on. Set ANONYMIZE_ENSEMBLE_ENABLED=true in /var/llars/.env. The .env only takes effect in newly created containers (docker restart does not re-read it); the clean way is the next deploy. To apply it immediately, recreate worker and Flask of the active color:

COLOR=$(cat .deploy/active_color)
DEPLOY_COLOR=$COLOR docker compose --project-name llars-$COLOR \
  -f docker-compose.yml -f docker-compose.prod.yml -f docker-compose.prod-bluegreen.yml \
  up -d --no-deps --force-recreate backend-worker-service backend-flask-service

4. Verify. GET /api/anonymize/health?mode=full (permission feature:anonymize:view or the system API key) reports {enabled, models: {pii_de, multi_org}, source} in the field ensemble; source: worker means the NER process has published its state (Redis key anonymize:ner:worker:capabilities). Expected is ready for both models. A newly detected case then no longer carries the warning ENSEMBLE_UNAVAILABLE; cases detected without the models can be redone with "Detect again".

Variables (templates .env.template.development and .env.template.production): ANONYMIZE_ENSEMBLE_ENABLED, ANONYMIZE_GLINER_MODEL (naeyn/nobody-pii-de), ANONYMIZE_GLINER_MODEL_REVISION, ANONYMIZE_GLINER_ORG_MODEL (urchade/gliner_multi_pii-v1, empty = without), ANONYMIZE_GLINER_ORG_MODEL_REVISION, HF_HOME, plus for the replacement suggestions ANONYMIZE_SEED_SECRET (secret of the substitute identity, empty → JWT_SECRET_KEY; changing it means different replacements on "Detect again") and ANONYMIZE_SUGGEST_LLM_MODEL (model for suggestions on click if the scenario names no language model; empty → default LLM; OpenAI is excluded).

Dependencies: since wave 2 the image ships transformers==4.57.3 (previously 4.46.3), gliner==0.2.30, rapidfuzz and wordfreq. The models are not in the image but only in the volume — a new server needs step 1. The measurement with all numbers is in scripts/anonymize/bench/README.md, the user guide under Anonymize cases › Operations.

Recordings

Since 1.65.0 (2026-11-18, build contract .claude/plans/aufnahmen-2026-11-18.md) individually enabled accounts record interviews and meetings through the tile "Recordings" (/recordings). The browser sends a piece of PCM (16 kHz mono) every 5 seconds to PUT /api/recordings/<rid>/chunks/<seq>; Flask stores it losslessly compressed (FLAC) and AES-256-GCM-encrypted in MariaDB (recording_chunks). The process recordings in the worker container does the rest: a background thread writes the live preview with a small Whisper model, the main thread takes finished recordings one after the other through the final transcription (large model in the whisper-service), speaker detection (sherpa-onnx in a child process) and the summary (KIZ proxy). There is no Socket.IO for this; the interface polls. Usage and privacy for users: guide Recordings.

What happens on deploy by itself.

  • db.create_all() creates the tables recordings and recording_chunks at startup.
  • The permission seeder creates feature:recordings:use and gives it to no role, not even admin. If it is attached to a role by hand, the next start removes it again.
  • The worker container starts the process recordings (at most one, switch RECORDINGS_WORKER_ENABLED, default on). At startup it immediately puts every chain still marked processing back into the queue — there is only this one process, and the old one has already been stopped by the deploy. In operation it checks every minute and puts back chains whose heartbeat is older than 15 minutes.
  • The image ships soundfile==0.13.1, sherpa-onnx==1.13.8 and sherpa-onnx-core==1.13.8 (app/requirements.txt). All three are imported inside functions only: if new code runs on an old image (the old color after git pull), Flask stores the pieces raw instead of as FLAC, and the speaker stage ends as "skipped" (diarization_unavailable).
  • The dump before the deploy leaves out recording_chunks (see Backup).
  • /api/recordings is exempt from the per-IP limit (main.exempt_endpoints), but only for requests with Authorization: Bearer … and without X-API-Key; anonymous requests and keys stay under the IP limit. For signed-in people buckets per person apply (pieces 240, writes 60, reads 600 per minute, counted in Redis).
  • Per-person caps, checked on creation only: at most RECORDINGS_MAX_OPEN_PER_USER (3) open recordings (409 TOO_MANY_OPEN) and RECORDINGS_MAX_STORED_BYTES_PER_USER (20 GiB, 0 = off) of stored audio (409 storage_quota_exceeded). A running upload is never rejected because of the quota.

Entries of your own in /var/llars/.env are not required: without them LLARS derives the key from FLASK_SECRET_KEY and uses the Whisper service and model of the ticket voice notes (TICKET_TRANSCRIPTION_BASE_URL, TICKET_TRANSCRIPTION_MODEL). Without a base URL there is no live preview, and the final transcription ends with whisper_not_configured.

Key. app/services/recordings/recording_crypto.py picks the main key in this order:

  1. RECORDINGS_ENCRYPTION_KEY if it is strong (at least 32 characters, no CHANGE_ME…, not the dev default) — source key. A weak value, including the placeholder of the production template, counts as none (one warning in the log).
  2. Otherwise derived from FLASK_SECRET_KEY via HKDF-SHA256 (info = llars:recordings:at-rest:v1) — source derived.
  3. Otherwise, outside production, a fixed development key — source dev. It is in the repo and never counts in production: neither as RECORDINGS_ENCRYPTION_KEY nor for decryption.
  4. Otherwise LLARS accepts no recording: 503 encryption_not_configured, in the interface "Recordings are not set up yet". The app start does not abort because of this.

Since the start guard enforces a strong FLASK_SECRET_KEY in production, production records with the derived key from the first deploy on. This command shows which source applies without printing a key (the ids are the first 8 hex characters of a hash):

COLOR=$(cat .deploy/active_color)
docker exec -u flaskuser -w /app llars_flask_$COLOR python -c \
  "from services.recordings import recording_crypto as c; print(c.source(), c.is_ready(), c.configured_key_ids())"

A key of its own (recommended) is created by scripts/server/prod_recordings_key.sh, run from the workstation in the repo root (needs SSH to the host). The script generates the value in a short-lived container on the host (openssl rand -base64 48), writes it into /var/llars/.env and never shows it. It never replaces a key that is set; a missing, empty or placeholder line it does.

bash scripts/server/prod_recordings_key.sh                   # host llars: create if needed
bash scripts/server/prod_recordings_key.sh --check           # check only
bash scripts/server/prod_recordings_key.sh --dry-run         # shows what would happen
bash scripts/server/prod_recordings_key.sh --host llars-dev  # kia-dev
Exit Meaning
0 set (or --dry-run)
1 error (SSH, Docker, .env)
2 wrong invocation
3 --check: not validly set
4 too short or set more than once — check by hand, the script does not touch the line

Flask and the worker only read the new value when their containers are recreated (next deploy or switch; docker restart is not enough). Until then LLARS keeps encrypting with the derived key. The switch needs no re-encryption: the key derived from the current FLASK_SECRET_KEY always stays valid for reading. When decrypting, LLARS picks the key by its id in the stored value, never by trial; the id at creation time is in recordings.enc_key_id.

Back it up. Without the key all recordings are unreadable, also from every backup. A human reads the own key in a separate SSH session from /var/llars/.env and stores it in the password manager — never an agent, never into a log. As long as the key is derived, FLASK_SECRET_KEY is that secret.

Rotation.

  • Rotating FLASK_SECRET_KEY: first put the old value into RECORDINGS_ENCRYPTION_SECRET_FALLBACK (comma-separated if there are several). Otherwise all recordings stored with the derived key become unreadable. This also applies to the older recordings after switching to a key of its own.
  • Changing the own key: put the old value into RECORDINGS_ENCRYPTION_KEY_FALLBACK (comma-separated) and only then set the new one. The script does not do this; the change is manual.

Whisper. Recordings only use the internal service from the section Whisper service, never LLMClientFactory or OpenAI; the audio does not leave the host. The base URL (RECORDINGS_WHISPER_BASE_URL, otherwise TICKET_TRANSCRIPTION_BASE_URL) only counts with an internal host: a name without a dot (Docker service such as whisper-service), localhost, a private or loopback IP — or a host from RECORDINGS_WHISPER_ALLOWED_HOSTS. If the ticket variable points to an outside service, Whisper counts as not set up for recordings (one warning per process in the log, with the host name only).

  • Final transcription: RECORDINGS_TRANSCRIPTION_MODEL, otherwise TICKET_TRANSCRIPTION_MODEL (production: Systran/faster-whisper-large-v3, which the service preloads anyway). The chain never downloads this model. If the service does not have it, the recording stays in the queue and is retried every 60 seconds (log "Modell der Nachtranskription nicht bereit"). So use the same id as WHISPER_MODEL.
  • Live preview: RECORDINGS_LIVE_MODEL (default Systran/faster-whisper-tiny since 2026-11-19; previously Systran/faster-whisper-small). The live thread checks it at startup and then at most every 5 minutes through the service API (GET /v1/models/<id>), downloads it the first time (POST /v1/models/<id>; for this the Whisper container needs network access to huggingface.co once) and loads it into memory (POST /api/ps/<id>). With STT_MODEL_TTL=-1 it then stays loaded. RAM: measured on 2026-11-19 on production, the service uses 4.3 of 8 GiB with large-v3, small and tiny loaded (limit WHISPER_MEMORY_LIMIT, default 8 GB). After the switch, small stays in RAM until the next restart of the Whisper service. On production tiny is already in the service since the measurement; on other instances the live thread loads it at first start (needs network). Until the model is ready, the interface shows no live preview; the recording runs anyway.
  • Why tiny, 12 seconds and cool-down (2026-11-19): on production small needed 13–26 s per live call of 10–15 s of audio, i.e. longer than the audio itself. An aborted call keeps computing in the service; the live thread sent the next call right away, which queued up behind it. The result was 14 timeouts in a row and about 7 minutes without live text. The audio was nevertheless saved completely. The older measurement of ≈ 2 s per call with small comes from arm64 with 4 CPUs and does not apply to production. The live text should be fast, not good; the good text comes from the final transcription. Since then:
  • Time budget RECORDINGS_LIVE_TIMEOUT_SECONDS (default 12, range 5–30) for the VAD pre-call and the transcription together: VAD at most 5 s, the call the rest, at least 2 s.
  • Run size RECORDINGS_LIVE_GROUP_CHUNKS default 1: every piece is computed right away. With a backlog the thread still merges up to three waiting neighbours into one call.
  • Cool-down: after a timeout (VAD or call) the thread sends no call for 15 s, after the next one in a row 30 s, then 60 s; only a successful call resets the level. If the service is unreachable, it is 15 s. Waiting pieces become skipped during this time.
  • Visible pause: during the cool-down the Redis key llars:recordings:live:paused is set (TTL = cool-down). /api/recordings/config and every upload then report live_available: false, and the interface shows "The live preview is not available right now. The recording continues anyway."
  • Live statistics in the worker log: at most once per 60 s, and only if something happened, the live thread writes one line with numbers (no content):
docker logs llars_worker_$COLOR 2>&1 | grep "Live-Statistik" | tail -20

Example: Live-Statistik 60 s: 11 Aufrufe, Median 2.9 s, Max 4.4 s, Stücke done=9 silent=2 failed=0 skipped=0, Modell Systran/faster-whisper-tiny, Abkühlstufe 0 (the line is in German: calls, median, max, pieces, model, cool-down level). Healthy: median well below 5 s (a piece is 5 s of audio), max below the time budget, failed and skipped close to 0, cool-down level 0. Rising skipped or cool-down level means live cannot keep up — usually because a final transcription is running at the same time. - Production measurements (2026-11-19, 6 threads, int8): synthetic German speech, the same path as the live thread (VAD, then transcription), while large-v3 was transcribing a window at the same time (unfavourable case; not measured without final transcription). Median per call:

Audio tiny small VAD pre-call
5 s 2.4 s 11.1 s 0.3 s
10 s 3.1 s 13.7 s 0.3 s
15 s 4.2 s 11.9 s 0.3 s

The statistics line of the first recording after the deploy confirms this with real speech. If tiny is not fast enough next to a final transcription, the next step would be a separate small live service with its own cores. - Live preview variables: RECORDINGS_LIVE_ENABLED (default on), RECORDINGS_LIVE_MODEL (tiny), RECORDINGS_LIVE_TIMEOUT_SECONDS (12, 5–30), RECORDINGS_LIVE_GROUP_CHUNKS (1, 1–3). - Priority: before each window of the final transcription (≈ 45 seconds of audio) the chain waits while ticket voice notes are pending or running, at most 10 minutes. Live sends at most one call at a time for all recordings, every piece right away (RECORDINGS_LIVE_GROUP_CHUNKS, 1–3), and skips backlog. There is no priority between live and final transcription. The same model computes sequentially in the service; two different ones run in parallel on the same 6 cores — so live and final transcription slow each other down. - Duration as the lever: for recordings large-v3 needs 95–140 s per window of 40–47 s of audio on production, i.e. about 2 to 3 times the audio length (finding of 2026-11-19, without competition); a one-hour interview therefore needs two to three hours of transcription. The older estimate of 1.3 s per second of audio (measured 2026-10-08 on a ticket voice note) does not apply to recordings. Recordings run one after the other. Turbo is faster, switched as in the Whisper service section (WHISPER_MODEL and TICKET_TRANSCRIPTION_MODEL both to deepdml/faster-whisper-large-v3-turbo-ct2); recordings and voice notes then follow together. Setting only RECORDINGS_TRANSCRIPTION_MODEL to a different model means the service must have installed it beforehand (POST /v1/models/<id>) and then keeps two large models in memory.

docker exec llars_flask_$COLOR curl -fsS http://whisper-service:8000/v1/models     # installed models
docker exec llars_redis sh -c 'redis-cli -a "$REDIS_PASSWORD" --no-auth-warning EXISTS llars:recordings:live:alive'   # 1 = live thread alive (TTL 30 s)

Speaker detection. sherpa-onnx computes on the CPU, without torch and without a token, in a freshly started child process (spawn): the library holds the GIL for the whole computation, and an out-of-memory kill must not take the worker down. Two threads (RECORDINGS_DIARIZATION_THREADS, 1–8), memory about 0.75 GiB per hour of audio; above 60 minutes it computes in sections of 45 minutes with 5 minutes of overlap. Timeout: the larger of 1,200 seconds and half the audio length. The worker container shares its 12 GB with the NER process of the anonymization.

  • Models, pinned with URL and SHA-256: pyannote segmentation-3.0 as ONNX (MIT; from an archive of 6.9 MB) and 3D-Speaker CAM++ (Apache-2.0, 28 MB), both only from https://github.com/k2-fsa/sherpa-onnx/releases/… (redirects only to GitHub hosts). The target is RECORDINGS_MODEL_DIR (default /app/storage/models/recordings in the volume llars_rag_storage, shared by blue and green). The first recording downloads them if RECORDINGS_DIARIZATION_DOWNLOAD is on (default). Before every run the stage recomputes the checksums of both files (≈ 35 MB, without cache), because other services share the volume; a mismatching file is deleted and downloaded again.
  • Known versions (since 19.11.2026): For each model the code lists known good versions (size + SHA-256 as a pair). The vendor republished CAM++ under the same URL on 19.11.2026 (28,281,165 bytes, SHA-256 53cab20b…; before 28,281,164 bytes, aa3cfc16…); both are accepted. A file that matches no version is still rejected. If a download fails, the worker log states why: Modelle nicht verfügbar (ValueError, code=checksum, model=…onnx); with checksum, download_too_large or download_size_mismatch the vendor has probably republished the file — see the Recordings chapter ("Fallen"), then redo affected recordings with "Try again" on the speaker stage.
  • Preload by hand (once per server; output True):
docker exec -u flaskuser -w /app llars_worker_$COLOR python -c \
  "from services.recordings.recording_diarization import ensure_models; print(ensure_models())"
  • Switches: RECORDINGS_DIARIZATION_ENABLED=false → stage "skipped" (diarization_disabled). Package or models missing → "skipped" (diarization_unavailable). Less than 15 seconds of speech or 3 segments → too_short. The chain continues in every case.

Summary. RECORDINGS_SUMMARY_MODEL (default Global/Qwen/Qwen3.8-Flash-Next-FP8). The model has to be active in llm_models and run through the KIZ proxy (Global/… with provider litellm); the stage rejects OpenAI and user-provider models (summary_model_forbidden) as well as an inactive one (summary_model_inactive). There is no fallback to the default LLM. The call uses the key of the DB provider (not LITELLM_API_KEY), has a 180-second timeout and no retry of its own. A 429 puts the recording back with Retry-After; other errors get up to three attempts. Transcripts under 40 words are skipped (too_few_words); transcripts above 45,000 characters are summarised in parts. For this stage the transcript text (with title and speaker names) leaves the host towards the KIZ.

  • Target server pinned: the provider's address is stored in the database and can be changed by admins. The stage therefore checks the client's host before sending against a list from the environment only: RECORDINGS_SUMMARY_ALLOWED_HOSTS (comma-separated), otherwise the host of LITELLM_BASE_URL, plus always the KIZ proxy from the templates. https is mandatory, except for internal names without a dot and localhost. If the host does not match, the stage ends with summary_model_forbidden without sending a single byte.
  • Thinking off: Qwen is a reasoning model. With thinking, measurements showed the whole output budget going into thinking (empty answer, about 40 s); without it the summary came in about 4 s with the right structure. RECORDINGS_SUMMARY_THINKING = off (default, chat_template_kwargs.enable_thinking = false), low (reasoning_effort = low) or default (no addition). If a model rejects the addition with 400 or 422, the stage repeats the call once without it and remembers this per model.
  • Answer cleaned: the stage removes links, images, bare URLs and raw HTML from the answer ("[Link entfernt]"). The interface additionally renders it strictly sanitised (summaryMarkdown.js: structure tags only, no attributes, no links or images).

Name suggestion (since 1.70.0, 19.11.2026, build contract .claude/plans/aufnahmen-sprecher-2026-11-19.md). Between speaker detection and summary the pipeline suggests names for "Speaker A, B …" from the context of the conversation (self-introduction, direct address). Same KIZ model and same host binding as the summary (RECORDINGS_SUMMARY_MODEL, RECORDINGS_SUMMARY_ALLOWED_HOSTS), but always with short reasoning (reasoning_effort: low, independent of RECORDINGS_SUMMARY_THINKING). One additional call per recording, measured at a median of about 3 s (at most about 8 s). No new variable, no new table or column: the suggestions are stored encrypted in the transcript blob. If the call fails, the summary still runs. The worker log states only status, count and duration, never names:

[recordings] Aufnahme <id>: Namensvorschlag <done|none|failed> (<n> Namen) in <s> s
[recordings] Aufnahme <id>: Namensvorschlag gescheitert (<exception>, <code>)

Measuring again (from the development machine on the VPN, never on the server): python3 scripts/agenten/speaker_names_eval.py --variant low-reason. The script reads LITELLM_BASE_URL and LITELLM_API_KEY from the .env itself and never prints the key; it uses the same prompt and checking logic as the server. By default it runs the 60 invented conversations in tests/fixtures/recordings/speaker_name_cases.json; --file <file> measures your own cases in the same format (for an honest cross-check, cases that were not available while tuning the prompt). Status 19.11.2026: 146 of 146 speakers right, 0 wrong; fresh cross-check 36 of 36. The figures come from clean, invented texts and are an upper bound for real recordings.

Existing recordings do not get names by themselves: in the recording choose "Suggest names again" or the same entry in the three-dot menu "Restart processing" (POST …/retry {stage: "speaker_names"}).

Enabling accounts. The permission goes to no role, only to individual accounts (permission admin:permissions:manage, for example with the system key). Usernames do not belong in the repo.

curl -s -X POST "$BASE/api/permissions/grant" -H "X-API-Key: $KEY" -H "Content-Type: application/json" \
  -d '{"username": "<username>", "permission_key": "feature:recordings:use"}'

The tile appears once the interface reloads the permissions (permission event, returning to the tab or a new sign-in). Revoke with POST /api/permissions/revoke and the same body; this sets an explicit deny for the account. The recordings stay stored encrypted and become visible again when the permission returns.

Storage. PCM at 16 kHz, mono, 16 bit is about 115 MB per hour. Each piece is stored as FLAC if that is smaller and converts back bit-exactly; for speech, about half is to be expected (rule of thumb, not measured: ≈ 55–60 MB per hour). Without soundfile it stays raw. Encryption costs 39 bytes per piece; transcript and summary are small by comparison. The WAV download reads in blocks (12 pieces ≈ 1 minute of audio) and ends the transaction before a block goes out; a slow download therefore does not hold a database connection. Current state (numbers only):

docker exec llars_db_service sh -c 'mariadb -u "$MYSQL_USER" -p"$MYSQL_PASSWORD" "$MYSQL_DATABASE" -e "SELECT codec, COUNT(*) AS chunks, ROUND(SUM(byte_size)/1048576) AS mib FROM recording_chunks GROUP BY codec"'

Backup. The dump before every deploy (scripts/ci/deploy_bluegreen.sh, step 1/6, the five newest are kept) leaves out recording_chunks with --ignore-table: a few hours of audio would otherwise break the 300-second timeout and fill the disk with five dumps. recordings with transcripts and summaries (encrypted) stays in the dump. Restoring this dump brings back transcripts and summaries, not the audio. A dump of the recordings only (file name outside the rotation, which only cleans up *.sql):

docker exec llars_db_service sh -c 'mariadb-dump -u "$MYSQL_USER" -p"$MYSQL_PASSWORD" --single-transaction --quick "$MYSQL_DATABASE" recordings recording_chunks' \
  | gzip > /var/llars/backups/recordings_$(date +%Y%m%d_%H%M%S).sql.gz

The dump is worthless without the key; back up the key (or FLASK_SECRET_KEY) separately. A full backup with --all-databases as in section 6 contains the audio.

Manual run and status. In the worker container; the output names only public ids, status and numbers:

docker exec -u flaskuser -w /app llars_worker_$COLOR python -m scripts.recordings --status   # counts per status and the queue
docker exec -u flaskuser -w /app llars_worker_$COLOR python -m scripts.recordings --once     # the oldest waiting recording now
docker logs --since 1h llars_worker_$COLOR 2>&1 | grep -i recording                           # chain, live, speakers, summary

Without switches the manual run processes all waiting recordings in the foreground (this can take hours). RECORDINGS_WORKER_ENABLED does not apply to it; next to the running loop it processes nothing twice, because every recording is claimed atomically. Exit 0 on success (also without work), 2 on wrong arguments.

Troubleshooting. The stage codes appear in the interface as a sentence and in the API as stages.<stage>.error_code.

Symptom Cause Remedy
Tile missing account without the individual grant grant it (see above); refocus the tab or sign in again
"Recordings are not set up yet" (503 encryption_not_configured) production without a strong RECORDINGS_ENCRYPTION_KEY and without a strong FLASK_SECRET_KEY set a key, recreate Flask and the worker
Recording stays "Waiting" loop off (RECORDINGS_WORKER_ENABLED=false), worker not running, transcription model not in the service, Whisper unreachable or ticket notes in the queue --status, worker log ("nicht bereit", "nicht erreichbar"), GET /v1/models of the service
whisper_not_configured no base URL, or it points to a host that is not internal (log "nicht internen Host") point TICKET_TRANSCRIPTION_BASE_URL or RECORDINGS_WHISPER_BASE_URL to the internal service (or add the host to RECORDINGS_WHISPER_ALLOWED_HOSTS), recreate containers, "Try again"
New recording 409 TOO_MANY_OPEN · storage_quota_exceeded three open recordings or 20 GiB of stored audio for the person finish or delete open ones, delete audio; caps via RECORDINGS_MAX_OPEN_PER_USER · RECORDINGS_MAX_STORED_BYTES_PER_USER
whisper_timeout · whisper_error service overloaded or error; final after three attempts docker logs llars_whisper_service, then "Try again"
decrypt_failed key changed without fallback (FLASK_SECRET_KEY rotated without …_SECRET_FALLBACK, own key replaced without …_KEY_FALLBACK) add the old value as fallback, recreate containers, "Try again"
audio_missing no pieces or audio deleted —
Live preview "not available right now" live thread without heartbeat, RECORDINGS_LIVE_ENABLED=false, no base URL or small model not loadable (no network to huggingface.co) check the Redis key and the worker log; the recording itself continues
Speakers "skipped": diarization_unavailable sherpa-onnx missing in the image (old color) or models not loadable (reason in the log: code=…, model=…) rebuild the image (deploy), preload the models
Speakers diarization_timeout · diarization_failed child process over the time limit or crashed (memory) docker stats, RECORDINGS_DIARIZATION_THREADS; "Try again"
Speakers too_short · summary no_speech · too_few_words too little speech or fewer than 40 words (MIN_SUMMARY_WORDS) expected
summary_model_inactive · summary_model_forbidden model inactive, not on the KIZ proxy, or the provider's host is not in the list of allowed target servers activate the model or set RECORDINGS_SUMMARY_MODEL to an active Global/… model on the proxy; match the provider address with LITELLM_BASE_URL or RECORDINGS_SUMMARY_ALLOWED_HOSTS
summary_unavailable proxy unreachable or key not cleared for the model GET <proxy>/models with the key of the instance
summary_failed · summary_empty model error or empty answer (three attempts) "Try again"
internal_error exception in the chain (three attempts, also across restarts) worker log
429 rate_limited bucket per person empty wait; the recording buffers in the browser

Smoke test. scripts/ci/smoke_test_recordings.sh (block in scripts/ci/smoke_test.sh, switch SMOKE_RECORDINGS, default 1, 0 = off) calls GET /api/recordings twice: without a key it must get 401 or 403, with the system key 403 with HUMAN_REQUIRED. It writes nothing and depends neither on Whisper nor on the worker. A 404, a 5xx or a 200 with the system key are real errors (exit 1), also in smoke:production — where the rollback follows.

Switching off. RECORDINGS_WORKER_ENABLED=false stops processing (finished recordings stay in the queue), RECORDINGS_LIVE_ENABLED=false only the live preview. Anyone who should no longer record loses the individual grant.

Known limits (security review of 2026-11-18, open)

  • Anyone holding the system key or the right to manage users can create a password reset link for an account and sign in as that person. This is noticeable (the password no longer works afterwards) but is a limit of the platform. Likewise, whoever runs the server has access to the key and the database.
  • The nginx access log contains the requests to /api/recordings/… (recording id, time, IP — no content, no token). Administrators can see from it when someone records. Hiding these entries is planned as follow-up work.
  • The queue position reveals that other recordings are waiting ahead (not whose and not what).
  • Until upload, sections are stored unencrypted in IndexedDB in the browser of the person's own device: deliverable ones for up to 30 days from the recording, orphaned or rejected ones 7 days after being orphaned (chunkStore.js, cleaned up only after uploading).

Variables (templates .env.template.*, block "Aufnahmen"): RECORDINGS_ENCRYPTION_KEY, RECORDINGS_ENCRYPTION_KEY_FALLBACK, RECORDINGS_ENCRYPTION_SECRET_FALLBACK, RECORDINGS_WHISPER_BASE_URL, RECORDINGS_WHISPER_API_KEY, RECORDINGS_TRANSCRIPTION_MODEL, RECORDINGS_WHISPER_ALLOWED_HOSTS, RECORDINGS_LIVE_MODEL, RECORDINGS_LIVE_ENABLED, RECORDINGS_LIVE_GROUP_CHUNKS, RECORDINGS_SUMMARY_MODEL, RECORDINGS_SUMMARY_ALLOWED_HOSTS, RECORDINGS_SUMMARY_THINKING (off), RECORDINGS_DIARIZATION_ENABLED, RECORDINGS_DIARIZATION_THREADS, RECORDINGS_DIARIZATION_DOWNLOAD, RECORDINGS_WORKER_ENABLED, RECORDINGS_WORKER_INTERVAL_SECONDS (5, at least 2), RECORDINGS_MAX_SECONDS (14,400), RECORDINGS_MAX_OPEN_PER_USER (3), RECORDINGS_MAX_STORED_BYTES_PER_USER (21,474,836,480 = 20 GiB, 0 = off), RECORDINGS_STALE_FINALIZE_SECONDS (7,200), RECORDINGS_MODEL_DIR. In the code only: RECORDINGS_STALE_MUTED_FINALIZE_SECONDS (43,200).

Online experiment: bind the anchor scenario

Since the online experiment (scenario type 12, 2026-11-12, build contract .claude/plans/study-scenario-2026-11-12.md §3) every study collection (study_collections) belongs to a scenario. The collections of the running study only get their scenario through the binding script: it creates the anchor scenario (type 12, package llm-communication-v1, legacy_global_alerts: true) and binds every collection that is still free to it. Until then participants carry on unchanged (/s/<slug>, /s/klicktest, /api/study/run/*), but the operator views exist only inside the scenario: without an anchor, /s/study and the other old addresses lead to the start page, and only admins reach the data through the old alias API /api/study/*. Run the script right after the switch.

The script writes only into experiment_scenario_collections (INSERT), into rating_scenarios (one INSERT if there is no anchor yet) and into scenario_users (new rows by INSERT, existing rows of the named accounts by UPDATE to their role and to active). It binds every free collection. The script changes no row in study_*. A second run right afterwards changes nothing ("0 neu gebunden"). If an account is missing or there is already more than one anchor scenario, it aborts and writes nothing.

The script imports the app (from main import app). As on every start, db.create_all and the seeders run (idempotent). In the web container, without LLARS_SKIP_STARTUP_TASKS=true, the one-time startup tasks (among them the click-test link via ensure_clicktest_link, the instrument archive and the docs sync) and the background threads would run as well; the startup tasks commit on their own, also in a dry run. The commands below therefore always set the switch.

Staging and production share the database

The inactive colour on staging talks to the same MariaDB as production. A binding run therefore always writes into the production database, whichever Flask container it runs in. The previous version does not know type 12 and shows the anchor scenario as a scenario of unknown type. Bind only after the switch, from the Flask container of the active colour.

When free collections appear again. At startup LLARS creates or repairs the click-test link (collection_service.ensure_clicktest_link, called in main.py) and opens a click-test collection for it if none is open. The same happens after a click-test collection is archived through the alias API. Such a collection is unbound, and only admins can run the click test with it, until the script runs again. The collections of another online experiment that was deleted without data become free as well; an open one among them keeps accepting participations through its links. The script binds every free collection to the anchor, these included, together with later participations that came through someone else's links.

Before every further run, therefore look at the free collections (metadata only; for signing in to the MariaDB client see step 6):

SELECT c.id, c.stage, c.seq, c.opened_at, c.closed_at
FROM study_collections c
LEFT JOIN experiment_scenario_collections b ON b.collection_id = c.id
WHERE b.id IS NULL;

Run the script only if all of them belong to the running study; otherwise clarify first. For a further run, name only --owner <an owner who is active today>, for example the operator account, and no --editors. The script sets every named account back to its role and to active, even if the team has since removed or downgraded it. Who is owner today is listed in the anchor scenario under Settings → Team.

1. Capture before (before the deploy, on the machine with the .env that holds PRODUCTION_ADMIN_API_KEY; only the orchestrator does this):

P=$(mktemp -d) && echo "$P"    # note the path: steps 6 and 7 need it
python3 scripts/agenten/experiment_parity.py --env prod --out "$P/before"

Without --scenario the script captures only the alias (/api/study/export/{datasets,summary,bundle}): per named collection the row counts and the ZIP as normalised JSON, plus counts.json (rows per dataset, participations per collection) and SHA256SUMS. It reads the key from the .env itself, sends only GET requests with X-API-Key, follows no redirect and never prints the key. --out must be new or empty and outside every git working tree; directories get 0700, files 0600.

The files contain complete study data. Do not put them in backed-up or synced folders (Time Machine, iCloud, Dropbox); mktemp -d creates a fresh temporary directory. Never open them in an agent or chat session; look only at the output of diff and at counts.json. They are deleted right after step 6 (step 7). Keeping them is not an option, because later withdrawals do not reach this copy. If a run aborts ("Paritätsprüfung fehlgeschlagen", e.g. after an HTTP 429 from the rate limit; the script retries nothing), delete the partial directory at once (e.g. rm -rf "$P/before") and repeat the run into a new, empty directory.

2. Deploy and switch as usual (nightly or FORCE_DEPLOY=true).

3. Dry run in the Flask container of the active colour, as flaskuser, with working directory /app, PYTHONPATH=/app and without startup tasks:

cd /var/llars
COLOR=$(cat .deploy/active_color)
docker exec -u flaskuser -w /app -e PYTHONPATH=/app -e LLARS_SKIP_STARTUP_TASKS=true \
  llars_flask_$COLOR python -m scripts.experiment_bind_legacy \
  --owner <study-lead-account> --owner <operator-account> --dry-run

--owner can be repeated: the first account becomes the scenario's created_by, every further one an additional owner. --editors a,b makes accounts editors (whoever is already an owner stays owner), --name "…" sets the name (default "Online-Experiment"). The output reads like Szenario-Id: <id>; Sammlungen vorher gebunden: 0; nachher gebunden: <n>; <n> neu gebunden; neue Mitglieder: <m> (scenario id, collections bound before and after, newly bound, new members). In a dry run a newly reported scenario id is only provisional, because the script rolls back its writes. Exit 1 with "Bindung fehlgeschlagen; Transaktion zurückgerollt" means the script wrote nothing (missing account, more than one anchor); the message deliberately names neither accounts nor database errors. Locally the container is llars_flask_service.

4. Bind: the same command without --dry-run. A second run right afterwards must report "0 neu gebunden" and "neue Mitglieder: 0". For later runs, see the paragraph "When free collections appear again".

5. Check: open /s/study in the browser as an owner. The redirect lands in the "Overview" tab of the anchor scenario, and the figures match the former overview. The alert settings are in the "Alerts" tab; the mails continue unchanged, and their link /s/study leads to the "Overview" tab of the anchor scenario.

6. Capture after and compare:

python3 scripts/agenten/experiment_parity.py --env prod --scenario <anchor-id> \
  --out "$P/after"
# scenario against alias in the same run: must be equal (exit 0, no output)
python3 scripts/agenten/experiment_parity.py diff "$P/after/alias" "$P/after/scenario"
# alias before against after: allowed differences see below
python3 scripts/agenten/experiment_parity.py diff "$P/before/alias" "$P/after/alias"

diff names only file names and JSON key paths, never values. It exits with 0 when everything is equal and with 1 otherwise (also on an error, then with "Paritätsprüfung fehlgeschlagen"). Only the timestamps of the export itself are normalised (exported_at, exportiert_am, loaded_at, the timestamp in the file names inside the ZIP).

As long as all collections hang on the anchor, alias and scenario must be equal within one run. The script fetches them one after the other; run it in a quiet hour, therefore, and repeat it if the only differences are in datasets of running participations.

Between "before" and "after" these are allowed: server_stand in the manifest.json (version and commit always differ after the deploy; a file's checksum changes with its content), the links dataset (the view counts include link previews) and datasets with new or running participations or withdrawals. counts.json of both runs explains the row counts. Anything else is a finding.

For an additional check on table level, query directly before and after step 4 in the MariaDB client. The sign-in reads the credentials inside the container, so no password ends up in the shell history:

docker exec -it llars_db_service sh -c 'exec mariadb -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" "$MYSQL_DATABASE"'
SELECT COUNT(*), MAX(id) FROM study_collections;
SELECT COUNT(*), MAX(id) FROM study_participants;
CHECKSUM TABLE study_collections, study_alert_recipients;
SELECT stage, interval_hours, anchor_hour, enabled FROM study_alert_settings ORDER BY stage;
SELECT COUNT(*) FROM experiment_scenario_collections;

study_participants may change through new participations and withdrawals (a withdrawal deletes the row). study_collections, the checksum and the alert settings must stay the same, unless someone changed collections or alerts in the meantime. There is deliberately no checksum over study_alert_settings: the alert worker writes the columns last_slot, last_sent_at and last_error with every report. The last number grows by the newly bound collections. experiment_parity.py does not do this table comparison.

7. Clean up: rm -rf "$P" right after step 6. If $P is no longer set in the shell, use the path noted in step 1.

Rollback.

  1. Code back without touching the database: cd /var/llars && bash scripts/ci/rollback_bluegreen.sh or deploy the previous version. Participants notice nothing, because the participant routes and study_* are the same in both versions. The old operator pages /s/study* and /api/study/* work there as before, but for admins only; anyone who is not an admin, including the external study lead, can then no longer reach the study administration.

    If the instant rollback reports "Falling back to full rollback...", start neither scripts/ci/rollback_production.sh nor the CI job rollback:production, which falls back to it; deploy the previous version instead. The full rollback restores the database backup taken at the deploy: it deletes every participation since the backup and brings back the data of withdrawn participations as well as the key hashes of a data cut set in the meantime. Because withdrawals carry no pseudonym, it can no longer be told afterwards which of the restored participations had been withdrawn. 2. If smoke:production fails, check in the job log whether "Automatic rollback (full)" ran; the job's after_script falls back to the full rollback on its own. Then participations since the backup are lost and withdrawals are undone. Report this to the external study lead at once; whether it is a reportable data protection incident is for those responsible for the study to assess. 3. The previous version does not read experiment_scenario_collections. It shows the row (12, 'online_experiment') only in the admin type picker, with its raw name (GET /api/admin/get_function_types). Anchor scenario and table stay; do not delete the anchor and do not remove the table. The table holds the binding of every experiment; without it, a later binding run after a new deploy would also bind the collections of other experiments, data included, to the anchor. If the table has to go after all, first run SELECT scenario_id, COUNT(*) FROM experiment_scenario_collections GROUP BY scenario_id;: if a scenario other than the anchor has bindings, do not remove it, or save the binding (SELECT scenario_id, collection_id FROM experiment_scenario_collections;) and restore it after a new deploy, before the binding run. 4. The binding never changed study_*. There is nothing to restore, and a database restore would be wrong here (see item 1).

The steps for managers are in the user guide Online experiment, the technical rules in the chapter .claude/kapitel/online-experiment.md.


15. Troubleshooting production

Eventlet DNS issues

Problem: With eventlet in Docker:

Can't connect to MySQL server on 'db-maria-service' ([Errno -3] Lookup timed out)

Solution: Use gevent instead of eventlet (already standard):

# In .env
PROJECT_STATE=production
# Automatically uses wsgi_gevent.py

WebSocket fallback to polling

Problem: Browser uses polling instead of WebSocket.

Check:

# In container
docker exec llars_flask_service python3 -c "
import socketio
sio = socketio.Client()
sio.connect('http://localhost:8081', transports=['websocket'])
print('Transport:', sio.transport())  # Should be 'websocket'
sio.disconnect()
"

Solution: Ensure PROJECT_STATE=production and Gunicorn runs with gevent.

Container does not start after update

Problem: Permission denied for start_flask.sh.

Solution:

docker compose build --no-cache llars_flask_service
docker compose up -d llars_flask_service


Next steps

  1. Set up users
  2. Create first chatbots
  3. Configure RAG pipeline