Files
karaoke-gen/infrastructure/encoding-worker
Andrew Beveridge ☄️ db42594740 feat(encoding-worker): persist job state to Firestore (hardening 2/3) (#757)
## Summary

Addresses **hardening item 2 of 3** from
\`docs/archive/2026-05-06-capacity-resilience-session.md\`.

(Replaces #755, which was auto-closed when its base branch was merged +
deleted.)

Encoding worker held job state in a process-local dict. When systemd
restarted the service (deploy, crash, OOM) the dict was empty, so polls
from the Cloud Run side returned 404 and either failed the user's job or
triggered wasteful re-renders.

Rebased onto main after #754 merged. Item 3 (#756) is stacked on this
PR.

## Changes

- **\`backend/services/gce_encoding/persistence.py\`** (new):
\`JobStatePersister\` class. Lazy Firestore client (no creds at import
time). Per-VM tagging via \`vm_name\`. 7-day TTL via \`expires_at\`. All
write paths swallow Firestore errors so encoding correctness is never
blocked by persistence.
- **\`backend/services/gce_encoding/main.py\`**: \`_persist(job_id)\`
helper called after each status transition. FastAPI lifespan startup
runs \`mark_orphans_failed_on_startup()\`, flipping any in-progress jobs
from before the restart to \`failed\` with \`restart_failure_code:
encoding_worker_restart\`. Subsequent polls see clear failure instead of
404.
- **\`infrastructure/encoding-worker/startup.sh\`**: reads the GCE
instance name from the metadata server and exports
\`ENCODING_WORKER_VM_NAME\` so persistence tags rows with the actual VM
identifier.
- **\`infrastructure/modules/iam/worker_sas.py\`**:
\`roles/datastore.user\` for the encoding-worker SA.
- **\`backend/services/gce_encoding/requirements.txt\`**:
\`google-cloud-firestore>=2.14.0\`.
- **\`pyproject.toml\`**: 0.174.4 → 0.174.5

## ⚠ Deploy note

**Run \`pulumi up\` locally before merging.** Without the IAM binding
the persister logs warnings and disables — encoding still works exactly
as before, but the persistence benefit only kicks in once IAM applies.

## Test plan

- [x] 10 new tests in \`test_encoding_worker_persistence.py\` (passed
locally)
- [x] Existing encoding-worker tests still pass
- [ ] Prod verification:
  1. \`pulumi up\` (apply IAM)
  2. Deploy via CI (uploads new wheel + startup.sh, blue-green VM swap)
  3. Submit a render via the orchestrator
4. SSH to the encoding-worker VM and \`sudo systemctl restart
encoding-worker\` while the job is running
5. Observe: poll from orchestrator returns \`status: failed\` with
\`error\` containing \`encoding_worker_restart\` (not 404)
6. Confirm Firestore \`encoding_worker_jobs\` collection has the row
tagged with the correct \`vm_name\`

@coderabbitai ignore
2026-05-06 22:46:00 -04:00
..

Encoding Worker Deployment

This directory contains the scripts for the GCE encoding worker's immutable deployment pattern.

Architecture

┌─────────────────────────────────────────────────────────────────┐
│                    PACKER IMAGE (rarely changes)                │
├─────────────────────────────────────────────────────────────────┤
│ - Python 3.13, FFmpeg, fonts (static dependencies)             │
│ - bootstrap.sh (downloads startup.sh from GCS)                 │
│ - systemd service definition                                    │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼ downloads on every service start
┌─────────────────────────────────────────────────────────────────┐
│                    GCS (CI-managed, always current)             │
├─────────────────────────────────────────────────────────────────┤
│ gs://karaoke-gen-storage-nomadkaraoke/                         │
│ ├── encoding-worker/                                            │
│ │   ├── startup.sh      ← Main logic (this file)               │
│ │   └── version.txt     ← Expected version number              │
│ └── wheels/                                                     │
│     └── karaoke_gen-current.whl  ← Latest wheel (fixed path)   │
└─────────────────────────────────────────────────────────────────┘

Files

File Location Purpose
bootstrap.sh Baked in Packer image Downloads and runs startup.sh
startup.sh Deployed to GCS by CI Main startup logic
version.txt Written to GCS by CI Expected version for verification

Deployment Flow

  1. CI builds wheel → uploads to wheels/karaoke_gen-current.whl
  2. CI uploads startup.sh → encoding-worker/startup.sh
  3. CI writes version → encoding-worker/version.txt
  4. CI restarts service → triggers bootstrap.sh
  5. bootstrap.sh downloads fresh startup.sh from GCS
  6. startup.sh downloads wheel, installs, verifies version
  7. CI verifies health endpoint returns correct version
  8. CI FAILS if version mismatch

Why This Pattern?

Before (problematic)

  • startup.sh baked into Packer image
  • Required image rebuild + VM recreation for logic changes
  • 51 versioned wheels, sorting could fail
  • CI warned on version mismatch but continued

After (robust)

  • startup.sh downloaded from GCS on every start
  • Logic changes via CI, no image rebuild needed
  • Fixed path karaoke_gen-current.whl, no sorting
  • CI FAILS on version mismatch

Modifying Startup Logic

  1. Edit infrastructure/encoding-worker/startup.sh
  2. Push to main
  3. CI automatically deploys to GCS
  4. Service restart picks up new script

No Packer image rebuild needed!

When to Rebuild Packer Image

Only rebuild when changing:

  • Python version
  • FFmpeg version
  • System packages/fonts
  • bootstrap.sh (should be extremely rare)

Manual Operations

# Check current version on VM
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
  --tunnel-through-iap \
  --command="curl -s http://localhost:8080/health | jq '.wheel_version'"

# View startup logs
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
  --tunnel-through-iap \
  --command="sudo journalctl -u encoding-worker -n 50"

# Force service restart (triggers fresh startup.sh download)
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
  --tunnel-through-iap \
  --command="sudo systemctl restart encoding-worker"

Troubleshooting

Version mismatch after deployment

  1. Check CI logs for GCS upload success
  2. Check /var/log/encoding-worker-startup.log on VM
  3. Verify version.txt in GCS matches expected

Service won't start

  1. Check bootstrap.sh can reach GCS: gsutil ls gs://karaoke-gen-storage-nomadkaraoke/
  2. Check Secret Manager access for API key
  3. Check startup.sh logs: cat /var/log/encoding-worker-startup.log