Files
karaoke-gen/CLAUDE.md
T
Andrew Beveridge ☄️andClaude Opus 4.8 bcbe87a68d perf(encoding): remove dead ffmpeg_threads config; confirm finalization not CPU-capped (#914)
## Summary
- Investigated whether prod video **finalization** (`/encode` → 4K
lossless/lossy + 720p) uses the 32-vCPU `*-highcpu-32` workers
efficiently. **It does** — ~21–25 of 32 cores busy during every heavy
libx264 stage. Not capped at 8.
- `"ffmpeg_threads": 8` in `video_worker.py` was **dead config** (zero
consumers; no finalization ffmpeg command carries `-threads`). Removed
it + the stale `c4-standard-8` comment.
- No behaviour change — cleanup + documentation of the empirical
finding.

## Evidence (process-level measurement)
Drove a real finalization on a live `c4-highcpu-32` worker and sampled
`top -bH` on that same VM. System-wide `%Cpu(s)` during the heavy
stages:

| Stage | ffmpeg | `%Cpu us` (of 32) | ≈cores | peak RSS |
|---|---|---|---|---|
| "With Vocals" convert | `libx264 -c:a copy` | 64–70% | ~21 | ~11 GB |
| Lossless 4K concat | `libx264 -c:a pcm_s16le` | 72–75% | ~23 | ~9 GB |
| 720p | `libx264 scale=1280:720` | 76–78% | ~25 | ~1.2 GB |
| Lossy 4K / MKV | stream copies | low (I/O) | — | <0.1 GB |

An 8-core cap would show `us≈25%, idle≈75%`; observed the opposite. The
residual ~25–30% idle is x264's structural frame-threading ceiling, not
a recoverable cap. Full write-up in
`docs/archive/2026-08-16-finalization-cpu-efficiency-handoff.md`
(RESOLUTION section).

## Changes
- `backend/workers/video_worker.py` — remove dead `"ffmpeg_threads": 8`
field + stale comment; replace with explanatory NOTE.
- `docs/archive/2026-08-16-finalization-cpu-efficiency-handoff.md` —
append RESOLUTION with measurement, argv, stage timings, and a follow-up
note.
- `pyproject.toml` — bump `0.195.1` → `0.195.2`.
- `CLAUDE.md` — note to avoid `gsutil -m` on macOS (fork segfaults →
crash popups/hangs); use `gcloud storage`.

## Testing
- [x] Targeted encoding/worker tests pass (110:
`test_video_worker_orchestrator`, `test_workers_extended`,
`test_encoding_interface_contract`)
- [x] `grep` confirms no remaining `ffmpeg_threads` code/test references
- [x] Change is a no-op removal of an already-ignored dict field

## Review
- [x] Local CodeRabbit review completed
- [x] Review feedback addressed (1 minor doc-accuracy fix)

## Follow-up (separate task)
The "With Vocals" preview is a full 4K libx264 re-encode (~59s) of an
**already-H.264** source (`yuv444p`). If nothing downstream needs a
re-encode / different pix_fmt, a `-c:v copy` remux could save
~40–50s/job — bigger than any threading tweak. Needs its own
investigation.

@coderabbitai ignore

---
🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-16 15:14:04 -04:00

9.6 KiB

Karaoke-Gen AI Assistant Guidelines

Project Overview

Karaoke video generation platform - CLI tool and web service that creates professional karaoke videos with synchronized lyrics.

Quick Reference

What Where
Product vision & goals docs/PRODUCT-VISION.md
Current status docs/README.md
Architecture docs/ARCHITECTURE.md
Dev setup & testing docs/DEVELOPMENT.md
Testing & code quality docs/TESTING.md
API reference docs/API.md
Past learnings docs/LESSONS-LEARNED.md
Operational runbooks docs/TROUBLESHOOTING.md
GDrive validator & gaps docs/GDRIVE-VALIDATOR.md
Product communication docs/PRODUCT-COMMUNICATION-GUIDE.md
Brand style guide docs/BRAND-STYLE-GUIDE.md

Tech Stack

  • Backend: FastAPI on Cloud Run, Firestore, GCS, Secret Manager
  • Frontend: Next.js on Cloudflare Pages
  • Processing: Cloud Run GPU (L4 audio separation), AudioShake/Whisper (transcription)
  • Infra: Pulumi IaC, GitHub Actions CI/CD

Essential Rules

Git Workflow

  • Never commit directly to main - use /new-worktree <description> to start
  • Follow global workflow - see ~/.claude/CLAUDE.md for command sequence
  • Create PR with summary, changes, testing info
  • Merge only after CI passes

Testing (Required)

Before planning any implementation work, read docs/TESTING.md and ensure your plan includes a thorough testing strategy that follows the guidance there. This includes:

  • Which test types are needed (unit, integration, E2E)
  • Where tests should be placed
  • What mocking approach to use
  • Coverage expectations
  • Production E2E tests for user-facing features - see below

Critical: If your plan includes "Manual Testing" steps, convert them to automated Playwright E2E tests. Production E2E tests (in frontend/e2e/production/) are valuable even if only run once after deployment - they codify expected behavior and verify the deployed code works. See docs/TESTING.md for details.

Before committing, run all tests:

make test 2>&1 | tail -n 500

This single command:

  • Installs dependencies automatically (backend + frontend)
  • Runs all backend tests (unit, integration, emulator)
  • Runs all frontend tests (Jest unit + Playwright E2E)
  • Takes ~5-10 minutes

All tests must pass. Don't dismiss failures as "pre-existing" - investigate and fix them.

Testing in Production (for Agents)

When asked to "test it yourself in prod" or verify a fix in production:

# Get admin token
export KARAOKE_ADMIN_TOKEN=$(gcloud secrets versions access latest --secret=admin-tokens --project=nomadkaraoke | cut -d',' -f1)

# Option 1: Use the debug template directly
cd frontend && node e2e/helpers/debug-prod-template.mjs

# Option 2: Copy template for customization (gitignored)
cp frontend/e2e/helpers/debug-prod-template.mjs frontend/test-my-issue.local.mjs
# Edit the script, then run it
node test-my-issue.local.mjs

# Option 3: Run existing production E2E tests
KARAOKE_ADMIN_TOKEN=$KARAOKE_ADMIN_TOKEN npx playwright test e2e/production/admin-dashboard.spec.ts

Files matching test-*.local.* and debug-*.local.* are gitignored - you can hardcode tokens in them safely.

See docs/TESTING.md § "Ad-Hoc Production Debugging" for full details.

Version Bumping

  • Bump tool.poetry.version in pyproject.toml for code changes
  • Skip for docs-only changes

Infrastructure

  • All GCP changes via Pulumi PRs - changes in infrastructure/ deploy automatically on merge to main
  • Always run pulumi up locally BEFORE merging PRs - CI deploys run on spot VMs that can be preempted mid-apply, causing partial state. Apply locally first, then merge (CI re-runs as no-op)
  • Never modify GCP resources directly via console or gcloud CLI
  • gcloud CLI for reading/debugging only (e.g., checking logs, SSH to VMs)
  • Stop and notify user on auth issues
  • GCS ops on macOS: never use gsutil -m — its fork-based multiprocessing segfaults on macOS (crash-report popups + the parent process hangs forever). Use gcloud storage instead (gcloud storage cp/rm/rsync …) — no fork, and faster. Plain gsutil (no -m) is safe but slower. ~/.boto pins parallel_process_count=1 as a safety net; don't remove it.

Internationalization (i18n)

  • All user-facing strings live in frontend/messages/{locale}.json (33 locales), NOT in components
  • Backend strings live in backend/translations/{locale}.json (currently 3 locales: en, es, de)
  • Components use useTranslations('namespace') from next-intl
  • Pages are under frontend/app/[locale]/ — locale-aware routing (customer-facing: /, /app/*, /order/*, /auth/*, /payment/*, /r/*)
  • Non-locale routes at those same paths (e.g. frontend/app/app/jobs/[[...slug]]/page.tsx) are <LocaleRedirect /> shims that redirect into [locale] — they are NOT English-only surfaces
  • The /app/jobs/#/{id}/review, /instrumental, and /audio-edit review UIs are fully multilingual (components under components/lyrics-review/, components/instrumental-review/, components/audio-editor/ use useTranslations heavily)
  • Only /admin/* is English-only — it has no [locale]/admin counterpart and inherits DefaultIntlProvider from the root layout
  • Internal links use Link from @/i18n/routing (locale-aware)
  • After adding/changing English strings: python frontend/scripts/translate.py --messages-dir frontend/messages --target all
  • Translation uses Gemini 3.1 Pro via Vertex AI with GCS cache for efficiency
  • CI validates all locale files have matching keys — PR will fail if translations are missing
  • Pre-commit hook auto-translates when en.json changes (enable: git config core.hooksPath .githooks)
  • Don't hardcode user-facing strings — add to messages/en.json and use t('key')

API Authentication (for Agents)

When you need to call backend APIs programmatically:

Internal Worker Endpoints

Use the X-Admin-Token header with the token from Secret Manager:

# Trigger video worker
curl -X POST "https://api.nomadkaraoke.com/api/internal/workers/video" \
  -H "X-Admin-Token: $(gcloud secrets versions access latest --secret=admin-tokens --project=nomadkaraoke)" \
  -H "Content-Type: application/json" \
  -d '{"job_id": "YOUR_JOB_ID"}'

# Other internal endpoints follow the same pattern

Firestore Direct Access

# Set the correct project
export GOOGLE_CLOUD_PROJECT=nomadkaraoke

# Use Python with google-cloud-firestore
python3 << 'EOF'
import os
os.environ['GOOGLE_CLOUD_PROJECT'] = 'nomadkaraoke'
from google.cloud import firestore
db = firestore.Client(project='nomadkaraoke')
# Query/update documents...
EOF

GCE Encoding Worker

The worker is a c4d blue-green primary pair (encoding-worker-a/-b, us-central1-c) plus 8 stopped fallback VMs across 6 machine families for stockout resilience (encoding-worker-fallback-{a,b,n2c,n2f,c4a,n4db,c2df,n2da}). The currently-serving VM is active_override_vm in config/encoding-worker if set, else primary_vm. Use that VM name + its zone below (there is no VM literally named encoding-worker):

# Check health (includes wheel_version). Example uses the primary pair's VM.
gcloud compute ssh encoding-worker-a --zone=us-central1-c --project=nomadkaraoke \
  --command="curl -s http://localhost:8080/health"

# Restart the service (pick up new worker-side code after a deploy)
gcloud compute ssh encoding-worker-a --zone=us-central1-c --project=nomadkaraoke \
  --command="sudo systemctl restart encoding-worker"

For job stuck at encoding status, see docs/TROUBLESHOOTING.md.

What Doesn't Work

  • gcloud auth print-identity-token - Wrong token type for internal endpoints
  • Cloud Tasks without proper service account - Gets 401 from Cloud Run

Documentation Maintenance

Structure

docs/
├── README.md          # Current status + navigation (UPDATE THIS)
├── ARCHITECTURE.md    # System design
├── DEVELOPMENT.md     # Dev setup, testing, deployment
├── API.md             # Backend API reference
├── LESSONS-LEARNED.md # Key insights for future agents
└── archive/           # Historical docs (YYYY-MM-DD-topic.md)

Rules

  1. Before merging PRs: Run /docs-review to check if docs need updating
  2. Periodically: Run /docs-maintain to verify docs are organized
  3. For significant work: Create docs/archive/YYYY-MM-DD-topic.md
  4. Add learnings: Update docs/LESSONS-LEARNED.md with insights
  5. Keep status current: Update docs/README.md when project state changes

What Goes Where

  • README.md: Current status, known issues, quick links
  • ARCHITECTURE.md: System design, data flow, tech decisions
  • DEVELOPMENT.md: Setup, testing, deployment, CI/CD
  • API.md: Endpoints, request/response formats
  • LESSONS-LEARNED.md: What worked, what didn't, gotchas
  • archive/: Completed work, session summaries, old plans

flacfetch

Location: /Users/andrew/Projects/flacfetch

Workflow: Make changes on main, bump version, push, wait for CI, then poetry update flacfetch in karaoke-gen.

Pre-PR Checklist

Follow global workflow (~/.claude/CLAUDE.md):

  • Tests pass: /test (or make test / npm run test:all)
  • Version bumped (if code changed)
  • Docs checked: /docs-review
  • Code reviewed: /review (CodeRabbit CLI)
  • PR created: /pr (adds @coderabbitai ignore)