Compare commits

...
125 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 4.6 8c1dfe5460 feat(i18n): Phase 3 frontend — next-intl infrastructure + 1062 strings (en/es/de) (#656)
@coderabbitai ignore

## Summary
- Phase 3 of the i18n multilingual initiative — makes the karaoke-gen
frontend fully multilingual (English, Spanish, German)
- Installs `next-intl` with `[locale]` path-based routing,
LanguageSwitcher, and `Accept-Language` API header
- Extracts **1,062 strings** from ~70 components into `messages/en.json`
across 31 namespaces
- Wires `useTranslations()` into all user-facing components (landing,
dashboard, auth, job flow, lyrics review, instrumental review, audio
editor, etc.)
- Admin pages (`/admin/*`) stay outside locale routing — intentionally
excluded from i18n scope
- Static export generates `/en/`, `/es/`, `/de/` directories (45 total
pages) for Cloudflare Pages
- `es.json`/`de.json` are English placeholders — translation via Gemini
pipeline pending
- Translation pipeline (`scripts/translate.py`) and glossary (55
karaoke-specific terms) included

## Key architecture decisions
- Root layout keeps ThemeProvider/TenantProvider (needed by admin pages
outside `[locale]`)
- Only NextIntlClientProvider added to `[locale]/layout.tsx`
- `job-status.ts` labels converted to translation keys; consumers
translate via `useTranslations('jobStatus')`
- Jest mock loads actual `en.json` so existing tests validate i18n
wiring without assertion changes

## Test plan
- [x] All 707 frontend tests pass (39 suites)
- [x] Static build generates all 45 pages across 3 locales
- [x] Admin pages render at `/admin/` without locale prefix
- [x] CodeRabbit review: 4 issues fixed, 7 pre-existing noted
- [ ] Post-deploy: verify `/en/` landing page renders correctly
- [ ] Post-deploy: verify LanguageSwitcher redirects to `/es/` and
`/de/`
- [ ] Post-deploy: verify `/admin/` still works without locale context

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 21:50:53 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 105a5b28fd fix: default dashboard to all jobs, fix E2E completion detection (#655)
## Summary
- Default the dashboard status filter from "active" to "all" so
completed jobs remain visible (existing localStorage preferences
preserved)
- Add recovery logic to E2E happy path test: after 10 consecutive "card
unavailable" polls, automatically switch the filter dropdown to "All
statuses"
- Bump version to 0.157.4

**Root cause:** The daily E2E test (run #126) timed out at Step 9
because the "active" filter uses `hide_completed: true` at the API level
— when the job completed, the card vanished from the DOM and the test
retried for ~25 min until timeout. The generator itself was working
fine.

## Test plan
- [x] All 707 tests pass (`make test`)
- [x] CodeRabbit review clean (1 finding fixed)
- [ ] Next scheduled E2E run should pass with these changes

@coderabbitai ignore

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

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-03 11:41:48 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 a0e6448e7b fix: make E2E job card polling resilient to transient DOM changes (#654)
## Summary
- E2E happy path test failed because the job card DOM element briefly
disappeared during a status transition (step 9/10 "Packaging files"),
causing an unhandled `TimeoutError` on `jobCard.textContent()`
- Wrapped all `textContent()` calls in polling loops with try/catch and
a 15s explicit timeout so transient DOM disappearances retry instead of
crashing the test
- Applied fix to both `happy-path-real-user.spec.ts` and
`demo-recording.spec.ts`

Fixes:
https://github.com/nomadkaraoke/karaoke-gen/actions/runs/23887007717

## Test plan
- [x] Verified TypeScript has no new errors (all existing errors are
pre-existing Playwright type issues)
- [ ] Next scheduled E2E run will validate the fix against production

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-02 03:11:12 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 fbe3edceec fix: video worker downloads PNG instead of MOV for screens (#650)
## Summary

Follow-up to #647. The video worker was hardcoded to download
`title.mov`/`end.mov` from GCS, but those no longer exist after the
screens_worker change. 404 error on all job retries.

- `video_worker.py`: download PNG (or MOV for legacy), validate with PNG
fallback
- `video_worker_orchestrator.py`: `_screen_ext()` helper for dynamic
file extension

## Test plan

- [x] All video unit tests pass
- [ ] Retry job f0d51a0a after deploy

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 23:39:57 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 ead074505b fix: skip files >3GB in divebar sync to prevent OOM kills (#653)
## Summary

- Skip files larger than 3GB in divebar file sync — the VM has 4GB RAM
and buffers files in memory, so a 4.3GB MKV was causing OOM kills every
run
- Sets `gcs_path = 'skipped:too_large'` so the file won't be retried
nightly (the `WHERE gcs_path IS NULL` query excludes it)
- Only 1 file currently affected: `IMBK-0068 - Zolas - Ancient Mars.mkv`
(4.3 GB)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 23:24:56 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 7e93d62457 fix: thread-safe Drive service in divebar file sync (#651)
## Summary

- Use `threading.local()` for Drive API service — `googleapiclient` is
not thread-safe and sharing across `ThreadPoolExecutor` workers caused
SSL errors, bad file descriptors, and heap corruption (`free():
corrupted unsorted chunks`)
- This is why ~200 files were permanently stuck with `gcs_path=NULL` —
different files failed each run depending on thread timing

**Evidence from VM logs:**
```
ERROR Failed files/NOMAD-1346.zip: 'email'
ERROR Failed files/Shark Attack.zip: [Errno 9] Bad file descriptor
ERROR Failed files/KGAL-0004.zip: [SSL: DECRYPTION_FAILED_OR_BAD_RECORD_MAC]
ERROR Failed files/LSWK-0024.zip: [SSL: WRONG_VERSION_NUMBER]
free(): corrupted unsorted chunks
```

## Test plan

- [x] Existing unit tests pass
- [ ] Next nightly file sync run should have 0 failures (was ~200/run)
- [ ] Monitor `gcs_path IS NULL` count — should drop to only genuinely
new files

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 23:04:54 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 1c846ebae7 fix: preserve gcs_path in divebar catalog sync (#649)
## Summary

- **index_builder.py**: replaced `WRITE_TRUNCATE` with staging table +
`MERGE` SQL to preserve `gcs_path` values during daily catalog index
updates
- **divebar_file_sync.py**: added `blob.exists()` check before
downloading from Drive — if a file is already in GCS, just updates
`gcs_path` in BigQuery without re-downloading
- Added unit tests verifying the MERGE approach preserves `gcs_path`
correctly

**Root cause**: The daily 2 AM index sync was atomically replacing the
entire `divebar_catalog` BigQuery table, wiping all `gcs_path` values.
The 3 AM file sync then saw all ~48K files as unsynced and re-downloaded
the entire ~779 GB catalog from Google Drive every night.

## Test plan

- [x] Unit tests for staging+MERGE behavior (5 tests pass)
- [ ] Verify staging table auto-creates on first run (BigQuery creates
on WRITE_TRUNCATE with schema)
- [ ] Monitor next nightly sync — file_sync should report "recovered
from GCS" instead of downloading
- [ ] Confirm gcs_path values persist across consecutive index runs

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 22:31:42 +00:00
Andrew Beveridge ☄️andClaude Sonnet 4.6 c02fdc8d9f Fix GCE cache invalidation and empty corrections handling (#648)
## Summary
- **GCE style asset disk cache** now validates file size against GCS on
cache hit, re-downloading when content has changed at the same URI.
Transient GCS errors gracefully fall back to cached version.
- **Review complete endpoint** no longer writes
`corrections_updated.json` when no corrections data is present (root
cause fix for KeyError in render workers).
- **Both GCE and Cloud Run render workers** validate
`corrections_updated.json` has a `corrections` key before processing,
falling back to base result gracefully (defensive fix).

## Test plan
- [x] Added `test_cache_hit_redownloads_on_size_mismatch` — verifies
stale cache replaced
- [x] Updated `test_cache_hit_skips_download` for size validation flow
- [x] Added `test_gce_worker_skips_empty_corrections` — verifies empty
dict doesn't crash
- [x] Added `TestCompleteReviewSkipsEmptyCorrections` — 4 tests covering
guard conditions
- [x] All 2875 tests pass (8 pre-existing emulator failures unrelated)

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-31 18:03:26 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 3bc1fcb250 fix: move screen video generation to GCE encoding worker (#647)
## Summary

- Screen MOV generation (4K H.264) was silently failing on Cloud Run
after right-sizing to 2Gi (PR #640), producing 36-byte empty shells that
broke all downstream encoding
- `screens_worker` now only generates PNG/JPG images (Pillow, no FFmpeg)
- GCE encoding worker generates MOV from PNG before encoding, with
proper `subprocess.run()` error handling
- Fixed `os.system()` in `video_generator.py` to use `subprocess.run()`
so failures are no longer silent

## Root Cause

PR #640 reduced Cloud Run from 8CPU/16Gi to 2CPU/2Gi. The
`VideoGenerator._create_video_from_image()` used `os.system(ffmpeg ...)`
which OOMs silently for 4K H.264 encoding, producing 36-byte empty MOV
shells. All jobs since March 31 are affected.

## Test plan

- [x] 2875 tests pass (8 pre-existing emulator failures unrelated)
- [x] CodeRabbit: no findings
- [ ] Re-run failed job f0d51a0a after deploy to verify fix
- [ ] Verify admin "Regen screens" button works (tested flow: deletes
old screens → worker generates PNG/JPG only → GCE generates MOV from
PNG)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 21:44:53 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 adae022fbf Fix encoding progress callback causing invalid state transition (#646)
## Summary
- Fix `encoding -> encoding` invalid state transition that caused job
7bbd0d9d to fail
- The GCE encoding `progress_callback` was using `transition_to_state()`
to update progress while already in ENCODING state, which the state
machine correctly rejects as a self-transition
- Changed to `update_job()` which updates progress/message without
validating state transitions

## Test plan
- [x] All 2875 backend tests pass (8 pre-existing emulator failures
unrelated to change)
- [x] State machine integration tests pass
- [x] Encoding interface contract tests pass

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 21:19:47 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 9ccad7c6d3 feat: service health status modal with blue-green deploy details (#645)
## Summary
- Clickable footer opens a modal showing all service health, versions,
deploy times, and PR links
- Progressive disclosure: basic info for everyone, blue-green encoder
details for admins
- New aggregated `/api/health/system-status` endpoint (single fetch
instead of 4 separate calls)
- CI captures git SHA and PR info, passes to frontend and backend builds

## Changes
- **Backend**: New `/api/health/system-status` endpoint with optional
admin auth for blue-green Firestore config
- **Backend**: Build metadata env vars (COMMIT_SHA, PR_NUMBER, PR_TITLE,
STARTUP_TIME) in version module
- **Frontend**: New `SystemStatusModal` component with service cards and
expandable blue-green section
- **Frontend**: Footer version line is now clickable to open the modal
- **Frontend**: Build metadata env vars passed through next.config.mjs
- **CI**: Both frontend and backend deploy jobs capture and pass git SHA
+ PR info

## Testing
- [x] 3 unit tests for system-status endpoint (public, offline, admin
blue-green)
- [x] TypeScript compilation clean (no new errors)
- [x] CodeRabbit CLI reviewed

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 15:42:58 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 8e2a949a29 fix: complete blue-green deploy test payload and status check (#644)
## Summary
- Fix the deploy health check test payload and status value mismatches
that prevented blue-green swaps from ever completing
- Follow-up to #642 which fixed the error handling / rollback conditions

## Changes
- **Missing required fields**: `encode-preview` requires
`audio_gcs_path` and `output_gcs_path` but the health check only sent
`job_id`, `ass_gcs_path`, and `duration_seconds` (caused HTTP 422).
Added a 3-second test audio file and proper output path.
- **Status polling mismatch**: Polling checked for `"completed"` but the
GCE worker returns `"complete"` — would always time out even on success.
- **Submit response mismatch**: Validated against `"completed"` which is
never returned — endpoint returns `"accepted"`, `"cached"`, or
`"in_progress"`.

## Root Cause
The test payload was written based on the plan doc which had an
incomplete request schema. The `audio_gcs_path` and `output_gcs_path`
fields have been required since the endpoint was first created (PR #200,
Jan 2026). The status string mismatch (`"completed"` vs `"complete"`)
was likely a typo that was never caught because the request always
failed before reaching the polling stage.

## Testing
- Previous deploy (#642) confirmed the 422 error and verified rollback
now triggers correctly
- This fix addresses the payload so the encode test can actually succeed
and the swap can complete
- Real validation: next deploy after merge

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 14:07:38 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 0464d3edb3 Fix render_video GCE endpoint import paths (#643)
@coderabbitai ignore

## Summary

- Fix broken import paths in GCE worker's `/render-video` endpoint that
caused `ImportError: No module named 'backend.output_generator'` in
production
- Fix incorrect API signatures for OutputGenerator, CountdownProcessor,
CorrectionResult, load_styles_from_gcs
- Update tests to mock correct module paths

## Root cause

The subagent that implemented Task 2 (PR #641) used invented module
paths (`backend.output_generator`,
`backend.services.countdown_processor`, etc.) instead of the actual
karaoke-gen wheel paths
(`karaoke_gen.lyrics_transcriber.output.generator`, etc.). The tests
also mocked the wrong paths, so they passed locally but the code failed
in production.

## Changes

- `backend/services/gce_encoding/main.py` — Rewrote `run_render_video()`
to use correct imports and API calls matching `render_video_worker.py`
- `tests/unit/test_gce_render_video_endpoint.py` — Rewrote
TestRunRenderVideo to mock correct module paths

## Test plan

- [ ] 18 unit tests pass (verified locally with
`GOOGLE_CLOUD_PROJECT=""` to simulate CI)
- [ ] E2E happy path test after merge validates full pipeline

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 14:01:36 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 5dfaa3f73f fix: blue-green deploy health check and rollback conditions (#642)
## Summary
- Fix blue-green deploy workflow that has been silently failing since
v0.151.0 (March 25)
- Every deploy has fallen through to `ensure_latest_wheel()` hot-update
instead of tested blue-green swap

## Changes
- **Health check curl**: Replace `curl -sf` (which exits immediately on
HTTP errors before setting output) with `curl -s -o file -w
'%{http_code}'` to capture HTTP status without early exit
- **Status polling curl**: Remove `-f` flag and add fallback for failed
status checks
- **Rollback condition**: Change `passed == 'false'` to `passed !=
'true'` to catch unset/skipped cases (defense in depth)

## Root Cause
`curl -sf` with `-f` (fail silently) exits non-zero on HTTP errors.
Combined with GitHub Actions' `set -e`, the script exits before writing
`passed=false` to `$GITHUB_OUTPUT`. Both the rollback (`== 'false'`) and
swap (`== 'true'`) conditions evaluate false against the unset output,
creating a silent no-op.

## Testing
- [x] CI workflow syntax validated
- [x] CodeRabbit CLI review completed locally (no issues in changed
file)
- Real validation: next deploy will exercise the fixed workflow

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 13:46:30 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 1cf6b62398 Route render_video to GCE encoding worker (#641)
@coderabbitai ignore

## Summary

- Route `render_video_worker` (OutputGenerator/ffmpeg lyrics rendering)
to the GCE encoding worker instead of running on Cloud Run
- Fixes OOM crashes after Cloud Run memory was right-sized to 2Gi
- Adds style asset disk cache on GCE worker to avoid repeated downloads
of the same default theme
- Preserves local fallback when GCE is disabled

## Changes

### GCE Worker (`backend/services/gce_encoding/main.py`)
- New `/render-video` endpoint with `RenderVideoRequest` model
- `run_render_video()` — downloads corrections/audio/styles from GCS,
runs OutputGenerator, uploads outputs
- `download_with_cache()` — SHA-256 keyed disk cache for style assets
(fonts, backgrounds)
- `metadata` field added to `JobStatus` model for countdown padding info

### EncodingService (`backend/services/encoding_service.py`)
- `submit_render_video_job()` — POST to `/render-video` with retry logic
- `render_video_on_gce()` — submit + wait convenience method

### render_video_worker (`backend/workers/render_video_worker.py`)
- Conditional GCE routing when `encoding_service.is_enabled`
- Cloud Run does zero downloads in GCE path — constructs GCS paths from
Firestore metadata
- Existing local path preserved unchanged as fallback

## Test plan

- [ ] 18 new unit tests covering cache, endpoint, service methods, and
routing logic (all pass)
- [ ] Full test suite: 1164 passed, 0 failures
- [ ] CodeRabbit review: 1 bug caught and fixed (missing metadata in
cached response)
- [ ] E2E happy path CI validates full pipeline after merge

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 16:58:00 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 82e9becc7c chore: right-size Cloud Run + fix divebar-sync auto-shutdown (#640)
## Summary
- Right-size karaoke-backend Cloud Run: concurrency 1→80, minScale 4→1,
CPU 8→2, memory 16Gi→2Gi, enable cpu-throttling, maxScale 50→20
- Fix divebar-sync VM: add missing `shutdown -h now` after file sync
completes (VM was staying on 24/7)

## Cost Impact
- Backend right-sizing: ~$1,800/mo savings
- Divebar-sync fix: ~$32/mo savings
- Part of broader GCP cost reduction
(docs/2026-03-31-cost-reduction-design.md)

## Context
The backend is an I/O-bound API orchestrator (Firestore queries + Cloud
Run job dispatch). Heavy processing was moved to Cloud Run Jobs and a
dedicated GCE encoding worker months ago, but the Cloud Run config was
never updated. Concurrency=1 forced one-request-per-instance, and
minScale=4 kept 4 instances of 8CPU/16Gi running 24/7.

Changes have already been applied live via `gcloud run services update`
and verified with health checks.

## Test plan
- [x] All 6 Cloud Run settings updated incrementally with health checks
between each
- [x] `curl https://api.nomadkaraoke.com/api/health` returns 200 after
all changes
- [x] Divebar-sync VM stopped and metadata updated with new startup
script
- [ ] Monitor billing data over next 24-48h to confirm cost reduction

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 10:00:16 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 ca0d5507b2 Business continuity: DR backups, read-only SA, deny policies (#639)
## Summary

- Two-tier disaster recovery: GCP-native protections (PITR, versioning,
deny policies) + cross-cloud AWS S3 backups
- Nightly Cloud Function exports Firestore, BigQuery, and GCS job files
to AWS S3
- Read-only Claude SA (`claude-readonly`) and break-glass SA for
emergency access
- IAM deny policy blocking `buckets.delete` and `datasets.delete` for
all principals
- External backup freshness monitor (AWS Lambda alerts if backups go
stale >48h)

## Changes

**Infrastructure (Pulumi):**
- `modules/iam/claude_readonly_sa.py` — new read-only + break-glass SAs
- `modules/backup.py` — backup SA, staging bucket, Cloud Function, Cloud
Scheduler
- `modules/database.py` — enable Firestore PITR
- `modules/storage.py` — enable GCS versioning + soft delete lifecycle
- `modules/secrets.py` — add `discord-alert-webhook` secret
- `__main__.py` — wire new modules

**Backup Cloud Function:**
- `functions/backup_to_aws/` — Firestore export, BigQuery export
(weekly/monthly), GCS delta sync, S3 streaming upload, Discord alerts

**Documentation:**
- `docs/DISASTER-RECOVERY.md` — restore runbook for accidental deletion
+ catastrophic GCP loss
- `docs/archive/2026-03-27-business-continuity-design.md` — full design
spec
- `docs/archive/2026-03-29-business-continuity-plan.md` — implementation
plan
- `docs/archive/2026-03-29-external-services-config.md` —
OAuth/DNS/external service reference

## Already deployed

All infrastructure has been applied via `pulumi up`. First backup run
completed successfully (Firestore + job files in S3). Nightly backups
running at 1 AM ET.

## Test plan

- [x] Pulumi preview — 30 creates, 2 updates, 0 deletes
- [x] Pulumi up — all resources deployed
- [x] Manual backup function trigger — Firestore export (1.4 GB) landed
in S3
- [x] GCS job files sync — 161 files (2.9 GB) in S3
- [x] AWS Lambda freshness check — returned `ok` (3h age)
- [x] IAM deny policy verified active via `gcloud iam policies get`

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 03:32:01 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 789bf80646 Skip welcome credit AI evaluation for test emails (#638)
## Summary
- E2E test accounts (`@inbox.testmail.app`) were triggering the
Gemini-based credit evaluation on every daily test run, wasting LLM
credits and sending unnecessary denial emails
- Skip both the pre-compute (at magic link send) and inline evaluation
(at verification) for test emails — they get auto-granted directly

## Changes
- `backend/api/routes/users.py`: Skip background pre-compute thread for
test emails
- `backend/services/user_service.py`: Skip AI evaluation in
`grant_welcome_credits_if_eligible()` for test emails, go straight to
granting
- `backend/tests/test_anti_abuse.py`: Add test verifying AI eval is
skipped for testmail addresses

## Testing
- [x] All 2872 unit tests pass (8 pre-existing emulator failures
unrelated)
- [x] New test `test_skips_evaluation_for_test_emails` verifies behavior

## Review
- [x] Local CodeRabbit review completed — no findings

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 14:37:14 -04:00
Andrew Beveridge ☄️ c98da49da9 feat: add jobs search, status filter, and fix loading states (#637)
## Summary
- Add server-side text search to jobs list API (case-insensitive
substring match across artist, title, job_id)
- Replace eye icon toggle with status filter dropdown (All statuses,
Active, Failed, Completed, Cancelled, Awaiting review, Processing)
- Add debounced search input to Recent Jobs header
- Expand limit dropdown options (5, 10, 20, 50, 100, 1000)
- Fix loading state showing "No jobs yet" during cold starts (now shows
spinner)
- Fix API always fetching limit=100 regardless of dropdown selection

## Test plan
- [x] 8 unit tests for `_search_filter_jobs` (artist, title, job_id,
audio search fields, case insensitivity, None handling, empty string,
limit interaction)
- [x] Full backend test suite passes (2870 passed)
- [x] Frontend builds cleanly
- [ ] Manual: verify search filters jobs in real-time on dashboard
- [ ] Manual: verify status dropdown filters correctly
- [ ] Manual: verify loading spinner shows during cold starts instead of
"No jobs yet"

<!-- @coderabbitai ignore -->

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-03-30 05:03:05 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 022b4e343a fix: backing vocals recommendation showing 0% with contradictory message (#636)
## Summary

- Fixed API defaulting `recommended_selection` to `with_backing` when no
analysis exists, creating contradictory "Significant backing vocals
(0%)" message — now defaults to `clean`
- Fixed analyzer returning `review_needed` (unknown to frontend) instead
of `with_backing` when backing vocals detected
- Fixed race condition where backing vocals analysis ran in
screens_worker before audio separation completed — moved to audio_worker

## Test plan

- [x] All 25 analyzer unit tests pass (3 updated to match new
`WITH_BACKING` return value)
- [x] All 21 frontend instrumental review component tests pass
- [x] Full test suite: 2863 passed (8 pre-existing emulator failures)
- [x] CodeRabbit: no findings
- [ ] Verify fix in production: create new job and check instrumental
review shows correct recommendation

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 00:39:59 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 16fcb77d0f fix: relevance filtering in correction_disabled path + guidance message (#635)
## Summary

Two fixes found during post-deploy testing of #632:

1. **Relevance filter bypassed when SKIP_CORRECTION=true** — The
controller's `create_uncorrected_result()` path builds CorrectionResult
directly without going through LyricsCorrector, so wrong-song references
were never filtered. Now applies `filter_irrelevant_sources()` in this
path too.

2. **Misleading "All lyrics matched" message** — When no reference
sources exist (all filtered or none found), the guidance panel showed
"All lyrics matched the reference — no corrections needed." Now shows
"No reference lyrics were found" with guidance to use the search panel.

## Testing

- 9/9 relevance tests passing
- 22/22 GuidancePanel tests passing (updated + new test for empty state)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 04:21:58 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 14a6b767ce fix: improve cancelled job UX and fix /dashboard redirects (#633)
## Summary
- Allow downloading files from cancelled jobs (backend no longer
requires job to be complete if the file exists in GCS)
- Hide cancelled jobs from default recent jobs view alongside completed
jobs; visible via "Show all jobs" toggle
- Fix stale `/dashboard` routes → `/app` (including impersonation
redirect that 404'd)
- Show accurate total job count and helpful empty state when jobs are
filtered out

## Test plan
- [x] Backend unit tests pass (2837 passed)
- [x] Frontend unit tests pass (717 passed, 39 suites)
- [ ] Verify cancelled job download works in prod after deploy
- [ ] Verify impersonation redirects to /app correctly
- [ ] Verify "Show all jobs" toggle shows/hides cancelled and completed
jobs
- [ ] Verify empty state message shows correct total and eye icon hint

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 20:49:28 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 591c050545 feat: Reference lyrics search with relevance filtering (#632)
## Summary

- Add relevance filtering to the correction pipeline — automatically
rejects wrong-song reference lyrics (below 30% word match threshold,
validated against 168 prod source pairs)
- New `POST /api/review/{job_id}/search-lyrics` endpoint lets users
search with alternate artist/title from the review UI, with force-add
override for edge cases
- Redesigned Add Reference Lyrics modal with Search (default) and Paste
tabs, plus inline empty state when no valid sources exist

## Changes

### Backend
- **Relevance filtering** (`correction/relevance.py`): Per-source
scoring based on anchor sequence word coverage. Integrated into
`LyricsCorrector.run()` after anchor finding — sources below threshold
removed before corrections computed
- **Search endpoint** (`routes/review.py`): Queries all providers
(Genius, Spotify, Musixmatch, LRCLIB) with user-supplied artist/title,
auto-filters results, returns added/rejected/not-found breakdown
- **Provider factory** (`operations.py`): `create_lyrics_providers()`
reads env vars, `search_lyrics_sources()` orchestrates
fetch+filter+correct
- **Force override**: `add-lyrics` and `search-lyrics` support `force`
flag to bypass threshold

### Frontend
- **Tabbed modal**: `AddLyricsModal` rewritten with Search (default) and
Paste tabs
- **SearchLyricsTab**: Artist/title inputs, provider search, rejected
source cards with force-add checkboxes
- **ReferenceEmptyState**: Inline search/paste UI when no valid
reference sources exist
- **API client**: New `searchLyrics()` method with
`SearchLyricsResponse` types

### Analysis
- Empirical threshold analysis script
(`scripts/analyze_reference_relevance.py`) + visual review tool
- 168 source pairs from 81 prod jobs: wrong-song max 3.5%, correct-song
min 26.8% → 30% threshold

## Testing
- 35 new backend tests (relevance scoring, filtering, corrector
integration, search operation, API endpoint)
- 717 existing frontend tests passing (no regressions)
- Edge case: all sources filtered out handled gracefully

## Review
- [x] Local CodeRabbit review completed (3 issues fixed: response
contract, force param coercion, null checks)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 00:25:47 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 5a5ee4a780 fix: validate Google OIDC tokens from Cloud Scheduler (#631)
## Summary
- All 4 Cloud Scheduler → backend jobs (stale review processor, stuck
job recovery, YouTube queue, disposable domain sync) were returning 401
because the auth system didn't validate Google OIDC JWT tokens
- Added OIDC token validation to `AuthService.validate_token_full()`
using `google.oauth2.id_token.verify_oauth2_token()`
- Only accepts tokens signed by Google from the configured backend
service account

## Changes
- `backend/services/auth_service.py` — New `_validate_oidc_token()`
method + integration into `validate_token_full()`
- `backend/config.py` — New `SCHEDULER_SERVICE_ACCOUNT` setting
(defaults to `karaoke-backend@nomadkaraoke.iam.gserviceaccount.com`)
- `backend/tests/test_auth_oidc.py` — 10 unit tests covering all code
paths
- `docs/LESSONS-LEARNED.md` — New lesson about Cloud Scheduler OIDC vs
admin token auth
- `pyproject.toml` — Version bump 0.153.6 → 0.153.7

## Testing
- [x] 10 new unit tests (valid token, wrong SA, expired, invalid
signature, network error, passthrough)
- [x] Full backend suite: 2837 passed
- [x] Full frontend suite: 717 passed

## Review
- [x] Local CodeRabbit review completed (no findings)
- [x] Docs reviewed and updated

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 20:00:36 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 f6102e11ab fix: correct admin credits API path in e2e test (#630)
## Summary
- Follow-up to #629 — the admin credits endpoint is at
`/api/users/admin/credits` (users router prefix `/users`), not
`/api/admin/credits`
- One-line fix to the URL in the e2e test

<!-- @coderabbitai ignore -->

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 12:59:18 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 dba4ea1912 fix: grant credits via admin API when e2e test user gets 0 credits (#629)
## Summary
- Follow-up to #625 and #628 — after fixing the disposable email
allowlist and credit interstitial handling, the e2e test hits a third
issue: the credit evaluation system denies credits to testmail.app
users, leaving the guided flow inputs disabled
- Now detects 0 credits after signup and uses `E2E_ADMIN_TOKEN` to grant
1 credit via the admin API, then reloads the page

## Changes
- `frontend/e2e/production/happy-path-real-user.spec.ts`: After signup,
check credit balance and grant via admin API if 0

## Test plan
- [ ] E2E happy path test passes after merge (triggered manually)

<!-- @coderabbitai ignore -->

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 12:48:19 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 dbadcc5c17 fix: handle credit interstitial in e2e happy path test (#628)
## Summary
- Follow-up to #625 — after fixing the disposable email allowlist, the
e2e test hit a second failure: the magic link verification page now
shows credit evaluation interstitials for new users instead of
"Successfully signed in!" (which is only for returning users)
- The test now handles all verification outcomes (credits_granted,
credits_denied, credits_pending, success) and clicks through credit
interstitials to reach /app

## Changes
- `frontend/e2e/production/happy-path-real-user.spec.ts`: Use
`Promise.race` to detect which verification state appears, handle credit
interstitials by clicking through

## Test plan
- [ ] E2E happy path test passes after deployment (triggered manually)

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 12:38:30 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 257315d632 ci: use poetry.lock for GPU base image hash to avoid needless rebuilds (#627)
## Summary

- Use `poetry.lock` instead of `pyproject.toml` when computing the GPU
base image content hash
- Prevents expensive 15-20 min GPU base image rebuilds on version-only
bumps

## Problem

The GPU base image hash was computed from `cat Dockerfile.gpu-base
pyproject.toml | sha256sum`. Any change to `pyproject.toml` — including
version bumps that don't change dependencies — triggered a full GPU base
image rebuild. This adds ~15-20 min to every deploy that follows a
version bump.

## Fix

`poetry.lock` is the authoritative record of resolved dependencies. It
only changes when actual dependencies are added/removed/updated, not on
version bumps. The GPU base image installs deps via `pip install -e .`
which reads `pyproject.toml` at build time, but the Docker layer cache
handles that separately — the CI hash check just needs to know if deps
changed.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 11:30:50 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 92d1c9729d ci: auto-update lyrics-transcription-job on deploy (#626)
## Summary

- Add `lyrics-transcription-job` to the CI deploy step that updates
Cloud Run Jobs
- Previously only `video-encoding-job` and `audio-separation-job` were
updated, requiring manual `gcloud run jobs update` for lyrics

## Context

Discovered during the anchor IndexError fix (#623) — the fix was
deployed to the Cloud Run Service automatically but the Cloud Run Job
(where lyrics transcription actually runs) had to be updated manually.

## Changes

- `.github/workflows/ci.yml`: Add `gcloud run jobs update
lyrics-transcription-job` alongside the existing job updates

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 10:52:02 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 cd3076fc58 fix: allowlisted domains bypassed by external disposable email APIs (#625)
## Summary
- The disposable email detection had a bug where the Firestore
`allowlisted_domains` only protected against the Tier 1 static blocklist
check. External API checks (DeBounce, verifymail.io) at Tiers 3-4 ran
regardless and could override admin allowlist decisions.
- This broke the E2E happy path test starting March 21 when
`inbox.testmail.app` got flagged by DeBounce as disposable — the signup
step failed because "Check Your Email" never appeared.
- Adds a "Tier 1.5" check so allowlisted domains skip external API calls
entirely, plus a CI setup step to ensure the domain stays allowlisted.

## Changes
- `backend/services/email_validation_service.py`: Add allowlist check
before external API calls; include `allowlisted_domains` in cached
config
- `backend/tests/test_email_validation_service.py`: Regression test for
allowlisted domain bypass
- `.github/workflows/e2e-happy-path.yml`: CI setup step to ensure
`inbox.testmail.app` is allowlisted before test runs

## Test plan
- [x] All 53 email validation tests pass (52 existing + 1 new regression
test)
- [x] `inbox.testmail.app` added to production Firestore allowlist
- [ ] E2E happy path test passes after deployment

<!-- @coderabbitai ignore -->

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-29 10:48:24 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 78e4cc7010 fix: bounds check ref_words in anchor gap extension (IndexError b7e8c96d) (#623)
## Summary

- Fix IndexError in `_extend_anchors_into_single_word_gaps` when
`ref_texts_clean` and `ref_words` have different word counts due to
`clean_text()` normalization
- Adds production fixture regression test from crashing job `b7e8c96d`
(Bằng Kiều - Dẫu có lỗi lầm)

## Root Cause

`ref_texts_clean` is built by joining words → `clean_text()` →
`split()`, which can produce a **different word count** than the raw
`ref_words` Word objects list. For Spotify in the crashing job:
`ref_texts_clean` had 599 words, `ref_words` had 528. Anchor
`reference_positions` computed against the 599-word list were used to
index the 528-word list.

## Changes

- `anchor_sequence.py`: Add `< len(ref_words[source])` bounds check in
both `_apply_forward_extension` and `_apply_backward_extension`
- `test_anchor_gap_extension_bounds.py`: 4 regression tests (production
fixture + synthetic bounds tests)
- `anchor_crash_b7e8c96d.json`: Sanitized production fixture (49
anchors, 526 words)
- `LESSONS-LEARNED.md`: Document text normalization word count mismatch
gotcha
- Version bump: 0.153.4 → 0.153.5

## Testing

- [x] 33 anchor gap extension tests pass (29 existing + 4 new)
- [x] Full unit suite: 1146 tests pass
- [ ] After deploy: retry job `b7e8c96d`

## Review

- [x] CodeRabbit CLI review completed locally (1 finding fixed:
sanitized copyrighted lyrics)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-28 14:23:13 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 dd25a6110f docs: troubleshooting runbooks for job repair and Cloud Run Jobs (#622)
## Summary

- Surgical audio re-separation that preserves lyrics/review data (direct
Firestore + Cloud Run Jobs API)
- How to trigger Cloud Run Jobs directly, bypassing internal API
idempotency checks
- CI gap: `lyrics-transcription-job` image not updated on deploy (manual
workaround + permanent fix pointer)

Docs-only — no code changes, no version bump.

<!-- @coderabbitai ignore -->

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 20:36:51 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 e3c55672e5 fix: bounds check in anchor sequence gap extension (#621)
## Summary

- Fix IndexError in `_extend_anchors_into_single_word_gaps` when
`gap_position >= len(all_words)`
- This crashes lyrics transcription for songs where the last anchor ends
at the transcription boundary
- Affected job: `b7e8c96d` (Bằng Kiều - Dẫu có lỗi lầm)

## Fix

Add `if gap_position >= len(all_words): continue` before accessing
`all_words[gap_position]`.

## Test plan

- [x] 2 new boundary regression tests in test_anchor_gap_extension.py
- [x] Full unit suite: 1142 passed (29 anchor gap tests)
- [ ] After deploy: retry job b7e8c96d

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 19:51:42 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 bcbbb7865f fix: prevent false 'No audio sources found' on search failure (#620)
## Summary

- Fix misleading "No audio sources found" message that appeared when
audio search failed (timeout, network error, 5xx) instead of showing an
error
- Replace scattered boolean/string state with explicit `SearchStatus`
state machine so the no-results message can only appear after a
confirmed successful search
- Add automatic retry (up to 3 attempts with backoff) for transient
failures

## Changes

- **State machine:** Replace `isSearching`, `error`, `isCreditError`
with single `SearchStatus` discriminated union (`searching | succeeded |
failed`)
- **Retry logic:** Auto-retry network errors, timeouts, and 5xx up to 3
times with 2s/4s backoff delays. 4xx errors (auth, credits) fail
immediately
- **Spinner feedback:** Show "Retry 1 of 2" / "Retry 2 of 2" during
retries
- **Fuzzy accept:** Route through `doSearch` via useEffect instead of
inline API call, so corrected searches also get retry protection
- **Tests:** 5 new tests covering the core bug fix, retry behavior, and
error classification
- **Docs:** Added lesson learned about state conflation pattern

## Testing

- [x] 20/20 unit tests pass (15 existing + 5 new)
- [x] 712/712 full suite tests pass
- [x] TypeScript compiles cleanly
- [x] Production flacfetch verified healthy (v0.19.5, all providers up)

## Review

- [x] Local CodeRabbit review completed (no findings)
- [x] Two-stage review (spec compliance + code quality) during
implementation

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 14:44:27 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 8c7627b7ec fix: prevent video worker race condition and add encoding worker warmup (#619)
## Summary
- Fix race condition where Cloud Run Job `max_retries` + manual retry
launched concurrent video workers that corrupted each other's state
transitions (job 13b8adcf)
- Add encoding worker VM warmup to all paths that trigger video
encoding, not just the frontend happy path
- Defense in depth: frontend warmup → worker dispatch warmup → encoding
retry warmup

## Changes
- **job_health_service.py**: Remove `GENERATING_VIDEO`/`RENDERING_VIDEO`
from valid video_worker startup states — if a job is already in those
states, another worker is processing it
- **video_worker.py**: Make `_validate_prerequisites` a hard failure on
wrong status (was warn-and-continue)
- **worker_service.py**: Add `_warmup_encoding_worker()` called from
both `trigger_video_worker` and `trigger_render_video_worker`
- **encoding_service.py**: Add `_warmup_encoding_worker_fallback()`
called on first connection failure in retry loop
- **docs/LESSONS-LEARNED.md**: Document both findings

## Testing
- [x] 7 new unit tests covering race condition fix, warmup dispatch, and
fallback behavior
- [x] Full backend suite passes (2817 passed)
- [x] Full frontend suite passes (712 passed)

## Review
- [x] Local CodeRabbit review completed (0 code issues)
- [x] Review feedback addressed

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 14:27:29 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 0c996d1c8e fix: rename Stage 1 vocals before Stage 2 to avoid stem tag regex collision (#618)
## Summary

Follow-up to #617 — the stem tag parsing fix alone wasn't enough. The
audio-separator library's ensemble code uses
`re.search(r'_\(([^)]+)\)')` to classify intermediate stems, matching
the **first** `_(Tag)_` pattern. When Stage 2 receives Stage 1 output
like `Song_(Vocals)_preset_instrumental_clean.flac`, the regex matches
the Stage 1 tag instead of the Stage 2 tag, classifying ALL stems as
"Vocals" and producing only 1 output file instead of 2.

## Fix

Copy Stage 1 vocals to a clean filename (`Artist - Song (Vocals).flac`)
before passing to Stage 2, avoiding the regex collision.

## Test plan

- [x] Unit tests updated to verify clean filename is used for Stage 2
input
- [x] Full test suite: 1140 passed, 0 failed
- [ ] After deploy: trigger test job and verify backing vocals +
combined instrumental stems appear

<!-- @coderabbitai ignore -->

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 14:18:07 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 f58c74e67e fix: ensemble preset stem tag parsing — restore backing vocals separation (#617)
## Summary

- Fix stem filename parsing bug where preset name `instrumental_clean`
caused the Vocals file to be misclassified as instrumental, preventing
Stage 2 (backing vocals separation) from running
- All new GPU-processed jobs were only producing `instrumental_clean` —
no backing vocals, lead vocals, or combined instrumentals
- The instrumental review page showed "No backing vocals detected" for
all jobs

## Root Cause

Ensemble preset output filenames follow
`{base}_(StemTag)_preset_{name}.flac`. The old code did `"instrumental"
in basename` which matched the **preset name** `instrumental_clean` in
the Vocals file, so `result["vocals"]` was never set, and Stage 2 never
ran.

## Fix

Extract the stem tag from between `_(` and `)_` delimiters and match
only that, not the full filename.

## Test plan

- [x] 5 new regression tests for stem tag parsing (both stages)
- [x] 2 pre-existing tests fixed to use realistic ensemble filenames
- [x] Full unit suite: 1140 passed, 0 failed
- [x] CodeRabbit: no findings
- [ ] After deploy: trigger a test job and verify all stems appear on
instrumental review page

<!-- @coderabbitai ignore -->

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 12:14:32 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 ccc1b7c714 Fix lyrics upload race condition when artist/title changes mid-processing (#616)
## Summary

- Fix race condition in `upload_lyrics_results` where admin edits to job
artist/title during lyrics worker execution caused filename mismatch and
"No corrections JSON found" errors
- Scan lyrics directory by file suffix pattern instead of reconstructing
filenames from mutable Firestore metadata
- Remove unnecessary `get_job()` call and `sanitize_filename` import
from upload path

## Root Cause

Job `fbec37d6` failed because:
1. Lyrics worker started processing with artist = `zmcmillan08`
2. Admin updated artist to `Quay Money` mid-processing
3. `upload_lyrics_results` read the updated artist from Firestore and
looked for `Quay Money - ... (Lyrics Corrections).json`
4. File on disk was `zmcmillan08 - ... (Lyrics Corrections).json` → not
found → job failed

## Test plan

- [x] Updated 3 existing tests to validate directory-scanning behavior
- [x] Added new test: error path when no corrections file exists at all
- [x] All 68 worker tests pass
- [x] CodeRabbit review: no findings

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 11:14:55 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 056ce3ce2d docs: GPU audio separation learnings and cleanup (#615)
## Summary
- Remove deprecated `AUDIO_SEPARATOR_API_URL` from DEVELOPMENT.md env
vars (no longer used — separation runs directly in Cloud Run Job)
- Add GPU-specific lessons to LESSONS-LEARNED.md:
  - Pin CUDA-specific PyTorch versions in Docker images
  - Ensemble presets require explicit `load_model()` before `separate()`
  - Validate with actual Docker builds, not just package combos

Docs-only, no version bump needed.

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 01:32:35 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 dfcd79e5c7 fix: GPU app image — preserve pinned torch cu126 with --no-deps (#614)
## Summary
- Use `--no-deps` in app Dockerfile when building on GPU base image
(detected via `MODEL_DIR` env var)
- Without this, `pip install -e .` upgrades torch from pinned cu126 back
to cu130 (pyproject.toml has `torch>=2.7`) and reinstalls
audio-separator[cpu], breaking both CUDA and GPU ONNX Runtime

This is a follow-up to #613 — the GPU base image had the right packages,
but the app layer's `pip install -e .` undid the pinning.

## Test plan
- [ ] CI passes
- [ ] Deploy, trigger audio separation job
- [ ] Verify Job logs show CUDA available + successful separation

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 23:59:47 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 c4ea0e8fb4 fix: GPU audio separation — pin PyTorch cu126 + missing load_model() (#613)
## Summary
- Pin PyTorch to `cu126` in GPU Dockerfile — Cloud Run L4 GPUs have
driver 570 (CUDA 12.8 max), but `audio-separator[gpu]` pulls PyTorch
`cu130` which fails with "driver too old"
- Add missing `separator.load_model()` before `separator.separate()` for
ensemble presets in `audio_processor.py` — the Separator API requires
this even for presets
- Remove `AUDIO_SEPARATOR_API_URL` from Service env vars (cleanup — Job
has its own `MODEL_DIR`)

## Validation
Tested on GCE L4 GPU VM:
- `torch==2.6.0+cu126` + `audio-separator[gpu]` 0.44.1 → CUDA detected,
GPU acceleration enabled
- Full ensemble separation (`instrumental_clean` preset) completed in
**26.6s** on real audio
- Docker image build validation in progress on separate L4 VM

## Test plan
- [ ] CI passes (GPU image rebuilds due to Dockerfile change)
- [ ] Trigger audio separation job after deploy
- [ ] Verify Cloud Run Job logs show "CUDA is available" and "local GPU"
mode
- [ ] Verify stems are correct

@coderabbitai ignore

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 23:18:32 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 7424398fcf fix: use us-east4 region for audio separation job trigger (#612)
## Summary

The audio-separation-job moved to us-east4 (GPU), but the worker trigger
was still using the default us-central1 region. Added `location`
parameter to `_trigger_worker_cloud_run_job()` and passed `us-east4` for
the audio worker.

Also includes the FFmpeg apt fix from #611.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 17:36:07 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 41f296f70b fix: use apt FFmpeg in GPU Dockerfile (CI timeout fix) (#611)
## Summary

The johnvansickle.com static FFmpeg download times out in CI (curl exit
code 28). The audio worker only uses FFmpeg for format conversion and
padding, not encoding, so the Ubuntu apt package is sufficient.

Fixes the GPU base image build failure in the deploy-backend workflow.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 20:56:36 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 177e70efc5 fix: GPU Cloud Run Job infra fixes (zonal redundancy, deletion protection) (#610)
## Summary

Fixes for the GPU audio worker Cloud Run Job that were discovered during
Pulumi apply:

- `deletion_protection=False` — needed so Pulumi can replace the job
when changing regions
- `gpu_zonal_redundancy_disabled=True` — required for Cloud Run Jobs
with GPU (GCP capacity limitation)

Follow-up to #609 (GPU image CI) where the Pulumi apply failed.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 16:28:17 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 55dd7a30d0 ci: add GPU image build and audio worker deploy to workflow (#609)
## Summary

- Adds GPU base image build to the deploy-backend CI job (same
hash-check pattern as regular base image)
- Builds GPU app image (regular Dockerfile with GPU base as
`BASE_IMAGE`)
- Updates `audio-separation-job` in us-east4 with the GPU image on every
deploy
- Configures Docker auth for the us-east4 Artifact Registry

## Changes

- `.github/workflows/ci.yml` — GPU base image hash check + build, GPU
app image build, audio-separation-job update
- `backend/Dockerfile.gpu-base` — Added `BASE_CONTENT_HASH` label for
hash-based rebuild detection

## How it works

On merge to main, the deploy-backend job now:
1. Builds regular base + app images (unchanged)
2. Hashes `Dockerfile.gpu-base` + `pyproject.toml` → checks if GPU base
needs rebuild
3. If rebuild needed: builds GPU base image (CUDA + PyTorch + models,
~45 min timeout)
4. Builds GPU app image (regular Dockerfile with GPU base)
5. Updates `audio-separation-job` in us-east4 with the new GPU image

The first run will take longer (GPU base image bootstrap). Subsequent
runs skip the GPU base build unless `Dockerfile.gpu-base` or
`pyproject.toml` changes.

## Testing
- [x] YAML syntax verified
- [ ] First CI run will bootstrap the GPU base image (expect ~30-45 min)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 15:47:07 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 92ae3fb28f feat: run audio separation directly on GPU in audio worker (#608)
## Summary

- **Eliminates HTTP hop** between the audio worker Cloud Run Job and the
audio-separator Cloud Run Service by running the `Separator` class
directly with an L4 GPU attached
- **Adds GPU Docker image** (`karaoke-backend-gpu`) with CUDA 12.6,
PyTorch, and pre-baked ensemble preset models
- **Moves audio worker to us-east4** with L4 GPU, 4 CPU, 16Gi memory —
old separator service kept for rollback

## Changes

### Code
- `audio_processor.py` — Ensemble presets wired into local Separator
path (2-stage: `instrumental_clean` + `karaoke`)
- `audio_worker.py` — Dual-mode support: `MODEL_DIR` env var → local
GPU, `AUDIO_SEPARATOR_API_URL` → remote API
- `create_audio_processor()` — New `model_file_dir` parameter to enable
local GPU mode

### Infrastructure (Pulumi)
- `gpu_artifact_registry.py` — New Artifact Registry in us-east4 for GPU
images
- `cloud_run.py` — Audio worker job: GPU (nvidia-l4), us-east4, 16Gi,
`MODEL_DIR=/models`
- `__main__.py` — Wire in GPU registry + Cloud Build IAM

### Docker
- `Dockerfile.gpu-base` — CUDA 12.6 + Python 3.11 + audio-separator[gpu]
+ baked models
- `cloudbuild-gpu-base.yaml` — Cloud Build config (E2_HIGHCPU_32, 100GB
disk, 1h timeout)
- `download_models.py` — Bakes `instrumental_clean` + `karaoke` preset
models at build time

### Tests
- 8 new unit tests covering factory config, mode selection, and preset
wiring
- Updated existing test patch targets for module-level Separator import

## Testing
- [x] 22/22 unit tests pass (8 new + 14 existing)
- [x] Code review completed (subagent-driven + final review)
- [x] CodeRabbit CLI review completed locally
- [ ] GPU image build (requires `gcloud builds submit`)
- [ ] Production verification with `under_pressure_harmonies.flac`

## Rollback Plan
Set `AUDIO_SEPARATOR_API_URL` back on the audio worker job → falls
through to remote API path. Old separator service is still running
(scale-to-zero).

## Design & Plan
- Design spec:
`docs/archive/2026-03-26-direct-gpu-audio-separation-design.md`
- Implementation plan:
`docs/archive/2026-03-26-direct-gpu-audio-separation-plan.md`

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 15:13:51 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 2cc1061a9d Audio separator infra + docs (concurrency, Firestore, GCS) (#607)
## Summary

- Infrastructure for async audio separator: GCS output bucket, Firestore
index, IAM, env vars
- Set concurrency=1 (each GPU job gets own instance for proper
autoscaling)
- Updated all docs: Modal→Cloud Run GPU references, architecture design
spec, lessons learned
- Phase 2 noted: migrate separator to Cloud Run Jobs

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 17:37:59 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 be19e6c7a0 Infra for async audio separator (concurrency, GCS, Firestore) (#606)
## Summary

- Update audio separator Cloud Run service:
`max_instance_request_concurrency` 1→50, `max_instances` 5→10
- Add `OUTPUT_BUCKET` and `GCP_PROJECT` env vars for the separator
service
- Create `nomadkaraoke-audio-separator-outputs` GCS bucket with 1-day
lifecycle policy
- Grant separator service account `roles/datastore.user` for Firestore
and `roles/storage.objectAdmin` for the output bucket
- Add Firestore composite index on `audio_separation_jobs` (status +
updated_at) for cleanup queries

Companion to nomadkaraoke/python-audio-separator#280. Deploy order: this
PR's infra first (`pulumi up`), then the separator service.

## Test plan

- [ ] `pulumi preview` shows expected resource changes
- [ ] `pulumi up` applies cleanly
- [ ] Verify GCS bucket created with lifecycle policy
- [ ] Verify Firestore index created
- [ ] Verify separator service updated with new concurrency/scaling
settings

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-26 00:41:45 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 8f8fc269e6 fix: retry returns to lyrics review when not completed (#605)
## Summary
- Fixed retry checkpoint detection skipping lyrics review when user
never completed it
- Previously, retry used `corrections.json` + `title.mov` as proxy for
"review done," but both are auto-generated artifacts that exist BEFORE
user review
- Now requires `instrumental_selection` in state_data (only set via
review submit endpoint) to confirm review was actually completed
- Jobs that failed before review completion now correctly return to
`awaiting_review` on retry

## Root Cause
Job `45f9bbc0` hit this: audio separation kept failing, but corrections
+ title screen existed from the lyrics/screens pipeline. Retry jumped to
`REVIEW_COMPLETE`, skipping review entirely. Admin had to manually
reset.

## Test plan
- [x] Updated existing render checkpoint test to require
`instrumental_selection`
- [x] Added regression test for the skip-review scenario
- [x] All 8 retry endpoint tests pass
- [x] Full backend suite passes (2583 passed)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 21:58:58 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 ce4bde6a6d fix: update audio-separator to 0.44.1 (multipart fix) (#603)
## Summary
Update audio-separator from 0.44.0 to 0.44.1 to fix 400 Bad Request when
using `gcs_uri`.

v0.44.0 sent `x-www-form-urlencoded` when no file was uploaded (gcs_uri
mode), but FastAPI requires `multipart/form-data`. v0.44.1 fixes this.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 19:01:25 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 22a500d153 Pre-compute credit evaluation at magic link send time (#602)
## Summary
- Run AI credit evaluation in background thread when sending magic link
(new users only)
- Store result on magic link Firestore doc
- At verify time, use pre-computed result if available, fall back to
inline evaluation if not
- Most users will see instant verification instead of 20s wait

## Test plan
- [x] 53 anti-abuse + credit evaluation tests pass (3 new)
- [x] New test: pre-computed eval skips AI call
- [x] New test: verify passes pre-computed eval from magic link doc
- [x] New test: verify falls back to None when no pre-computed eval
- [ ] Manual test: sign up, verify welcome screen appears quickly

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 22:36:31 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 7c39b2817f Fix Vertex AI region: use global for latest Gemini models (#600)
## Summary
- Preview Gemini models (gemini-3.1-pro-preview) require
`location="global"`, not `us-central1`
- This was causing 404 errors when the credit evaluation tried to call
Gemini for users with abuse signal correlations
- Bump version to 0.150.6

## Test plan
- [x] All 50 anti-abuse + credit evaluation tests pass
- [ ] Manual test: sign up with correlated fingerprint/IP, verify AI
evaluation runs successfully

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 17:20:08 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 c47fe6518c fix: update audio separator URL from Modal to Cloud Run (#601)
## Summary
- The CI deploy script was still setting `AUDIO_SEPARATOR_API_URL` to
the old Modal endpoint
- Update to the Cloud Run GPU service URL
(`audio-separator-718638054799.us-east4.run.app`)
- This was the root cause of the 422 error when retrying job 45f9bbc0

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 16:18:44 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 046ca69a1c fix: pass GCS URI to audio separator, fix WIF for deploys (#599)
## Summary
- Fix 413 Request Entity Too Large for audio separation of large FLAC
files
- Fix Workload Identity Federation for python-audio-separator Cloud Run
deploys

## Changes
- **Infrastructure:** Grant `storage.objectViewer` to audio-separator SA
so it can read from the main GCS bucket
- **Infrastructure:** Add `python-audio-separator` repo to the WIF
binding (was missing, blocking all Cloud Run deploys)
- **Audio worker:** Set `input_gcs_uri` on the processor when the input
file is already in GCS
- **Audio processor:** Stage 1 passes `gcs_uri` to the separator API
instead of uploading file bytes
- **Dependency:** Update `audio-separator` to 0.44.0 (adds `gcs_uri`
support)
- **Version:** 0.151.0 → 0.152.0

## How it works
Before: `audio_worker → download from GCS → HTTP POST (file bytes) →
separator` (fails for >32MB)
After: `audio_worker → pass gs:// URI → separator downloads from GCS
directly` (no size limit)

Stage 2 (backing vocals) still uses file upload since the input is a
Stage 1 output that's already local.

## Test plan
- [x] 2 new unit tests: GCS URI passthrough + fallback to file upload
- [x] All 28 migration tests pass
- [x] Pulumi infra changes applied (GCS IAM + WIF binding)
- [x] Audio separator v0.44.0 deployed to Cloud Run and healthy
- [ ] Re-run failed job 45f9bbc0 to verify fix end-to-end

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 14:36:03 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 efb4aa8351 fix: add google-cloud-compute dependency for encoding worker VM management (#598)
## Summary

- Adds `google-cloud-compute` to pyproject.toml dependencies
- The backend needs this to call the Compute API (start/stop VMs) for
the blue-green encoding worker warmup
- Without it, the warmup/heartbeat endpoints return 500 with
`ImportError: cannot import name 'compute_v1' from 'google.cloud'`

## Test plan

- [x] Verified the import error in Cloud Run logs
- [ ] After merge, warmup endpoint should return 200

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 14:12:15 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 d681e26b02 fix: encoding worker deploy failure should not block Docker deploy (#597)
## Summary

- The blue-green encoding worker health check failure was blocking the
entire CI job, preventing the Docker image from being built and deployed
to Cloud Run
- This meant the new backend code (with warmup/heartbeat endpoints) was
never deployed, causing 404s on the new routes
- Fix: add `continue-on-error: true` to health check and encode test
steps so the Docker deploy always proceeds
- The rollback step now checks step outputs instead of `failure()`
condition

## Root cause

The CI job runs encoding worker deploy → Docker build → Cloud Run deploy
sequentially. When the encoding worker health check failed (missing
`packaging` module), the job stopped before reaching the Docker build
step.

## Test plan

- [x] Encoding worker deploy failure no longer blocks Docker deploy
- [ ] Next CI run on main will deploy the backend with new routes

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 13:53:46 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 2003d4acc8 fix: add packaging to encoding worker Packer image venv (#596)
## Summary

- Adds `packaging` to the pre-installed Python dependencies in the
Packer image venv
- The encoding worker imports `packaging.version.Version` but this
wasn't in the base image
- First blue-green deploy caught this via the health check — encoding
worker crashed on startup with `ModuleNotFoundError: No module named
'packaging'`
- Manually installed on both VMs as a temporary fix; this makes it
permanent for future image builds

## Test plan

- [x] Verified encoding worker starts after manual `pip install
packaging` on both VMs
- [ ] Next Packer image build will include this dependency

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 12:00:05 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 19efa269a8 feat: blue-green encoding worker deployment with deep health checks (#595)
## Summary

- Replaces single encoding worker VM with a blue-green pair (a/b) for
zero-downtime deployments
- VMs auto-start on demand (JIT warmup when user opens lyrics review)
and auto-shutdown after 15 min idle
- CI deploys to secondary VM, runs a real encode test, then swaps the
Firestore pointer atomically
- Deep health check catches issues like PR #587's pip crash before they
reach users
- Cloud Function checks idle VMs every 5 minutes and stops them to
minimize cost (~$10-15/mo idle vs $800/mo always-on)

## Architecture

- **Firestore config doc** (`config/encoding-worker`) is single source
of truth for primary/secondary routing
- **Backend** reads primary IP from Firestore (30s TTL cache), starts VM
on demand via Compute API
- **CI workflow** handles blue-green swap: deploy → health check → real
encode test → atomic Firestore swap → drain & stop old
- **Cloud Function** auto-stops idle VMs based on active jobs, user
activity, and deploy status
- **Frontend** sends warmup signal on lyrics review page load +
heartbeat on interactions

## Changes

### New Files
- `backend/services/encoding_worker_manager.py` — VM lifecycle +
Firestore config management
- `backend/api/routes/encoding_worker.py` — Warmup and heartbeat API
endpoints
- `infrastructure/functions/encoding_worker_idle/` — Idle shutdown Cloud
Function
- `infrastructure/modules/encoding_worker_manager.py` — Pulumi module
for Cloud Function + Scheduler
- `scripts/seed-encoding-worker-config.py` — Firestore config seeding
script
- `infrastructure/encoding-worker/test-assets/test-preview.ass` — Test
file for deploy health check

### Modified Files
- `infrastructure/compute/encoding_worker_vm.py` — Single VM →
blue-green pair
- `infrastructure/__main__.py` — Wire up new VMs, Cloud Function, IAM
- `backend/services/encoding_service.py` — Dynamic URL from Firestore,
warmup-aware retry
- `.github/workflows/ci.yml` — Blue-green deploy flow
- `frontend/` — Warmup signal on lyrics review, heartbeat, warming-up UI
state
- `docs/` — Architecture, development, troubleshooting, lessons learned

## Test plan

- [x] 47 new backend tests pass (EncodingWorkerManager, routes, dynamic
URL resolution)
- [x] 9 Cloud Function unit tests pass
- [x] All 2808 existing backend tests pass (1 pre-existing failure
unrelated)
- [x] All 1116 existing unit tests pass (3 pre-existing failures
unrelated)
- [ ] Pulumi preview shows expected resource changes
- [ ] Pulumi up applied locally before merge
- [ ] Firestore config seeded with VM IPs
- [ ] End-to-end verification after deployment

## Migration Steps (post-merge)

1. `pulumi up` creates 2 VMs, removes old VM
2. Seed Firestore: `python scripts/seed-encoding-worker-config.py <ip-a>
<ip-b>`
3. Start VM A, verify health
4. First CI deploy exercises the blue-green flow

## Design Docs

- Spec:
`docs/superpowers/specs/2026-03-24-blue-green-encoding-worker-design.md`
- Plan:
`docs/superpowers/plans/2026-03-24-blue-green-encoding-worker.md`

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-25 11:28:45 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 4e23f07d0a Fix credit evaluation: Vertex AI credentials + enriched admin review email (#594)
## Summary
- Fix Gemini API call failing due to missing API key — switch to Vertex
AI with default GCP credentials
- Enrich admin review email with abuse signals (IP, geo, fingerprint,
matching accounts, user agent, signup counts)
- HTML-escape user-controlled values in review email

## Test plan
- [x] All 50 anti-abuse + credit evaluation tests pass
- [x] Full backend test suite passes (2549 pass, 139 skipped)
- [ ] Manual test: sign up with clean email, verify welcome credits
granted
- [ ] Manual test: verify admin review email includes signal details
when evaluation triggers

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 23:48:39 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 7d887a11b0 Fix FLAC uploads to AudioShake by stripping metadata (#593)
## Summary
- Strip metadata from FLAC files before uploading to AudioShake to
prevent 502 errors caused by non-standard tags (MP4/M4A container fields
embedded in FLAC)
- Uses `ffmpeg -map 0:a -c copy -map_metadata -1` to remove metadata
while keeping audio unchanged
- Added unit + integration tests for the new metadata stripping path

## Context
AudioShake confirmed that non-standard metadata tags in FLAC files cause
their processing pipeline to fail during task creation. The audio itself
is valid — only the metadata is problematic. This fix proactively strips
all metadata before upload.

## Test plan
- [x] Unit test: FLAC files route through `_strip_metadata` instead of
direct upload
- [x] Integration test: metadata is actually removed from output FLAC
(verified via ffprobe)
- [x] All 30 AudioShake tests pass
- [x] Full test suite: 1117 passed (3 pre-existing failures unrelated to
this change)

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 23:18:56 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 6577babfea Reduce free credits from 2 to 1 per grant (#592)
## Summary

- Welcome credits: 2 → 1 (granted on first email verification)
- Feedback credits: 2 → 1 (granted for submitting product feedback)
- Total possible free credits per account: 4 → 2

## Changes

**Backend:** `NEW_USER_FREE_CREDITS` constant, feedback credit grant, AI
evaluation prompt, model defaults
**Frontend:** Landing page, dashboard banner, feedback dialog, auth
dropdown menu text
**Tests:** Updated all assertions and mock values (115 backend + 712
frontend tests pass)
**Docs:** AI-CREDIT-GATING.md, API.md, README.md,
PRODUCT-COMMUNICATION-GUIDE.md

## Test plan

- [x] Backend tests pass (115 passed)
- [x] Frontend Jest tests pass (712 passed)
- [ ] CI pipeline passes
- [ ] Verify landing page shows "1 Free Credit" after deploy
- [ ] Verify new user signup grants 1 credit (not 2)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 21:30:38 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 a7e41a09d6 Fix custom background image not applied in guided flow (#590)
@coderabbitai ignore

## Summary

- **Bug:** Custom background images uploaded during guided job creation
were silently ignored — the endpoint returned 500 due to
`AttributeError: 'StorageService' object has no attribute 'bucket_name'`
- **Fix:** `storage_service.bucket_name` → `storage_service.bucket.name`
(the correct attribute path)
- **Test fix:** Updated mock to use real attribute path
(`mock.bucket.name`) so this class of bug is caught

## Root Cause

The `complete_style_uploads` endpoint (line 2489) referenced
`storage_service.bucket_name`, but `StorageService` only exposes
`self.bucket` (a GCS Bucket object). The correct path is
`storage_service.bucket.name`.

The frontend's `uploadStyleAssets` caught the 500 error silently
(`console.error` only), so jobs continued rendering with default theme
backgrounds instead of the user's uploaded custom image.

The test passed because Mock objects auto-create attributes —
`mock.bucket_name = "test-bucket"` worked even though the real service
has no such attribute.

## Test plan

- [x] All 23 style upload tests pass
- [ ] Submit a job with custom background image and verify it renders
correctly

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 21:00:12 -04:00
Andrew Beveridge ☄️andClaude Sonnet 4.6 3e8e3474b2 Fix Pulumi state drift: env var ordering, divebar VM, model bucket (#591)
@coderabbitai ignore

## Summary
- Sort Cloud Run Job env vars alphabetically to match GCP API return
order (prevents phantom diffs on every `pulumi preview`)
- Add divebar-sync VM infrastructure code that was deployed from a
feature branch but never merged to main (prevents accidental deletion of
active infrastructure)
- Remove dead `create_model_bucket()` code and empty GCS bucket (models
baked into Docker image)

## Changes
- **`infrastructure/modules/cloud_run.py`**: Reorder env vars
alphabetically in all 4 Cloud Run Jobs (video-encoding,
audio-separation, lyrics-transcription, audio-download)
- **`infrastructure/compute/divebar_sync_vm.py`** (new): GCE VM
definition for divebar file sync (Drive → GCS)
- **`infrastructure/compute/startup_scripts/divebar_sync.sh`** (new): VM
startup script with google-auth pinning and MTLS workarounds
- **`infrastructure/__main__.py`**: Wire divebar-sync VM, Cloud
Scheduler, and IAM binding
- **`infrastructure/modules/audio_separator_service.py`**: Remove unused
`create_model_bucket()` and `storage` import

## Verification
- `pulumi preview` shows **0 changes** after applying
- `pulumi up` applied successfully (4 Cloud Run Job SDK metadata updates
+ 2 empty bucket deletes)
- Divebar-sync VM continues running undisturbed

## Test plan
- [x] `pulumi preview --diff` confirms zero drift
- [x] `pulumi up` applied cleanly (update #649)
- [x] Divebar-sync VM verified RUNNING in GCP
- [x] No application code changes — infra-only

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

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-24 20:53:58 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 4f8d2d71ed Fix pip resolution-too-deep in Docker base image build (#589)
## Summary
- Pin all 10 google-cloud-* and google-auth-* packages to exact latest
versions instead of loose lower bounds (e.g., `>=2.14.0` → `2.26.0`)
- Eliminates pip's massive backtracking that caused
`resolution-too-deep` errors during Docker base image builds
- Version bump: 0.150.2 → 0.150.3

## Context
The Docker base image build (`pip install -e .`) was failing because pip
had to search through hundreds of version combinations for
google-cloud-run, google-cloud-monitoring, grpc-google-iam-v1, and
googleapis-common-protos. Exact pins give pip zero backtracking to do.

## Test plan
- [x] `poetry lock` resolves cleanly
- [x] Backend tests pass (297 passed)
- [ ] CI Docker base image build succeeds (the actual fix)

<!-- @coderabbitai ignore -->

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 20:47:05 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 0666a827dd Fix: migrate from google-generativeai to google-genai SDK (#588)
## Summary
- Remove `google-generativeai` (old SDK) from pyproject.toml — caused
17h encoding worker outage via pip dependency resolution explosion
- Migrate `credit_evaluation_service.py` to use `google.genai.Client`
(new SDK, already available via langchain-google-genai)
- Regenerate poetry.lock

Fixes the encoding worker crash loop from PR #584. See PR #587 for the
immediate `--no-deps` workaround.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 16:00:53 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 0635f800f6 Fix audio separation failure: smart fallback, retry, scale GPU (#586)
@coderabbitai ignore

## Summary

Fixes job 491be627 which failed because the remote audio-separator API
was busy and the code fell back to local `Separator()` which crashed
with `model_file_dir=None` in Cloud Run.

- **audio_processor**: Only fall back to local processing if
`model_file_dir` is configured (preserves CLI fallback, prevents crash
in Cloud Run)
- **audio_worker**: Retry separation up to 5x with exponential backoff
(60s, 120s, 240s, 480s — handles 15+ min busy periods)
- **infrastructure**: Scale audio-separator from 1→5 max instances with
`concurrency=1` so Cloud Run routes concurrent jobs to separate GPU
instances

## Infrastructure changes (already applied via `pulumi up`)

- `audio-separator` Cloud Run service: `maxInstanceCount: 1 → 5`,
`maxInstanceRequestConcurrency: 80 → 1`
- `audio-separator-allow-unauthenticated` IAM member created

## Test plan

- [x] Backend tests pass (2549 passed)
- [x] Pulumi changes applied successfully to prod
- [ ] Verify next audio separation job succeeds

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 15:34:48 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 9142ae5e5d fix: encoding worker crash loop from pip resolution-too-deep (#587)
## Summary
- Encoding worker has been in a crash loop since Mar 24 01:58 UTC (~17
hours) because `pip install --force-reinstall` of the 0.150.0 wheel hits
pip 25.3's `resolution-too-deep` error
- Root cause: `google-generativeai >= 0.8.0` added in #584 creates an
overly complex dependency graph when combined with existing
langchain/CUDA packages
- Fix: add `--no-deps` to pip install in `startup.sh` — the venv already
has runtime deps pre-installed, only the karaoke-gen code needs updating
- **Already deployed**: fixed `startup.sh` uploaded to GCS and encoding
worker restarted successfully

## Test plan
- [x] Reproduced `resolution-too-deep` locally with pip 25.3 in clean
venv
- [x] Verified `--no-deps` install works locally (instant, module loads)
- [x] Tested `--no-deps` install directly on the encoding worker VM with
sudo
- [x] Uploaded fixed startup.sh to GCS and restarted service
- [x] Verified health check passes:
`{"status":"ok","wheel_version":"0.150.0"}`
- [x] Retried failed job `b6e4b044` — now processing

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 15:31:26 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 5ea7a57eac Fix admin sidebar transparent background on mobile and desktop (#585)
## Summary
- Add missing sidebar CSS variables to `app/globals.css` for both dark
and light themes
- Add Tailwind v4 `@theme inline` color mappings for sidebar utilities
(`bg-sidebar`, `text-sidebar-foreground`, etc.)
- The sidebar component (shadcn/ui) was using `bg-sidebar` which
resolved to transparent because the CSS variables were defined in an
unused `styles/globals.css` file but missing from the active
`app/globals.css`

## Test plan
- [x] Verified sidebar has solid opaque background on mobile (375px) —
Sheet drawer no longer shows content behind
- [x] Verified sidebar has solid background on desktop (1280px) — no
transparency on abuse page or other admin screens
- [x] Verified sidebar renders correctly at tablet width (768px)
- [x] Verified all 10 admin pages render correctly on mobile (Dashboard,
Users, Jobs, Payments, Audio Searches, Rate Limits, Edit Reviews, Audio
Edits, Feedback, Abuse Investigation)
- [x] All 712 frontend tests pass

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 15:06:23 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 42a7793681 AI-powered credit gating with Gemini evaluation (#584)
## Summary
- Replace automatic welcome/feedback credit grants with AI-powered abuse
evaluation using Gemini 3.1 Pro
- **Fail-closed**: errors/uncertainty → credits withheld, admin notified
via email with user admin link
- Clean users (no correlations) get instant grant with no AI call
latency
- Frontend verify page shows preparing account →
celebratory/denied/pending interstitial
- Comprehensive docs at `docs/AI-CREDIT-GATING.md`

## Changes
| File | What |
|------|------|
| `backend/services/credit_evaluation_service.py` | **New**: Signal
collection, Gemini prompt, response parsing, Firestore audit |
| `backend/config.py` | `CREDIT_EVAL_ENABLED`, `CREDIT_EVAL_MODEL`
config |
| `backend/services/user_service.py` | Welcome credit flow integration
(returns tuple) |
| `backend/api/routes/users.py` | Feedback credit + verify response
integration |
| `backend/services/email_service.py` | `send_credit_denied_email()`,
`send_credit_review_needed_email()` |
| `backend/models/user.py` | `credit_status` field on verify response |
| `frontend/app/auth/verify/page.tsx` | 5-state interstitial flow |
| `frontend/lib/types.ts` + `auth.ts` | Type + state updates |
| `backend/tests/test_credit_evaluation.py` | **New**: 17 tests |
| `backend/tests/test_anti_abuse.py` | Updated for new return type |
| `docs/AI-CREDIT-GATING.md` | **New**: Comprehensive documentation |
| `pyproject.toml` | `google-generativeai` dep, version bump |

## Test plan
- [x] 50 backend tests pass (17 new + 33 updated)
- [ ] Manual: test with new account signup in prod (see docs for
expected flow)
- [ ] Manual: verify admin review email received for error cases

## Rollback
Set `CREDIT_EVAL_ENABLED=false` in Cloud Run env vars → instant revert
to auto-grant.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 21:57:46 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 21d8b270ae Fix: filter bad IPs from abuse correlation clusters (#583)
## Summary
- Filter known bad IPs (169.254.169.126 GCP load balancer, "unknown",
empty) from IP correlation clusters
- Discovered in production: the load balancer IP was creating a false
22-account cluster

Follow-up to #582.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 17:05:43 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 8e33c4b6aa Rework abuse investigation with cross-account correlations (#582)
## Summary
- **Fix** broken user profile link URL (was 404, now goes to correct
detail page)
- **Add** internal/test account filtering — excludes @nomadkaraoke.com,
@beveridge.uk, @inbox.testmail.app from all abuse views
- **New** Correlations tab (now default) showing fingerprint clusters
(RED flag) and IP clusters (ORANGE flag), with user agent matching
highlighted (YELLOW signal)
- **Demote** old "Suspicious Accounts" to secondary tab

## Motivation
The existing "Suspicious Accounts" view flagged too many false positives
— legitimate users who just used their 2 free credits, internal test
accounts, etc. The real abuse signal is **cross-account correlation**:
multiple accounts sharing the same device fingerprint or signup IP.

## Changes
| File | What |
|------|------|
| `backend/utils/test_data.py` | Add internal email domain filtering |
| `backend/services/user_service.py` | New
`find_account_correlations()`, filter suspicious accounts |
| `backend/api/routes/admin.py` | New `GET
/api/admin/abuse/correlations` endpoint |
| `frontend/lib/api.ts` | New types + API client method |
| `frontend/app/admin/abuse/page.tsx` | Fix link URL, new Correlations
tab, restructure tabs |
| `backend/tests/test_anti_abuse_investigation.py` | 10 new tests |

## Test plan
- [x] 27 anti-abuse investigation tests pass (10 new)
- [x] 2749 backend tests pass
- [x] Frontend dev server starts without errors
- [ ] Manual: verify correlations tab shows real data in prod

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 16:40:07 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 c9e434037b feat: admin feedback visibility — page + email notification (#581)
<!-- @coderabbitai ignore -->

## Summary

- **Admin feedback page** at `/admin/feedback` — browse all user
feedback submissions with star ratings, text fields, search, pagination,
and aggregate stats
- **Email notification** to admin@nomadkaraoke.com whenever a user
submits new feedback (configurable via `ADMIN_NOTIFICATION_EMAIL` env
var)
- **Admin API endpoint** `GET /api/admin/feedback` with pagination,
search, test-data filtering, and average ratings

## Context

User feedback was stored in Firestore (`user_feedback` collection) but
completely invisible to the admin — the admin panel only showed a
boolean "Feedback Submitted: Yes/No" badge per user. This PR closes that
gap.

## Changes

**Backend:**
- `GET /api/admin/feedback` endpoint with pagination, search,
`exclude_test` filter, aggregate rating averages
- `send_feedback_notification()` method on `EmailService` — sends HTML
email with star ratings, all text fields, link to admin page
- Wired into `submit_user_feedback` as fire-and-forget (won't block user
response)

**Frontend:**
- New admin page with aggregate stat cards, searchable/paginated table,
visual star ratings, expandable rows for text detail
- "Feedback" sidebar nav item with MessageSquare icon
- `adminApi.listFeedback()` client method + TypeScript types

**Tests:** 14 tests covering endpoint (pagination, search, filtering,
aggregates, empty state, datetime edge cases), email (content, subject,
custom admin, failure), and caller-callee contract integration

## Test plan

- [x] `make test` — 712 tests pass (39 suites)
- [x] 14 new tests in `test_admin_feedback.py`
- [ ] Manual: verify admin page renders at `/admin/feedback` after
deploy
- [ ] Manual: submit feedback → verify email arrives at
admin@nomadkaraoke.com

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 16:18:32 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 17265a6f28 fix: runner manager idle check misses python-audio-separator jobs (#579)
## Summary

- The `check_github_for_pending_jobs` function in the runner manager
Cloud Function only checked `karaoke-gen` for active workflow runs
- When `python-audio-separator` had queued GPU integration tests, the
idle checker saw no pending jobs and stopped the GPU runners prematurely
- Now checks both `karaoke-gen` and `python-audio-separator` repos

Already deployed via `pulumi up` (infra change — deploy first, merge
second).

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 15:57:30 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 5e7ede1cfe feat: show audio-separator version in footer (#580)
## Summary

- Adds audio-separator package version to the version footer display
- Shows as `● Separator: v0.43.1` alongside existing Encoder and
Flacfetch versions
- Uses locally installed package version (`importlib.metadata`) — does
NOT call the remote Cloud Run GPU service, avoiding unnecessary
cold-starts (~$0.07 per wake)

## Test plan

- [x] All 712 tests pass (`make test`)
- [ ] After deploy: verify footer shows separator version on
gen.nomadkaraoke.com

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 19:47:34 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 7294db2f6d fix: ASS subtitle preview/render divergence — embedded newlines drop lyrics (#578)
## Summary

- **Bug:** Lyrics that rendered correctly in preview videos were missing
words in final (with_vocals/final) video output. Discovered on job
`0d4b550c` (The Ataris - All Souls Day).
- **Root cause:** Word objects from the transcription pipeline contain
embedded newline characters (e.g., `"spell\n"`) at segment boundaries.
These corrupt ASS subtitle dialogue events by splitting them across file
lines, causing the video renderer to silently drop words after the
newline.
- **Why preview worked but final didn't:** Two divergent
CorrectionResult construction paths — preview used
`update_correction_result_with_data()` which `.strip()`s word text,
while the render worker used manual dict merge + `Word.from_dict()`
which did not strip.

## Changes

- **`Word.__post_init__`** strips whitespace/newlines from text — single
source of truth for Word invariants
- **Defensive strip in `_create_ass_text()`** — belt-and-suspenders
safety net at the ASS output boundary
- **Render worker refactored** to use the same
`CorrectionOperations.update_correction_result_with_data()` method as
preview generation (DRY, eliminates divergence)
- **Removed redundant `.strip()`** from
`update_correction_result_with_data()` Word text (now handled by
`__post_init__`)
- **Documented lesson** in `docs/LESSONS-LEARNED.md`: "Data Types Must
Enforce Their Own Invariants"
- **8 unit tests** covering Word stripping and ASS output sanitization

## Testing

- [x] 1126 unit tests pass, 0 failures
- [x] Sanity check with real bug data from job `0d4b550c` confirms fix
- [x] CodeRabbit CLI review completed, feedback addressed

## Review

- [x] Local CodeRabbit review completed
- [x] Review feedback addressed (test improved to bypass `__post_init__`
and exercise defensive strip independently)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-22 23:20:12 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 83c75a9d98 Cutover: audio separation Modal → Cloud Run GPU (#577)
@coderabbitai ignore

## Summary
- Switch `AUDIO_SEPARATOR_API_URL` from Modal to Cloud Run GPU service
- Bump `audio-separator` dependency to >=0.43.0 (preset + CLI support)

The Cloud Run GPU service has been tested and verified:
- Health check: healthy, models ready
- Both ensemble presets (instrumental_clean, karaoke) verified
- Full 2-stage separation tested with real audio files

**Note:** Pulumi apply was done locally. The Cloud Run Job env var is
already live.

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 02:53:46 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 38b966f30c Modal → GCP audio separation migration (#571)
@coderabbitai ignore

## Summary
- Comprehensive migration plan: Modal → Cloud Run GPU (L4) for audio
separation
- Replaces old stub plan with full implementation details
- **Architecture**: Cloud Run GPU service (scale-to-zero, ~$0.13/job)
- **Model upgrade**: Ensemble presets as default (instrumental_clean +
karaoke) for +35% quality
- **Pipeline optimization**: Decouple separation from lyrics review
critical path
- Implementation will be added to this PR

## Plan highlights
- Phase 1: Cloud Run GPU server (python-audio-separator repo)
- Phase 2: GCP infrastructure via Pulumi (this repo)
- Phase 3: Pipeline decoupling + preset-based model config
- Phase 4: Cutover, monitor, decommission Modal

See `docs/archive/2026-03-22-modal-to-gcp-migration-plan.md` for full
details.

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-22 22:20:55 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 3391e5c9f5 Fix missing pip in GPU runner Python toolcache (#576)
## Summary

- Python 3.13 on GPU runners was built with `--with-ensurepip=install`
but `pip` wasn't actually in site-packages
- `setup-python@v5` requires a working `pip` module — CI failed with `No
module named pip`
- Added explicit `ensurepip --upgrade` bootstrap after `make install`
- Manually fixed all 3 runners (cleared toolcache + bootstrapped pip)

Follows #573, #574, #575 in the GPU runner fix series.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-22 20:21:29 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 b0575ba62c Fix Poetry permissions on GPU runners (#575)
## Summary

- Follow-up to #574. GPU runners' CI jobs failed with `EACCES:
permission denied, stat '/usr/local/bin/poetry'` because Poetry was
installed under `/root/.local/` (mode 700)
- The `runner` user can't follow symlinks into root's home directory
- Fix: install Poetry to `/opt/poetry` (shared location) using
`POETRY_HOME` env var

## What happened

1. Startup script runs `curl | python3 -` as root → Poetry installed to
`/root/.local/share/pypoetry/`
2. Symlink created: `/usr/local/bin/poetry` → `/root/.local/bin/poetry`
3. Poetry binary's shebang:
`#!/root/.local/share/pypoetry/venv/bin/python`
4. `runner` user can't access anything under `/root/` (mode 700)
5. `setup-python@v5` cache step tries to stat Poetry → EACCES → job
cancellation

## Test plan

- [x] Manually fixed permissions on all 3 running runners (temporary)
- [x] Applied via `pulumi up` — runners recreated with new startup
script
- [ ] Runners will re-register with GitHub after full startup (~15-20
min)
- [ ] Re-run audio-separator CI to confirm

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-22 20:10:24 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 8baa7d7db2 Fix GPU startup: upgrade kernel when headers unavailable (#574)
## Summary

- Follow-up to #573. The previous fix handled kernel mismatches on
**existing** VMs but failed on **fresh** VMs created from the
`debian-cloud/debian-12` base image
- The base image ships kernel `6.1.0-43` but Debian repos have moved to
`6.1.0-44`, so `apt-get install linux-headers-6.1.0-43-cloud-amd64`
fails with "Unable to locate package"
- The startup script now detects this and upgrades the kernel + reboots
once before proceeding

## What changed

Added kernel upgrade + reboot logic to `github_runner_gpu.sh`:

1. Check if headers are available for the running kernel via `apt-cache
show`
2. If not: install `linux-image-cloud-amd64` +
`linux-headers-cloud-amd64` (meta-packages tracking latest), set a
reboot flag, and reboot
3. After reboot: running kernel matches available headers, flag is
cleaned up, script continues normally with DKMS build + NVIDIA driver
install

The reboot flag (`/var/lib/gpu-runner-kernel-upgraded`) prevents
infinite reboot loops — if headers are still unavailable after one
upgrade attempt, the script gives up with diagnostics.

## Test plan

- [x] Applied new startup script to all 3 GPU runners via `pulumi up
--target`
- [x] Verified runner 1: kernel upgraded from `6.1.0-43` → `6.1.0-44`,
reboot happened, nvidia-smi shows `595.45.04, Tesla T4, 15360 MiB`
- [x] Verified runner 2: same result
- [ ] Waiting for all 3 runners to complete full startup and register
online with GitHub

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-22 16:52:25 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 067a66fc26 Fix GPU runner NVIDIA driver failure on kernel updates (#573)
## Summary

- GPU runners (github-gpu-runner-1/2/3) failed with `nvidia-smi` errors
because Debian auto-updated the kernel but the NVIDIA kernel module
wasn't rebuilt for the new version
- The startup script's idempotency check (`command -v nvidia-smi`) was
checking for the *binary*, not the *loaded kernel module*, so it
silently skipped driver setup on restarts
- Fixed the startup script to always ensure kernel headers match the
running kernel, rebuild DKMS modules when the nvidia module isn't
loaded, and clean up stale headers

## What happened

1. Debian updated kernel from `6.1.0-43` → `6.1.0-44-cloud-amd64`
2. NVIDIA kernel module was built for `-43` only
3. On next VM start, `nvidia-smi` binary existed (passes `command -v`)
so driver install was skipped
4. But the kernel module couldn't load (built for wrong kernel) →
`nvidia-smi` failed at runtime
5. All 3 GPU integration test jobs failed on PR #273
(python-audio-separator)

## Fix

**Immediate** (already applied to all 3 runners via SSH):
- Installed `linux-headers-6.1.0-44-cloud-amd64`, ran `dkms
autoinstall`, `modprobe nvidia`
- Re-ran CI run 23408072295 → all 4 jobs passed

**Permanent** (this PR — startup script changes):
- Always install kernel headers for `$(uname -r)` on every boot
- Install `dkms` alongside headers (not just as fallback)
- Check `lsmod | grep nvidia` to detect unloaded module → rebuild via
DKMS
- Clean up stale kernel headers for old kernels (prevents disk bloat)
- Add diagnostic output on failure (dkms status, module listing)
- Reduce retry from 30×10s to 10×5s (DKMS rebuild is deterministic)

## Test plan

- [x] Manually fixed all 3 GPU runners and verified `nvidia-smi` works
- [x] Re-ran failing CI (run 23408072295) — all jobs passed
- [ ] After merge + Pulumi deploy, stop/start a GPU runner to verify the
new startup script works end-to-end

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-22 15:10:13 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 d1a877c8f4 Disable GDrive validator success notifications (#572)
## Summary
- Set `NOTIFY_ON_SUCCESS` to `false` for the GDrive validator Cloud
Function
- Stops "Karaoke GDrive: All Clear" emails and Pushbullet notifications
on successful daily validation
- Error/issue notifications remain active and unaffected

Already deployed via `pulumi up`.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-22 14:23:44 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 be4acbe915 IP geolocation enrichment for admin UI (#570)
Enrich all admin IP displays with country flag + ISP inline, hover
popover for full details. Backend caches via ip-api.com in Firestore.

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-22 03:05:18 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 fef5130519 Add stats action to divebar-lookup Cloud Function (#568)
## Summary
- New `stats` action on the divebar-lookup Cloud Function
- Returns catalog, GCS mirror, format breakdown, cross-reference, and KN
data stats
- Used by KJ Controller's new status panel

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 22:14:43 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 25aa2ef8ef Fix three production job failure modes with robust error handling (#565)
@coderabbitai ignore

## Summary

Fixes three distinct production job failures identified from
investigating jobs 503a4ad3, 7be8d1e5, and 1868f323:

- **0-segment lyrics guard**: Block review submission when transcription
produces no lyrics (e.g. karaoke input with no vocals). Backend
validation + frontend warning with guidance. CDG orchestrator gracefully
skips when LRC has no content.
- **Audio processor stage 2 validation**: Validate backing vocals
separation produced all expected stems (mirrors existing stage 1
validation). Defensive null checks prevent confusing NoneType crashes.
Full tracebacks in error logs.
- **AudioShake retry with exponential backoff**: 5 attempts via
tenacity, ~40 min spread (60s base, 3x multiplier), retries on
5xx/429/connection errors. Applied to all HTTP call points. Fixed file
handle exhaustion bug on upload retry.

Also includes:
- Troubleshooting runbooks for all 3 failure modes
- Lessons learned entry on pipeline robustness patterns
- Seed planning doc for Modal-to-GCP audio separation migration
- Version bump to 0.147.0

## Test plan

- [x] 2696 backend tests passing (54 new/modified)
- [x] 712 frontend tests passing (5 new for ReviewChangesModal)
- [x] HTTP endpoint test verifies 400 response for 0-segment review
submission
- [x] AudioShake retry tests verify 502 retry, 400 no-retry, connection
error retry
- [x] Audio processor tests verify stage 2 validation, null safety,
combined instrumentals
- [x] CDG orchestrator tests verify graceful skip on empty LRC, fail on
valid LRC errors
- [x] LRC timestamp regex tests for millisecond, centisecond, and
no-decimal formats

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 17:58:31 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 de02570514 fix: real client IPs + user detail identity info (#567)
## Summary

Two fixes:

1. **Real client IPs** — All stored IPs were `169.254.169.126` (Cloud
Run LB). Now uses `X-Forwarded-For` header via shared `get_client_ip()`
helper. Fixed in magic link, verify, and job creation endpoints.
Backfill endpoint updated to clear bad IPs and re-fetch.

2. **User detail identity info** — Admin user detail page now shows:
- Identity & Security card: signup IP, device fingerprint, welcome
credits status
   - Active sessions: IP, user agent, fingerprint, last activity
   - Total spent and feedback status

After deploy, re-run backfill to fix the bad IPs:
```bash
curl -X POST .../api/admin/abuse/backfill-ips -H "Authorization: Bearer $TOKEN"
```

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 21:48:14 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 51b2a170f0 Switch Divebar downloads from Google Drive to GCS mirror (#566)
## Summary
- divebar-lookup Cloud Function now returns public GCS URLs for synced
files
- Falls back to Drive URLs for files not yet in GCS mirror
- Search results include `in_gcs` boolean field
- GCS bucket set to public read (same access as source Drive folder)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 21:27:36 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 2f10d5b54e fix: backfill-ips missing index (#564)
Remove order_by from backfill query — sessions(user_email, created_at)
index doesn't exist.

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 21:08:07 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 ede4538276 Admin abuse UI: sortable columns + IP backfill (#562)
Sortable table columns + backfill endpoint for existing user IPs.

After deploy, run: `curl -X POST .../api/admin/abuse/backfill-ips -H
"Authorization: Bearer $TOKEN"`

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 20:40:21 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 9683f198fd Add GCS file mirror for Divebar karaoke collection (~779 GB) (#560)
## Summary
- GCS bucket `nomadkaraoke-divebar-files` for mirroring all actual
karaoke files from the Divebar Google Drive
- ~48,533 files, ~779 GB total (MP4s: 570 GB, ZIPs: 123 GB, CDG+MP3: 33
GB, etc.)
- Sync script reads BigQuery index, downloads from Drive API, uploads to
GCS
- Tracks progress via `gcs_path` column (incremental — only downloads
new/unsynced files)
- Estimated storage cost: ~$16/month (Standard), can lifecycle to
Nearline later

## Test plan
- [x] Pulumi deployed: bucket + IAM + BigQuery schema update
- [ ] Initial bulk sync via `python divebar_file_sync.py --workers 4`
(run from Cloud Shell or GCE VM)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 20:18:47 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 a90017889a Update ARCHITECTURE.md with data pipeline Cloud Functions (#557)
## Summary
- Document 3 new data pipeline Cloud Functions (divebar-mirror,
kn-data-sync, divebar-lookup)
- Add infrastructure details (service accounts, GCS buckets, BigQuery
tables, secrets)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 20:03:22 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 0e721a15f1 Fix Firestore index Pulumi errors: remove stale import declarations (#556)
## Summary
- Remove stale `import_=` declarations from 3 Firestore indexes that
were already imported
- These caused "previously-imported resources may not be replaced"
errors blocking all Pulumi deploys
- Re-imported all 13 indexes into Pulumi state with current GCP values
- Pulumi now shows 186 resources, zero pending changes, zero errors

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 18:36:31 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 a05cc7ce6c Admin UI: Abuse Investigation panel (#555)
## Summary

New admin panel at `/admin/abuse` for investigating potential
free-credit abuse patterns.

## Features

### Suspicious Accounts tab
- Table of accounts with many jobs but no spend (configurable
thresholds)
- Shows: email, jobs, credits, spend, feedback, signup IP, fingerprint,
created date
- Click any row to drill into related accounts

### Lookup tab
- Search by email, IP address, or device fingerprint
- Email search opens the related accounts view
- IP/fingerprint search returns a table of all matching users

### Related Accounts view
- Target user details (IP, fingerprint, credits, jobs, spend)
- Linked accounts grouped by shared IP and shared fingerprint
- Clickable drill-down to investigate any related account
- Link to full user profile page

## Changes
- `frontend/app/admin/abuse/page.tsx` (new) — full page with 3 views
- `frontend/components/admin/admin-sidebar.tsx` — Fingerprint icon + nav
entry
- `frontend/app/admin/layout.tsx` — breadcrumb support
- `frontend/lib/api.ts` — 4 adminApi methods + TypeScript types

## Testing
- [x] Frontend build passes
- [x] All tests pass (707 frontend + all backend)
- [x] No backend changes (uses endpoints from PR #553)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 14:01:01 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 e1edc64a31 Divebar Drive mirror, KN pipeline migration, and cross-reference index (#554)
## Summary
- **Phase 1**: Cloud Function `divebar-mirror` — recursively indexes 84
brand folders in Divebar Google Drive into BigQuery `divebar_catalog`
table. Daily at 2 AM ET.
- **Phase 2**: Cloud Function `kn-data-sync` — replaces legacy
`projectbread-karaokay` pipeline. Fetches full KN catalog (281K songs) +
community tracks (58K with YouTube URLs). Stores to GCS + refreshes
BigQuery. KN API key in Secret Manager.
- **Phase 3**: Cloud Function `divebar-lookup` — public API for search,
KN ID lookup, and cross-reference rebuild. Links KN songs to Divebar
files via artist+title matching.

All three are Pulumi-managed with dedicated service accounts, Cloud
Scheduler triggers, and minimal IAM permissions.

## Infrastructure deployed
- 3 Cloud Functions (Gen2, Python 3.12)
- 3 Service accounts with least-privilege IAM
- 4 GCS buckets (3 source + 1 data)
- 3 BigQuery tables (`divebar_catalog`, `karaokenerds_community`,
`kn_divebar_xref`)
- 5 Cloud Scheduler jobs
- 1 Secret Manager secret (`karaokenerds-api-key`)

## Test plan
- [x] KN full catalog sync: 281,007 songs loaded in 60s
- [x] KN community sync: 58,825 tracks loaded in 17s
- [x] Divebar mirror: deployed, running initial sync (cycle detection
fix applied)
- [ ] Cross-reference rebuild after mirror completes
- [ ] KJ Controller search integration (in kjbox PR)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 16:15:52 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 2d47fa7ab3 Anti-abuse: queryability improvements + investigation endpoints (#553)
## Summary

Follow-up to #552. Makes anti-abuse data queryable for investigation and
adds ongoing tracking beyond signup.

- **Firestore composite indexes** for `signup_ip` and
`device_fingerprint` on `gen_users`
- **Session fingerprint tracking** — device fingerprint propagated from
magic link to session
- **Job creation IP** — client IP stored on every job for cross-account
correlation
- **Admin investigation endpoints** — find related accounts, suspicious
users, lookup by IP/fingerprint

## Changes

### Infrastructure
- 2 new Firestore composite indexes: `gen_users(signup_ip, created_at)`
and `gen_users(device_fingerprint, created_at)`

### Backend
- `Session` model: added `device_fingerprint` field
- `create_session()`: accepts and stores `device_fingerprint`
- Verify endpoint: passes magic link's fingerprint to session
- `Job` model: added `creation_ip` field  
- Both job creation endpoints: store client IP on job document
- New `UserService` methods: `find_users_by_signup_ip()`,
`find_users_by_fingerprint()`, `find_suspicious_accounts()`,
`find_related_accounts()`
- New admin endpoints:
- `GET /api/admin/abuse/related/{email}` — find linked accounts by
shared IP/fingerprint
- `GET /api/admin/abuse/suspicious?min_jobs=2&max_spend=0` — free-credit
abusers
  - `GET /api/admin/abuse/by-ip/{ip}` — all users from an IP
- `GET /api/admin/abuse/by-fingerprint/{fp}` — all users with a
fingerprint

### Tests
- 15 new tests in `test_anti_abuse_investigation.py`
- Full suite passes (707 frontend + all backend)

## Testing
- [x] Unit tests pass
- [x] Integration tests pass
- [x] `make test` passes

## Review
- [x] Local review completed

**Note:** Infrastructure changes (Firestore indexes) deploy
automatically on merge. Run `pulumi up` locally first per CLAUDE.md
guidelines.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 16:07:14 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 376008fc8f Anti-abuse: credits on verification, IP + fingerprint rate limiting (#552)
## Summary

Three-layer defense against free credit abuse (disposable email bypass):

- **Credits on verification**: Welcome credits granted on first magic
link verification, not account creation. Unverified accounts get 0
credits.
- **Per-IP rate limiting**: Max 2 new accounts per IP per 24 hours.
Silent reject (anti-enumeration).
- **Device fingerprinting**: FingerprintJS (open source) sends browser
fingerprint with magic link request. Combined with IP — either signal
hitting 2/day triggers block. Graceful degradation if fingerprinting
fails.

## Changes

### Backend
- `get_or_create_user()` creates users with 0 credits, stores
`signup_ip` and `device_fingerprint`
- New `grant_welcome_credits_if_eligible()` with
`welcome_credits_granted` flag for idempotency
- Verify endpoint grants credits and returns `credits_granted` in
response
- `count_recent_signups_from_ip()` and
`count_recent_signups_from_fingerprint()` query Firestore
- `is_signup_rate_limited()` combines IP + fingerprint signals
- `send_magic_link` endpoint checks rate limit before creating magic
link (new users only)
- New fields: `User.signup_ip`, `User.device_fingerprint`,
`User.welcome_credits_granted`, `MagicLinkToken.device_fingerprint`,
`SendMagicLinkRequest.device_fingerprint`,
`VerifyMagicLinkResponse.credits_granted`

### Frontend
- New `fingerprint.ts` lib (lazy-loaded FingerprintJS)
- `sendMagicLink` sends `device_fingerprint` with request
- Verify page shows "You received N free credits to get started!" on
first login
- `VerifyMagicLinkResponse` type updated with `credits_granted`

### Tests
- 33 unit + integration tests in `test_anti_abuse.py`
- Covers: credit granting, idempotency, rate limiting (IP +
fingerprint), error paths, caller-callee contracts, model fields,
endpoint integration

## Testing
- [x] All backend tests pass (33 new + existing)
- [x] All frontend tests pass (707 tests)
- [x] `make test` passes

## Review
- [x] CodeRabbit CLI review completed locally
- [x] Review feedback addressed (added `welcome_credits_granted` flag
for idempotency)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 01:51:44 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 4e7439e80e feat: tiered disposable email detection via external APIs (#550)
## Summary

- Add tiered disposable email checking: static blocklist → DeBounce API
(free) → verifymail.io API (paid) — catches domains the static list
misses
- Auto-learn: flagged domains persist to Firestore `manual_domains`, so
each domain only needs one API call ever
- Clean domain cache: verified-clean domains skip API calls for 7 days
- Well-known providers (gmail, yahoo, etc.) skip all checks instantly
- Graceful degradation: if external APIs are down, static blocklist
still works

Investigation of 60 recent signups found 10 disposable accounts — the
static list only caught 6, external APIs caught the remaining 4
(including niche `.io.vn` vanity domains and `nghienplus.store`).

## Test plan

- [x] 52 unit tests pass (18 new tests for external API checking)
- [x] All 707 frontend tests pass
- [x] Integration tests verify magic link 422 rejection flow
- [x] `make test` passes clean
- [ ] After deploy: create GCP secret `verifymail-api-key`, then attempt
signup with known-disposable domain not in static list (e.g.,
`test@lxbeta.com`)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 00:04:26 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 a9db298b22 fix: review session cross-job search returns empty (#551)
@coderabbitai ignore

## Summary

- **Fixed missing Firestore collection group index** — the
`review_sessions` subcollection needed a single-field index exemption
with `COLLECTION_GROUP` scope on `updated_at` for the cross-job search
to work. Without it, every `collection_group("review_sessions")` query
silently failed with a 400 error, caught by the try/except and returned
as `[]`.
- **Fixed over-fetch before filter bug** — even with the index, the
search was applying `.limit(20)` at the Firestore level before filtering
by text in Python. Sessions not in the 20 most recent across all jobs
would never match a text search. Now over-fetches (up to 500) when a
query is provided, filters in Python, then trims to the requested limit.
- **Documented the index creation command** in the IaC module since
Pulumi doesn't support single-field index exemptions natively.

## Root cause

The `search_review_sessions` endpoint uses a Firestore collection group
query (`db.collection_group("review_sessions")`) which requires an index
with `COLLECTION_GROUP` query scope. This index was never created, so
every cross-job search silently returned empty results.

## Test plan

- [x] Verified the Firestore index was created and is READY
- [x] Tested `GET /api/review/sessions/search?q=&limit=5` returns
sessions (was empty before)
- [x] Tested `GET /api/review/sessions/search?q=d1695003&limit=5`
returns matching sessions
- [x] All 707 tests pass (`make test`)

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-20 23:54:53 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 124036716a fix: show Edit Audio button for in_audio_edit status (#549)
## Summary
- The "Edit Audio" button on job cards was only shown for
`awaiting_audio_edit` status, but not `in_audio_edit`
- Users who navigated away from the audio editor had no button to return
to it from the job card
- Added `in_audio_edit` to both the interactive status check and the
button render condition

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-20 23:07:31 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 fe7fdc8ed5 fix: map with_vocals_mp4 in GCE encoding output (#548)
## Summary

- **Fix GCE encoding backend** dropping the `(With Vocals).mp4` file
from output results — the list-to-dict mapper didn't recognize the "with
vocals" filename pattern, so `finals/with_vocals_mp4` was never set in
Firestore
- **Set `with_vocals_mp4_path`** in the `EncodingOutput` returned by
`GCEEncodingBackend.encode()` so the orchestrator can thread it through
to upload
- **Fix local encoding edge case** where input already being MP4 caused
the with-vocals output to be silently skipped instead of copied

PR #535 threaded `with_vocals_mp4` through the pipeline but missed these
two spots in the GCE backend path, which is what production uses.

## Test plan

- [x] 27 encoding interface tests pass (including new regression test)
- [x] 38 local encoding service tests pass
- [x] Full backend suite: 2323+ tests pass
- [x] Full frontend suite: 707 tests pass (38 suites)
- [x] CodeRabbit: no findings
- [x] Manual: fixed job `fa1e2eab` in Firestore — download now serves
39.6 MB MP4 instead of 120.4 MB MKV

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-20 17:23:03 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 05cb7a9bec feat: auto-sync disposable email blocklist from community repo (#546)
## Summary

- Add daily auto-sync of disposable email domains from the
[disposable-email-domains](https://github.com/disposable-email-domains/disposable-email-domains)
community repo (~4,800 domains vs previous 160 hardcoded)
- Restructure Firestore blocklist into three layers: external
(auto-synced), manual (admin-added), allowlisted (admin overrides)
- Admin UI updated with separate sections for each domain source + "Sync
Now" button

## Changes

### Backend
- New `disposable_domain_sync_service.py` — fetch, parse, and sync
external blocklist with migration support
- Updated `email_validation_service.py` — effective set = (external +
manual) - allowlisted, new allowlist CRUD, backward-compatible
`get_blocklist_config()`
- New API endpoints: `POST /blocklists/sync`, `POST/DELETE
/blocklists/allowlisted-domains`, `POST
/internal/sync-disposable-domains`
- Updated `GET /blocklists` response with `external_domains`,
`manual_domains`, `allowlisted_domains`, `last_sync_at`,
`last_sync_count`

### Frontend
- Admin rate-limits page: three sub-sections (external/manual/allowlist)
with sync status bar
- Updated API client types and methods

### Infrastructure
- Cloud Scheduler job for daily sync at 3:00 AM UTC (Pulumi)

### Migration
- First sync automatically migrates from old `disposable_domains` field
- Hardcoded `DEFAULT_DISPOSABLE_DOMAINS` replaced with empty set
(external sync takes over)

## Testing
- 47 new/updated tests across 3 test files (54 total for email
validation + sync)
- 2584 tests pass in full suite
- CodeRabbit CLI: no findings

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 18:45:51 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 4cdb9884df fix: stale review processor uses list_jobs (not get_jobs) (#547)
## Summary

- Fix `get_jobs` → `list_jobs` — the correct method name on
`FirestoreService`
- Production logs showed: `'FirestoreService' object has no attribute
'get_jobs'`

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 21:24:15 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 6b17a1c748 feat: review reminder emails and auto-expiry for stale jobs (#544)
## Summary

- Hourly cron detects jobs stuck in review (`awaiting_review` /
`in_review`) and takes action
- **24h**: sends gentle reminder email with review link, help offer, and
expiry warning
- **48h**: auto-cancels job, refunds credit, sends expiry notification
with balance

## Changes

- **New:** `backend/workers/stale_review_processor.py` — core processor
logic
- **New:** `EmailService.send_review_reminder()` and
`send_review_expired()` email methods
- **New:** `POST /api/internal/process-stale-reviews` endpoint (Cloud
Scheduler target)
- **New:** Cloud Scheduler job `stale-review-hourly` (hourly, Pulumi)
- **New:** 24 unit tests (14 processor + 10 email)
- **Fix:** `make test` no longer hangs on frontend Playwright E2E tests
- Excludes made-for-you and tenant jobs
- Uses separate `expiry_reminder_sent` flag (independent of existing
idle reminder)
- Version bump: 0.142.4 → 0.143.0

## Testing

- [x] 24 new unit tests, all passing
- [x] Full backend test suite: 2578 passed
- [x] Full frontend unit tests: 704 passed
- [x] `make test` completes without hanging

## Review

- [x] Local CodeRabbit review completed (5 findings, 4 fixed, 1
correctly skipped)
- [x] Spec review completed (critical `reminder_sent` flag collision
caught and fixed)

## Design

See `docs/archive/2026-03-19-review-reminder-autoexpiry.plan.md` for
full spec.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 16:15:01 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 f582236d18 fix: prevent flaky "docker not found" in CI emulator tests (#543)
## Summary

- Fix race condition where GHA runner systemd service auto-starts on VM
boot and accepts CI jobs before Docker is available
- Add defense-in-depth Docker readiness check in the emulator test
workflow

## Changes

- **`infrastructure/compute/startup_scripts/github_runner.sh`** — Stop
the runner service at the very top of the startup script, before any
package installations, preventing premature job acceptance
- **`.github/workflows/ci.yml`** — Add a "Wait for Docker to be
available" step with 60s retry loop in `backend-emulator-tests` job
- **`docs/SELF-HOSTED-RUNNERS.md`** — Document Bug 8 in the Historical
Bugs section

## Root Cause

When runner VMs are stopped/started by the runner_manager, the GHA
runner systemd service (from `svc.sh install` on a previous boot)
auto-starts immediately on boot. The GCE startup script runs
concurrently but only stops/re-registers the runner service after
installing Docker and other dependencies. During this window, the runner
can accept jobs that fail because Docker isn't ready yet.

## Testing

- [x] Infrastructure-only change — no unit tests applicable
- [x] Verified startup script logic is correct (subshell for cd,
idempotent)
- [x] CI workflow change adds graceful retry, not a breaking change

## Review

- [x] Local CodeRabbit review completed (no findings)
- [x] Documentation updated

## Note

The startup script change will trigger Pulumi to detect a metadata
change on runner VMs. Run `pulumi up` locally before merging per project
convention.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 15:29:58 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 b8239dc691 Block disposable email registration with friendly messaging (#542)
## Summary

- Wire existing `EmailValidationService` into the magic link signup flow
to reject disposable email domains (yopmail, tempmail, emailhook.site,
etc.) before creating users
- Return 422 with machine-readable `disposable_email_not_allowed` error
code for disposable domains
- Silent rejection for explicitly blocked emails/IPs (anti-enumeration)
- Frontend shows a warm amber message box encouraging real email use,
promising no spam
- Add `emailhook.site` to default disposable domains list (160+ domains
total)

## Context

Users were signing up with disposable emails like `anything@yopmail.com`
to get unlimited free welcome credits (2 per account). The
`EmailValidationService` existed with a comprehensive blocklist but was
never called during signup. This PR wires it in.

The admin UI for managing the blocklist already exists at
`/admin/rate-limits/` (Blocklists tab) with full CRUD for domains,
emails, and IPs.

## Test plan

- [x] 8 new backend integration tests (disposable rejection, blocked
email/IP, email lowercasing, domain list)
- [x] 2 new frontend tests (friendly message rendering, generic error
fallback)
- [x] All 2562 backend tests pass
- [x] All 16 frontend auth component tests pass
- [x] CodeRabbit review: no findings

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 14:33:41 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 d0efa9722f infra: only start GPU runners for gpu-labeled jobs (#541)
## Summary
- GPU runners (3x n1-standard-4 + T4, ~$1.62/hr combined) were starting
on every CI trigger despite no workflow using the `gpu` label
- Now the runner manager checks job labels and only wakes GPU runners
when `gpu` is in the label set
- Also includes the int→float fix for `IDLE_TIMEOUT_HOURS` and 15min
idle timeout from #540

## Changes
- `start_runners(include_gpu=False)` — new parameter, skips GPU runners
by default
- `GPU_RUNNER_NAMES` env var tells the function which runners are GPU
- Webhook handler passes `include_gpu="gpu" in labels`
- 2 new tests for GPU filtering (26 total, all passing)
- Pulumi wires GPU runner names as separate env var

## Test plan
- [x] 26 unit tests passing
- [x] Pulumi applied locally — function deployed with GPU_RUNNER_NAMES
env var
- [x] Function responding correctly (verified via curl)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 09:26:10 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 951c1d543e infra: reduce runner idle timeout to 15min, fix int->float parsing (#540)
## Summary
- Reduce idle timeout from 1h to 15min (0.25h) — solo dev project, no
need for long idle periods
- Fix `int()` -> `float()` for `IDLE_TIMEOUT_HOURS` env var parsing
(crashed on "0.25")

## Test plan
- [x] Pulumi applied locally, function deployed via gcloud
- [x] All 7 runners successfully stopped (verified TERMINATED status)
- [x] Logs confirm: creationTimestamp fallback, parallel stops, all
runners managed

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 09:06:28 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 3af68a5047 fix: runner manager idle shutdown bugs preventing scale-to-zero (#539)
## Summary
- Fixed 6 bugs in the runner manager Cloud Function that prevented idle
shutdown, causing all 7 runner VMs to run 24/7 (~$1,600/mo wasted GCP
credits)
- Added IAM permission (`iam.serviceAccountUser`) so the runner manager
can set metadata on runner VMs
- All fixes learned from the Aquarius project's identical journey
(documented in docs/SELF-HOSTED-RUNNERS.md)

## Changes
- **infrastructure/functions/runner_manager/main.py** — Complete rewrite
applying all Aquarius Phase 4 fixes: await metadata ops,
creationTimestamp fallback, parallel stops, STOPPING state handling,
per-runner metadata updates
- **infrastructure/modules/runner_manager.py** — Added
`iam.serviceAccountUser` IAM binding
- **infrastructure/__main__.py** — Pass runner SA to runner manager for
IAM binding
- **docs/SELF-HOSTED-RUNNERS.md** — Comprehensive doc (architecture,
cost model, bug history, troubleshooting)
- **docs/LESSONS-LEARNED.md** — 3 new infrastructure lessons
- **docs/GCP-COST-OPTIMIZATION.md** — Corrected status and cost
estimates

## Test plan
- [x] 24 unit tests covering all 6 bug fixes (all passing)
- [x] `pulumi up` applied locally — IAM binding created, function source
updated
- [x] Function deployed and processing webhooks (verified via logs)
- [ ] Monitor Cloud Function logs over next hour to confirm idle
shutdown triggers
- [ ] Verify all runners reach TERMINATED state after 1h idle

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 08:32:37 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 c443f99517 infra: 3x on-demand GPU runners + startup reliability (#538)
## Summary

- Scale GPU runners from 1 to 3 for parallel CI jobs
- Switch from spot to on-demand (spot kept getting preempted during
15-min startup)
- Fix startup script: build Python 3.13 from source (pyenv broken on
Debian 12 + CUDA), DEBIAN_FRONTEND=noninteractive, deferred runner
start, nvidia-smi retry

All 3 runners verified online with clean startup — no manual hacks.

Infrastructure already applied via `pulumi up`.

## Test plan

- [x] All 3 runners booted from clean startup script
- [x] GPU, Python 3.13, tool cache, 45 model files verified on each
- [x] Integration tests passed on GPU runner (PR #265)

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-16 21:04:33 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 33eaaec4c0 fix: guard Python tool cache in GPU runner startup (#537)
## Summary

Fix broken Python tool cache on GPU runner that caused `setup-python` to
find an empty cache and fail with `python: command not found`.

The pyenv Python 3.13 compilation was failing silently, but the
`.complete` marker was still being created, tricking `setup-python` into
thinking Python was cached.

Now checks that pyenv actually produced a binary before populating the
tool cache, and cleans up the empty dir if it didn't.

## Test plan

- [x] Verified on running GPU runner via SSH that broken cache was
cleaned
- [x] All workflow steps verified manually: GPU, pipx, poetry, system
deps, model cache, `poetry install -E gpu`, torch CUDA=True

<!-- @coderabbitai ignore -->

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-16 19:17:20 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 0401434a07 infra: add GPU runner for audio-separator CI (#536)
## Summary

- Add `n1-standard-4` + NVIDIA T4 GPU spot VM to GitHub runner
infrastructure
- GPU startup script with CUDA 12.4 drivers, model pre-caching,
nvidia-smi verification with retry
- Runner service starts only after all caches are warm (CodeRabbit fix)
- Wired into runner_manager Cloud Function for auto-start/stop on CI
demand

## Details

Cost: ~$0.03 per CI run ($3/mo at 100 runs) — actually cheaper per-run
than current CPU runners because GPU tests finish 5× faster.

Infrastructure already applied via `pulumi up` — GPU runner is online
and verified working:
- `nvidia-smi`: Tesla T4, 15.6 GB VRAM, driver 595.45.04
- PyTorch CUDA: True, ONNX Runtime CUDAExecutionProvider enabled
- 45 model files pre-cached at `/opt/audio-separator-models`
- Runner registered with labels: `[self-hosted, Linux, X64, gcp, gpu]`

Companion PR in python-audio-separator updates the workflow to target
`[self-hosted, gpu]`.

## Test plan

- [x] `pulumi up` applied successfully (1 created, 1 updated)
- [x] GPU runner VM booted and startup script completed
- [x] nvidia-smi verified Tesla T4 accessible
- [x] audio-separator separation test ran with CUDA acceleration
- [x] Runner shows as "online" in GitHub Actions with correct labels
- [ ] Integration tests pass on GPU runner (verified after companion PR
merges)

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-16 18:06:08 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 a918c5a310 fix: serve encoded MP4 for With Vocals download (3.4x smaller) (#535)
## Summary

- **Serve the encoded MP4** (~39MB) for "With Vocals" download instead
of the raw MKV (~134MB) — 3.4x smaller, universally compatible
- **Fix .mov mislabeling** — the MKV from GCS was being saved with a
`.mov` extension in the temp dir, causing Dropbox to receive a
wrongly-named file
- **Thread `with_vocals_mp4`** through the full pipeline:
`EncodingOutput` → `OrchestratorResult` → `_upload_results()` →
Firestore `file_urls.finals.with_vocals_mp4`
- **Backward compatible** — frontend prefers `finals.with_vocals_mp4`
(MP4) but falls back to `videos.with_vocals` (MKV) for older jobs

## Test plan

- [x] 3 new OutputLinks tests: MP4 preference, MKV fallback, MP4-only
scenario (all pass)
- [x] All 20 OutputLinks tests pass
- [x] 2323 backend tests pass (1 pre-existing failure unrelated)
- [x] CodeRabbit review: 3 findings fixed (GCE download mapping, legacy
path, distribution dir extension)
- [ ] Manual: verify new job produces `finals/with_vocals_mp4` in
Firestore after encoding
- [ ] Manual: verify "With Vocals" download from dashboard serves MP4

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-16 03:31:17 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 d7c46a1567 infra: pre-download audio separator models on runner startup (#534)
## Summary
- Add audio-separator model pre-download to the GitHub runner startup
script
- Pre-downloads 8 ML models + 3 metadata files (~2GB) to
`/opt/audio-separator-models/`
- Models persist across job runs, eliminating repeated downloads during
CI

## What changed
- Added model download section to
`infrastructure/compute/startup_scripts/github_runner.sh`
- Downloads models from TRvlvr/model_repo, Facebook demucs, and
nomadkaraoke fallback repos
- Idempotent: skips files that already exist, uses fallback URLs for
404s
- Sets ownership to `runner:runner` for CI job access

## Context
Companion to nomadkaraoke/python-audio-separator#266 which updates the
integration test workflow to use this persistent path.

Models are already manually pre-loaded on all 3 current runners — this
ensures future runner recreations also have them.

## Test plan
- [x] Manually ran the download script on all 3 runners via SSH —
verified 15 files, 2.1GB each
- [ ] Integration tests in python-audio-separator#266 should pass using
these pre-cached models

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-16 00:07:52 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 c0fabf9f54 fix: NameError 'settings' in orchestrated video worker distribution warnings (#533)
## Summary
Fix `NameError: name 'settings' is not defined` in two call sites when
video generation completes with distribution warnings.

## Root Cause
Both `generate_video_orchestrated()` and `_handle_native_distribution()`
called `_send_distribution_warning_notification(settings=settings)` but
never defined `settings` in their scope. This only triggers when
`result.distribution_warnings` is truthy (partial distribution upload
failure) — a rare code path that was never tested.

## Fix
Remove `settings=settings` argument from both call sites. The function
already handles `settings=None` by calling `get_settings()` internally.

## Testing
- [x] 2555 backend tests pass
- [x] 4 new regression tests added:
- Contract test: `_send_distribution_warning_notification` works without
settings arg
- Static analysis: `generate_video_orchestrated` has no
`settings=settings` reference
- Static analysis: `_handle_native_distribution` has no
`settings=settings` reference
- Integration: `_handle_native_distribution` with distribution_warnings
doesn't crash

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-15 23:50:27 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 e9ec343598 fix: sanitize artist/title in encoding output paths for slash characters (#532)
## Summary
- Fix encoding failure when song title contains `/` characters (creates
subdirectories in output paths)

## Root Cause
The GCE encoding worker's `run_encoding()` builds output file paths
using raw `artist` and `title`, causing `/` in titles (e.g., "MEDLEY -
PORTRAIT/WALK/BORN") to be treated as directory separators. The encoding
fails at the remux step because the output directory doesn't exist.

## Fix
Sanitize `artist` and `title` with `re.sub(r'[<>:"/\\|?*]', '_', ...)`
before using them in `base_name` for output paths.

## Testing
- [x] 55 encoding tests pass
- [x] 2551 backend tests pass

## Context
Follow-up to PRs #530 and #531. Job 27054772 now passes CDG generation
(fixed in #531) but fails at encoding due to the same slash-in-title
issue in the GCE encoding worker.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-15 17:08:52 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 00a6cabc5e fix: sanitize artist/title in CDG packaging paths (#531)
## Summary
- Fix CDG generation failure when song title contains `/` characters
(e.g., "MEDLEY - PORTRAIT/WALK/BORN")

## Root Cause
The orchestrator's `_run_packaging()` built CDG output paths using raw
`artist` and `title`, causing `/` in titles to be treated as directory
separators. This resulted in `FileNotFoundError` when the CDG generator
tried to write the TOML file.

## Fix
Use `sanitize_filename()` for `base_name` in `_run_packaging()`,
matching the pattern already used in `_run_encoding()` and
`create_orchestrator_config_from_job()`.

## Testing
- [x] 2551 backend tests pass (including 57 orchestrator tests)

## Context
Follow-up to PR #530. Discovered during retry of job 27054772 which has
title "MEDLEY - PORTRAIT/WALK/BORN".

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-15 16:44:56 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 1c0eb8bf52 fix: prevent style_params.json lifecycle deletion, CDG font fallback, video worker state guard (#530)
## Summary
- Fix GCS lifecycle rule silently deleting `style_params.json` after 7
days by moving style files from `uploads/` to `jobs/` prefix
- Improve CDG font fallback chain to try bundled fonts by filename
before failing, preventing opaque `KeyError: 'font'` errors
- Add video worker state guard (matching audio/lyrics/render worker
pattern) to prevent cascading retry errors on failed jobs

## Changes
- **Style path prefix**: Changed all `uploads/{job_id}/style/`
references to `jobs/{job_id}/style/` in `theme_service.py`,
`file_upload.py`, `audio_search.py` and 7 test files
- **CDG font fallback**: Enhanced `_validate_and_setup_font()` with
5-step resolution (exact → bundled full path → bundled by filename →
arial.ttf → None), added None guard in `_create_toml_data()`,
absolutized all resolved paths
- **Video worker guard**: Added `validate_worker_can_run()` to both
orchestrated and legacy video pipelines, added terminal state check
(`failed`, `cancelled`, `complete`, `prep_complete`, `error`) to
`_check_worker_idempotency()`
- **Docs**: Added GCS lifecycle gotcha to LESSONS-LEARNED.md

## Context
Triggered by investigation of two production job failures:
- Job `2d4a7bab` (Mar 5): `style_params.json` 404 after 10 days — GCS
lifecycle rule deleted it
- Job `27054772` (Mar 14): CDG generation failed with `KeyError: 'font'`
when font couldn't be resolved, then Cloud Tasks retries produced
cascading `Invalid state transition: failed -> GENERATING_VIDEO` errors

## Testing
- [x] 2551 backend tests pass
- [x] 139 remote CLI tests pass
- [x] 10 new tests added (5 font fallback, 5 state guard/idempotency)

## Review
- [x] Local CodeRabbit review completed (3 findings, 2 fixed, 1 skipped
as nitpick)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-15 16:19:59 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 c69b129893 fix: add lyrics_dir to transcribe_lyrics() for metadata storage (#529)
## Summary

- **Bug fix**: `transcribe_lyrics()` didn't include `lyrics_dir` in its
return dict, so `_store_lyrics_processing_metadata()` could never find
`corrections.json`. AudioShake IDs and correction stats were silently
lost in production (v0.142.0) because the metadata storage is wrapped in
try/except.
- **One-line fix**: Add `"lyrics_dir": lyrics_dir` to the
`transcriber_outputs` dict in `lyrics_processor.py`
- **Docs improvement**: Added "Test the Contract Between Caller and
Callee" guidance to `TESTING.md` and `/test-review` skill to prevent
this class of bug in future

## Why testing didn't catch it

The test for `_store_lyrics_processing_metadata` hand-crafted its input:
`transcription_result={"lyrics_dir": str(lyrics_dir)}`. This tested the
function in isolation — proving it works *if given correct input* — but
never verified the actual caller (`transcribe_lyrics()`) produces that
key. The mock was "too helpful."

This is especially dangerous with non-fatal code paths: the function is
designed to never crash (try/except), so the broken input silently did
nothing, and the test still passed.

## Test plan

- [x] 3 new tests: contract test (transcribe_lyrics returns lyrics_dir),
integration test (lyrics_dir points to corrections.json location),
regression test (pre-fix behavior: only duration stored without
lyrics_dir)
- [x] All 27 processing metadata tests pass
- [x] Verify in production: new jobs should show AudioShake IDs in
`processing_metadata.transcription`

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 11:16:20 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 694a7ff04e feat: add audio source details modal to admin panel (#528)
## Summary

- **Fix source detection**: `getJobSource` now checks
`audio_source_type` field first, correctly identifying audio search jobs
even when `audio_search_artist`/`audio_search_title` are null (was
showing upload icon for RED audio search jobs)
- **Add source details modal**: Clicking the source text opens a dialog
showing all available source metadata (type, provider, source ID,
filename, target file, download URL, etc.)
- **Add source fields to API**: Backend now includes
`audio_source_type`, `source_name`, `source_id`, `target_file`,
`download_url` in the summary field projection

## Test plan

- [x] Backend: Regression test asserting all source fields are in
`SUMMARY_FIELD_PATHS` (11 tests pass)
- [x] E2E regression: 3 new tests for source modal (audio search,
YouTube, file upload)
- [x] E2E regression: Updated existing YouTube source test for new modal
behavior
- [x] Full admin-job-detail E2E suite: 24/24 passing

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 02:55:29 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 deb870a980 feat: store processing metadata permanently for all workers (#527)
## Summary

- Add `processing_metadata` field to Job model — immutable provenance
data written by each worker during processing, separate from
`state_data` (mutable workflow state)
- **Critical fix**: Persist AudioShake `task_id` and `asset_id` which
were previously lost after processing, requiring costly log/API recovery
for data exports
- Each worker writes its own section: transcription (AudioShake IDs),
separation (models, timing), rendering, encoding, distribution, audio
source (ffprobe), and worker timing
- All metadata writes are non-fatal (try/except wrapped) — never fails
jobs
- Stores auth context (`auth_method`, `user_type`,
`credits_at_creation`) and search query metadata at job creation
- Uses Firestore dot-notation for atomic section updates without
overwriting other workers' data

## Changes

- **Model**: `processing_metadata` field on Job,
`update_processing_metadata` helper on JobManager
- **Workers**: lyrics, audio, screens, render_video, video — each writes
timing + worker-specific metadata
- **AudioShake**: `asset_id` now stored in `TranscriptionData.metadata`,
flows through `corrections.json`
- **API routes**: `extract_request_metadata()` accepts optional
`auth_result` for auth context; audio search stores search query
- **Firestore**: `processing_metadata` added to `SUMMARY_FIELD_PATHS`
- **Tests**: 24 tests covering model, helpers, all worker functions,
error handling, SUMMARY_FIELD_PATHS regression guard

## Test plan

- [x] 24 new unit tests all passing
- [x] All 2512 existing tests pass
- [x] CodeRabbit review — fixed timing overwrite bug (deep dot-notation)
- [ ] Deploy and verify metadata appears on new jobs via Firestore
console

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 01:16:43 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 010784141c fix: resolve 500 error on admin users search (#526)
## Summary
- Fix 500 error when searching users on admin dashboard caused by
Firestore range filter on `email` conflicting with `order_by` on
`created_at` (requires composite index)
- Move sorting to Python when search is active (docs are already fetched
for in-memory pagination anyway)
- Strip whitespace from search input to handle trailing spaces from URL
encoding (`search=dalton+`)

## Test plan
- [x] All 2489 backend tests pass
- [x] CodeRabbit review: 1 finding fixed (type-safe sort key)
- [ ] Verify search works in production after deploy

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-10 00:38:53 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 64a95d79c6 perf: pre-generate audio editor assets for instant loading (#525)
## Summary
- Audio editor UI was taking 10-20 seconds to load because waveform
generation + FLAC→OGG transcoding happened on-demand
- Now pre-generates both assets in the download worker before
`awaiting_audio_edit`, matching the pattern `screens_worker` uses for
lyrics/instrumental review
- Editor should now load in ~1s (just reads cached JSON + serves signed
URL for pre-transcoded OGG)

## Changes
- `AudioAnalysisService`: new `cache_waveform_data()` and
`load_cached_waveform()` methods
- `audio_download_worker`: pre-transcodes OGG + caches waveform JSON
before state transition (non-fatal)
- `input-audio-info` endpoint: checks for cached waveform first, falls
back to on-demand
- 10 new unit tests covering cache hit/miss, pre-generation, and
fallback behavior

## Test plan
- [x] 2512 backend tests pass (1 pre-existing failure unrelated)
- [ ] Create job with audio edit enabled, verify editor loads instantly

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 18:04:13 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 4824743a99 fix: update E2E tests for new Visibility step (#524)
## Summary
- The guided job creation flow was expanded from 3→4 steps (added
Visibility step between audio selection and Customize & Create)
- E2E tests were not updated, causing the daily happy path test to fail
([run
#95](https://github.com/nomadkaraoke/karaoke-gen/actions/runs/22840888562))
- Updated 3 test files to interact with the new Visibility step before
proceeding to Customize & Create

## Changes
- **happy-path-real-user.spec.ts**: Click "Keep Private" in Visibility
step, remove obsolete `#guided-private` checkbox
- **guided-flow.spec.ts**: All 4 job-creation tests updated for
Visibility step (search, private+display names, YouTube URL, file
upload)
- **demo-recording.spec.ts**: Added Visibility scene, renumbered
subsequent scenes

## Test plan
- [x] All 701 frontend unit tests pass
- [ ] CI E2E smoke tests pass
- [ ] `e2e-happy-path` label triggers production happy path test —
should now pass with the Visibility step interaction

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 17:54:14 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 b2b2469f6f ui: improve audio edit opt-in with clearer visual hierarchy (#523)
## Summary
- Redesigned the audio edit opt-in screen shown after selecting audio in
the job creation flow
- "Use as-is" (default) gets a green Zap icon and "Recommended" badge —
visually prominent so most users click through quickly
- "Edit audio first" gets a purple Scissors icon with a gold lightbulb
hint explaining when it's useful (live recordings with intros, tracks
with sections to remove)
- Left-aligned layout with icons for better scannability

## Test plan
- [x] All 701 frontend tests pass
- [ ] Visual check in production after deploy

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 16:38:17 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 ba265839cf fix: swap upload_json arguments for audio edit endpoints (#522)
## Summary
- Fixed swapped `upload_json(destination_path, data)` arguments in two
audio edit endpoints
- Both `save_audio_edit_session` and `submit_audio_edit` were passing
`(data, path)` instead of `(path, data)`, causing 500 errors

## Test plan
- [x] Verify audio edit session save works (POST
`/api/review/{job_id}/audio-edit-sessions`)
- [x] Verify audio edit submit works (POST
`/api/review/{job_id}/audio-edit/submit`)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 16:27:10 -04:00
366 changed files with 75320 additions and 4537 deletions

No files matched your search

@@ -0,0 +1,109 @@
# Plan: Admin Feedback Visibility
**Created:** 2026-03-23
**Branch:** feat/sess-20260323-1454-feedback-email-debug
**Status:** Draft
## Overview
User feedback submissions are stored in Firestore (`user_feedback` collection) but are completely invisible to the admin. The admin panel only shows a boolean "Feedback Submitted: Yes/No" badge per user. This plan adds:
1. **Admin UI page** to browse and review all submitted feedback
2. **Email notification** to admin@nomadkaraoke.com on each new submission
## Requirements
- [ ] Admin page at `/admin/feedback` listing all feedback with ratings, text, timestamps, and user info
- [ ] Sortable by date (newest first by default) and filterable by search (email)
- [ ] Star ratings rendered visually (not just numbers)
- [ ] Email sent to admin@nomadkaraoke.com immediately when feedback is submitted
- [ ] Email includes all feedback content (ratings, text fields, user email)
- [ ] Test data filtering works (exclude_test toggle)
- [ ] Sidebar navigation includes new "Feedback" item
## Technical Approach
### Admin API Endpoint
Add `GET /api/admin/feedback` to `backend/api/routes/admin.py`. Follows the standard admin endpoint pattern: `require_admin` dependency, pagination with `limit`/`offset`/`search`/`exclude_test`, returns Pydantic response model. Queries `user_feedback` Firestore collection.
### Admin UI Page
New page at `frontend/app/admin/feedback/page.tsx`. Follows existing admin page patterns (Card, Table, Badge, pagination, search input, loading states). Uses `adminApi.listFeedback()` to fetch data.
### Email Notification
Add a new method to `EmailService` (or call `send_email` directly) from the `submit_user_feedback` endpoint in `users.py`. Uses the existing SendGrid infrastructure — no new template service templates needed since this is an internal admin notification (simple HTML table with the feedback data).
## Implementation Steps
### Step 1: Backend — Admin feedback list endpoint
1. [ ] Add `AdminFeedbackItem` and `AdminFeedbackListResponse` Pydantic models to `admin.py`
2. [ ] Add `GET /api/admin/feedback` endpoint with:
- Pagination: `limit=50`, `offset=0`
- Search by user email
- `exclude_test` filter (reuse `is_test_email`)
- Sort by `created_at` descending
- Return: items, total, offset, limit, has_more
3. [ ] Add aggregate stats in response: average ratings, total count
### Step 2: Backend — Email notification on submission
4. [ ] Add `send_feedback_notification` method to `EmailService` that sends an HTML email to `admin@nomadkaraoke.com` containing:
- User email
- All 4 star ratings
- All text fields
- Would recommend / would use again
- Submitted timestamp
- Link to admin feedback page
5. [ ] Call `send_feedback_notification` from `submit_user_feedback` in `users.py` (fire-and-forget, don't block the user response on email success)
### Step 3: Frontend — Admin API client
6. [ ] Add `listFeedback` method to `adminApi` in `frontend/lib/api.ts`
7. [ ] Add TypeScript types for `AdminFeedbackItem` and `AdminFeedbackListResponse`
### Step 4: Frontend — Admin feedback page
8. [ ] Create `frontend/app/admin/feedback/page.tsx` with:
- Table: user email, date, overall rating (stars), ease of use, lyrics accuracy, correction experience, would recommend, would use again
- Expandable rows or click-to-detail for text fields (what went well, what could improve, additional comments)
- Search by email
- Pagination (50 per page)
- Refresh button
- Test data toggle (via `useAdminSettings`)
9. [ ] Add "Feedback" item to admin sidebar in `frontend/components/admin/admin-sidebar.tsx` with `MessageSquare` icon
### Step 5: Testing
10. [ ] Backend unit test for `GET /api/admin/feedback` endpoint (pagination, search, exclude_test)
11. [ ] Backend unit test for `send_feedback_notification` email method
12. [ ] Frontend component test for feedback page (render, empty state)
## Files to Create/Modify
| File | Action | Description |
|------|--------|-------------|
| `backend/api/routes/admin.py` | Modify | Add feedback list endpoint + response models |
| `backend/api/routes/users.py` | Modify | Add email notification call in `submit_user_feedback` |
| `backend/services/email_service.py` | Modify | Add `send_feedback_notification` method |
| `frontend/lib/api.ts` | Modify | Add `adminApi.listFeedback()` method + types |
| `frontend/app/admin/feedback/page.tsx` | Create | Admin feedback review page |
| `frontend/components/admin/admin-sidebar.tsx` | Modify | Add "Feedback" nav item |
| `backend/tests/test_admin_feedback.py` | Create | Tests for admin feedback endpoint |
| `backend/tests/test_feedback_email.py` | Create | Tests for feedback email notification |
## Testing Strategy
- **Unit tests**: Admin endpoint (pagination, filtering, sorting), email method (content formatting, send call)
- **Integration**: Submit feedback → verify email service called
- **Manual verification**: Check email arrives in admin@nomadkaraoke.com inbox after submission
## Open Questions
- [ ] Should the admin page show feedback from the old `beta_feedback` collection too, or just `user_feedback`? (Recommendation: just `user_feedback` — the beta collection is legacy)
- [ ] Should there be any spam/quality detection flagging? (Some submissions appear to game the system for credits)
## Rollback Plan
- Backend: Remove endpoint from admin.py, revert email call in users.py
- Frontend: Delete feedback page, remove sidebar item
- No data migration needed — Firestore collection unchanged
+151
View File
@@ -0,0 +1,151 @@
# Plan: AI-Powered Credit Gating
**Created:** 2026-03-23
**Branch:** feat/sess-20260323-1716-ai-credit-gating
**Status:** Implemented
## Overview
Replace the automatic welcome/feedback credit grants with an AI-powered evaluation step. When a user triggers a credit grant (email verification or feedback submission), instead of immediately granting credits, we collect abuse signals and ask Gemini to make a grant/deny decision. Suspected abusers get a friendly rejection email (CC'd to Andrew) instead of free credits.
## Requirements
- [ ] Welcome credit grants go through AI evaluation before granting
- [ ] Feedback credit grants go through AI evaluation before granting
- [ ] AI evaluates: fingerprint correlations, IP correlations, IP geo info, user agent, signup recency patterns
- [ ] Approved users get credits as before (seamless experience)
- [ ] Rejected users get a friendly-but-firm email explaining the situation, CC'd to andrew@beveridge.uk
- [ ] Rejection email invites them to reply if it's a mistake
- [ ] Decision is logged to Firestore for audit trail
- [ ] Fail-open: if AI evaluation fails, grant credits (don't punish users for our errors)
- [ ] Admin can override decisions via existing admin credit grant endpoint
## Technical Approach
### Architecture
```
User verifies email / submits feedback
↓
Collect abuse signals (sync, fast):
- User's fingerprint + IP
- Other accounts with same fingerprint (from correlations)
- Other accounts with same IP
- IP geolocation info
- Recent signup count from same IP/fingerprint (last 24h)
- User agent string
- For feedback: the feedback content itself
↓
Call Gemini (vertexai/gemini-2.5-pro-preview) with structured prompt:
- Present all signals
- Ask for JSON response: {decision: "grant" | "deny", reasoning: string, confidence: number}
↓
If "grant": grant credits normally, log decision
If "deny": skip credit grant, send rejection email, log decision
If AI call fails: grant credits (fail-open), log error
```
### Key Design Decisions
1. **Two-phase verification**: The magic link verify endpoint returns immediately with session + a `credit_status: "evaluating"` field. The frontend shows a "preparing your account" loading screen, then polls/waits for the evaluation result via a new lightweight endpoint. This keeps the auth flow snappy while the AI evaluation runs in the background of the same request or via a short follow-up call. The frontend then shows either a celebratory "2 free credits!" interstitial or a "sorry, couldn't grant credits" interstitial before navigating to the dashboard.
2. **Fail-open**: If Gemini is down or returns an error, we grant credits. Better to let an occasional abuser through than block legitimate users.
3. **Use google-genai directly**: The project already has `langchain-google-genai` installed. We can use the simpler `google.generativeai` library directly for a focused prompt/response, or use the existing LangChain setup. We'll use `google.generativeai` for simplicity since this is a single-turn evaluation, not an agentic workflow.
4. **Structured JSON output**: Ask Gemini for structured output with decision, reasoning, and confidence to make decisions parseable and auditable.
5. **Log all decisions**: Store every evaluation in a `credit_evaluations` Firestore collection for audit trail and to tune the prompt over time.
## Implementation Steps
### Step 1: Add google-generativeai dependency
- Add `google-generativeai` to pyproject.toml (lightweight, direct Gemini access)
- Verify it works with Vertex AI auth in the nomadkaraoke project
### Step 2: Create credit evaluation service
- New file: `backend/services/credit_evaluation_service.py`
- `CreditEvaluationService` class with:
- `evaluate_credit_grant(email, grant_type, feedback_content=None) -> CreditEvaluation`
- Collects all abuse signals by calling existing services (user_service, ip_geolocation_service)
- Builds prompt with signals
- Calls Gemini for decision
- Logs decision to Firestore
- Returns structured result
### Step 3: Build the Gemini prompt
- System prompt explaining the role: "You are an anti-abuse evaluator for a karaoke video service..."
- Present all signals in a structured format
- Request JSON response: `{decision: "grant"|"deny", reasoning: "...", confidence: 0.0-1.0}`
- Include clear guidelines: same fingerprint across accounts = very suspicious, same IP = somewhat suspicious, etc.
### Step 4: Create rejection email template
- Add `send_credit_denied_email(email, reasoning)` to EmailService
- Friendly-but-firm tone
- CC andrew@beveridge.uk
- Invite reply if it's a mistake
- Use existing email template infrastructure (branding, styling)
### Step 5: Integrate into welcome credit flow
- Modify `grant_welcome_credits_if_eligible()` in user_service.py
- Before granting: call `CreditEvaluationService.evaluate_credit_grant(email, "welcome")`
- If denied: send rejection email, return False
- If error: log warning, grant anyway (fail-open)
### Step 6: Integrate into feedback credit flow
- Modify feedback endpoint in users.py
- Before granting credits: evaluate with feedback content included
- If denied: return different response message, send rejection email
- If error: grant anyway
### Step 7: Add Firestore collection for audit trail
- Collection: `credit_evaluations`
- Document fields: email, grant_type, decision, reasoning, confidence, signals_snapshot, model_used, evaluated_at
- TTL: keep indefinitely (small volume, high audit value)
### Step 8: Tests
- Unit tests for signal collection
- Unit tests for prompt building
- Unit tests for decision parsing (grant/deny/error cases)
- Integration test for the evaluation service with mocked Gemini
- Integration test for welcome credit flow with evaluation
- Integration test for feedback credit flow with evaluation
- Test fail-open behavior
### Step 9: Configuration
- Add env vars: `CREDIT_EVAL_MODEL` (default: "gemini-2.5-pro-preview"), `CREDIT_EVAL_ENABLED` (default: true)
- Add to config.py
## Files to Create/Modify
| File | Action | Description |
|------|--------|-------------|
| `pyproject.toml` | Modify | Add google-generativeai dependency |
| `backend/config.py` | Modify | Add credit evaluation config vars |
| `backend/services/credit_evaluation_service.py` | Create | New service: collect signals, call Gemini, log decision |
| `backend/services/user_service.py` | Modify | Integrate evaluation into welcome credit grant |
| `backend/api/routes/users.py` | Modify | Integrate evaluation into feedback credit grant |
| `backend/services/email_service.py` | Modify | Add credit denied email template |
| `backend/tests/test_credit_evaluation.py` | Create | Tests for evaluation service |
| `backend/tests/test_anti_abuse.py` | Modify | Update welcome credit tests for evaluation |
| `frontend/app/auth/verify/page.tsx` | Modify | Add "preparing account" loading + credit result interstitial |
| `frontend/lib/api.ts` | Modify | Add credit evaluation status endpoint |
## Testing Strategy
- **Unit tests**: Signal collection, prompt building, response parsing, fail-open behavior
- **Integration tests**: Full evaluation flow with mocked Gemini responses
- **E2E tests**: Manual verification in production with test accounts
- **Edge cases**: Gemini timeout, malformed response, missing signals, first-ever user (no correlations)
## Open Questions
1. **Gemini model**: Using `gemini-3.1-pro-preview` as specified — already available in the nomadkaraoke GCP project.
2. **Latency UX**: Frontend shows a friendly "preparing your account" loading screen while evaluation runs. Then transitions to either a celebratory "2 free credits!" message (with gentle reminder not to abuse) or a "sorry, couldn't grant free credits" message with a buy credits CTA. User clicks through to dashboard from either.
3. **Should we also gate the existing rate limiter?** Currently `is_signup_rate_limited()` silently blocks at 2 accounts per IP/fingerprint per 24h. The AI evaluation is complementary — rate limiter blocks obvious rapid abuse, AI evaluation catches more subtle patterns.
## Rollback Plan
Set `CREDIT_EVAL_ENABLED=false` in Cloud Run env vars → immediate rollback to auto-grant behavior. No data model changes needed. The evaluation service is purely additive.
@@ -0,0 +1,150 @@
# Plan: Block Disposable Email Registration
**Created:** 2026-03-19
**Branch:** feat/sess-20260319-1332-disposable-email-abuse
**Status:** Draft
## Overview
Users are signing up with disposable email addresses (yopmail.com, emailhook.site, etc.) to get unlimited free credits (2 per account). The `EmailValidationService` already exists with 160+ disposable domains but is **never called during signup**. We need to wire it into the magic link flow and show a friendly rejection message.
## Context
- The `EmailValidationService` (`backend/services/email_validation_service.py`) is fully implemented with disposable domain detection, email/IP blocklists, and admin management APIs
- The admin blocklist management routes exist (`backend/api/routes/rate_limits.py`) and work
- The magic link endpoint (`POST /api/users/auth/magic-link` in `backend/api/routes/users.py:133`) **never calls** the validation service
- Currently 1 yopmail user and 1 emailhook.site user in `gen_users`
- Each new account gets 2 free welcome credits automatically
## Requirements
- [x] Reject disposable email domains at the magic link endpoint (backend)
- [x] Return a **specific, distinguishable error** so the frontend can show a friendly message (not the generic "email enumeration" response)
- [x] Show a warm, friendly message in the AuthDialog explaining why and encouraging real email use
- [x] Add `emailhook.site` to the default disposable domains list
- [x] Add backend unit tests for the integration
- [x] Add frontend test coverage for the new error state
## Design Decision: Explicit Rejection vs Silent Failure
The current magic link endpoint returns a generic success message to prevent email enumeration. For disposable emails, we will **explicitly reject** with a 422 status and a specific error message. This is the right trade-off because:
1. We *want* the user to know their disposable email won't work (so they can use a real one)
2. Disposable domain detection is not sensitive information — the blocklist is public knowledge
3. The friendly message serves our goal of converting them to real email users
## Implementation Steps
### Step 1: Backend — Add disposable email check to magic link endpoint
**File:** `backend/api/routes/users.py`
Add the `EmailValidationService` check **after** email lowercasing (line 158) and **before** tenant validation (line 164). Return a 422 with a friendly message.
```python
# Check for disposable email domains
email_validation = get_email_validation_service()
if email_validation.is_disposable_domain(email):
logger.warning(f"Blocked disposable email signup attempt: {_mask_email(email)}")
raise HTTPException(
status_code=422,
detail="disposable_email_not_allowed"
)
```
Use a machine-readable error code (`disposable_email_not_allowed`) so the frontend can match on it and show the custom friendly message. This keeps the backend response lean and puts the UX copy in the frontend where it belongs.
### Step 2: Backend — Also check email and IP blocklists
In the same location, add checks for explicitly blocked emails and IPs:
```python
if email_validation.is_email_blocked(email):
logger.warning(f"Blocked email signup attempt: {_mask_email(email)}")
# Silent reject — return generic success to prevent enumeration
return SendMagicLinkResponse(
status="success",
message="If this email is registered, you will receive a sign-in link shortly."
)
ip_address = http_request.client.host if http_request.client else None
if ip_address and email_validation.is_ip_blocked(ip_address):
logger.warning(f"Blocked IP signup attempt: {ip_address}")
return SendMagicLinkResponse(
status="success",
message="If this email is registered, you will receive a sign-in link shortly."
)
```
Note: Blocked emails/IPs get silent rejection (anti-enumeration). Disposable domains get explicit rejection (we want the user to switch to a real email).
### Step 3: Backend — Add `emailhook.site` to default disposable domains
**File:** `backend/services/email_validation_service.py`
Add `emailhook.site` to `DEFAULT_DISPOSABLE_DOMAINS` set.
### Step 4: Frontend — Handle the disposable email error in AuthDialog
**File:** `frontend/components/auth/AuthDialog.tsx`
The `sendMagicLink` call in `auth.ts` already catches errors and sets `error` from the API response message. The `handleResponse` in `api.ts` throws an `ApiError` with the `detail` string for non-200 responses.
Update `handleSendMagicLink` to detect the `disposable_email_not_allowed` error code and show a friendly multi-line message instead of the terse error string:
```tsx
const success = await sendMagicLink(email.trim().toLowerCase())
if (success) {
setStep("sent")
}
// If error contains our specific code, override with friendly message
// (the error state is already set by the auth store)
```
We need to detect the specific error. The cleanest approach: check the error string in the `displayError` rendering. If it matches `disposable_email_not_allowed`, render a custom friendly block instead of the red error text.
The friendly message:
> **We don't support disposable email addresses**
>
> We'd love to help you create karaoke videos! Please use your regular email address so we can send you a notification when your video is ready.
>
> We promise — no spam, no marketing emails, ever. We only email you about your karaoke videos.
### Step 5: Backend tests
**File:** `backend/tests/test_email_validation_integration.py` (new)
Test cases:
1. Magic link with disposable email returns 422 with `disposable_email_not_allowed`
2. Magic link with legitimate email proceeds normally
3. Magic link with blocked email returns silent success (no actual email sent)
4. Magic link with blocked IP returns silent success
### Step 6: Frontend tests
**File:** `frontend/components/__tests__/AuthDialog.test.tsx` (new or extend existing)
Test cases:
1. Submitting a disposable email shows the friendly rejection message
2. The friendly message contains the key copy (no spam promise, use real email)
## Files to Create/Modify
| File | Action | Description |
|------|--------|-------------|
| `backend/api/routes/users.py` | Modify | Add email validation checks to magic link endpoint |
| `backend/services/email_validation_service.py` | Modify | Add `emailhook.site` to default domains |
| `frontend/components/auth/AuthDialog.tsx` | Modify | Handle disposable email error with friendly message |
| `backend/tests/test_email_validation_integration.py` | Create | Integration tests for the validation in signup flow |
## Testing Strategy
- **Unit tests:** Validate `is_disposable_domain` catches yopmail, emailhook.site (already covered in existing tests)
- **Integration tests:** New test file verifying the magic link endpoint rejects disposable emails with 422
- **Frontend tests:** Verify the AuthDialog shows friendly message on disposable email error
- **Manual verification:** Try signing up with `test@yopmail.com` on dev server to see the UX
## Rollback Plan
Remove the validation check from `send_magic_link()` in `users.py`. The `EmailValidationService` itself remains unchanged (it's already deployed and used by admin routes).
+432 -123
View File
@@ -628,7 +628,24 @@ jobs:
- name: Install dependencies
run: poetry install
- name: Start Docker for GCS emulator
- name: Wait for Docker to be available
run: |
# Self-hosted runners may still be initializing Docker on boot.
# Wait up to 60s for the docker command and daemon to be ready.
for i in $(seq 1 12); do
if command -v docker &>/dev/null && docker info &>/dev/null 2>&1; then
echo "Docker is ready"
exit 0
fi
echo "Waiting for Docker... (attempt $i/12)"
sleep 5
done
echo "ERROR: Docker not available after 60s"
echo "PATH=$PATH"
which docker 2>&1 || echo "docker binary not found"
exit 1
- name: Pull GCS emulator image
run: docker pull fsouza/fake-gcs-server:latest
- name: Run emulator integration tests
@@ -885,6 +902,22 @@ jobs:
# - / (main app)
# - /app/jobs/{id}/lyrics (lyrics review)
# - /app/jobs/{id}/instrumental (instrumental review)
- name: Capture build metadata
id: frontend-meta
run: |
echo "sha=${GITHUB_SHA::8}" >> $GITHUB_OUTPUT
PR_NUM=$(git log -1 --format=%s | grep -oP '\(#\K[0-9]+' | head -1 || echo "")
if [ -n "$PR_NUM" ]; then
PR_TITLE=$(gh pr view "$PR_NUM" --json title -q .title 2>/dev/null || echo "")
else
PR_NUM=""
PR_TITLE=""
fi
echo "pr_number=${PR_NUM}" >> $GITHUB_OUTPUT
echo "pr_title=${PR_TITLE}" >> $GITHUB_OUTPUT
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Install frontend dependencies
working-directory: frontend
run: npm ci --legacy-peer-deps
@@ -894,6 +927,10 @@ jobs:
working-directory: frontend
env:
NEXT_PUBLIC_API_URL: https://api.nomadkaraoke.com
NEXT_PUBLIC_COMMIT_SHA: ${{ steps.frontend-meta.outputs.sha }}
NEXT_PUBLIC_PR_NUMBER: ${{ steps.frontend-meta.outputs.pr_number }}
NEXT_PUBLIC_PR_TITLE: ${{ steps.frontend-meta.outputs.pr_title }}
NEXT_PUBLIC_BUILD_TIME: ${{ github.event.head_commit.timestamp }}
run: npm run build
- name: Deploy consumer to Cloudflare Pages
@@ -912,6 +949,10 @@ jobs:
env:
NEXT_PUBLIC_API_URL: https://api.nomadkaraoke.com
NEXT_PUBLIC_TENANT_PORTAL: "true"
NEXT_PUBLIC_COMMIT_SHA: ${{ steps.frontend-meta.outputs.sha }}
NEXT_PUBLIC_PR_NUMBER: ${{ steps.frontend-meta.outputs.pr_number }}
NEXT_PUBLIC_PR_TITLE: ${{ steps.frontend-meta.outputs.pr_title }}
NEXT_PUBLIC_BUILD_TIME: ${{ github.event.head_commit.timestamp }}
run: npm run build
- name: Deploy tenant portal to Cloudflare Pages
@@ -942,6 +983,11 @@ jobs:
REPOSITORY: karaoke-repo
BASE_IMAGE_NAME: karaoke-backend-base
APP_IMAGE_NAME: karaoke-backend
# GPU image for audio worker (L4 in us-east4)
GPU_REGISTRY: us-east4-docker.pkg.dev
GPU_REPOSITORY: karaoke-backend-gpu
GPU_BASE_IMAGE_NAME: karaoke-backend-gpu-base
GPU_APP_IMAGE_NAME: karaoke-backend
steps:
- name: Check disk space (aggressive for Docker builds)
run: |
@@ -986,6 +1032,23 @@ jobs:
echo "📋 Current version: $VERSION"
echo "🚀 Deploying on every push to main"
- name: Capture build metadata
id: build-meta
run: |
echo "sha=${GITHUB_SHA::8}" >> $GITHUB_OUTPUT
# For squash-merge commits, PR number is in the commit message as (#NNN)
PR_NUM=$(git log -1 --format=%s | grep -oP '\(#\K[0-9]+' | head -1 || echo "")
if [ -n "$PR_NUM" ]; then
PR_TITLE=$(gh pr view "$PR_NUM" --json title -q .title 2>/dev/null || echo "")
else
PR_NUM=""
PR_TITLE=""
fi
echo "pr_number=${PR_NUM}" >> $GITHUB_OUTPUT
echo "pr_title=${PR_TITLE}" >> $GITHUB_OUTPUT
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Authenticate to Google Cloud (Workload Identity)
id: auth
uses: google-github-actions/auth@v2
@@ -999,14 +1062,15 @@ jobs:
version: "latest"
# ============================================
# Deploy to GCE Encoding Worker (Immutable Deployment Pattern)
# Blue-Green Deploy to GCE Encoding Worker
#
# This pattern ensures version consistency:
# 1. Upload wheel to FIXED path (no version sorting)
# 2. Upload startup.sh (logic can change without image rebuild)
# 3. Write version manifest for verification
# 4. Restart service (triggers bootstrap.sh -> startup.sh)
# 5. STRICTLY verify deployed version (fail CI on mismatch)
# This pattern ensures zero-downtime deployments:
# 1. Upload wheel + startup.sh + version manifest to GCS
# 2. Read blue-green config from Firestore
# 3. Start secondary VM, wait for health + version match
# 4. Deep health check: submit a real encode test
# 5. Swap primary/secondary in Firestore (atomic transaction)
# 6. Drain and stop old primary
#
# See infrastructure/encoding-worker/README.md for details
# ============================================
@@ -1017,12 +1081,12 @@ jobs:
name: package-dist
path: dist/
- name: Deploy to GCE Encoding Worker
- name: Deploy to GCS
run: |
VERSION="${{ steps.version_check.outputs.version }}"
BUCKET="gs://karaoke-gen-storage-${{ env.PROJECT_ID }}"
echo "🚀 Deploying encoding worker v${VERSION}..."
echo "Deploying encoding worker v${VERSION}..."
# 1. Find the wheel file
WHEEL_FILE=$(ls dist/*.whl | head -1)
@@ -1030,11 +1094,11 @@ jobs:
echo "::error::No wheel file found in dist/"
exit 1
fi
echo "📦 Found wheel: $WHEEL_FILE"
echo "Found wheel: $WHEEL_FILE"
# 2. Upload wheel to FIXED path (atomic via temp file)
# This eliminates version sorting - always use karaoke_gen-current.whl
echo "📤 Uploading wheel to fixed path..."
echo "Uploading wheel to fixed path..."
gsutil cp "$WHEEL_FILE" "${BUCKET}/wheels/karaoke_gen-current.whl.tmp"
gsutil mv "${BUCKET}/wheels/karaoke_gen-current.whl.tmp" \
"${BUCKET}/wheels/karaoke_gen-current.whl"
@@ -1043,132 +1107,280 @@ jobs:
gsutil cp "$WHEEL_FILE" "${BUCKET}/wheels/"
# 3. Upload startup.sh (allows logic changes without image rebuild)
echo "📤 Uploading startup.sh..."
echo "Uploading startup.sh..."
gsutil cp infrastructure/encoding-worker/startup.sh \
"${BUCKET}/encoding-worker/startup.sh"
# 4. Write version manifest for verification
echo "📝 Writing version manifest..."
echo "Writing version manifest..."
echo "${VERSION}" | gsutil cp - "${BUCKET}/encoding-worker/version.txt"
echo "✅ GCS deployment complete"
echo "GCS deployment complete"
- name: Drain active encoding jobs before restart
- name: Install Firestore client
run: pip install google-cloud-firestore
- name: Read Firestore config
id: config
run: |
# Graceful drain: wait for any active encoding jobs to finish before
# restarting the worker. This prevents killing in-flight FFmpeg encodes.
#
# The /health endpoint returns active_jobs count. We poll until it's 0
# or until the drain timeout expires (10 minutes — well within the
# longest encoding time of ~5 min for a full 4-format encode).
python3 << 'PYEOF'
import json, os
from google.cloud import firestore
db = firestore.Client(project="nomadkaraoke")
doc = db.collection("config").document("encoding-worker").get()
if not doc.exists:
print("::error::Encoding worker config not found in Firestore")
raise SystemExit(1)
data = doc.to_dict()
with open(os.environ["GITHUB_OUTPUT"], "a") as f:
for key in ["primary_vm", "primary_ip", "primary_version",
"secondary_vm", "secondary_ip"]:
f.write(f"{key}={data.get(key, '')}\n")
f.write(f"deploy_in_progress={str(data.get('deploy_in_progress', False)).lower()}\n")
print(f"Config: primary={data['primary_vm']}, secondary={data['secondary_vm']}")
PYEOF
WORKER_KEY=$(gcloud secrets versions access latest --secret=encoding-worker-api-key --project=nomadkaraoke)
WORKER_URL=$(gcloud secrets versions access latest --secret=encoding-worker-url --project=nomadkaraoke)
DRAIN_TIMEOUT=600 # 10 minutes
POLL_INTERVAL=15
ELAPSED=0
- name: Wait for concurrent deploy
if: steps.config.outputs.deploy_in_progress == 'true'
run: |
echo "Another deploy is in progress, waiting..."
python3 << 'PYEOF'
import time
from google.cloud import firestore
db = firestore.Client(project="nomadkaraoke")
for i in range(20):
time.sleep(30)
doc = db.collection("config").document("encoding-worker").get()
if not doc.to_dict().get("deploy_in_progress", False):
print("Concurrent deploy finished, proceeding")
break
else:
print("::error::Timed out waiting for concurrent deploy (10 min)")
raise SystemExit(1)
PYEOF
echo "🔍 Checking for active encoding jobs before restart..."
- name: Set deploy in progress
run: |
python3 << 'PYEOF'
from datetime import datetime, timezone
from google.cloud import firestore
db = firestore.Client(project="nomadkaraoke")
db.collection("config").document("encoding-worker").update({
"deploy_in_progress": True,
"deploy_in_progress_since": datetime.now(timezone.utc).isoformat(),
})
print("Set deploy_in_progress=true")
PYEOF
while [ $ELAPSED -lt $DRAIN_TIMEOUT ]; do
HEALTH=$(curl -sf -H "X-API-Key: $WORKER_KEY" "$WORKER_URL/health" 2>/dev/null || echo '{"active_jobs": -1}')
ACTIVE=$(echo "$HEALTH" | grep -o '"active_jobs":[0-9]*' | cut -d: -f2)
- name: Start secondary VM
run: |
SECONDARY_VM="${{ steps.config.outputs.secondary_vm }}"
echo "Starting secondary VM: $SECONDARY_VM"
gcloud compute instances start "$SECONDARY_VM" \
--zone=us-central1-c --project=nomadkaraoke || true
if [ -z "$ACTIVE" ] || [ "$ACTIVE" = "-1" ]; then
echo "⚠️ Could not reach health endpoint (worker may already be down). Proceeding with restart."
for i in $(seq 1 12); do
STATUS=$(gcloud compute instances describe "$SECONDARY_VM" \
--zone=us-central1-c --project=nomadkaraoke \
--format='value(status)')
echo "VM status: $STATUS (attempt $i/12)"
if [ "$STATUS" = "RUNNING" ]; then
break
fi
if [ "$ACTIVE" = "0" ]; then
echo "✅ No active encoding jobs. Safe to restart."
break
fi
echo "⏳ $ACTIVE active encoding job(s) running. Waiting ${POLL_INTERVAL}s... (${ELAPSED}s/${DRAIN_TIMEOUT}s)"
sleep $POLL_INTERVAL
ELAPSED=$((ELAPSED + POLL_INTERVAL))
sleep 10
done
if [ $ELAPSED -ge $DRAIN_TIMEOUT ]; then
echo "⚠️ Drain timeout reached (${DRAIN_TIMEOUT}s) with jobs still active. Proceeding with restart."
echo " Active jobs will be recoverable via idempotent /encode endpoint (PR #413)."
fi
- name: Restart GCE Encoding Worker
- name: Wait for service health
id: health
continue-on-error: true
run: |
VERSION="${{ steps.version_check.outputs.version }}"
SECONDARY_IP="${{ steps.config.outputs.secondary_ip }}"
EXPECTED_VERSION="${{ steps.version_check.outputs.version }}"
HEALTH_URL="http://${SECONDARY_IP}:8080/health"
echo "🔄 Restarting encoding worker..."
# Use IAP tunneling - works directly with service account credentials
gcloud compute ssh encoding-worker \
--zone=us-central1-c \
--project=nomadkaraoke \
--tunnel-through-iap \
--command="sudo systemctl restart encoding-worker"
echo "⏳ Waiting for service to start (up to 60s)..."
sleep 20
- name: Verify Encoding Worker Version
run: |
VERSION="${{ steps.version_check.outputs.version }}"
echo "🔍 Verifying encoding worker version..."
# Retry loop - service may take time to fully start
MAX_RETRIES=6
RETRY_DELAY=10
for i in $(seq 1 $MAX_RETRIES); do
echo "Attempt $i/$MAX_RETRIES..."
NEW_VERSION=$(gcloud compute ssh encoding-worker \
--zone=us-central1-c \
--project=nomadkaraoke \
--tunnel-through-iap \
--command="curl -s http://localhost:8080/health 2>/dev/null | grep -o '\"wheel_version\":\"[^\"]*\"' | cut -d'\"' -f4" 2>/dev/null || echo "")
if [ "$NEW_VERSION" = "$VERSION" ]; then
echo "✅ Encoding worker version verified: v$NEW_VERSION"
exit 0
fi
if [ -n "$NEW_VERSION" ]; then
echo "⚠️ Version: $NEW_VERSION (expected: $VERSION)"
else
echo "⚠️ Health endpoint not responding yet"
fi
if [ $i -lt $MAX_RETRIES ]; then
echo " Retrying in ${RETRY_DELAY}s..."
sleep $RETRY_DELAY
echo "Waiting for service at $HEALTH_URL..."
for i in $(seq 1 18); do
RESPONSE=$(curl -sf "$HEALTH_URL" 2>/dev/null || echo "")
if [ -n "$RESPONSE" ]; then
WHEEL_VERSION=$(echo "$RESPONSE" | jq -r '.wheel_version // empty')
echo "Health: version=$WHEEL_VERSION"
if [ "$WHEEL_VERSION" = "$EXPECTED_VERSION" ]; then
echo "Version matches! Service is healthy."
echo "healthy=true" >> $GITHUB_OUTPUT
exit 0
fi
fi
echo "Attempt $i/18 - waiting 10s..."
sleep 10
done
# STRICT VERIFICATION: Fail CI on version mismatch
echo ""
echo "=============================================="
echo "❌ ENCODING WORKER DEPLOYMENT FAILED"
echo "=============================================="
echo "Expected version: $VERSION"
echo "Deployed version: $NEW_VERSION"
echo ""
echo "Possible causes:"
echo " - GCS upload failed (check 'Deploy to GCE' step)"
echo " - startup.sh download failed (check VM logs)"
echo " - Wheel installation failed (check VM logs)"
echo ""
echo "To debug, SSH to VM and check logs:"
echo " gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke --tunnel-through-iap"
echo " sudo journalctl -u encoding-worker -n 100"
echo " cat /var/log/encoding-worker-startup.log"
echo "=============================================="
echo "::error::Service did not become healthy within 3 minutes"
echo "healthy=false" >> $GITHUB_OUTPUT
exit 1
- name: Deep health check - real encode test
if: steps.health.outputs.healthy == 'true'
id: encode-test
continue-on-error: true
run: |
SECONDARY_IP="${{ steps.config.outputs.secondary_ip }}"
API_KEY=$(gcloud secrets versions access latest \
--secret=encoding-worker-api-key --project=nomadkaraoke)
DEPLOY_TEST_PATH="gs://karaoke-gen-storage-nomadkaraoke/deploy-test"
echo "Uploading test assets to GCS..."
gsutil cp infrastructure/encoding-worker/test-assets/test-preview.ass \
"${DEPLOY_TEST_PATH}/test-preview.ass"
gsutil cp infrastructure/encoding-worker/test-assets/test-audio.flac \
"${DEPLOY_TEST_PATH}/test-audio.flac"
echo "Submitting test encode to $SECONDARY_IP..."
HTTP_CODE=$(curl -s -o /tmp/encode-response.json -w '%{http_code}' \
-X POST "http://${SECONDARY_IP}:8080/encode-preview" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d "{
\"job_id\": \"deploy-health-check\",
\"ass_gcs_path\": \"${DEPLOY_TEST_PATH}/test-preview.ass\",
\"audio_gcs_path\": \"${DEPLOY_TEST_PATH}/test-audio.flac\",
\"output_gcs_path\": \"${DEPLOY_TEST_PATH}/output-preview.mp4\"
}") || HTTP_CODE="000"
RESPONSE=$(cat /tmp/encode-response.json 2>/dev/null || echo "{}")
echo "Encode response (HTTP $HTTP_CODE): $RESPONSE"
if [ "$HTTP_CODE" != "200" ] && [ "$HTTP_CODE" != "202" ]; then
echo "::error::Encode request failed with HTTP $HTTP_CODE"
echo "passed=false" >> $GITHUB_OUTPUT
exit 1
fi
STATUS=$(echo "$RESPONSE" | jq -r '.status // "unknown"')
if [ "$STATUS" != "accepted" ] && [ "$STATUS" != "cached" ] && [ "$STATUS" != "in_progress" ]; then
echo "::error::Encode test failed with status: $STATUS"
echo "passed=false" >> $GITHUB_OUTPUT
exit 1
fi
for i in $(seq 1 12); do
sleep 5
JOB_STATUS=$(curl -s \
"http://${SECONDARY_IP}:8080/status/deploy-health-check" \
-H "X-API-Key: $API_KEY" 2>/dev/null | jq -r '.status // "unknown"' 2>/dev/null) || JOB_STATUS="unknown"
echo "Encode status: $JOB_STATUS (attempt $i/12)"
if [ "$JOB_STATUS" = "complete" ]; then
echo "Encode test passed!"
echo "passed=true" >> $GITHUB_OUTPUT
gsutil rm -f gs://karaoke-gen-storage-nomadkaraoke/deploy-test/** || true
exit 0
elif [ "$JOB_STATUS" = "failed" ]; then
echo "::error::Encode test failed"
echo "passed=false" >> $GITHUB_OUTPUT
exit 1
fi
done
echo "::error::Encode test timed out after 60s"
echo "passed=false" >> $GITHUB_OUTPUT
exit 1
- name: Rollback on failure
if: steps.health.outputs.healthy != 'true' || steps.encode-test.outputs.passed != 'true'
run: |
SECONDARY_VM="${{ steps.config.outputs.secondary_vm }}"
if [ -n "$SECONDARY_VM" ]; then
echo "Stopping secondary VM $SECONDARY_VM due to failed deploy"
gcloud compute instances stop "$SECONDARY_VM" \
--zone=us-central1-c --project=nomadkaraoke || true
fi
python3 -c "
from google.cloud import firestore
db = firestore.Client(project='nomadkaraoke')
db.collection('config').document('encoding-worker').update({
'deploy_in_progress': False,
'deploy_in_progress_since': None,
})
print('Cleared deploy_in_progress flag')
" || true
- name: Swap primary in Firestore
if: steps.encode-test.outputs.passed == 'true'
env:
NEW_PRIMARY: ${{ steps.config.outputs.secondary_vm }}
NEW_PRIMARY_IP: ${{ steps.config.outputs.secondary_ip }}
NEW_VERSION: ${{ steps.version_check.outputs.version }}
OLD_PRIMARY: ${{ steps.config.outputs.primary_vm }}
OLD_PRIMARY_IP: ${{ steps.config.outputs.primary_ip }}
OLD_VERSION: ${{ steps.config.outputs.primary_version }}
run: |
echo "Swapping: $OLD_PRIMARY -> secondary, $NEW_PRIMARY -> primary"
python3 << 'PYEOF'
import os
from datetime import datetime, timezone
from google.cloud import firestore
db = firestore.Client(project="nomadkaraoke")
doc_ref = db.collection("config").document("encoding-worker")
now = datetime.now(timezone.utc).isoformat()
@firestore.transactional
def swap(transaction):
transaction.update(doc_ref, {
"primary_vm": os.environ["NEW_PRIMARY"],
"primary_ip": os.environ["NEW_PRIMARY_IP"],
"primary_version": os.environ["NEW_VERSION"],
"primary_deployed_at": now,
"secondary_vm": os.environ["OLD_PRIMARY"],
"secondary_ip": os.environ["OLD_PRIMARY_IP"],
"secondary_version": os.environ["OLD_VERSION"],
"secondary_deployed_at": now,
"last_swap_at": now,
"deploy_in_progress": False,
"deploy_in_progress_since": None,
})
transaction = db.transaction()
swap(transaction)
print(f"Swapped: {os.environ['NEW_PRIMARY']} is now primary")
PYEOF
- name: Drain and stop old primary
if: steps.encode-test.outputs.passed == 'true'
run: |
OLD_PRIMARY="${{ steps.config.outputs.primary_vm }}"
OLD_PRIMARY_IP="${{ steps.config.outputs.primary_ip }}"
API_KEY=$(gcloud secrets versions access latest \
--secret=encoding-worker-api-key --project=nomadkaraoke)
ACTIVE_JOBS=$(curl -sf "http://${OLD_PRIMARY_IP}:8080/health" \
| jq -r '.active_jobs // 0' 2>/dev/null || echo "0")
if [ "$ACTIVE_JOBS" -gt 0 ]; then
echo "Old primary has $ACTIVE_JOBS active jobs, waiting for drain..."
DRAIN_TIMEOUT=600
ELAPSED=0
while [ $ELAPSED -lt $DRAIN_TIMEOUT ]; do
sleep 15
ELAPSED=$((ELAPSED + 15))
ACTIVE_JOBS=$(curl -sf "http://${OLD_PRIMARY_IP}:8080/health" \
| jq -r '.active_jobs // 0' 2>/dev/null || echo "0")
echo "Active jobs: $ACTIVE_JOBS (${ELAPSED}s elapsed)"
if [ "$ACTIVE_JOBS" -eq 0 ]; then
break
fi
done
fi
echo "Stopping old primary: $OLD_PRIMARY"
gcloud compute instances stop "$OLD_PRIMARY" \
--zone=us-central1-c --project=nomadkaraoke || true
- name: Configure Docker for Artifact Registry
run: gcloud auth configure-docker ${{ env.REGISTRY }} --quiet
run: |
gcloud auth configure-docker ${{ env.REGISTRY }} --quiet
gcloud auth configure-docker ${{ env.GPU_REGISTRY }} --quiet
# ============================================
# Docker Build with BuildKit + Registry Cache
@@ -1287,6 +1499,88 @@ jobs:
cache-to: type=registry,ref=${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:cache,mode=max,ignore-error=true
provenance: false
# ============================================
# GPU Image Build (for audio worker with L4 GPU)
# Same pattern as base image: hash check → rebuild if needed
# GPU image lives in us-east4 (co-located with GPU instances)
# ============================================
- name: Calculate GPU base image hash
id: gpu-base-hash
run: |
# Hash Dockerfile.gpu-base + poetry.lock (resolved deps that affect GPU image)
# Using poetry.lock instead of pyproject.toml so that version-only bumps
# (which don't change dependencies) don't trigger expensive GPU base rebuilds
CURRENT_HASH=$(cat backend/Dockerfile.gpu-base poetry.lock | sha256sum | cut -d' ' -f1)
echo "hash=$CURRENT_HASH" >> $GITHUB_OUTPUT
echo "📋 GPU base content hash: $CURRENT_HASH"
- name: Check if GPU base image exists and is current
id: check-gpu-base
run: |
GPU_BASE_IMAGE="${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest"
EXISTING_HASH=""
MANIFEST=$(docker manifest inspect $GPU_BASE_IMAGE 2>/dev/null || echo "")
CONFIG_DIGEST=$(echo "$MANIFEST" | jq -r '.config.digest // ""' 2>/dev/null || echo "")
if [ -n "$CONFIG_DIGEST" ] && [ "$CONFIG_DIGEST" != "null" ] && [ "$CONFIG_DIGEST" != "" ]; then
echo "📋 Found GPU manifest, config digest: $CONFIG_DIGEST"
TOKEN=$(gcloud auth print-access-token)
CONFIG_JSON=$(curl -sL -H "Authorization: Bearer $TOKEN" \
"https://${{ env.GPU_REGISTRY }}/v2/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}/blobs/$CONFIG_DIGEST" 2>/dev/null)
EXISTING_HASH=$(echo "$CONFIG_JSON" | jq -r '.config.Labels["base.content.hash"] // ""' 2>/dev/null || echo "")
echo "📋 Registry GPU base image hash: $EXISTING_HASH"
else
echo "⚠️ No existing GPU base image found in registry - will build"
fi
if [ "${{ steps.gpu-base-hash.outputs.hash }}" != "$EXISTING_HASH" ]; then
echo "🔄 GPU base image needs rebuild (Dockerfile.gpu-base or pyproject.toml changed)"
echo " Current: ${{ steps.gpu-base-hash.outputs.hash }}"
echo " Registry: $EXISTING_HASH"
echo "needs_rebuild=true" >> $GITHUB_OUTPUT
else
echo "✅ GPU base image is up to date"
echo "needs_rebuild=false" >> $GITHUB_OUTPUT
fi
- name: Build and push GPU base image (if needed)
if: steps.check-gpu-base.outputs.needs_rebuild == 'true'
timeout-minutes: 45
uses: docker/build-push-action@v6
with:
context: .
file: backend/Dockerfile.gpu-base
push: true
tags: |
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:${{ github.sha }}
cache-from: type=registry,ref=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:cache,ignore-error=true
cache-to: type=registry,ref=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:cache,mode=max,ignore-error=true
build-args: |
BUILD_DATE=${{ github.run_id }}
BUILD_ID=${{ github.sha }}
BASE_CONTENT_HASH=${{ steps.gpu-base-hash.outputs.hash }}
provenance: false
- name: Build and push GPU app image
timeout-minutes: 10
uses: docker/build-push-action@v6
with:
context: .
file: backend/Dockerfile
push: true
tags: |
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:latest
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:${{ github.sha }}
${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:v${{ steps.version_check.outputs.version }}
build-args: |
BASE_IMAGE=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_BASE_IMAGE_NAME }}:latest
cache-from: type=registry,ref=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:cache,ignore-error=true
cache-to: type=registry,ref=${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:cache,mode=max,ignore-error=true
provenance: false
# ============================================
# Deploy to Cloud Run
# ============================================
@@ -1305,33 +1599,48 @@ jobs:
--region us-central1 \
--platform managed \
--allow-unauthenticated \
--memory 16Gi \
--cpu 8 \
--memory 2Gi \
--cpu 2 \
--cpu-boost \
--no-cpu-throttling \
--cpu-throttling \
--execution-environment gen2 \
--timeout 1800 \
--concurrency 1 \
--max-instances 50 \
--min-instances 4 \
--concurrency 80 \
--max-instances 20 \
--min-instances 1 \
--vpc-connector projects/nomadkaraoke/locations/us-central1/connectors/cloud-run-connector \
--vpc-egress private-ranges-only \
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,AUDIO_SEPARATOR_API_URL=https://nomadkaraoke--audio-separator-api.modal.run,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true" \
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
--set-secrets "AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,SENDGRID_API_KEY=sendgrid-api-key:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest"
- name: Update Cloud Run Jobs with new image
run: |
IMAGE="${{ env.REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.APP_IMAGE_NAME }}:${{ github.sha }}"
GPU_IMAGE="${{ env.GPU_REGISTRY }}/${{ env.PROJECT_ID }}/${{ env.GPU_REPOSITORY }}/${{ env.GPU_APP_IMAGE_NAME }}:${{ github.sha }}"
echo "📦 Updating Cloud Run Jobs to image: $IMAGE"
echo "📦 Updating Cloud Run Jobs..."
# Video encoding job - runs video worker to completion, immune to service deployments
# Video encoding job (CPU, us-central1)
gcloud run jobs update video-encoding-job \
--image "$IMAGE" \
--region us-central1 \
--project ${{ env.PROJECT_ID }} \
--quiet
# Lyrics transcription job (CPU, us-central1)
gcloud run jobs update lyrics-transcription-job \
--image "$IMAGE" \
--region us-central1 \
--project ${{ env.PROJECT_ID }} \
--quiet
# Audio separation job (GPU, us-east4) — uses GPU image
gcloud run jobs update audio-separation-job \
--image "$GPU_IMAGE" \
--region us-east4 \
--project ${{ env.PROJECT_ID }} \
--quiet
echo "✅ Cloud Run Jobs updated"
- name: Verify deployment and version
+10
View File
@@ -67,6 +67,16 @@ jobs:
working-directory: frontend
run: mkdir -p test-results
- name: Ensure testmail.app domain is allowlisted
run: |
# testmail.app is used for E2E testing but gets flagged as disposable
# by external APIs. Ensure it's in the allowlist before the test runs.
curl -sf -X POST \
"https://api.nomadkaraoke.com/api/admin/rate-limits/blocklists/allowlisted-domains" \
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
-H "Content-Type: application/json" \
-d '{"domain": "inbox.testmail.app"}' || echo "Warning: failed to allowlist domain (may already exist)"
- name: Refresh E2E session token (when use_test_token enabled)
id: refresh_token
if: inputs.use_test_token == true
+1
View File
@@ -232,3 +232,4 @@ flacfetch
# Test output directories
Rick Astley*/
.superpowers/
+1
View File
@@ -0,0 +1 @@
[{"name":"generate-buildid","duration":272,"timestamp":244518298649,"id":4,"parentId":1,"tags":{},"startTime":1775262331361,"traceId":"b3ef0d179e8acedf"},{"name":"load-custom-routes","duration":314,"timestamp":244518299029,"id":5,"parentId":1,"tags":{},"startTime":1775262331361,"traceId":"b3ef0d179e8acedf"},{"name":"create-dist-dir","duration":333,"timestamp":244518299363,"id":6,"parentId":1,"tags":{},"startTime":1775262331362,"traceId":"b3ef0d179e8acedf"},{"name":"clean","duration":358,"timestamp":244518300558,"id":7,"parentId":1,"tags":{},"startTime":1775262331363,"traceId":"b3ef0d179e8acedf"},{"name":"next-build","duration":1670851,"timestamp":244516630180,"id":1,"tags":{"buildMode":"default","version":"16.2.2","bundler":"turbopack","failed":true},"startTime":1775262329693,"traceId":"b3ef0d179e8acedf"}]
+1
View File
@@ -0,0 +1 @@
[{"name":"next-build","duration":1670851,"timestamp":244516630180,"id":1,"tags":{"buildMode":"default","version":"16.2.2","bundler":"turbopack","failed":true},"startTime":1775262329693,"traceId":"b3ef0d179e8acedf"}]
+1 -1
View File
@@ -28,7 +28,7 @@
- **Backend**: FastAPI on Cloud Run, Firestore, GCS, Secret Manager
- **Frontend**: Next.js on Cloudflare Pages
- **Processing**: Modal (GPU audio separation), AudioShake/Whisper (transcription)
- **Processing**: Cloud Run GPU (L4 audio separation), AudioShake/Whisper (transcription)
- **Infra**: Pulumi IaC, GitHub Actions CI/CD
## Essential Rules
+10 -4
View File
@@ -13,7 +13,8 @@ help:
@echo "Available commands:"
@echo " make test - Run ALL tests (backend + frontend, installs deps automatically)"
@echo " make test-backend - Run backend tests only (unit + emulator)"
@echo " make test-frontend - Run frontend tests only (unit + E2E)"
@echo " make test-frontend - Run frontend unit tests (Jest)"
@echo " make test-frontend-e2e - Run frontend E2E tests (Playwright, requires dev server)"
@echo " make test-unit - Run unit tests only (karaoke_gen package)"
@echo " make test-e2e - Run emulator tests with auto-start/stop"
@echo " make install - Install all dependencies (backend + frontend)"
@@ -89,10 +90,15 @@ test-backend: test-unit test-backend-unit test-e2e
@echo ""
@echo "✅ Backend tests passed!"
# Run frontend tests (unit + E2E)
# Run frontend unit tests (Jest only - E2E requires manual setup)
test-frontend: install-frontend
@echo "=== Running frontend tests ==="
cd frontend && timeout $(TEST_TIMEOUT) npm run test:all
@echo "=== Running frontend unit tests ==="
cd frontend && timeout $(TEST_TIMEOUT) npm run test:unit
# Run frontend E2E tests (requires dev server - run manually, not in make test)
test-frontend-e2e: install-frontend
@echo "=== Running frontend E2E tests ==="
cd frontend && timeout $(TEST_TIMEOUT) npm run test:e2e
# Run ALL tests (backend + frontend) - use this before committing!
test: test-backend test-frontend
+9 -1
View File
@@ -26,7 +26,15 @@ COPY backend /app/backend
# Note: lyrics_transcriber is now a subpackage of karaoke_gen
COPY karaoke_gen /app/karaoke_gen
COPY pyproject.toml README.md LICENSE /app/
RUN pip install --no-cache-dir -e .
# GPU images (MODEL_DIR set in base): use --no-deps to preserve pinned torch cu126
# and audio-separator[gpu]. Without this, pip upgrades torch to cu130 (breaks CUDA
# on Cloud Run L4 drivers) and reinstalls audio-separator[cpu] (breaks GPU ONNX).
# CPU images: normal install resolves all deps from pyproject.toml.
RUN if [ -n "$MODEL_DIR" ]; then \
pip install --no-cache-dir --no-deps -e .; \
else \
pip install --no-cache-dir -e .; \
fi
# Set environment variables
ENV PYTHONUNBUFFERED=1
+136
View File
@@ -0,0 +1,136 @@
# GPU base image with CUDA, PyTorch, audio-separator, and pre-downloaded models
# This image is rebuilt only when deps or models change (infrequently).
#
# Build with: gcloud builds submit --config=backend/cloudbuild-gpu-base.yaml --project=nomadkaraoke --timeout=3600s
# Or manually: docker build -f backend/Dockerfile.gpu-base -t karaoke-backend-gpu-base .
#
# Layer caching strategy:
# 1. System deps + fonts + ffmpeg (rarely change, always cached)
# 2. CUDA library path configuration
# 3. pyproject.toml + package stubs (changes with dep updates)
# 4. pip install karaoke-gen deps + audio-separator[gpu] (slow, cached unless pyproject.toml changes)
# 5. Source code copy (changes every rebuild, but AFTER deps are installed)
# 6. spaCy model download (cached unless pip install layer changes)
# 7. Pre-downloaded ensemble preset models (~1-1.5 GB, cached unless pip layer changes)
FROM nvidia/cuda:12.6.3-runtime-ubuntu22.04
# Prevent interactive prompts during package installation
ENV DEBIAN_FRONTEND=noninteractive
# Install Python 3.11 from deadsnakes PPA and system dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
software-properties-common \
&& add-apt-repository -y ppa:deadsnakes/ppa \
&& apt-get update && apt-get install -y --no-install-recommends \
# Python 3.11
python3.11 \
python3.11-dev \
python3.11-venv \
# Audio libraries
libsndfile1 \
libsox-dev \
sox \
# Build tools
build-essential \
# Utilities
curl \
xz-utils \
&& rm -rf /var/lib/apt/lists/* \
&& python3.11 --version
# Install comprehensive font support for international lyrics and symbols
# Noto fonts provide full Unicode coverage including:
# - Latin, Greek, Cyrillic (core)
# - CJK: Chinese, Japanese, Korean (~150MB)
# - Arabic, Hebrew, Thai, Hindi, and other scripts (extra)
# - Color emoji (limited support in libass, but available)
# - Musical symbols (♪ ♫ etc.)
# Note: This adds ~200-300MB to the image but ensures all languages render correctly
RUN apt-get update && apt-get install -y --no-install-recommends \
fonts-noto-core \
fonts-noto-cjk \
fonts-noto-extra \
fonts-noto-color-emoji \
fontconfig \
&& fc-cache -f \
&& rm -rf /var/lib/apt/lists/*
# Install FFmpeg from Ubuntu package
# The audio worker only uses FFmpeg for format conversion and padding, not
# encoding-intensive tasks, so the Debian package is sufficient. The static
# build from johnvansickle.com is used for the encoding worker instead.
RUN apt-get update && apt-get install -y ffmpeg && rm -rf /var/lib/apt/lists/*
# Set Python 3.11 as default and install pip
RUN update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.11 1 \
&& update-alternatives --install /usr/bin/python python /usr/bin/python3.11 1 \
&& curl -sS https://bootstrap.pypa.io/get-pip.py | python3.11 \
&& python3 -m pip install --no-cache-dir --upgrade pip setuptools wheel
# Set up CUDA library paths so GPU-accelerated packages can find CUDA libs at runtime
RUN echo '/usr/local/cuda/lib64' >> /etc/ld.so.conf.d/cuda.conf && ldconfig
# Environment configuration for CUDA and Python
ENV LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH \
PATH=/usr/local/cuda/bin:$PATH \
PYTHONUNBUFFERED=1 \
MODEL_DIR=/models
# Set working directory
WORKDIR /app
# Copy ONLY dependency specification files first (changes less often than source code)
COPY pyproject.toml README.md LICENSE /app/
# Create minimal package stubs so pip can resolve the editable install
# pip install -e . needs package directories to exist but doesn't validate content
RUN mkdir -p /app/karaoke_gen /app/lyrics_transcriber_temp /app/backend && \
touch /app/karaoke_gen/__init__.py /app/lyrics_transcriber_temp/__init__.py /app/backend/__init__.py
# Install all karaoke-gen Python dependencies (the slow part)
# BuildKit cache mount preserves downloaded wheels across builds
RUN --mount=type=cache,target=/root/.cache/pip \
pip install --upgrade pip && \
pip install -e .
# Install audio-separator with GPU support (PyTorch + CUDA + onnxruntime-gpu)
# This is separate from pip install -e . to keep layer caching granular
#
# IMPORTANT: Install PyTorch cu126 FIRST, then audio-separator[gpu].
# The default audio-separator[gpu] pulls PyTorch cu130, but Cloud Run L4 GPUs
# have NVIDIA driver 570 which only supports up to CUDA 12.8. PyTorch cu130
# fails with "NVIDIA driver is too old". PyTorch cu126 works with 12.8 drivers.
# Installing torch first means audio-separator[gpu] sees it as already satisfied.
RUN --mount=type=cache,target=/root/.cache/pip \
pip install torch==2.6.0+cu126 torchvision==0.21.0+cu126 --index-url https://download.pytorch.org/whl/cu126 && \
pip install "audio-separator[gpu]"
# Now copy actual source code (AFTER deps installed, so code changes don't
# invalidate the expensive pip install layer in registry cache)
COPY karaoke_gen /app/karaoke_gen
COPY lyrics_transcriber_temp /app/lyrics_transcriber_temp
COPY backend /app/backend
# Download spaCy language model for lyrics transcription
# Must be done at build time, not runtime (Cloud Run network restrictions)
RUN python -m spacy download en_core_web_sm
# Create models directory and pre-download ensemble preset models
# Baking models into the image eliminates cold-start model download latency.
# Total model size: ~1-1.5 GB for instrumental_clean + karaoke presets.
RUN mkdir -p /models
COPY backend/scripts/download_models.py /tmp/download_models.py
RUN python /tmp/download_models.py /models && \
rm /tmp/download_models.py && \
ls -lh /models/
# Label with build info
ARG BUILD_DATE
ARG BUILD_ID
ARG BASE_CONTENT_HASH
LABEL org.opencontainers.image.created="${BUILD_DATE}"
LABEL org.opencontainers.image.revision="${BUILD_ID}"
LABEL org.opencontainers.image.title="karaoke-backend-gpu-base"
LABEL org.opencontainers.image.description="GPU base image with CUDA, PyTorch, audio-separator, and pre-downloaded models for karaoke-backend audio worker"
LABEL base.content.hash="${BASE_CONTENT_HASH}"
+422
View File
@@ -24,6 +24,7 @@ from backend.services.audio_search_service import get_audio_search_service, NoRe
from backend.models.job import JobStatus
from backend.services.firestore_service import log_to_job
from backend.utils.test_data import is_test_email
from backend.services.ip_geolocation_service import get_ip_geolocation_service
from karaoke_gen.utils import sanitize_filename
@@ -3528,3 +3529,424 @@ async def get_audio_edit_review_detail(
"original_audio_url": original_audio_url,
"current_audio_url": current_audio_url,
}
# =============================================================================
# Anti-Abuse Investigation
# =============================================================================
@router.get("/abuse/related/{email}")
async def find_related_accounts(
email: str,
auth_result: AuthResult = Depends(require_admin),
user_service: UserService = Depends(get_user_service),
):
"""
Find accounts related to the given email by shared signup IP or device fingerprint.
Returns the target user plus lists of other accounts from the same IP and/or fingerprint.
"""
result = user_service.find_related_accounts(email)
if not result["user"]:
raise HTTPException(status_code=404, detail="User not found")
user = result["user"]
return {
"user": {
"email": user.email,
"signup_ip": user.signup_ip,
"device_fingerprint": user.device_fingerprint,
"credits": user.credits,
"total_jobs_created": user.total_jobs_created,
"total_spent": user.total_spent,
"created_at": str(user.created_at),
},
"related_by_ip": [
{
"email": u.email,
"credits": u.credits,
"total_jobs_created": u.total_jobs_created,
"total_spent": u.total_spent,
"created_at": str(u.created_at),
}
for u in result["by_ip"]
],
"related_by_fingerprint": [
{
"email": u.email,
"credits": u.credits,
"total_jobs_created": u.total_jobs_created,
"total_spent": u.total_spent,
"created_at": str(u.created_at),
}
for u in result["by_fingerprint"]
],
}
@router.get("/abuse/correlations")
async def find_account_correlations(
auth_result: AuthResult = Depends(require_admin),
user_service: UserService = Depends(get_user_service),
):
"""
Find clusters of accounts sharing the same device fingerprint or signup IP.
Returns fingerprint clusters (RED flag - near-certain multi-accounting) and
IP clusters (ORANGE flag - suspicious but could be shared network), sorted
by group size. Includes user agent data for additional correlation signal.
"""
result = user_service.find_account_correlations()
user_agents = result.get("user_agents", {})
def serialize_cluster_user(u, include_user_agent=True):
data = {
"email": u.email,
"signup_ip": u.signup_ip,
"device_fingerprint": u.device_fingerprint,
"credits": u.credits,
"total_jobs_created": u.total_jobs_created,
"total_jobs_completed": u.total_jobs_completed,
"total_spent": u.total_spent,
"created_at": str(u.created_at),
}
if include_user_agent:
data["user_agent"] = user_agents.get(u.email)
return data
return {
"fingerprint_clusters": [
{
"fingerprint": cluster["fingerprint"],
"count": len(cluster["users"]),
"users": [serialize_cluster_user(u) for u in cluster["users"]],
}
for cluster in result["fingerprint_clusters"]
],
"ip_clusters": [
{
"ip": cluster["ip"],
"count": len(cluster["users"]),
"users": [serialize_cluster_user(u) for u in cluster["users"]],
}
for cluster in result["ip_clusters"]
],
}
@router.get("/abuse/suspicious")
async def find_suspicious_accounts(
min_jobs: int = 2,
max_spend: int = 0,
auth_result: AuthResult = Depends(require_admin),
user_service: UserService = Depends(get_user_service),
):
"""
Find accounts with many jobs but no (or low) spend.
Detects potential free-credit abusers: people creating multiple accounts
to get welcome credits without ever paying.
Args:
min_jobs: Minimum jobs created to flag (default: 2)
max_spend: Maximum total_spent in cents (default: 0 = only free accounts)
"""
users = user_service.find_suspicious_accounts(min_jobs=min_jobs, max_spend=max_spend)
return {
"count": len(users),
"users": [
{
"email": u.email,
"signup_ip": u.signup_ip,
"device_fingerprint": u.device_fingerprint,
"credits": u.credits,
"total_jobs_created": u.total_jobs_created,
"total_jobs_completed": u.total_jobs_completed,
"total_spent": u.total_spent,
"has_submitted_feedback": u.has_submitted_feedback,
"created_at": str(u.created_at),
"last_login_at": str(u.last_login_at) if u.last_login_at else None,
}
for u in users
],
}
@router.get("/abuse/by-ip/{ip_address:path}")
async def find_users_by_ip(
ip_address: str,
auth_result: AuthResult = Depends(require_admin),
user_service: UserService = Depends(get_user_service),
):
"""Find all users who signed up from a specific IP address."""
users = user_service.find_users_by_signup_ip(ip_address)
return {
"ip_address": ip_address,
"count": len(users),
"users": [
{
"email": u.email,
"device_fingerprint": u.device_fingerprint,
"credits": u.credits,
"total_jobs_created": u.total_jobs_created,
"total_spent": u.total_spent,
"created_at": str(u.created_at),
}
for u in users
],
}
@router.get("/abuse/by-fingerprint/{fingerprint}")
async def find_users_by_fingerprint(
fingerprint: str,
auth_result: AuthResult = Depends(require_admin),
user_service: UserService = Depends(get_user_service),
):
"""Find all users who signed up with a specific device fingerprint."""
users = user_service.find_users_by_fingerprint(fingerprint)
return {
"device_fingerprint": fingerprint,
"count": len(users),
"users": [
{
"email": u.email,
"signup_ip": u.signup_ip,
"credits": u.credits,
"total_jobs_created": u.total_jobs_created,
"total_spent": u.total_spent,
"created_at": str(u.created_at),
}
for u in users
],
}
@router.post("/abuse/backfill-ips")
async def backfill_signup_ips(
auth_result: AuthResult = Depends(require_admin),
user_service: UserService = Depends(get_user_service),
):
"""
Backfill signup_ip for existing users from their earliest session or magic link.
One-time operation to populate signup_ip for users created before the field was added.
Only updates users who currently have signup_ip=None.
"""
from backend.services.user_service import SESSIONS_COLLECTION, MAGIC_LINKS_COLLECTION
from google.cloud.firestore_v1 import FieldFilter
db = user_service.db
updated = 0
skipped = 0
no_ip_found = 0
# Known bad IPs (load balancer / proxy IPs that aren't real client IPs)
BAD_IPS = {"169.254.169.126", "unknown", ""}
# Find all users without signup_ip or with a known-bad IP
users_query = db.collection(USERS_COLLECTION).stream()
for user_doc in users_query:
user_data = user_doc.to_dict()
current_ip = user_data.get("signup_ip")
if current_ip and current_ip not in BAD_IPS:
skipped += 1
continue
email = user_data.get("email", "")
if not email:
continue
ip = None
# Try sessions first (most reliable — created at verification)
# No order_by to avoid needing extra composite index; any IP is fine
sessions = (
db.collection(SESSIONS_COLLECTION)
.where(filter=FieldFilter("user_email", "==", email))
.limit(5)
.stream()
)
for session_doc in sessions:
session_data = session_doc.to_dict()
candidate_ip = session_data.get("ip_address")
if candidate_ip and candidate_ip not in BAD_IPS:
ip = candidate_ip
break
# Fallback: try magic links
if not ip:
links = (
db.collection(MAGIC_LINKS_COLLECTION)
.where(filter=FieldFilter("email", "==", email))
.limit(5)
.stream()
)
for link_doc in links:
link_data = link_doc.to_dict()
candidate_ip = link_data.get("ip_address")
if candidate_ip:
ip = candidate_ip
break
if ip:
user_doc.reference.update({"signup_ip": ip})
updated += 1
logger.info(f"Backfilled signup_ip for {email}: {ip}")
else:
# Clear bad IP if one was set (e.g., load balancer IP)
if current_ip and current_ip in BAD_IPS:
user_doc.reference.update({"signup_ip": None})
updated += 1
logger.info(f"Cleared bad signup_ip for {email}: {current_ip}")
else:
no_ip_found += 1
return {
"status": "success",
"updated": updated,
"skipped_already_set": skipped,
"no_ip_found": no_ip_found,
}
# =============================================================================
# IP Geolocation Lookup
# =============================================================================
class IpBatchRequest(BaseModel):
"""Request for batch IP geolocation lookup."""
ips: list[str]
@router.get("/abuse/ip-info/{ip_address:path}")
async def get_ip_info(
ip_address: str,
auth_result: AuthResult = Depends(require_admin),
):
"""Look up geolocation info for a single IP address."""
geo_service = get_ip_geolocation_service()
return geo_service.lookup_ip(ip_address)
@router.post("/abuse/ip-info/batch")
async def get_ip_info_batch(
request: IpBatchRequest,
auth_result: AuthResult = Depends(require_admin),
):
"""Look up geolocation info for multiple IP addresses."""
if len(request.ips) > 100:
raise HTTPException(status_code=400, detail="Maximum 100 IPs per batch request")
geo_service = get_ip_geolocation_service()
return geo_service.lookup_ips_batch(request.ips)
# =============================================================================
# User Feedback
# =============================================================================
class AdminFeedbackItem(BaseModel):
"""Single feedback submission for admin view."""
id: str
user_email: str
created_at: Optional[str] = None
overall_rating: int
ease_of_use_rating: int
lyrics_accuracy_rating: int
correction_experience_rating: int
what_went_well: Optional[str] = None
what_could_improve: Optional[str] = None
additional_comments: Optional[str] = None
would_recommend: bool = True
would_use_again: bool = True
class AdminFeedbackListResponse(BaseModel):
"""Paginated list of feedback submissions."""
items: List[AdminFeedbackItem]
total: int
offset: int
limit: int
has_more: bool
avg_overall_rating: Optional[float] = None
avg_ease_of_use_rating: Optional[float] = None
avg_lyrics_accuracy_rating: Optional[float] = None
avg_correction_experience_rating: Optional[float] = None
@router.get("/feedback", response_model=AdminFeedbackListResponse)
def list_user_feedback(
limit: int = 50,
offset: int = 0,
search: Optional[str] = None,
exclude_test: bool = False,
auth_result: AuthResult = Depends(require_admin),
):
"""List all user feedback submissions with pagination and search."""
limit = max(1, min(limit, 200))
offset = max(0, offset)
user_service = get_user_service()
db = user_service.db
items = []
for doc in db.collection("user_feedback").stream():
data = doc.to_dict()
email = data.get("user_email", "")
if exclude_test and is_test_email(email):
continue
if search and search.lower() not in email.lower():
continue
created_at = data.get("created_at")
if created_at is not None and hasattr(created_at, "isoformat"):
created_at = created_at.isoformat()
elif created_at is not None:
created_at = str(created_at)
items.append(AdminFeedbackItem(
id=data.get("id", doc.id),
user_email=email,
created_at=created_at,
overall_rating=data.get("overall_rating", 0),
ease_of_use_rating=data.get("ease_of_use_rating", 0),
lyrics_accuracy_rating=data.get("lyrics_accuracy_rating", 0),
correction_experience_rating=data.get("correction_experience_rating", 0),
what_went_well=data.get("what_went_well"),
what_could_improve=data.get("what_could_improve"),
additional_comments=data.get("additional_comments"),
would_recommend=data.get("would_recommend", True),
would_use_again=data.get("would_use_again", True),
))
# Sort by newest first
items.sort(key=lambda x: x.created_at or "", reverse=True)
# Compute aggregate stats
total = len(items)
avg_overall = sum(i.overall_rating for i in items) / total if total else None
avg_ease = sum(i.ease_of_use_rating for i in items) / total if total else None
avg_lyrics = sum(i.lyrics_accuracy_rating for i in items) / total if total else None
avg_correction = sum(i.correction_experience_rating for i in items) / total if total else None
paginated = items[offset:offset + limit]
return AdminFeedbackListResponse(
items=paginated,
total=total,
offset=offset,
limit=limit,
has_more=(offset + limit) < total,
avg_overall_rating=round(avg_overall, 2) if avg_overall is not None else None,
avg_ease_of_use_rating=round(avg_ease, 2) if avg_ease is not None else None,
avg_lyrics_accuracy_rating=round(avg_lyrics, 2) if avg_lyrics is not None else None,
avg_correction_experience_rating=round(avg_correction, 2) if avg_correction is not None else None,
)
+22 -10
View File
@@ -240,24 +240,24 @@ class AudioSelectResponse(BaseModel):
selected_provider: str
def extract_request_metadata(request: Request, created_from: str = "audio_search") -> Dict[str, Any]:
def extract_request_metadata(request: Request, created_from: str = "audio_search", auth_result=None) -> Dict[str, Any]:
"""Extract metadata from request for job tracking."""
headers = dict(request.headers)
client_ip = headers.get('x-forwarded-for', '').split(',')[0].strip()
if not client_ip and request.client:
client_ip = request.client.host
user_agent = headers.get('user-agent', '')
environment = headers.get('x-environment', '')
client_id = headers.get('x-client-id', '')
custom_headers = {}
for key, value in headers.items():
if key.lower().startswith('x-') and key.lower() not in ('x-forwarded-for', 'x-forwarded-proto', 'x-forwarded-host'):
custom_headers[key] = value
return {
metadata = {
'client_ip': client_ip,
'user_agent': user_agent,
'environment': environment,
@@ -267,6 +267,17 @@ def extract_request_metadata(request: Request, created_from: str = "audio_search
'custom_headers': custom_headers,
}
# Add auth context for abuse investigation and analytics
if auth_result is not None:
metadata['auth_method'] = getattr(auth_result, 'auth_method', None)
user_type = getattr(auth_result, 'user_type', None)
metadata['user_type'] = user_type.value if hasattr(user_type, 'value') else str(user_type) if user_type else None
remaining = getattr(auth_result, 'remaining_uses', None)
if remaining is not None:
metadata['credits_at_creation'] = remaining
return metadata
def _extract_gcs_path(filepath: str) -> str:
"""
@@ -633,8 +644,9 @@ async def search_audio(
}
)
# Extract request metadata
request_metadata = extract_request_metadata(request, created_from="audio_search")
# Extract request metadata (includes auth context + search query info)
request_metadata = extract_request_metadata(request, created_from="audio_search", auth_result=auth_result)
request_metadata['search_query'] = {'artist': body.artist, 'title': body.title}
# Apply default theme if none specified
# This ensures all karaoke videos use the Nomad theme by default
@@ -754,11 +766,11 @@ async def search_audio(
# Generate GCS path
if file_info.file_type == 'style_params':
gcs_path = f"uploads/{job_id}/style/style_params.json"
gcs_path = f"jobs/{job_id}/style/style_params.json"
else:
# style_intro_background -> intro_background, etc.
asset_key = file_info.file_type.replace('style_', '')
gcs_path = f"uploads/{job_id}/style/{asset_key}{ext}"
gcs_path = f"jobs/{job_id}/style/{asset_key}{ext}"
# Generate signed upload URL
signed_url = storage_service.generate_signed_upload_url(
+65
View File
@@ -0,0 +1,65 @@
"""
Encoding worker lifecycle endpoints.
Provides warmup and heartbeat endpoints for the blue-green
encoding worker VMs. Called by the frontend to ensure the
primary VM is running before encoding requests.
"""
import logging
from fastapi import APIRouter, Depends
from backend.api.dependencies import require_admin
from backend.services.encoding_worker_manager import EncodingWorkerManager
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/internal/encoding-worker", tags=["encoding-worker"])
# Lazy-loaded singleton
_manager = None
def get_worker_manager():
global _manager
if _manager is None:
from google.cloud import compute_v1, firestore
from backend.config import get_settings
settings = get_settings()
db = firestore.Client(project=settings.google_cloud_project)
compute_client = compute_v1.InstancesClient()
_manager = EncodingWorkerManager(
db=db,
compute_client=compute_client,
project_id=settings.google_cloud_project,
)
return _manager
@router.post("/warmup")
async def warmup_encoding_worker(
_admin=Depends(require_admin),
manager=Depends(get_worker_manager),
):
"""Start the primary encoding worker VM if it's stopped."""
try:
result = manager.ensure_primary_running()
if result["started"]:
logger.info(f"Started encoding worker VM: {result['vm_name']}")
return result
except Exception as e:
logger.error(f"Failed to warm up encoding worker: {e}")
return {"started": False, "error": str(e)}
@router.post("/heartbeat")
async def heartbeat_encoding_worker(
_admin=Depends(require_admin),
manager=Depends(get_worker_manager),
):
"""Update activity timestamp to prevent idle shutdown."""
try:
manager.update_activity()
return {"status": "ok"}
except Exception as e:
logger.error(f"Failed to update encoding worker heartbeat: {e}")
return {"status": "error", "error": str(e)}
+38 -25
View File
@@ -268,10 +268,10 @@ storage_service = StorageService()
worker_service = get_worker_service()
def extract_request_metadata(request: Request, created_from: str = "upload") -> Dict[str, Any]:
def extract_request_metadata(request: Request, created_from: str = "upload", auth_result=None) -> Dict[str, Any]:
"""
Extract metadata from a FastAPI Request for job tracking.
Captures:
- Client IP address (handles X-Forwarded-For for proxies)
- User-Agent header
@@ -280,34 +280,36 @@ def extract_request_metadata(request: Request, created_from: str = "upload") ->
- All custom X-* headers
- Server version
- Creation source (upload/url)
- Auth context (method, user type) if auth_result provided
Args:
request: FastAPI Request object
created_from: How the job was created ("upload" or "url")
auth_result: Optional AuthResult from authentication
Returns:
Dict with metadata fields for storage in job.request_metadata
"""
headers = dict(request.headers)
# Extract client IP (check X-Forwarded-For for proxy scenarios)
client_ip = headers.get('x-forwarded-for', '').split(',')[0].strip()
if not client_ip and request.client:
client_ip = request.client.host
# Extract standard headers
user_agent = headers.get('user-agent', '')
environment = headers.get('x-environment', '') # test, production, development
client_id = headers.get('x-client-id', '') # Customer/user identifier
# Collect all X-* custom headers (excluding standard ones we already captured)
custom_headers = {}
for key, value in headers.items():
if key.lower().startswith('x-') and key.lower() not in ('x-forwarded-for', 'x-forwarded-proto', 'x-forwarded-host'):
# Normalize header name to original casing if possible
custom_headers[key] = value
return {
metadata = {
'client_ip': client_ip,
'user_agent': user_agent,
'environment': environment,
@@ -317,6 +319,17 @@ def extract_request_metadata(request: Request, created_from: str = "upload") ->
'custom_headers': custom_headers,
}
# Add auth context for abuse investigation and analytics
if auth_result is not None:
metadata['auth_method'] = getattr(auth_result, 'auth_method', None)
user_type = getattr(auth_result, 'user_type', None)
metadata['user_type'] = user_type.value if hasattr(user_type, 'value') else str(user_type) if user_type else None
remaining = getattr(auth_result, 'remaining_uses', None)
if remaining is not None:
metadata['credits_at_creation'] = remaining
return metadata
# File extension validation
ALLOWED_AUDIO_EXTENSIONS = {'.mp3', '.wav', '.flac', '.m4a', '.ogg', '.aac'}
@@ -564,7 +577,7 @@ async def upload_and_create_job(
)
# Extract request metadata for tracking and filtering
request_metadata = extract_request_metadata(request, created_from="upload")
request_metadata = extract_request_metadata(request, created_from="upload", auth_result=auth_result)
# Parse color_overrides from JSON if provided
parsed_color_overrides: Dict[str, str] = {}
@@ -709,7 +722,7 @@ async def upload_and_create_job(
# Upload style files if provided
if style_params:
style_gcs_path = f"uploads/{job_id}/style/style_params.json"
style_gcs_path = f"jobs/{job_id}/style/style_params.json"
logger.info(f"Uploading style params to GCS: {style_gcs_path}")
storage_service.upload_fileobj(
style_params.file,
@@ -728,7 +741,7 @@ async def upload_and_create_job(
(style_cdg_outro_background, "cdg_outro_background"),
]:
if img_file:
gcs_path = f"uploads/{job_id}/style/{asset_key}{Path(img_file.filename).suffix.lower()}"
gcs_path = f"jobs/{job_id}/style/{asset_key}{Path(img_file.filename).suffix.lower()}"
logger.info(f"Uploading {asset_key} to GCS: {gcs_path}")
storage_service.upload_fileobj(
img_file.file,
@@ -739,7 +752,7 @@ async def upload_and_create_job(
# Upload font file
if style_font:
font_gcs_path = f"uploads/{job_id}/style/font{Path(style_font.filename).suffix.lower()}"
font_gcs_path = f"jobs/{job_id}/style/font{Path(style_font.filename).suffix.lower()}"
logger.info(f"Uploading font to GCS: {font_gcs_path}")
storage_service.upload_fileobj(
style_font.file,
@@ -1063,11 +1076,11 @@ def _get_gcs_path_for_file(job_id: str, file_type: str, filename: str) -> str:
if file_type == 'audio':
return f"uploads/{job_id}/audio/{filename}"
elif file_type == 'style_params':
return f"uploads/{job_id}/style/style_params.json"
return f"jobs/{job_id}/style/style_params.json"
elif file_type.startswith('style_'):
# Map style_intro_background -> intro_background, etc.
asset_key = file_type.replace('style_', '')
return f"uploads/{job_id}/style/{asset_key}{ext}"
return f"jobs/{job_id}/style/{asset_key}{ext}"
elif file_type == 'lyrics_file':
return f"uploads/{job_id}/lyrics/user_lyrics{ext}"
elif file_type == 'existing_instrumental':
@@ -1195,7 +1208,7 @@ async def create_job_with_upload_urls(
)
# Extract request metadata for tracking
request_metadata = extract_request_metadata(request, created_from="signed_url_upload")
request_metadata = extract_request_metadata(request, created_from="signed_url_upload", auth_result=auth_result)
# Get original audio filename
audio_file = audio_files[0]
@@ -1360,10 +1373,10 @@ async def mark_uploads_complete(
if file_type == 'audio':
prefix = f"uploads/{job_id}/audio/"
elif file_type == 'style_params':
prefix = f"uploads/{job_id}/style/style_params"
prefix = f"jobs/{job_id}/style/style_params"
elif file_type.startswith('style_'):
asset_key = file_type.replace('style_', '')
prefix = f"uploads/{job_id}/style/{asset_key}"
prefix = f"jobs/{job_id}/style/{asset_key}"
elif file_type == 'lyrics_file':
prefix = f"uploads/{job_id}/lyrics/user_lyrics"
elif file_type == 'existing_instrumental':
@@ -1663,7 +1676,7 @@ async def create_job_from_url(
)
# Extract request metadata for tracking
request_metadata = extract_request_metadata(request, created_from="url")
request_metadata = extract_request_metadata(request, created_from="url", auth_result=auth_result)
# Use provided artist/title or leave as None (will be auto-detected by audio worker)
artist = body.artist
@@ -1857,7 +1870,7 @@ def _get_gcs_path_for_finalise_file(job_id: str, file_type: str, filename: str)
elif file_type == 'corrections':
return f"jobs/{job_id}/lyrics/corrections.json"
elif file_type == 'style_params':
return f"uploads/{job_id}/style/style_params.json"
return f"jobs/{job_id}/style/style_params.json"
else:
return f"uploads/{job_id}/other/{filename}"
@@ -1983,7 +1996,7 @@ async def create_finalise_only_job(
)
# Extract request metadata
request_metadata = extract_request_metadata(request, created_from="finalise_only_upload")
request_metadata = extract_request_metadata(request, created_from="finalise_only_upload", auth_result=auth_result)
# Apply default theme if none specified
# This ensures all karaoke videos use the Nomad theme by default
@@ -2189,7 +2202,7 @@ async def mark_finalise_uploads_complete(
elif file_type == 'corrections':
prefix = f"jobs/{job_id}/lyrics/corrections"
elif file_type == 'style_params':
prefix = f"uploads/{job_id}/style/style_params"
prefix = f"jobs/{job_id}/style/style_params"
else:
continue
@@ -2442,7 +2455,7 @@ async def complete_style_uploads(
continue
asset_key = file_type.replace('style_', '')
prefix = f"uploads/{job_id}/style/{asset_key}"
prefix = f"jobs/{job_id}/style/{asset_key}"
files = storage_service.list_files(prefix)
if not files:
raise HTTPException(
@@ -2473,7 +2486,7 @@ async def complete_style_uploads(
# Overwrite background paths with custom uploads
for asset_key, gcs_path in new_style_assets.items():
bucket_name = storage_service.bucket_name
bucket_name = storage_service.bucket.name
gcs_uri = f"gs://{bucket_name}/{gcs_path}"
if asset_key == "intro_background" and "intro" in style_params:
style_params["intro"]["background_image"] = gcs_uri
@@ -2483,7 +2496,7 @@ async def complete_style_uploads(
style_params["end"]["background_image"] = gcs_uri
# Upload updated style_params.json
style_params_path = f"uploads/{job_id}/style/style_params.json"
style_params_path = f"jobs/{job_id}/style/style_params.json"
storage_service.upload_json(style_params_path, style_params)
update_data["style_params_gcs_path"] = style_params_path
+174 -3
View File
@@ -5,10 +5,12 @@ import os
import logging
import subprocess
import platform
from fastapi import APIRouter
from typing import Dict, Any, Optional
from fastapi import APIRouter, Depends
from typing import Dict, Any, Optional, Tuple
from backend.version import VERSION
from backend.version import VERSION, COMMIT_SHA, PR_NUMBER, PR_TITLE, STARTUP_TIME
from backend.api.dependencies import optional_auth
from backend.services.auth_service import UserType
from backend.services.flacfetch_client import get_flacfetch_client
from backend.services.email_service import get_email_service
from backend.services.stripe_service import get_stripe_service
@@ -308,6 +310,175 @@ async def flacfetch_health() -> Dict[str, Any]:
}
def check_audio_separator_status() -> Dict[str, Any]:
"""Check audio separator availability without calling the remote GPU service."""
from backend.config import get_settings
settings = get_settings()
if not settings.audio_separator_api_url:
return {
"available": False,
"status": "not_configured",
}
try:
from importlib.metadata import version
pkg_version = version("audio-separator")
except Exception:
pkg_version = None
return {
"available": True,
"status": "ok",
"version": pkg_version,
}
@router.get("/health/audio-separator")
async def audio_separator_health() -> Dict[str, Any]:
"""
Return the installed audio-separator package version.
Does NOT call the remote GPU service — that would cold-start an expensive
Cloud Run GPU instance (~$0.07 per wake). Instead reports the locally
installed package version, which matches what the audio worker uses.
No authentication required.
"""
from backend.config import get_settings
settings = get_settings()
if not settings.audio_separator_api_url:
return {
"available": False,
"status": "not_configured",
}
try:
from importlib.metadata import version
pkg_version = version("audio-separator")
except Exception:
pkg_version = None
return {
"available": True,
"status": "ok",
"version": pkg_version,
}
def _get_encoding_worker_manager():
"""Get the EncodingWorkerManager instance. Separated for testability."""
try:
encoding_service = get_encoding_service()
if hasattr(encoding_service, '_worker_manager') and encoding_service._worker_manager:
return encoding_service._worker_manager
except Exception:
pass
return None
@router.get("/health/system-status")
async def system_status(
auth: Optional[Tuple] = Depends(optional_auth),
) -> Dict[str, Any]:
"""
Aggregated system status for all services.
Returns basic info for everyone. Admin users get additional
blue-green deployment details for the encoder.
"""
is_admin = auth is not None and len(auth) >= 2 and auth[1] == UserType.ADMIN
# Fetch all health statuses concurrently
import asyncio
encoding_task = check_encoding_worker_status()
flacfetch_task = check_flacfetch_service_status()
encoding_status, flacfetch_status = await asyncio.gather(
encoding_task, flacfetch_task
)
separator_status = check_audio_separator_status()
# Build frontend service info (from env vars baked at build time — returned as-is)
frontend_svc = {
"status": "ok",
"version": VERSION, # Frontend and backend share the same version from pyproject.toml
}
# Build backend service info
backend_svc = {
"status": "ok",
"version": VERSION,
"deployed_at": STARTUP_TIME,
}
if COMMIT_SHA:
backend_svc["commit_sha"] = COMMIT_SHA
if PR_NUMBER:
backend_svc["pr_number"] = PR_NUMBER
if PR_TITLE:
backend_svc["pr_title"] = PR_TITLE
# Build encoder service info
encoder_svc = {
"status": "ok" if encoding_status.get("available") else "offline",
"version": encoding_status.get("wheel_version"),
"active_jobs": encoding_status.get("active_jobs", 0),
}
# Build flacfetch service info
flacfetch_svc = {
"status": "ok" if flacfetch_status.get("available") else "offline",
"version": flacfetch_status.get("version"),
}
# Build separator service info
separator_svc = {
"status": "ok" if separator_status.get("available") else "offline",
"version": separator_status.get("version"),
}
# Admin-only: blue-green encoder details from Firestore
if is_admin:
manager = _get_encoding_worker_manager()
if manager:
try:
config = manager.get_config()
encoder_svc["admin_details"] = {
"primary_vm": config.primary_vm,
"primary_ip": config.primary_ip,
"primary_version": config.primary_version,
"primary_deployed_at": config.primary_deployed_at,
"secondary_vm": config.secondary_vm,
"secondary_ip": config.secondary_ip,
"secondary_version": config.secondary_version,
"secondary_deployed_at": config.secondary_deployed_at,
"last_swap_at": config.last_swap_at,
"deploy_in_progress": config.deploy_in_progress,
"active_jobs": encoding_status.get("active_jobs", 0),
"queue_length": encoding_status.get("queue_length", 0),
}
except Exception as e:
logger.warning(f"Failed to get blue-green config: {e}")
# Add error details for offline services
if not flacfetch_status.get("available"):
flacfetch_svc["admin_details"] = {"error": flacfetch_status.get("error")}
if not separator_status.get("available"):
separator_svc["admin_details"] = {"error": separator_status.get("error")}
if not encoding_status.get("available") and "admin_details" not in encoder_svc:
encoder_svc["admin_details"] = {"error": encoding_status.get("error")}
return {
"services": {
"frontend": frontend_svc,
"backend": backend_svc,
"encoder": encoder_svc,
"flacfetch": flacfetch_svc,
"separator": separator_svc,
}
}
@router.get("/health/detailed")
async def detailed_health_check() -> Dict[str, Any]:
"""
+76 -1
View File
@@ -25,7 +25,7 @@ from backend.workers.screens_worker import generate_screens
from backend.workers.video_worker import generate_video
from backend.workers.render_video_worker import process_render_video
from backend.api.dependencies import require_admin
from backend.services.auth_service import UserType
from backend.services.auth_service import AuthResult, UserType
from backend.services.job_manager import JobManager
from backend.services.tracing import (
extract_trace_context,
@@ -76,6 +76,18 @@ def _check_worker_idempotency(job_id: str, worker_name: str) -> Optional[WorkerR
message=f"Job {job_id} not found"
)
# Reject workers for jobs in terminal states (failed, cancelled, complete)
# This prevents Cloud Tasks retries from triggering workers on dead jobs
terminal_statuses = {'failed', 'cancelled', 'complete', 'prep_complete', 'error'}
job_status = job.status.value if hasattr(job.status, 'value') else str(job.status)
if job_status in terminal_statuses:
logger.info(f"[job:{job_id}] Job in terminal state '{job_status}', skipping {worker_name} worker")
return WorkerResponse(
status="skipped",
job_id=job_id,
message=f"Job is in terminal state '{job_status}', {worker_name} worker not needed"
)
# Check worker-specific progress in state_data
progress_key = f"{worker_name}_progress"
worker_progress = job.state_data.get(progress_key, {})
@@ -102,6 +114,31 @@ def _check_worker_idempotency(job_id: str, worker_name: str) -> Optional[WorkerR
return None
@router.post("/sync-disposable-domains", response_model=WorkerResponse)
async def sync_disposable_domains_endpoint(
request: Request,
auth_result: AuthResult = Depends(require_admin),
):
"""Sync external disposable domain blocklist. Called by Cloud Scheduler daily."""
import asyncio
from backend.services.disposable_domain_sync_service import (
fetch_external_blocklist, sync_disposable_domains
)
from backend.services.firestore_service import get_firestore_client
from backend.services.email_validation_service import EmailValidationService
domains = await fetch_external_blocklist()
db = get_firestore_client()
result = await asyncio.to_thread(sync_disposable_domains, db, domains)
EmailValidationService._blocklist_cache = None
return WorkerResponse(
status="completed",
job_id="sync-disposable-domains",
message=f"Synced {result['external_count']} domains"
)
@router.post("/workers/audio", response_model=WorkerResponse)
async def trigger_audio_worker(
request: WorkerRequest,
@@ -468,6 +505,44 @@ async def process_youtube_upload_queue(
}
@router.post("/process-stale-reviews")
async def process_stale_reviews_endpoint(
http_request: Request,
background_tasks: BackgroundTasks,
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
):
"""
Process stale review jobs — send reminders and expire old ones.
Called by Cloud Scheduler (hourly). Can also be triggered manually
from the admin dashboard.
- Jobs in review for >= 24h get a reminder email
- Jobs in review for >= 48h are auto-cancelled with credit refund
"""
from backend.workers.stale_review_processor import process_stale_reviews
trace_context = extract_trace_context(dict(http_request.headers))
logger.info("STALE_REVIEW_PROCESS starting")
add_span_attribute("operation", "stale_review_process")
async def _process():
try:
result = await process_stale_reviews()
logger.info(f"STALE_REVIEW_PROCESS complete: {result}")
except Exception as e:
logger.exception(f"STALE_REVIEW_PROCESS failed: {e}")
background_tasks.add_task(_process)
add_span_event("stale_review_processing_started")
return {
"status": "started",
"message": "Stale review processing started in background"
}
@router.post("/trigger-gdrive-validation")
async def trigger_gdrive_validation_endpoint(
http_request: Request,
+105 -25
View File
@@ -18,6 +18,7 @@ from typing import List, Optional, Dict, Any
from fastapi import APIRouter, HTTPException, BackgroundTasks, Depends, Request, UploadFile, File
from datetime import datetime
from backend.utils.request_helpers import get_client_ip
from backend.models.job import Job, JobCreate, JobResponse, JobStatus
from backend.models.requests import (
URLSubmissionRequest,
@@ -70,6 +71,7 @@ async def _trigger_workers_parallel(job_id: str) -> None:
@router.post("", response_model=JobResponse)
async def create_job(
request: URLSubmissionRequest,
http_request: Request,
background_tasks: BackgroundTasks,
auth_result: AuthResult = Depends(require_auth)
) -> JobResponse:
@@ -132,6 +134,11 @@ async def create_job(
)
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
# Store client IP on job for anti-abuse correlation
creation_ip = get_client_ip(http_request)
if creation_ip:
FirestoreService().update_job(job.job_id, {"creation_ip": creation_ip})
# Trace attributes for observability
add_span_attribute("job_id", job.job_id)
add_span_attribute("job.source", "url")
@@ -512,7 +519,7 @@ _SUMMARY_STATE_DATA_KEYS = {
'backing_vocals_analysis', 'visibility_change_in_progress',
}
_SUMMARY_FILE_URLS_KEYS = {'finals', 'videos', 'packages'}
_HIDE_COMPLETED_STATUSES = ['complete', 'prep_complete']
_HIDE_COMPLETED_STATUSES = ['complete', 'prep_complete', 'cancelled']
def _prune_state_data(data: Dict[str, Any]) -> Dict[str, Any]:
@@ -531,6 +538,21 @@ def _prune_file_urls(data: Dict[str, Any]) -> Dict[str, Any]:
return data
def _search_filter_jobs(jobs: List[Dict[str, Any]], search: str) -> List[Dict[str, Any]]:
"""Filter job dicts by case-insensitive substring match across key fields."""
if not search:
return jobs
term = search.lower()
results = []
for job in jobs:
searchable = " ".join(
str(job.get(f) or "") for f in ("job_id", "artist", "title", "audio_search_artist", "audio_search_title")
)
if term in searchable.lower():
results.append(job)
return results
@router.get("", response_model=None)
async def list_jobs(
request: Request,
@@ -543,6 +565,7 @@ async def list_jobs(
limit: int = 100,
fields: Optional[str] = None,
hide_completed: bool = False,
search: Optional[str] = None,
auth_result: AuthResult = Depends(require_auth)
):
"""
@@ -561,6 +584,7 @@ async def list_jobs(
limit: Maximum number of jobs to return (default 100)
fields: Set to "summary" for reduced payload with only dashboard-required fields
hide_completed: If True, exclude successful completions (complete, prep_complete). Failed jobs remain visible.
search: Text search filter - matches against artist, title, audio_search_artist, audio_search_title, and job_id (case-insensitive substring). Only works with fields=summary.
Returns:
List of jobs matching filters, ordered by created_at descending.
@@ -608,6 +632,8 @@ async def list_jobs(
# --- Summary mode: field-projected query returning dicts ---
if fields == "summary":
exclude_statuses = _HIDE_COMPLETED_STATUSES if hide_completed else None
# When searching, fetch more results and filter in Python
fetch_limit = 1000 if search else limit
jobs_dicts = job_manager.list_jobs_summary(
status=status,
exclude_statuses=exclude_statuses,
@@ -617,13 +643,18 @@ async def list_jobs(
created_before=created_before_dt,
user_email=user_email_filter,
tenant_id=effective_tenant_id,
limit=limit,
limit=fetch_limit,
)
# Exclude test user jobs (Python-side, same as full mode)
if exclude_test and auth_result.is_admin:
jobs_dicts = [j for j in jobs_dicts if not is_test_email(j.get('user_email') or "")]
# Apply search filter if provided
if search:
jobs_dicts = _search_filter_jobs(jobs_dicts, search)
jobs_dicts = jobs_dicts[:limit] # Apply original limit after filtering
# Safety-net pruning (in case Firestore returned extra nested keys)
jobs_dicts = [_prune_file_urls(_prune_state_data(j)) for j in jobs_dicts]
@@ -1277,6 +1308,26 @@ async def complete_review(
detail=f"Job not in review state (current status: {job.status})"
)
# Check for 0-segment lyrics — fail early with user-friendly message
# Only check when lyrics pipeline has run (lyrics_metadata exists in state_data)
state_data = job.state_data or {}
lyrics_metadata = state_data.get('lyrics_metadata')
if lyrics_metadata is not None:
segment_count = lyrics_metadata.get('segment_count', 0)
corrected_lyrics = state_data.get('corrected_lyrics', {})
corrected_segments = corrected_lyrics.get('corrected_segments', [])
if segment_count == 0 and len(corrected_segments) == 0:
raise HTTPException(
status_code=400,
detail=(
"Cannot complete review: no lyrics were detected in the audio. "
"This can happen when the input audio has no vocals (e.g. a karaoke track or instrumental). "
"You can go back and paste lyrics manually using 'Replace All', "
"or cancel this job and try again with an audio file that contains vocals."
)
)
try:
# Store instrumental selection if provided (combined review flow)
instrumental_selection = body.instrumental_selection if body else None
@@ -1396,18 +1447,12 @@ async def get_download_urls(
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to access this job")
if job.status != JobStatus.COMPLETE:
raise HTTPException(
status_code=400,
detail=f"Job not complete (current status: {job.status})"
)
file_urls = job.file_urls or {}
download_urls = {}
# Build download URLs using the streaming endpoint
base_url = f"/api/jobs/{job_id}/download"
for category, files in file_urls.items():
if isinstance(files, dict):
download_urls[category] = {}
@@ -1417,7 +1462,7 @@ async def get_download_urls(
elif isinstance(files, str) and files:
# For single-file categories, use the category name as the file_key
download_urls[category] = f"{base_url}/{category}/{category}"
return {
"job_id": job_id,
"artist": job.artist,
@@ -1434,7 +1479,8 @@ DOWNLOAD_FILENAME_SUFFIXES = {
"lossy_720p_mp4": " (Final Karaoke Lossy 720p).mp4",
"cdg_zip": " (Final Karaoke CDG).zip",
"txt_zip": " (Final Karaoke TXT).zip",
"with_vocals": " (With Vocals).mkv",
"with_vocals_mp4": " (With Vocals).mp4",
"with_vocals": " (With Vocals).mkv", # legacy: raw MKV from render step
}
@@ -1462,12 +1508,6 @@ async def download_file(
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to access this job")
if job.status != JobStatus.COMPLETE:
raise HTTPException(
status_code=400,
detail=f"Job not complete (current status: {job.status})"
)
file_urls = job.file_urls or {}
category_files = file_urls.get(category)
@@ -1665,11 +1705,14 @@ async def retry_job(
"retry_stage": "video_generation"
}
# If we have corrections and screens but no video, retry render
elif (file_urls.get('lyrics', {}).get('corrections') and
file_urls.get('screens', {}).get('title')):
logger.info(f"Job {job_id}: Has corrections and screens, retrying from render stage")
# If we have corrections, screens, AND review was completed, retry render
# Review completion is proven by instrumental_selection in state_data
# (set only when user submits the review endpoint)
elif (file_urls.get('lyrics', {}).get('corrections') and
file_urls.get('screens', {}).get('title') and
state_data.get('instrumental_selection')):
logger.info(f"Job {job_id}: Has corrections, screens, and completed review — retrying from render stage")
# Clear error state and reset worker progress for idempotency
job_manager.update_job(job_id, {
@@ -1689,16 +1732,48 @@ async def retry_job(
status_code=500,
detail="Failed to transition job status for retry"
)
# Trigger render video worker
background_tasks.add_task(worker_service.trigger_render_video_worker, job_id)
return {
"status": "success",
"job_status": "review_complete",
"message": "Job retry started from render stage",
"retry_stage": "render_video"
}
# If we have corrections and screens but review was NOT completed,
# return to awaiting_review so the user can review lyrics
elif (file_urls.get('lyrics', {}).get('corrections') and
file_urls.get('screens', {}).get('title')):
logger.info(f"Job {job_id}: Has corrections and screens but review not completed — returning to review")
# Clear error state
job_manager.update_job(job_id, {
'error_message': None,
'error_details': None,
})
# Transition to AWAITING_REVIEW so user can review lyrics
if not job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.AWAITING_REVIEW,
progress=55,
message=f"Ready for review. Please review lyrics and select your instrumental."
):
raise HTTPException(
status_code=500,
detail="Failed to transition job status for retry"
)
return {
"status": "success",
"job_status": "awaiting_review",
"message": "Job retry: returning to lyrics review (review was not completed before failure)",
"retry_stage": "awaiting_review"
}
# If we have stems and corrections, retry from screens generation
elif (file_urls.get('stems', {}).get('instrumental_clean') and
@@ -2234,6 +2309,11 @@ async def create_job_from_search(
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
job_id = job.job_id
# Store client IP on job for anti-abuse correlation
creation_ip = get_client_ip(request)
if creation_ip:
FirestoreService().update_job(job_id, {"creation_ip": creation_ip})
logger.info(f"Created job {job_id} from search session {body.search_session_id}")
# Trace attributes for observability
+62 -35
View File
@@ -49,12 +49,16 @@ class YouTubeQueueListResponse(BaseModel):
class BlocklistsResponse(BaseModel):
"""All blocklist data."""
disposable_domains: List[str]
"""All blocklist data with domain source separation."""
external_domains: List[str]
manual_domains: List[str]
allowlisted_domains: List[str]
blocked_emails: List[str]
blocked_ips: List[str]
updated_at: Optional[datetime]
updated_by: Optional[str]
last_sync_at: Optional[datetime] = None
last_sync_count: Optional[int] = None
updated_at: Optional[datetime] = None
updated_by: Optional[str] = None
class DomainRequest(BaseModel):
@@ -86,38 +90,10 @@ class SuccessResponse(BaseModel):
async def get_blocklists(
auth_result: AuthResult = Depends(require_admin),
):
"""
Get all blocklist data.
Returns disposable domains, blocked emails, and blocked IPs.
"""
"""Get all blocklist data with domain source separation."""
email_validation = get_email_validation_service()
# Force refresh to get latest data
config = email_validation.get_blocklist_config(force_refresh=True)
# Get the raw document for metadata
from google.cloud import firestore
from backend.services.firestore_service import get_firestore_client
from backend.services.email_validation_service import BLOCKLISTS_COLLECTION, BLOCKLIST_CONFIG_DOC
db = get_firestore_client()
doc = db.collection(BLOCKLISTS_COLLECTION).document(BLOCKLIST_CONFIG_DOC).get()
updated_at = None
updated_by = None
if doc.exists:
data = doc.to_dict()
updated_at = data.get("updated_at")
updated_by = data.get("updated_by")
return BlocklistsResponse(
disposable_domains=sorted(list(config["disposable_domains"])),
blocked_emails=sorted(list(config["blocked_emails"])),
blocked_ips=sorted(list(config["blocked_ips"])),
updated_at=updated_at,
updated_by=updated_by,
)
raw_data = email_validation.get_blocklist_raw_data()
return BlocklistsResponse(**raw_data)
@router.post("/blocklists/disposable-domains", response_model=SuccessResponse)
@@ -158,6 +134,57 @@ async def remove_disposable_domain(
)
@router.post("/blocklists/allowlisted-domains", response_model=SuccessResponse)
async def add_allowlisted_domain(
request: DomainRequest,
auth_result: AuthResult = Depends(require_admin),
):
"""Add a domain to the allowlist (overrides external blocklist)."""
email_validation = get_email_validation_service()
domain = request.domain.lower().strip()
if not domain or "." not in domain:
raise HTTPException(status_code=400, detail="Invalid domain format")
email_validation.add_allowlisted_domain(domain, auth_result.user_email)
return SuccessResponse(success=True, message=f"Domain '{domain}' added to allowlist")
@router.delete("/blocklists/allowlisted-domains/{domain}", response_model=SuccessResponse)
async def remove_allowlisted_domain(
domain: str,
auth_result: AuthResult = Depends(require_admin),
):
"""Remove a domain from the allowlist."""
email_validation = get_email_validation_service()
domain = domain.lower().strip()
if not email_validation.remove_allowlisted_domain(domain, auth_result.user_email):
raise HTTPException(status_code=404, detail="Domain not found in allowlist")
return SuccessResponse(success=True, message=f"Domain '{domain}' removed from allowlist")
@router.post("/blocklists/sync", response_model=SuccessResponse)
async def trigger_sync(
auth_result: AuthResult = Depends(require_admin),
):
"""Manually trigger a sync of the external disposable domain blocklist."""
import asyncio
from backend.services.disposable_domain_sync_service import (
fetch_external_blocklist, sync_disposable_domains
)
from backend.services.firestore_service import get_firestore_client
domains = await fetch_external_blocklist()
db = get_firestore_client()
result = await asyncio.to_thread(sync_disposable_domains, db, domains)
# Invalidate cache
EmailValidationService._blocklist_cache = None
return SuccessResponse(
success=True,
message=f"Synced {result['external_count']} external domains ({result['added']} added, {result['removed']} removed)"
)
@router.post("/blocklists/blocked-emails", response_model=SuccessResponse)
async def add_blocked_email(
request: EmailRequest,
+180 -21
View File
@@ -19,7 +19,7 @@ import json
import os
import tempfile
from pathlib import Path
from typing import Dict, Any, Set, Tuple
from typing import Dict, Any, List, Optional, Set, Tuple
from fastapi import APIRouter, HTTPException, Request, Depends
from fastapi.responses import FileResponse, RedirectResponse, StreamingResponse
@@ -331,12 +331,16 @@ async def complete_review(
# (it's stored separately in state_data)
corrections_to_save = {k: v for k, v in updated_data.items() if k != "instrumental_selection"}
# Save updated corrections to GCS
corrections_gcs_path = f"jobs/{job_id}/lyrics/corrections_updated.json"
storage.upload_json(corrections_gcs_path, corrections_to_save)
job_manager.update_file_url(job_id, 'lyrics', 'corrections_updated', corrections_gcs_path)
logger.info(f"Job {job_id}: Saved updated corrections")
# Only write corrections_updated.json if there's actual correction data.
# Writing an empty dict causes KeyError downstream when render workers
# try to access updated_data["corrections"].
if corrections_to_save and "corrections" in corrections_to_save:
corrections_gcs_path = f"jobs/{job_id}/lyrics/corrections_updated.json"
storage.upload_json(corrections_gcs_path, corrections_to_save)
job_manager.update_file_url(job_id, 'lyrics', 'corrections_updated', corrections_gcs_path)
logger.info(f"Job {job_id}: Saved updated corrections")
else:
logger.info(f"Job {job_id}: No corrections data in request, skipping corrections_updated.json")
# === Store instrumental selection in state_data ===
# This will be used by render_video_worker to skip AWAITING_INSTRUMENTAL_SELECTION
@@ -427,8 +431,10 @@ async def add_lyrics(
source = data.get("source", "").strip()
lyrics_text = data.get("lyrics", "").strip()
logger.info(f"Job {job_id}: Adding lyrics source '{source}' with {len(lyrics_text)} characters")
raw_force = data.get("force", False)
force = raw_force if isinstance(raw_force, bool) else str(raw_force).lower() == "true"
logger.info(f"Job {job_id}: Adding lyrics source '{source}' with {len(lyrics_text)} characters (force={force})")
# Use tracing and job_log_context for full observability
with create_span("add-lyrics", {"job_id": job_id, "source": source, "lyrics_length": len(lyrics_text)}) as span:
@@ -465,7 +471,8 @@ async def add_lyrics(
source=source,
lyrics_text=lyrics_text,
cache_dir=cache_dir,
logger=logger
logger=logger,
force=force,
)
add_span_event("correction_complete", {
"new_segments": len(updated_result.corrected_segments) if updated_result.corrected_segments else 0,
@@ -501,6 +508,151 @@ async def add_lyrics(
raise HTTPException(status_code=500, detail=f"Failed to add lyrics: {str(e)}")
@router.post("/{job_id}/search-lyrics")
async def search_lyrics(
job_id: str,
data: Dict[str, Any],
auth_info: Tuple[str, str] = Depends(require_review_auth)
):
"""
Search for lyrics using an alternate artist/title and rerun correction.
Queries all configured lyrics providers (Genius, Spotify, Musixmatch, LRCLIB)
with the supplied artist and title, then runs the correction pipeline (which
includes the relevance filter). Sources that pass the filter are added to the
job's corrections.json and returned to the frontend.
Request body:
artist (str): Artist name to search.
title (str): Song title to search.
force_sources (list[str], optional): Provider names whose results should
bypass the relevance filter.
Response:
200 {"status": "success", "data": {...CorrectionData...}, "sources_added": [...],
"sources_rejected": {...}, "sources_not_found": [...]}
200 {"status": "no_results", "message": "...", "sources_rejected": {...},
"sources_not_found": [...]}
400 on invalid request / wrong job state
500 on internal error
"""
job_manager = JobManager()
storage = StorageService()
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
raise HTTPException(
status_code=400,
detail=f"Job not in review state (current status: {job.status})"
)
artist = (data.get("artist") or "").strip()
title = (data.get("title") or "").strip()
force_sources: List[str] = data.get("force_sources") or []
if not artist or not title:
raise HTTPException(status_code=400, detail="artist and title are required")
logger.info(f"Job {job_id}: Searching lyrics for '{artist}' - '{title}' (force={force_sources})")
with create_span("search-lyrics", {"job_id": job_id, "artist": artist, "title": title}) as span:
with job_log_context(job_id, worker="search-lyrics"):
try:
with tempfile.TemporaryDirectory() as temp_dir:
# Download current corrections.json
with create_span("download-corrections") as download_span:
corrections_gcs = f"jobs/{job_id}/lyrics/corrections.json"
corrections_path = os.path.join(temp_dir, "corrections.json")
storage.download_file(corrections_gcs, corrections_path)
download_span.set_attribute("gcs_path", corrections_gcs)
with open(corrections_path, "r", encoding="utf-8") as f:
original_data = json.load(f)
correction_result = CorrectionResult.from_dict(original_data)
add_span_event("corrections_loaded", {
"segments": len(correction_result.corrected_segments) if correction_result.corrected_segments else 0,
"reference_sources": len(correction_result.reference_lyrics) if correction_result.reference_lyrics else 0,
})
cache_dir = os.path.join(temp_dir, "cache")
os.makedirs(cache_dir, exist_ok=True)
with create_span("correction-operations-search-lyrics") as correction_span:
correction_span.set_attribute("artist", artist)
correction_span.set_attribute("title", title)
search_result = CorrectionOperations.search_lyrics_sources(
correction_result=correction_result,
artist=artist,
title=title,
cache_dir=cache_dir,
force_sources=force_sources,
logger=logger,
)
sources_added = search_result["sources_added"]
sources_rejected = search_result["sources_rejected"]
sources_not_found = search_result["sources_not_found"]
updated_result = search_result["updated_result"]
if not sources_added or updated_result is None:
logger.info(
f"Job {job_id}: No valid lyrics found via search "
f"(rejected={list(sources_rejected.keys())}, not_found={sources_not_found})"
)
span.set_attribute("success", False)
return {
"status": "no_results",
"message": "No matching lyrics found from any provider",
"sources_added": [],
"sources_rejected": sources_rejected,
"sources_not_found": sources_not_found,
}
# Add audio hash / job metadata for the frontend
audio_hash = _get_audio_hash(job_id)
if not updated_result.metadata:
updated_result.metadata = {}
updated_result.metadata["audio_hash"] = audio_hash
updated_result.metadata["artist"] = job.artist
updated_result.metadata["title"] = job.title
# Upload updated corrections back to GCS
with create_span("upload-corrections") as upload_span:
updated_data = updated_result.to_dict()
storage.upload_json(corrections_gcs, updated_data)
upload_span.set_attribute("gcs_path", corrections_gcs)
logger.info(
f"Job {job_id}: Search complete — added={sources_added}, "
f"rejected={list(sources_rejected.keys())}, not_found={sources_not_found}"
)
span.set_attribute("success", True)
span.set_attribute("sources_added", len(sources_added))
return {
"status": "success",
"data": updated_data,
"sources_added": sources_added,
"sources_rejected": sources_rejected,
"sources_not_found": sources_not_found,
}
except HTTPException:
raise
except ValueError as e:
logger.warning(f"Job {job_id}: Invalid search lyrics request: {e}")
span.set_attribute("error", str(e))
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
logger.error(f"Job {job_id}: Failed to search lyrics: {e}", exc_info=True)
span.set_attribute("error", str(e))
raise HTTPException(status_code=500, detail=f"Failed to search lyrics: {str(e)}")
@router.post("/{job_id}/preview-video")
async def generate_preview_video(
job_id: str,
@@ -870,7 +1022,7 @@ async def get_instrumental_analysis(
"has_audible_content": backing_analysis.get('has_audible_content', False),
"total_duration_seconds": backing_analysis.get('total_duration_seconds', 0),
"audible_segments": backing_analysis.get('audible_segments', []),
"recommended_selection": backing_analysis.get('recommended_selection', 'with_backing'),
"recommended_selection": backing_analysis.get('recommended_selection', 'clean'),
"total_audible_duration_seconds": backing_analysis.get('total_audible_duration_seconds', 0),
"audible_percentage": backing_analysis.get('audible_percentage', 0),
"silence_threshold_db": backing_analysis.get('silence_threshold_db', -40),
@@ -1165,7 +1317,7 @@ async def save_audio_edit_session(
# Upload edit_data to GCS
storage = StorageService()
gcs_path = f"jobs/{job_id}/audio_edit_sessions/{session.session_id}.json"
storage.upload_json(edit_data, gcs_path)
storage.upload_json(gcs_path, edit_data)
session.edit_data_gcs_path = gcs_path
# Save metadata to Firestore
@@ -1338,15 +1490,22 @@ async def get_input_audio_info(
state_data = job.state_data or {}
edit_stack = state_data.get('audio_edit_stack', [])
# Get metadata for the original audio
metadata = edit_service.get_metadata_from_gcs(job.input_media_gcs_path)
# Try cached waveform first (pre-generated by download worker), fall back to on-demand
waveform_cache_path = state_data.get('audio_edit_waveform_cache_path')
cached = None
if waveform_cache_path:
cached = analysis_service.load_cached_waveform(waveform_cache_path)
if cached:
orig_amplitudes, orig_duration = cached
logger.info(f"Job {job_id}: Using cached waveform data")
else:
orig_amplitudes, orig_duration = analysis_service.get_waveform_data(
gcs_audio_path=job.input_media_gcs_path,
job_id=job_id,
num_points=1000,
)
# Waveform for original audio
orig_amplitudes, orig_duration = analysis_service.get_waveform_data(
gcs_audio_path=job.input_media_gcs_path,
job_id=job_id,
num_points=1000,
)
original_playback_url = transcoding_service.get_review_audio_url(job.input_media_gcs_path)
# Determine current audio state
@@ -1733,7 +1892,7 @@ async def submit_audio_edit(
edit_log = body.get("edit_log")
if edit_log:
edit_log_path = f"jobs/{job_id}/audio_edit/edit_log.json"
storage.upload_json(edit_log, edit_log_path)
storage.upload_json(edit_log_path, edit_log)
logger.info(f"Job {job_id}: Saved audio edit log to {edit_log_path}")
if edit_stack:
+233 -20
View File
@@ -10,6 +10,7 @@ Handles:
"""
import hashlib
import logging
import threading
from datetime import datetime
from typing import Optional, Tuple
@@ -34,6 +35,7 @@ def _mask_email(email: str) -> str:
from fastapi import APIRouter, HTTPException, Depends, Request, Header
from pydantic import BaseModel, EmailStr
from backend.services.email_validation_service import get_email_validation_service
from backend.models.user import (
UserRole,
UserPublic,
@@ -67,6 +69,7 @@ from backend.services.youtube_download_service import (
)
from backend.exceptions import InvalidStateTransitionError
from backend.services.tracing import add_span_attribute
from backend.utils.request_helpers import get_client_ip
logger = logging.getLogger(__name__)
@@ -130,6 +133,32 @@ class LogoutResponse(BaseModel):
# Magic Link Authentication
# =============================================================================
def _precompute_credit_eval(token: str, email: str) -> None:
"""Run credit evaluation in background and store result on magic link doc.
Called in a background thread after sending a magic link for new users.
If the user clicks the link before this finishes, verify_magic_link falls
back to inline evaluation (same as before this optimization).
"""
try:
from backend.services.credit_evaluation_service import get_credit_evaluation_service
from backend.services.user_service import get_user_service, MAGIC_LINKS_COLLECTION
eval_service = get_credit_evaluation_service()
evaluation = eval_service.evaluate(email, "welcome")
user_service = get_user_service()
user_service.db.collection(MAGIC_LINKS_COLLECTION).document(token).update({
"credit_eval_decision": evaluation.decision,
"credit_eval_reasoning": evaluation.reasoning,
"credit_eval_error": evaluation.error,
})
logger.info(f"Pre-computed credit eval for {_mask_email(email)}: {evaluation.decision}")
except Exception:
logger.exception(f"Background credit eval failed for {_mask_email(email)} — verify will compute inline")
@router.post("/auth/magic-link", response_model=SendMagicLinkResponse)
async def send_magic_link(
request: SendMagicLinkRequest,
@@ -147,6 +176,50 @@ async def send_magic_link(
"""
from backend.middleware.tenant import get_tenant_from_request, get_tenant_config_from_request
email = request.email.lower()
# Check for disposable email domains, blocked emails, and blocked IPs
# (done before email service check so we can reject without needing email config)
email_validation = get_email_validation_service()
if email_validation.is_disposable_domain(email):
logger.warning(f"Blocked disposable email signup attempt: {_mask_email(email)}")
raise HTTPException(
status_code=422,
detail="disposable_email_not_allowed"
)
if email_validation.is_email_blocked(email):
logger.warning(f"Blocked email signup attempt: {_mask_email(email)}")
return SendMagicLinkResponse(
status="success",
message="If this email is registered, you will receive a sign-in link shortly."
)
ip_address = get_client_ip(http_request)
if ip_address and email_validation.is_ip_blocked(ip_address):
logger.warning(f"Blocked IP signup attempt: {ip_address}")
return SendMagicLinkResponse(
status="success",
message="If this email is registered, you will receive a sign-in link shortly."
)
# Per-IP and per-fingerprint signup rate limit (only for new users)
device_fingerprint = request.device_fingerprint
existing_user = user_service.get_user(email)
if existing_user is None:
if user_service.is_signup_rate_limited(
ip_address=ip_address, device_fingerprint=device_fingerprint
):
logger.warning(
f"Signup rate limit hit: IP={ip_address} for {_mask_email(email)}"
)
# Silent reject (anti-enumeration)
return SendMagicLinkResponse(
status="success",
message="If this email is registered, you will receive a sign-in link shortly."
)
# Check if email service is configured
if not email_service.is_configured():
logger.error("Email service not configured - cannot send magic links")
@@ -155,8 +228,6 @@ async def send_magic_link(
detail="Email service is not available. Please contact support."
)
email = request.email.lower()
# Get tenant context from middleware
tenant_id = get_tenant_from_request(http_request)
tenant_config = get_tenant_config_from_request(http_request)
@@ -171,16 +242,16 @@ async def send_magic_link(
message="If this email is registered, you will receive a sign-in link shortly."
)
# Get client info for security logging
ip_address = http_request.client.host if http_request.client else None
# Get client info for security logging (ip_address already extracted above for blocklist check)
user_agent = http_request.headers.get("user-agent")
# Create magic link token with tenant context
# Create magic link token with tenant context and fingerprint
magic_link = user_service.create_magic_link(
email,
ip_address=ip_address,
user_agent=user_agent,
tenant_id=tenant_id
tenant_id=tenant_id,
device_fingerprint=device_fingerprint,
)
# Get tenant-specific email configuration
@@ -206,6 +277,18 @@ async def send_magic_link(
# Don't reveal failure to prevent email enumeration
# Still return success
# Pre-compute credit evaluation in background for new users.
# By the time they check their email and click the link, the decision
# will be ready and verification will be instant.
# Skip for test emails — they get auto-granted without evaluation.
if existing_user is None and not is_test_email(email):
thread = threading.Thread(
target=_precompute_credit_eval,
args=(magic_link.token, email),
daemon=True,
)
thread.start()
return SendMagicLinkResponse(
status="success",
message="If this email is registered, you will receive a sign-in link shortly."
@@ -230,7 +313,7 @@ async def verify_magic_link(
raise HTTPException(status_code=401, detail="Invalid token")
# Get client info
ip_address = http_request.client.host if http_request.client else None
ip_address = get_client_ip(http_request)
user_agent = http_request.headers.get("user-agent")
# Check if this is a first login BEFORE verification (which sets last_login_at)
@@ -253,12 +336,37 @@ async def verify_magic_link(
if not success or not user:
raise HTTPException(status_code=401, detail=message)
# Create session with tenant context from the magic link
# Grant welcome credits on first verification (with AI abuse evaluation)
# Use pre-computed evaluation from magic link if available (computed at send time)
precomputed_eval = None
if magic_link_doc.exists:
precomputed_eval = {
k: magic_link_data.get(k)
for k in ("credit_eval_decision", "credit_eval_reasoning", "credit_eval_error")
if magic_link_data.get(k) is not None
} or None
credits_granted = 0
credit_status = "not_applicable" # returning user, not first login
granted, credit_status = user_service.grant_welcome_credits_if_eligible(
user.email, precomputed_eval=precomputed_eval,
)
if granted:
credits_granted = user_service.NEW_USER_FREE_CREDITS
logger.info(f"Granted {credits_granted} welcome credits to {_mask_email(user.email)}")
# Refresh user to get updated credit balance
user = user_service.get_user(user.email)
elif credit_status == "denied":
logger.info(f"Welcome credits denied for {_mask_email(user.email)}")
# Create session with tenant context and device fingerprint from the magic link
magic_link_fingerprint = magic_link_data.get('device_fingerprint') if magic_link_doc.exists else None
session = user_service.create_session(
user.email,
ip_address=ip_address,
user_agent=user_agent,
tenant_id=magic_link_tenant_id
tenant_id=magic_link_tenant_id,
device_fingerprint=magic_link_fingerprint,
)
# Send welcome email to first-time users
@@ -291,6 +399,8 @@ async def verify_magic_link(
user=user_public,
message="Successfully signed in",
tenant_subdomain=tenant_subdomain,
credits_granted=credits_granted,
credit_status=credit_status,
)
@@ -1066,7 +1176,7 @@ async def check_feedback_eligibility(
eligible=eligible,
has_submitted=user.has_submitted_feedback,
jobs_completed=user.total_jobs_completed,
credits_reward=2,
credits_reward=1,
)
@@ -1077,7 +1187,7 @@ async def submit_user_feedback(
user_service: UserService = Depends(get_user_service),
):
"""
Submit product feedback to earn 2 free credits.
Submit product feedback to earn 1 free credit.
Requires authentication. Users must have completed 2+ jobs and
not have already submitted feedback. At least one text field
@@ -1155,8 +1265,59 @@ async def submit_user_feedback(
has_submitted_feedback=True,
)
# Grant 2 credits
credits_granted = 2
# AI evaluation before granting feedback credits
credits_granted = 0
feedback_content = {
"overall_rating": request.overall_rating,
"what_went_well": request.what_went_well,
"what_could_improve": request.what_could_improve,
"additional_comments": request.additional_comments,
}
try:
from backend.services.credit_evaluation_service import get_credit_evaluation_service
eval_service = get_credit_evaluation_service()
evaluation = eval_service.evaluate(user.email, "feedback", feedback_content)
if evaluation.decision == "deny":
logger.info(f"Feedback credits denied for {_mask_email(user.email)}: {evaluation.reasoning}")
try:
from backend.services.email_service import get_email_service
get_email_service().send_credit_denied_email(user.email, "feedback")
except Exception:
logger.exception(f"Failed to send credit denied email to {_mask_email(user.email)}")
return UserFeedbackResponse(
status="success",
message="Thank you for your feedback! We appreciate your input.",
credits_granted=0,
)
if evaluation.decision == "pending_review":
logger.info(f"Feedback credits pending review for {_mask_email(user.email)}: {evaluation.reasoning}")
try:
from backend.services.email_service import get_email_service
get_email_service().send_credit_review_needed_email(user.email, "feedback", evaluation.reasoning)
except Exception:
logger.exception(f"Failed to send review needed email for {_mask_email(user.email)}")
return UserFeedbackResponse(
status="success",
message="Thank you for your feedback! Our team will review your account shortly.",
credits_granted=0,
)
except Exception:
logger.exception(f"Credit evaluation failed for {_mask_email(user.email)} — pending review (fail-closed)")
try:
from backend.services.email_service import get_email_service
get_email_service().send_credit_review_needed_email(user.email, "feedback", "Evaluation error")
except Exception:
pass
return UserFeedbackResponse(
status="success",
message="Thank you for your feedback! Our team will review your account shortly.",
credits_granted=0,
)
# Grant 1 credit (passed evaluation)
credits_granted = 1
user_service.add_credits(
email=user.email,
amount=credits_granted,
@@ -1168,6 +1329,25 @@ async def submit_user_feedback(
f"credits granted: {credits_granted}"
)
# Send admin notification email (fire-and-forget)
try:
from backend.services.email_service import get_email_service
email_service = get_email_service()
email_service.send_feedback_notification(
user_email=user.email,
overall_rating=request.overall_rating,
ease_of_use_rating=request.ease_of_use_rating,
lyrics_accuracy_rating=request.lyrics_accuracy_rating,
correction_experience_rating=request.correction_experience_rating,
what_went_well=request.what_went_well,
what_could_improve=request.what_could_improve,
additional_comments=request.additional_comments,
would_recommend=request.would_recommend,
would_use_again=request.would_use_again,
)
except Exception as e:
logger.warning(f"Failed to send feedback notification email: {e}")
return UserFeedbackResponse(
status="success",
message=f"Thank you for your feedback! You earned {credits_granted} free credits.",
@@ -1201,9 +1381,17 @@ class UserDetailResponse(BaseModel):
last_login_at: Optional[str] = None
total_jobs_created: int = 0
total_jobs_completed: int = 0
total_spent: int = 0
credit_transactions: list[dict] = []
recent_jobs: list[dict] = []
active_sessions_count: int = 0
# Anti-abuse / identity info
signup_ip: Optional[str] = None
device_fingerprint: Optional[str] = None
welcome_credits_granted: bool = False
has_submitted_feedback: bool = False
# Recent session details (IP, user agent, fingerprint)
recent_sessions: list[dict] = []
@router.get("/admin/users", response_model=UserListResponsePaginated)
@@ -1244,6 +1432,7 @@ async def list_users(
query = query.where(filter=FieldFilter('is_active', '==', True))
# Search by email prefix (case-insensitive via range query)
search = search.strip() if search else None
if search:
search_lower = search.lower()
# Use range query for prefix matching
@@ -1251,16 +1440,23 @@ async def list_users(
query = query.where(filter=FieldFilter('email', '<', search_lower + '\uffff'))
# Sorting
direction = firestore.Query.DESCENDING if sort_order == "desc" else firestore.Query.ASCENDING
if sort_by in ["created_at", "last_login_at", "credits", "email"]:
query = query.order_by(sort_by, direction=direction)
else:
query = query.order_by("created_at", direction=direction)
# When search is active, Firestore range filters on 'email' conflict with
# order_by on a different field (requires composite index). Since we already
# fetch all docs and paginate in Python, just sort in Python when searching.
sort_field = sort_by if sort_by in ["created_at", "last_login_at", "credits", "email"] else "created_at"
if not search:
direction = firestore.Query.DESCENDING if sort_order == "desc" else firestore.Query.ASCENDING
query = query.order_by(sort_field, direction=direction)
# Get all docs and filter in Python
# Note: This is expensive for large datasets, consider caching
all_docs = list(query.stream())
# Sort in Python when search is active (can't use Firestore order_by with range filter)
if search:
reverse = sort_order == "desc"
all_docs.sort(key=lambda d: (d.to_dict().get(sort_field) is None, d.to_dict().get(sort_field)), reverse=reverse)
# Filter out test users if exclude_test is True
if exclude_test:
all_docs = [d for d in all_docs if not is_test_email(d.to_dict().get('email', ''))]
@@ -1340,13 +1536,24 @@ async def get_user_detail(
"created_at": created_at_str,
})
# Count active sessions
# Get active sessions with details
sessions_query = db.collection("sessions").where(
filter=FieldFilter("user_email", "==", email)
).where(
filter=FieldFilter("is_active", "==", True)
)
active_sessions_count = sum(1 for _ in sessions_query.stream())
active_sessions = []
for session_doc in sessions_query.stream():
sd = session_doc.to_dict()
created = sd.get("created_at")
active_sessions.append({
"ip_address": sd.get("ip_address"),
"user_agent": sd.get("user_agent"),
"device_fingerprint": sd.get("device_fingerprint"),
"created_at": created.isoformat() if hasattr(created, 'isoformat') else str(created) if created else None,
"last_activity_at": str(sd.get("last_activity_at", "")),
})
active_sessions_count = len(active_sessions)
# Format credit transactions
credit_transactions = []
@@ -1368,9 +1575,15 @@ async def get_user_detail(
last_login_at=user.last_login_at.isoformat() if user.last_login_at else None,
total_jobs_created=user.total_jobs_created,
total_jobs_completed=user.total_jobs_completed,
total_spent=user.total_spent,
credit_transactions=credit_transactions,
recent_jobs=recent_jobs,
active_sessions_count=active_sessions_count,
signup_ip=user.signup_ip,
device_fingerprint=user.device_fingerprint,
welcome_credits_granted=user.welcome_credits_granted,
has_submitted_feedback=user.has_submitted_feedback,
recent_sessions=active_sessions,
)
+35
View File
@@ -0,0 +1,35 @@
# Cloud Build config for GPU base image
#
# Builds the CUDA + PyTorch + models base image used by the audio worker.
# This image is large (~10GB) so builds take 15-30 minutes.
#
# Trigger manually:
# gcloud builds submit --config=backend/cloudbuild-gpu-base.yaml --project=nomadkaraoke --timeout=3600s
#
# The app-layer Dockerfile uses this as its BASE_IMAGE for audio worker deploys.
steps:
- name: 'gcr.io/cloud-builders/docker'
args:
- 'build'
- '-f'
- 'backend/Dockerfile.gpu-base'
- '-t'
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:latest'
- '-t'
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:$BUILD_ID'
- '--build-arg'
- 'BUILD_DATE=$_BUILD_DATE'
- '--build-arg'
- 'BUILD_ID=$BUILD_ID'
- '.'
images:
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:latest'
- 'us-east4-docker.pkg.dev/nomadkaraoke/karaoke-backend-gpu/karaoke-backend-gpu-base:$BUILD_ID'
timeout: '3600s'
options:
machineType: 'E2_HIGHCPU_32'
diskSizeGb: 100
+10
View File
@@ -32,6 +32,10 @@ class Settings(BaseSettings):
# Authentication
admin_tokens: Optional[str] = os.getenv("ADMIN_TOKENS") # Comma-separated list
scheduler_service_account: str = os.getenv(
"SCHEDULER_SERVICE_ACCOUNT",
"karaoke-backend@nomadkaraoke.iam.gserviceaccount.com"
)
# Application
environment: str = os.getenv("ENVIRONMENT", "development")
@@ -57,6 +61,12 @@ class Settings(BaseSettings):
# use uncorrected transcription - human review will fix any issues.
agentic_correction_timeout_seconds: int = int(os.getenv("AGENTIC_CORRECTION_TIMEOUT_SECONDS", "180"))
# AI Credit Evaluation (anti-abuse gating for free credits)
# When enabled, welcome and feedback credit grants are evaluated by Gemini
# before granting. Fail-open: if evaluation fails, credits are granted anyway.
credit_eval_enabled: bool = os.getenv("CREDIT_EVAL_ENABLED", "true").lower() in ("true", "1", "yes")
credit_eval_model: str = os.getenv("CREDIT_EVAL_MODEL", "gemini-3.1-pro-preview")
# Cloud Tasks (for scalable worker coordination)
# When enabled, workers are triggered via Cloud Tasks for guaranteed delivery
# When disabled (default), workers are triggered via direct HTTP (for development)
+2 -1
View File
@@ -7,7 +7,7 @@ from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from backend.config import settings
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, rate_limits, push, catalog
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, rate_limits, push, catalog, encoding_worker
from backend.services.tracing import setup_tracing, instrument_app, get_current_trace_id
from backend.services.structured_logging import setup_structured_logging
from backend.services.spacy_preloader import preload_spacy_model
@@ -153,6 +153,7 @@ app.include_router(health.router, prefix="/api")
app.include_router(jobs.router, prefix="/api")
app.include_router(file_upload.router, prefix="/api") # File upload endpoint
app.include_router(internal.router, prefix="/api") # Internal worker endpoints
app.include_router(encoding_worker.router, prefix="/api") # Encoding worker lifecycle
app.include_router(review.router, prefix="/api") # Review UI compatibility endpoints
app.include_router(auth.router, prefix="/api") # OAuth credential management
app.include_router(audio_search.router, prefix="/api") # Audio search (artist+title mode)
+40
View File
@@ -321,6 +321,9 @@ class Job(BaseModel):
# Creation-time decision params (for observability — what did the user actually choose?)
creation_params: Dict[str, Any] = Field(default_factory=dict)
# Anti-abuse: IP address at job creation time (for cross-account correlation)
creation_ip: Optional[str] = None
# Output deletion tracking (for admin cleanup without deleting job)
outputs_deleted_at: Optional[datetime] = None # Timestamp when outputs were deleted by admin
outputs_deleted_by: Optional[str] = None # Admin email who deleted outputs
@@ -421,6 +424,43 @@ class Job(BaseModel):
}
"""
# Processing metadata (immutable provenance data written by workers during processing)
processing_metadata: Dict[str, Any] = Field(default_factory=dict)
"""
Immutable processing provenance data. Written once by each worker during processing.
Never modified after initial write. Used for analytics, debugging, and data export.
Structure:
{
"transcription": {
"provider": "audioshake",
"audioshake_task_id": "...",
"audioshake_asset_id": "...",
"language_detected": "en",
"word_count": 358,
"segment_count": 42,
},
"correction": {
"handlers_applied": [...],
"corrections_made": 12,
"correction_ratio": 0.034,
"reference_sources_found": ["genius", "spotify"],
"agentic_routing": "rule-based",
"duration_seconds": 33.2,
},
"separation": {
"provider": "modal",
"clean_model": "...",
"duration_seconds": 420.5,
},
"timing": {
"lyrics_worker_seconds": 125.3,
"audio_worker_seconds": 420.5,
...
},
}
"""
# Request metadata (captured at job creation for tracking and filtering)
request_metadata: Dict[str, Any] = Field(default_factory=dict)
"""
+19 -2
View File
@@ -98,6 +98,13 @@ class User(BaseModel):
# Feedback-for-credits program
has_submitted_feedback: bool = False
# Anti-abuse: IP address and device fingerprint used during signup
signup_ip: Optional[str] = None
device_fingerprint: Optional[str] = None
# Flag to prevent duplicate welcome credit grants (idempotency)
welcome_credits_granted: bool = False
class MagicLinkToken(BaseModel):
"""
@@ -117,10 +124,16 @@ class MagicLinkToken(BaseModel):
used_at: Optional[datetime] = None
ip_address: Optional[str] = None
user_agent: Optional[str] = None
device_fingerprint: Optional[str] = None
# Multi-tenant support (None = default Nomad Karaoke)
tenant_id: Optional[str] = None
# Pre-computed credit evaluation (set asynchronously after magic link is sent)
credit_eval_decision: Optional[str] = None # "grant", "deny", "pending_review"
credit_eval_reasoning: Optional[str] = None
credit_eval_error: Optional[str] = None
class Session(BaseModel):
"""
@@ -138,6 +151,7 @@ class Session(BaseModel):
last_activity_at: datetime = Field(default_factory=datetime.utcnow)
ip_address: Optional[str] = None
user_agent: Optional[str] = None
device_fingerprint: Optional[str] = None
is_active: bool = True
# Multi-tenant support (None = default Nomad Karaoke)
@@ -149,6 +163,7 @@ class Session(BaseModel):
class SendMagicLinkRequest(BaseModel):
"""Request to send a magic link email."""
email: str
device_fingerprint: Optional[str] = None
class SendMagicLinkResponse(BaseModel):
@@ -169,6 +184,8 @@ class VerifyMagicLinkResponse(BaseModel):
user: "UserPublic"
message: str
tenant_subdomain: Optional[str] = None
credits_granted: int = 0
credit_status: str = "not_applicable" # "granted", "denied", "pending_review", "already_granted", "not_applicable"
class UserPublic(BaseModel):
@@ -217,7 +234,7 @@ class UserFeedback(BaseModel):
Feedback from any user (not just beta testers).
Stored in Firestore 'user_feedback' collection.
Users earn 2 free credits for submitting detailed feedback.
Users earn 1 free credit for submitting detailed feedback.
"""
id: str
user_email: str
@@ -272,4 +289,4 @@ class FeedbackEligibilityResponse(BaseModel):
eligible: bool
has_submitted: bool
jobs_completed: int
credits_reward: int = 2
credits_reward: int = 1
+48
View File
@@ -0,0 +1,48 @@
#!/usr/bin/env python3
"""
Download ensemble preset models at Docker build time.
Bakes models into the image so they're available immediately at runtime,
avoiding cold-start model download latency in Cloud Run Jobs.
Usage: python backend/scripts/download_models.py /models
"""
import json
import sys
import logging
import importlib.resources as resources
from audio_separator.separator import Separator
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Presets to bake into the GPU image
PRESETS_TO_DOWNLOAD = ["instrumental_clean", "karaoke"]
def download_preset_models(model_dir: str) -> None:
"""Download all models for the configured presets individually.
Ensemble presets resolve to multiple model filenames. We must download
each model individually via load_model(model_filename) — calling
load_model() with no args on an ensemble preset doesn't trigger downloads.
"""
with resources.open_text("audio_separator", "ensemble_presets.json") as f:
presets = json.load(f)["presets"]
models_to_download = set()
for preset_name in PRESETS_TO_DOWNLOAD:
models_to_download.update(presets[preset_name]["models"])
logger.info(f"Downloading {len(models_to_download)} models for presets: {PRESETS_TO_DOWNLOAD}")
for model in sorted(models_to_download):
logger.info(f" Downloading: {model}")
sep = Separator(model_file_dir=model_dir)
sep.load_model(model)
logger.info(f" Done: {model}")
if __name__ == "__main__":
model_dir = sys.argv[1] if len(sys.argv) > 1 else "/models"
download_preset_models(model_dir)
logger.info(f"All preset models downloaded to {model_dir}")
+73 -1
View File
@@ -5,6 +5,7 @@ This service wraps the shared karaoke_gen.instrumental_review module
to provide GCS-integrated audio analysis capabilities.
"""
import json
import logging
import os
import tempfile
@@ -187,7 +188,78 @@ class AudioAnalysisService:
)
return amplitudes, duration
def cache_waveform_data(
self,
gcs_audio_path: str,
job_id: str,
cache_gcs_path: str,
num_points: int = 1000,
) -> tuple[list[float], float]:
"""
Generate waveform data and cache it as JSON in GCS.
Args:
gcs_audio_path: Path to the audio file in GCS
job_id: Job ID for logging
cache_gcs_path: GCS path to store the cached waveform JSON
num_points: Number of data points to generate
Returns:
Tuple of (amplitude_values, duration_seconds)
"""
logger.info(f"[{job_id}] Generating and caching waveform data: {gcs_audio_path}")
amplitudes, duration = self.get_waveform_data(
gcs_audio_path=gcs_audio_path,
job_id=job_id,
num_points=num_points,
)
cache_data = {
"amplitudes": list(amplitudes),
"duration_seconds": duration,
"num_points": num_points,
"source_gcs_path": gcs_audio_path,
}
self.storage_service.upload_json(cache_gcs_path, cache_data)
logger.info(f"[{job_id}] Waveform data cached at {cache_gcs_path}")
return amplitudes, duration
def load_cached_waveform(
self,
cache_gcs_path: str,
) -> Optional[tuple[list[float], float]]:
"""
Load cached waveform data from GCS.
Args:
cache_gcs_path: GCS path to the cached waveform JSON
Returns:
Tuple of (amplitude_values, duration_seconds) or None if not found
"""
try:
if not self.storage_service.file_exists(cache_gcs_path):
return None
with tempfile.TemporaryDirectory() as temp_dir:
local_path = os.path.join(temp_dir, "waveform.json")
self.storage_service.download_file(cache_gcs_path, local_path)
with open(local_path) as f:
data = json.load(f)
amplitudes = data.get("amplitudes", [])
duration = data.get("duration_seconds", 0.0)
if not amplitudes:
return None
return amplitudes, duration
except Exception as e:
logger.warning(f"Failed to load cached waveform from {cache_gcs_path}: {e}")
return None
def generate_waveform_with_mutes(
self,
gcs_audio_path: str,
+61
View File
@@ -3,6 +3,7 @@ Authentication service for karaoke backend.
Provides token-based authentication with support for:
- Admin tokens (hardcoded in environment)
- Google OIDC tokens (from Cloud Scheduler / Cloud Tasks service accounts)
- Admin by email domain (@nomadkaraoke.com)
- User tokens (stored in Firestore auth_tokens collection)
- Session tokens (stored in Firestore sessions collection, from magic link auth)
@@ -19,6 +20,9 @@ from enum import Enum
from typing import Optional, Tuple, Dict, Any, List
from datetime import datetime
from google.auth.transport import requests as google_auth_requests
from google.oauth2 import id_token as google_id_token
from backend.services.firestore_service import FirestoreService
from backend.config import get_settings
from backend.models.user import UserRole
@@ -72,6 +76,7 @@ class AuthService:
self.firestore = FirestoreService()
self.settings = get_settings()
self._init_admin_tokens()
self._scheduler_service_account = self.settings.scheduler_service_account
def _init_admin_tokens(self):
"""Load admin tokens from environment variables."""
@@ -83,6 +88,56 @@ class AuthService:
logger.info(f"Loaded {len(self.admin_tokens)} admin token(s)")
else:
logger.warning("No admin tokens configured! Set ADMIN_TOKENS environment variable.")
def _validate_oidc_token(self, token: str) -> Optional[AuthResult]:
"""
Validate a Google OIDC token (from Cloud Scheduler or Cloud Tasks).
Returns AuthResult if token is a valid Google OIDC JWT from an allowed
service account, None if the token is not a JWT or validation fails.
"""
# Quick check: JWTs have 3 dot-separated parts
if token.count('.') != 2:
return None
try:
# Verify the token signature and claims with Google
# audience=None skips audience check — Cloud Scheduler sets audience
# to the endpoint URL, which varies per endpoint
claims = google_id_token.verify_oauth2_token(
token,
google_auth_requests.Request(),
audience=None,
)
token_email = claims.get("email", "")
# Only accept tokens from the configured service account
if token_email != self._scheduler_service_account:
logger.warning(
f"OIDC token from unexpected service account: {token_email} "
f"(expected {self._scheduler_service_account})"
)
return None
logger.info(f"OIDC token validated for service account: {token_email}")
return AuthResult(
is_valid=True,
user_type=UserType.ADMIN,
remaining_uses=-1,
message="OIDC service account access granted",
user_email=token_email,
is_admin=True,
)
except ValueError as e:
# verify_oauth2_token raises ValueError for invalid/expired tokens
logger.debug(f"OIDC token validation failed: {e}")
return None
except Exception as e:
# Network errors fetching Google certs, etc.
logger.warning(f"OIDC token verification error: {e}")
return None
def validate_token(self, token: str) -> Tuple[bool, UserType, int, str]:
"""
@@ -213,6 +268,12 @@ class AuthService:
is_admin=True
)
# Check for Google OIDC tokens (Cloud Scheduler / Cloud Tasks)
# Done before Firestore lookup to avoid wasting a read on JWT strings
oidc_result = self._validate_oidc_token(token)
if oidc_result is not None:
return oidc_result
# Check stored tokens in Firestore (auth_tokens collection)
token_data = self.firestore.get_token(token)
@@ -0,0 +1,441 @@
"""
AI-powered credit evaluation service.
Evaluates whether to grant free credits (welcome or feedback) by collecting
abuse signals and asking Gemini for a grant/deny decision. Fail-open: if
the AI call fails for any reason, credits are granted.
"""
import json
import logging
import uuid
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Optional
from backend.config import get_settings
logger = logging.getLogger(__name__)
CREDIT_EVALUATIONS_COLLECTION = "credit_evaluations"
@dataclass
class CreditEvaluation:
"""Result of an AI credit evaluation."""
decision: str # "grant" or "deny"
reasoning: str
confidence: float
error: Optional[str] = None # Set if evaluation failed (decision defaults to "grant")
signals: Optional[dict] = None # Collected abuse signals (for admin review emails)
SYSTEM_PROMPT = """You are an anti-abuse evaluator for Nomad Karaoke, a web service that creates professional karaoke videos. Each job costs the service real money in API credits and cloud compute.
New users get 1 free welcome credit to try the service. Users who complete 2 jobs and submit feedback get 1 more credit. Some users abuse this by creating multiple accounts to get unlimited free karaoke generation.
Your job: Given the signals below, decide whether to GRANT or DENY free credits to this user.
## Decision Guidelines
**DENY if any of these are true:**
- The user's device fingerprint matches other accounts (strong signal of multi-accounting)
- The user's signup IP matches other accounts AND those accounts also have suspicious patterns (e.g., no spend, same user agent)
- There's a clear pattern of account creation from the same device/network to farm free credits
**GRANT if:**
- This appears to be a genuine new user with no suspicious correlations
- The IP match is explainable (e.g., different fingerprints suggest different actual users on a shared network like a school or office)
- There's insufficient evidence to confidently flag abuse
**When in doubt, GRANT.** False positives (blocking real users) are worse than false negatives (letting an occasional abuser through). We'd rather lose a few dollars than alienate a real customer.
## Response Format
Respond with ONLY a JSON object, no other text:
{"decision": "grant" or "deny", "reasoning": "Brief explanation", "confidence": 0.0 to 1.0}
"""
def _build_user_prompt(
email: str,
grant_type: str,
user_data: dict,
fingerprint_matches: list,
ip_matches: list,
ip_geo: Optional[dict],
recent_signups_ip: int,
recent_signups_fp: int,
user_agent: Optional[str],
feedback_content: Optional[dict] = None,
) -> str:
"""Build the user prompt with all abuse signals."""
lines = [
f"## Credit Grant Request",
f"- **Email:** {email}",
f"- **Grant type:** {grant_type} credits",
f"- **User's device fingerprint:** {user_data.get('device_fingerprint', 'unknown')}",
f"- **User's signup IP:** {user_data.get('signup_ip', 'unknown')}",
f"- **User agent:** {user_agent or 'unknown'}",
f"- **Account created:** {user_data.get('created_at', 'unknown')}",
f"- **Jobs created:** {user_data.get('total_jobs_created', 0)}",
f"- **Jobs completed:** {user_data.get('total_jobs_completed', 0)}",
f"- **Total spent (real money):** ${user_data.get('total_spent', 0) / 100:.2f}",
f"- **Current credits:** {user_data.get('credits', 0)}",
"",
]
# IP geolocation
if ip_geo and ip_geo.get("status") == "success":
lines.extend([
f"## IP Geolocation",
f"- **Country:** {ip_geo.get('country', 'unknown')} ({ip_geo.get('country_code', '')})",
f"- **City/Region:** {ip_geo.get('city', '')}, {ip_geo.get('region', '')}",
f"- **ISP:** {ip_geo.get('isp', 'unknown')}",
f"- **Organization:** {ip_geo.get('org', 'unknown')}",
f"- **ASN:** {ip_geo.get('as_number', '')} {ip_geo.get('as_name', '')}",
"",
])
# Recent signup patterns
lines.extend([
f"## Recent Signup Patterns (last 24 hours)",
f"- **New accounts from same IP:** {recent_signups_ip}",
f"- **New accounts from same fingerprint:** {recent_signups_fp}",
"",
])
# Fingerprint correlations
if fingerprint_matches:
lines.append("## Other Accounts with Same Device Fingerprint (RED FLAG)")
for match in fingerprint_matches:
lines.append(
f"- {match.get('email', '?')} | "
f"Jobs: {match.get('total_jobs_created', 0)} | "
f"Spent: ${match.get('total_spent', 0) / 100:.2f} | "
f"Created: {match.get('created_at', '?')}"
)
lines.append("")
else:
lines.extend(["## Other Accounts with Same Device Fingerprint", "None found.", ""])
# IP correlations
if ip_matches:
lines.append("## Other Accounts from Same Signup IP")
for match in ip_matches:
lines.append(
f"- {match.get('email', '?')} | "
f"Fingerprint: {match.get('device_fingerprint', 'unknown')} | "
f"Jobs: {match.get('total_jobs_created', 0)} | "
f"Spent: ${match.get('total_spent', 0) / 100:.2f} | "
f"Created: {match.get('created_at', '?')}"
)
lines.append("")
else:
lines.extend(["## Other Accounts from Same Signup IP", "None found.", ""])
# Feedback content (if applicable)
if feedback_content:
lines.extend([
"## Feedback Submitted",
f"- **Overall rating:** {feedback_content.get('overall_rating', '?')}/5",
f"- **What went well:** {feedback_content.get('what_went_well', 'N/A')[:200]}",
f"- **What could improve:** {feedback_content.get('what_could_improve', 'N/A')[:200]}",
f"- **Additional comments:** {feedback_content.get('additional_comments', 'N/A')[:200]}",
"",
])
lines.append("Based on these signals, should we GRANT or DENY free credits to this user?")
return "\n".join(lines)
def _parse_gemini_response(response_text: str) -> CreditEvaluation:
"""Parse Gemini's JSON response into a CreditEvaluation."""
try:
# Strip markdown code fences if present
text = response_text.strip()
if text.startswith("```"):
text = text.split("\n", 1)[1] if "\n" in text else text[3:]
if text.endswith("```"):
text = text.rsplit("```", 1)[0]
text = text.strip()
if text.startswith("json"):
text = text[4:].strip()
data = json.loads(text)
decision = data.get("decision", "").lower()
if decision not in ("grant", "deny"):
decision = "pending_review" # fail-closed: unknown decision → manual review
return CreditEvaluation(
decision=decision,
reasoning=str(data.get("reasoning", "No reasoning provided")),
confidence=float(data.get("confidence", 0.5)),
)
except (json.JSONDecodeError, ValueError, TypeError) as e:
logger.warning(f"Failed to parse Gemini response: {e}. Response: {response_text[:200]}")
return CreditEvaluation(
decision="pending_review",
reasoning="Failed to parse AI response — pending manual review",
confidence=0.0,
error=f"Parse error: {e}",
)
class CreditEvaluationService:
"""Evaluates credit grant requests using Gemini AI."""
def __init__(self):
self.settings = get_settings()
def _collect_signals(self, email: str) -> dict:
"""Collect all abuse signals for evaluation."""
from backend.services.user_service import get_user_service
from backend.services.ip_geolocation_service import get_ip_geolocation_service
user_service = get_user_service()
user = user_service.get_user(email)
if not user:
return {
"user_data": {},
"fingerprint_matches": [],
"ip_matches": [],
"ip_geo": None,
"recent_signups_ip": 0,
"recent_signups_fp": 0,
"user_agent": None,
}
user_data = {
"email": user.email,
"device_fingerprint": user.device_fingerprint,
"signup_ip": user.signup_ip,
"credits": user.credits,
"total_jobs_created": user.total_jobs_created,
"total_jobs_completed": user.total_jobs_completed,
"total_spent": user.total_spent,
"created_at": str(user.created_at),
}
# Find other accounts with same fingerprint
fingerprint_matches = []
if user.device_fingerprint:
fp_users = user_service.find_users_by_fingerprint(user.device_fingerprint)
fingerprint_matches = [
{
"email": u.email,
"total_jobs_created": u.total_jobs_created,
"total_spent": u.total_spent,
"created_at": str(u.created_at),
}
for u in fp_users if u.email != email
]
# Find other accounts from same IP
ip_matches = []
if user.signup_ip:
ip_users = user_service.find_users_by_signup_ip(user.signup_ip)
ip_matches = [
{
"email": u.email,
"device_fingerprint": u.device_fingerprint,
"total_jobs_created": u.total_jobs_created,
"total_spent": u.total_spent,
"created_at": str(u.created_at),
}
for u in ip_users if u.email != email
]
# IP geolocation
ip_geo = None
if user.signup_ip:
try:
geo_service = get_ip_geolocation_service()
ip_geo = geo_service.lookup_ip(user.signup_ip)
except Exception:
pass
# Recent signup counts
recent_signups_ip = 0
recent_signups_fp = 0
if user.signup_ip:
recent_signups_ip = user_service.count_recent_signups_from_ip(user.signup_ip)
if user.device_fingerprint:
recent_signups_fp = user_service.count_recent_signups_from_fingerprint(user.device_fingerprint)
# User agent from latest session
user_agent = None
try:
from google.cloud.firestore_v1 import FieldFilter
from google.cloud import firestore as fs
sessions = (
user_service.db.collection("sessions")
.where(filter=FieldFilter("user_email", "==", email))
.order_by("created_at", direction=fs.Query.DESCENDING)
.limit(1)
.stream()
)
for session_doc in sessions:
user_agent = session_doc.to_dict().get("user_agent")
except Exception:
pass
return {
"user_data": user_data,
"fingerprint_matches": fingerprint_matches,
"ip_matches": ip_matches,
"ip_geo": ip_geo,
"recent_signups_ip": recent_signups_ip,
"recent_signups_fp": recent_signups_fp,
"user_agent": user_agent,
}
def _call_gemini(self, prompt: str) -> str:
"""Call Gemini and return the response text."""
from google import genai
client = genai.Client(
vertexai=True,
project=self.settings.google_cloud_project,
location="global",
)
response = client.models.generate_content(
model=self.settings.credit_eval_model,
contents=prompt,
config=genai.types.GenerateContentConfig(
system_instruction=SYSTEM_PROMPT,
),
)
return response.text
def _log_evaluation(
self,
email: str,
grant_type: str,
evaluation: CreditEvaluation,
signals: dict,
):
"""Log the evaluation decision to Firestore for audit trail."""
try:
from google.cloud import firestore as fs
db = fs.Client(project=self.settings.google_cloud_project)
doc_id = str(uuid.uuid4())
db.collection(CREDIT_EVALUATIONS_COLLECTION).document(doc_id).set({
"id": doc_id,
"email": email,
"grant_type": grant_type,
"decision": evaluation.decision,
"reasoning": evaluation.reasoning,
"confidence": evaluation.confidence,
"error": evaluation.error,
"model": self.settings.credit_eval_model,
"signals_snapshot": {
"fingerprint_match_count": len(signals.get("fingerprint_matches", [])),
"ip_match_count": len(signals.get("ip_matches", [])),
"recent_signups_ip": signals.get("recent_signups_ip", 0),
"recent_signups_fp": signals.get("recent_signups_fp", 0),
"user_ip": signals.get("user_data", {}).get("signup_ip"),
"user_fingerprint": signals.get("user_data", {}).get("device_fingerprint"),
},
"evaluated_at": datetime.now(timezone.utc).isoformat(),
})
except Exception:
logger.exception(f"Failed to log credit evaluation for {email}")
def evaluate(
self,
email: str,
grant_type: str,
feedback_content: Optional[dict] = None,
) -> CreditEvaluation:
"""
Evaluate whether to grant free credits.
Args:
email: User's email
grant_type: "welcome" or "feedback"
feedback_content: Feedback form data (for feedback grants only)
Returns:
CreditEvaluation with decision, reasoning, confidence.
Fail-closed: returns "pending_review" on any error (admin notified).
"""
if not self.settings.credit_eval_enabled:
return CreditEvaluation(
decision="grant",
reasoning="Credit evaluation disabled — auto-granting",
confidence=1.0,
)
try:
# Collect signals
signals = self._collect_signals(email)
# Quick-grant: if no correlations found at all, skip AI call
if (
not signals["fingerprint_matches"]
and not signals["ip_matches"]
and signals["recent_signups_ip"] <= 1
and signals["recent_signups_fp"] <= 1
):
evaluation = CreditEvaluation(
decision="grant",
reasoning="No suspicious correlations found — clean user",
confidence=1.0,
signals=signals,
)
self._log_evaluation(email, grant_type, evaluation, signals)
return evaluation
# Build prompt and call Gemini
prompt = _build_user_prompt(
email=email,
grant_type=grant_type,
user_data=signals["user_data"],
fingerprint_matches=signals["fingerprint_matches"],
ip_matches=signals["ip_matches"],
ip_geo=signals["ip_geo"],
recent_signups_ip=signals["recent_signups_ip"],
recent_signups_fp=signals["recent_signups_fp"],
user_agent=signals["user_agent"],
feedback_content=feedback_content,
)
response_text = self._call_gemini(prompt)
evaluation = _parse_gemini_response(response_text)
evaluation.signals = signals
self._log_evaluation(email, grant_type, evaluation, signals)
logger.info(
f"Credit evaluation for {email} ({grant_type}): "
f"{evaluation.decision} (confidence={evaluation.confidence:.2f})"
)
return evaluation
except Exception as e:
logger.exception(f"Credit evaluation failed for {email} — pending manual review (fail-closed)")
# Include whatever signals were collected before the failure
collected_signals = locals().get("signals")
evaluation = CreditEvaluation(
decision="pending_review",
reasoning="Evaluation failed — pending manual review",
confidence=0.0,
error=str(e),
signals=collected_signals,
)
try:
self._log_evaluation(email, grant_type, evaluation, collected_signals or {})
except Exception:
pass
return evaluation
_service_instance: Optional[CreditEvaluationService] = None
def get_credit_evaluation_service() -> CreditEvaluationService:
"""Get or create the singleton credit evaluation service."""
global _service_instance
if _service_instance is None:
_service_instance = CreditEvaluationService()
return _service_instance
@@ -0,0 +1,129 @@
"""
Disposable Domain Sync Service.
Fetches and syncs disposable email domain blocklists from external sources.
"""
import logging
from datetime import datetime, timezone
from typing import Set
import httpx
from backend.services.email_validation_service import (
BLOCKLISTS_COLLECTION,
BLOCKLIST_CONFIG_DOC,
DEFAULT_DISPOSABLE_DOMAINS,
)
logger = logging.getLogger(__name__)
EXTERNAL_BLOCKLIST_URL = (
"https://raw.githubusercontent.com/disposable-email-domains/"
"disposable-email-domains/refs/heads/main/disposable_email_blocklist.conf"
)
FETCH_TIMEOUT_SECONDS = 30
MAX_RESPONSE_BYTES = 2 * 1024 * 1024 # 2 MB
MAX_DOMAIN_COUNT = 50_000
def parse_blocklist_text(text: str) -> Set[str]:
"""Parse newline-delimited blocklist text into a set of lowercase domains."""
domains = set()
for line in text.splitlines():
domain = line.strip().lower()
if domain:
domains.add(domain)
return domains
async def fetch_external_blocklist() -> Set[str]:
"""Fetch the external disposable domain blocklist from GitHub.
Checks Content-Length header and response body size against safety limits.
"""
async with httpx.AsyncClient(timeout=FETCH_TIMEOUT_SECONDS) as client:
response = await client.get(EXTERNAL_BLOCKLIST_URL)
response.raise_for_status()
content_length = response.headers.get("content-length")
if content_length and int(content_length) > MAX_RESPONSE_BYTES:
raise ValueError(
f"Response size {content_length} exceeds maximum {MAX_RESPONSE_BYTES}"
)
text = response.text
if len(text.encode()) > MAX_RESPONSE_BYTES:
raise ValueError(
f"Response body size exceeds maximum {MAX_RESPONSE_BYTES}"
)
domains = parse_blocklist_text(text)
if len(domains) > MAX_DOMAIN_COUNT:
raise ValueError(
f"Domain count {len(domains)} exceeds maximum {MAX_DOMAIN_COUNT}"
)
logger.info(f"Fetched {len(domains)} domains from external blocklist")
return domains
def sync_disposable_domains(db, external_domains: Set[str]) -> dict:
"""
Sync external domains into Firestore.
Handles first-run migration from old disposable_domains field,
and cleans up redundant manual domains on subsequent runs.
Note: This is a synchronous function (Firestore SDK is sync).
Call from async code with `await asyncio.to_thread(sync_disposable_domains, db, domains)`.
Returns a summary dict with counts.
"""
doc_ref = db.collection(BLOCKLISTS_COLLECTION).document(BLOCKLIST_CONFIG_DOC)
doc = doc_ref.get()
data = doc.to_dict() if doc.exists else {}
result = {"external_count": len(external_domains), "added": 0, "removed": 0, "migrated_to_manual": []}
is_migration = "external_domains" not in data
if is_migration:
old_domains = set(data.get("disposable_domains", [])) | DEFAULT_DISPOSABLE_DOMAINS
manual_only = old_domains - external_domains
result["migrated_to_manual"] = sorted(manual_only)
new_data = {
**data, # preserve all existing fields
"external_domains": sorted(external_domains),
"manual_domains": sorted(manual_only),
"allowlisted_domains": data.get("allowlisted_domains", []),
"last_sync_at": datetime.now(timezone.utc),
"last_sync_count": len(external_domains),
}
new_data.pop("disposable_domains", None) # remove legacy field
doc_ref.set(new_data)
else:
old_external = set(data.get("external_domains", []))
manual_domains = set(data.get("manual_domains", []))
result["added"] = len(external_domains - old_external)
result["removed"] = len(old_external - external_domains)
cleaned_manual = manual_domains - external_domains
new_data = {
**data,
"external_domains": sorted(external_domains),
"manual_domains": sorted(cleaned_manual),
"last_sync_at": datetime.now(timezone.utc),
"last_sync_count": len(external_domains),
}
doc_ref.set(new_data)
logger.info(
f"Sync complete: {result['external_count']} external domains, "
f"{result['added']} added, {result['removed']} removed"
)
return result
+497
View File
@@ -981,6 +981,194 @@ Get started: {self.frontend_url}
text_content=message_content,
)
def send_review_reminder(
self,
to_email: str,
artist: Optional[str] = None,
title: Optional[str] = None,
job_id: Optional[str] = None,
) -> bool:
"""
Send 24h review reminder email with expiry warning.
Sent when a job has been awaiting review for 24 hours.
Offers help and warns that the job will expire in another 24 hours.
Args:
to_email: User's email address
artist: Artist name for subject line
title: Song title for subject line
job_id: Job ID for constructing the review link
Returns:
True if email was sent successfully
"""
song_info = f" — {artist} - {title}" if artist and title else ""
subject = f"Reminder: Your karaoke video is waiting for review{song_info}"
review_url = f"{self.frontend_url}/app/jobs#/{job_id}/review" if job_id else f"{self.frontend_url}/app"
extra_styles = """
.alert {
background-color: #fef3c7;
border: 1px solid #fcd34d;
border-radius: 8px;
padding: 16px;
margin: 20px 0;
text-align: center;
}
.expiry-warning {
background-color: #fef2f2;
border: 1px solid #fca5a5;
border-radius: 8px;
padding: 16px;
margin: 20px 0;
text-align: center;
color: #991b1b;
}
.review-btn {
display: inline-block;
background-color: #ff7acc;
color: #ffffff !important;
text-decoration: none;
padding: 12px 24px;
border-radius: 8px;
font-weight: bold;
margin: 16px 0;
}
"""
song_name = f" for <strong>{html.escape(artist)} - {html.escape(title)}</strong>" if artist and title else ""
content = f"""
<div class="alert">
⏰ Your karaoke video is waiting for you!
</div>
<p>Hi there! Just a friendly reminder that your karaoke video{song_name} is ready for review.</p>
<p style="text-align: center;">
<a href="{html.escape(review_url)}" class="review-btn">Review Your Video</a>
</p>
<p>During the review, you can check the lyrics are correct and choose your preferred instrumental track. It usually only takes a few minutes!</p>
<p>If you're having any trouble with the review process, just reply to this email and I'll be happy to help you out.</p>
<div class="expiry-warning">
⚠️ Please note: if the review isn't completed within the next <strong>24 hours</strong>,
the job will automatically expire and your credit will be refunded.
</div>
"""
html_content = self._build_email_html(content, extra_styles)
text_content = (
f"Reminder: Your karaoke video{' for ' + artist + ' - ' + title if artist and title else ''} is ready for review.\n\n"
f"Review it here: {review_url}\n\n"
"If you're having trouble with the review process, just reply to this email and I'll help you out.\n\n"
"Please note: if the review isn't completed within the next 24 hours, "
"the job will automatically expire and your credit will be refunded."
)
return self.provider.send_email(
to_email=to_email,
subject=subject,
html_content=html_content,
text_content=text_content,
)
def send_review_expired(
self,
to_email: str,
artist: Optional[str] = None,
title: Optional[str] = None,
credits_balance: int = 0,
) -> bool:
"""
Send review expiry notification email.
Sent when a job is auto-cancelled after 48 hours in review.
Informs the user their credit has been refunded.
Args:
to_email: User's email address
artist: Artist name for subject line
title: Song title for subject line
credits_balance: User's current credit balance after refund
Returns:
True if email was sent successfully
"""
song_info = f" — {artist} - {title}" if artist and title else ""
subject = f"Your karaoke video has expired{song_info}"
extra_styles = """
.info-box {
background-color: #f0f9ff;
border: 1px solid #93c5fd;
border-radius: 8px;
padding: 16px;
margin: 20px 0;
text-align: center;
}
.credit-badge {
display: inline-block;
background-color: #22c55e;
color: #ffffff;
padding: 4px 12px;
border-radius: 12px;
font-weight: bold;
}
.create-btn {
display: inline-block;
background-color: #ff7acc;
color: #ffffff !important;
text-decoration: none;
padding: 12px 24px;
border-radius: 8px;
font-weight: bold;
margin: 16px 0;
}
"""
song_name = f" for <strong>{html.escape(artist)} - {html.escape(title)}</strong>" if artist and title else ""
content = f"""
<div class="info-box">
Your karaoke video{song_name} has been automatically cancelled because the review
wasn't completed within 48 hours.
</div>
<p>Don't worry — your credit has been refunded! Your current balance is
<span class="credit-badge">{credits_balance} credit{'s' if credits_balance != 1 else ''}</span>.</p>
<p>You can create a new karaoke video anytime using your credits:</p>
<p style="text-align: center;">
<a href="{html.escape(self.frontend_url)}/app" class="create-btn">Create New Video</a>
</p>
<p>If you had any trouble with the review process or need help, just reply to this email — I'd love to help!</p>
"""
html_content = self._build_email_html(content, extra_styles)
text_content = (
f"Your karaoke video{' for ' + artist + ' - ' + title if artist and title else ''} has been "
"automatically cancelled because the review wasn't completed within 48 hours.\n\n"
f"Your credit has been refunded. Current balance: {credits_balance} credit{'s' if credits_balance != 1 else ''}.\n\n"
f"Create a new video anytime: {self.frontend_url}/app\n\n"
"If you had any trouble or need help, just reply to this email."
)
return self.provider.send_email(
to_email=to_email,
subject=subject,
html_content=html_content,
text_content=text_content,
)
def send_youtube_upload_complete(
self,
to_email: str,
@@ -1228,6 +1416,315 @@ Open Job: {app_url}
)
def send_feedback_notification(
self,
user_email: str,
overall_rating: int,
ease_of_use_rating: int,
lyrics_accuracy_rating: int,
correction_experience_rating: int,
what_went_well: Optional[str] = None,
what_could_improve: Optional[str] = None,
additional_comments: Optional[str] = None,
would_recommend: bool = True,
would_use_again: bool = True,
) -> bool:
"""
Send admin notification when a user submits product feedback.
Args:
user_email: Email of the user who submitted feedback
overall_rating: 1-5 star rating
ease_of_use_rating: 1-5 star rating
lyrics_accuracy_rating: 1-5 star rating
correction_experience_rating: 1-5 star rating
what_went_well: Optional text feedback
what_could_improve: Optional text feedback
additional_comments: Optional text feedback
would_recommend: Whether user would recommend
would_use_again: Whether user would use again
Returns:
True if email was sent successfully
"""
admin_email = os.getenv("ADMIN_NOTIFICATION_EMAIL", "admin@nomadkaraoke.com")
subject = f"New Feedback from {user_email} — {overall_rating}/5 overall"
def stars(rating: int) -> str:
return "★" * rating + "☆" * (5 - rating)
def text_block(label: str, value: Optional[str]) -> str:
if not value:
return ""
escaped = html.escape(value).replace("\n", "<br>")
return f"""
<tr>
<td style="padding: 8px 12px; font-weight: bold; vertical-align: top; white-space: nowrap;">{label}</td>
<td style="padding: 8px 12px;">{escaped}</td>
</tr>"""
recommend_badge = "Yes ✓" if would_recommend else "No ✗"
use_again_badge = "Yes ✓" if would_use_again else "No ✗"
admin_url = f"{self.frontend_url}/admin/feedback"
extra_styles = """
.feedback-table {
width: 100%;
border-collapse: collapse;
margin: 16px 0;
}
.feedback-table td {
border-bottom: 1px solid #e5e7eb;
}
.stars {
color: #eab308;
font-size: 18px;
letter-spacing: 2px;
}
"""
content = f"""
<p>New product feedback submitted by <strong>{html.escape(user_email)}</strong>:</p>
<table class="feedback-table">
<tr>
<td style="padding: 8px 12px; font-weight: bold;">Overall</td>
<td style="padding: 8px 12px;"><span class="stars">{stars(overall_rating)}</span> ({overall_rating}/5)</td>
</tr>
<tr>
<td style="padding: 8px 12px; font-weight: bold;">Ease of Use</td>
<td style="padding: 8px 12px;"><span class="stars">{stars(ease_of_use_rating)}</span> ({ease_of_use_rating}/5)</td>
</tr>
<tr>
<td style="padding: 8px 12px; font-weight: bold;">Lyrics Accuracy</td>
<td style="padding: 8px 12px;"><span class="stars">{stars(lyrics_accuracy_rating)}</span> ({lyrics_accuracy_rating}/5)</td>
</tr>
<tr>
<td style="padding: 8px 12px; font-weight: bold;">Correction Experience</td>
<td style="padding: 8px 12px;"><span class="stars">{stars(correction_experience_rating)}</span> ({correction_experience_rating}/5)</td>
</tr>
<tr>
<td style="padding: 8px 12px; font-weight: bold;">Would Recommend</td>
<td style="padding: 8px 12px;">{recommend_badge}</td>
</tr>
<tr>
<td style="padding: 8px 12px; font-weight: bold;">Would Use Again</td>
<td style="padding: 8px 12px;">{use_again_badge}</td>
</tr>
{text_block("What went well", what_went_well)}
{text_block("What could improve", what_could_improve)}
{text_block("Additional comments", additional_comments)}
</table>
<p style="text-align: center;">
<a href="{admin_url}" class="button">View All Feedback</a>
</p>
"""
text_content = f"""New Feedback from {user_email}
Overall: {overall_rating}/5
Ease of Use: {ease_of_use_rating}/5
Lyrics Accuracy: {lyrics_accuracy_rating}/5
Correction Experience: {correction_experience_rating}/5
Would Recommend: {recommend_badge}
Would Use Again: {use_again_badge}
What went well: {what_went_well or '(empty)'}
What could improve: {what_could_improve or '(empty)'}
Additional comments: {additional_comments or '(empty)'}
View all feedback: {admin_url}
"""
html_content = self._build_email_html(content, extra_styles)
return self.provider.send_email(
to_email=admin_email,
subject=subject,
html_content=html_content,
text_content=text_content,
)
def send_credit_review_needed_email(
self,
user_email: str,
grant_type: str,
reason: str,
signals: dict | None = None,
) -> bool:
"""
Notify Andrew that a credit grant needs manual review.
Sent when AI evaluation fails, is uncertain, or encounters an error.
Includes abuse signals and a direct link to the user's admin page.
"""
admin_user_url = f"{self.frontend_url}/admin/users/detail?email={user_email}"
subject = f"Credit review needed: {user_email} ({grant_type})"
# Build signals summary for the email
signals_html = ""
signals_text = ""
if signals:
user_data = signals.get("user_data", {})
ip_geo = signals.get("ip_geo")
fp_matches = signals.get("fingerprint_matches", [])
ip_matches = signals.get("ip_matches", [])
rows = []
text_rows = []
if user_data.get("signup_ip"):
rows.append(("IP Address", user_data["signup_ip"]))
text_rows.append(f"IP Address: {user_data['signup_ip']}")
if ip_geo:
geo_str = ", ".join(
str(v) for v in [
ip_geo.get("city"), ip_geo.get("region"), ip_geo.get("country"),
] if v
)
if ip_geo.get("org"):
geo_str += f" ({ip_geo['org']})"
if geo_str:
rows.append(("Location", geo_str))
text_rows.append(f"Location: {geo_str}")
if signals.get("user_agent"):
rows.append(("User Agent", signals["user_agent"]))
text_rows.append(f"User Agent: {signals['user_agent']}")
if user_data.get("device_fingerprint"):
fp = user_data["device_fingerprint"]
rows.append(("Fingerprint", f"{fp[:12]}..."))
text_rows.append(f"Fingerprint: {fp[:12]}...")
rows.append(("Recent signups (IP)", str(signals.get("recent_signups_ip", 0))))
rows.append(("Recent signups (fingerprint)", str(signals.get("recent_signups_fp", 0))))
text_rows.append(f"Recent signups from IP: {signals.get('recent_signups_ip', 0)}")
text_rows.append(f"Recent signups from fingerprint: {signals.get('recent_signups_fp', 0)}")
if fp_matches:
match_emails = ", ".join(m.get("email", "?") for m in fp_matches)
rows.append(("Fingerprint matches", match_emails))
text_rows.append(f"Fingerprint matches: {match_emails}")
if ip_matches:
match_emails = ", ".join(m.get("email", "?") for m in ip_matches)
rows.append(("IP matches", match_emails))
text_rows.append(f"IP matches: {match_emails}")
table_rows = "".join(
f'<tr><td style="padding:4px 12px 4px 0;color:#999;white-space:nowrap;">{html.escape(label)}</td>'
f'<td style="padding:4px 0;">{html.escape(value or "")}</td></tr>'
for label, value in rows
)
signals_html = f"""
<table style="margin:12px 0;font-size:14px;border-collapse:collapse;">{table_rows}</table>"""
signals_text = "\n".join(text_rows)
content = f"""
<p>A {grant_type} credit grant for <strong>{user_email}</strong> needs your review.</p>
<p><strong>Reason:</strong> {reason}</p>
{signals_html}
<p>The user has been told that their signup is being reviewed and credits will be
assigned shortly if everything checks out.</p>
<p style="text-align: center;">
<a href="{admin_user_url}" class="button">Review User</a>
</p>
<p style="color: #999; font-size: 14px;">
If the user looks legitimate, grant them credits from their admin page.
If not, no action needed — they already have 0 credits.
</p>
"""
signals_section = f"\n{signals_text}\n" if signals_text else ""
text_content = f"""Credit review needed: {user_email} ({grant_type})
Reason: {reason}
{signals_section}
Review user: {admin_user_url}
If the user looks legitimate, grant them credits from their admin page.
"""
html_content = self._build_email_html(content)
return self.provider.send_email(
to_email="andrew@beveridge.uk",
subject=subject,
html_content=html_content,
text_content=text_content,
)
def send_credit_denied_email(self, email: str, grant_type: str = "welcome") -> bool:
"""
Send a friendly-but-firm email when free credits are denied due to abuse signals.
CC'd to andrew@beveridge.uk so he can intervene if it's a false positive.
The tone invites the user to reply if it's a mistake.
"""
subject = "About your Nomad Karaoke free credits"
credit_type = "welcome credits" if grant_type == "welcome" else "feedback bonus credits"
content = f"""
<p>Hi there,</p>
<p>Thanks for signing up for Nomad Karaoke!</p>
<p>Unfortunately, we weren't able to grant your free {credit_type} this time. Our system detected
patterns that suggest this may not be your first account with us, and each karaoke generation job
costs us real money in cloud computing and API fees.</p>
<p>We totally understand if this is a mistake! If you're a genuine new user, please just
<strong>reply to this email</strong> and let Andrew (the founder) know. He built this service and is
happy to grant you some free credits to try it out — he just asks that you provide honest feedback
on the experience in return.</p>
<p>If you'd like to get started right away, you can also purchase credits:</p>
<p style="text-align: center;">
<a href="{self.buy_url}" class="button">Buy Credits</a>
</p>
<p style="color: #999; font-size: 14px;">We keep costs low so we can offer the service affordably,
which means we need to be careful about free credit abuse. Thanks for understanding!</p>
{self._get_email_signature()}
"""
text_content = f"""Hi there,
Thanks for signing up for Nomad Karaoke!
Unfortunately, we weren't able to grant your free {credit_type} this time. Our system detected patterns that suggest this may not be your first account with us, and each karaoke generation job costs us real money in cloud computing and API fees.
We totally understand if this is a mistake! If you're a genuine new user, please just reply to this email and let Andrew (the founder) know. He built this service and is happy to grant you some free credits to try it out - he just asks that you provide honest feedback on the experience in return.
If you'd like to get started right away, you can also purchase credits:
{self.buy_url}
---
© {self._get_year()} Nomad Karaoke
"""
html_content = self._build_email_html(content)
return self.provider.send_email(
to_email=email,
subject=subject,
html_content=html_content,
text_content=text_content,
cc_emails=["andrew@beveridge.uk"],
)
# Global instance
_email_service = None
+409 -169
View File
@@ -3,20 +3,42 @@ Email Validation Service.
Provides email validation, normalization, and blocklist checking
to prevent abuse during enrollment and other flows.
Uses a tiered disposable domain detection strategy:
1. Static blocklist (instant, from Firestore)
2. Verified-clean domain cache (skip API calls for 7 days)
3. DeBounce API (free, <50ms)
4. verifymail.io API (paid, only if DeBounce says clean)
Auto-learns: flagged domains are persisted to manual_domains,
clean domains are cached for 7 days in verified_clean_domains.
"""
import hashlib
import logging
import re
from datetime import datetime, timezone
from datetime import datetime, timedelta, timezone
from typing import Optional, Tuple, Set
import httpx
from google.cloud import firestore
from backend.config import settings
logger = logging.getLogger(__name__)
# Module-level HTTP client for connection pooling (external API checks)
_http_client: Optional[httpx.Client] = None
_HTTP_TIMEOUT = 2.0 # seconds per external API call
def _get_http_client() -> httpx.Client:
"""Get or create the module-level HTTP client."""
global _http_client
if _http_client is None or _http_client.is_closed:
_http_client = httpx.Client(timeout=_HTTP_TIMEOUT)
return _http_client
def _mask_email(email: str) -> str:
"""Mask an email address for privacy-safe logging."""
@@ -34,164 +56,12 @@ def _mask_email(email: str) -> str:
BLOCKLISTS_COLLECTION = "blocklists"
BLOCKLIST_CONFIG_DOC = "config"
# Default disposable email domains (can be extended via admin UI)
DEFAULT_DISPOSABLE_DOMAINS = {
# Popular temporary email services
"10minutemail.com",
"10minutemail.net",
"guerrillamail.com",
"guerrillamail.org",
"guerrillamail.net",
"guerrillamail.biz",
"guerrillamailblock.com",
"tempmail.com",
"tempmail.net",
"temp-mail.org",
"temp-mail.io",
"throwawaymail.com",
"mailinator.com",
"mailinator.net",
"mailinator.org",
"mailinator.info",
"maildrop.cc",
"yopmail.com",
"yopmail.fr",
"yopmail.net",
"fakeinbox.com",
"fakemailgenerator.com",
"dispostable.com",
"getairmail.com",
"getnada.com",
"mohmal.com",
"trashmail.com",
"trashmail.net",
"trashmail.org",
"sharklasers.com",
"grr.la",
"guerrillamail.de",
"pokemail.net",
"spam4.me",
"spamgourmet.com",
"mytrashmail.com",
"mailnesia.com",
"mailcatch.com",
"mintemail.com",
"tempr.email",
"tempail.com",
"emailondeck.com",
"incognitomail.com",
"inboxalias.com",
"33mail.com",
"spamex.com",
"spamfree24.org",
"spamspot.com",
"mailnull.com",
"mailsac.com",
"emailfake.com",
"fakemail.fr",
"tempinbox.com",
"throwaway.email",
"burnermail.io",
"anonbox.net",
"anonymbox.com",
"discard.email",
"discardmail.com",
"discardmail.de",
"mailexpire.com",
"mailforspam.com",
"meltmail.com",
"mt2009.com",
"mt2014.com",
"nospam.ze.tc",
"nospamfor.us",
"nowmymail.com",
"receiveee.com",
"safe-mail.net",
"spamavert.com",
"spambob.com",
"spambog.com",
"spambox.us",
"spamcannon.com",
"spamcannon.net",
"spamcon.org",
"spamcorptastic.com",
"spamday.com",
"spamfree.eu",
"spamherelots.com",
"spamhereplease.com",
"spamhole.com",
"spamify.com",
"spaminator.de",
"spamkill.info",
"spaml.com",
"spaml.de",
"spamoff.de",
"spamobox.com",
"spamslicer.com",
"spamstack.net",
"spamthis.co.uk",
"spamthisplease.com",
"supergreatmail.com",
"suremail.info",
"teleworm.us",
"tempemail.co.za",
"tempemail.net",
"tempmailaddress.com",
"tempmailo.com",
"thankyou2010.com",
"thisisnotmyrealemail.com",
"tm.slsrs.ru",
"tmpeml.info",
"trash-mail.at",
"trash-mail.de",
"trash2009.com",
"trashemail.de",
"trashmail.at",
"trashmailer.com",
"wegwerfmail.de",
"wegwerfmail.net",
"wegwerfmail.org",
"wh4f.org",
"willhackforfood.biz",
"willselfdestruct.com",
"xmaily.com",
"xyzfree.net",
"yep.it",
"yogamaven.com",
"yuurok.com",
"zehnminutenmail.de",
"zippymail.info",
# Additional common ones
"mailnator.com",
"bugmenot.com",
"dodgeit.com",
"dodgit.com",
"e4ward.com",
"emailsensei.com",
"hushmail.com",
"jetable.org",
"kasmail.com",
"mailblock.net",
"mailcatch.com",
"mymailoasis.com",
"nervmich.net",
"nervtmansen.de",
"oneoffemail.com",
"pookmail.com",
"shortmail.net",
"sneakemail.com",
"sogetthis.com",
"tempemailaddress.com",
"tempomail.fr",
"temporaryemail.net",
"temporaryforwarding.com",
"temporaryinbox.com",
"thankyou2010.com",
"tyldd.com",
"uggsrock.com",
"veryrealemail.com",
"yourewronghereswhy.com",
}
# Legacy default set — kept as empty set for import compatibility.
# The external sync (disposable_domain_sync_service) replaces this with ~4,800
# domains from the community-curated disposable-email-domains repo.
# The migration path in sync_disposable_domains() references this set to ensure
# no domains are lost during the transition.
DEFAULT_DISPOSABLE_DOMAINS: Set[str] = set()
# Gmail-like domains that support alias normalization
GMAIL_LIKE_DOMAINS = {
@@ -199,6 +69,47 @@ GMAIL_LIKE_DOMAINS = {
"googlemail.com",
}
# Well-known email providers that are never disposable.
# These skip all external API checks for zero-latency validation.
WELL_KNOWN_PROVIDERS = {
"gmail.com",
"googlemail.com",
"yahoo.com",
"yahoo.co.uk",
"yahoo.co.jp",
"yahoo.fr",
"hotmail.com",
"hotmail.co.uk",
"outlook.com",
"outlook.fr",
"live.com",
"live.co.uk",
"msn.com",
"icloud.com",
"me.com",
"mac.com",
"aol.com",
"protonmail.com",
"proton.me",
"zoho.com",
"yandex.com",
"yandex.ru",
"mail.com",
"gmx.com",
"gmx.de",
"fastmail.com",
"hey.com",
"tutanota.com",
"tuta.io",
}
# How long a verified-clean domain result is trusted before re-checking
VERIFIED_CLEAN_TTL = timedelta(days=7)
# External API URLs
DEBOUNCE_API_URL = "https://disposable.debounce.io/"
VERIFYMAIL_API_URL = "https://verifymail.io/api"
class EmailValidationService:
"""
@@ -293,17 +204,30 @@ class EmailValidationService:
if doc.exists:
data = doc.to_dict()
if "external_domains" in data:
# New data model: effective = (external + manual) - allowlisted
external = set(data.get("external_domains", []))
manual = set(data.get("manual_domains", []))
allowlisted = set(data.get("allowlisted_domains", []))
effective_domains = (external | manual) - allowlisted
else:
# Old data model (pre-migration): use disposable_domains + defaults
allowlisted = set()
effective_domains = set(data.get("disposable_domains", [])) | DEFAULT_DISPOSABLE_DOMAINS
config = {
"disposable_domains": set(data.get("disposable_domains", [])) | DEFAULT_DISPOSABLE_DOMAINS,
"disposable_domains": effective_domains,
"allowlisted_domains": allowlisted,
"blocked_emails": set(data.get("blocked_emails", [])),
"blocked_ips": set(data.get("blocked_ips", [])),
"verified_clean_domains": data.get("verified_clean_domains", {}),
}
else:
# Use defaults if no config exists
config = {
"disposable_domains": DEFAULT_DISPOSABLE_DOMAINS.copy(),
"allowlisted_domains": set(),
"blocked_emails": set(),
"blocked_ips": set(),
"verified_clean_domains": {},
}
# Update cache
@@ -316,6 +240,16 @@ class EmailValidationService:
"""
Check if an email uses a disposable domain.
Uses a tiered checking strategy:
0. Well-known providers (gmail, yahoo, etc.) → instant False
1. Static blocklist from Firestore → instant
2. Verified-clean cache (7-day TTL) → skip API calls
3. DeBounce API (free) → fast external check
4. verifymail.io API (paid) → only if DeBounce says clean
Flagged domains are auto-learned to manual_domains.
Clean domains are cached for 7 days.
Args:
email: Email address to check
@@ -326,8 +260,194 @@ class EmailValidationService:
return False
domain = email.lower().split("@")[-1]
# Tier 0: Well-known providers — skip everything
if domain in WELL_KNOWN_PROVIDERS:
return False
# Tier 1: Static blocklist (instant, always available)
config = self.get_blocklist_config()
return domain in config["disposable_domains"]
if domain in config["disposable_domains"]:
return True
# Tier 1.5: Explicitly allowlisted domains skip external API checks.
# Without this, external APIs can override admin allowlist decisions
# (e.g. inbox.testmail.app is a legitimate testing domain we allow).
if domain in config.get("allowlisted_domains", set()):
return False
# Tier 2: Recently verified clean? Skip API calls
if self._is_domain_verified_clean(domain, config):
return False
# Tier 3: DeBounce API (free, fast)
debounce_result = self._check_debounce(email)
if debounce_result is True:
self._auto_learn_domain(domain)
return True
# Tier 4: verifymail.io (paid, only if DeBounce gave definitive clean)
if debounce_result is False:
verifymail_result = self._check_verifymail(email)
if verifymail_result is True:
self._auto_learn_domain(domain)
return True
# Both APIs say clean (or errored) — cache clean result
if debounce_result is False:
self._mark_domain_clean(domain)
return False
def _check_debounce(self, email: str) -> Optional[bool]:
"""
Check email against DeBounce disposable email API.
Returns:
True if disposable, False if clean, None if error/timeout.
"""
try:
client = _get_http_client()
response = client.get(DEBOUNCE_API_URL, params={"email": email})
response.raise_for_status()
data = response.json()
result = str(data.get("disposable", "")).lower() == "true"
logger.info(
f"DeBounce check for {_mask_email(email)}: "
f"disposable={result}"
)
return result
except httpx.TimeoutException:
logger.warning(f"DeBounce API timeout for {_mask_email(email)}")
return None
except Exception as e:
logger.warning(f"DeBounce API error for {_mask_email(email)}: {e}")
return None
def _check_verifymail(self, email: str) -> Optional[bool]:
"""
Check email against verifymail.io API.
Only called when DeBounce says clean (to minimize paid API usage).
Returns:
True if disposable/blocked, False if clean, None if error/timeout
or API key not configured.
"""
api_key = settings.get_secret("verifymail-api-key")
if not api_key:
logger.debug("verifymail.io API key not configured, skipping")
return None
try:
client = _get_http_client()
response = client.get(
f"{VERIFYMAIL_API_URL}/{email}",
params={"key": api_key},
)
response.raise_for_status()
data = response.json()
# verifymail.io returns both "disposable" and "block" flags
is_disposable = data.get("disposable") is True
is_blocked = data.get("block") is True
result = is_disposable or is_blocked
logger.info(
f"verifymail.io check for {_mask_email(email)}: "
f"disposable={is_disposable}, block={is_blocked}"
)
return result
except httpx.TimeoutException:
logger.warning(f"verifymail.io API timeout for {_mask_email(email)}")
return None
except Exception as e:
logger.warning(f"verifymail.io API error for {_mask_email(email)}: {e}")
return None
def _is_domain_verified_clean(self, domain: str, config: dict) -> bool:
"""Check if a domain was verified clean within the TTL period."""
verified = config.get("verified_clean_domains", {})
entry = verified.get(domain)
if not entry:
return False
checked_at = entry.get("checked_at")
if not checked_at:
return False
# Handle both datetime objects and ISO strings
if isinstance(checked_at, str):
try:
checked_at = datetime.fromisoformat(checked_at)
except (ValueError, TypeError):
return False
# Make timezone-aware if naive
if checked_at.tzinfo is None:
checked_at = checked_at.replace(tzinfo=timezone.utc)
return (datetime.now(timezone.utc) - checked_at) < VERIFIED_CLEAN_TTL
def _auto_learn_domain(self, domain: str) -> None:
"""
Add a domain flagged by external API to manual_domains in Firestore.
This persists the result so future checks don't need the API call.
Fire-and-forget: errors are logged but don't affect the caller.
"""
try:
doc_ref = self.db.collection(BLOCKLISTS_COLLECTION).document(
BLOCKLIST_CONFIG_DOC
)
doc = doc_ref.get()
if doc.exists:
data = doc.to_dict()
manual = set(data.get("manual_domains", []))
else:
manual = set()
if domain not in manual:
manual.add(domain)
doc_ref.set(
{
"manual_domains": list(manual),
"updated_at": datetime.now(timezone.utc).isoformat(),
"updated_by": "auto-learn",
},
merge=True,
)
logger.info(f"Auto-learned disposable domain: {domain}")
# Invalidate cache so the domain is blocked immediately
EmailValidationService._blocklist_cache = None
except Exception as e:
logger.error(f"Failed to auto-learn domain {domain}: {e}")
def _mark_domain_clean(self, domain: str) -> None:
"""
Record that a domain was verified clean by external APIs.
Stored in verified_clean_domains dict keyed by domain.
Future checks within VERIFIED_CLEAN_TTL will skip API calls.
Note: Uses read-modify-write instead of dot notation because
domain names contain dots which Firestore interprets as nested paths.
"""
try:
doc_ref = self.db.collection(BLOCKLISTS_COLLECTION).document(
BLOCKLIST_CONFIG_DOC
)
doc = doc_ref.get()
verified = doc.to_dict().get("verified_clean_domains", {}) if doc.exists else {}
verified[domain] = {
"checked_at": datetime.now(timezone.utc).isoformat(),
}
doc_ref.set({"verified_clean_domains": verified}, merge=True)
logger.debug(f"Marked domain as verified clean: {domain}")
# Invalidate cache so new data is picked up
EmailValidationService._blocklist_cache = None
except Exception as e:
logger.error(f"Failed to mark domain clean {domain}: {e}")
def is_email_blocked(self, email: str) -> bool:
"""
@@ -398,13 +518,13 @@ class EmailValidationService:
doc = doc_ref.get(transaction=transaction)
if doc.exists:
data = doc.to_dict()
domains = set(data.get("disposable_domains", []))
domains = set(data.get("manual_domains", []))
else:
data = {}
domains = set()
domains.add(domain)
data["disposable_domains"] = list(domains)
data["manual_domains"] = list(domains)
data["updated_at"] = datetime.now(timezone.utc)
data["updated_by"] = admin_email
transaction.set(doc_ref, data, merge=True)
@@ -432,14 +552,22 @@ class EmailValidationService:
return
data = doc.to_dict()
domains = set(data.get("disposable_domains", []))
if domain not in domains:
manual = set(data.get("manual_domains", []))
external = set(data.get("external_domains", []))
if domain in manual:
result["found"] = True
manual.discard(domain)
data["manual_domains"] = list(manual)
elif domain in external:
result["found"] = True
allowlisted = set(data.get("allowlisted_domains", []))
allowlisted.add(domain)
data["allowlisted_domains"] = list(allowlisted)
else:
return
result["found"] = True
domains.discard(domain)
data["disposable_domains"] = list(domains)
data["updated_at"] = datetime.now(timezone.utc)
data["updated_by"] = admin_email
transaction.set(doc_ref, data, merge=True)
@@ -598,14 +726,126 @@ class EmailValidationService:
logger.info(f"Removed blocked IP: {ip_address} by {admin_email}")
return True
def add_allowlisted_domain(self, domain: str, admin_email: str) -> bool:
"""Add a domain to the allowlisted domains list."""
domain = domain.lower().strip()
if not domain:
return False
doc_ref = self.db.collection(BLOCKLISTS_COLLECTION).document(BLOCKLIST_CONFIG_DOC)
@firestore.transactional
def update_in_transaction(transaction, doc_ref):
doc = doc_ref.get(transaction=transaction)
if doc.exists:
data = doc.to_dict()
domains = set(data.get("allowlisted_domains", []))
else:
data = {}
domains = set()
domains.add(domain)
data["allowlisted_domains"] = list(domains)
data["updated_at"] = datetime.now(timezone.utc)
data["updated_by"] = admin_email
transaction.set(doc_ref, data, merge=True)
transaction = self.db.transaction()
update_in_transaction(transaction, doc_ref)
# Invalidate cache
EmailValidationService._blocklist_cache = None
logger.info(f"Added allowlisted domain: {domain} by {admin_email}")
return True
def remove_allowlisted_domain(self, domain: str, admin_email: str) -> bool:
"""Remove a domain from the allowlisted domains list."""
domain = domain.lower().strip()
doc_ref = self.db.collection(BLOCKLISTS_COLLECTION).document(BLOCKLIST_CONFIG_DOC)
result = {"found": False}
@firestore.transactional
def remove_in_transaction(transaction, doc_ref):
doc = doc_ref.get(transaction=transaction)
if not doc.exists:
return
data = doc.to_dict()
domains = set(data.get("allowlisted_domains", []))
if domain not in domains:
return
result["found"] = True
domains.discard(domain)
data["allowlisted_domains"] = list(domains)
data["updated_at"] = datetime.now(timezone.utc)
data["updated_by"] = admin_email
transaction.set(doc_ref, data, merge=True)
transaction = self.db.transaction()
remove_in_transaction(transaction, doc_ref)
if not result["found"]:
return False
# Invalidate cache
EmailValidationService._blocklist_cache = None
logger.info(f"Removed allowlisted domain: {domain} by {admin_email}")
return True
def get_blocklist_raw_data(self) -> dict:
"""Get raw blocklist data for admin display (not the effective set)."""
doc_ref = self.db.collection(BLOCKLISTS_COLLECTION).document(BLOCKLIST_CONFIG_DOC)
doc = doc_ref.get()
if not doc.exists:
return {
"external_domains": [], "manual_domains": [], "allowlisted_domains": [],
"blocked_emails": [], "blocked_ips": [],
"last_sync_at": None, "last_sync_count": None,
"updated_at": None, "updated_by": None,
}
data = doc.to_dict()
return {
"external_domains": sorted(data.get("external_domains", [])),
"manual_domains": sorted(data.get("manual_domains", [])),
"allowlisted_domains": sorted(data.get("allowlisted_domains", [])),
"blocked_emails": sorted(data.get("blocked_emails", [])),
"blocked_ips": sorted(data.get("blocked_ips", [])),
"last_sync_at": data.get("last_sync_at"),
"last_sync_count": data.get("last_sync_count"),
"updated_at": data.get("updated_at"),
"updated_by": data.get("updated_by"),
}
def get_blocklist_stats(self) -> dict:
"""Get statistics about current blocklists."""
config = self.get_blocklist_config(force_refresh=True)
# Also get raw data for detailed counts
doc_ref = self.db.collection(BLOCKLISTS_COLLECTION).document(BLOCKLIST_CONFIG_DOC)
doc = doc_ref.get()
if doc.exists:
data = doc.to_dict()
external_count = len(data.get("external_domains", []))
manual_count = len(data.get("manual_domains", []))
allowlisted_count = len(data.get("allowlisted_domains", []))
else:
external_count = 0
manual_count = 0
allowlisted_count = 0
return {
"disposable_domains_count": len(config["disposable_domains"]),
"blocked_emails_count": len(config["blocked_emails"]),
"blocked_ips_count": len(config["blocked_ips"]),
"default_disposable_domains_count": len(DEFAULT_DISPOSABLE_DOMAINS),
"external_domains_count": external_count,
"manual_domains_count": manual_count,
"allowlisted_domains_count": allowlisted_count,
}
+3
View File
@@ -383,6 +383,8 @@ class GCEEncodingBackend(EncodingBackend):
output_files["mp4_4k_lossy"] = path
elif "720p" in filename_lower:
output_files["mp4_720p"] = path
elif "with vocals" in filename_lower and filename.endswith(".mp4"):
output_files["with_vocals_mp4"] = path
self.logger.info(f"Converted output_files list to dict: {output_files}")
else:
output_files = raw_output_files if isinstance(raw_output_files, dict) else {}
@@ -393,6 +395,7 @@ class GCEEncodingBackend(EncodingBackend):
lossy_4k_mp4_path=output_files.get("mp4_4k_lossy"),
lossless_mkv_path=output_files.get("mkv_4k"),
lossy_720p_mp4_path=output_files.get("mp4_720p"),
with_vocals_mp4_path=output_files.get("with_vocals_mp4"),
output_files=output_files,
encoding_time_seconds=encoding_time,
encoding_backend=self.name
+183 -4
View File
@@ -17,6 +17,7 @@ Usage:
import asyncio
import logging
import time
from typing import Optional, Dict, Any
import aiohttp
@@ -52,6 +53,34 @@ class EncodingService:
self._url = None
self._api_key = None
self._initialized = False
self._worker_manager = None
self._cached_url = None
self._url_cached_at = 0
self._URL_CACHE_TTL = 30 # seconds
def set_worker_manager(self, manager):
"""Set the worker manager for dynamic URL resolution from Firestore."""
self._worker_manager = manager
def _get_worker_url(self) -> str:
"""Get the current primary worker URL from Firestore (with TTL cache).
Falls back to static URL from config if worker_manager is not set.
"""
now = time.time()
if self._cached_url and (now - self._url_cached_at) < self._URL_CACHE_TTL:
return self._cached_url
if self._worker_manager:
config = self._worker_manager.get_config()
self._cached_url = config.primary_url
self._url_cached_at = now
return self._cached_url
# Fallback to static URL
if not self._initialized:
self._load_credentials()
return self._url
def _load_credentials(self):
"""Load encoding worker URL and API key from config/secrets."""
@@ -86,6 +115,28 @@ class EncodingService:
"""Check if GCE preview encoding is enabled and configured."""
return self.settings.use_gce_preview_encoding and self.is_configured
def _warmup_encoding_worker_fallback(self, job_id: str) -> None:
"""Safety net: try to start the encoding worker VM on first connection failure.
If the worker_manager is available, calls ensure_primary_running() so the VM
starts booting during the retry window. If worker_manager is not set (e.g. dev
mode with static URL), this is a no-op.
"""
if not self._worker_manager:
return
try:
result = self._worker_manager.ensure_primary_running()
if result["started"]:
logger.warning(
f"[job:{job_id}] Encoding worker unreachable — started VM {result['vm_name']} as fallback"
)
else:
logger.info(
f"[job:{job_id}] Encoding worker unreachable — VM {result['vm_name']} already running/starting"
)
except Exception as e:
logger.warning(f"[job:{job_id}] Encoding worker warmup fallback failed (non-fatal): {e}")
async def _request_with_retry(
self,
method: str,
@@ -147,6 +198,8 @@ class EncodingService:
}
except (aiohttp.ClientConnectorError, aiohttp.ServerDisconnectedError, asyncio.TimeoutError) as e:
last_exception = e
if attempt == 0:
self._warmup_encoding_worker_fallback(job_id)
if attempt < MAX_RETRIES:
logger.warning(
f"[job:{job_id}] GCE worker connection failed (attempt {attempt + 1}/{MAX_RETRIES + 1}): {e}. "
@@ -188,7 +241,7 @@ class EncodingService:
if not self.is_configured:
raise RuntimeError("Encoding service not configured")
url = f"{self._url}/encode"
url = f"{self._get_worker_url()}/encode"
headers = {"X-API-Key": self._api_key, "Content-Type": "application/json"}
payload = {
"job_id": job_id,
@@ -249,7 +302,7 @@ class EncodingService:
if not self.is_configured:
raise RuntimeError("Encoding service not configured")
url = f"{self._url}/status/{job_id}"
url = f"{self._get_worker_url()}/status/{job_id}"
headers = {"X-API-Key": self._api_key}
resp = await self._request_with_retry(
@@ -437,7 +490,7 @@ class EncodingService:
if not self.is_configured:
raise RuntimeError("Encoding service not configured")
url = f"{self._url}/encode-preview"
url = f"{self._get_worker_url()}/encode-preview"
headers = {"X-API-Key": self._api_key, "Content-Type": "application/json"}
payload = {
"job_id": job_id,
@@ -531,6 +584,116 @@ class EncodingService:
timeout=timeout,
)
async def submit_render_video_job(
self,
job_id: str,
render_config: Dict[str, Any],
) -> Dict[str, Any]:
"""
Submit a render-video job to the GCE worker.
Args:
job_id: Unique job identifier
render_config: Configuration dict containing original_corrections_gcs_path,
audio_gcs_path, output_gcs_prefix, artist, title, and any other render params.
Returns:
Response from the encoding worker
Raises:
RuntimeError: If submission fails
"""
self._load_credentials()
if not self.is_configured:
raise RuntimeError("Encoding service not configured")
url = f"{self._get_worker_url()}/render-video"
headers = {"X-API-Key": self._api_key, "Content-Type": "application/json"}
payload = {"job_id": job_id, **render_config}
logger.info(f"[job:{job_id}] Submitting render-video job to GCE worker: {url}")
resp = await self._request_with_retry(
method="POST",
url=url,
headers=headers,
json_payload=payload,
timeout=30.0,
job_id=job_id,
)
if resp["status"] == 401:
raise RuntimeError("Invalid API key for encoding worker")
if resp["status"] == 409:
# Job already exists on worker — check if it already completed
logger.warning(f"[job:{job_id}] GCE worker returned 409, checking job status")
try:
status = await self.get_job_status(job_id)
job_status = status.get("status", "unknown")
if job_status == "complete":
logger.info(f"[job:{job_id}] Render-video job already complete on GCE worker, returning cached result")
return {
"status": "cached",
"job_id": job_id,
"output_files": status.get("output_files"),
"metadata": status.get("metadata"),
}
elif job_status in ("pending", "running"):
logger.info(f"[job:{job_id}] Render-video job still in progress on GCE worker")
return {"status": "in_progress", "job_id": job_id}
else:
raise RuntimeError(f"Render-video job {job_id} already exists with status: {job_status}")
except RuntimeError as e:
if "not found" in str(e).lower():
raise RuntimeError(f"Render-video job {job_id} conflict: 409 but job not found on status check")
raise
if resp["status"] != 200:
raise RuntimeError(f"Failed to submit render-video job: {resp['status']} - {resp['text']}")
return resp["json"]
async def render_video_on_gce(
self,
job_id: str,
render_config: Dict[str, Any],
progress_callback=None,
) -> Dict[str, Any]:
"""
Submit render-video job and wait for completion.
This is a convenience method that combines submit + wait.
Args:
job_id: Unique job identifier
render_config: Configuration dict for the render-video worker endpoint
progress_callback: Optional callback for progress updates
Returns:
Final job status with output files and metadata
"""
# Submit the job
submit_result = await self.submit_render_video_job(job_id, render_config)
# If cached, return immediately — rendering already done
submit_status = submit_result.get("status")
if submit_status == "cached":
logger.info(f"[job:{job_id}] Render-video already cached, returning immediately")
return {
"status": "complete",
"output_files": submit_result.get("output_files"),
"metadata": submit_result.get("metadata"),
}
# If in_progress, another request is rendering it — just wait for that
if submit_status == "in_progress":
logger.info(f"[job:{job_id}] Render-video already in progress, joining poll")
# Wait for completion
return await self.wait_for_completion(
job_id, progress_callback=progress_callback
)
async def health_check(self) -> Dict[str, Any]:
"""
Check the health of the encoding worker.
@@ -543,7 +706,7 @@ class EncodingService:
if not self.is_configured:
return {"status": "not_configured"}
url = f"{self._url}/health"
url = f"{self._get_worker_url()}/health"
headers = {"X-API-Key": self._api_key}
try:
@@ -565,4 +728,20 @@ def get_encoding_service() -> EncodingService:
global _encoding_service
if _encoding_service is None:
_encoding_service = EncodingService()
# Wire up worker manager for dynamic URL resolution
try:
from backend.services.encoding_worker_manager import EncodingWorkerManager
from google.cloud import compute_v1, firestore
settings = get_settings()
db = firestore.Client(project=settings.google_cloud_project)
compute_client = compute_v1.InstancesClient()
manager = EncodingWorkerManager(
db=db,
compute_client=compute_client,
project_id=settings.google_cloud_project,
)
_encoding_service.set_worker_manager(manager)
except Exception:
# Fallback to static URL if worker manager setup fails
pass
return _encoding_service
+239
View File
@@ -0,0 +1,239 @@
"""
Blue-Green Encoding Worker Manager.
Manages the lifecycle and role assignment of two GCE encoding worker VMs
(blue/green) via a Firestore config document as the single source of truth.
The config document at `config/encoding-worker` tracks which VM is primary
(actively serving encoding requests) and which is secondary (idle or being
deployed to). This enables zero-downtime deployments by swapping roles
after deploying new code to the secondary.
Usage:
from google.cloud import firestore
from google.cloud.compute_v1 import InstancesClient
db = firestore.Client()
compute = InstancesClient()
manager = EncodingWorkerManager(db, compute)
# Get current config
config = manager.get_config()
print(f"Primary: {config.primary_vm} at {config.primary_url}")
# Ensure primary VM is running before dispatching work
result = manager.ensure_primary_running()
"""
import logging
from dataclasses import dataclass
from datetime import datetime, UTC
from typing import Optional
from google.cloud import firestore
logger = logging.getLogger(__name__)
CONFIG_COLLECTION = "config"
CONFIG_DOCUMENT = "encoding-worker"
ENCODING_WORKER_PORT = 8080
@dataclass
class EncodingWorkerConfig:
"""Represents the Firestore config/encoding-worker document."""
primary_vm: str
primary_ip: str
primary_version: str
primary_deployed_at: Optional[str]
secondary_vm: str
secondary_ip: str
secondary_version: Optional[str]
secondary_deployed_at: Optional[str]
last_swap_at: Optional[str]
last_activity_at: Optional[str]
deploy_in_progress: bool
deploy_in_progress_since: Optional[str]
@property
def primary_url(self) -> str:
return f"http://{self.primary_ip}:{ENCODING_WORKER_PORT}"
@property
def secondary_url(self) -> str:
return f"http://{self.secondary_ip}:{ENCODING_WORKER_PORT}"
class EncodingWorkerManager:
"""Manages blue-green encoding worker VMs via Firestore config and Compute API."""
def __init__(self, db, compute_client=None, project_id="nomadkaraoke", zone="us-central1-c"):
self._db = db
self._compute = compute_client
self._project_id = project_id
self._zone = zone
def _doc_ref(self):
"""Return a reference to the config/encoding-worker document."""
return self._db.collection(CONFIG_COLLECTION).document(CONFIG_DOCUMENT)
# ------------------------------------------------------------------
# Firestore config operations (Task 1)
# ------------------------------------------------------------------
def get_config(self) -> EncodingWorkerConfig:
"""Read config/encoding-worker from Firestore and return as dataclass."""
snapshot = self._doc_ref().get()
if not snapshot.exists:
raise ValueError(
f"Encoding worker config document not found at "
f"{CONFIG_COLLECTION}/{CONFIG_DOCUMENT}"
)
data = snapshot.to_dict()
return EncodingWorkerConfig(
primary_vm=data["primary_vm"],
primary_ip=data["primary_ip"],
primary_version=data["primary_version"],
primary_deployed_at=data.get("primary_deployed_at"),
secondary_vm=data["secondary_vm"],
secondary_ip=data["secondary_ip"],
secondary_version=data.get("secondary_version"),
secondary_deployed_at=data.get("secondary_deployed_at"),
last_swap_at=data.get("last_swap_at"),
last_activity_at=data.get("last_activity_at"),
deploy_in_progress=data.get("deploy_in_progress", False),
deploy_in_progress_since=data.get("deploy_in_progress_since"),
)
def update_activity(self) -> None:
"""Update last_activity_at timestamp to record recent usage."""
now = datetime.now(UTC).isoformat()
self._doc_ref().update({"last_activity_at": now})
logger.info("Updated encoding worker last_activity_at to %s", now)
def swap_roles(
self,
new_primary_vm: str,
new_primary_ip: str,
new_primary_version: str,
old_primary_vm: str,
old_primary_ip: str,
old_primary_version: str,
) -> None:
"""Atomically swap primary and secondary roles using a Firestore transaction.
Args:
new_primary_vm: VM name that will become the new primary.
new_primary_ip: Internal IP of the new primary.
new_primary_version: Version deployed on the new primary.
old_primary_vm: Current primary VM name (becomes secondary).
old_primary_ip: Internal IP of the old primary.
old_primary_version: Version on the old primary.
"""
transaction = self._db.transaction()
doc_ref = self._doc_ref()
now = datetime.now(UTC).isoformat()
@firestore.transactional
def _swap_in_transaction(txn, ref):
txn.update(ref, {
"primary_vm": new_primary_vm,
"primary_ip": new_primary_ip,
"primary_version": new_primary_version,
"primary_deployed_at": now,
"secondary_vm": old_primary_vm,
"secondary_ip": old_primary_ip,
"secondary_version": old_primary_version,
"secondary_deployed_at": None,
"last_swap_at": now,
"deploy_in_progress": False,
"deploy_in_progress_since": None,
})
_swap_in_transaction(transaction, doc_ref)
logger.info(
"Swapped encoding worker roles: %s -> primary, %s -> secondary",
new_primary_vm, old_primary_vm,
)
# ------------------------------------------------------------------
# VM lifecycle operations (Task 2)
# ------------------------------------------------------------------
def get_vm_status(self, vm_name: str) -> str:
"""Get the current status of a GCE VM (e.g. RUNNING, TERMINATED, STAGING)."""
instance = self._compute.get(
project=self._project_id,
zone=self._zone,
instance=vm_name,
)
return instance.status
def start_vm(self, vm_name: str) -> None:
"""Start a VM if it is not already running or starting.
Fire-and-forget: returns immediately. Caller should poll get_vm_status
if they need to wait for the VM to be fully RUNNING.
"""
status = self.get_vm_status(vm_name)
if status in ("RUNNING", "STAGING"):
logger.info("VM %s is already %s, skipping start", vm_name, status)
return
logger.info("Starting VM %s (current status: %s)", vm_name, status)
self._compute.start(
project=self._project_id,
zone=self._zone,
instance=vm_name,
)
def stop_vm(self, vm_name: str) -> None:
"""Stop a VM if it is not already stopped or stopping."""
status = self.get_vm_status(vm_name)
if status in ("TERMINATED", "STOPPING"):
logger.info("VM %s is already %s, skipping stop", vm_name, status)
return
logger.info("Stopping VM %s (current status: %s)", vm_name, status)
self._compute.stop(
project=self._project_id,
zone=self._zone,
instance=vm_name,
)
def ensure_primary_running(self) -> dict:
"""Ensure the primary encoding worker VM is running.
Reads config, starts primary VM if stopped, and updates activity timestamp.
Returns:
dict with keys:
- started (bool): True if VM was started, False if already running
- vm_name (str): Name of the primary VM
- primary_url (str): URL of the primary encoding worker
"""
config = self.get_config()
vm_name = config.primary_vm
status = self.get_vm_status(vm_name)
started = False
if status not in ("RUNNING", "STAGING"):
logger.info("Primary VM %s is %s, starting it", vm_name, status)
self._compute.start(
project=self._project_id,
zone=self._zone,
instance=vm_name,
)
started = True
else:
logger.info("Primary VM %s is already %s", vm_name, status)
self.update_activity()
return {
"started": started,
"vm_name": vm_name,
"primary_url": config.primary_url,
}
+14 -6
View File
@@ -182,11 +182,14 @@ class FirestoreService:
SUMMARY_FIELD_PATHS = [
'job_id', 'status', 'progress', 'created_at', 'artist', 'title',
'error_message', 'non_interactive', 'outputs_deleted_at', 'user_email', 'is_private',
'url', 'filename', 'audio_search_artist', 'audio_search_title',
'audio_source_type', 'source_name', 'source_id', 'target_file', 'download_url',
'state_data.brand_code', 'state_data.youtube_url', 'state_data.dropbox_link',
'state_data.audio_progress', 'state_data.lyrics_progress',
'state_data.audio_complete', 'state_data.lyrics_complete',
'state_data.backing_vocals_analysis', 'state_data.visibility_change_in_progress',
'file_urls.finals', 'file_urls.videos', 'file_urls.packages',
'processing_metadata',
]
def list_jobs_summary(
@@ -868,12 +871,14 @@ class FirestoreService:
# Collection group query across all jobs
sessions_ref = self.db.collection_group("review_sessions")
query = sessions_ref.order_by("updated_at", direction=firestore.Query.DESCENDING).limit(limit)
docs = query.stream()
results = [doc.to_dict() for doc in docs]
# Filter in Python for text search (Firestore doesn't support LIKE)
if query_text:
# Over-fetch since we filter in Python (Firestore doesn't support LIKE/contains)
fetch_limit = max(limit * 25, 500)
query = sessions_ref.order_by("updated_at", direction=firestore.Query.DESCENDING).limit(fetch_limit)
docs = query.stream()
results = [doc.to_dict() for doc in docs]
q_lower = query_text.lower()
results = [
r for r in results
@@ -881,8 +886,11 @@ class FirestoreService:
or q_lower in (r.get("title") or "").lower()
or q_lower in (r.get("job_id") or "").lower()
]
return results
return results[:limit]
else:
query = sessions_ref.order_by("updated_at", direction=firestore.Query.DESCENDING).limit(limit)
docs = query.stream()
return [doc.to_dict() for doc in docs]
except Exception as e:
logger.error(f"Error searching review sessions: {e}")
+385 -2
View File
@@ -1,9 +1,11 @@
import asyncio
import glob as glob_module
import hashlib
import json
import logging
import os
import re
import shutil
import subprocess
import sys
import tempfile
@@ -59,12 +61,27 @@ class EncodePreviewRequest(BaseModel):
font_gcs_path: Optional[str] = None # gs://bucket/path/to/custom-font.ttf
class RenderVideoRequest(BaseModel):
job_id: str
original_corrections_gcs_path: str
updated_corrections_gcs_path: Optional[str] = None
audio_gcs_path: str
style_params_gcs_path: Optional[str] = None
style_assets: Optional[dict] = None
output_gcs_prefix: str
artist: str
title: str
subtitle_offset_ms: int = 0
video_resolution: str = "4k"
class JobStatus(BaseModel):
job_id: str
status: str # pending, running, complete, failed
progress: int # 0-100
error: Optional[str] = None
output_files: Optional[list[str]] = None
metadata: Optional[dict] = None
def download_from_gcs(gcs_uri: str, local_path: Path):
@@ -136,6 +153,59 @@ def upload_single_file_to_gcs(local_path: Path, gcs_uri: str):
logger.info(f"Uploaded: {local_path} -> {gcs_uri}")
# Style asset disk cache directory
# Persists across jobs to avoid re-downloading the same theme assets (fonts, backgrounds)
STYLE_CACHE_DIR = Path("/var/cache/karaoke-gen/styles")
def download_with_cache(gcs_uri: str, local_path: Path, cache_dir: Optional[Path] = STYLE_CACHE_DIR):
"""Download a file from GCS, using a local disk cache to skip repeated downloads.
Cache key is SHA-256 of the GCS URI. Cache hits are validated by comparing
the cached file size against the GCS object size (via a lightweight metadata
call). On size mismatch the stale entry is replaced.
When cache_dir is None, downloads directly (no caching).
"""
if cache_dir is None:
download_single_file_from_gcs(gcs_uri, local_path)
return
cache_dir.mkdir(parents=True, exist_ok=True)
cache_key = hashlib.sha256(gcs_uri.encode()).hexdigest()
cached_path = cache_dir / cache_key
if cached_path.exists():
# Validate cached file against GCS object size
try:
parts = gcs_uri.replace("gs://", "").split("/", 1)
bucket_name = parts[0]
blob_name = parts[1] if len(parts) > 1 else ""
blob = storage_client.bucket(bucket_name).blob(blob_name)
blob.reload() # Fetch metadata (lightweight HEAD request)
gcs_size = blob.size
cached_size = cached_path.stat().st_size
if gcs_size is not None and cached_size != gcs_size:
logger.warning(
f"Cache stale for {gcs_uri}: cached={cached_size}B, GCS={gcs_size}B. Re-downloading."
)
cached_path.unlink()
else:
logger.info(f"Cache hit for {gcs_uri} -> {cached_path}")
shutil.copy2(str(cached_path), str(local_path))
return
except Exception as e:
# On transient GCS errors, serve from cache rather than failing the job
logger.warning(f"Cache validation failed for {gcs_uri}: {e}. Serving from cache.")
shutil.copy2(str(cached_path), str(local_path))
return
logger.info(f"Cache miss for {gcs_uri}, downloading...")
download_single_file_from_gcs(gcs_uri, local_path)
# Store in cache
shutil.copy2(str(local_path), str(cached_path))
def run_preview_encoding(job_id: str, work_dir: Path, request: "EncodePreviewRequest"):
# Run FFmpeg encoding for preview video (480x270, fast settings)
jobs[job_id]["status"] = "running"
@@ -239,6 +309,192 @@ def run_preview_encoding(job_id: str, work_dir: Path, request: "EncodePreviewReq
raise
def run_render_video(job_id: str, work_dir: Path, request: "RenderVideoRequest"):
"""Run video rendering using OutputGenerator from the karaoke-gen wheel.
Downloads corrections, audio, and style assets from GCS, runs OutputGenerator
to produce with_vocals.mkv and subtitle files, then uploads results.
Style assets use disk cache to avoid repeated downloads of the same theme.
This mirrors the logic in render_video_worker.py but runs on the GCE VM
instead of Cloud Run, providing more memory and CPU for ffmpeg/libass.
"""
jobs[job_id]["status"] = "running"
jobs[job_id]["progress"] = 5
try:
# Import from installed karaoke-gen wheel
from karaoke_gen.lyrics_transcriber.output.generator import OutputGenerator
from karaoke_gen.lyrics_transcriber.output.countdown_processor import CountdownProcessor
from karaoke_gen.lyrics_transcriber.types import CorrectionResult
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
from karaoke_gen.lyrics_transcriber.core.config import OutputConfig
from karaoke_gen.style_loader import load_styles_from_gcs
from karaoke_gen.utils import sanitize_filename
# 1. Download original corrections
corrections_path = work_dir / "corrections.json"
download_single_file_from_gcs(request.original_corrections_gcs_path, corrections_path)
jobs[job_id]["progress"] = 15
with open(corrections_path, 'r', encoding='utf-8') as f:
original_data = json.load(f)
base_result = CorrectionResult.from_dict(original_data)
# 2. Apply user corrections if available
if request.updated_corrections_gcs_path:
updated_path = work_dir / "corrections_updated.json"
download_single_file_from_gcs(request.updated_corrections_gcs_path, updated_path)
with open(updated_path, 'r', encoding='utf-8') as f:
updated_data = json.load(f)
if isinstance(updated_data, dict) and "corrections" in updated_data:
correction_result = CorrectionOperations.update_correction_result_with_data(
base_result, updated_data
)
logger.info(f"[job:{job_id}] Applied user corrections")
else:
logger.warning(f"[job:{job_id}] corrections_updated.json exists but has no 'corrections' key, using base result")
correction_result = base_result
else:
correction_result = base_result
jobs[job_id]["progress"] = 25
# 3. Download audio
audio_path = work_dir / "audio.flac"
download_single_file_from_gcs(request.audio_gcs_path, audio_path)
jobs[job_id]["progress"] = 35
# 4. Process countdown intro
countdown_processor = CountdownProcessor(cache_dir=str(work_dir), logger=logger)
correction_result, audio_path_str, padding_added, padding_seconds = countdown_processor.process(
correction_result=correction_result,
audio_filepath=str(audio_path),
)
audio_path = Path(audio_path_str)
jobs[job_id]["progress"] = 40
# 5. Download style assets (with disk cache for repeated themes)
def cached_download(gcs_path, local_path):
download_with_cache(gcs_path, Path(local_path), STYLE_CACHE_DIR)
styles_path, style_data = load_styles_from_gcs(
style_params_gcs_path=request.style_params_gcs_path,
style_assets=request.style_assets,
temp_dir=str(work_dir),
download_func=cached_download,
logger=logger,
)
# Register any downloaded fonts with fontconfig
for asset_key, gcs_path in (request.style_assets or {}).items():
if 'font' in asset_key.lower() and gcs_path.endswith(('.ttf', '.otf', '.woff', '.woff2')):
fonts_dir = Path("/usr/local/share/fonts/custom")
fonts_dir.mkdir(parents=True, exist_ok=True)
font_filename = gcs_path.split("/")[-1]
font_dest = fonts_dir / font_filename
if not font_dest.exists():
ext = os.path.splitext(gcs_path)[1]
style_font = work_dir / "style" / f"{asset_key}{ext}"
if style_font.exists():
shutil.copy2(str(style_font), str(font_dest))
subprocess.run(["fc-cache", "-fv"], capture_output=True)
logger.info(f"Registered font: {font_filename}")
jobs[job_id]["progress"] = 50
# 6. Configure and run OutputGenerator
output_dir = work_dir / "output"
cache_dir = work_dir / "cache"
output_dir.mkdir(exist_ok=True)
cache_dir.mkdir(exist_ok=True)
config = OutputConfig(
output_dir=str(output_dir),
cache_dir=str(cache_dir),
output_styles_json=styles_path,
render_video=True,
generate_cdg=False,
generate_plain_text=True,
generate_lrc=True,
video_resolution=request.video_resolution,
subtitle_offset_ms=request.subtitle_offset_ms,
)
output_generator = OutputGenerator(config, logger)
safe_artist = sanitize_filename(request.artist) if request.artist else "Unknown"
safe_title = sanitize_filename(request.title) if request.title else "Unknown"
output_prefix = f"{safe_artist} - {safe_title}"
logger.info(f"[job:{job_id}] Generating outputs with prefix '{output_prefix}'")
jobs[job_id]["progress"] = 55
outputs = output_generator.generate_outputs(
transcription_corrected=correction_result,
lyrics_results={},
output_prefix=output_prefix,
audio_filepath=str(audio_path),
artist=request.artist,
title=request.title,
)
jobs[job_id]["progress"] = 85
# 7. Upload outputs to GCS
output_prefix_gcs = request.output_gcs_prefix.rstrip("/")
output_files = []
if outputs.video and os.path.exists(outputs.video):
gcs_path = f"{output_prefix_gcs}/videos/with_vocals.mkv"
upload_single_file_to_gcs(Path(outputs.video), gcs_path)
output_files.append(gcs_path)
logger.info(f"[job:{job_id}] Uploaded with_vocals.mkv ({os.path.getsize(outputs.video)} bytes)")
else:
raise RuntimeError("Video generation failed - no output file produced")
if outputs.ass and os.path.exists(outputs.ass):
gcs_path = f"{output_prefix_gcs}/lyrics/karaoke.ass"
upload_single_file_to_gcs(Path(outputs.ass), gcs_path)
output_files.append(gcs_path)
if outputs.lrc and os.path.exists(outputs.lrc):
gcs_path = f"{output_prefix_gcs}/lyrics/karaoke.lrc"
upload_single_file_to_gcs(Path(outputs.lrc), gcs_path)
output_files.append(gcs_path)
if outputs.corrected_txt and os.path.exists(outputs.corrected_txt):
gcs_path = f"{output_prefix_gcs}/lyrics/corrected.txt"
upload_single_file_to_gcs(Path(outputs.corrected_txt), gcs_path)
output_files.append(gcs_path)
jobs[job_id]["progress"] = 95
jobs[job_id]["output_files"] = output_files
jobs[job_id]["metadata"] = {
"countdown_padding_added": padding_added,
"countdown_padding_seconds": padding_seconds if padding_added else 0,
}
logger.info(f"[job:{job_id}] Render video complete. Output files: {output_files}")
except ImportError as e:
error_msg = (
f"OutputGenerator not available: {e}. "
"The karaoke-gen wheel must be installed. "
"Check that ensure_latest_wheel() succeeded."
)
logger.error(error_msg)
jobs[job_id]["status"] = "failed"
jobs[job_id]["error"] = error_msg
raise RuntimeError(error_msg) from e
except Exception as e:
logger.error(f"[job:{job_id}] Render video failed: {e}")
jobs[job_id]["status"] = "failed"
jobs[job_id]["error"] = str(e)
raise
def ensure_latest_wheel():
'''Download and install latest karaoke-gen wheel from GCS.
@@ -307,6 +563,43 @@ def find_file(work_dir: Path, *patterns):
return None
def generate_mov_from_png(png_path: Path, mov_path: Path, duration: int = 5) -> Path:
"""Generate a MOV video from a static PNG image using FFmpeg.
This runs on the GCE encoding worker (not Cloud Run) because 4K H.264
encoding requires more memory than the right-sized Cloud Run container
provides (2Gi). See PR #640 / #647.
Args:
png_path: Path to input PNG image
mov_path: Path for output MOV video
duration: Video duration in seconds (default 5)
Returns:
Path to generated MOV file
Raises:
RuntimeError: If FFmpeg fails
"""
command = [
"ffmpeg", "-hide_banner", "-loglevel", "error", "-nostats", "-y",
"-loop", "1", "-framerate", "30", "-i", str(png_path),
"-f", "lavfi", "-i", "anullsrc",
"-c:v", "libx264", "-r", "30", "-t", str(duration),
"-pix_fmt", "yuv420p", "-vf", "scale=3840:2160",
"-c:a", "aac", "-shortest",
str(mov_path),
]
logger.info(f"Generating MOV from PNG: {png_path.name} -> {mov_path.name}")
result = subprocess.run(command, capture_output=True, text=True, timeout=120)
if result.returncode != 0:
raise RuntimeError(f"FFmpeg failed to generate {mov_path.name}: {result.stderr}")
if not mov_path.exists() or mov_path.stat().st_size < 1024:
raise RuntimeError(f"FFmpeg produced invalid output for {mov_path.name}")
logger.info(f"Generated MOV: {mov_path.name} ({mov_path.stat().st_size} bytes)")
return mov_path
def run_encoding(job_id: str, work_dir: Path, config: dict):
'''Run encoding using LocalEncodingService (single source of truth).
@@ -329,14 +622,43 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
# Get artist/title from config for proper naming
artist = config.get("artist", "Unknown Artist")
title = config.get("title", "Unknown Title")
base_name = f"{artist} - {title}"
# Sanitize for use in file paths (e.g., title "PORTRAIT/WALK/BORN" → "PORTRAIT_WALK_BORN")
safe_artist = re.sub(r'[<>:"/\\|?*]', '_', artist)
safe_title = re.sub(r'[<>:"/\\|?*]', '_', title)
base_name = f"{safe_artist} - {safe_title}"
logger.info(f"Encoding for: {base_name}")
# Find input files in work_dir
# Title/end screens are in screens/ subdirectory
# Title/end screens: look for MOV first, fall back to generating from PNG.
# Since PR #640 right-sized Cloud Run to 2Gi, the screens_worker only generates
# PNG/JPG images — MOV video generation now happens here on the GCE worker.
title_video = find_file(work_dir, "screens/title.mov", "*Title*.mov", "*title*.mov")
end_video = find_file(work_dir, "screens/end.mov", "*End*.mov", "*end*.mov")
# Get intro/end video durations from style config (default 5s)
intro_duration = config.get("intro_video_duration", 5)
end_duration = config.get("end_video_duration", 5)
# Generate title MOV from PNG if missing or invalid (< 1KB = empty shell)
if not title_video or title_video.stat().st_size < 1024:
title_png = find_file(work_dir, "screens/title.png", "*Title*.png", "*title*.png")
if title_png:
title_mov_path = title_png.parent / "title.mov"
logger.info(f"Title MOV missing/invalid, generating from PNG: {title_png}")
title_video = generate_mov_from_png(title_png, title_mov_path, duration=intro_duration)
elif title_video:
logger.warning(f"Title MOV is only {title_video.stat().st_size} bytes and no PNG found")
# Generate end MOV from PNG if missing or invalid
if not end_video or (end_video and end_video.stat().st_size < 1024):
end_png = find_file(work_dir, "screens/end.png", "*End*.png", "*end*.png")
if end_png:
end_mov_path = end_png.parent / "end.mov"
logger.info(f"End MOV missing/invalid, generating from PNG: {end_png}")
end_video = generate_mov_from_png(end_png, end_mov_path, duration=end_duration)
elif end_video:
logger.warning(f"End MOV is only {end_video.stat().st_size} bytes and no PNG found")
# Karaoke video - search for With Vocals or main karaoke video
# IMPORTANT: Search order matters! Search specific paths first to avoid picking up
# old encoding outputs from finals/ directory when re-encoding after reset
@@ -581,6 +903,36 @@ async def process_preview_job(job_id: str, request: EncodePreviewRequest):
jobs[job_id]["error"] = str(e)
async def process_render_video_job(job_id: str, request: RenderVideoRequest):
# Process a render-video job asynchronously
try:
# Download and install latest wheel at job start (allows hot updates without restart)
ensure_latest_wheel()
with tempfile.TemporaryDirectory() as temp_dir:
work_dir = Path(temp_dir) / "work"
work_dir.mkdir()
# Run render-video in thread pool (CPU-bound)
loop = asyncio.get_event_loop()
await loop.run_in_executor(
executor,
run_render_video,
job_id,
work_dir,
request
)
jobs[job_id]["status"] = "complete"
jobs[job_id]["progress"] = 100
logger.info(f"Render video job {job_id} complete")
except Exception as e:
logger.error(f"Render video job {job_id} failed: {e}")
jobs[job_id]["status"] = "failed"
jobs[job_id]["error"] = str(e)
@app.post("/encode-preview")
async def submit_preview_encode_job(request: EncodePreviewRequest, background_tasks: BackgroundTasks, _auth: bool = Depends(verify_api_key)):
# Submit a preview encoding job
@@ -612,6 +964,37 @@ async def submit_preview_encode_job(request: EncodePreviewRequest, background_ta
return {"status": "accepted", "job_id": job_id}
@app.post("/render-video")
async def submit_render_video_job(request: RenderVideoRequest, background_tasks: BackgroundTasks, _auth: bool = Depends(verify_api_key)):
# Submit a render-video job
job_id = request.job_id
# If job already exists, return cached result or current status
if job_id in jobs:
existing_job = jobs[job_id]
if existing_job["status"] == "complete":
return {"status": "cached", "job_id": job_id, "output_files": existing_job.get("output_files"), "metadata": existing_job.get("metadata")}
elif existing_job["status"] == "failed":
# Previous attempt failed, allow retry by replacing the job
pass
else:
# Job is still in progress
return {"status": "in_progress", "job_id": job_id}
jobs[job_id] = {
"job_id": job_id,
"status": "pending",
"progress": 0,
"error": None,
"output_files": None,
"metadata": None,
}
background_tasks.add_task(process_render_video_job, job_id, request)
return {"status": "accepted", "job_id": job_id}
@app.post("/encode")
async def submit_encode_job(request: EncodeRequest, background_tasks: BackgroundTasks, _auth: bool = Depends(verify_api_key)):
# Submit an encoding job
+228
View File
@@ -0,0 +1,228 @@
"""
IP geolocation service with Firestore caching.
Looks up IP addresses via ip-api.com (free, no key needed) and caches
results in Firestore to avoid repeated lookups. Used by admin UI to
enrich IP displays with country, city, ISP, and ASN info.
"""
import ipaddress
import logging
import time
from datetime import datetime, timedelta
from typing import Optional, Dict, List
import httpx
from google.cloud import firestore
from backend.config import get_settings
logger = logging.getLogger(__name__)
IP_GEOLOCATION_COLLECTION = "ip_geolocation"
CACHE_TTL_DAYS = 90 # Cache results for 90 days
IP_API_URL = "http://ip-api.com/json"
IP_API_BATCH_URL = "http://ip-api.com/batch"
IP_API_FIELDS = "status,country,countryCode,regionName,city,isp,org,as,timezone,query"
RATE_LIMIT_PER_MINUTE = 45
def _is_private_ip(ip: str) -> bool:
"""Check if an IP is private/reserved (not routable on the internet)."""
try:
addr = ipaddress.ip_address(ip)
return addr.is_private or addr.is_reserved or addr.is_loopback or addr.is_link_local
except ValueError:
return True # Invalid IP
def _parse_ip_api_response(data: dict) -> dict:
"""Parse ip-api.com response into our standard format."""
if data.get("status") != "success":
return {
"status": "fail",
"ip": data.get("query", ""),
"cached_at": datetime.utcnow().isoformat(),
}
# Parse AS field: "AS14615 Comporium Inc" -> number + name
as_field = data.get("as", "")
as_number = ""
as_name = ""
if as_field:
parts = as_field.split(" ", 1)
as_number = parts[0] if parts else ""
as_name = parts[1] if len(parts) > 1 else ""
return {
"status": "success",
"ip": data.get("query", ""),
"country": data.get("country", ""),
"country_code": data.get("countryCode", ""),
"region": data.get("regionName", ""),
"city": data.get("city", ""),
"isp": data.get("isp", ""),
"org": data.get("org", ""),
"as_number": as_number,
"as_name": as_name,
"timezone": data.get("timezone", ""),
"cached_at": datetime.utcnow().isoformat(),
}
class IpGeolocationService:
"""IP geolocation lookup with Firestore caching."""
def __init__(self):
settings = get_settings()
self.db = firestore.Client(project=settings.google_cloud_project)
self._last_request_times: List[float] = []
def _check_rate_limit(self):
"""Simple rate limiter — sleep if approaching 45 req/min."""
now = time.time()
# Remove entries older than 60 seconds
self._last_request_times = [
t for t in self._last_request_times if now - t < 60
]
if len(self._last_request_times) >= RATE_LIMIT_PER_MINUTE - 5:
# Getting close to limit, wait
sleep_time = 60 - (now - self._last_request_times[0])
if sleep_time > 0:
logger.info(f"IP geolocation rate limit: sleeping {sleep_time:.1f}s")
time.sleep(sleep_time)
self._last_request_times.append(time.time())
def _get_cached(self, ip: str) -> Optional[dict]:
"""Get cached geolocation data for an IP."""
try:
# Firestore doc IDs can't contain '/' so IPv6 with :: is fine,
# but we need to sanitize for doc ID
doc_id = ip.replace("/", "_")
doc = self.db.collection(IP_GEOLOCATION_COLLECTION).document(doc_id).get()
if not doc.exists:
return None
data = doc.to_dict()
# Check TTL
cached_at = data.get("cached_at", "")
if cached_at:
try:
cached_dt = datetime.fromisoformat(cached_at)
if datetime.utcnow() - cached_dt > timedelta(days=CACHE_TTL_DAYS):
return None # Expired
except (ValueError, TypeError):
pass
return data
except Exception:
logger.exception(f"Error reading IP geo cache for {ip}")
return None
def _cache_result(self, ip: str, data: dict):
"""Store geolocation result in Firestore cache."""
try:
doc_id = ip.replace("/", "_")
self.db.collection(IP_GEOLOCATION_COLLECTION).document(doc_id).set(data)
except Exception:
logger.exception(f"Error caching IP geo for {ip}")
def lookup_ip(self, ip: str) -> dict:
"""
Look up geolocation for a single IP address.
Returns cached result if available, otherwise queries ip-api.com.
"""
if not ip or _is_private_ip(ip):
return {"status": "private", "ip": ip or ""}
# Check cache
cached = self._get_cached(ip)
if cached:
return cached
# Query ip-api.com
try:
self._check_rate_limit()
with httpx.Client(timeout=10) as client:
response = client.get(
f"{IP_API_URL}/{ip}",
params={"fields": IP_API_FIELDS},
)
response.raise_for_status()
data = response.json()
result = _parse_ip_api_response(data)
self._cache_result(ip, result)
return result
except Exception:
logger.exception(f"Error looking up IP {ip}")
return {"status": "error", "ip": ip}
def lookup_ips_batch(self, ips: List[str]) -> Dict[str, dict]:
"""
Look up geolocation for multiple IPs.
Returns dict of ip -> geo data. Uses cache for known IPs,
batches uncached lookups to ip-api.com.
"""
results = {}
uncached = []
for ip in set(ips): # Deduplicate
if not ip or _is_private_ip(ip):
results[ip] = {"status": "private", "ip": ip or ""}
continue
cached = self._get_cached(ip)
if cached:
results[ip] = cached
else:
uncached.append(ip)
if not uncached:
return results
# ip-api.com batch endpoint accepts up to 100 IPs per request
for i in range(0, len(uncached), 100):
batch = uncached[i:i + 100]
try:
self._check_rate_limit()
# Batch endpoint takes a JSON array of IPs
payload = [
{"query": ip, "fields": IP_API_FIELDS}
for ip in batch
]
with httpx.Client(timeout=15) as client:
response = client.post(IP_API_BATCH_URL, json=payload)
response.raise_for_status()
batch_results = response.json()
for data in batch_results:
result = _parse_ip_api_response(data)
ip = result.get("ip", data.get("query", ""))
if ip:
results[ip] = result
self._cache_result(ip, result)
except Exception:
logger.exception(f"Error in batch IP lookup ({len(batch)} IPs)")
# Mark failed IPs
for ip in batch:
if ip not in results:
results[ip] = {"status": "error", "ip": ip}
return results
# Global instance
_service = None
def get_ip_geolocation_service() -> IpGeolocationService:
"""Get the global IP geolocation service instance."""
global _service
if _service is None:
_service = IpGeolocationService()
return _service
+4 -2
View File
@@ -213,8 +213,10 @@ def get_worker_valid_statuses() -> Dict[str, List[JobStatus]]:
"video_worker": [
JobStatus.INSTRUMENTAL_SELECTED,
JobStatus.REVIEW_COMPLETE,
JobStatus.RENDERING_VIDEO,
JobStatus.GENERATING_VIDEO,
# Note: RENDERING_VIDEO and GENERATING_VIDEO are intentionally excluded.
# If the job is already in those states, another worker is actively processing it.
# Including them caused a race condition where Cloud Run Job retries + manual retries
# could launch concurrent workers that corrupt each other's state transitions.
],
"render_video_worker": [
JobStatus.REVIEW_COMPLETE,
+47 -27
View File
@@ -748,6 +748,31 @@ class JobManager:
self.update_job(job_id, {'state_data': state_data})
logger.debug(f"Job {job_id} state_data updated: {key} = {value}")
def update_processing_metadata(self, job_id: str, section: str, data) -> None:
"""
Write data into processing_metadata[section] using Firestore dot-notation.
Each worker writes its own section once. This uses Firestore's nested
field update to avoid overwriting other workers' sections.
The section can use dot-notation for deeper nesting, e.g.
'timing.lyrics_worker_seconds' writes to processing_metadata.timing.lyrics_worker_seconds
without overwriting other timing entries.
Args:
job_id: Job ID
section: Metadata section path (e.g., 'transcription', 'timing.audio_worker_seconds')
data: Value to store (dict for sections, scalar for individual fields)
"""
try:
self.firestore.update_job(job_id, {
f"processing_metadata.{section}": data,
})
logger.debug(f"Job {job_id} processing_metadata.{section} updated")
except Exception as e:
# Log but don't raise - metadata storage should never fail a job
logger.warning(f"Job {job_id}: Failed to update processing_metadata.{section}: {e}")
def delete_state_data_key(self, job_id: str, key: str) -> bool:
"""
Delete a specific key from the job's state_data field.
@@ -906,22 +931,22 @@ class JobManager:
def check_parallel_processing_complete(self, job_id: str) -> bool:
"""
Check if both parallel tracks (audio + lyrics) are complete.
This is called after audio_complete or lyrics_complete to determine
if we can proceed to screen generation.
Check if lyrics processing is complete (sufficient for screen generation).
Audio separation is decoupled from the critical path — users can start
reviewing lyrics while separation continues in the background. The
instrumental review page handles the case where separation isn't done yet.
Returns:
True if both tracks complete, False otherwise
True if lyrics are complete, False otherwise
"""
job = self.get_job(job_id)
if not job:
return False
audio_complete = job.state_data.get('audio_complete', False)
lyrics_complete = job.state_data.get('lyrics_complete', False)
return audio_complete and lyrics_complete
return lyrics_complete
async def start_job_processing(
self,
@@ -997,30 +1022,25 @@ class JobManager:
def mark_audio_complete(self, job_id: str) -> None:
"""
Mark audio processing as complete and check if can proceed.
If lyrics are also complete, automatically triggers screens worker.
Mark audio processing as complete.
Audio completion is decoupled from the lyrics review path — it no longer
triggers screens. The instrumental review page polls for this flag.
"""
self.update_state_data(job_id, 'audio_complete', True)
if self.check_parallel_processing_complete(job_id):
logger.info(f"Job {job_id}: Both audio and lyrics complete, triggering screens worker")
# Transition happens in screens worker
# We just trigger it here
self._trigger_screens_worker(job_id)
logger.info(f"Job {job_id}: Audio processing complete (separation finished)")
def mark_lyrics_complete(self, job_id: str) -> None:
"""
Mark lyrics processing as complete and check if can proceed.
If audio is also complete, automatically triggers screens worker.
Mark lyrics processing as complete and trigger screens if ready.
Lyrics completion is the sole gate for screen generation and review.
Audio separation runs independently in the background.
"""
self.update_state_data(job_id, 'lyrics_complete', True)
if self.check_parallel_processing_complete(job_id):
logger.info(f"Job {job_id}: Both audio and lyrics complete, triggering screens worker")
# Transition happens in screens worker
# We just trigger it here
logger.info(f"Job {job_id}: Lyrics complete, triggering screens worker")
self._trigger_screens_worker(job_id)
def _trigger_screens_worker(self, job_id: str) -> None:
+4 -1
View File
@@ -545,7 +545,10 @@ class LocalEncodingService:
)
output_files["with_vocals_mp4"] = config.output_with_vocals_mp4
else:
self.logger.info("[Step 2/6] Skipped - video already MP4")
self.logger.info("[Step 2/6] Skipped - video already MP4, copying as-is")
import shutil
shutil.copy2(config.karaoke_video, config.output_with_vocals_mp4)
output_files["with_vocals_mp4"] = config.output_with_vocals_mp4
# Step 3: Encode lossless 4K MP4
if config.output_lossless_4k_mp4:
+2 -1
View File
@@ -334,7 +334,8 @@ class ThemeService:
style_params = self._update_asset_paths_in_style(theme_id, style_params)
# Upload modified style_params.json to job's style folder
job_style_path = f"uploads/{job_id}/style/style_params.json"
# Uses jobs/ prefix (not uploads/) to avoid GCS lifecycle deletion rule
job_style_path = f"jobs/{job_id}/style/style_params.json"
self.storage.upload_json(job_style_path, style_params)
logger.info(f"Prepared job {job_id} style from theme {theme_id}")
+432 -18
View File
@@ -48,7 +48,7 @@ class UserService:
"""Service for user management and authentication."""
# Number of free credits granted to new users
NEW_USER_FREE_CREDITS = 2
NEW_USER_FREE_CREDITS = 1
def __init__(self):
"""Initialize user service with Firestore client."""
@@ -107,15 +107,23 @@ class UserService:
logger.exception(f"Error getting user {email}")
return None
def get_or_create_user(self, email: str, tenant_id: Optional[str] = None) -> User:
def get_or_create_user(
self,
email: str,
tenant_id: Optional[str] = None,
signup_ip: Optional[str] = None,
device_fingerprint: Optional[str] = None,
) -> User:
"""
Get existing user or create a new one.
New users receive a welcome credit to try the service.
Welcome credits are granted on first magic link verification, not here.
Args:
email: User's email address
tenant_id: Tenant ID for white-label portals (None = default Nomad Karaoke)
signup_ip: Client IP address at signup (for rate limiting)
device_fingerprint: Browser fingerprint at signup (for rate limiting)
Note: If user exists but has a different tenant_id, the existing user is returned.
Users are uniquely identified by email, not email+tenant.
@@ -129,22 +137,17 @@ class UserService:
# (though features may be restricted per-tenant)
return user
# Create new user with welcome credit
welcome_credit = self.NEW_USER_FREE_CREDITS
welcome_transaction = CreditTransaction(
id=str(uuid.uuid4()),
amount=welcome_credit,
reason="welcome_credit",
)
# Create new user with zero credits (welcome credits granted on first verification)
user = User(
email=email,
credits=welcome_credit,
credit_transactions=[welcome_transaction],
credits=0,
credit_transactions=[],
tenant_id=tenant_id, # Associate with tenant on creation
signup_ip=signup_ip,
device_fingerprint=device_fingerprint,
)
self._save_user(user)
logger.info(f"Created new user: {email} with {welcome_credit} welcome credit(s) (tenant: {tenant_id or 'default'})")
logger.info(f"Created new user: {email} (tenant: {tenant_id or 'default'}) — credits pending verification")
return user
def _save_user(self, user: User) -> None:
@@ -213,7 +216,8 @@ class UserService:
email: str,
ip_address: Optional[str] = None,
user_agent: Optional[str] = None,
tenant_id: Optional[str] = None
tenant_id: Optional[str] = None,
device_fingerprint: Optional[str] = None,
) -> MagicLinkToken:
"""
Create a magic link token for email authentication.
@@ -226,11 +230,17 @@ class UserService:
ip_address: Client IP for auditing
user_agent: Client user agent for auditing
tenant_id: Tenant ID for white-label portals (None = default Nomad Karaoke)
device_fingerprint: Browser fingerprint for anti-abuse
"""
email = email.lower()
# Ensure user exists (with tenant association)
self.get_or_create_user(email, tenant_id=tenant_id)
# Ensure user exists (with tenant association, signup IP, and fingerprint)
self.get_or_create_user(
email,
tenant_id=tenant_id,
signup_ip=ip_address,
device_fingerprint=device_fingerprint,
)
# Generate secure token
token = secrets.token_urlsafe(32)
@@ -242,6 +252,7 @@ class UserService:
ip_address=ip_address,
user_agent=user_agent,
tenant_id=tenant_id,
device_fingerprint=device_fingerprint,
)
# Save to Firestore
@@ -359,6 +370,406 @@ class UserService:
logger.exception("Error verifying magic link")
return False, None, "An error occurred during verification"
def grant_welcome_credits_if_eligible(
self,
email: str,
precomputed_eval: Optional[dict] = None,
) -> Tuple[bool, str]:
"""
Grant welcome credits on first magic link verification.
Uses AI evaluation to check for abuse before granting. Fail-open:
if evaluation fails, credits are granted anyway.
Uses a dedicated welcome_credits_granted flag as primary idempotency
check (survives credit_transactions list trimming). Falls back to
checking for welcome_credit transaction as secondary defense.
Args:
email: User's email address.
precomputed_eval: Optional pre-computed evaluation from magic link doc.
Keys: credit_eval_decision, credit_eval_reasoning, credit_eval_error.
If provided and has a decision, skips the AI call.
Returns:
Tuple of (credits_granted: bool, status: str).
status is one of: "granted", "denied", "already_granted", "not_found", "error"
"""
try:
email = email.lower()
user = self.get_user(email)
if not user:
return False, "not_found"
# Primary check: dedicated flag (survives transaction list trimming)
if user.welcome_credits_granted:
return False, "already_granted"
# Secondary check: look for existing welcome_credit transaction
for txn in user.credit_transactions:
if txn.reason == "welcome_credit":
return False, "already_granted"
# Skip AI evaluation for test emails (e.g. E2E test accounts)
# to avoid wasting LLM credits and sending unnecessary denial emails
from backend.utils.test_data import is_test_email
if not is_test_email(email):
# AI evaluation: check for abuse signals before granting
# Use pre-computed result from magic link if available
try:
from backend.services.credit_evaluation_service import (
get_credit_evaluation_service,
CreditEvaluation,
)
precomputed_decision = (precomputed_eval or {}).get("credit_eval_decision")
if precomputed_decision:
logger.info(f"Using pre-computed credit eval for {email}: {precomputed_decision}")
evaluation = CreditEvaluation(
decision=precomputed_decision,
reasoning=(precomputed_eval or {}).get("credit_eval_reasoning", ""),
confidence=1.0,
error=(precomputed_eval or {}).get("credit_eval_error"),
)
else:
eval_service = get_credit_evaluation_service()
evaluation = eval_service.evaluate(email, "welcome")
if evaluation.decision == "deny":
# Mark as evaluated but not granted so we don't re-evaluate
self.update_user(email, welcome_credits_granted=True)
logger.info(
f"Denied welcome credits to {email}: {evaluation.reasoning}"
)
try:
from backend.services.email_service import get_email_service
get_email_service().send_credit_denied_email(email, "welcome")
except Exception:
logger.exception(f"Failed to send credit denied email to {email}")
return False, "denied"
if evaluation.decision == "pending_review":
# Don't mark welcome_credits_granted — allow retry after manual review
logger.info(
f"Welcome credits pending review for {email}: {evaluation.reasoning}"
)
try:
from backend.services.email_service import get_email_service
email_service = get_email_service()
email_service.send_credit_review_needed_email(
email, "welcome", evaluation.reasoning, signals=evaluation.signals,
)
except Exception:
logger.exception(f"Failed to send review needed email for {email}")
return False, "pending_review"
except Exception:
logger.exception(f"Credit evaluation failed for {email} — pending review (fail-closed)")
try:
from backend.services.email_service import get_email_service
email_service = get_email_service()
email_service.send_credit_review_needed_email(
email, "welcome", f"Evaluation error: {email}",
)
except Exception:
pass
return False, "pending_review"
else:
logger.info(f"Skipping credit evaluation for test email {email}")
# Grant welcome credits
welcome_credit = self.NEW_USER_FREE_CREDITS
transaction = CreditTransaction(
id=str(uuid.uuid4()),
amount=welcome_credit,
reason="welcome_credit",
)
transactions = user.credit_transactions[-MAX_CREDIT_TRANSACTIONS + 1:]
transactions.append(transaction)
new_balance = user.credits + welcome_credit
self.update_user(
email,
credits=new_balance,
credit_transactions=[t.model_dump(mode='json') for t in transactions],
welcome_credits_granted=True,
)
logger.info(f"Granted {welcome_credit} welcome credits to {email}")
return True, "granted"
except Exception:
logger.exception(f"Error granting welcome credits to {email}")
return False, "error"
# =========================================================================
# Anti-Abuse Rate Limiting
# =========================================================================
# Maximum new signups allowed per IP address in the rate limit window
MAX_SIGNUPS_PER_IP = 2
SIGNUP_RATE_LIMIT_HOURS = 24
def count_recent_signups_from_ip(self, ip_address: str, hours: int = 24) -> int:
"""
Count new user accounts created from this IP in the last N hours.
Queries gen_users where signup_ip matches and created_at is recent.
Used to rate-limit new account creation per IP address.
Args:
ip_address: Client IP to check
hours: Lookback window in hours (default: 24)
Returns:
Number of recent signups from this IP
"""
try:
cutoff = datetime.utcnow() - timedelta(hours=hours)
query = (
self.db.collection(USERS_COLLECTION)
.where(filter=FieldFilter("signup_ip", "==", ip_address))
.where(filter=FieldFilter("created_at", ">=", cutoff))
)
count = 0
for _ in query.stream():
count += 1
return count
except Exception:
logger.exception(f"Error counting signups from IP {ip_address}")
# On error, don't block — return 0 to allow the request
return 0
def count_recent_signups_from_fingerprint(
self, device_fingerprint: str, hours: int = 24
) -> int:
"""
Count new user accounts created with this device fingerprint in the last N hours.
Args:
device_fingerprint: Browser fingerprint to check
hours: Lookback window in hours (default: 24)
Returns:
Number of recent signups from this fingerprint
"""
try:
cutoff = datetime.utcnow() - timedelta(hours=hours)
query = (
self.db.collection(USERS_COLLECTION)
.where(filter=FieldFilter("device_fingerprint", "==", device_fingerprint))
.where(filter=FieldFilter("created_at", ">=", cutoff))
)
count = 0
for _ in query.stream():
count += 1
return count
except Exception:
logger.exception(f"Error counting signups from fingerprint")
return 0
def is_signup_rate_limited(
self, ip_address: Optional[str] = None, device_fingerprint: Optional[str] = None
) -> bool:
"""
Check if a signup should be rate limited based on IP and/or fingerprint.
Either signal hitting the limit triggers a block.
"""
if ip_address:
ip_count = self.count_recent_signups_from_ip(
ip_address, hours=self.SIGNUP_RATE_LIMIT_HOURS
)
if ip_count >= self.MAX_SIGNUPS_PER_IP:
return True
if device_fingerprint:
fp_count = self.count_recent_signups_from_fingerprint(
device_fingerprint, hours=self.SIGNUP_RATE_LIMIT_HOURS
)
if fp_count >= self.MAX_SIGNUPS_PER_IP:
return True
return False
# =========================================================================
# Anti-Abuse Investigation
# =========================================================================
def find_users_by_signup_ip(self, ip_address: str) -> List[User]:
"""Find all users who signed up from this IP address."""
try:
query = (
self.db.collection(USERS_COLLECTION)
.where(filter=FieldFilter("signup_ip", "==", ip_address))
.order_by("created_at", direction=firestore.Query.DESCENDING)
.limit(50)
)
return [User(**doc.to_dict()) for doc in query.stream()]
except Exception:
logger.exception(f"Error finding users by IP {ip_address}")
return []
def find_users_by_fingerprint(self, device_fingerprint: str) -> List[User]:
"""Find all users who signed up with this device fingerprint."""
try:
query = (
self.db.collection(USERS_COLLECTION)
.where(filter=FieldFilter("device_fingerprint", "==", device_fingerprint))
.order_by("created_at", direction=firestore.Query.DESCENDING)
.limit(50)
)
return [User(**doc.to_dict()) for doc in query.stream()]
except Exception:
logger.exception(f"Error finding users by fingerprint")
return []
def find_suspicious_accounts(self, min_jobs: int = 2, max_spend: int = 0) -> List[User]:
"""
Find accounts with many jobs but no spend (potential free-credit abusers).
Args:
min_jobs: Minimum total_jobs_created to flag (default: 2)
max_spend: Maximum total_spent in cents to include (default: 0 = free only)
"""
from backend.utils.test_data import is_internal_or_test_email
try:
query = (
self.db.collection(USERS_COLLECTION)
.where(filter=FieldFilter("total_jobs_created", ">=", min_jobs))
.order_by("total_jobs_created", direction=firestore.Query.DESCENDING)
.limit(100)
)
users = []
for doc in query.stream():
user = User(**doc.to_dict())
if user.total_spent <= max_spend and not is_internal_or_test_email(user.email):
users.append(user)
return users
except Exception:
logger.exception("Error finding suspicious accounts")
return []
def find_related_accounts(self, email: str) -> dict:
"""
Given a user email, find all accounts that share the same signup IP
or device fingerprint. Returns a dict with grouped results.
"""
user = self.get_user(email)
if not user:
return {"user": None, "by_ip": [], "by_fingerprint": []}
by_ip = []
if user.signup_ip:
by_ip = [
u for u in self.find_users_by_signup_ip(user.signup_ip)
if u.email != user.email
]
by_fingerprint = []
if user.device_fingerprint:
by_fingerprint = [
u for u in self.find_users_by_fingerprint(user.device_fingerprint)
if u.email != user.email
]
return {
"user": user,
"by_ip": by_ip,
"by_fingerprint": by_fingerprint,
}
def find_account_correlations(self) -> dict:
"""
Find clusters of accounts sharing the same fingerprint or signup IP.
Returns groups of 2+ accounts that share the same identifier,
sorted by group size (largest first). Excludes internal/test accounts.
"""
from collections import defaultdict
from backend.utils.test_data import is_internal_or_test_email
# Known bad IPs (load balancer, metadata, placeholder) that don't represent real client IPs
BAD_IPS = {"169.254.169.126", "unknown", ""}
try:
all_users = []
for doc in self.db.collection(USERS_COLLECTION).stream():
user = User(**doc.to_dict())
if not is_internal_or_test_email(user.email):
all_users.append(user)
# Group by fingerprint
fp_groups: dict[str, list[User]] = defaultdict(list)
for user in all_users:
if user.device_fingerprint:
fp_groups[user.device_fingerprint].append(user)
# Group by IP (exclude known bad IPs)
ip_groups: dict[str, list[User]] = defaultdict(list)
for user in all_users:
if user.signup_ip and user.signup_ip not in BAD_IPS:
ip_groups[user.signup_ip].append(user)
# Collect user agents from latest sessions for users in clusters
cluster_emails = set()
for fp, users in fp_groups.items():
if len(users) >= 2:
cluster_emails.update(u.email for u in users)
for ip, users in ip_groups.items():
if len(users) >= 2:
cluster_emails.update(u.email for u in users)
user_agents: dict[str, str] = {}
for email in cluster_emails:
try:
sessions = (
self.db.collection(SESSIONS_COLLECTION)
.where(filter=FieldFilter("user_email", "==", email))
.order_by("created_at", direction=firestore.Query.DESCENDING)
.limit(1)
.stream()
)
for session_doc in sessions:
session_data = session_doc.to_dict()
ua = session_data.get("user_agent")
if ua:
user_agents[email] = ua
except Exception:
pass # Skip if session lookup fails
# Build response - only clusters with 2+ users
fingerprint_clusters = []
for fp, users in fp_groups.items():
if len(users) >= 2:
fingerprint_clusters.append({
"fingerprint": fp,
"users": sorted(users, key=lambda u: u.created_at or "", reverse=True),
})
fingerprint_clusters.sort(key=lambda c: len(c["users"]), reverse=True)
ip_clusters = []
for ip, users in ip_groups.items():
if len(users) >= 2:
ip_clusters.append({
"ip": ip,
"users": sorted(users, key=lambda u: u.created_at or "", reverse=True),
})
ip_clusters.sort(key=lambda c: len(c["users"]), reverse=True)
return {
"fingerprint_clusters": fingerprint_clusters,
"ip_clusters": ip_clusters,
"user_agents": user_agents,
}
except Exception:
logger.exception("Error finding account correlations")
return {"fingerprint_clusters": [], "ip_clusters": [], "user_agents": {}}
# =========================================================================
# Session Management
# =========================================================================
@@ -368,7 +779,8 @@ class UserService:
user_email: str,
ip_address: Optional[str] = None,
user_agent: Optional[str] = None,
tenant_id: Optional[str] = None
tenant_id: Optional[str] = None,
device_fingerprint: Optional[str] = None,
) -> Session:
"""
Create a new session for an authenticated user.
@@ -378,6 +790,7 @@ class UserService:
ip_address: Client IP for auditing
user_agent: Client user agent for auditing
tenant_id: Tenant ID for white-label portals (None = default Nomad Karaoke)
device_fingerprint: Browser fingerprint for cross-account correlation
"""
token = secrets.token_urlsafe(32)
token_prefix = token[:12]
@@ -389,6 +802,7 @@ class UserService:
ip_address=ip_address,
user_agent=user_agent,
tenant_id=tenant_id,
device_fingerprint=device_fingerprint,
)
# Serialize and write to Firestore
+33 -5
View File
@@ -383,14 +383,13 @@ class WorkerService:
"""
Trigger audio separation worker.
Always uses Cloud Run Jobs to avoid instance termination during long-running
Modal API calls. The BackgroundTasks approach caused Cloud Run to terminate
instances mid-processing when no HTTP requests were active.
Uses Cloud Run Jobs with L4 GPU in us-east4 for direct audio separation.
"""
return await self._trigger_worker_cloud_run_job(
job_id=job_id,
cloud_run_job_name="audio-separation-job",
worker_module="audio_worker",
location="us-east4", # GPU job runs in us-east4 (L4 quota)
)
async def trigger_lyrics_worker(self, job_id: str) -> bool:
@@ -412,14 +411,40 @@ class WorkerService:
"""Trigger screen generation worker."""
return await self.trigger_worker("screens", job_id)
def _warmup_encoding_worker(self, job_id: str) -> None:
"""Fire-and-forget warmup of the encoding worker VM.
Called before dispatching video/render workers so the GCE encoding
VM starts booting while the worker downloads files and prepares.
Failures are logged but never block worker dispatch.
"""
try:
from backend.services.encoding_worker_manager import EncodingWorkerManager
from google.cloud import compute_v1, firestore
db = firestore.Client(project=self.settings.google_cloud_project)
compute_client = compute_v1.InstancesClient()
manager = EncodingWorkerManager(
db=db,
compute_client=compute_client,
project_id=self.settings.google_cloud_project,
)
result = manager.ensure_primary_running()
if result["started"]:
logger.info(f"[job:{job_id}] Encoding worker warmup: started VM {result['vm_name']}")
else:
logger.info(f"[job:{job_id}] Encoding worker warmup: VM {result['vm_name']} already running")
except Exception as e:
logger.warning(f"[job:{job_id}] Encoding worker warmup failed (non-fatal): {e}")
async def trigger_video_worker(self, job_id: str) -> bool:
"""
Trigger video generation worker.
When USE_CLOUD_RUN_JOBS_FOR_VIDEO=true and ENABLE_CLOUD_TASKS=true,
uses Cloud Run Jobs for execution (supports >30 min encoding).
Otherwise, uses Cloud Tasks or direct HTTP.
"""
self._warmup_encoding_worker(job_id)
if self._use_cloud_tasks and self.settings.use_cloud_run_jobs_for_video:
return await self._trigger_cloud_run_job(job_id)
return await self.trigger_worker("video", job_id)
@@ -448,6 +473,7 @@ class WorkerService:
job_id: str,
cloud_run_job_name: str,
worker_module: str,
location: str | None = None,
) -> bool:
"""
Trigger a worker as a Cloud Run Job.
@@ -460,6 +486,7 @@ class WorkerService:
job_id: Job ID to process
cloud_run_job_name: Name of the Cloud Run Job (e.g., "lyrics-transcription-job")
worker_module: Worker module name (e.g., "lyrics_worker")
location: GCP region for the job (defaults to settings.gcp_region)
Returns:
True if job was triggered successfully, False otherwise
@@ -472,7 +499,7 @@ class WorkerService:
logger.error("GOOGLE_CLOUD_PROJECT not set, cannot trigger Cloud Run Job")
return False
location = self.settings.gcp_region
location = location or self.settings.gcp_region
job_name = f"projects/{project}/locations/{location}/jobs/{cloud_run_job_name}"
# Create Cloud Run Jobs client
@@ -510,6 +537,7 @@ class WorkerService:
async def trigger_render_video_worker(self, job_id: str) -> bool:
"""Trigger render video worker (post-review)."""
self._warmup_encoding_worker(job_id)
return await self.trigger_worker("render-video", job_id)
async def schedule_idle_reminder(
@@ -150,15 +150,15 @@ class TestStyleLoadingFix:
}
# Upload style JSON to GCS (the CORRECT location)
style_gcs_path = f"uploads/{job_id}/style/style_params.json"
style_gcs_path = f"jobs/{job_id}/style/style_params.json"
self.storage.upload_string(json.dumps(style_json), style_gcs_path)
# Upload mock assets
assets = {
"intro_background": f"uploads/{job_id}/style/intro_background.png",
"karaoke_background": f"uploads/{job_id}/style/karaoke_background.png",
"end_background": f"uploads/{job_id}/style/end_background.png",
"font": f"uploads/{job_id}/style/font.ttf",
"intro_background": f"jobs/{job_id}/style/intro_background.png",
"karaoke_background": f"jobs/{job_id}/style/karaoke_background.png",
"end_background": f"jobs/{job_id}/style/end_background.png",
"font": f"jobs/{job_id}/style/font.ttf",
}
for asset_key, gcs_path in assets.items():
@@ -255,7 +255,7 @@ class TestStyleLoadingFix:
job_id = f"test-bug-{int(time.time() * 1000)}"
# Upload style to CORRECT location
style_gcs_path = f"uploads/{job_id}/style/style_params.json"
style_gcs_path = f"jobs/{job_id}/style/style_params.json"
self.storage.upload_string('{"karaoke": {"font_size": 100}}', style_gcs_path)
# Create job with styles in CORRECT location
+460
View File
@@ -0,0 +1,460 @@
"""
Unit tests for admin feedback endpoint and feedback email notification.
"""
import pytest
from unittest.mock import Mock, patch, MagicMock
from datetime import datetime
from backend.services.email_service import EmailService
class TestAdminFeedbackEndpoint:
"""Tests for GET /api/admin/feedback endpoint."""
def _make_feedback_doc(self, email="user@example.com", overall=4, **kwargs):
"""Create a mock Firestore feedback document."""
doc = Mock()
doc.id = kwargs.get("id", "test-id-1")
data = {
"id": doc.id,
"user_email": email,
"created_at": kwargs.get("created_at", datetime(2026, 3, 1, 12, 0, 0)),
"overall_rating": overall,
"ease_of_use_rating": kwargs.get("ease_of_use", 4),
"lyrics_accuracy_rating": kwargs.get("lyrics_accuracy", 3),
"correction_experience_rating": kwargs.get("correction_experience", 4),
"what_went_well": kwargs.get("what_went_well", "Great app"),
"what_could_improve": kwargs.get("what_could_improve", "More songs"),
"additional_comments": kwargs.get("additional_comments", None),
"would_recommend": kwargs.get("would_recommend", True),
"would_use_again": kwargs.get("would_use_again", True),
}
doc.to_dict.return_value = data
return doc
@patch("backend.api.routes.admin.get_user_service")
@patch("backend.api.routes.admin.is_test_email")
def test_list_feedback_returns_items(self, mock_is_test, mock_get_user_svc):
"""Test that feedback items are returned correctly."""
from backend.api.routes.admin import list_user_feedback
mock_db = Mock()
mock_user_svc = Mock()
mock_user_svc.db = mock_db
mock_get_user_svc.return_value = mock_user_svc
mock_is_test.return_value = False
doc1 = self._make_feedback_doc("alice@example.com", 5, id="id-1")
doc2 = self._make_feedback_doc("bob@example.com", 3, id="id-2")
mock_db.collection.return_value.stream.return_value = [doc1, doc2]
result = list_user_feedback(
limit=50, offset=0, search=None, exclude_test=False,
auth_result=("admin@test.com", "admin", 1),
)
assert result.total == 2
assert len(result.items) == 2
assert result.has_more is False
@patch("backend.api.routes.admin.get_user_service")
@patch("backend.api.routes.admin.is_test_email")
def test_list_feedback_search_filter(self, mock_is_test, mock_get_user_svc):
"""Test that search filters by email."""
from backend.api.routes.admin import list_user_feedback
mock_db = Mock()
mock_user_svc = Mock()
mock_user_svc.db = mock_db
mock_get_user_svc.return_value = mock_user_svc
mock_is_test.return_value = False
doc1 = self._make_feedback_doc("alice@example.com", 5, id="id-1")
doc2 = self._make_feedback_doc("bob@example.com", 3, id="id-2")
mock_db.collection.return_value.stream.return_value = [doc1, doc2]
result = list_user_feedback(
limit=50, offset=0, search="alice", exclude_test=False,
auth_result=("admin@test.com", "admin", 1),
)
assert result.total == 1
assert result.items[0].user_email == "alice@example.com"
@patch("backend.api.routes.admin.get_user_service")
@patch("backend.api.routes.admin.is_test_email")
def test_list_feedback_exclude_test(self, mock_is_test, mock_get_user_svc):
"""Test that test emails are excluded when exclude_test=True."""
from backend.api.routes.admin import list_user_feedback
mock_db = Mock()
mock_user_svc = Mock()
mock_user_svc.db = mock_db
mock_get_user_svc.return_value = mock_user_svc
doc1 = self._make_feedback_doc("alice@example.com", 5, id="id-1")
doc2 = self._make_feedback_doc("test@inbox.testmail.app", 3, id="id-2")
mock_db.collection.return_value.stream.return_value = [doc1, doc2]
# Make is_test_email return True for the test email
mock_is_test.side_effect = lambda e: "testmail" in e
result = list_user_feedback(
limit=50, offset=0, search=None, exclude_test=True,
auth_result=("admin@test.com", "admin", 1),
)
assert result.total == 1
assert result.items[0].user_email == "alice@example.com"
@patch("backend.api.routes.admin.get_user_service")
@patch("backend.api.routes.admin.is_test_email")
def test_list_feedback_pagination(self, mock_is_test, mock_get_user_svc):
"""Test pagination with offset and limit."""
from backend.api.routes.admin import list_user_feedback
mock_db = Mock()
mock_user_svc = Mock()
mock_user_svc.db = mock_db
mock_get_user_svc.return_value = mock_user_svc
mock_is_test.return_value = False
docs = [
self._make_feedback_doc(f"user{i}@example.com", 4, id=f"id-{i}")
for i in range(5)
]
mock_db.collection.return_value.stream.return_value = docs
result = list_user_feedback(
limit=2, offset=2, search=None, exclude_test=False,
auth_result=("admin@test.com", "admin", 1),
)
assert result.total == 5
assert len(result.items) == 2
assert result.has_more is True
assert result.offset == 2
assert result.limit == 2
@patch("backend.api.routes.admin.get_user_service")
@patch("backend.api.routes.admin.is_test_email")
def test_list_feedback_aggregate_stats(self, mock_is_test, mock_get_user_svc):
"""Test that aggregate rating averages are computed correctly."""
from backend.api.routes.admin import list_user_feedback
mock_db = Mock()
mock_user_svc = Mock()
mock_user_svc.db = mock_db
mock_get_user_svc.return_value = mock_user_svc
mock_is_test.return_value = False
doc1 = self._make_feedback_doc("a@x.com", 5, id="id-1", ease_of_use=4, lyrics_accuracy=3, correction_experience=2)
doc2 = self._make_feedback_doc("b@x.com", 3, id="id-2", ease_of_use=2, lyrics_accuracy=5, correction_experience=4)
mock_db.collection.return_value.stream.return_value = [doc1, doc2]
result = list_user_feedback(
limit=50, offset=0, search=None, exclude_test=False,
auth_result=("admin@test.com", "admin", 1),
)
assert result.avg_overall_rating == 4.0
assert result.avg_ease_of_use_rating == 3.0
assert result.avg_lyrics_accuracy_rating == 4.0
assert result.avg_correction_experience_rating == 3.0
@patch("backend.api.routes.admin.get_user_service")
@patch("backend.api.routes.admin.is_test_email")
def test_list_feedback_empty(self, mock_is_test, mock_get_user_svc):
"""Test empty results."""
from backend.api.routes.admin import list_user_feedback
mock_db = Mock()
mock_user_svc = Mock()
mock_user_svc.db = mock_db
mock_get_user_svc.return_value = mock_user_svc
mock_db.collection.return_value.stream.return_value = []
result = list_user_feedback(
limit=50, offset=0, search=None, exclude_test=False,
auth_result=("admin@test.com", "admin", 1),
)
assert result.total == 0
assert len(result.items) == 0
assert result.avg_overall_rating is None
@patch("backend.api.routes.admin.get_user_service")
@patch("backend.api.routes.admin.is_test_email")
def test_list_feedback_handles_string_created_at(self, mock_is_test, mock_get_user_svc):
"""Test that string timestamps (not datetime objects) are handled correctly."""
from backend.api.routes.admin import list_user_feedback
mock_db = Mock()
mock_user_svc = Mock()
mock_user_svc.db = mock_db
mock_get_user_svc.return_value = mock_user_svc
mock_is_test.return_value = False
doc = self._make_feedback_doc("a@x.com", 5, id="id-1", created_at="2026-03-01T12:00:00")
mock_db.collection.return_value.stream.return_value = [doc]
result = list_user_feedback(
limit=50, offset=0, search=None, exclude_test=False,
auth_result=("admin@test.com", "admin", 1),
)
assert result.items[0].created_at == "2026-03-01T12:00:00"
@patch("backend.api.routes.admin.get_user_service")
@patch("backend.api.routes.admin.is_test_email")
def test_list_feedback_handles_none_created_at(self, mock_is_test, mock_get_user_svc):
"""Test that None created_at is handled correctly."""
from backend.api.routes.admin import list_user_feedback
mock_db = Mock()
mock_user_svc = Mock()
mock_user_svc.db = mock_db
mock_get_user_svc.return_value = mock_user_svc
mock_is_test.return_value = False
doc = self._make_feedback_doc("a@x.com", 5, id="id-1", created_at=None)
mock_db.collection.return_value.stream.return_value = [doc]
result = list_user_feedback(
limit=50, offset=0, search=None, exclude_test=False,
auth_result=("admin@test.com", "admin", 1),
)
assert result.items[0].created_at is None
class TestSubmitFeedbackEmailIntegration:
"""Test that submit_user_feedback correctly calls send_feedback_notification."""
@patch("backend.services.email_service.get_email_service")
@patch("backend.services.auth_service.get_auth_service")
def test_submit_feedback_sends_admin_notification(self, mock_get_auth, mock_get_email):
"""Verify the caller (submit_user_feedback) passes correct args to email service."""
import asyncio
import uuid as uuid_mod
from backend.api.routes.users import submit_user_feedback
from backend.models.user import UserFeedbackRequest
# Mock auth
mock_auth_svc = Mock()
mock_auth_result = Mock()
mock_auth_result.is_valid = True
mock_auth_result.user_email = "alice@example.com"
mock_auth_svc.validate_token_full.return_value = mock_auth_result
mock_get_auth.return_value = mock_auth_svc
# Mock email service
mock_email_svc = Mock()
mock_email_svc.send_feedback_notification.return_value = True
mock_get_email.return_value = mock_email_svc
# Mock user service with a db that has a collection mock
mock_user_svc = Mock()
mock_user = Mock()
mock_user.email = "alice@example.com"
mock_user.total_jobs_completed = 5
mock_user.has_submitted_feedback = False
mock_user_svc.get_or_create_user.return_value = mock_user
mock_user_svc.update_user.return_value = None
mock_user_svc.add_credits.return_value = None
went_well = "The lyrics synchronization was incredibly accurate and impressive overall"
could_improve = "Speed could be faster for longer songs in the processing queue"
request = UserFeedbackRequest(
overall_rating=4,
ease_of_use_rating=3,
lyrics_accuracy_rating=5,
correction_experience_rating=2,
what_went_well=went_well,
what_could_improve=could_improve,
additional_comments=None,
would_recommend=True,
would_use_again=False,
)
with patch.object(uuid_mod, "uuid4", return_value="fake-uuid"):
result = asyncio.get_event_loop().run_until_complete(
submit_user_feedback(request, authorization="Bearer test-token", user_service=mock_user_svc)
)
# Verify email notification was called with matching args
mock_email_svc.send_feedback_notification.assert_called_once_with(
user_email="alice@example.com",
overall_rating=4,
ease_of_use_rating=3,
lyrics_accuracy_rating=5,
correction_experience_rating=2,
what_went_well=went_well,
what_could_improve=could_improve,
additional_comments=None,
would_recommend=True,
would_use_again=False,
)
assert result.credits_granted == 1
@patch("backend.services.email_service.get_email_service")
@patch("backend.services.auth_service.get_auth_service")
def test_submit_feedback_continues_on_email_failure(self, mock_get_auth, mock_get_email):
"""Verify feedback submission succeeds even if email notification fails."""
import asyncio
import uuid as uuid_mod
from backend.api.routes.users import submit_user_feedback
from backend.models.user import UserFeedbackRequest
mock_auth_svc = Mock()
mock_auth_result = Mock()
mock_auth_result.is_valid = True
mock_auth_result.user_email = "bob@example.com"
mock_auth_svc.validate_token_full.return_value = mock_auth_result
mock_get_auth.return_value = mock_auth_svc
# Email service throws an exception
mock_email_svc = Mock()
mock_email_svc.send_feedback_notification.side_effect = Exception("SendGrid down")
mock_get_email.return_value = mock_email_svc
mock_user_svc = Mock()
mock_user = Mock()
mock_user.email = "bob@example.com"
mock_user.total_jobs_completed = 3
mock_user.has_submitted_feedback = False
mock_user_svc.get_or_create_user.return_value = mock_user
request = UserFeedbackRequest(
overall_rating=5,
ease_of_use_rating=5,
lyrics_accuracy_rating=5,
correction_experience_rating=5,
what_went_well="Everything was perfect and I really enjoyed the experience a lot",
)
with patch.object(uuid_mod, "uuid4", return_value="fake-uuid"):
result = asyncio.get_event_loop().run_until_complete(
submit_user_feedback(request, authorization="Bearer test-token", user_service=mock_user_svc)
)
# User still gets credits even though email failed
assert result.status == "success"
assert result.credits_granted == 1
class TestFeedbackEmailNotification:
"""Tests for send_feedback_notification email method."""
@patch.object(EmailService, '_get_provider')
def test_send_feedback_notification_calls_provider(self, mock_get_provider):
"""Test that feedback notification sends email via provider."""
mock_provider = Mock()
mock_provider.send_email.return_value = True
mock_get_provider.return_value = mock_provider
service = EmailService()
result = service.send_feedback_notification(
user_email="alice@example.com",
overall_rating=5,
ease_of_use_rating=4,
lyrics_accuracy_rating=3,
correction_experience_rating=4,
what_went_well="Great lyrics sync",
what_could_improve="More song variety",
additional_comments=None,
would_recommend=True,
would_use_again=True,
)
assert result is True
mock_provider.send_email.assert_called_once()
call_args = mock_provider.send_email.call_args
# Check email is sent to admin
to_email = call_args.kwargs.get("to_email") or call_args[0][0]
assert to_email == "admin@nomadkaraoke.com"
# Check subject contains user email and rating
subject = call_args.kwargs.get("subject") or call_args[0][1]
assert "alice@example.com" in subject
assert "5/5" in subject
@patch.object(EmailService, '_get_provider')
def test_send_feedback_notification_content(self, mock_get_provider):
"""Test that feedback notification email contains all feedback fields."""
mock_provider = Mock()
mock_provider.send_email.return_value = True
mock_get_provider.return_value = mock_provider
service = EmailService()
service.send_feedback_notification(
user_email="bob@example.com",
overall_rating=3,
ease_of_use_rating=2,
lyrics_accuracy_rating=4,
correction_experience_rating=5,
what_went_well="Easy to use",
what_could_improve="Better mobile support",
additional_comments="Love it overall",
would_recommend=False,
would_use_again=True,
)
call_args = mock_provider.send_email.call_args
html_content = call_args.kwargs.get("html_content") or call_args[0][2]
text_content = call_args.kwargs.get("text_content") or call_args[0][3]
# Check HTML contains feedback text
assert "Easy to use" in html_content
assert "Better mobile support" in html_content
assert "Love it overall" in html_content
assert "bob@example.com" in html_content
# Check plain text also contains feedback
assert "Easy to use" in text_content
assert "Better mobile support" in text_content
assert "3/5" in text_content
@patch.object(EmailService, '_get_provider')
@patch.dict("os.environ", {"ADMIN_NOTIFICATION_EMAIL": "custom@admin.com"})
def test_send_feedback_notification_custom_admin_email(self, mock_get_provider):
"""Test that admin email can be configured via env var."""
mock_provider = Mock()
mock_provider.send_email.return_value = True
mock_get_provider.return_value = mock_provider
service = EmailService()
service.send_feedback_notification(
user_email="test@example.com",
overall_rating=4,
ease_of_use_rating=4,
lyrics_accuracy_rating=4,
correction_experience_rating=4,
)
call_args = mock_provider.send_email.call_args
to_email = call_args.kwargs.get("to_email") or call_args[0][0]
assert to_email == "custom@admin.com"
@patch.object(EmailService, '_get_provider')
def test_send_feedback_notification_returns_false_on_failure(self, mock_get_provider):
"""Test that failure is returned when provider fails."""
mock_provider = Mock()
mock_provider.send_email.return_value = False
mock_get_provider.return_value = mock_provider
service = EmailService()
result = service.send_feedback_notification(
user_email="test@example.com",
overall_rating=1,
ease_of_use_rating=1,
lyrics_accuracy_rating=1,
correction_experience_rating=1,
)
assert result is False
+857
View File
@@ -0,0 +1,857 @@
"""
Tests for anti-abuse improvements: credits on verification, IP rate limiting,
and device fingerprinting.
Covers:
- Phase 1: Welcome credits granted on verification, not account creation
- Phase 2: Per-IP signup rate limiting (2 new accounts per 24h)
- Phase 3: Device fingerprint rate limiting
"""
import pytest
import uuid
from datetime import datetime, timedelta
from unittest.mock import MagicMock, Mock, patch
from fastapi.testclient import TestClient
# Mock Firestore before importing modules that use it
import sys
sys.modules.setdefault('google.cloud.firestore', MagicMock())
sys.modules.setdefault('google.cloud.firestore_v1', MagicMock())
from backend.models.user import (
User,
MagicLinkToken,
CreditTransaction,
SendMagicLinkRequest,
)
# =============================================================================
# Phase 1: Credits on Verification
# =============================================================================
class TestGetOrCreateUserNoCredits:
"""New users should be created with 0 credits."""
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_new_user_created_with_zero_credits(self, mock_fs, mock_settings):
"""get_or_create_user creates users with 0 credits."""
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
# Simulate user not found
mock_doc = MagicMock()
mock_doc.exists = False
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
mock_db.collection.return_value.where.return_value.limit.return_value.stream.return_value = []
from backend.services.user_service import UserService
service = UserService()
user = service.get_or_create_user("new@example.com")
assert user.credits == 0
assert user.credit_transactions == []
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_new_user_stores_signup_ip(self, mock_fs, mock_settings):
"""get_or_create_user stores the signup IP."""
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
mock_doc = MagicMock()
mock_doc.exists = False
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
mock_db.collection.return_value.where.return_value.limit.return_value.stream.return_value = []
from backend.services.user_service import UserService
service = UserService()
user = service.get_or_create_user(
"new@example.com", signup_ip="1.2.3.4"
)
assert user.signup_ip == "1.2.3.4"
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_new_user_stores_device_fingerprint(self, mock_fs, mock_settings):
"""get_or_create_user stores the device fingerprint."""
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
mock_doc = MagicMock()
mock_doc.exists = False
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
mock_db.collection.return_value.where.return_value.limit.return_value.stream.return_value = []
from backend.services.user_service import UserService
service = UserService()
user = service.get_or_create_user(
"new@example.com", device_fingerprint="abc123"
)
assert user.device_fingerprint == "abc123"
class TestGrantWelcomeCredits:
"""Welcome credits should be granted on first verification."""
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_grants_credits_to_new_user(self, mock_fs, mock_settings):
"""grant_welcome_credits_if_eligible grants credits to user without welcome_credit txn."""
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
# User exists with 0 credits and no transactions
user = User(email="new@example.com", credits=0, credit_transactions=[])
mock_doc = MagicMock()
mock_doc.exists = True
mock_doc.to_dict.return_value = user.model_dump(mode='json')
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
from backend.services.user_service import UserService
service = UserService()
with patch('backend.services.credit_evaluation_service.get_credit_evaluation_service') as mock_eval:
from backend.services.credit_evaluation_service import CreditEvaluation
mock_eval.return_value.evaluate.return_value = CreditEvaluation(decision="grant", reasoning="OK", confidence=1.0)
granted, status = service.grant_welcome_credits_if_eligible("new@example.com")
assert granted is True
# Verify update was called with credits and flag
mock_db.collection.return_value.document.return_value.update.assert_called_once()
update_args = mock_db.collection.return_value.document.return_value.update.call_args[0][0]
assert update_args['credits'] == 1
assert update_args['welcome_credits_granted'] is True
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_uses_precomputed_eval_when_provided(self, mock_fs, mock_settings):
"""grant_welcome_credits_if_eligible uses pre-computed eval and skips AI call."""
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
user = User(email="new@example.com", credits=0, credit_transactions=[])
mock_doc = MagicMock()
mock_doc.exists = True
mock_doc.to_dict.return_value = user.model_dump(mode='json')
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
from backend.services.user_service import UserService
service = UserService()
with patch('backend.services.credit_evaluation_service.get_credit_evaluation_service') as mock_eval:
granted, status = service.grant_welcome_credits_if_eligible(
"new@example.com",
precomputed_eval={
"credit_eval_decision": "grant",
"credit_eval_reasoning": "Pre-computed: clean user",
},
)
# AI evaluation should NOT have been called
mock_eval.return_value.evaluate.assert_not_called()
assert granted is True
assert status == "granted"
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_skips_if_flag_already_set(self, mock_fs, mock_settings):
"""grant_welcome_credits_if_eligible returns False if welcome_credits_granted flag is True."""
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
# User has the flag set (even if transactions were trimmed)
user = User(
email="existing@example.com",
credits=2,
welcome_credits_granted=True,
)
mock_doc = MagicMock()
mock_doc.exists = True
mock_doc.to_dict.return_value = user.model_dump(mode='json')
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
from backend.services.user_service import UserService
service = UserService()
granted, status = service.grant_welcome_credits_if_eligible("existing@example.com")
assert granted is False
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_skips_if_transaction_exists(self, mock_fs, mock_settings):
"""grant_welcome_credits_if_eligible returns False if welcome_credit txn exists (secondary check)."""
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
# User has transaction but flag not set (legacy user)
user = User(
email="existing@example.com",
credits=2,
welcome_credits_granted=False,
credit_transactions=[
CreditTransaction(
id=str(uuid.uuid4()),
amount=2,
reason="welcome_credit",
)
],
)
mock_doc = MagicMock()
mock_doc.exists = True
mock_doc.to_dict.return_value = user.model_dump(mode='json')
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
from backend.services.user_service import UserService
service = UserService()
granted, status = service.grant_welcome_credits_if_eligible("existing@example.com")
assert granted is False
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_returns_false_for_nonexistent_user(self, mock_fs, mock_settings):
"""grant_welcome_credits_if_eligible returns False for unknown user."""
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
mock_doc = MagicMock()
mock_doc.exists = False
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
mock_db.collection.return_value.where.return_value.limit.return_value.stream.return_value = []
from backend.services.user_service import UserService
service = UserService()
granted, status = service.grant_welcome_credits_if_eligible("ghost@example.com")
assert granted is False
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_skips_evaluation_for_test_emails(self, mock_fs, mock_settings):
"""grant_welcome_credits_if_eligible skips AI evaluation for @inbox.testmail.app emails."""
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
user = User(email="e2e.test@inbox.testmail.app", credits=0, credit_transactions=[])
mock_doc = MagicMock()
mock_doc.exists = True
mock_doc.to_dict.return_value = user.model_dump(mode='json')
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
from backend.services.user_service import UserService
service = UserService()
with patch('backend.services.credit_evaluation_service.get_credit_evaluation_service') as mock_eval:
granted, status = service.grant_welcome_credits_if_eligible("e2e.test@inbox.testmail.app")
# AI evaluation should NOT have been called
mock_eval.return_value.evaluate.assert_not_called()
assert granted is True
assert status == "granted"
# =============================================================================
# Phase 2: Per-IP Signup Rate Limiting
# =============================================================================
class TestIPRateLimiting:
"""Test IP-based signup rate limiting."""
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_count_recent_signups_from_ip(self, mock_fs, mock_settings):
"""count_recent_signups_from_ip counts matching users."""
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
# Simulate 2 matching users
mock_docs = [MagicMock(), MagicMock()]
mock_db.collection.return_value.where.return_value.where.return_value.stream.return_value = mock_docs
from backend.services.user_service import UserService
service = UserService()
count = service.count_recent_signups_from_ip("1.2.3.4")
assert count == 2
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_is_signup_rate_limited_by_ip(self, mock_fs, mock_settings):
"""is_signup_rate_limited returns True when IP count >= 2."""
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
# 2 signups = rate limited
mock_docs = [MagicMock(), MagicMock()]
mock_db.collection.return_value.where.return_value.where.return_value.stream.return_value = mock_docs
from backend.services.user_service import UserService
service = UserService()
assert service.is_signup_rate_limited(ip_address="1.2.3.4") is True
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_not_rate_limited_with_one_signup(self, mock_fs, mock_settings):
"""is_signup_rate_limited returns False when IP count < 2."""
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
mock_docs = [MagicMock()]
mock_db.collection.return_value.where.return_value.where.return_value.stream.return_value = mock_docs
from backend.services.user_service import UserService
service = UserService()
assert service.is_signup_rate_limited(ip_address="1.2.3.4") is False
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_no_ip_not_rate_limited(self, mock_fs, mock_settings):
"""is_signup_rate_limited returns False when no IP provided."""
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
from backend.services.user_service import UserService
service = UserService()
assert service.is_signup_rate_limited(ip_address=None) is False
# =============================================================================
# Phase 3: Device Fingerprint Rate Limiting
# =============================================================================
class TestFingerprintRateLimiting:
"""Test fingerprint-based signup rate limiting."""
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_count_recent_signups_from_fingerprint(self, mock_fs, mock_settings):
"""count_recent_signups_from_fingerprint counts matching users."""
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
mock_docs = [MagicMock(), MagicMock(), MagicMock()]
mock_db.collection.return_value.where.return_value.where.return_value.stream.return_value = mock_docs
from backend.services.user_service import UserService
service = UserService()
count = service.count_recent_signups_from_fingerprint("fp123")
assert count == 3
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_is_signup_rate_limited_by_fingerprint(self, mock_fs, mock_settings):
"""is_signup_rate_limited returns True when fingerprint count >= 2."""
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
# IP returns 0, fingerprint returns 2
def side_effect_stream():
return iter([MagicMock(), MagicMock()])
# We need separate mock chains for IP and fingerprint queries
# Since both use the same mock chain, we'll set up the calls differently
call_count = [0]
def stream_side_effect():
call_count[0] += 1
if call_count[0] == 1:
return iter([]) # IP query: 0 results
return iter([MagicMock(), MagicMock()]) # Fingerprint query: 2 results
mock_db.collection.return_value.where.return_value.where.return_value.stream = stream_side_effect
from backend.services.user_service import UserService
service = UserService()
result = service.is_signup_rate_limited(
ip_address="1.2.3.4", device_fingerprint="fp123"
)
assert result is True
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_no_fingerprint_not_rate_limited(self, mock_fs, mock_settings):
"""is_signup_rate_limited doesn't check fingerprint when None."""
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
# IP query returns 0
mock_db.collection.return_value.where.return_value.where.return_value.stream.return_value = []
from backend.services.user_service import UserService
service = UserService()
result = service.is_signup_rate_limited(
ip_address="1.2.3.4", device_fingerprint=None
)
assert result is False
# =============================================================================
# Integration: Magic Link Endpoint Rate Limiting
# =============================================================================
@pytest.fixture
def mock_validation_svc():
"""Create a mock EmailValidationService."""
svc = MagicMock()
svc.is_disposable_domain.return_value = False
svc.is_email_blocked.return_value = False
svc.is_ip_blocked.return_value = False
return svc
@pytest.fixture
def mock_user_svc():
"""Create a mock UserService."""
svc = MagicMock()
svc.get_user.return_value = None # New user by default
svc.is_signup_rate_limited.return_value = False
svc.create_magic_link.return_value = MagicLinkToken(
token="test-token",
email="test@example.com",
expires_at=datetime.utcnow() + timedelta(minutes=15),
)
svc.NEW_USER_FREE_CREDITS = 1
return svc
@pytest.fixture
def mock_email_svc():
"""Create a mock EmailService."""
svc = MagicMock()
svc.is_configured.return_value = True
svc.send_magic_link.return_value = True
return svc
@pytest.fixture
def client(mock_validation_svc, mock_user_svc, mock_email_svc):
"""Create TestClient with mocked services via FastAPI dependency overrides."""
from backend.main import app
from backend.services.user_service import get_user_service
from backend.services.email_service import get_email_service
app.dependency_overrides[get_user_service] = lambda: mock_user_svc
app.dependency_overrides[get_email_service] = lambda: mock_email_svc
with patch(
"backend.api.routes.users.get_email_validation_service",
return_value=mock_validation_svc,
):
yield TestClient(app)
app.dependency_overrides.clear()
class TestMagicLinkRateLimiting:
"""Integration tests for rate limiting in the magic link endpoint."""
def test_new_signup_allowed_when_not_rate_limited(
self, client, mock_user_svc
):
"""New signup succeeds when not rate limited."""
mock_user_svc.get_user.return_value = None
mock_user_svc.is_signup_rate_limited.return_value = False
response = client.post(
"/api/users/auth/magic-link",
json={"email": "new@example.com"},
)
assert response.status_code == 200
mock_user_svc.create_magic_link.assert_called_once()
def test_new_signup_blocked_when_rate_limited(
self, client, mock_user_svc
):
"""New signup is silently rejected when rate limited."""
mock_user_svc.get_user.return_value = None
mock_user_svc.is_signup_rate_limited.return_value = True
response = client.post(
"/api/users/auth/magic-link",
json={"email": "abuser@example.com"},
)
assert response.status_code == 200
assert response.json()["status"] == "success"
# Magic link should NOT have been created
mock_user_svc.create_magic_link.assert_not_called()
def test_existing_user_not_rate_limited(
self, client, mock_user_svc
):
"""Returning user bypasses rate limiting."""
mock_user_svc.get_user.return_value = User(
email="existing@example.com", credits=5
)
response = client.post(
"/api/users/auth/magic-link",
json={"email": "existing@example.com"},
)
assert response.status_code == 200
# Rate limit check should not be called for existing users
mock_user_svc.is_signup_rate_limited.assert_not_called()
mock_user_svc.create_magic_link.assert_called_once()
def test_fingerprint_passed_to_create_magic_link(
self, client, mock_user_svc
):
"""Device fingerprint from request body is passed to create_magic_link."""
mock_user_svc.get_user.return_value = None
mock_user_svc.is_signup_rate_limited.return_value = False
response = client.post(
"/api/users/auth/magic-link",
json={"email": "new@example.com", "device_fingerprint": "fp-abc123"},
)
assert response.status_code == 200
create_call = mock_user_svc.create_magic_link.call_args
assert create_call.kwargs.get('device_fingerprint') == "fp-abc123"
def test_fingerprint_passed_to_rate_limiter(
self, client, mock_user_svc
):
"""Device fingerprint is included in rate limit check."""
mock_user_svc.get_user.return_value = None
mock_user_svc.is_signup_rate_limited.return_value = False
response = client.post(
"/api/users/auth/magic-link",
json={"email": "new@example.com", "device_fingerprint": "fp-abc123"},
)
rate_limit_call = mock_user_svc.is_signup_rate_limited.call_args
assert rate_limit_call.kwargs.get('device_fingerprint') == "fp-abc123"
def test_missing_fingerprint_gracefully_handled(
self, client, mock_user_svc
):
"""Missing fingerprint doesn't break the flow."""
mock_user_svc.get_user.return_value = None
mock_user_svc.is_signup_rate_limited.return_value = False
response = client.post(
"/api/users/auth/magic-link",
json={"email": "new@example.com"},
)
assert response.status_code == 200
rate_limit_call = mock_user_svc.is_signup_rate_limited.call_args
assert rate_limit_call.kwargs.get('device_fingerprint') is None
# =============================================================================
# Integration: Verify Endpoint Grants Credits
# =============================================================================
class TestVerifyGrantsCredits:
"""Test that the verify endpoint grants welcome credits."""
def _make_verify_client(self, mock_user_svc, user, credits_eligible):
"""Helper to create a TestClient for verify endpoint tests."""
from backend.main import app
from backend.services.user_service import get_user_service
from backend.services.email_service import get_email_service
mock_user_svc.verify_magic_link.return_value = (True, user, "Success")
mock_user_svc.grant_welcome_credits_if_eligible.return_value = (credits_eligible, "granted" if credits_eligible else "already_granted")
mock_user_svc.get_user.return_value = user
mock_user_svc.create_session.return_value = MagicMock(token="session-token")
mock_user_svc.NEW_USER_FREE_CREDITS = 1
# Mock magic link doc for first-login check
mock_ml_doc = MagicMock()
mock_ml_doc.exists = True
mock_ml_doc.to_dict.return_value = {
'email': user.email,
'tenant_id': None,
}
mock_user_svc.db.collection.return_value.document.return_value.get.return_value = mock_ml_doc
mock_email_svc = MagicMock()
app.dependency_overrides[get_user_service] = lambda: mock_user_svc
app.dependency_overrides[get_email_service] = lambda: mock_email_svc
client = TestClient(app)
return client
def test_verify_returns_credits_granted(self, mock_user_svc):
"""Verify endpoint returns credits_granted in response."""
user = User(email="new@example.com", credits=2, email_verified=True)
client = self._make_verify_client(mock_user_svc, user, credits_eligible=True)
try:
response = client.get("/api/users/auth/verify?token=valid-token")
assert response.status_code == 200
data = response.json()
assert data["credits_granted"] == 1
mock_user_svc.grant_welcome_credits_if_eligible.assert_called_once()
finally:
from backend.main import app
app.dependency_overrides.clear()
def test_verify_passes_precomputed_eval(self, mock_user_svc):
"""Verify endpoint passes pre-computed eval from magic link doc."""
user = User(email="new@example.com", credits=2, email_verified=True)
client = self._make_verify_client(mock_user_svc, user, credits_eligible=True)
# Add pre-computed eval to the magic link doc
mock_ml_doc = mock_user_svc.db.collection.return_value.document.return_value.get.return_value
mock_ml_doc.to_dict.return_value = {
'email': user.email,
'tenant_id': None,
'credit_eval_decision': 'grant',
'credit_eval_reasoning': 'Clean user',
}
try:
response = client.get("/api/users/auth/verify?token=valid-token")
assert response.status_code == 200
# Verify precomputed_eval was passed through
call_kwargs = mock_user_svc.grant_welcome_credits_if_eligible.call_args
assert call_kwargs[1]['precomputed_eval'] == {
'credit_eval_decision': 'grant',
'credit_eval_reasoning': 'Clean user',
}
finally:
from backend.main import app
app.dependency_overrides.clear()
def test_verify_falls_back_without_precomputed_eval(self, mock_user_svc):
"""Verify endpoint passes None when no pre-computed eval exists."""
user = User(email="new@example.com", credits=2, email_verified=True)
client = self._make_verify_client(mock_user_svc, user, credits_eligible=True)
try:
response = client.get("/api/users/auth/verify?token=valid-token")
assert response.status_code == 200
call_kwargs = mock_user_svc.grant_welcome_credits_if_eligible.call_args
assert call_kwargs[1]['precomputed_eval'] is None
finally:
from backend.main import app
app.dependency_overrides.clear()
def test_verify_returns_zero_credits_for_returning_user(self, mock_user_svc):
"""Returning user gets credits_granted=0."""
user = User(
email="existing@example.com",
credits=5,
email_verified=True,
last_login_at=datetime.utcnow(),
)
client = self._make_verify_client(mock_user_svc, user, credits_eligible=False)
try:
response = client.get("/api/users/auth/verify?token=valid-token")
assert response.status_code == 200
data = response.json()
assert data["credits_granted"] == 0
finally:
from backend.main import app
app.dependency_overrides.clear()
# =============================================================================
# Model Tests
# =============================================================================
class TestModelFields:
"""Test that new fields exist on models."""
def test_user_has_signup_ip(self):
"""User model has signup_ip field."""
user = User(email="test@example.com", signup_ip="1.2.3.4")
assert user.signup_ip == "1.2.3.4"
def test_user_has_device_fingerprint(self):
"""User model has device_fingerprint field."""
user = User(email="test@example.com", device_fingerprint="fp123")
assert user.device_fingerprint == "fp123"
def test_user_defaults_none(self):
"""New fields default to None."""
user = User(email="test@example.com")
assert user.signup_ip is None
assert user.device_fingerprint is None
def test_magic_link_has_device_fingerprint(self):
"""MagicLinkToken model has device_fingerprint field."""
ml = MagicLinkToken(
token="tok",
email="test@example.com",
expires_at=datetime.utcnow(),
device_fingerprint="fp123",
)
assert ml.device_fingerprint == "fp123"
def test_send_magic_link_request_has_fingerprint(self):
"""SendMagicLinkRequest accepts device_fingerprint."""
req = SendMagicLinkRequest(
email="test@example.com",
device_fingerprint="fp123",
)
assert req.device_fingerprint == "fp123"
def test_send_magic_link_request_fingerprint_optional(self):
"""SendMagicLinkRequest works without device_fingerprint."""
req = SendMagicLinkRequest(email="test@example.com")
assert req.device_fingerprint is None
# =============================================================================
# Error Path Tests
# =============================================================================
class TestErrorPaths:
"""Test graceful degradation on errors."""
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_grant_credits_handles_exception(self, mock_fs, mock_settings):
"""grant_welcome_credits_if_eligible returns False on exception."""
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
# User lookup raises exception
mock_db.collection.return_value.document.return_value.get.side_effect = Exception("Firestore down")
from backend.services.user_service import UserService
service = UserService()
granted, status = service.grant_welcome_credits_if_eligible("test@example.com")
assert granted is False
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_count_signups_from_ip_handles_exception(self, mock_fs, mock_settings):
"""count_recent_signups_from_ip returns 0 on Firestore error (fail-open)."""
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
mock_db.collection.return_value.where.return_value.where.side_effect = Exception("Query error")
from backend.services.user_service import UserService
service = UserService()
count = service.count_recent_signups_from_ip("1.2.3.4")
assert count == 0 # Fail-open: don't block on error
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_count_signups_from_fingerprint_handles_exception(self, mock_fs, mock_settings):
"""count_recent_signups_from_fingerprint returns 0 on error (fail-open)."""
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
mock_db.collection.return_value.where.return_value.where.side_effect = Exception("Query error")
from backend.services.user_service import UserService
service = UserService()
count = service.count_recent_signups_from_fingerprint("fp123")
assert count == 0
# =============================================================================
# Caller-Callee Contract Tests
# =============================================================================
class TestCallerCalleeContracts:
"""Verify that callers pass the right data to callees."""
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_create_magic_link_passes_fingerprint_to_get_or_create(self, mock_fs, mock_settings):
"""create_magic_link passes device_fingerprint through to get_or_create_user."""
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
# User already exists (to avoid save path)
user = User(email="test@example.com", credits=0)
mock_doc = MagicMock()
mock_doc.exists = True
mock_doc.to_dict.return_value = user.model_dump(mode='json')
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
from backend.services.user_service import UserService
service = UserService()
with patch.object(service, 'get_or_create_user', wraps=service.get_or_create_user) as spy:
service.create_magic_link(
"test@example.com",
ip_address="1.2.3.4",
device_fingerprint="fp-xyz",
)
spy.assert_called_once_with(
"test@example.com",
tenant_id=None,
signup_ip="1.2.3.4",
device_fingerprint="fp-xyz",
)
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_create_magic_link_stores_fingerprint_on_token(self, mock_fs, mock_settings):
"""create_magic_link includes device_fingerprint in the MagicLinkToken."""
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
user = User(email="test@example.com", credits=0)
mock_doc = MagicMock()
mock_doc.exists = True
mock_doc.to_dict.return_value = user.model_dump(mode='json')
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
from backend.services.user_service import UserService
service = UserService()
ml = service.create_magic_link(
"test@example.com",
ip_address="1.2.3.4",
device_fingerprint="fp-xyz",
)
assert ml.device_fingerprint == "fp-xyz"
# Also verify the data written to Firestore includes the fingerprint
set_call = mock_db.collection.return_value.document.return_value.set
set_call.assert_called()
saved_data = set_call.call_args[0][0]
assert saved_data["device_fingerprint"] == "fp-xyz"
@@ -0,0 +1,480 @@
"""
Tests for anti-abuse investigation features: admin endpoints, session/job
fingerprint tracking, and user lookup methods.
"""
import pytest
from datetime import datetime, timedelta
from unittest.mock import MagicMock, patch
from fastapi.testclient import TestClient
import sys
sys.modules.setdefault('google.cloud.firestore', MagicMock())
sys.modules.setdefault('google.cloud.firestore_v1', MagicMock())
from backend.models.user import User, Session, MagicLinkToken
# =============================================================================
# Model Tests
# =============================================================================
class TestSessionFingerprint:
"""Session model stores device_fingerprint."""
def test_session_has_device_fingerprint(self):
session = Session(
token="tok",
user_email="test@example.com",
expires_at=datetime.utcnow() + timedelta(days=30),
device_fingerprint="fp-abc",
)
assert session.device_fingerprint == "fp-abc"
def test_session_fingerprint_defaults_none(self):
session = Session(
token="tok",
user_email="test@example.com",
expires_at=datetime.utcnow() + timedelta(days=30),
)
assert session.device_fingerprint is None
class TestJobCreationIp:
"""Job model stores creation_ip."""
def test_job_has_creation_ip(self):
from backend.models.job import Job, JobStatus
job = Job(
job_id="test123",
status=JobStatus.PENDING,
created_at=datetime.utcnow(),
updated_at=datetime.utcnow(),
creation_ip="1.2.3.4",
)
assert job.creation_ip == "1.2.3.4"
def test_job_creation_ip_defaults_none(self):
from backend.models.job import Job, JobStatus
job = Job(
job_id="test123",
status=JobStatus.PENDING,
created_at=datetime.utcnow(),
updated_at=datetime.utcnow(),
)
assert job.creation_ip is None
# =============================================================================
# Internal/Test Email Filtering
# =============================================================================
class TestInternalOrTestEmail:
"""Tests for is_internal_or_test_email utility."""
def test_nomadkaraoke_is_internal(self):
from backend.utils.test_data import is_internal_or_test_email
assert is_internal_or_test_email("admin@nomadkaraoke.com") is True
def test_beveridge_is_internal(self):
from backend.utils.test_data import is_internal_or_test_email
assert is_internal_or_test_email("vocalstar@beveridge.uk") is True
def test_testmail_is_test(self):
from backend.utils.test_data import is_internal_or_test_email
assert is_internal_or_test_email("test123@inbox.testmail.app") is True
def test_regular_email_is_not_internal(self):
from backend.utils.test_data import is_internal_or_test_email
assert is_internal_or_test_email("user@gmail.com") is False
def test_empty_email(self):
from backend.utils.test_data import is_internal_or_test_email
assert is_internal_or_test_email("") is False
def test_is_internal_email_only(self):
from backend.utils.test_data import is_internal_email
assert is_internal_email("andrew@beveridge.uk") is True
assert is_internal_email("user@gmail.com") is False
# =============================================================================
# UserService Investigation Methods
# =============================================================================
class TestFindUsersBySignupIp:
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_finds_matching_users(self, mock_fs, mock_settings):
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
user1 = User(email="a@test.com", signup_ip="1.2.3.4").model_dump(mode='json')
user2 = User(email="b@test.com", signup_ip="1.2.3.4").model_dump(mode='json')
mock_doc1 = MagicMock()
mock_doc1.to_dict.return_value = user1
mock_doc2 = MagicMock()
mock_doc2.to_dict.return_value = user2
mock_db.collection.return_value.where.return_value.order_by.return_value.limit.return_value.stream.return_value = [mock_doc1, mock_doc2]
from backend.services.user_service import UserService
service = UserService()
results = service.find_users_by_signup_ip("1.2.3.4")
assert len(results) == 2
assert results[0].email == "a@test.com"
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_returns_empty_on_error(self, mock_fs, mock_settings):
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
mock_db.collection.return_value.where.side_effect = Exception("Firestore down")
from backend.services.user_service import UserService
service = UserService()
results = service.find_users_by_signup_ip("1.2.3.4")
assert results == []
class TestFindUsersByFingerprint:
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_finds_matching_users(self, mock_fs, mock_settings):
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
user1 = User(email="a@test.com", device_fingerprint="fp123").model_dump(mode='json')
mock_doc1 = MagicMock()
mock_doc1.to_dict.return_value = user1
mock_db.collection.return_value.where.return_value.order_by.return_value.limit.return_value.stream.return_value = [mock_doc1]
from backend.services.user_service import UserService
service = UserService()
results = service.find_users_by_fingerprint("fp123")
assert len(results) == 1
class TestFindSuspiciousAccounts:
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_finds_free_high_usage_accounts(self, mock_fs, mock_settings):
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
free_abuser = User(email="free@test.com", total_jobs_created=5, total_spent=0).model_dump(mode='json')
paying_user = User(email="paid@test.com", total_jobs_created=10, total_spent=500).model_dump(mode='json')
mock_doc1 = MagicMock()
mock_doc1.to_dict.return_value = free_abuser
mock_doc2 = MagicMock()
mock_doc2.to_dict.return_value = paying_user
mock_db.collection.return_value.where.return_value.order_by.return_value.limit.return_value.stream.return_value = [mock_doc1, mock_doc2]
from backend.services.user_service import UserService
service = UserService()
results = service.find_suspicious_accounts(min_jobs=2, max_spend=0)
assert len(results) == 1
assert results[0].email == "free@test.com"
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_excludes_internal_and_test_accounts(self, mock_fs, mock_settings):
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
real_user = User(email="abuser@gmail.com", total_jobs_created=5, total_spent=0).model_dump(mode='json')
internal_user = User(email="admin@nomadkaraoke.com", total_jobs_created=10, total_spent=0).model_dump(mode='json')
test_user = User(email="e2e@inbox.testmail.app", total_jobs_created=8, total_spent=0).model_dump(mode='json')
personal_user = User(email="vocalstar@beveridge.uk", total_jobs_created=3, total_spent=0).model_dump(mode='json')
docs = []
for data in [real_user, internal_user, test_user, personal_user]:
doc = MagicMock()
doc.to_dict.return_value = data
docs.append(doc)
mock_db.collection.return_value.where.return_value.order_by.return_value.limit.return_value.stream.return_value = docs
from backend.services.user_service import UserService
service = UserService()
results = service.find_suspicious_accounts(min_jobs=2, max_spend=0)
assert len(results) == 1
assert results[0].email == "abuser@gmail.com"
class TestFindRelatedAccounts:
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_finds_related_by_ip_and_fingerprint(self, mock_fs, mock_settings):
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
target = User(email="target@test.com", signup_ip="1.2.3.4", device_fingerprint="fp123")
from backend.services.user_service import UserService
service = UserService()
with patch.object(service, 'get_user', return_value=target), \
patch.object(service, 'find_users_by_signup_ip', return_value=[
target,
User(email="related@test.com", signup_ip="1.2.3.4"),
]), \
patch.object(service, 'find_users_by_fingerprint', return_value=[
target,
User(email="device-buddy@test.com", device_fingerprint="fp123"),
]):
result = service.find_related_accounts("target@test.com")
assert result["user"].email == "target@test.com"
# Should exclude the target user from related lists
assert len(result["by_ip"]) == 1
assert result["by_ip"][0].email == "related@test.com"
assert len(result["by_fingerprint"]) == 1
assert result["by_fingerprint"][0].email == "device-buddy@test.com"
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_returns_empty_for_unknown_user(self, mock_fs, mock_settings):
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
mock_doc = MagicMock()
mock_doc.exists = False
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
mock_db.collection.return_value.where.return_value.limit.return_value.stream.return_value = []
from backend.services.user_service import UserService
service = UserService()
result = service.find_related_accounts("ghost@test.com")
assert result["user"] is None
assert result["by_ip"] == []
assert result["by_fingerprint"] == []
# =============================================================================
# Admin Endpoint Integration Tests
# =============================================================================
@pytest.fixture
def mock_user_svc():
svc = MagicMock()
svc.NEW_USER_FREE_CREDITS = 1
return svc
@pytest.fixture
def admin_client(mock_user_svc):
from backend.main import app
from backend.services.user_service import get_user_service
from backend.api.dependencies import require_admin
mock_auth = MagicMock()
mock_auth.is_admin = True
mock_auth.user_email = "admin@nomadkaraoke.com"
app.dependency_overrides[get_user_service] = lambda: mock_user_svc
app.dependency_overrides[require_admin] = lambda: mock_auth
yield TestClient(app)
app.dependency_overrides.clear()
class TestAdminAbuseEndpoints:
def test_suspicious_accounts_endpoint(self, admin_client, mock_user_svc):
mock_user_svc.find_suspicious_accounts.return_value = [
User(email="free@test.com", total_jobs_created=5, total_spent=0),
]
response = admin_client.get("/api/admin/abuse/suspicious?min_jobs=2&max_spend=0")
assert response.status_code == 200
data = response.json()
assert data["count"] == 1
assert data["users"][0]["email"] == "free@test.com"
def test_by_ip_endpoint(self, admin_client, mock_user_svc):
mock_user_svc.find_users_by_signup_ip.return_value = [
User(email="a@test.com", signup_ip="1.2.3.4"),
User(email="b@test.com", signup_ip="1.2.3.4"),
]
response = admin_client.get("/api/admin/abuse/by-ip/1.2.3.4")
assert response.status_code == 200
data = response.json()
assert data["count"] == 2
def test_by_fingerprint_endpoint(self, admin_client, mock_user_svc):
mock_user_svc.find_users_by_fingerprint.return_value = [
User(email="a@test.com", device_fingerprint="fp123"),
]
response = admin_client.get("/api/admin/abuse/by-fingerprint/fp123")
assert response.status_code == 200
data = response.json()
assert data["count"] == 1
def test_related_endpoint(self, admin_client, mock_user_svc):
target = User(email="target@test.com", signup_ip="1.2.3.4", device_fingerprint="fp123", total_jobs_created=3)
mock_user_svc.find_related_accounts.return_value = {
"user": target,
"by_ip": [User(email="buddy@test.com", signup_ip="1.2.3.4")],
"by_fingerprint": [],
}
response = admin_client.get("/api/admin/abuse/related/target@test.com")
assert response.status_code == 200
data = response.json()
assert data["user"]["email"] == "target@test.com"
assert len(data["related_by_ip"]) == 1
assert len(data["related_by_fingerprint"]) == 0
def test_related_endpoint_user_not_found(self, admin_client, mock_user_svc):
mock_user_svc.find_related_accounts.return_value = {
"user": None, "by_ip": [], "by_fingerprint": [],
}
response = admin_client.get("/api/admin/abuse/related/ghost@test.com")
assert response.status_code == 404
def test_correlations_endpoint(self, admin_client, mock_user_svc):
user_a = User(email="a@test.com", signup_ip="1.2.3.4", device_fingerprint="fp123", total_jobs_created=2)
user_b = User(email="b@test.com", signup_ip="1.2.3.4", device_fingerprint="fp123", total_jobs_created=3)
mock_user_svc.find_account_correlations.return_value = {
"fingerprint_clusters": [
{"fingerprint": "fp123", "users": [user_a, user_b]},
],
"ip_clusters": [
{"ip": "1.2.3.4", "users": [user_a, user_b]},
],
"user_agents": {"a@test.com": "Mozilla/5.0", "b@test.com": "Mozilla/5.0"},
}
response = admin_client.get("/api/admin/abuse/correlations")
assert response.status_code == 200
data = response.json()
assert len(data["fingerprint_clusters"]) == 1
assert data["fingerprint_clusters"][0]["fingerprint"] == "fp123"
assert data["fingerprint_clusters"][0]["count"] == 2
assert data["fingerprint_clusters"][0]["users"][0]["user_agent"] == "Mozilla/5.0"
assert len(data["ip_clusters"]) == 1
assert data["ip_clusters"][0]["ip"] == "1.2.3.4"
assert data["ip_clusters"][0]["count"] == 2
def test_correlations_endpoint_empty(self, admin_client, mock_user_svc):
mock_user_svc.find_account_correlations.return_value = {
"fingerprint_clusters": [],
"ip_clusters": [],
"user_agents": {},
}
response = admin_client.get("/api/admin/abuse/correlations")
assert response.status_code == 200
data = response.json()
assert data["fingerprint_clusters"] == []
assert data["ip_clusters"] == []
# =============================================================================
# Correlations Service Method Tests
# =============================================================================
class TestFindAccountCorrelations:
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_groups_by_fingerprint_and_ip(self, mock_fs, mock_settings):
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
user_a = User(email="a@gmail.com", signup_ip="1.2.3.4", device_fingerprint="fp123", total_jobs_created=2).model_dump(mode='json')
user_b = User(email="b@gmail.com", signup_ip="1.2.3.4", device_fingerprint="fp123", total_jobs_created=3).model_dump(mode='json')
user_c = User(email="c@gmail.com", signup_ip="5.6.7.8", device_fingerprint="fp999", total_jobs_created=1).model_dump(mode='json')
docs = []
for data in [user_a, user_b, user_c]:
doc = MagicMock()
doc.to_dict.return_value = data
docs.append(doc)
# Mock the users collection stream
mock_db.collection.return_value.stream.return_value = docs
# Mock session lookups (return empty for simplicity)
mock_db.collection.return_value.where.return_value.order_by.return_value.limit.return_value.stream.return_value = []
from backend.services.user_service import UserService
service = UserService()
result = service.find_account_correlations()
# a and b share fp123 → 1 fingerprint cluster
assert len(result["fingerprint_clusters"]) == 1
assert result["fingerprint_clusters"][0]["fingerprint"] == "fp123"
assert len(result["fingerprint_clusters"][0]["users"]) == 2
# a and b share IP 1.2.3.4 → 1 IP cluster
assert len(result["ip_clusters"]) == 1
assert result["ip_clusters"][0]["ip"] == "1.2.3.4"
assert len(result["ip_clusters"][0]["users"]) == 2
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_excludes_internal_accounts(self, mock_fs, mock_settings):
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
real_user = User(email="user@gmail.com", signup_ip="1.2.3.4", device_fingerprint="fp123").model_dump(mode='json')
internal_user = User(email="admin@nomadkaraoke.com", signup_ip="1.2.3.4", device_fingerprint="fp123").model_dump(mode='json')
docs = []
for data in [real_user, internal_user]:
doc = MagicMock()
doc.to_dict.return_value = data
docs.append(doc)
mock_db.collection.return_value.stream.return_value = docs
from backend.services.user_service import UserService
service = UserService()
result = service.find_account_correlations()
# Only 1 non-internal user with fp123, so no cluster (need 2+)
assert len(result["fingerprint_clusters"]) == 0
assert len(result["ip_clusters"]) == 0
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_returns_empty_on_error(self, mock_fs, mock_settings):
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
mock_db.collection.return_value.stream.side_effect = Exception("Firestore down")
from backend.services.user_service import UserService
service = UserService()
result = service.find_account_correlations()
assert result["fingerprint_clusters"] == []
assert result["ip_clusters"] == []
@@ -5,7 +5,9 @@ These tests mock the storage service and shared karaoke_gen modules to verify:
- GCS file download/upload operations
- Audio analysis delegation to shared AudioAnalyzer
- Waveform generation delegation to shared WaveformGenerator
- Waveform data caching (cache_waveform_data / load_cached_waveform)
"""
import json
import pytest
from unittest.mock import Mock, MagicMock, patch, ANY
import tempfile
@@ -292,3 +294,119 @@ class TestGenerateWaveformWithMutes:
# Verify return
assert result_path == "uploads/job123/waveform_muted.png"
class TestCacheWaveformData:
"""Test cache_waveform_data method."""
@patch("backend.services.audio_analysis_service.StorageService")
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
@patch("backend.services.audio_analysis_service.WaveformGenerator")
def test_caches_waveform_to_gcs(
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
):
"""cache_waveform_data should generate waveform and upload JSON to GCS."""
from backend.services.audio_analysis_service import AudioAnalysisService
mock_storage = Mock()
mock_storage_class.return_value = mock_storage
mock_waveform = Mock()
mock_waveform.generate_data_only.return_value = ([0.1, 0.5, 0.3], 200.0)
mock_waveform_class.return_value = mock_waveform
service = AudioAnalysisService()
amplitudes, duration = service.cache_waveform_data(
gcs_audio_path="jobs/j1/input/song.flac",
job_id="j1",
cache_gcs_path="jobs/j1/audio_edit/waveform_original.json",
num_points=1000,
)
assert amplitudes == [0.1, 0.5, 0.3]
assert duration == 200.0
# Verify JSON was uploaded with correct structure
mock_storage.upload_json.assert_called_once()
call_args = mock_storage.upload_json.call_args
assert call_args[0][0] == "jobs/j1/audio_edit/waveform_original.json"
uploaded_data = call_args[0][1]
assert uploaded_data["amplitudes"] == [0.1, 0.5, 0.3]
assert uploaded_data["duration_seconds"] == 200.0
assert uploaded_data["num_points"] == 1000
assert uploaded_data["source_gcs_path"] == "jobs/j1/input/song.flac"
class TestLoadCachedWaveform:
"""Test load_cached_waveform method."""
@patch("backend.services.audio_analysis_service.StorageService")
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
@patch("backend.services.audio_analysis_service.WaveformGenerator")
def test_returns_none_when_cache_missing(
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
):
"""Should return None when cache file doesn't exist."""
from backend.services.audio_analysis_service import AudioAnalysisService
mock_storage = Mock()
mock_storage.file_exists.return_value = False
mock_storage_class.return_value = mock_storage
service = AudioAnalysisService()
result = service.load_cached_waveform("jobs/j1/audio_edit/waveform_original.json")
assert result is None
@patch("backend.services.audio_analysis_service.StorageService")
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
@patch("backend.services.audio_analysis_service.WaveformGenerator")
def test_loads_cached_waveform(
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
):
"""Should load and parse cached waveform JSON from GCS."""
from backend.services.audio_analysis_service import AudioAnalysisService
cache_data = {
"amplitudes": [0.2, 0.6, 0.4],
"duration_seconds": 180.0,
"num_points": 1000,
"source_gcs_path": "jobs/j1/input/song.flac",
}
mock_storage = Mock()
mock_storage.file_exists.return_value = True
# Simulate download_file writing JSON to the local path
def write_json(gcs_path, local_path):
with open(local_path, 'w') as f:
json.dump(cache_data, f)
mock_storage.download_file.side_effect = write_json
mock_storage_class.return_value = mock_storage
service = AudioAnalysisService()
result = service.load_cached_waveform("jobs/j1/audio_edit/waveform_original.json")
assert result is not None
amplitudes, duration = result
assert amplitudes == [0.2, 0.6, 0.4]
assert duration == 180.0
@patch("backend.services.audio_analysis_service.StorageService")
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
@patch("backend.services.audio_analysis_service.WaveformGenerator")
def test_returns_none_on_error(
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
):
"""Should return None gracefully on any error."""
from backend.services.audio_analysis_service import AudioAnalysisService
mock_storage = Mock()
mock_storage.file_exists.return_value = True
mock_storage.download_file.side_effect = Exception("GCS timeout")
mock_storage_class.return_value = mock_storage
service = AudioAnalysisService()
result = service.load_cached_waveform("jobs/j1/audio_edit/waveform_original.json")
assert result is None
@@ -183,6 +183,85 @@ class TestProcessAudioDownload:
assert call_kwargs['source_id'] == 'spotify123'
class TestAudioEditPreGeneration:
"""Tests for pre-generation of editor assets when requires_audio_edit is set."""
@pytest.mark.asyncio
async def test_pregenerates_assets_when_audio_edit_requested(self):
"""Should transcode OGG + cache waveform before transitioning to awaiting_audio_edit."""
job = _make_job(state_data={'requires_audio_edit': True})
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
patch("backend.workers.audio_download_worker.StorageService"), \
patch("backend.workers.audio_download_worker._download_audio", new_callable=AsyncMock) as mock_dl, \
patch("backend.services.audio_transcoding_service.AudioTranscodingService") as MockTS, \
patch("backend.services.audio_analysis_service.AudioAnalysisService") as MockAS:
mock_jm = MagicMock()
# First get_job returns the initial job, second returns the one with requires_audio_edit
mock_jm.get_job.return_value = job
mock_jm.transition_to_state.return_value = True
mock_jm_cls.return_value = mock_jm
mock_dl.return_value = ("uploads/test-job-123/audio/song.flac", "song.flac")
mock_ts = MagicMock()
MockTS.return_value = mock_ts
mock_as = MagicMock()
mock_as.cache_waveform_data.return_value = ([0.1, 0.5], 200.0)
MockAS.return_value = mock_as
result = await process_audio_download("test-job-123")
assert result is True
# Should have transcoded OGG
mock_ts.transcode_if_needed.assert_called_once_with("uploads/test-job-123/audio/song.flac")
# Should have cached waveform
mock_as.cache_waveform_data.assert_called_once_with(
"uploads/test-job-123/audio/song.flac",
"test-job-123",
"jobs/test-job-123/audio_edit/waveform_original.json",
)
# Should have stored cache path in state_data
mock_jm.update_state_data.assert_any_call(
"test-job-123", "audio_edit_waveform_cache_path",
"jobs/test-job-123/audio_edit/waveform_original.json",
)
# Should have transitioned to awaiting_audio_edit
calls = mock_jm.transition_to_state.call_args_list
assert any(c.kwargs.get('new_status') == JobStatus.AWAITING_AUDIO_EDIT for c in calls)
@pytest.mark.asyncio
async def test_pregeneration_failure_is_nonfatal(self):
"""Pre-generation failure should not prevent the job from reaching awaiting_audio_edit."""
job = _make_job(state_data={'requires_audio_edit': True})
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
patch("backend.workers.audio_download_worker.StorageService"), \
patch("backend.workers.audio_download_worker._download_audio", new_callable=AsyncMock) as mock_dl, \
patch("backend.services.audio_transcoding_service.AudioTranscodingService") as MockTS:
mock_jm = MagicMock()
mock_jm.get_job.return_value = job
mock_jm.transition_to_state.return_value = True
mock_jm_cls.return_value = mock_jm
mock_dl.return_value = ("uploads/test-job-123/audio/song.flac", "song.flac")
# Transcoding fails
mock_ts = MagicMock()
mock_ts.transcode_if_needed.side_effect = RuntimeError("ffmpeg not found")
MockTS.return_value = mock_ts
result = await process_audio_download("test-job-123")
# Should still succeed and transition to awaiting_audio_edit
assert result is True
calls = mock_jm.transition_to_state.call_args_list
assert any(c.kwargs.get('new_status') == JobStatus.AWAITING_AUDIO_EDIT for c in calls)
class TestDownloadAudio:
"""Tests for _download_audio routing."""
+60
View File
@@ -170,6 +170,66 @@ class TestGetInputAudioInfo:
resp = test_client.get("/api/review/no-audio/input-audio-info")
assert resp.status_code == 404
def test_uses_cached_waveform_when_available(self, test_client, mock_job_manager, mock_services):
"""When waveform cache exists, should use it instead of on-demand generation."""
job = _job(
job_id="cached-job",
status=JobStatus.AWAITING_AUDIO_EDIT,
input_media_gcs_path="jobs/cached-job/input/song.flac",
state_data={"audio_edit_waveform_cache_path": "jobs/cached-job/audio_edit/waveform_original.json"},
)
mock_job_manager.get_job.return_value = job
mock_services["analysis"].load_cached_waveform.return_value = ([0.2, 0.6, 0.4], 180.0)
mock_services["edit"].get_metadata_from_gcs.return_value = AudioMetadata(
duration_seconds=180.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=30000000,
)
resp = test_client.get("/api/review/cached-job/input-audio-info")
assert resp.status_code == 200
data = resp.json()
assert data["original_duration_seconds"] == 180.0
assert data["original_waveform_data"]["amplitudes"] == [0.2, 0.6, 0.4]
# Should have used cache, not on-demand generation
mock_services["analysis"].load_cached_waveform.assert_called_once_with(
"jobs/cached-job/audio_edit/waveform_original.json"
)
mock_services["analysis"].get_waveform_data.assert_not_called()
def test_falls_back_to_on_demand_when_cache_missing(self, test_client, mock_job_manager, mock_services):
"""When waveform cache path is set but cache doesn't exist, should fall back."""
job = _job(
job_id="no-cache-job",
status=JobStatus.AWAITING_AUDIO_EDIT,
input_media_gcs_path="jobs/no-cache-job/input/song.flac",
state_data={"audio_edit_waveform_cache_path": "jobs/no-cache-job/audio_edit/waveform_original.json"},
)
mock_job_manager.get_job.return_value = job
mock_services["analysis"].load_cached_waveform.return_value = None
mock_services["edit"].get_metadata_from_gcs.return_value = AudioMetadata(
duration_seconds=200.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=30000000,
)
resp = test_client.get("/api/review/no-cache-job/input-audio-info")
assert resp.status_code == 200
# Should have fallen back to on-demand
mock_services["analysis"].get_waveform_data.assert_called_once()
def test_on_demand_when_no_cache_path_in_state(self, test_client, mock_job_manager, mock_services, audio_edit_job):
"""Jobs without cache path in state_data should use on-demand generation."""
mock_job_manager.get_job.return_value = audio_edit_job
mock_services["edit"].get_metadata_from_gcs.return_value = AudioMetadata(
duration_seconds=200.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=30000000,
)
resp = test_client.get("/api/review/edit-job-1/input-audio-info")
assert resp.status_code == 200
# No cache path → should not attempt to load cache
mock_services["analysis"].load_cached_waveform.assert_not_called()
mock_services["analysis"].get_waveform_data.assert_called_once()
# --- POST /audio-edit/apply ---
@@ -0,0 +1,134 @@
"""
Tests for audio processor robustness fixes.
Covers:
- Stage 2 validation catches missing stems
- _normalize_audio_files handles missing clean instrumental path
- _generate_combined_instrumentals handles missing backing vocals path
"""
import pytest
from unittest.mock import MagicMock, patch
from karaoke_gen.audio_processor import AudioProcessor
def _make_processor():
"""Create an AudioProcessor with mocked dependencies."""
processor = AudioProcessor.__new__(AudioProcessor)
processor.logger = MagicMock()
processor.clean_instrumental_model = "model_bs_roformer"
processor.backing_vocals_models = ["mel_band_roformer_karaoke"]
processor.other_stems_models = []
processor.lossless_output_format = "FLAC"
processor.ffmpeg_base_command = "ffmpeg -y"
return processor
class TestNormalizeAudioFilesNullSafety:
"""Tests for _normalize_audio_files defensive checks."""
def test_raises_on_missing_clean_instrumental(self):
processor = _make_processor()
separation_result = {
"clean_instrumental": {}, # missing "instrumental" key
"combined_instrumentals": {},
}
with pytest.raises(ValueError, match="clean instrumental path is missing"):
processor._normalize_audio_files(separation_result, "Artist - Title", "/tmp/output")
def test_raises_on_none_clean_instrumental(self):
processor = _make_processor()
separation_result = {
"clean_instrumental": {"instrumental": None},
"combined_instrumentals": {},
}
with pytest.raises(ValueError, match="clean instrumental path is missing"):
processor._normalize_audio_files(separation_result, "Artist - Title", "/tmp/output")
def test_works_with_valid_path(self, tmp_path):
processor = _make_processor()
# Create a real file so _file_exists returns True
audio_file = tmp_path / "instrumental.flac"
audio_file.write_bytes(b"fake audio data")
separation_result = {
"clean_instrumental": {"instrumental": str(audio_file), "vocals": str(tmp_path / "vocals.flac")},
"combined_instrumentals": {},
"other_stems": {},
"backing_vocals": {},
}
# Mock _normalize_audio to avoid actually running ffmpeg
with patch.object(processor, "_normalize_audio"):
processor._normalize_audio_files(separation_result, "Artist - Title", str(tmp_path))
# Should have logged success (no exception)
assert processor.logger.info.called
def test_normalizes_combined_instrumentals(self, tmp_path):
processor = _make_processor()
instrumental = tmp_path / "instrumental.flac"
instrumental.write_bytes(b"fake instrumental")
combined = tmp_path / "combined.flac"
combined.write_bytes(b"fake combined")
separation_result = {
"clean_instrumental": {"instrumental": str(instrumental), "vocals": str(tmp_path / "v.flac")},
"combined_instrumentals": {"mel_band_roformer_karaoke": str(combined)},
}
with patch.object(processor, "_normalize_audio") as mock_normalize:
processor._normalize_audio_files(separation_result, "Artist - Title", str(tmp_path))
# Both clean instrumental and combined instrumental should be normalized
assert mock_normalize.call_count == 2
normalized_paths = [call.args[0] for call in mock_normalize.call_args_list]
assert str(instrumental) in normalized_paths
assert str(combined) in normalized_paths
class TestGenerateCombinedInstrumentalsNullSafety:
"""Tests for _generate_combined_instrumentals defensive checks."""
def test_skips_model_with_missing_backing_vocals(self, tmp_path):
processor = _make_processor()
instrumental_path = str(tmp_path / "instrumental.flac")
# Model has lead_vocals but not backing_vocals
backing_vocals_result = {
"mel_band_roformer_karaoke": {"lead_vocals": "/tmp/lead.flac"}
# "backing_vocals" key is missing
}
result = processor._generate_combined_instrumentals(
instrumental_path, backing_vocals_result, "Artist - Title", str(tmp_path)
)
assert result == {}
processor.logger.error.assert_called_once()
assert "backing_vocals path is missing" in processor.logger.error.call_args[0][0]
class TestStage2Validation:
"""Tests for stage 2 remote results validation in _process_audio_separation_remote."""
def test_organize_stage2_missing_backing_vocals_stem(self):
"""Test that _organize_stage2_remote_results correctly handles partial results."""
processor = _make_processor()
# Simulate only getting the Vocals file, not the Instrumental file
# This is what happened in the production failure
import tempfile, os
with tempfile.TemporaryDirectory() as tmpdir:
stems_dir = os.path.join(tmpdir, "stems")
os.makedirs(stems_dir)
# Create only the vocals file (missing the instrumental/backing vocals file)
vocals_file = os.path.join(tmpdir, "audio_(Vocals)_mel_band_roformer_karaoke.flac")
with open(vocals_file, "w") as f:
f.write("fake")
result = processor._organize_stage2_remote_results(
[vocals_file], "Artist - Title", stems_dir
)
# Should have the model with only lead_vocals, no backing_vocals
assert "mel_band_roformer_karaoke" in result
assert "lead_vocals" in result["mel_band_roformer_karaoke"]
assert "backing_vocals" not in result["mel_band_roformer_karaoke"]
+192
View File
@@ -0,0 +1,192 @@
"""
Tests for AudioShake API retry logic.
Covers:
- Retry on 5xx server errors
- Retry on 429 rate limit
- Retry on connection errors
- No retry on 4xx client errors (except 429)
- Retry exhaustion raises the original error
"""
import pytest
from unittest.mock import MagicMock, patch, call
import requests
from tenacity import wait_none
from karaoke_gen.lyrics_transcriber.transcribers.audioshake import (
AudioShakeAPI,
AudioShakeConfig,
_is_retryable_error,
)
@pytest.fixture(autouse=True)
def _no_retry_wait():
"""Disable retry wait times in all tests to avoid sleeping."""
# Temporarily replace the wait strategy with no-wait for both retry-decorated methods
methods = [AudioShakeAPI._request_with_retry, AudioShakeAPI._upload_file_with_retry]
original_waits = [m.retry.wait for m in methods]
for m in methods:
m.retry.wait = wait_none()
yield
for m, w in zip(methods, original_waits):
m.retry.wait = w
class TestIsRetryableError:
"""Tests for the _is_retryable_error predicate."""
def test_connection_error_is_retryable(self):
assert _is_retryable_error(requests.exceptions.ConnectionError()) is True
def test_timeout_is_retryable(self):
assert _is_retryable_error(requests.exceptions.Timeout()) is True
def test_502_is_retryable(self):
response = MagicMock()
response.status_code = 502
error = requests.exceptions.HTTPError(response=response)
assert _is_retryable_error(error) is True
def test_503_is_retryable(self):
response = MagicMock()
response.status_code = 503
error = requests.exceptions.HTTPError(response=response)
assert _is_retryable_error(error) is True
def test_429_is_retryable(self):
response = MagicMock()
response.status_code = 429
error = requests.exceptions.HTTPError(response=response)
assert _is_retryable_error(error) is True
def test_400_is_not_retryable(self):
response = MagicMock()
response.status_code = 400
error = requests.exceptions.HTTPError(response=response)
assert _is_retryable_error(error) is False
def test_401_is_not_retryable(self):
response = MagicMock()
response.status_code = 401
error = requests.exceptions.HTTPError(response=response)
assert _is_retryable_error(error) is False
def test_404_is_not_retryable(self):
response = MagicMock()
response.status_code = 404
error = requests.exceptions.HTTPError(response=response)
assert _is_retryable_error(error) is False
def test_value_error_is_not_retryable(self):
assert _is_retryable_error(ValueError("bad")) is False
class TestAudioShakeAPIRetry:
"""Tests for AudioShakeAPI._request_with_retry."""
def _make_api(self):
config = AudioShakeConfig(api_token="test-token")
logger = MagicMock()
return AudioShakeAPI(config, logger)
@patch("karaoke_gen.lyrics_transcriber.transcribers.audioshake.requests.request")
def test_succeeds_on_first_try(self, mock_request):
api = self._make_api()
mock_response = MagicMock()
mock_response.raise_for_status = MagicMock()
mock_request.return_value = mock_response
result = api._request_with_retry("GET", "https://api.example.com/test")
assert result == mock_response
mock_request.assert_called_once()
@patch("karaoke_gen.lyrics_transcriber.transcribers.audioshake.requests.request")
def test_retries_on_502_then_succeeds(self, mock_request):
api = self._make_api()
# First call: 502 error
bad_response = MagicMock()
bad_response.status_code = 502
bad_response.raise_for_status.side_effect = requests.exceptions.HTTPError(response=bad_response)
# Second call: success
good_response = MagicMock()
good_response.raise_for_status = MagicMock()
mock_request.side_effect = [bad_response, good_response]
result = api._request_with_retry("GET", "https://api.example.com/test")
assert result == good_response
assert mock_request.call_count == 2
@patch("karaoke_gen.lyrics_transcriber.transcribers.audioshake.requests.request")
def test_does_not_retry_on_400(self, mock_request):
api = self._make_api()
bad_response = MagicMock()
bad_response.status_code = 400
bad_response.raise_for_status.side_effect = requests.exceptions.HTTPError(response=bad_response)
mock_request.return_value = bad_response
with pytest.raises(requests.exceptions.HTTPError):
api._request_with_retry("GET", "https://api.example.com/test")
# Should NOT retry — only 1 call
mock_request.assert_called_once()
@patch("karaoke_gen.lyrics_transcriber.transcribers.audioshake.requests.request")
def test_retries_on_connection_error(self, mock_request):
api = self._make_api()
good_response = MagicMock()
good_response.raise_for_status = MagicMock()
mock_request.side_effect = [
requests.exceptions.ConnectionError("Connection refused"),
good_response,
]
result = api._request_with_retry("GET", "https://api.example.com/test")
assert result == good_response
assert mock_request.call_count == 2
class TestAudioShakeUploadRetry:
"""Tests for upload_file using retry."""
@patch("karaoke_gen.lyrics_transcriber.transcribers.audioshake.requests.post")
def test_upload_file_retries_on_502(self, mock_post, tmp_path):
config = AudioShakeConfig(api_token="test-token")
logger = MagicMock()
api = AudioShakeAPI(config, logger)
# Create a test file with known content
test_file = tmp_path / "test.flac"
test_file.write_bytes(b"fake audio data")
# First call: 502
bad_response = MagicMock()
bad_response.status_code = 502
bad_response.raise_for_status.side_effect = requests.exceptions.HTTPError(response=bad_response)
# Second call: success
good_response = MagicMock()
good_response.raise_for_status = MagicMock()
good_response.json.return_value = {"id": "asset-123"}
good_response.status_code = 200
good_response.text = '{"id": "asset-123"}'
mock_post.side_effect = [bad_response, good_response]
asset_id = api.upload_file(str(test_file))
assert asset_id == "asset-123"
assert mock_post.call_count == 2
# Verify file was re-opened on each attempt (both calls got file data)
for call_args in mock_post.call_args_list:
files_arg = call_args[1].get("files") or call_args[0][1] if len(call_args[0]) > 1 else call_args[1].get("files")
assert files_arg is not None, "Each retry should pass files"
+150
View File
@@ -0,0 +1,150 @@
"""
Tests for Google OIDC token validation in AuthService.
Cloud Scheduler and Cloud Tasks send OIDC JWTs signed by Google.
The auth service must validate these and grant admin access for
requests from the configured service account.
"""
import pytest
from unittest.mock import patch, MagicMock
from backend.services.auth_service import AuthService, AuthResult, UserType
@pytest.fixture
def auth_service():
"""Create an AuthService instance with mocked Firestore."""
with patch("backend.services.auth_service.FirestoreService"):
service = AuthService()
service._scheduler_service_account = "karaoke-backend@nomadkaraoke.iam.gserviceaccount.com"
return service
# A fake JWT-shaped token (3 dot-separated parts)
FAKE_JWT = "eyJhbGciOiJSUzI1NiJ9.eyJlbWFpbCI6InRlc3RAZXhhbXBsZS5jb20ifQ.signature"
class TestOidcTokenValidation:
"""Tests for _validate_oidc_token."""
def test_non_jwt_returns_none(self, auth_service):
"""Non-JWT tokens (no dots) should return None immediately."""
result = auth_service._validate_oidc_token("simple-token-no-dots")
assert result is None
def test_two_dots_not_three_parts_returns_none(self, auth_service):
"""Tokens with wrong number of dots should return None."""
result = auth_service._validate_oidc_token("only.one.dot-but-not-jwt")
# This has 2 dots = 3 parts, so it will attempt OIDC validation
# but fail signature verification. That's fine — it returns None.
# A token with 1 dot should be skipped entirely.
result_one_dot = auth_service._validate_oidc_token("one.dot")
assert result_one_dot is None
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
def test_valid_oidc_from_allowed_sa(self, mock_verify, auth_service):
"""Valid OIDC token from the configured service account grants admin."""
mock_verify.return_value = {
"email": "karaoke-backend@nomadkaraoke.iam.gserviceaccount.com",
"email_verified": True,
"iss": "https://accounts.google.com",
"aud": "https://api.nomadkaraoke.com/api/internal/process-stale-reviews",
}
result = auth_service._validate_oidc_token(FAKE_JWT)
assert result is not None
assert result.is_valid is True
assert result.is_admin is True
assert result.user_type == UserType.ADMIN
assert result.remaining_uses == -1
assert result.user_email == "karaoke-backend@nomadkaraoke.iam.gserviceaccount.com"
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
def test_oidc_from_wrong_sa_returns_none(self, mock_verify, auth_service):
"""OIDC token from a different service account is rejected."""
mock_verify.return_value = {
"email": "attacker@evil-project.iam.gserviceaccount.com",
"email_verified": True,
"iss": "https://accounts.google.com",
}
result = auth_service._validate_oidc_token(FAKE_JWT)
assert result is None
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
def test_expired_oidc_token_returns_none(self, mock_verify, auth_service):
"""Expired OIDC token raises ValueError and returns None."""
mock_verify.side_effect = ValueError("Token expired")
result = auth_service._validate_oidc_token(FAKE_JWT)
assert result is None
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
def test_invalid_signature_returns_none(self, mock_verify, auth_service):
"""Token with invalid signature raises ValueError and returns None."""
mock_verify.side_effect = ValueError("Could not verify token signature")
result = auth_service._validate_oidc_token(FAKE_JWT)
assert result is None
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
def test_network_error_returns_none(self, mock_verify, auth_service):
"""Network error fetching Google certs returns None gracefully."""
mock_verify.side_effect = Exception("Connection timeout")
result = auth_service._validate_oidc_token(FAKE_JWT)
assert result is None
class TestValidateTokenFullOidc:
"""Tests that OIDC validation is properly integrated into validate_token_full."""
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
def test_oidc_token_grants_admin_via_validate_token_full(self, mock_verify, auth_service):
"""OIDC token flows through validate_token_full and grants admin."""
mock_verify.return_value = {
"email": "karaoke-backend@nomadkaraoke.iam.gserviceaccount.com",
"email_verified": True,
}
# Mock Firestore to not interfere
auth_service.firestore.get_token = MagicMock(return_value=None)
result = auth_service.validate_token_full(FAKE_JWT)
assert result.is_valid is True
assert result.is_admin is True
assert result.user_type == UserType.ADMIN
def test_admin_token_still_works(self, auth_service):
"""Admin tokens from env var still take priority over OIDC."""
auth_service.admin_tokens = ["test-admin-token"]
result = auth_service.validate_token_full("test-admin-token")
assert result.is_valid is True
assert result.is_admin is True
assert result.message == "Admin access granted"
@patch("backend.services.auth_service.google_id_token.verify_oauth2_token")
def test_failed_oidc_falls_through_to_firestore(self, mock_verify, auth_service):
"""If OIDC validation fails, token is still checked against Firestore."""
mock_verify.side_effect = ValueError("Invalid token")
# Firestore has a valid token
auth_service.firestore.get_token = MagicMock(return_value={
"type": "unlimited",
"active": True,
"max_uses": -1,
"user_email": "user@example.com",
})
result = auth_service.validate_token_full(FAKE_JWT)
assert result.is_valid is True
assert result.user_type == UserType.UNLIMITED
+76
View File
@@ -7,6 +7,8 @@ Tests cover:
- Timestamp adjustment for instrumental audio sync
"""
import os
import pytest
from karaoke_gen.lyrics_transcriber.output.cdg import CDGGenerator
@@ -247,3 +249,77 @@ class TestCDGGenerateFromLRCWithCountdown:
# Verify _remove_countdown_from_lyrics was NOT called
mock_remove.assert_not_called()
class TestCDGFontFallback:
"""Test font resolution and fallback behavior in _validate_and_setup_font."""
@pytest.fixture
def generator(self, tmp_path):
return CDGGenerator(output_dir=str(tmp_path))
def test_absolute_path_that_exists_is_unchanged(self, generator, tmp_path):
"""An absolute path to an existing font is used as-is."""
font_file = tmp_path / "myfont.ttf"
font_file.write_bytes(b"fake font")
cdg_styles = {"font_path": str(font_file)}
generator._validate_and_setup_font(cdg_styles)
assert cdg_styles["font_path"] == str(font_file)
def test_nonexistent_path_falls_back_to_bundled_by_filename(self, generator):
"""A path like 'themes/nomad/assets/AvenirNext-Bold.ttf' should resolve
to the bundled AvenirNext-Bold.ttf by filename."""
cdg_styles = {"font_path": "themes/nomad/assets/AvenirNext-Bold.ttf"}
generator._validate_and_setup_font(cdg_styles)
assert cdg_styles["font_path"] is not None
assert cdg_styles["font_path"].endswith("AvenirNext-Bold.ttf")
assert os.path.isfile(cdg_styles["font_path"])
def test_totally_unknown_font_falls_back_to_arial(self, generator):
"""A completely unknown font name falls back to bundled arial.ttf."""
cdg_styles = {"font_path": "nonexistent/path/SuperRareFont.ttf"}
generator._validate_and_setup_font(cdg_styles)
assert cdg_styles["font_path"] is not None
assert cdg_styles["font_path"].endswith("arial.ttf")
assert os.path.isfile(cdg_styles["font_path"])
def test_none_font_path_is_left_alone(self, generator):
"""If font_path is already None, _validate_and_setup_font returns early."""
cdg_styles = {"font_path": None}
generator._validate_and_setup_font(cdg_styles)
assert cdg_styles["font_path"] is None
def test_create_toml_data_raises_on_none_font(self, generator):
"""_create_toml_data raises RuntimeError if font_path is None."""
cdg_styles = {
"font_path": None,
"clear_mode": "eager",
"sync_offset": 0,
"background_color": "#000000",
"border_color": "#000000",
"font_size": 18,
"stroke_width": 0,
"stroke_style": "octagon",
"active_fill": "#ffffff",
"active_stroke": "#000000",
"inactive_fill": "#888888",
"inactive_stroke": "#000000",
"title_color": "#ffffff",
"artist_color": "#ffffff",
"title_screen_background": "/tmp/fake.png",
"title_screen_transition": "centertexttoplogobottomtext",
"row": 4,
"line_tile_height": 3,
"lines_per_page": 4,
}
with pytest.raises(RuntimeError, match="CDG font_path is None"):
generator._create_toml_data(
title="Test",
artist="Artist",
audio_file="/tmp/audio.flac",
output_name="output",
sync_times=[100, 200],
instrumentals=[],
formatted_lyrics=["HELLO", "WORLD"],
cdg_styles=cdg_styles,
)
@@ -319,3 +319,59 @@ class TestRenderVideoWorkerUsesCorrectedData:
# Metadata and original_segments preserved
assert original_data['metadata']['preserved'] is True
assert original_data['original_segments'][0]['id'] == 1
class TestCompleteReviewSkipsEmptyCorrections:
"""Test that complete_review doesn't write corrections_updated.json when no corrections.
Bug scenario: Completing review via admin API without corrections payload writes
an empty {} to corrections_updated.json. Downstream render workers then get
KeyError: 'corrections' when processing it.
"""
def test_no_corrections_key_skips_upload(self):
"""When updated_data has only instrumental_selection, no corrections file is written."""
# Simulate what the endpoint does with the corrections_to_save logic
updated_data = {"instrumental_selection": "clean"}
corrections_to_save = {k: v for k, v in updated_data.items() if k != "instrumental_selection"}
# This is the guard we added
should_write = corrections_to_save and "corrections" in corrections_to_save
assert not should_write, "Should not write corrections_updated.json for empty payload"
def test_with_corrections_key_allows_upload(self):
"""When updated_data has corrections, the file should be written."""
updated_data = {
"corrections": [{"id": 1, "type": "edit"}],
"corrected_segments": [{"id": 1, "text": "fixed"}],
"instrumental_selection": "with_backing",
}
corrections_to_save = {k: v for k, v in updated_data.items() if k != "instrumental_selection"}
should_write = corrections_to_save and "corrections" in corrections_to_save
assert should_write, "Should write corrections_updated.json when corrections present"
def test_empty_dict_payload_skips_upload(self):
"""When updated_data is effectively empty after removing instrumental_selection."""
updated_data = {"instrumental_selection": "clean", "some_other_key": "value"}
corrections_to_save = {k: v for k, v in updated_data.items() if k != "instrumental_selection"}
# Has content but no "corrections" key
should_write = corrections_to_save and "corrections" in corrections_to_save
assert not should_write, "Should not write without corrections key"
def test_render_worker_handles_empty_corrections_gracefully(self):
"""Document that render workers skip empty corrections_updated.json.
Both GCE and Cloud Run workers now check for 'corrections' key
before passing to CorrectionOperations.update_correction_result_with_data().
"""
# Simulates what the workers do on download
empty_updated_data = {}
has_valid_corrections = empty_updated_data and "corrections" in empty_updated_data
assert not has_valid_corrections, "Empty dict should not be treated as valid corrections"
# Dict with irrelevant keys
bad_updated_data = {"some_key": "value"}
has_valid_corrections = bad_updated_data and "corrections" in bad_updated_data
assert not has_valid_corrections, "Dict without corrections key should not be valid"
+3 -3
View File
@@ -405,10 +405,10 @@ class TestCreditRefundOnJobDeletion:
class TestWelcomeCredits:
"""Test new user welcome credits."""
def test_new_user_gets_2_welcome_credits(self):
"""Verify NEW_USER_FREE_CREDITS is set to 2."""
def test_new_user_gets_1_welcome_credit(self):
"""Verify NEW_USER_FREE_CREDITS is set to 1."""
from backend.services.user_service import UserService
assert UserService.NEW_USER_FREE_CREDITS == 2
assert UserService.NEW_USER_FREE_CREDITS == 1
class TestInsufficientCreditsError:
+346
View File
@@ -0,0 +1,346 @@
"""
Tests for AI-powered credit evaluation service.
"""
import pytest
from unittest.mock import MagicMock, patch, PropertyMock
import sys
sys.modules.setdefault('google.cloud.firestore', MagicMock())
sys.modules.setdefault('google.cloud.firestore_v1', MagicMock())
from backend.models.user import User
# =============================================================================
# Prompt Building Tests
# =============================================================================
class TestBuildUserPrompt:
def test_builds_prompt_with_all_signals(self):
from backend.services.credit_evaluation_service import _build_user_prompt
prompt = _build_user_prompt(
email="test@example.com",
grant_type="welcome",
user_data={
"device_fingerprint": "fp123",
"signup_ip": "1.2.3.4",
"credits": 0,
"total_jobs_created": 0,
"total_jobs_completed": 0,
"total_spent": 0,
"created_at": "2026-03-23",
},
fingerprint_matches=[
{"email": "other@test.com", "total_jobs_created": 5, "total_spent": 0, "created_at": "2026-03-20"},
],
ip_matches=[],
ip_geo={"status": "success", "country": "US", "country_code": "US", "city": "Portland", "region": "OR", "isp": "Comcast", "org": "Comcast", "as_number": "AS7922", "as_name": "Comcast"},
recent_signups_ip=1,
recent_signups_fp=2,
user_agent="Mozilla/5.0",
)
assert "test@example.com" in prompt
assert "fp123" in prompt
assert "1.2.3.4" in prompt
assert "other@test.com" in prompt
assert "RED FLAG" in prompt
assert "Portland" in prompt
assert "Comcast" in prompt
assert "Mozilla/5.0" in prompt
def test_builds_prompt_without_correlations(self):
from backend.services.credit_evaluation_service import _build_user_prompt
prompt = _build_user_prompt(
email="clean@user.com",
grant_type="welcome",
user_data={"device_fingerprint": "fp999", "signup_ip": "5.6.7.8"},
fingerprint_matches=[],
ip_matches=[],
ip_geo=None,
recent_signups_ip=1,
recent_signups_fp=1,
user_agent=None,
)
assert "None found" in prompt
assert "clean@user.com" in prompt
def test_includes_feedback_content(self):
from backend.services.credit_evaluation_service import _build_user_prompt
prompt = _build_user_prompt(
email="test@example.com",
grant_type="feedback",
user_data={},
fingerprint_matches=[],
ip_matches=[],
ip_geo=None,
recent_signups_ip=0,
recent_signups_fp=0,
user_agent=None,
feedback_content={
"overall_rating": 5,
"what_went_well": "Great audio quality!",
"what_could_improve": "Faster processing",
"additional_comments": "Love it",
},
)
assert "Feedback Submitted" in prompt
assert "Great audio quality!" in prompt
assert "5" in prompt
# =============================================================================
# Response Parsing Tests
# =============================================================================
class TestParseGeminiResponse:
def test_parses_grant_decision(self):
from backend.services.credit_evaluation_service import _parse_gemini_response
result = _parse_gemini_response('{"decision": "grant", "reasoning": "Clean user", "confidence": 0.95}')
assert result.decision == "grant"
assert result.reasoning == "Clean user"
assert result.confidence == 0.95
assert result.error is None
def test_parses_deny_decision(self):
from backend.services.credit_evaluation_service import _parse_gemini_response
result = _parse_gemini_response('{"decision": "deny", "reasoning": "Same fingerprint as 3 other accounts", "confidence": 0.9}')
assert result.decision == "deny"
assert "fingerprint" in result.reasoning
def test_handles_markdown_code_fences(self):
from backend.services.credit_evaluation_service import _parse_gemini_response
result = _parse_gemini_response('```json\n{"decision": "grant", "reasoning": "OK", "confidence": 0.8}\n```')
assert result.decision == "grant"
def test_fails_closed_on_invalid_json(self):
from backend.services.credit_evaluation_service import _parse_gemini_response
result = _parse_gemini_response("I think this user is fine")
assert result.decision == "pending_review"
assert result.error is not None
def test_fails_closed_on_unexpected_decision(self):
from backend.services.credit_evaluation_service import _parse_gemini_response
result = _parse_gemini_response('{"decision": "maybe", "reasoning": "Unsure", "confidence": 0.5}')
assert result.decision == "pending_review" # fail-closed
def test_fails_closed_on_empty_response(self):
from backend.services.credit_evaluation_service import _parse_gemini_response
result = _parse_gemini_response("")
assert result.decision == "pending_review"
assert result.error is not None
# =============================================================================
# Evaluation Service Tests
# =============================================================================
class TestCreditEvaluationService:
@patch('backend.services.credit_evaluation_service.get_settings')
def test_returns_grant_when_disabled(self, mock_settings):
mock_settings.return_value = MagicMock(credit_eval_enabled=False)
from backend.services.credit_evaluation_service import CreditEvaluationService
service = CreditEvaluationService()
result = service.evaluate("test@example.com", "welcome")
assert result.decision == "grant"
assert "disabled" in result.reasoning
@patch('backend.services.credit_evaluation_service.get_settings')
def test_quick_grants_clean_users(self, mock_settings):
mock_settings.return_value = MagicMock(
credit_eval_enabled=True,
credit_eval_model="gemini-3.1-pro-preview",
google_cloud_project="test",
)
from backend.services.credit_evaluation_service import CreditEvaluationService
service = CreditEvaluationService()
with patch.object(service, '_collect_signals', return_value={
"user_data": {"email": "clean@user.com"},
"fingerprint_matches": [],
"ip_matches": [],
"ip_geo": None,
"recent_signups_ip": 1,
"recent_signups_fp": 1,
"user_agent": "Mozilla/5.0",
}), patch.object(service, '_log_evaluation'):
result = service.evaluate("clean@user.com", "welcome")
assert result.decision == "grant"
assert "clean" in result.reasoning.lower()
@patch('backend.services.credit_evaluation_service.get_settings')
def test_calls_gemini_when_correlations_found(self, mock_settings):
mock_settings.return_value = MagicMock(
credit_eval_enabled=True,
credit_eval_model="gemini-3.1-pro-preview",
google_cloud_project="test",
)
from backend.services.credit_evaluation_service import CreditEvaluationService
service = CreditEvaluationService()
with patch.object(service, '_collect_signals', return_value={
"user_data": {"email": "sus@user.com", "device_fingerprint": "fp123", "signup_ip": "1.2.3.4"},
"fingerprint_matches": [{"email": "other@test.com", "total_jobs_created": 5, "total_spent": 0, "created_at": "2026-03-20"}],
"ip_matches": [],
"ip_geo": None,
"recent_signups_ip": 1,
"recent_signups_fp": 2,
"user_agent": None,
}), patch.object(service, '_call_gemini', return_value='{"decision": "deny", "reasoning": "Same fingerprint", "confidence": 0.9}'), \
patch.object(service, '_log_evaluation'):
result = service.evaluate("sus@user.com", "welcome")
assert result.decision == "deny"
@patch('backend.services.credit_evaluation_service.get_settings')
def test_fails_closed_on_gemini_error(self, mock_settings):
mock_settings.return_value = MagicMock(
credit_eval_enabled=True,
credit_eval_model="gemini-3.1-pro-preview",
google_cloud_project="test",
)
from backend.services.credit_evaluation_service import CreditEvaluationService
service = CreditEvaluationService()
with patch.object(service, '_collect_signals', side_effect=Exception("Firestore down")), \
patch.object(service, '_log_evaluation'):
result = service.evaluate("test@example.com", "welcome")
assert result.decision == "pending_review"
assert result.error is not None
# =============================================================================
# Welcome Credit Integration Tests
# =============================================================================
class TestWelcomeCreditsWithEvaluation:
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_grants_credits_when_evaluation_approves(self, mock_fs, mock_settings):
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
user = User(email="new@user.com", welcome_credits_granted=False)
user_doc = MagicMock()
user_doc.exists = True
user_doc.to_dict.return_value = user.model_dump(mode='json')
mock_db.collection.return_value.document.return_value.get.return_value = user_doc
from backend.services.user_service import UserService
from backend.services.credit_evaluation_service import CreditEvaluation
service = UserService()
with patch('backend.services.credit_evaluation_service.get_credit_evaluation_service') as mock_eval:
mock_eval.return_value.evaluate.return_value = CreditEvaluation(
decision="grant", reasoning="Clean user", confidence=0.95
)
granted, status = service.grant_welcome_credits_if_eligible("new@user.com")
assert granted is True
assert status == "granted"
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_denies_credits_when_evaluation_rejects(self, mock_fs, mock_settings):
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
user = User(email="abuser@test.com", welcome_credits_granted=False)
user_doc = MagicMock()
user_doc.exists = True
user_doc.to_dict.return_value = user.model_dump(mode='json')
mock_db.collection.return_value.document.return_value.get.return_value = user_doc
from backend.services.user_service import UserService
from backend.services.credit_evaluation_service import CreditEvaluation
service = UserService()
with patch('backend.services.credit_evaluation_service.get_credit_evaluation_service') as mock_eval, \
patch('backend.services.email_service.get_email_service') as mock_email:
mock_eval.return_value.evaluate.return_value = CreditEvaluation(
decision="deny", reasoning="Same fingerprint as 3 accounts", confidence=0.9
)
granted, status = service.grant_welcome_credits_if_eligible("abuser@test.com")
assert granted is False
assert status == "denied"
# Verify rejection email was sent
mock_email.return_value.send_credit_denied_email.assert_called_once_with("abuser@test.com", "welcome")
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_pending_review_when_evaluation_fails(self, mock_fs, mock_settings):
"""Fail-closed: if evaluation crashes, credits are NOT granted, admin notified."""
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
user = User(email="new@user.com", welcome_credits_granted=False)
user_doc = MagicMock()
user_doc.exists = True
user_doc.to_dict.return_value = user.model_dump(mode='json')
mock_db.collection.return_value.document.return_value.get.return_value = user_doc
from backend.services.user_service import UserService
service = UserService()
with patch('backend.services.credit_evaluation_service.get_credit_evaluation_service') as mock_eval, \
patch('backend.services.email_service.get_email_service') as mock_email:
mock_eval.return_value.evaluate.side_effect = Exception("Gemini is down")
granted, status = service.grant_welcome_credits_if_eligible("new@user.com")
assert granted is False
assert status == "pending_review"
# Verify admin review email was sent
mock_email.return_value.send_credit_review_needed_email.assert_called_once()
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_skips_already_granted(self, mock_fs, mock_settings):
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
user = User(email="existing@user.com", welcome_credits_granted=True)
user_doc = MagicMock()
user_doc.exists = True
user_doc.to_dict.return_value = user.model_dump(mode='json')
mock_db.collection.return_value.document.return_value.get.return_value = user_doc
from backend.services.user_service import UserService
service = UserService()
granted, status = service.grant_welcome_credits_if_eligible("existing@user.com")
assert granted is False
assert status == "already_granted"
@@ -0,0 +1,173 @@
import pytest
from unittest.mock import MagicMock
import sys
sys.modules['google.cloud.firestore'] = MagicMock()
sys.modules['google.cloud.storage'] = MagicMock()
class TestParseExternalBlocklist:
def test_parse_newline_delimited_domains(self):
from backend.services.disposable_domain_sync_service import parse_blocklist_text
text = "tempmail.com\nmailinator.com\n\nguerrillamail.com\n"
result = parse_blocklist_text(text)
assert result == {"tempmail.com", "mailinator.com", "guerrillamail.com"}
def test_parse_strips_whitespace(self):
from backend.services.disposable_domain_sync_service import parse_blocklist_text
text = " tempmail.com \n mailinator.com\t\n"
result = parse_blocklist_text(text)
assert result == {"tempmail.com", "mailinator.com"}
def test_parse_lowercases_domains(self):
from backend.services.disposable_domain_sync_service import parse_blocklist_text
text = "TempMail.COM\nMailinator.com\n"
result = parse_blocklist_text(text)
assert result == {"tempmail.com", "mailinator.com"}
def test_parse_empty_text(self):
from backend.services.disposable_domain_sync_service import parse_blocklist_text
assert parse_blocklist_text("") == set()
assert parse_blocklist_text(" \n\n ") == set()
class TestFetchExternalBlocklist:
@pytest.mark.asyncio
async def test_fetch_success(self):
from backend.services.disposable_domain_sync_service import fetch_external_blocklist
from unittest.mock import AsyncMock, patch
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.text = "tempmail.com\nmailinator.com\n"
mock_response.headers = {"content-length": "30"}
with patch("backend.services.disposable_domain_sync_service.httpx.AsyncClient") as mock_client_cls:
mock_client = AsyncMock()
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
mock_client.__aexit__ = AsyncMock(return_value=False)
mock_client.get = AsyncMock(return_value=mock_response)
mock_client_cls.return_value = mock_client
domains = await fetch_external_blocklist()
assert domains == {"tempmail.com", "mailinator.com"}
@pytest.mark.asyncio
async def test_fetch_rejects_too_many_domains(self):
from backend.services.disposable_domain_sync_service import fetch_external_blocklist
from unittest.mock import AsyncMock, patch
fake_text = "\n".join(f"domain{i}.com" for i in range(50_001))
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.text = fake_text
mock_response.headers = {"content-length": str(len(fake_text))}
with patch("backend.services.disposable_domain_sync_service.httpx.AsyncClient") as mock_client_cls:
mock_client = AsyncMock()
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
mock_client.__aexit__ = AsyncMock(return_value=False)
mock_client.get = AsyncMock(return_value=mock_response)
mock_client_cls.return_value = mock_client
with pytest.raises(ValueError, match="exceeds maximum"):
await fetch_external_blocklist()
@pytest.mark.asyncio
async def test_fetch_rejects_non_200(self):
from backend.services.disposable_domain_sync_service import fetch_external_blocklist
from unittest.mock import AsyncMock, patch
mock_response = MagicMock()
mock_response.status_code = 500
mock_response.raise_for_status = MagicMock(side_effect=Exception("Server Error"))
with patch("backend.services.disposable_domain_sync_service.httpx.AsyncClient") as mock_client_cls:
mock_client = AsyncMock()
mock_client.__aenter__ = AsyncMock(return_value=mock_client)
mock_client.__aexit__ = AsyncMock(return_value=False)
mock_client.get = AsyncMock(return_value=mock_response)
mock_client_cls.return_value = mock_client
with pytest.raises(Exception):
await fetch_external_blocklist()
class TestSyncDisposableDomains:
@pytest.fixture
def mock_db(self):
mock = MagicMock()
return mock
def test_sync_first_run_migration(self, mock_db):
"""First sync: migrate old disposable_domains to manual_domains."""
from unittest.mock import patch
from backend.services.disposable_domain_sync_service import sync_disposable_domains
mock_doc = MagicMock()
mock_doc.exists = True
mock_doc.to_dict.return_value = {
"disposable_domains": ["tempmail.com", "custom-temp.com"],
"blocked_emails": [],
"blocked_ips": [],
}
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
external_domains = {"tempmail.com", "mailinator.com"}
with patch("backend.services.disposable_domain_sync_service.DEFAULT_DISPOSABLE_DOMAINS", set()):
result = sync_disposable_domains(mock_db, external_domains)
assert result["migrated_to_manual"] == ["custom-temp.com"]
assert result["external_count"] == 2
mock_db.collection.return_value.document.return_value.set.assert_called_once()
call_data = mock_db.collection.return_value.document.return_value.set.call_args[0][0]
assert set(call_data["external_domains"]) == {"tempmail.com", "mailinator.com"}
assert set(call_data["manual_domains"]) == {"custom-temp.com"}
assert "disposable_domains" not in call_data
def test_sync_subsequent_run(self, mock_db):
"""Subsequent sync: just replace external_domains."""
from backend.services.disposable_domain_sync_service import sync_disposable_domains
mock_doc = MagicMock()
mock_doc.exists = True
mock_doc.to_dict.return_value = {
"external_domains": ["tempmail.com"],
"manual_domains": ["my-custom.com"],
"allowlisted_domains": [],
"blocked_emails": [],
"blocked_ips": [],
}
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
external_domains = {"tempmail.com", "mailinator.com", "newdomain.com"}
result = sync_disposable_domains(mock_db, external_domains)
assert result["external_count"] == 3
assert result["added"] == 2
assert result["removed"] == 0
def test_sync_cleans_redundant_manual_domains(self, mock_db):
"""Sync removes manual domains that now appear in external list."""
from backend.services.disposable_domain_sync_service import sync_disposable_domains
mock_doc = MagicMock()
mock_doc.exists = True
mock_doc.to_dict.return_value = {
"external_domains": ["tempmail.com"],
"manual_domains": ["mailinator.com", "my-custom.com"],
"allowlisted_domains": [],
"blocked_emails": [],
"blocked_ips": [],
}
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
external_domains = {"tempmail.com", "mailinator.com"}
result = sync_disposable_domains(mock_db, external_domains)
call_data = mock_db.collection.return_value.document.return_value.set.call_args[0][0]
assert set(call_data["manual_domains"]) == {"my-custom.com"}
@@ -869,3 +869,47 @@ class TestVideoWorkerDistribution:
# Should log warning about import error
mock_job_log.warning.assert_called()
@pytest.mark.asyncio
async def test_handle_native_distribution_with_warnings_does_not_crash(self):
"""Test that distribution_warnings path doesn't raise NameError.
Regression test: _handle_native_distribution used to reference
undefined 'settings' variable when distribution_warnings were present.
"""
from backend.workers.video_worker import _handle_native_distribution
mock_job = MagicMock()
mock_job.dropbox_path = None
mock_job.gdrive_folder_id = None
mock_job.is_private = False
mock_job.artist = "Test Artist"
mock_job.title = "Test Song"
mock_job.state_data = {}
mock_job_log = MagicMock()
mock_job_manager = MagicMock()
# Result with distribution_warnings triggers the notification path
result_with_warnings = {
'distribution_warnings': ['Dropbox upload failed: timeout'],
}
# Should NOT raise NameError for undefined 'settings'
with patch('backend.workers.video_worker._send_distribution_warning_notification') as mock_notify:
await _handle_native_distribution(
job_id="test-warnings",
job=mock_job,
job_log=mock_job_log,
job_manager=mock_job_manager,
temp_dir="/tmp/test",
result=result_with_warnings,
)
# Verify notification was called (proving the code path was exercised)
mock_notify.assert_called_once_with(
job_id="test-warnings",
artist="Test Artist",
title="Test Song",
warnings=['Dropbox upload failed: timeout'],
)
+156
View File
@@ -0,0 +1,156 @@
"""
Unit tests for EmailService review reminder and expiry email methods.
"""
import pytest
from unittest.mock import Mock, MagicMock, patch
# Mock Google Cloud before imports
import sys
sys.modules.setdefault('google.cloud.firestore', MagicMock())
sys.modules.setdefault('google.cloud.storage', MagicMock())
class TestSendReviewReminder:
"""Test send_review_reminder() email method."""
def _make_service(self):
"""Create an EmailService with a mock provider."""
with patch('backend.services.email_service.get_settings'):
from backend.services.email_service import EmailService
service = EmailService.__new__(EmailService)
service.provider = Mock()
service.provider.send_email.return_value = True
service.frontend_url = "https://gen.nomadkaraoke.com"
service.buy_url = "https://gen.nomadkaraoke.com"
service.settings = Mock()
return service
def test_subject_with_artist_and_title(self):
"""Subject should include artist and title."""
service = self._make_service()
service.send_review_reminder(
to_email="user@test.com",
artist="Adele",
title="Hello",
job_id="abc123",
)
call_args = service.provider.send_email.call_args
assert "Adele - Hello" in call_args.kwargs["subject"]
assert "Reminder" in call_args.kwargs["subject"]
def test_subject_without_artist_and_title(self):
"""Subject should work without artist/title."""
service = self._make_service()
service.send_review_reminder(
to_email="user@test.com",
job_id="abc123",
)
call_args = service.provider.send_email.call_args
assert "Reminder: Your karaoke video is waiting for review" == call_args.kwargs["subject"]
def test_content_includes_review_link(self):
"""HTML content should include the review URL."""
service = self._make_service()
service.send_review_reminder(
to_email="user@test.com",
artist="Adele",
title="Hello",
job_id="abc123",
)
call_args = service.provider.send_email.call_args
assert "gen.nomadkaraoke.com/app/jobs#/abc123/review" in call_args.kwargs["html_content"]
assert "gen.nomadkaraoke.com/app/jobs#/abc123/review" in call_args.kwargs["text_content"]
def test_content_includes_expiry_warning(self):
"""Content should warn about 24h expiry."""
service = self._make_service()
service.send_review_reminder(
to_email="user@test.com",
job_id="abc123",
)
call_args = service.provider.send_email.call_args
assert "24 hours" in call_args.kwargs["html_content"]
assert "expire" in call_args.kwargs["html_content"]
def test_content_includes_help_offer(self):
"""Content should offer help via reply."""
service = self._make_service()
service.send_review_reminder(
to_email="user@test.com",
job_id="abc123",
)
call_args = service.provider.send_email.call_args
assert "reply to this email" in call_args.kwargs["html_content"]
class TestSendReviewExpired:
"""Test send_review_expired() email method."""
def _make_service(self):
"""Create an EmailService with a mock provider."""
with patch('backend.services.email_service.get_settings'):
from backend.services.email_service import EmailService
service = EmailService.__new__(EmailService)
service.provider = Mock()
service.provider.send_email.return_value = True
service.frontend_url = "https://gen.nomadkaraoke.com"
service.buy_url = "https://gen.nomadkaraoke.com"
service.settings = Mock()
return service
def test_subject_with_artist_and_title(self):
"""Subject should include artist and title."""
service = self._make_service()
service.send_review_expired(
to_email="user@test.com",
artist="Adele",
title="Hello",
credits_balance=2,
)
call_args = service.provider.send_email.call_args
assert "Adele - Hello" in call_args.kwargs["subject"]
assert "expired" in call_args.kwargs["subject"]
def test_subject_without_artist_and_title(self):
"""Subject should work without artist/title."""
service = self._make_service()
service.send_review_expired(
to_email="user@test.com",
credits_balance=1,
)
call_args = service.provider.send_email.call_args
assert "Your karaoke video has expired" == call_args.kwargs["subject"]
def test_content_includes_refund_message(self):
"""Content should confirm credit refund."""
service = self._make_service()
service.send_review_expired(
to_email="user@test.com",
credits_balance=3,
)
call_args = service.provider.send_email.call_args
assert "refunded" in call_args.kwargs["html_content"]
assert "3 credits" in call_args.kwargs["html_content"]
def test_content_shows_singular_credit(self):
"""Should show 'credit' (singular) for balance of 1."""
service = self._make_service()
service.send_review_expired(
to_email="user@test.com",
credits_balance=1,
)
call_args = service.provider.send_email.call_args
assert "1 credit" in call_args.kwargs["html_content"]
# Should NOT say "1 credits"
assert "1 credits" not in call_args.kwargs["html_content"]
def test_content_includes_create_link(self):
"""Content should include a link to create a new video."""
service = self._make_service()
service.send_review_expired(
to_email="user@test.com",
credits_balance=2,
)
call_args = service.provider.send_email.call_args
assert "gen.nomadkaraoke.com/app" in call_args.kwargs["html_content"]
@@ -0,0 +1,107 @@
"""
Tests for disposable email blocking in the magic link signup flow.
Verifies that EmailValidationService is correctly wired into the
POST /api/users/auth/magic-link endpoint.
"""
import pytest
from unittest.mock import MagicMock, patch
from fastapi.testclient import TestClient
@pytest.fixture
def mock_validation_svc():
"""Create a mock EmailValidationService."""
svc = MagicMock()
svc.is_disposable_domain.return_value = False
svc.is_email_blocked.return_value = False
svc.is_ip_blocked.return_value = False
return svc
@pytest.fixture
def client(mock_validation_svc):
"""Create TestClient with mocked email validation service."""
from backend.main import app
with patch(
"backend.api.routes.users.get_email_validation_service",
return_value=mock_validation_svc,
):
yield TestClient(app)
class TestDisposableEmailBlocking:
"""Tests for disposable email rejection in magic link flow."""
def test_disposable_email_returns_422(self, client, mock_validation_svc):
"""Disposable email domains should be rejected with 422."""
mock_validation_svc.is_disposable_domain.return_value = True
response = client.post(
"/api/users/auth/magic-link",
json={"email": "test@yopmail.com"},
)
assert response.status_code == 422
assert response.json()["detail"] == "disposable_email_not_allowed"
def test_disposable_email_does_not_send_email(self, client, mock_validation_svc):
"""Disposable email should be rejected before any email is sent."""
mock_validation_svc.is_disposable_domain.return_value = True
response = client.post(
"/api/users/auth/magic-link",
json={"email": "abuse@tempmail.com"},
)
assert response.status_code == 422
# Validation should have been called with lowercased email
mock_validation_svc.is_disposable_domain.assert_called_with("abuse@tempmail.com")
def test_blocked_email_silent_reject(self, client, mock_validation_svc):
"""Blocked email should return generic success (anti-enumeration)."""
mock_validation_svc.is_email_blocked.return_value = True
response = client.post(
"/api/users/auth/magic-link",
json={"email": "blocked@example.com"},
)
assert response.status_code == 200
assert response.json()["status"] == "success"
def test_blocked_ip_silent_reject(self, client, mock_validation_svc):
"""Blocked IP should return generic success (anti-enumeration)."""
mock_validation_svc.is_ip_blocked.return_value = True
response = client.post(
"/api/users/auth/magic-link",
json={"email": "innocent@gmail.com"},
)
assert response.status_code == 200
assert response.json()["status"] == "success"
def test_email_is_lowercased_before_check(self, client, mock_validation_svc):
"""Email should be lowercased before disposable domain check."""
mock_validation_svc.is_disposable_domain.return_value = True
client.post(
"/api/users/auth/magic-link",
json={"email": "Test@YOPMAIL.COM"},
)
mock_validation_svc.is_disposable_domain.assert_called_with("test@yopmail.com")
class TestDisposableDomainList:
"""Verify DEFAULT_DISPOSABLE_DOMAINS is now empty (replaced by external sync)."""
def test_defaults_empty_after_migration(self):
from backend.services.email_validation_service import DEFAULT_DISPOSABLE_DOMAINS
assert len(DEFAULT_DISPOSABLE_DOMAINS) == 0
def test_gmail_not_in_defaults(self):
from backend.services.email_validation_service import DEFAULT_DISPOSABLE_DOMAINS
assert "gmail.com" not in DEFAULT_DISPOSABLE_DOMAINS
+674 -11
View File
@@ -1,12 +1,16 @@
"""
Unit tests for EmailValidationService.
Tests email normalization, disposable domain detection, and blocklist management.
Tests email normalization, disposable domain detection, blocklist management,
and external API-based disposable domain checking (DeBounce + verifymail.io).
"""
import pytest
from datetime import datetime, timedelta, timezone
from unittest.mock import Mock, MagicMock, patch
import httpx
# Mock Google Cloud before imports
import sys
sys.modules['google.cloud.firestore'] = MagicMock()
@@ -107,14 +111,22 @@ class TestEmailNormalization:
class TestDisposableDomainDetection:
"""Test disposable domain detection."""
"""Test disposable domain detection (static blocklist only — external APIs mocked)."""
@pytest.fixture
def mock_db(self):
"""Create a mock Firestore client."""
"""Create a mock Firestore client with new data model."""
mock = MagicMock()
mock_doc = Mock()
mock_doc.exists = False
mock_doc.exists = True
mock_doc.to_dict.return_value = {
"external_domains": ["tempmail.com", "mailinator.com", "guerrillamail.com"],
"manual_domains": [],
"allowlisted_domains": [],
"blocked_emails": [],
"blocked_ips": [],
"verified_clean_domains": {},
}
mock.collection.return_value.document.return_value.get.return_value = mock_doc
return mock
@@ -128,9 +140,26 @@ class TestDisposableDomainDetection:
service = EmailValidationService(db=mock_db)
return service
@pytest.fixture(autouse=True)
def mock_external_apis(self):
"""Mock external API calls — these tests focus on static blocklist logic."""
with patch(
"backend.services.email_validation_service._get_http_client"
) as mock_client, patch(
"backend.services.email_validation_service.settings"
) as mock_settings:
# DeBounce returns clean for everything
mock_response = Mock()
mock_response.status_code = 200
mock_response.json.return_value = {"disposable": "false"}
mock_response.raise_for_status = Mock()
mock_client.return_value.get.return_value = mock_response
# No verifymail API key configured
mock_settings.get_secret.return_value = None
yield mock_client
def test_detect_known_disposable_domain(self, email_service):
"""Test known disposable domains are detected."""
# These are in DEFAULT_DISPOSABLE_DOMAINS
assert email_service.is_disposable_domain("user@tempmail.com") is True
assert email_service.is_disposable_domain("user@mailinator.com") is True
assert email_service.is_disposable_domain("user@guerrillamail.com") is True
@@ -165,6 +194,7 @@ class TestBlocklistManagement:
"disposable_domains": ["custom-temp.com"],
"blocked_emails": ["spammer@example.com"],
"blocked_ips": ["192.168.1.100"],
"verified_clean_domains": {},
}
mock.collection.return_value.document.return_value.get.return_value = mock_doc
return mock
@@ -179,6 +209,22 @@ class TestBlocklistManagement:
service = EmailValidationService(db=mock_db)
return service
@pytest.fixture(autouse=True)
def mock_external_apis(self):
"""Mock external API calls."""
with patch(
"backend.services.email_validation_service._get_http_client"
) as mock_client, patch(
"backend.services.email_validation_service.settings"
) as mock_settings:
mock_response = Mock()
mock_response.status_code = 200
mock_response.json.return_value = {"disposable": "false"}
mock_response.raise_for_status = Mock()
mock_client.return_value.get.return_value = mock_response
mock_settings.get_secret.return_value = None
yield
def test_is_email_blocked(self, email_service):
"""Test blocked email detection."""
assert email_service.is_email_blocked("spammer@example.com") is True
@@ -199,16 +245,226 @@ class TestBlocklistManagement:
assert email_service.is_disposable_domain("user@custom-temp.com") is True
def test_blocklist_caching(self, email_service, mock_db):
"""Test blocklist is cached."""
# First call
email_service.is_disposable_domain("user@test.com")
# Second call should use cache
email_service.is_disposable_domain("user@test2.com")
"""Test blocklist config is cached between calls."""
# Use well-known providers to avoid external API calls and Firestore writes
email_service.is_disposable_domain("user@gmail.com")
email_service.is_disposable_domain("user@yahoo.com")
# Should only call Firestore once due to caching
# Should only call Firestore once for the blocklist config (both hit WELL_KNOWN_PROVIDERS first,
# but the first call loads the config, and the second call uses the cache)
# Actually, well-known providers short-circuit before get_blocklist_config(), so use
# a disposable domain instead to exercise the config loading path.
from backend.services.email_validation_service import EmailValidationService
EmailValidationService._blocklist_cache = None
EmailValidationService._blocklist_cache_time = None
mock_db.collection.return_value.document.return_value.get.reset_mock()
email_service.is_disposable_domain("user@custom-temp.com") # hits static list
email_service.is_disposable_domain("user@custom-temp.com") # should use cache
# Only 1 Firestore read for blocklist config (cached on second call)
assert mock_db.collection.return_value.document.return_value.get.call_count == 1
class TestEffectiveBlocklist:
"""Test effective blocklist computation with new data model."""
@pytest.fixture
def mock_db(self):
mock = MagicMock()
mock_doc = Mock()
mock_doc.exists = True
mock_doc.to_dict.return_value = {
"external_domains": ["tempmail.com", "mailinator.com", "allowed-one.com"],
"manual_domains": ["my-custom.com"],
"allowlisted_domains": ["allowed-one.com"],
"blocked_emails": ["bad@example.com"],
"blocked_ips": ["1.2.3.4"],
"verified_clean_domains": {},
}
mock.collection.return_value.document.return_value.get.return_value = mock_doc
return mock
@pytest.fixture
def email_service(self, mock_db):
from backend.services.email_validation_service import EmailValidationService
EmailValidationService._blocklist_cache = None
EmailValidationService._blocklist_cache_time = None
return EmailValidationService(db=mock_db)
@pytest.fixture(autouse=True)
def mock_external_apis(self):
"""Mock external API calls."""
with patch(
"backend.services.email_validation_service._get_http_client"
) as mock_client, patch(
"backend.services.email_validation_service.settings"
) as mock_settings:
mock_response = Mock()
mock_response.status_code = 200
mock_response.json.return_value = {"disposable": "false"}
mock_response.raise_for_status = Mock()
mock_client.return_value.get.return_value = mock_response
mock_settings.get_secret.return_value = None
yield
def test_effective_set_excludes_allowlisted(self, email_service):
config = email_service.get_blocklist_config()
assert "tempmail.com" in config["disposable_domains"]
assert "mailinator.com" in config["disposable_domains"]
assert "my-custom.com" in config["disposable_domains"]
assert "allowed-one.com" not in config["disposable_domains"]
def test_allowlisted_domain_not_blocked(self, email_service):
assert email_service.is_disposable_domain("user@allowed-one.com") is False
def test_external_domain_blocked(self, email_service):
assert email_service.is_disposable_domain("user@tempmail.com") is True
def test_manual_domain_blocked(self, email_service):
assert email_service.is_disposable_domain("user@my-custom.com") is True
class TestNewDataModelCRUD:
"""Test CRUD operations with the new data model."""
@pytest.fixture
def mock_db(self):
mock = MagicMock()
mock_doc = Mock()
mock_doc.exists = True
mock_doc.to_dict.return_value = {
"external_domains": ["tempmail.com", "mailinator.com"],
"manual_domains": ["my-custom.com"],
"allowlisted_domains": [],
"blocked_emails": [],
"blocked_ips": [],
}
mock.collection.return_value.document.return_value.get.return_value = mock_doc
return mock
@pytest.fixture
def email_service(self, mock_db):
from backend.services.email_validation_service import EmailValidationService
EmailValidationService._blocklist_cache = None
EmailValidationService._blocklist_cache_time = None
return EmailValidationService(db=mock_db)
def test_add_disposable_domain_writes_to_manual(self, email_service, mock_db):
"""Test add_disposable_domain writes to manual_domains field."""
email_service.add_disposable_domain("new-spam.com", "admin@test.com")
# Get the transaction set call args
transaction = mock_db.transaction.return_value
set_call = transaction.set
assert set_call.called
data = set_call.call_args[0][1]
assert "new-spam.com" in data["manual_domains"]
assert "my-custom.com" in data["manual_domains"]
def test_remove_disposable_domain_manual(self, email_service, mock_db):
"""Test removing a manual domain removes from manual_domains."""
email_service.remove_disposable_domain("my-custom.com", "admin@test.com")
transaction = mock_db.transaction.return_value
set_call = transaction.set
assert set_call.called
data = set_call.call_args[0][1]
assert "my-custom.com" not in data["manual_domains"]
def test_remove_disposable_domain_external_adds_to_allowlist(self, email_service, mock_db):
"""Test removing an external domain adds it to allowlisted_domains."""
email_service.remove_disposable_domain("tempmail.com", "admin@test.com")
transaction = mock_db.transaction.return_value
set_call = transaction.set
assert set_call.called
data = set_call.call_args[0][1]
assert "tempmail.com" in data["allowlisted_domains"]
# external_domains should still contain it (not removed, just allowlisted)
assert "tempmail.com" in data["external_domains"]
def test_add_allowlisted_domain(self, email_service, mock_db):
"""Test add_allowlisted_domain writes to allowlisted_domains field."""
email_service.add_allowlisted_domain("legit.com", "admin@test.com")
transaction = mock_db.transaction.return_value
set_call = transaction.set
assert set_call.called
data = set_call.call_args[0][1]
assert "legit.com" in data["allowlisted_domains"]
def test_remove_allowlisted_domain(self, email_service, mock_db):
"""Test remove_allowlisted_domain removes from allowlisted_domains."""
# Set up mock with an existing allowlisted domain
mock_doc = Mock()
mock_doc.exists = True
mock_doc.to_dict.return_value = {
"external_domains": ["tempmail.com"],
"manual_domains": [],
"allowlisted_domains": ["legit.com"],
"blocked_emails": [],
"blocked_ips": [],
}
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
result = email_service.remove_allowlisted_domain("legit.com", "admin@test.com")
assert result is True
transaction = mock_db.transaction.return_value
set_call = transaction.set
assert set_call.called
data = set_call.call_args[0][1]
assert "legit.com" not in data["allowlisted_domains"]
def test_remove_allowlisted_domain_not_found(self, email_service, mock_db):
"""Test remove_allowlisted_domain returns False when domain not found."""
result = email_service.remove_allowlisted_domain("nonexistent.com", "admin@test.com")
assert result is False
def test_get_blocklist_raw_data(self, email_service, mock_db):
"""Test get_blocklist_raw_data returns all raw fields."""
from backend.services.email_validation_service import EmailValidationService
# Clear cache so it reads fresh
EmailValidationService._blocklist_cache = None
EmailValidationService._blocklist_cache_time = None
raw = email_service.get_blocklist_raw_data()
assert "external_domains" in raw
assert "manual_domains" in raw
assert "allowlisted_domains" in raw
assert "blocked_emails" in raw
assert "blocked_ips" in raw
assert "last_sync_at" in raw
assert "last_sync_count" in raw
assert "updated_at" in raw
assert "updated_by" in raw
# Check sorted
assert raw["external_domains"] == sorted(["tempmail.com", "mailinator.com"])
assert raw["manual_domains"] == ["my-custom.com"]
def test_get_blocklist_raw_data_no_doc(self, email_service, mock_db):
"""Test get_blocklist_raw_data returns defaults when doc doesn't exist."""
mock_doc = Mock()
mock_doc.exists = False
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
raw = email_service.get_blocklist_raw_data()
assert raw["external_domains"] == []
assert raw["manual_domains"] == []
assert raw["allowlisted_domains"] == []
assert raw["last_sync_at"] is None
def test_get_blocklist_stats_new_model(self, email_service, mock_db):
"""Test get_blocklist_stats returns counts for new data model fields."""
from backend.services.email_validation_service import EmailValidationService
EmailValidationService._blocklist_cache = None
EmailValidationService._blocklist_cache_time = None
stats = email_service.get_blocklist_stats()
assert stats["external_domains_count"] == 2
assert stats["manual_domains_count"] == 1
assert stats["allowlisted_domains_count"] == 0
assert stats["disposable_domains_count"] == 3 # 2 external + 1 manual - 0 allowlisted
assert stats["blocked_emails_count"] == 0
assert stats["blocked_ips_count"] == 0
class TestIPHashing:
"""Test IP address hashing."""
@@ -240,3 +496,410 @@ class TestIPHashing:
hash_result = email_service.hash_ip("192.168.1.1")
assert len(hash_result) == 64
assert all(c in "0123456789abcdef" for c in hash_result)
class TestExternalAPIChecks:
"""Test external API-based disposable domain detection (DeBounce + verifymail.io)."""
@pytest.fixture
def mock_db(self):
mock = MagicMock()
mock_doc = Mock()
mock_doc.exists = True
mock_doc.to_dict.return_value = {
"external_domains": ["yopmail.com"],
"manual_domains": [],
"allowlisted_domains": [],
"blocked_emails": [],
"blocked_ips": [],
"verified_clean_domains": {},
}
mock.collection.return_value.document.return_value.get.return_value = mock_doc
return mock
@pytest.fixture
def email_service(self, mock_db):
from backend.services.email_validation_service import EmailValidationService
EmailValidationService._blocklist_cache = None
EmailValidationService._blocklist_cache_time = None
return EmailValidationService(db=mock_db)
# =========================================================================
# Well-known provider skip
# =========================================================================
def test_well_known_providers_skip_all_checks(self, email_service):
"""Well-known providers return False without any API calls."""
with patch(
"backend.services.email_validation_service._get_http_client"
) as mock_client:
assert email_service.is_disposable_domain("user@gmail.com") is False
assert email_service.is_disposable_domain("user@yahoo.com") is False
assert email_service.is_disposable_domain("user@hotmail.com") is False
assert email_service.is_disposable_domain("user@outlook.com") is False
assert email_service.is_disposable_domain("user@protonmail.com") is False
assert email_service.is_disposable_domain("user@icloud.com") is False
# No HTTP calls should have been made
mock_client.return_value.get.assert_not_called()
# =========================================================================
# Allowlisted domain bypass (Tier 1.5)
# =========================================================================
def test_allowlisted_domain_skips_external_api_checks(self, mock_db):
"""Allowlisted domains should skip external API checks entirely.
Regression test: inbox.testmail.app was getting flagged by DeBounce
even though it was in the allowlist, because external API calls ran
after the static blocklist check but before checking the allowlist.
"""
from backend.services.email_validation_service import EmailValidationService
mock_doc = Mock()
mock_doc.exists = True
mock_doc.to_dict.return_value = {
"external_domains": ["yopmail.com"],
"manual_domains": ["inbox.testmail.app"], # auto-learned by DeBounce
"allowlisted_domains": ["inbox.testmail.app"], # but also allowlisted
"blocked_emails": [],
"blocked_ips": [],
"verified_clean_domains": {},
}
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
EmailValidationService._blocklist_cache = None
EmailValidationService._blocklist_cache_time = None
service = EmailValidationService(db=mock_db)
with patch(
"backend.services.email_validation_service._get_http_client"
) as mock_client:
result = service.is_disposable_domain("user@inbox.testmail.app")
assert result is False
# No HTTP calls should have been made — allowlist bypasses external APIs
mock_client.return_value.get.assert_not_called()
# =========================================================================
# DeBounce API
# =========================================================================
def test_debounce_flags_disposable(self, email_service):
"""DeBounce returning disposable=true should flag the domain."""
with patch(
"backend.services.email_validation_service._get_http_client"
) as mock_client, patch(
"backend.services.email_validation_service.settings"
) as mock_settings:
mock_response = Mock()
mock_response.json.return_value = {"disposable": "true"}
mock_response.raise_for_status = Mock()
mock_client.return_value.get.return_value = mock_response
mock_settings.get_secret.return_value = None
result = email_service.is_disposable_domain("user@sketchy-domain.xyz")
assert result is True
def test_debounce_clean_and_no_verifymail_key(self, email_service):
"""DeBounce clean + no verifymail key → domain is clean."""
with patch(
"backend.services.email_validation_service._get_http_client"
) as mock_client, patch(
"backend.services.email_validation_service.settings"
) as mock_settings:
mock_response = Mock()
mock_response.json.return_value = {"disposable": "false"}
mock_response.raise_for_status = Mock()
mock_client.return_value.get.return_value = mock_response
mock_settings.get_secret.return_value = None
result = email_service.is_disposable_domain("user@legit-company.com")
assert result is False
def test_debounce_timeout_falls_through_to_verifymail(self, email_service):
"""DeBounce timeout → should try verifymail.io."""
with patch(
"backend.services.email_validation_service._get_http_client"
) as mock_client, patch(
"backend.services.email_validation_service.settings"
) as mock_settings:
# DeBounce times out, verifymail says disposable
mock_client.return_value.get.side_effect = [
httpx.TimeoutException("timeout"), # DeBounce
]
mock_settings.get_secret.return_value = "test-api-key"
# DeBounce returns None (error) so verifymail is NOT called
# (tier 4 only runs if debounce_result is False, not None)
result = email_service.is_disposable_domain("user@unknown.xyz")
assert result is False
def test_debounce_error_does_not_block_users(self, email_service):
"""If DeBounce errors, don't block the user."""
with patch(
"backend.services.email_validation_service._get_http_client"
) as mock_client, patch(
"backend.services.email_validation_service.settings"
) as mock_settings:
mock_client.return_value.get.side_effect = Exception("network error")
mock_settings.get_secret.return_value = None
result = email_service.is_disposable_domain("user@some-domain.com")
assert result is False
# =========================================================================
# verifymail.io API
# =========================================================================
def test_verifymail_catches_what_debounce_misses(self, email_service):
"""DeBounce clean + verifymail disposable → flagged."""
with patch(
"backend.services.email_validation_service._get_http_client"
) as mock_client, patch(
"backend.services.email_validation_service.settings"
) as mock_settings:
# DeBounce says clean, verifymail says disposable
debounce_resp = Mock()
debounce_resp.json.return_value = {"disposable": "false"}
debounce_resp.raise_for_status = Mock()
verifymail_resp = Mock()
verifymail_resp.json.return_value = {"disposable": True, "block": True}
verifymail_resp.raise_for_status = Mock()
mock_client.return_value.get.side_effect = [debounce_resp, verifymail_resp]
mock_settings.get_secret.return_value = "test-api-key"
result = email_service.is_disposable_domain("user@sneaky-disposable.io.vn")
assert result is True
def test_verifymail_block_flag_also_triggers(self, email_service):
"""verifymail.io block=True (even if disposable=False) → flagged."""
with patch(
"backend.services.email_validation_service._get_http_client"
) as mock_client, patch(
"backend.services.email_validation_service.settings"
) as mock_settings:
debounce_resp = Mock()
debounce_resp.json.return_value = {"disposable": "false"}
debounce_resp.raise_for_status = Mock()
verifymail_resp = Mock()
verifymail_resp.json.return_value = {"disposable": False, "block": True}
verifymail_resp.raise_for_status = Mock()
mock_client.return_value.get.side_effect = [debounce_resp, verifymail_resp]
mock_settings.get_secret.return_value = "test-api-key"
result = email_service.is_disposable_domain("user@blocked-domain.store")
assert result is True
def test_both_apis_clean(self, email_service):
"""Both APIs say clean → not disposable."""
with patch(
"backend.services.email_validation_service._get_http_client"
) as mock_client, patch(
"backend.services.email_validation_service.settings"
) as mock_settings:
debounce_resp = Mock()
debounce_resp.json.return_value = {"disposable": "false"}
debounce_resp.raise_for_status = Mock()
verifymail_resp = Mock()
verifymail_resp.json.return_value = {"disposable": False, "block": False}
verifymail_resp.raise_for_status = Mock()
mock_client.return_value.get.side_effect = [debounce_resp, verifymail_resp]
mock_settings.get_secret.return_value = "test-api-key"
result = email_service.is_disposable_domain("user@real-company.vn")
assert result is False
def test_both_apis_timeout_falls_back_to_static(self, email_service):
"""Both APIs timeout → fall back to static list (returns False for unknown domain)."""
with patch(
"backend.services.email_validation_service._get_http_client"
) as mock_client, patch(
"backend.services.email_validation_service.settings"
) as mock_settings:
mock_client.return_value.get.side_effect = httpx.TimeoutException("timeout")
mock_settings.get_secret.return_value = "test-api-key"
# Unknown domain not in static list → False (don't block real users)
result = email_service.is_disposable_domain("user@unknown-domain.com")
assert result is False
def test_verifymail_skipped_when_no_api_key(self, email_service):
"""verifymail.io is skipped when API key is not configured."""
with patch(
"backend.services.email_validation_service._get_http_client"
) as mock_client, patch(
"backend.services.email_validation_service.settings"
) as mock_settings:
debounce_resp = Mock()
debounce_resp.json.return_value = {"disposable": "false"}
debounce_resp.raise_for_status = Mock()
mock_client.return_value.get.return_value = debounce_resp
mock_settings.get_secret.return_value = None # No API key
result = email_service.is_disposable_domain("user@some-domain.com")
assert result is False
# Only one HTTP call (DeBounce), not two
assert mock_client.return_value.get.call_count == 1
# =========================================================================
# Auto-learn
# =========================================================================
def test_auto_learn_adds_to_manual_domains(self, email_service, mock_db):
"""When DeBounce flags a domain, it should be auto-learned to manual_domains."""
with patch(
"backend.services.email_validation_service._get_http_client"
) as mock_client, patch(
"backend.services.email_validation_service.settings"
) as mock_settings:
mock_response = Mock()
mock_response.json.return_value = {"disposable": "true"}
mock_response.raise_for_status = Mock()
mock_client.return_value.get.return_value = mock_response
mock_settings.get_secret.return_value = None
email_service.is_disposable_domain("user@new-disposable.xyz")
# Verify Firestore was written to with the domain in manual_domains
set_calls = mock_db.collection.return_value.document.return_value.set.call_args_list
assert len(set_calls) > 0
# Find the auto-learn write
for call in set_calls:
data = call[0][0]
if "manual_domains" in data:
assert "new-disposable.xyz" in data["manual_domains"]
assert data.get("updated_by") == "auto-learn"
break
else:
pytest.fail("Auto-learn did not write manual_domains")
def test_auto_learn_verifymail_also_persists(self, email_service, mock_db):
"""When verifymail flags a domain DeBounce missed, it should also auto-learn."""
with patch(
"backend.services.email_validation_service._get_http_client"
) as mock_client, patch(
"backend.services.email_validation_service.settings"
) as mock_settings:
debounce_resp = Mock()
debounce_resp.json.return_value = {"disposable": "false"}
debounce_resp.raise_for_status = Mock()
verifymail_resp = Mock()
verifymail_resp.json.return_value = {"disposable": True, "block": True}
verifymail_resp.raise_for_status = Mock()
mock_client.return_value.get.side_effect = [debounce_resp, verifymail_resp]
mock_settings.get_secret.return_value = "test-api-key"
email_service.is_disposable_domain("user@tricky-disposable.store")
set_calls = mock_db.collection.return_value.document.return_value.set.call_args_list
found_auto_learn = False
for call in set_calls:
data = call[0][0]
if "manual_domains" in data and "tricky-disposable.store" in data["manual_domains"]:
found_auto_learn = True
break
assert found_auto_learn, "verifymail flagged domain was not auto-learned"
# =========================================================================
# Verified-clean domain cache
# =========================================================================
def test_verified_clean_domain_skips_api_calls(self, email_service, mock_db):
"""Domain verified clean within 7 days should skip external API calls."""
from backend.services.email_validation_service import EmailValidationService
# Set up blocklist with a verified clean domain
recent = (datetime.now(timezone.utc) - timedelta(hours=1)).isoformat()
mock_doc = Mock()
mock_doc.exists = True
mock_doc.to_dict.return_value = {
"external_domains": [],
"manual_domains": [],
"allowlisted_domains": [],
"blocked_emails": [],
"blocked_ips": [],
"verified_clean_domains": {
"recently-checked.com": {"checked_at": recent},
},
}
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
EmailValidationService._blocklist_cache = None
EmailValidationService._blocklist_cache_time = None
with patch(
"backend.services.email_validation_service._get_http_client"
) as mock_client:
result = email_service.is_disposable_domain("user@recently-checked.com")
assert result is False
# No HTTP calls — skipped due to verified-clean cache
mock_client.return_value.get.assert_not_called()
def test_expired_clean_domain_rechecks_api(self, email_service, mock_db):
"""Domain verified clean >7 days ago should re-check external APIs."""
from backend.services.email_validation_service import EmailValidationService
expired = (datetime.now(timezone.utc) - timedelta(days=8)).isoformat()
mock_doc = Mock()
mock_doc.exists = True
mock_doc.to_dict.return_value = {
"external_domains": [],
"manual_domains": [],
"allowlisted_domains": [],
"blocked_emails": [],
"blocked_ips": [],
"verified_clean_domains": {
"expired-check.com": {"checked_at": expired},
},
}
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
EmailValidationService._blocklist_cache = None
EmailValidationService._blocklist_cache_time = None
with patch(
"backend.services.email_validation_service._get_http_client"
) as mock_client, patch(
"backend.services.email_validation_service.settings"
) as mock_settings:
mock_response = Mock()
mock_response.json.return_value = {"disposable": "false"}
mock_response.raise_for_status = Mock()
mock_client.return_value.get.return_value = mock_response
mock_settings.get_secret.return_value = None
result = email_service.is_disposable_domain("user@expired-check.com")
assert result is False
# Should have called DeBounce since cache expired
assert mock_client.return_value.get.call_count >= 1
def test_clean_result_persisted_to_firestore(self, email_service, mock_db):
"""When both APIs say clean, the domain should be persisted as verified clean."""
with patch(
"backend.services.email_validation_service._get_http_client"
) as mock_client, patch(
"backend.services.email_validation_service.settings"
) as mock_settings:
mock_response = Mock()
mock_response.json.return_value = {"disposable": "false"}
mock_response.raise_for_status = Mock()
mock_client.return_value.get.return_value = mock_response
mock_settings.get_secret.return_value = None
email_service.is_disposable_domain("user@new-legit-domain.com")
# Check that verified_clean_domains was written
set_calls = mock_db.collection.return_value.document.return_value.set.call_args_list
found_clean = False
for call in set_calls:
data = call[0][0]
if "verified_clean_domains" in data:
verified = data["verified_clean_domains"]
if "new-legit-domain.com" in verified:
assert "checked_at" in verified["new-legit-domain.com"]
found_clean = True
break
assert found_clean, "Clean domain was not persisted to verified_clean_domains"
+47
View File
@@ -348,6 +348,53 @@ class TestGCEEncodingBackend:
assert output.lossless_4k_mp4_path == "gs://bucket/output/lossless.mp4"
@patch.object(GCEEncodingBackend, "_get_service")
@pytest.mark.asyncio
async def test_encode_maps_with_vocals_mp4_from_list(self, mock_get_service):
"""Test GCE encoding maps 'With Vocals' MP4 from output_files list.
The GCE worker returns output_files as a list of blob paths.
The mapper must recognize '(With Vocals).mp4' and set with_vocals_mp4_path.
Regression test for: with_vocals_mp4 silently dropped from GCE results.
"""
mock_service = MagicMock()
mock_service.encode_videos = AsyncMock(return_value={
"status": "complete",
"output_files": [
"jobs/test/finals/Artist - Title (Final Karaoke Lossless 4k).mp4",
"jobs/test/finals/Artist - Title (Final Karaoke Lossy 4k).mp4",
"jobs/test/finals/Artist - Title (Final Karaoke Lossless 4k).mkv",
"jobs/test/finals/Artist - Title (Final Karaoke Lossy 720p).mp4",
"jobs/test/finals/Artist - Title (With Vocals).mp4",
"jobs/test/finals/Artist - Title (Karaoke).mp4",
]
})
mock_get_service.return_value = mock_service
backend = GCEEncodingBackend()
input_config = EncodingInput(
title_video_path="/input/title.mov",
karaoke_video_path="/input/karaoke.mov",
instrumental_audio_path="/input/audio.flac",
artist="Artist",
title="Title",
options={
"job_id": "test-job",
"input_gcs_path": "gs://bucket/input/",
"output_gcs_path": "gs://bucket/output/",
}
)
output = await backend.encode(input_config)
assert output.success is True
assert output.with_vocals_mp4_path == "jobs/test/finals/Artist - Title (With Vocals).mp4"
assert output.lossless_4k_mp4_path == "jobs/test/finals/Artist - Title (Final Karaoke Lossless 4k).mp4"
assert output.lossy_4k_mp4_path == "jobs/test/finals/Artist - Title (Final Karaoke Lossy 4k).mp4"
assert output.lossless_mkv_path == "jobs/test/finals/Artist - Title (Final Karaoke Lossless 4k).mkv"
assert output.lossy_720p_mp4_path == "jobs/test/finals/Artist - Title (Final Karaoke Lossy 720p).mp4"
class TestGetEncodingBackend:
"""Test encoding backend factory function."""
+91
View File
@@ -239,6 +239,37 @@ class TestRequestWithRetry:
await encoding_service.submit_encoding_job("j1", "gs://in", "gs://out", {})
class TestWarmupFallback:
"""Tests for _warmup_encoding_worker_fallback() in the retry loop."""
def test_warmup_fallback_called_on_first_connection_failure(self, encoding_service):
"""Warmup fallback is called when the first connection attempt fails."""
mock_manager = MagicMock()
mock_manager.ensure_primary_running.return_value = {
"started": True, "vm_name": "encoding-worker-b", "primary_url": "http://1.2.3.4:8080"
}
encoding_service._worker_manager = mock_manager
encoding_service._warmup_encoding_worker_fallback("test-job")
mock_manager.ensure_primary_running.assert_called_once()
def test_warmup_fallback_noop_without_worker_manager(self, encoding_service):
"""Warmup fallback is a no-op when worker_manager is not set (dev mode)."""
encoding_service._worker_manager = None
# Should not raise
encoding_service._warmup_encoding_worker_fallback("test-job")
def test_warmup_fallback_swallows_exceptions(self, encoding_service):
"""Warmup fallback never raises — failures are logged but non-fatal."""
mock_manager = MagicMock()
mock_manager.ensure_primary_running.side_effect = Exception("Compute API down")
encoding_service._worker_manager = mock_manager
# Should not raise
encoding_service._warmup_encoding_worker_fallback("test-job")
class TestWaitForCompletionPollTolerance:
"""Tests for wait_for_completion() transient failure tolerance."""
@@ -310,3 +341,63 @@ class TestWaitForCompletionPollTolerance:
assert result["status"] == "complete"
assert call_count == 6 # 2 fail + 1 success + 2 fail + 1 success
class TestDynamicURLResolution:
"""Tests that EncodingService reads URL from Firestore, not static config."""
def test_url_from_worker_manager(self):
"""Should read primary_url from worker manager."""
mock_manager = MagicMock()
mock_manager.get_config.return_value = MagicMock(
primary_url="http://34.1.2.3:8080",
)
service = EncodingService()
service._initialized = True
service._api_key = "test-key"
service.set_worker_manager(mock_manager)
url = service._get_worker_url()
assert url == "http://34.1.2.3:8080"
mock_manager.get_config.assert_called_once()
def test_url_caches_within_ttl(self):
"""Should cache URL and not re-read within TTL."""
mock_manager = MagicMock()
mock_manager.get_config.return_value = MagicMock(
primary_url="http://34.1.2.3:8080",
)
service = EncodingService()
service._initialized = True
service.set_worker_manager(mock_manager)
service._get_worker_url()
service._get_worker_url()
assert mock_manager.get_config.call_count == 1
def test_url_refreshes_after_ttl(self):
"""Should re-read URL after TTL expires."""
mock_manager = MagicMock()
mock_manager.get_config.return_value = MagicMock(
primary_url="http://34.1.2.3:8080",
)
service = EncodingService()
service._initialized = True
service.set_worker_manager(mock_manager)
service._URL_CACHE_TTL = 0 # Expire immediately
service._get_worker_url()
service._get_worker_url()
assert mock_manager.get_config.call_count == 2
def test_fallback_to_static_url_without_manager(self):
"""Should fall back to static URL when no worker manager set."""
service = EncodingService()
service._url = "http://static:8080"
service._api_key = "test-key"
service._initialized = True
url = service._get_worker_url()
assert url == "http://static:8080"
@@ -0,0 +1,330 @@
"""
Tests for the blue-green encoding worker manager service.
Tests cover:
- Task 1: Firestore config document schema, get_config, update_activity, swap_roles
- Task 2: VM lifecycle (get_vm_status, start_vm, stop_vm, ensure_primary_running)
"""
import pytest
from datetime import datetime, UTC
from unittest.mock import MagicMock, patch, call
from backend.services.encoding_worker_manager import (
EncodingWorkerConfig,
EncodingWorkerManager,
CONFIG_COLLECTION,
CONFIG_DOCUMENT,
ENCODING_WORKER_PORT,
)
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
def _make_firestore_data(**overrides):
"""Create a realistic Firestore document dict for encoding-worker config."""
data = {
"primary_vm": "encoding-worker-blue",
"primary_ip": "10.128.0.50",
"primary_version": "1.0.0",
"primary_deployed_at": "2026-03-20T10:00:00Z",
"secondary_vm": "encoding-worker-green",
"secondary_ip": "10.128.0.51",
"secondary_version": "0.9.0",
"secondary_deployed_at": "2026-03-19T08:00:00Z",
"last_swap_at": "2026-03-20T10:00:00Z",
"last_activity_at": "2026-03-24T12:00:00Z",
"deploy_in_progress": False,
"deploy_in_progress_since": None,
}
data.update(overrides)
return data
@pytest.fixture
def mock_db():
"""Return a mock Firestore client with a pre-configured config document."""
db = MagicMock()
snapshot = MagicMock()
snapshot.exists = True
snapshot.to_dict.return_value = _make_firestore_data()
doc_ref = MagicMock()
doc_ref.get.return_value = snapshot
collection_ref = MagicMock()
collection_ref.document.return_value = doc_ref
db.collection.return_value = collection_ref
return db
@pytest.fixture
def mock_compute():
"""Return a mock Compute Engine InstancesClient."""
return MagicMock()
@pytest.fixture
def manager(mock_db, mock_compute):
return EncodingWorkerManager(
db=mock_db,
compute_client=mock_compute,
project_id="nomadkaraoke",
zone="us-central1-c",
)
# ---------------------------------------------------------------------------
# Task 1: Config dataclass
# ---------------------------------------------------------------------------
class TestEncodingWorkerConfig:
"""Tests for the EncodingWorkerConfig dataclass."""
def test_primary_url(self):
config = EncodingWorkerConfig(
primary_vm="blue", primary_ip="10.0.0.1", primary_version="1.0",
primary_deployed_at=None,
secondary_vm="green", secondary_ip="10.0.0.2",
secondary_version=None, secondary_deployed_at=None,
last_swap_at=None, last_activity_at=None,
deploy_in_progress=False, deploy_in_progress_since=None,
)
assert config.primary_url == "http://10.0.0.1:8080"
def test_secondary_url(self):
config = EncodingWorkerConfig(
primary_vm="blue", primary_ip="10.0.0.1", primary_version="1.0",
primary_deployed_at=None,
secondary_vm="green", secondary_ip="10.0.0.2",
secondary_version=None, secondary_deployed_at=None,
last_swap_at=None, last_activity_at=None,
deploy_in_progress=False, deploy_in_progress_since=None,
)
assert config.secondary_url == "http://10.0.0.2:8080"
# ---------------------------------------------------------------------------
# Task 1: get_config / update_activity / swap_roles
# ---------------------------------------------------------------------------
class TestEncodingWorkerManager:
"""Tests for Firestore config operations."""
def test_get_config_returns_dataclass(self, manager, mock_db):
config = manager.get_config()
assert isinstance(config, EncodingWorkerConfig)
assert config.primary_vm == "encoding-worker-blue"
assert config.primary_ip == "10.128.0.50"
assert config.primary_version == "1.0.0"
assert config.secondary_vm == "encoding-worker-green"
assert config.deploy_in_progress is False
def test_get_config_document_not_found(self, manager, mock_db):
snapshot = MagicMock()
snapshot.exists = False
mock_db.collection.return_value.document.return_value.get.return_value = snapshot
with pytest.raises(ValueError, match="not found"):
manager.get_config()
def test_get_config_reads_correct_path(self, manager, mock_db):
manager.get_config()
mock_db.collection.assert_called_with(CONFIG_COLLECTION)
mock_db.collection.return_value.document.assert_called_with(CONFIG_DOCUMENT)
def test_update_activity_sets_timestamp(self, manager, mock_db):
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
mock_dt.now.return_value = datetime(2026, 3, 24, 15, 0, 0, tzinfo=UTC)
mock_dt.side_effect = lambda *a, **kw: datetime(*a, **kw)
manager.update_activity()
doc_ref = mock_db.collection.return_value.document.return_value
doc_ref.update.assert_called_once_with({
"last_activity_at": "2026-03-24T15:00:00+00:00",
})
def test_swap_roles_uses_transaction(self, manager, mock_db):
"""swap_roles should use a Firestore transaction for atomicity."""
# Set up the transaction mock
mock_transaction = MagicMock()
mock_db.transaction.return_value = mock_transaction
# The transactional function is called with the transaction
manager.swap_roles(
new_primary_vm="encoding-worker-green",
new_primary_ip="10.128.0.51",
new_primary_version="2.0.0",
old_primary_vm="encoding-worker-blue",
old_primary_ip="10.128.0.50",
old_primary_version="1.0.0",
)
# Verify transaction was created and the doc was updated within it
mock_db.transaction.assert_called_once()
def test_swap_roles_writes_correct_data(self, manager, mock_db):
"""swap_roles should write the swapped primary/secondary fields."""
mock_transaction = MagicMock()
mock_db.transaction.return_value = mock_transaction
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
mock_dt.now.return_value = datetime(2026, 3, 24, 16, 0, 0, tzinfo=UTC)
mock_dt.side_effect = lambda *a, **kw: datetime(*a, **kw)
manager.swap_roles(
new_primary_vm="encoding-worker-green",
new_primary_ip="10.128.0.51",
new_primary_version="2.0.0",
old_primary_vm="encoding-worker-blue",
old_primary_ip="10.128.0.50",
old_primary_version="1.0.0",
)
# The transaction.update call should contain the swapped values
doc_ref = mock_db.collection.return_value.document.return_value
update_call = mock_transaction.update.call_args
assert update_call is not None
data = update_call[0][1] # second positional arg is the data dict
assert data["primary_vm"] == "encoding-worker-green"
assert data["primary_ip"] == "10.128.0.51"
assert data["primary_version"] == "2.0.0"
assert data["secondary_vm"] == "encoding-worker-blue"
assert data["secondary_ip"] == "10.128.0.50"
assert data["secondary_version"] == "1.0.0"
assert data["last_swap_at"] == "2026-03-24T16:00:00+00:00"
# ---------------------------------------------------------------------------
# Task 2: VM lifecycle
# ---------------------------------------------------------------------------
class TestVMLifecycle:
"""Tests for Compute Engine VM operations."""
def test_get_vm_status_returns_status(self, manager, mock_compute):
mock_instance = MagicMock()
mock_instance.status = "RUNNING"
mock_compute.get.return_value = mock_instance
status = manager.get_vm_status("encoding-worker-blue")
assert status == "RUNNING"
mock_compute.get.assert_called_once_with(
project="nomadkaraoke",
zone="us-central1-c",
instance="encoding-worker-blue",
)
def test_get_vm_status_terminated(self, manager, mock_compute):
mock_instance = MagicMock()
mock_instance.status = "TERMINATED"
mock_compute.get.return_value = mock_instance
assert manager.get_vm_status("encoding-worker-blue") == "TERMINATED"
def test_start_vm_calls_compute_start(self, manager, mock_compute):
mock_instance = MagicMock()
mock_instance.status = "TERMINATED"
mock_compute.get.return_value = mock_instance
manager.start_vm("encoding-worker-blue")
mock_compute.start.assert_called_once_with(
project="nomadkaraoke",
zone="us-central1-c",
instance="encoding-worker-blue",
)
def test_start_vm_skips_if_already_running(self, manager, mock_compute):
mock_instance = MagicMock()
mock_instance.status = "RUNNING"
mock_compute.get.return_value = mock_instance
manager.start_vm("encoding-worker-blue")
mock_compute.start.assert_not_called()
def test_stop_vm_calls_compute_stop(self, manager, mock_compute):
mock_instance = MagicMock()
mock_instance.status = "RUNNING"
mock_compute.get.return_value = mock_instance
manager.stop_vm("encoding-worker-blue")
mock_compute.stop.assert_called_once_with(
project="nomadkaraoke",
zone="us-central1-c",
instance="encoding-worker-blue",
)
def test_stop_vm_skips_if_already_terminated(self, manager, mock_compute):
mock_instance = MagicMock()
mock_instance.status = "TERMINATED"
mock_compute.get.return_value = mock_instance
manager.stop_vm("encoding-worker-blue")
mock_compute.stop.assert_not_called()
def test_ensure_primary_running_starts_stopped_vm(self, manager, mock_db, mock_compute):
"""When primary is stopped, ensure_primary_running should start it."""
mock_instance = MagicMock()
mock_instance.status = "TERMINATED"
mock_compute.get.return_value = mock_instance
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
mock_dt.now.return_value = datetime(2026, 3, 24, 15, 0, 0, tzinfo=UTC)
mock_dt.side_effect = lambda *a, **kw: datetime(*a, **kw)
result = manager.ensure_primary_running()
assert result["started"] is True
assert result["vm_name"] == "encoding-worker-blue"
assert result["primary_url"] == "http://10.128.0.50:8080"
mock_compute.start.assert_called_once()
def test_ensure_primary_running_already_running(self, manager, mock_db, mock_compute):
"""When primary is already running, should not start and still update activity."""
mock_instance = MagicMock()
mock_instance.status = "RUNNING"
mock_compute.get.return_value = mock_instance
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
mock_dt.now.return_value = datetime(2026, 3, 24, 15, 0, 0, tzinfo=UTC)
mock_dt.side_effect = lambda *a, **kw: datetime(*a, **kw)
result = manager.ensure_primary_running()
assert result["started"] is False
assert result["vm_name"] == "encoding-worker-blue"
assert result["primary_url"] == "http://10.128.0.50:8080"
mock_compute.start.assert_not_called()
def test_ensure_primary_running_updates_activity(self, manager, mock_db, mock_compute):
"""ensure_primary_running should always update last_activity_at."""
mock_instance = MagicMock()
mock_instance.status = "RUNNING"
mock_compute.get.return_value = mock_instance
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
mock_dt.now.return_value = datetime(2026, 3, 24, 15, 0, 0, tzinfo=UTC)
mock_dt.side_effect = lambda *a, **kw: datetime(*a, **kw)
manager.ensure_primary_running()
doc_ref = mock_db.collection.return_value.document.return_value
doc_ref.update.assert_called_once()
def test_start_vm_skips_if_staging(self, manager, mock_compute):
"""start_vm should also skip if VM is in STAGING state (already starting)."""
mock_instance = MagicMock()
mock_instance.status = "STAGING"
mock_compute.get.return_value = mock_instance
manager.start_vm("encoding-worker-blue")
mock_compute.start.assert_not_called()
def test_stop_vm_skips_if_stopping(self, manager, mock_compute):
"""stop_vm should skip if VM is already in STOPPING state."""
mock_instance = MagicMock()
mock_instance.status = "STOPPING"
mock_compute.get.return_value = mock_instance
manager.stop_vm("encoding-worker-blue")
mock_compute.stop.assert_not_called()
@@ -0,0 +1,81 @@
"""
Unit tests for encoding worker lifecycle endpoints.
Tests the warmup and heartbeat API endpoints.
"""
import pytest
from unittest.mock import MagicMock
from fastapi import FastAPI
from fastapi.testclient import TestClient
from backend.api.routes.encoding_worker import router, get_worker_manager
from backend.api.dependencies import require_admin
def get_mock_admin():
"""Override for require_admin dependency."""
return ("admin-token", "admin", 0)
class TestWarmupEndpoint:
def setup_method(self):
self.mock_manager = MagicMock()
self.app = FastAPI()
self.app.include_router(router, prefix="/api")
self.app.dependency_overrides[require_admin] = get_mock_admin
self.app.dependency_overrides[get_worker_manager] = lambda: self.mock_manager
self.client = TestClient(self.app)
def test_warmup_starts_stopped_vm(self):
self.mock_manager.ensure_primary_running.return_value = {
"started": True,
"vm_name": "encoding-worker-a",
"primary_url": "http://34.1.2.3:8080",
}
response = self.client.post("/api/internal/encoding-worker/warmup")
assert response.status_code == 200
data = response.json()
assert data["started"] is True
assert data["vm_name"] == "encoding-worker-a"
def test_warmup_already_running(self):
self.mock_manager.ensure_primary_running.return_value = {
"started": False,
"vm_name": "encoding-worker-a",
"primary_url": "http://34.1.2.3:8080",
}
response = self.client.post("/api/internal/encoding-worker/warmup")
assert response.status_code == 200
assert response.json()["started"] is False
def test_warmup_handles_error(self):
self.mock_manager.ensure_primary_running.side_effect = RuntimeError(
"VM not found"
)
response = self.client.post("/api/internal/encoding-worker/warmup")
assert response.status_code == 200
assert response.json()["started"] is False
assert "error" in response.json()
class TestHeartbeatEndpoint:
def setup_method(self):
self.mock_manager = MagicMock()
self.app = FastAPI()
self.app.include_router(router, prefix="/api")
self.app.dependency_overrides[require_admin] = get_mock_admin
self.app.dependency_overrides[get_worker_manager] = lambda: self.mock_manager
self.client = TestClient(self.app)
def test_heartbeat_updates_activity(self):
response = self.client.post("/api/internal/encoding-worker/heartbeat")
assert response.status_code == 200
assert response.json()["status"] == "ok"
self.mock_manager.update_activity.assert_called_once()
def test_heartbeat_handles_error(self):
self.mock_manager.update_activity.side_effect = RuntimeError(
"Firestore error"
)
response = self.client.post("/api/internal/encoding-worker/heartbeat")
assert response.status_code == 200
assert response.json()["status"] == "error"
+3 -3
View File
@@ -698,21 +698,21 @@ class TestSignedUrlGCSPathGeneration:
from backend.api.routes.file_upload import _get_gcs_path_for_file
path = _get_gcs_path_for_file("test123", "style_params", "style.json")
assert path == "uploads/test123/style/style_params.json"
assert path == "jobs/test123/style/style_params.json"
def test_style_background_gcs_path(self):
"""Test GCS path generation for style background images."""
from backend.api.routes.file_upload import _get_gcs_path_for_file
path = _get_gcs_path_for_file("test123", "style_intro_background", "bg.png")
assert path == "uploads/test123/style/intro_background.png"
assert path == "jobs/test123/style/intro_background.png"
def test_style_font_gcs_path(self):
"""Test GCS path generation for font file."""
from backend.api.routes.file_upload import _get_gcs_path_for_file
path = _get_gcs_path_for_file("test123", "style_font", "font.ttf")
assert path == "uploads/test123/style/font.ttf"
assert path == "jobs/test123/style/font.ttf"
def test_lyrics_file_gcs_path(self):
"""Test GCS path generation for lyrics file."""
+243
View File
@@ -0,0 +1,243 @@
"""
Tests for IP geolocation service.
"""
import pytest
from unittest.mock import MagicMock, patch
from datetime import datetime
import sys
sys.modules.setdefault('google.cloud.firestore', MagicMock())
sys.modules.setdefault('google.cloud.firestore_v1', MagicMock())
class TestIsPrivateIp:
def test_private_ipv4(self):
from backend.services.ip_geolocation_service import _is_private_ip
assert _is_private_ip("10.0.0.1") is True
assert _is_private_ip("192.168.1.1") is True
assert _is_private_ip("172.16.0.1") is True
assert _is_private_ip("169.254.169.126") is True
assert _is_private_ip("127.0.0.1") is True
def test_public_ipv4(self):
from backend.services.ip_geolocation_service import _is_private_ip
assert _is_private_ip("8.8.8.8") is False
assert _is_private_ip("1.2.3.4") is False
def test_invalid_ip(self):
from backend.services.ip_geolocation_service import _is_private_ip
assert _is_private_ip("not-an-ip") is True
assert _is_private_ip("") is True
def test_ipv6(self):
from backend.services.ip_geolocation_service import _is_private_ip
assert _is_private_ip("::1") is True # loopback
assert _is_private_ip("2001:db8::1") is True # documentation range
assert _is_private_ip("2402:800:63ac::1") is False # public
class TestParseIpApiResponse:
def test_success_response(self):
from backend.services.ip_geolocation_service import _parse_ip_api_response
data = {
"status": "success",
"country": "United States",
"countryCode": "US",
"regionName": "South Carolina",
"city": "Lancaster",
"isp": "Comporium Inc",
"org": "Comporium Inc",
"as": "AS14615 Comporium Inc",
"timezone": "America/New_York",
"query": "8.8.8.8",
}
result = _parse_ip_api_response(data)
assert result["status"] == "success"
assert result["country_code"] == "US"
assert result["city"] == "Lancaster"
assert result["isp"] == "Comporium Inc"
assert result["as_number"] == "AS14615"
assert result["as_name"] == "Comporium Inc"
def test_fail_response(self):
from backend.services.ip_geolocation_service import _parse_ip_api_response
result = _parse_ip_api_response({"status": "fail", "query": "bad"})
assert result["status"] == "fail"
class TestLookupIp:
@patch('backend.services.ip_geolocation_service.get_settings')
@patch('backend.services.ip_geolocation_service.firestore')
def test_private_ip_returns_immediately(self, mock_fs, mock_settings):
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_fs.Client.return_value = MagicMock()
from backend.services.ip_geolocation_service import IpGeolocationService
service = IpGeolocationService()
result = service.lookup_ip("192.168.1.1")
assert result["status"] == "private"
@patch('backend.services.ip_geolocation_service.get_settings')
@patch('backend.services.ip_geolocation_service.firestore')
def test_cache_hit_returns_cached(self, mock_fs, mock_settings):
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
cached_data = {
"status": "success",
"ip": "8.8.8.8",
"country_code": "US",
"cached_at": datetime.utcnow().isoformat(),
}
mock_doc = MagicMock()
mock_doc.exists = True
mock_doc.to_dict.return_value = cached_data
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
from backend.services.ip_geolocation_service import IpGeolocationService
service = IpGeolocationService()
result = service.lookup_ip("8.8.8.8")
assert result["status"] == "success"
assert result["country_code"] == "US"
@patch('backend.services.ip_geolocation_service.get_settings')
@patch('backend.services.ip_geolocation_service.firestore')
@patch('backend.services.ip_geolocation_service.httpx')
def test_cache_miss_fetches_from_api(self, mock_httpx, mock_fs, mock_settings):
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
# Cache miss
mock_doc = MagicMock()
mock_doc.exists = False
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
# Mock httpx response
mock_response = MagicMock()
mock_response.json.return_value = {
"status": "success",
"country": "Vietnam",
"countryCode": "VN",
"regionName": "Ho Chi Minh",
"city": "Ho Chi Minh City",
"isp": "Viettel",
"org": "Viettel Group",
"as": "AS7552 Viettel Group",
"timezone": "Asia/Ho_Chi_Minh",
"query": "14.191.152.247",
}
mock_client = MagicMock()
mock_client.__enter__ = MagicMock(return_value=mock_client)
mock_client.__exit__ = MagicMock(return_value=False)
mock_client.get.return_value = mock_response
mock_httpx.Client.return_value = mock_client
from backend.services.ip_geolocation_service import IpGeolocationService
service = IpGeolocationService()
result = service.lookup_ip("14.191.152.247")
assert result["status"] == "success"
assert result["country_code"] == "VN"
assert result["isp"] == "Viettel"
# Should have cached the result
mock_db.collection.return_value.document.return_value.set.assert_called_once()
@patch('backend.services.ip_geolocation_service.get_settings')
@patch('backend.services.ip_geolocation_service.firestore')
def test_null_ip_returns_private(self, mock_fs, mock_settings):
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_fs.Client.return_value = MagicMock()
from backend.services.ip_geolocation_service import IpGeolocationService
service = IpGeolocationService()
result = service.lookup_ip("")
assert result["status"] == "private"
result2 = service.lookup_ip(None)
assert result2["status"] == "private"
class TestLookupBatch:
@patch('backend.services.ip_geolocation_service.get_settings')
@patch('backend.services.ip_geolocation_service.firestore')
def test_all_cached(self, mock_fs, mock_settings):
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_db = MagicMock()
mock_fs.Client.return_value = mock_db
cached_data = {
"status": "success",
"ip": "8.8.8.8",
"country_code": "US",
"cached_at": datetime.utcnow().isoformat(),
}
mock_doc = MagicMock()
mock_doc.exists = True
mock_doc.to_dict.return_value = cached_data
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
from backend.services.ip_geolocation_service import IpGeolocationService
service = IpGeolocationService()
results = service.lookup_ips_batch(["8.8.8.8"])
assert "8.8.8.8" in results
assert results["8.8.8.8"]["status"] == "success"
@patch('backend.services.ip_geolocation_service.get_settings')
@patch('backend.services.ip_geolocation_service.firestore')
def test_private_ips_in_batch(self, mock_fs, mock_settings):
mock_settings.return_value = MagicMock(google_cloud_project='test')
mock_fs.Client.return_value = MagicMock()
from backend.services.ip_geolocation_service import IpGeolocationService
service = IpGeolocationService()
results = service.lookup_ips_batch(["192.168.1.1", "10.0.0.1"])
assert results["192.168.1.1"]["status"] == "private"
assert results["10.0.0.1"]["status"] == "private"
class TestAdminEndpoints:
@pytest.fixture
def admin_client(self):
from backend.main import app
from backend.api.dependencies import require_admin
from fastapi.testclient import TestClient
mock_auth = MagicMock()
mock_auth.is_admin = True
app.dependency_overrides[require_admin] = lambda: mock_auth
yield TestClient(app)
app.dependency_overrides.clear()
@patch('backend.api.routes.admin.get_ip_geolocation_service')
def test_single_ip_endpoint(self, mock_get_svc, admin_client):
mock_svc = MagicMock()
mock_svc.lookup_ip.return_value = {
"status": "success",
"ip": "8.8.8.8",
"country_code": "US",
}
mock_get_svc.return_value = mock_svc
response = admin_client.get("/api/admin/abuse/ip-info/8.8.8.8")
assert response.status_code == 200
assert response.json()["country_code"] == "US"
@patch('backend.api.routes.admin.get_ip_geolocation_service')
def test_batch_endpoint(self, mock_get_svc, admin_client):
mock_svc = MagicMock()
mock_svc.lookup_ips_batch.return_value = {
"8.8.8.8": {"status": "success", "country_code": "US"},
"1.1.1.1": {"status": "success", "country_code": "AU"},
}
mock_get_svc.return_value = mock_svc
response = admin_client.post(
"/api/admin/abuse/ip-info/batch",
json={"ips": ["8.8.8.8", "1.1.1.1"]},
)
assert response.status_code == 200
data = response.json()
assert data["8.8.8.8"]["country_code"] == "US"
assert data["1.1.1.1"]["country_code"] == "AU"
+7
View File
@@ -285,6 +285,13 @@ class TestValidateWorkerCanRun:
assert error is not None
assert "video_worker called but job status is pending" in error
def test_video_worker_invalid_with_generating_video_status(self):
"""Test video worker rejects GENERATING_VIDEO to prevent concurrent worker races."""
job = create_test_job(status=JobStatus.GENERATING_VIDEO)
error = validate_worker_can_run("video_worker", job)
assert error is not None
assert "video_worker called but job status is generating_video" in error
def test_render_video_worker_valid_with_review_complete_status(self):
"""Test render video worker is valid with REVIEW_COMPLETE status."""
job = create_test_job(status=JobStatus.REVIEW_COMPLETE)
+514
View File
@@ -0,0 +1,514 @@
"""
Tests for Modal → GCP audio separation migration.
Covers:
- Pipeline decoupling: separation no longer gates lyrics review
- Preset-based model configuration
- Custom output filenames (job_id prefix)
- Screens worker prerequisites relaxation
"""
import os
import tempfile
from datetime import datetime, timezone
from unittest.mock import Mock, patch, MagicMock
import pytest
from backend.models.job import Job, JobStatus
from backend.services.job_manager import JobManager
# ==================== Fixtures ====================
@pytest.fixture
def mock_firestore_service():
with patch('backend.services.job_manager.FirestoreService') as mock:
service = Mock()
mock.return_value = service
yield service
@pytest.fixture
def job_manager(mock_firestore_service):
return JobManager()
def _make_job(job_id="test-001", state_data=None, **kwargs):
defaults = dict(
job_id=job_id,
artist="Test Artist",
title="Test Song",
status=JobStatus.DOWNLOADING,
created_at=datetime.now(timezone.utc),
updated_at=datetime.now(timezone.utc),
theme_id="default",
)
defaults.update(kwargs)
if state_data is not None:
defaults["state_data"] = state_data
return Job(**defaults)
# ==================== P0: Pipeline Decoupling ====================
class TestPipelineDecoupling:
"""
Critical: verify separation is decoupled from lyrics review path.
New behavior:
- check_parallel_processing_complete() only checks lyrics_complete
- mark_audio_complete() sets flag but does NOT trigger screens
- mark_lyrics_complete() triggers screens on its own (no audio gate)
"""
def test_check_parallel_only_requires_lyrics(self, job_manager, mock_firestore_service):
"""lyrics_complete=True is sufficient, even without audio_complete."""
job = _make_job(state_data={"lyrics_complete": True, "audio_complete": False})
mock_firestore_service.get_job.return_value = job
assert job_manager.check_parallel_processing_complete("test-001") is True
def test_check_parallel_fails_without_lyrics(self, job_manager, mock_firestore_service):
"""lyrics_complete=False means not ready, even if audio_complete=True."""
job = _make_job(state_data={"lyrics_complete": False, "audio_complete": True})
mock_firestore_service.get_job.return_value = job
assert job_manager.check_parallel_processing_complete("test-001") is False
def test_check_parallel_fails_with_empty_state(self, job_manager, mock_firestore_service):
"""Empty state_data means not ready."""
job = _make_job(state_data={})
mock_firestore_service.get_job.return_value = job
assert job_manager.check_parallel_processing_complete("test-001") is False
def test_mark_audio_complete_does_not_trigger_screens(self, job_manager, mock_firestore_service):
"""Critical: audio completion must NOT trigger screens worker."""
job = _make_job(state_data={"lyrics_complete": True})
mock_firestore_service.get_job.return_value = job
mock_firestore_service.update_job.return_value = True
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
job_manager.mark_audio_complete("test-001")
mock_trigger.assert_not_called()
def test_mark_lyrics_complete_triggers_screens_without_audio(self, job_manager, mock_firestore_service):
"""Critical: lyrics completion triggers screens even if audio isn't done."""
# After update_state_data sets lyrics_complete, get_job returns updated state
job_after_update = _make_job(state_data={"audio_complete": False, "lyrics_complete": True})
mock_firestore_service.get_job.return_value = job_after_update
mock_firestore_service.update_job.return_value = True
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
job_manager.mark_lyrics_complete("test-001")
mock_trigger.assert_called_once_with("test-001")
def test_mark_lyrics_complete_triggers_screens_with_audio(self, job_manager, mock_firestore_service):
"""Lyrics completion triggers screens when audio is already done too."""
job_after_update = _make_job(state_data={"audio_complete": True, "lyrics_complete": True})
mock_firestore_service.get_job.return_value = job_after_update
mock_firestore_service.update_job.return_value = True
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
job_manager.mark_lyrics_complete("test-001")
mock_trigger.assert_called_once_with("test-001")
def test_ordering_audio_first_then_lyrics(self, job_manager, mock_firestore_service):
"""Typical flow: audio finishes first, then lyrics triggers screens."""
mock_firestore_service.update_job.return_value = True
# Audio completes first — get_job returns state without lyrics_complete
job_audio_only = _make_job(state_data={"audio_complete": True})
mock_firestore_service.get_job.return_value = job_audio_only
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
job_manager.mark_audio_complete("test-001")
mock_trigger.assert_not_called()
# Now lyrics completes — get_job returns state with both flags
job_both = _make_job(state_data={"audio_complete": True, "lyrics_complete": True})
mock_firestore_service.get_job.return_value = job_both
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
job_manager.mark_lyrics_complete("test-001")
mock_trigger.assert_called_once()
def test_ordering_lyrics_first_then_audio(self, job_manager, mock_firestore_service):
"""Less common: lyrics finishes first, triggers screens immediately."""
mock_firestore_service.update_job.return_value = True
# Lyrics completes first — get_job returns state with lyrics_complete
job_lyrics_only = _make_job(state_data={"lyrics_complete": True})
mock_firestore_service.get_job.return_value = job_lyrics_only
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
job_manager.mark_lyrics_complete("test-001")
mock_trigger.assert_called_once()
# Audio completes later — should NOT trigger screens again
job_both = _make_job(state_data={"lyrics_complete": True, "audio_complete": True})
mock_firestore_service.get_job.return_value = job_both
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
job_manager.mark_audio_complete("test-001")
mock_trigger.assert_not_called()
# ==================== P0: Preset Configuration ====================
class TestPresetConfiguration:
"""
Test that preset parameters flow through create_audio_processor correctly.
"""
def test_create_audio_processor_sets_presets(self):
"""Presets are set as attributes on the processor."""
with patch('backend.workers.audio_worker.AudioProcessor') as MockProcessor:
from backend.workers.audio_worker import create_audio_processor
with tempfile.TemporaryDirectory() as temp_dir:
processor = create_audio_processor(
temp_dir,
instrumental_preset="instrumental_clean",
karaoke_preset="karaoke",
)
# Verify presets are set on the returned object
assert processor.instrumental_preset == "instrumental_clean"
assert processor.karaoke_preset == "karaoke"
def test_create_audio_processor_default_presets(self):
"""Default presets are used when not explicitly provided."""
with patch('backend.workers.audio_worker.AudioProcessor') as MockProcessor:
from backend.workers.audio_worker import (
create_audio_processor,
DEFAULT_INSTRUMENTAL_PRESET,
DEFAULT_KARAOKE_PRESET,
)
with tempfile.TemporaryDirectory() as temp_dir:
processor = create_audio_processor(temp_dir)
assert processor.instrumental_preset == DEFAULT_INSTRUMENTAL_PRESET
assert processor.karaoke_preset == DEFAULT_KARAOKE_PRESET
def test_default_other_models_is_empty(self):
"""Demucs 6-stem is dropped — DEFAULT_OTHER_MODELS should be empty."""
from backend.workers.audio_worker import DEFAULT_OTHER_MODELS
assert DEFAULT_OTHER_MODELS == []
def test_create_audio_processor_with_explicit_models(self):
"""Explicit model names still work (legacy per-job override)."""
with patch('backend.workers.audio_worker.AudioProcessor') as MockProcessor:
from backend.workers.audio_worker import create_audio_processor
with tempfile.TemporaryDirectory() as temp_dir:
processor = create_audio_processor(
temp_dir,
clean_instrumental_model="custom_model.ckpt",
backing_vocals_models=["custom_bv.ckpt"],
)
call_kwargs = MockProcessor.call_args[1]
assert call_kwargs["clean_instrumental_model"] == "custom_model.ckpt"
assert call_kwargs["backing_vocals_models"] == ["custom_bv.ckpt"]
# ==================== P0: Custom Output Names Contract ====================
class TestCustomOutputNames:
"""
Test that AudioProcessor uses job_id-based custom_output_names
and organizes results by known filenames.
"""
def test_job_id_used_as_file_prefix(self):
"""When job_id is set, it's used as the filename prefix in custom_output_names."""
from karaoke_gen.audio_processor import AudioProcessor
import logging
processor = AudioProcessor(
logger=logging.getLogger("test"),
log_level=logging.INFO,
log_formatter=None,
model_file_dir=None,
lossless_output_format="FLAC",
clean_instrumental_model="test.ckpt",
backing_vocals_models=[], # No stage 2
other_stems_models=[],
ffmpeg_base_command="ffmpeg",
)
processor.instrumental_preset = "instrumental_clean"
processor.karaoke_preset = None # No stage 2
processor.job_id = "abc123"
mock_client = Mock()
with tempfile.TemporaryDirectory() as temp_dir:
stems_dir = os.path.join(temp_dir, "stems")
os.makedirs(stems_dir)
# Create expected output files
for name in ["abc123_mixed_vocals.flac", "abc123_mixed_instrumental.flac"]:
with open(os.path.join(stems_dir, name), "w") as f:
f.write("fake audio")
mock_client.separate_audio_and_wait.return_value = {
"status": "completed",
"downloaded_files": [
os.path.join(stems_dir, "abc123_mixed_vocals.flac"),
os.path.join(stems_dir, "abc123_mixed_instrumental.flac"),
],
"files": {},
}
input_file = os.path.join(temp_dir, "test.flac")
with open(input_file, "w") as f:
f.write("fake input")
with patch.object(processor, '_create_stems_directory', return_value=stems_dir):
with patch.object(processor, '_normalize_audio_files'):
with patch('karaoke_gen.audio_processor.AudioSeparatorAPIClient', return_value=mock_client):
result = processor._process_audio_separation_remote(
input_file, "Test - Song", temp_dir, "http://fake-api",
)
# Verify custom_output_names used job_id prefix
call_kwargs = mock_client.separate_audio_and_wait.call_args[1]
assert call_kwargs["custom_output_names"]["Vocals"] == "abc123_mixed_vocals"
assert call_kwargs["custom_output_names"]["Instrumental"] == "abc123_mixed_instrumental"
# Verify results found by known filenames
assert result["clean_instrumental"]["vocals"].endswith("abc123_mixed_vocals.flac")
assert "abc123_mixed_instrumental" in result["clean_instrumental"]["instrumental"]
def test_stage1_results_found_by_known_filenames(self):
"""Stage 1 results are located by predictable filenames, not parsed from model names."""
from karaoke_gen.audio_processor import AudioProcessor
import logging
processor = AudioProcessor(
logger=logging.getLogger("test"),
log_level=logging.INFO,
log_formatter=None,
model_file_dir=None,
lossless_output_format="FLAC",
clean_instrumental_model="test.ckpt",
backing_vocals_models=[],
other_stems_models=[],
ffmpeg_base_command="ffmpeg",
)
processor.instrumental_preset = "instrumental_clean"
processor.karaoke_preset = None # No stage 2
processor.job_id = "job42"
with tempfile.TemporaryDirectory() as temp_dir:
stems_dir = os.path.join(temp_dir, "stems")
os.makedirs(stems_dir)
# Create the files the API would produce
vocals_path = os.path.join(stems_dir, "job42_mixed_vocals.flac")
instrumental_path = os.path.join(stems_dir, "job42_mixed_instrumental.flac")
with open(vocals_path, "w") as f:
f.write("fake vocals")
with open(instrumental_path, "w") as f:
f.write("fake instrumental")
mock_client = Mock()
mock_client.separate_audio_and_wait.return_value = {
"status": "completed",
"downloaded_files": [vocals_path, instrumental_path],
"files": {},
}
# Write a fake input file
input_file = os.path.join(temp_dir, "input.flac")
with open(input_file, "w") as f:
f.write("fake input")
with patch.object(processor, '_create_stems_directory', return_value=stems_dir):
with patch('karaoke_gen.audio_processor.AudioSeparatorAPIClient', return_value=mock_client):
with patch.object(processor, '_normalize_audio_files'):
result = processor._process_audio_separation_remote(
input_file, "Test - Song", temp_dir, "http://fake-api",
)
# Should find vocals and instrumental by known filenames
assert result["clean_instrumental"]["vocals"] == vocals_path
assert "mixed_instrumental" in result["clean_instrumental"]["instrumental"]
# ==================== P1: Screens Worker Prerequisites ====================
class TestScreensWorkerPrerequisites:
"""
Test that screens worker no longer requires audio_complete.
"""
def test_validate_prerequisites_passes_without_audio(self):
"""Screens can generate with only lyrics_complete (audio still in progress)."""
from backend.workers.screens_worker import _validate_prerequisites
job = _make_job(state_data={"lyrics_complete": True, "audio_complete": False})
assert _validate_prerequisites(job) is True
def test_validate_prerequisites_passes_with_both(self):
"""Normal case: both audio and lyrics complete."""
from backend.workers.screens_worker import _validate_prerequisites
job = _make_job(state_data={"lyrics_complete": True, "audio_complete": True})
assert _validate_prerequisites(job) is True
def test_validate_prerequisites_fails_without_lyrics(self):
"""Missing lyrics_complete should fail."""
from backend.workers.screens_worker import _validate_prerequisites
job = _make_job(state_data={"lyrics_complete": False, "audio_complete": True})
assert _validate_prerequisites(job) is False
def test_validate_prerequisites_fails_with_empty_state(self):
"""Empty state_data should fail."""
from backend.workers.screens_worker import _validate_prerequisites
job = _make_job(state_data={})
assert _validate_prerequisites(job) is False
def test_validate_prerequisites_fails_without_theme(self):
"""Missing theme_id should fail."""
from backend.workers.screens_worker import _validate_prerequisites
job = _make_job(state_data={"lyrics_complete": True}, theme_id=None)
assert _validate_prerequisites(job) is False
def test_validate_prerequisites_fails_without_artist_title(self):
"""Missing artist or title should fail."""
from backend.workers.screens_worker import _validate_prerequisites
job = _make_job(state_data={"lyrics_complete": True}, artist="", title="Test")
assert _validate_prerequisites(job) is False
# ==================== GCS URI Passthrough ====================
class TestGCSURIPassthrough:
"""
Test that Stage 1 uses gcs_uri when input_gcs_uri is set on the processor.
Fixes 413 Request Entity Too Large for large FLAC files.
"""
def test_stage1_uses_gcs_uri_when_set(self):
"""When input_gcs_uri is set, Stage 1 passes gcs_uri instead of file_path."""
from karaoke_gen.audio_processor import AudioProcessor
import logging
processor = AudioProcessor(
logger=logging.getLogger("test"),
log_level=logging.INFO,
log_formatter=None,
model_file_dir=None,
lossless_output_format="FLAC",
clean_instrumental_model="test.ckpt",
backing_vocals_models=[],
other_stems_models=[],
ffmpeg_base_command="ffmpeg",
)
processor.instrumental_preset = "instrumental_clean"
processor.karaoke_preset = None
processor.job_id = "gcs-test-001"
processor.input_gcs_uri = "gs://karaoke-gen-storage-nomadkaraoke/jobs/gcs-test-001/input/song.flac"
mock_client = Mock()
with tempfile.TemporaryDirectory() as temp_dir:
stems_dir = os.path.join(temp_dir, "stems")
os.makedirs(stems_dir)
for name in ["gcs-test-001_mixed_vocals.flac", "gcs-test-001_mixed_instrumental.flac"]:
with open(os.path.join(stems_dir, name), "w") as f:
f.write("fake audio")
mock_client.separate_audio_and_wait.return_value = {
"status": "completed",
"downloaded_files": [
os.path.join(stems_dir, "gcs-test-001_mixed_vocals.flac"),
os.path.join(stems_dir, "gcs-test-001_mixed_instrumental.flac"),
],
"files": {},
}
input_file = os.path.join(temp_dir, "song.flac")
with open(input_file, "w") as f:
f.write("fake input")
with patch.object(processor, '_create_stems_directory', return_value=stems_dir):
with patch.object(processor, '_normalize_audio_files'):
with patch('karaoke_gen.audio_processor.AudioSeparatorAPIClient', return_value=mock_client):
processor._process_audio_separation_remote(
input_file, "Test - Song", temp_dir, "http://fake-api",
)
# Verify gcs_uri was passed instead of file_path
call_kwargs = mock_client.separate_audio_and_wait.call_args[1]
assert call_kwargs["gcs_uri"] == "gs://karaoke-gen-storage-nomadkaraoke/jobs/gcs-test-001/input/song.flac"
# Verify file_path was NOT passed as a positional arg
call_args = mock_client.separate_audio_and_wait.call_args[0]
assert len(call_args) == 0
def test_stage1_uses_file_upload_when_no_gcs_uri(self):
"""When input_gcs_uri is not set, Stage 1 uses file upload as before."""
from karaoke_gen.audio_processor import AudioProcessor
import logging
processor = AudioProcessor(
logger=logging.getLogger("test"),
log_level=logging.INFO,
log_formatter=None,
model_file_dir=None,
lossless_output_format="FLAC",
clean_instrumental_model="test.ckpt",
backing_vocals_models=[],
other_stems_models=[],
ffmpeg_base_command="ffmpeg",
)
processor.instrumental_preset = "instrumental_clean"
processor.karaoke_preset = None
processor.job_id = "file-test-001"
# No input_gcs_uri set
mock_client = Mock()
with tempfile.TemporaryDirectory() as temp_dir:
stems_dir = os.path.join(temp_dir, "stems")
os.makedirs(stems_dir)
for name in ["file-test-001_mixed_vocals.flac", "file-test-001_mixed_instrumental.flac"]:
with open(os.path.join(stems_dir, name), "w") as f:
f.write("fake audio")
mock_client.separate_audio_and_wait.return_value = {
"status": "completed",
"downloaded_files": [
os.path.join(stems_dir, "file-test-001_mixed_vocals.flac"),
os.path.join(stems_dir, "file-test-001_mixed_instrumental.flac"),
],
"files": {},
}
input_file = os.path.join(temp_dir, "song.flac")
with open(input_file, "w") as f:
f.write("fake input")
with patch.object(processor, '_create_stems_directory', return_value=stems_dir):
with patch.object(processor, '_normalize_audio_files'):
with patch('karaoke_gen.audio_processor.AudioSeparatorAPIClient', return_value=mock_client):
processor._process_audio_separation_remote(
input_file, "Test - Song", temp_dir, "http://fake-api",
)
# Verify file_path was passed as positional arg (old behavior)
call_args = mock_client.separate_audio_and_wait.call_args[0]
assert call_args[0] == input_file
# Verify gcs_uri was NOT in kwargs
call_kwargs = mock_client.separate_audio_and_wait.call_args[1]
assert "gcs_uri" not in call_kwargs
+781
View File
@@ -0,0 +1,781 @@
"""
Tests for processing_metadata field and related functionality.
Covers:
- Job model has processing_metadata field
- processing_metadata is in SUMMARY_FIELD_PATHS (regression test)
- update_processing_metadata helper works correctly
- AudioShake transcriber stores asset_id in metadata
- Corrector passes through transcription metadata
- extract_request_metadata includes auth context when provided
"""
import pytest
from unittest.mock import MagicMock, patch
from datetime import datetime
from backend.models.job import Job, JobStatus
class TestProcessingMetadataField:
"""Test the processing_metadata field on the Job model."""
def test_job_has_processing_metadata_field(self):
"""processing_metadata should exist and default to empty dict."""
job = Job(
job_id="test-123",
status=JobStatus.PENDING,
created_at=datetime.utcnow(),
updated_at=datetime.utcnow(),
)
assert hasattr(job, 'processing_metadata')
assert job.processing_metadata == {}
def test_processing_metadata_serializes(self):
"""processing_metadata should serialize to JSON correctly."""
job = Job(
job_id="test-123",
status=JobStatus.PENDING,
created_at=datetime.utcnow(),
updated_at=datetime.utcnow(),
processing_metadata={
"transcription": {
"provider": "audioshake",
"audioshake_task_id": "task-abc",
"audioshake_asset_id": "asset-xyz",
},
},
)
data = job.model_dump(mode='json')
assert data['processing_metadata']['transcription']['audioshake_task_id'] == "task-abc"
assert data['processing_metadata']['transcription']['audioshake_asset_id'] == "asset-xyz"
def test_processing_metadata_deserializes(self):
"""processing_metadata should deserialize from dict correctly."""
data = {
"job_id": "test-123",
"status": "pending",
"created_at": datetime.utcnow(),
"updated_at": datetime.utcnow(),
"processing_metadata": {
"separation": {
"provider": "modal",
"duration_seconds": 420.5,
},
},
}
job = Job(**data)
assert job.processing_metadata["separation"]["provider"] == "modal"
assert job.processing_metadata["separation"]["duration_seconds"] == 420.5
class TestSummaryFieldPaths:
"""Regression tests for SUMMARY_FIELD_PATHS."""
def test_processing_metadata_in_summary_field_paths(self):
"""processing_metadata must be in SUMMARY_FIELD_PATHS for dashboard queries."""
from backend.services.firestore_service import FirestoreService
assert 'processing_metadata' in FirestoreService.SUMMARY_FIELD_PATHS
class TestUpdateProcessingMetadata:
"""Test the JobManager.update_processing_metadata helper."""
@patch('backend.services.job_manager.FirestoreService')
@patch('backend.services.job_manager.StorageService')
def test_update_processing_metadata_uses_dot_notation(self, mock_storage_cls, mock_firestore_cls):
"""update_processing_metadata should use Firestore dot-notation for nested updates."""
from backend.services.job_manager import JobManager
mock_firestore = MagicMock()
mock_firestore_cls.return_value = mock_firestore
jm = JobManager()
jm.update_processing_metadata("job-123", "transcription", {
"provider": "audioshake",
"audioshake_task_id": "task-abc",
})
# Should call update_job with dot-notation key
mock_firestore.update_job.assert_called_once()
call_args = mock_firestore.update_job.call_args
assert call_args[0][0] == "job-123"
updates = call_args[0][1]
assert "processing_metadata.transcription" in updates
assert updates["processing_metadata.transcription"]["provider"] == "audioshake"
@patch('backend.services.job_manager.FirestoreService')
@patch('backend.services.job_manager.StorageService')
def test_update_processing_metadata_deep_dot_notation(self, mock_storage_cls, mock_firestore_cls):
"""Deeper dot-notation paths (e.g. timing.worker_seconds) avoid overwriting sibling fields."""
from backend.services.job_manager import JobManager
mock_firestore = MagicMock()
mock_firestore_cls.return_value = mock_firestore
jm = JobManager()
jm.update_processing_metadata("job-123", "timing.lyrics_worker_seconds", 42.5)
call_args = mock_firestore.update_job.call_args
updates = call_args[0][1]
assert "processing_metadata.timing.lyrics_worker_seconds" in updates
assert updates["processing_metadata.timing.lyrics_worker_seconds"] == 42.5
@patch('backend.services.job_manager.FirestoreService')
@patch('backend.services.job_manager.StorageService')
def test_update_processing_metadata_swallows_errors(self, mock_storage_cls, mock_firestore_cls):
"""update_processing_metadata should not raise on failure."""
from backend.services.job_manager import JobManager
mock_firestore = MagicMock()
mock_firestore.update_job.side_effect = Exception("Firestore error")
mock_firestore_cls.return_value = mock_firestore
jm = JobManager()
# Should not raise
jm.update_processing_metadata("job-123", "timing", {"foo": 1})
class TestAudioShakeAssetId:
"""Test that AudioShake transcriber stores asset_id in metadata."""
def test_convert_result_format_includes_asset_id(self):
"""_convert_result_format should include asset_id from task_data.assetId."""
from karaoke_gen.lyrics_transcriber.transcribers.audioshake import AudioShakeTranscriber
# Create a minimal transcriber instance
transcriber = AudioShakeTranscriber.__new__(AudioShakeTranscriber)
transcriber.logger = MagicMock()
transcriber._last_asset_id = "fallback-asset-id"
raw_data = {
"task_data": {
"id": "task-123",
"assetId": "asset-456",
"duration": 120.5,
"targets": [],
},
"transcription": {
"text": "hello world",
"lines": [
{
"text": "hello world",
"words": [
{"text": "hello", "start": 0.0, "end": 0.5},
{"text": "world", "start": 0.6, "end": 1.0},
],
}
],
"metadata": {"language": "en"},
},
}
result = transcriber._convert_result_format(raw_data)
assert result.metadata["task_id"] == "task-123"
assert result.metadata["asset_id"] == "asset-456"
assert result.metadata["language"] == "en"
def test_convert_result_format_fallback_asset_id(self):
"""asset_id should fall back to _last_asset_id if not in task_data."""
from karaoke_gen.lyrics_transcriber.transcribers.audioshake import AudioShakeTranscriber
transcriber = AudioShakeTranscriber.__new__(AudioShakeTranscriber)
transcriber.logger = MagicMock()
transcriber._last_asset_id = "fallback-asset-id"
raw_data = {
"task_data": {
"id": "task-123",
# No assetId in task_data
"targets": [],
},
"transcription": {
"text": "hello",
"lines": [
{
"text": "hello",
"words": [{"text": "hello", "start": 0.0, "end": 0.5}],
}
],
"metadata": {},
},
}
result = transcriber._convert_result_format(raw_data)
assert result.metadata["asset_id"] == "fallback-asset-id"
class TestCorrectorMetadataPassthrough:
"""Test that corrector passes through transcription metadata."""
def test_correction_result_includes_transcription_metadata(self):
"""CorrectionResult.metadata should include transcription_metadata from primary transcription."""
from karaoke_gen.lyrics_transcriber.correction.corrector import LyricsCorrector
from karaoke_gen.lyrics_transcriber.types import (
TranscriptionResult, TranscriptionData, LyricsSegment, Word
)
# Create a minimal corrector
corrector = LyricsCorrector(cache_dir="/tmp", enabled_handlers=[])
# Create transcription result with metadata
word = Word(id="w1", text="hello", start_time=0.0, end_time=0.5)
segment = LyricsSegment(id="s1", text="hello", words=[word], start_time=0.0, end_time=0.5)
transcription_data = TranscriptionData(
text="hello",
words=[word],
segments=[segment],
source="AudioShake",
metadata={
"task_id": "task-123",
"asset_id": "asset-456",
"language": "en",
},
)
transcription_result = TranscriptionResult(
name="AudioShake",
priority=1,
result=transcription_data,
)
# Run corrector with no reference lyrics (will skip correction but still build result)
result = corrector.run(
transcription_results=[transcription_result],
lyrics_results={},
)
# Check that transcription_metadata is passed through
assert "transcription_metadata" in result.metadata
assert result.metadata["transcription_metadata"]["task_id"] == "task-123"
assert result.metadata["transcription_metadata"]["asset_id"] == "asset-456"
class TestExtractRequestMetadataAuthContext:
"""Test that extract_request_metadata includes auth context."""
def _make_request(self):
"""Create a minimal mock request."""
request = MagicMock()
request.headers = {
"user-agent": "test-agent",
"x-forwarded-for": "1.2.3.4",
}
request.client = MagicMock()
request.client.host = "127.0.0.1"
return request
def test_auth_context_included_when_provided(self):
"""Auth context should be in metadata when auth_result is provided."""
from backend.api.routes.file_upload import extract_request_metadata
auth_result = MagicMock()
auth_result.auth_method = "session"
auth_result.user_type = MagicMock()
auth_result.user_type.value = "unlimited"
auth_result.remaining_uses = 42
metadata = extract_request_metadata(self._make_request(), auth_result=auth_result)
assert metadata['auth_method'] == "session"
assert metadata['user_type'] == "unlimited"
assert metadata['credits_at_creation'] == 42
def test_no_auth_context_without_auth_result(self):
"""No auth context should be added when auth_result is None."""
from backend.api.routes.file_upload import extract_request_metadata
metadata = extract_request_metadata(self._make_request())
assert 'auth_method' not in metadata
assert 'user_type' not in metadata
assert 'credits_at_creation' not in metadata
def test_audio_search_extract_includes_auth(self):
"""audio_search extract_request_metadata should also support auth_result."""
from backend.api.routes.audio_search import extract_request_metadata
auth_result = MagicMock()
auth_result.auth_method = "api_key"
auth_result.user_type = MagicMock()
auth_result.user_type.value = "limited"
auth_result.remaining_uses = 5
metadata = extract_request_metadata(self._make_request(), auth_result=auth_result)
assert metadata['auth_method'] == "api_key"
assert metadata['user_type'] == "limited"
assert metadata['credits_at_creation'] == 5
def test_auth_without_remaining_uses(self):
"""Should handle auth_result with no remaining_uses (e.g., admin)."""
from backend.api.routes.file_upload import extract_request_metadata
auth_result = MagicMock(spec=['auth_method', 'user_type'])
auth_result.auth_method = "admin_token"
auth_result.user_type = MagicMock()
auth_result.user_type.value = "admin"
metadata = extract_request_metadata(self._make_request(), auth_result=auth_result)
assert metadata['auth_method'] == "admin_token"
assert metadata['user_type'] == "admin"
assert 'credits_at_creation' not in metadata
def test_auth_with_none_user_type(self):
"""Should handle auth_result where user_type is None."""
from backend.api.routes.file_upload import extract_request_metadata
auth_result = MagicMock()
auth_result.auth_method = "session"
auth_result.user_type = None
auth_result.remaining_uses = 10
metadata = extract_request_metadata(self._make_request(), auth_result=auth_result)
assert metadata['auth_method'] == "session"
assert metadata['user_type'] is None
assert metadata['credits_at_creation'] == 10
class TestStoreLyricsProcessingMetadata:
"""Test the _store_lyrics_processing_metadata helper function."""
def test_extracts_audioshake_ids_from_corrections(self, tmp_path):
"""Should extract task_id and asset_id from corrections.json metadata."""
import json
from backend.workers.lyrics_worker import _store_lyrics_processing_metadata
# Create a mock corrections file
lyrics_dir = tmp_path / "lyrics"
lyrics_dir.mkdir()
corrections_file = lyrics_dir / "Artist - Title (Lyrics Corrections).json"
corrections_data = {
"metadata": {
"transcription_metadata": {
"task_id": "task-abc",
"asset_id": "asset-xyz",
"language": "en",
},
"enabled_handlers": ["anchor_sequence", "gap_word_count"],
"correction_ratio": 0.95,
"total_words": 100,
"agentic_routing": "rule-based",
"anchor_sequences_count": 5,
"gap_sequences_count": 3,
},
"corrections_made": 5,
"corrected_segments": [
{"words": [{"text": "w1"}, {"text": "w2"}]},
{"words": [{"text": "w3"}]},
],
"reference_lyrics": {"genius": {}, "spotify": {}},
}
corrections_file.write_text(json.dumps(corrections_data))
job_manager = MagicMock()
job_log = MagicMock()
_store_lyrics_processing_metadata(
job_manager=job_manager,
job_id="test-job",
transcription_result={"lyrics_dir": str(lyrics_dir)},
transcription_duration=45.6,
cache_stats={"downloaded": 2, "not_found": 1},
job_log=job_log,
)
# Check transcription metadata was stored
transcription_call = [
c for c in job_manager.update_processing_metadata.call_args_list
if c[0][1] == "transcription"
]
assert len(transcription_call) == 1
trans_data = transcription_call[0][0][2]
assert trans_data["provider"] == "audioshake"
assert trans_data["audioshake_task_id"] == "task-abc"
assert trans_data["audioshake_asset_id"] == "asset-xyz"
assert trans_data["segment_count"] == 2
assert trans_data["word_count"] == 3
assert trans_data["duration_seconds"] == 45.6
# Check correction metadata was stored
correction_call = [
c for c in job_manager.update_processing_metadata.call_args_list
if c[0][1] == "correction"
]
assert len(correction_call) == 1
corr_data = correction_call[0][0][2]
assert corr_data["corrections_made"] == 5
assert corr_data["handlers_applied"] == ["anchor_sequence", "gap_word_count"]
assert corr_data["reference_sources_found"] == ["genius", "spotify"]
# Check cache stats were stored
cache_call = [
c for c in job_manager.update_processing_metadata.call_args_list
if c[0][1] == "cache"
]
assert len(cache_call) == 1
cache_data = cache_call[0][0][2]
assert cache_data["transcription_cache_downloaded"] == 2
assert cache_data["transcription_cache_not_found"] == 1
def test_handles_missing_corrections_file(self):
"""Should not raise when corrections file is not found."""
from backend.workers.lyrics_worker import _store_lyrics_processing_metadata
job_manager = MagicMock()
job_log = MagicMock()
_store_lyrics_processing_metadata(
job_manager=job_manager,
job_id="test-job",
transcription_result={"lyrics_dir": "/nonexistent/path"},
transcription_duration=30.0,
cache_stats=None,
job_log=job_log,
)
# Should still store duration even without corrections file
transcription_call = [
c for c in job_manager.update_processing_metadata.call_args_list
if c[0][1] == "transcription"
]
assert len(transcription_call) == 1
assert transcription_call[0][0][2]["duration_seconds"] == 30.0
def test_swallows_exceptions(self):
"""Should not raise on unexpected errors."""
from backend.workers.lyrics_worker import _store_lyrics_processing_metadata
job_manager = MagicMock()
job_manager.update_processing_metadata.side_effect = Exception("boom")
job_log = MagicMock()
# Should not raise
_store_lyrics_processing_metadata(
job_manager=job_manager,
job_id="test-job",
transcription_result={"lyrics_dir": ""},
transcription_duration=10.0,
cache_stats=None,
job_log=job_log,
)
job_log.warning.assert_called()
def test_no_audioshake_ids_when_lyrics_dir_missing(self):
"""Without lyrics_dir, corrections.json can't be found — only duration is stored.
This is the exact bug that shipped in v0.142.0: transcribe_lyrics() didn't
include lyrics_dir in its return dict, so _store_lyrics_processing_metadata
could never find the corrections file and AudioShake IDs were silently lost.
"""
from backend.workers.lyrics_worker import _store_lyrics_processing_metadata
job_manager = MagicMock()
job_log = MagicMock()
# Simulate the pre-fix result dict — no lyrics_dir key at all
_store_lyrics_processing_metadata(
job_manager=job_manager,
job_id="test-job",
transcription_result={"lrc_filepath": "/tmp/output.lrc"}, # no lyrics_dir!
transcription_duration=45.0,
cache_stats=None,
job_log=job_log,
)
# Only duration should be stored — no AudioShake IDs, no correction stats
transcription_call = [
c for c in job_manager.update_processing_metadata.call_args_list
if c[0][1] == "transcription"
]
assert len(transcription_call) == 1
trans_data = transcription_call[0][0][2]
assert trans_data["duration_seconds"] == 45.0
assert "audioshake_task_id" not in trans_data
assert "provider" not in trans_data
# No correction metadata should be stored
correction_calls = [
c for c in job_manager.update_processing_metadata.call_args_list
if c[0][1] == "correction"
]
assert len(correction_calls) == 0
class TestTranscribeLyricsReturnsLyricsDir:
"""Contract test: transcribe_lyrics() must include lyrics_dir in its return dict.
This is the test that would have caught the v0.142.0 bug. The previous test suite
only tested _store_lyrics_processing_metadata in isolation with a hand-crafted input
that included lyrics_dir — it never verified the actual caller provides that key.
Testing lesson: When function A calls function B, don't just test B with ideal inputs.
Also verify A actually produces those inputs. Test the contract between caller and callee.
"""
@patch('karaoke_gen.lyrics_processor.LyricsTranscriber')
@patch('karaoke_gen.lyrics_processor.load_dotenv')
def test_transcribe_lyrics_returns_lyrics_dir(self, mock_dotenv, mock_transcriber_cls, tmp_path):
"""transcribe_lyrics() result must contain lyrics_dir pointing to the lyrics subdirectory."""
from karaoke_gen.lyrics_processor import LyricsProcessor
# Set up mock transcriber result
mock_results = MagicMock()
mock_results.lrc_filepath = str(tmp_path / "lyrics" / "output.lrc")
mock_results.ass_filepath = str(tmp_path / "lyrics" / "output.ass")
mock_results.video_filepath = str(tmp_path / "lyrics" / "output.mkv")
mock_results.transcription_corrected = None # skip correction output
mock_results.countdown_padding_added = False
mock_results.countdown_padding_seconds = 0.0
mock_results.padded_audio_filepath = None
mock_transcriber_cls.return_value.process.return_value = mock_results
# Create necessary dirs and a dummy audio file
lyrics_dir = tmp_path / "lyrics"
lyrics_dir.mkdir(exist_ok=True)
(tmp_path / "lyrics" / "output.lrc").write_text("[00:00.00] test")
(tmp_path / "lyrics" / "output.mkv").write_bytes(b"fake")
lrc_dest = tmp_path / "Artist - Title (Karaoke).lrc"
mkv_dest = tmp_path / "Artist - Title (With Vocals).mkv"
processor = LyricsProcessor.__new__(LyricsProcessor)
processor.logger = MagicMock()
processor.lyrics_file = None
processor.render_video = False
processor.skip_transcription = False
processor.skip_transcription_review = True
processor.style_params_json = None
processor.subtitle_offset_ms = 0
with patch.dict('os.environ', {
'AUDIOSHAKE_API_TOKEN': 'fake-token',
}):
result = processor.transcribe_lyrics(
input_audio_wav=str(tmp_path / "audio.wav"),
artist="Artist",
title="Title",
track_output_dir=str(tmp_path),
)
# THE KEY ASSERTION: lyrics_dir must be in the result
assert "lyrics_dir" in result, (
"transcribe_lyrics() must return lyrics_dir so _store_lyrics_processing_metadata "
"can find corrections.json. This was the v0.142.0 bug."
)
assert result["lyrics_dir"] == str(tmp_path / "lyrics")
def test_lyrics_dir_matches_corrections_file_location(self, tmp_path):
"""The lyrics_dir returned by transcribe_lyrics must be where corrections.json lives.
This verifies the contract: _store_lyrics_processing_metadata looks for corrections
files in result['lyrics_dir'], and transcribe_lyrics writes them to {track_output_dir}/lyrics.
"""
import json
from backend.workers.lyrics_worker import _store_lyrics_processing_metadata
# Simulate a result dict with lyrics_dir set correctly
lyrics_dir = tmp_path / "lyrics"
lyrics_dir.mkdir()
# Write a corrections file in the same location transcribe_lyrics would
corrections_file = lyrics_dir / "Artist - Title (Lyrics Corrections).json"
corrections_file.write_text(json.dumps({
"metadata": {
"transcription_metadata": {"task_id": "t1", "asset_id": "a1"},
"enabled_handlers": [],
},
"corrections_made": 0,
"corrected_segments": [],
}))
job_manager = MagicMock()
job_log = MagicMock()
# Use the result dict shape that transcribe_lyrics now produces
_store_lyrics_processing_metadata(
job_manager=job_manager,
job_id="test-job",
transcription_result={
"lyrics_dir": str(lyrics_dir),
"lrc_filepath": str(tmp_path / "output.lrc"),
},
transcription_duration=30.0,
cache_stats=None,
job_log=job_log,
)
# AudioShake IDs should be extracted successfully
transcription_call = [
c for c in job_manager.update_processing_metadata.call_args_list
if c[0][1] == "transcription"
]
assert len(transcription_call) == 1
trans_data = transcription_call[0][0][2]
assert trans_data["provider"] == "audioshake"
assert trans_data["audioshake_task_id"] == "t1"
assert trans_data["audioshake_asset_id"] == "a1"
class TestStoreAudioSourceMetadata:
"""Test the _store_audio_source_metadata helper function."""
@patch('subprocess.run')
def test_parses_ffprobe_output(self, mock_run):
"""Should parse ffprobe JSON output and store audio properties."""
import json
from backend.workers.audio_worker import _store_audio_source_metadata
mock_run.return_value = MagicMock(
returncode=0,
stdout=json.dumps({
"format": {
"format_name": "flac",
"duration": "210.4",
"size": "26541900",
"bit_rate": "1008000",
},
"streams": [
{
"codec_type": "audio",
"codec_name": "flac",
"sample_rate": "44100",
"channels": 2,
"bits_per_raw_sample": "16",
}
],
}),
)
job_manager = MagicMock()
job_log = MagicMock()
_store_audio_source_metadata(job_manager, "job-123", "/fake/audio.flac", job_log)
job_manager.update_processing_metadata.assert_called_once()
call_args = job_manager.update_processing_metadata.call_args
assert call_args[0][1] == "audio_source"
data = call_args[0][2]
assert data["input_format"] == "flac"
assert data["input_codec"] == "flac"
assert data["input_sample_rate"] == 44100
assert data["input_channels"] == 2
assert data["input_bit_depth"] == 16
assert data["input_duration_seconds"] == 210.4
assert data["input_file_size_bytes"] == 26541900
assert data["input_bitrate_kbps"] == 1008
@patch('subprocess.run')
def test_handles_ffprobe_failure(self, mock_run):
"""Should not raise when ffprobe fails."""
from backend.workers.audio_worker import _store_audio_source_metadata
mock_run.return_value = MagicMock(returncode=1, stderr="No such file")
job_manager = MagicMock()
job_log = MagicMock()
_store_audio_source_metadata(job_manager, "job-123", "/bad/path", job_log)
job_manager.update_processing_metadata.assert_not_called()
job_log.warning.assert_called()
@patch('subprocess.run')
def test_handles_missing_audio_stream(self, mock_run):
"""Should handle files with no audio stream gracefully."""
import json
from backend.workers.audio_worker import _store_audio_source_metadata
mock_run.return_value = MagicMock(
returncode=0,
stdout=json.dumps({
"format": {"format_name": "mp4", "duration": "30.0", "size": "1000"},
"streams": [{"codec_type": "video", "codec_name": "h264"}],
}),
)
job_manager = MagicMock()
job_log = MagicMock()
_store_audio_source_metadata(job_manager, "job-123", "/fake/video.mp4", job_log)
job_manager.update_processing_metadata.assert_called_once()
data = job_manager.update_processing_metadata.call_args[0][2]
# Should have format-level data but no audio stream data
assert data["input_format"] == "mp4"
assert "input_codec" not in data
class TestStoreVideoProcessingMetadata:
"""Test the _store_video_processing_metadata helper function."""
def test_stores_encoding_and_distribution_metadata(self, tmp_path):
"""Should store encoding time, formats, and distribution info."""
from backend.workers.video_worker import _store_video_processing_metadata
# Create mock result with some files existing
result = MagicMock()
result.encoding_time_seconds = 180.5
result.youtube_url = "https://youtube.com/watch?v=abc"
result.youtube_upload_queued = False
result.dropbox_link = "https://dropbox.com/s/xxx"
result.gdrive_files = {"4k": "file-id-1"}
result.brand_code = "NOMAD0001"
# Create a temp file to simulate output
lossless = tmp_path / "output.mp4"
lossless.write_bytes(b"x" * 1000)
result.final_video = str(lossless)
result.final_video_mkv = None
result.final_video_lossy = None
result.final_video_720p = None
job_manager = MagicMock()
_store_video_processing_metadata(job_manager, "job-123", result, 300.0)
calls = {c[0][1]: c[0][2] for c in job_manager.update_processing_metadata.call_args_list}
# Check encoding
assert "encoding" in calls
assert calls["encoding"]["encoding_time_seconds"] == 180.5
assert "lossless_4k_mp4" in calls["encoding"]["output_formats"]
assert calls["encoding"]["output_sizes_bytes"]["lossless_4k_mp4"] == 1000
# Check distribution
assert "distribution" in calls
assert calls["distribution"]["youtube_video_url"] == "https://youtube.com/watch?v=abc"
assert calls["distribution"]["brand_code"] == "NOMAD0001"
assert calls["distribution"]["gdrive_file_count"] == 1
# Check timing (uses deep dot-notation to avoid overwriting other workers' timing)
assert "timing.video_worker_seconds" in calls
assert calls["timing.video_worker_seconds"] == 300.0
def test_swallows_exceptions(self):
"""Should not raise on errors."""
from backend.workers.video_worker import _store_video_processing_metadata
job_manager = MagicMock()
job_manager.update_processing_metadata.side_effect = Exception("boom")
result = MagicMock()
result.encoding_time_seconds = None
# Should not raise
_store_video_processing_metadata(job_manager, "job-123", result, 100.0)
class TestAudioShakeStartTranscriptionAssetId:
"""Test that start_transcription stores _last_asset_id."""
def test_start_transcription_stores_last_asset_id(self):
"""start_transcription should store _last_asset_id for metadata fallback."""
from karaoke_gen.lyrics_transcriber.transcribers.audioshake import AudioShakeTranscriber
transcriber = AudioShakeTranscriber.__new__(AudioShakeTranscriber)
transcriber.logger = MagicMock()
# Mock the API and upload optimizer
transcriber.api = MagicMock()
transcriber.api.upload_file.return_value = "asset-from-upload"
transcriber.api.create_task.return_value = "task-from-create"
transcriber.upload_optimizer = MagicMock()
transcriber.upload_optimizer.prepare_for_upload.return_value = ("/fake/path", None)
task_id = transcriber.start_transcription("/fake/audio.flac")
assert task_id == "task-from-create"
assert transcriber._last_asset_id == "asset-from-upload"
+146 -7
View File
@@ -224,7 +224,38 @@ class TestRetryEndpoint:
assert has_video and has_instrumental_selection
def test_retry_checkpoint_detection_render_stage(self):
"""Test retry detects render stage checkpoint."""
"""Test retry detects render stage checkpoint when review was completed."""
job = Job(
job_id="test123",
status=JobStatus.FAILED,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test",
title="Song",
file_urls={
'lyrics': {'corrections': 'gs://bucket/path/corrections.json'},
'screens': {'title': 'gs://bucket/path/title.mov'}
},
state_data={
'instrumental_selection': 'clean'
}
)
# This job has corrections, screens, AND completed review - should retry from render
has_corrections = job.file_urls.get('lyrics', {}).get('corrections')
has_screens = job.file_urls.get('screens', {}).get('title')
has_video = job.file_urls.get('videos', {}).get('with_vocals')
has_review = (job.state_data or {}).get('instrumental_selection')
assert has_corrections and has_screens and not has_video and has_review
def test_retry_checkpoint_returns_to_review_when_not_completed(self):
"""Test retry returns to awaiting_review when corrections and screens exist
but user never completed the review (no instrumental_selection).
Regression test: previously, retry would skip to REVIEW_COMPLETE based solely
on corrections.json + title.mov existing, but these are auto-generated artifacts
that exist BEFORE the user reviews anything.
"""
job = Job(
job_id="test123",
status=JobStatus.FAILED,
@@ -236,13 +267,15 @@ class TestRetryEndpoint:
'lyrics': {'corrections': 'gs://bucket/path/corrections.json'},
'screens': {'title': 'gs://bucket/path/title.mov'}
}
# No state_data.instrumental_selection — review was never completed
)
# This job has corrections and screens - should retry from render
# Has corrections and screens but NO review completion
has_corrections = job.file_urls.get('lyrics', {}).get('corrections')
has_screens = job.file_urls.get('screens', {}).get('title')
has_video = job.file_urls.get('videos', {}).get('with_vocals')
assert has_corrections and has_screens and not has_video
has_review = (job.state_data or {}).get('instrumental_selection')
# Should match the "awaiting_review" checkpoint, NOT "render"
assert has_corrections and has_screens and not has_review
def test_retry_checkpoint_detection_from_beginning(self):
"""Test retry detects need to restart from beginning."""
@@ -446,6 +479,20 @@ class TestSummaryEndpoint:
assert _prune_state_data({}) == {}
assert _prune_state_data({'state_data': None}) == {'state_data': None}
def test_summary_projection_includes_source_fields(self):
"""Verify SUMMARY_FIELD_PATHS includes audio source tracking fields.
These fields are required for the Source column in the admin dashboard
and the source details modal. Without them, the dashboard incorrectly
shows audio search jobs as file uploads when audio_search_artist/title
are null.
"""
from backend.services.firestore_service import FirestoreService
paths = FirestoreService.SUMMARY_FIELD_PATHS
for field in ['url', 'filename', 'audio_search_artist', 'audio_search_title',
'audio_source_type', 'source_name', 'source_id', 'target_file', 'download_url']:
assert field in paths, f"{field} must be in summary projection for source details modal"
def test_prune_file_urls_keeps_allowed_keys(self):
"""Verify _prune_file_urls keeps only dashboard-required keys."""
from backend.api.routes.jobs import _prune_file_urls
@@ -511,14 +558,14 @@ class TestSummaryEndpoint:
assert list(result['file_urls'].keys()) == ['finals']
def test_hide_completed_statuses(self):
"""Verify _HIDE_COMPLETED_STATUSES only hides successful completions (not failed/cancelled)."""
"""Verify _HIDE_COMPLETED_STATUSES hides terminal statuses (not failed or active)."""
from backend.api.routes.jobs import _HIDE_COMPLETED_STATUSES
assert 'complete' in _HIDE_COMPLETED_STATUSES
assert 'prep_complete' in _HIDE_COMPLETED_STATUSES
# Failed/cancelled should NOT be hidden - users need to see these
assert 'cancelled' in _HIDE_COMPLETED_STATUSES
# Failed should NOT be hidden - users need to see these
assert 'failed' not in _HIDE_COMPLETED_STATUSES
assert 'cancelled' not in _HIDE_COMPLETED_STATUSES
# Active statuses should NOT be in the list
assert 'pending' not in _HIDE_COMPLETED_STATUSES
assert 'downloading' not in _HIDE_COMPLETED_STATUSES
@@ -689,3 +736,95 @@ class TestContentDispositionHeader:
decoded = unquote(utf8_part)
assert decoded == "周杰倫 - 青花瓷.mp4"
class TestSearchFiltering:
"""Tests for the search parameter on list_jobs summary mode."""
def _make_job_dict(self, job_id="job1", artist="Queen", title="Bohemian Rhapsody",
audio_search_artist=None, audio_search_title=None, status="complete"):
return {
"job_id": job_id,
"artist": artist,
"title": title,
"audio_search_artist": audio_search_artist,
"audio_search_title": audio_search_title,
"status": status,
"user_email": "admin@nomadkaraoke.com",
}
def test_search_filters_by_artist(self):
"""Search 'queen' should match job with artist='Queen'."""
from backend.api.routes.jobs import _search_filter_jobs
jobs = [
self._make_job_dict(job_id="j1", artist="Queen", title="We Will Rock You"),
self._make_job_dict(job_id="j2", artist="Eagles", title="Hotel California"),
]
result = _search_filter_jobs(jobs, "queen")
assert len(result) == 1
assert result[0]["job_id"] == "j1"
def test_search_filters_by_title(self):
"""Search 'california' should match job with title containing it."""
from backend.api.routes.jobs import _search_filter_jobs
jobs = [
self._make_job_dict(job_id="j1", artist="Queen", title="We Will Rock You"),
self._make_job_dict(job_id="j2", artist="Eagles", title="Hotel California"),
]
result = _search_filter_jobs(jobs, "california")
assert len(result) == 1
assert result[0]["job_id"] == "j2"
def test_search_filters_by_job_id(self):
"""Search by partial job_id."""
from backend.api.routes.jobs import _search_filter_jobs
jobs = [
self._make_job_dict(job_id="abc-123-def"),
self._make_job_dict(job_id="xyz-789-ghi"),
]
result = _search_filter_jobs(jobs, "abc-123")
assert len(result) == 1
assert result[0]["job_id"] == "abc-123-def"
def test_search_filters_by_audio_search_fields(self):
"""Search should also check audio_search_artist and audio_search_title."""
from backend.api.routes.jobs import _search_filter_jobs
jobs = [
self._make_job_dict(job_id="j1", artist="Display Name", title="Display Title",
audio_search_artist="Original Artist", audio_search_title="Original Song"),
]
result = _search_filter_jobs(jobs, "original artist")
assert len(result) == 1
def test_search_is_case_insensitive(self):
"""Search should be case-insensitive."""
from backend.api.routes.jobs import _search_filter_jobs
jobs = [self._make_job_dict(artist="QUEEN", title="Bohemian Rhapsody")]
result = _search_filter_jobs(jobs, "queen")
assert len(result) == 1
def test_search_handles_none_fields(self):
"""Search should not crash on None artist/title fields."""
from backend.api.routes.jobs import _search_filter_jobs
jobs = [self._make_job_dict(artist=None, title=None)]
result = _search_filter_jobs(jobs, "queen")
assert len(result) == 0
def test_search_empty_string_returns_all(self):
"""Empty search string should return all jobs."""
from backend.api.routes.jobs import _search_filter_jobs
jobs = [
self._make_job_dict(job_id="j1"),
self._make_job_dict(job_id="j2"),
]
result = _search_filter_jobs(jobs, "")
assert len(result) == 2
def test_search_returns_all_matches_for_limit_slicing(self):
"""Search returns all matches — caller applies limit separately."""
from backend.api.routes.jobs import _search_filter_jobs
jobs = [self._make_job_dict(job_id=f"j{i}", artist="Queen", title=f"Song {i}") for i in range(10)]
result = _search_filter_jobs(jobs, "queen")
assert len(result) == 10 # All 10 match; limit slicing is caller's job
# Verify caller can slice: simulates jobs_dicts[:limit] in route handler
assert len(result[:3]) == 3
+93 -4
View File
@@ -6,6 +6,8 @@ Tests that require full backend imports are in the emulator integration tests.
"""
import pytest
import json
from datetime import datetime, UTC
from unittest.mock import MagicMock, AsyncMock, patch
class TestJobStatusTransitionsForReview:
@@ -277,6 +279,93 @@ class TestReviewResubmissionClearsWorkerProgress:
assert callable(getattr(jm, 'delete_state_data_keys'))
class TestCompleteReviewZeroSegmentValidation:
"""Tests for the 0-segment lyrics guard in complete_review endpoint.
These test the actual HTTP endpoint, not just the validation logic.
"""
@pytest.fixture
def _patched_client(self):
"""Create TestClient with mocked services for complete_review."""
from backend.models.job import Job, JobStatus
mock_job_manager = MagicMock()
mock_job_manager.transition_to_state.return_value = True
mock_worker_service = MagicMock()
mock_creds = MagicMock()
mock_creds.universe_domain = "googleapis.com"
with patch("backend.api.routes.jobs.job_manager", mock_job_manager), \
patch("backend.api.routes.jobs.worker_service", mock_worker_service), \
patch("backend.services.firestore_service.firestore"), \
patch("backend.services.storage_service.storage"), \
patch("google.auth.default", return_value=(mock_creds, "test-project")):
from backend.main import app
from fastapi.testclient import TestClient
yield TestClient(app), mock_job_manager
def _make_job(self, state_data=None):
from backend.models.job import Job, JobStatus
return Job(
job_id="job-zero-seg",
status=JobStatus.AWAITING_REVIEW,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test Artist",
title="Test Song",
state_data=state_data,
)
def test_endpoint_rejects_zero_segment_lyrics(self, _patched_client):
"""POST complete-review returns 400 when lyrics pipeline produced 0 segments."""
client, mock_jm = _patched_client
job = self._make_job(state_data={
'lyrics_metadata': {'segment_count': 0, 'ready_for_review': True},
'corrected_lyrics': {'corrected_segments': [], 'original_segments': []},
})
mock_jm.get_job.return_value = job
response = client.post(
"/api/jobs/job-zero-seg/complete-review",
headers={"Authorization": "Bearer test-admin-token"},
)
assert response.status_code == 400
assert "no lyrics were detected" in response.json()["detail"]
mock_jm.transition_to_state.assert_not_called()
def test_endpoint_allows_nonzero_segment_lyrics(self, _patched_client):
"""POST complete-review succeeds when lyrics have segments."""
client, mock_jm = _patched_client
job = self._make_job(state_data={
'lyrics_metadata': {'segment_count': 42},
'corrected_lyrics': {'corrected_segments': [{'text': 'hello'}] * 42},
})
mock_jm.get_job.return_value = job
response = client.post(
"/api/jobs/job-zero-seg/complete-review",
headers={"Authorization": "Bearer test-admin-token"},
)
assert response.status_code == 200
mock_jm.transition_to_state.assert_called_once()
def test_endpoint_allows_job_without_lyrics_metadata(self, _patched_client):
"""POST complete-review succeeds for jobs without lyrics_metadata (e.g. finalise-only)."""
client, mock_jm = _patched_client
job = self._make_job(state_data={}) # No lyrics pipeline ran
mock_jm.get_job.return_value = job
response = client.post(
"/api/jobs/job-zero-seg/complete-review",
headers={"Authorization": "Bearer test-admin-token"},
)
assert response.status_code == 200
class TestPreviewStyleLoading:
"""Tests for the unified style loader used in preview video generation.
@@ -328,13 +417,13 @@ class TestPreviewStyleLoading:
# Call the unified style loader function
style_assets = {
"style_params": "uploads/test123/style/style_params.json",
"karaoke_background": "uploads/test123/style/karaoke_background.png",
"font": "uploads/test123/style/font.ttf",
"style_params": "jobs/test123/style/style_params.json",
"karaoke_background": "jobs/test123/style/karaoke_background.png",
"font": "jobs/test123/style/font.ttf",
}
styles_path, result_styles = load_styles_from_gcs(
style_params_gcs_path="uploads/test123/style/style_params.json",
style_params_gcs_path="jobs/test123/style/style_params.json",
style_assets=style_assets,
temp_dir=str(tmp_path / "workdir"),
download_func=mock_download,
+551
View File
@@ -0,0 +1,551 @@
"""
Tests for the search-lyrics operation and API endpoint.
Covers:
- create_lyrics_providers() factory function
- CorrectionOperations.search_lyrics_sources() static method
- CorrectionOperations.add_lyrics_source() force parameter
- POST /{job_id}/search-lyrics API endpoint
"""
import pytest
import os
from unittest.mock import MagicMock, patch, call
from typing import Dict, Any, List
# ---------------------------------------------------------------------------
# Helpers / fixtures
# ---------------------------------------------------------------------------
def _make_lyrics_data(source: str = "TestSource", text: str = "Hello world\nTest line") -> "LyricsData":
"""Create a minimal LyricsData object for testing."""
from karaoke_gen.lyrics_transcriber.types import LyricsData, LyricsSegment, LyricsMetadata, Word
from karaoke_gen.lyrics_transcriber.utils.word_utils import WordUtils
segments = []
for line in text.strip().splitlines():
words = [
Word(id=WordUtils.generate_id(), text=w, start_time=None, end_time=None)
for w in line.split()
]
segments.append(
LyricsSegment(
id=WordUtils.generate_id(),
text=line,
words=words,
start_time=None,
end_time=None,
)
)
return LyricsData(source=source, segments=segments, metadata=LyricsMetadata(source=source, track_name="Test Track", artist_names="Test Artist"))
def _make_correction_result(
reference_lyrics: Dict = None,
metadata: Dict = None,
) -> "CorrectionResult":
"""Create a minimal CorrectionResult for testing."""
from karaoke_gen.lyrics_transcriber.types import (
CorrectionResult, LyricsSegment, Word, LyricsData, LyricsMetadata
)
from karaoke_gen.lyrics_transcriber.utils.word_utils import WordUtils
# A single transcription segment
word = Word(id=WordUtils.generate_id(), text="hello", start_time=0.0, end_time=0.5)
segment = LyricsSegment(id=WordUtils.generate_id(), text="hello", words=[word], start_time=0.0, end_time=0.5)
return CorrectionResult(
original_segments=[segment],
corrected_segments=[segment],
corrections=[],
corrections_made=0,
confidence=1.0,
reference_lyrics=reference_lyrics or {},
anchor_sequences=[],
gap_sequences=[],
resized_segments=None,
metadata=metadata or {"audio_hash": "testhash"},
correction_steps=[],
word_id_map={},
segment_id_map={},
)
# ---------------------------------------------------------------------------
# Tests: create_lyrics_providers factory
# ---------------------------------------------------------------------------
class TestCreateLyricsProviders:
"""Tests for the create_lyrics_providers() module-level factory."""
def test_returns_list(self):
"""Factory always returns a list."""
from karaoke_gen.lyrics_transcriber.correction.operations import create_lyrics_providers
with patch.dict(os.environ, {}, clear=False):
# Remove API keys so only LRCLIB is created
env_override = {
k: "" for k in ["GENIUS_API_KEY", "RAPIDAPI_KEY", "SPOTIFY_COOKIE_SP_DC"]
}
with patch.dict(os.environ, env_override):
providers = create_lyrics_providers(cache_dir="/tmp")
assert isinstance(providers, list)
def test_lrclib_always_included(self):
"""LRCLIBProvider is always included regardless of env vars."""
from karaoke_gen.lyrics_transcriber.correction.operations import create_lyrics_providers
with patch.dict(os.environ, {"GENIUS_API_KEY": "", "RAPIDAPI_KEY": "", "SPOTIFY_COOKIE_SP_DC": ""}):
providers = create_lyrics_providers(cache_dir="/tmp")
provider_names = [p.get_name() for p in providers]
assert "LRCLIB" in provider_names
def test_genius_included_when_genius_key_set(self):
"""GeniusProvider is included when GENIUS_API_KEY is set."""
from karaoke_gen.lyrics_transcriber.correction.operations import create_lyrics_providers
with patch.dict(os.environ, {"GENIUS_API_KEY": "fake-key", "RAPIDAPI_KEY": "", "SPOTIFY_COOKIE_SP_DC": ""}):
providers = create_lyrics_providers(cache_dir="/tmp")
provider_names = [p.get_name() for p in providers]
assert "Genius" in provider_names
def test_genius_included_when_rapidapi_key_set(self):
"""GeniusProvider is included when RAPIDAPI_KEY is set (uses RapidAPI path)."""
from karaoke_gen.lyrics_transcriber.correction.operations import create_lyrics_providers
with patch.dict(os.environ, {"GENIUS_API_KEY": "", "RAPIDAPI_KEY": "fake-rapidapi", "SPOTIFY_COOKIE_SP_DC": ""}):
providers = create_lyrics_providers(cache_dir="/tmp")
provider_names = [p.get_name() for p in providers]
assert "Genius" in provider_names
def test_spotify_included_when_cookie_set(self):
"""SpotifyProvider is included when SPOTIFY_COOKIE_SP_DC is set."""
from karaoke_gen.lyrics_transcriber.correction.operations import create_lyrics_providers
with patch.dict(os.environ, {"GENIUS_API_KEY": "", "RAPIDAPI_KEY": "", "SPOTIFY_COOKIE_SP_DC": "fake-cookie"}):
providers = create_lyrics_providers(cache_dir="/tmp")
provider_names = [p.get_name() for p in providers]
assert "Spotify" in provider_names
def test_musixmatch_included_when_rapidapi_key_set(self):
"""MusixmatchProvider is included when RAPIDAPI_KEY is set."""
from karaoke_gen.lyrics_transcriber.correction.operations import create_lyrics_providers
with patch.dict(os.environ, {"GENIUS_API_KEY": "", "RAPIDAPI_KEY": "fake-rapidapi", "SPOTIFY_COOKIE_SP_DC": ""}):
providers = create_lyrics_providers(cache_dir="/tmp")
provider_names = [p.get_name() for p in providers]
assert "Musixmatch" in provider_names
def test_genius_not_included_without_keys(self):
"""GeniusProvider is excluded when neither key is set."""
from karaoke_gen.lyrics_transcriber.correction.operations import create_lyrics_providers
with patch.dict(os.environ, {"GENIUS_API_KEY": "", "RAPIDAPI_KEY": "", "SPOTIFY_COOKIE_SP_DC": ""}):
providers = create_lyrics_providers(cache_dir="/tmp")
provider_names = [p.get_name() for p in providers]
assert "Genius" not in provider_names
def test_all_providers_when_all_keys_set(self):
"""All four providers are returned when all credentials are set."""
from karaoke_gen.lyrics_transcriber.correction.operations import create_lyrics_providers
with patch.dict(os.environ, {
"GENIUS_API_KEY": "gk",
"RAPIDAPI_KEY": "rk",
"SPOTIFY_COOKIE_SP_DC": "sc",
}):
providers = create_lyrics_providers(cache_dir="/tmp")
provider_names = [p.get_name() for p in providers]
assert "Genius" in provider_names
assert "Spotify" in provider_names
assert "Musixmatch" in provider_names
assert "LRCLIB" in provider_names
assert len(providers) == 4
# ---------------------------------------------------------------------------
# Tests: CorrectionOperations.search_lyrics_sources
# ---------------------------------------------------------------------------
class TestSearchLyricsSources:
"""Tests for CorrectionOperations.search_lyrics_sources()."""
def _mock_provider(self, name: str, lyrics_data=None):
"""Build a mock BaseLyricsProvider that returns lyrics_data."""
mock = MagicMock()
mock.get_name.return_value = name
mock.fetch_lyrics.return_value = lyrics_data
return mock
def test_returns_dict_with_expected_keys(self):
"""Return value always contains all four expected keys."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
correction_result = _make_correction_result()
with patch("karaoke_gen.lyrics_transcriber.correction.operations.create_lyrics_providers") as mock_factory:
mock_factory.return_value = [] # No providers — simulates empty env
result = CorrectionOperations.search_lyrics_sources(
correction_result=correction_result,
artist="Artist",
title="Title",
cache_dir="/tmp",
)
assert "updated_result" in result
assert "sources_added" in result
assert "sources_rejected" in result
assert "sources_not_found" in result
def test_no_providers_returns_no_results(self):
"""When no providers are available, returns no results."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
correction_result = _make_correction_result()
with patch("karaoke_gen.lyrics_transcriber.correction.operations.create_lyrics_providers") as mock_factory:
mock_factory.return_value = []
result = CorrectionOperations.search_lyrics_sources(
correction_result=correction_result,
artist="Artist",
title="Title",
cache_dir="/tmp",
)
assert result["updated_result"] is None
assert result["sources_added"] == []
def test_provider_not_found_appended_to_not_found(self):
"""Provider returning None is recorded in sources_not_found."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
correction_result = _make_correction_result()
mock_provider = self._mock_provider("LRCLIB", lyrics_data=None)
with patch("karaoke_gen.lyrics_transcriber.correction.operations.create_lyrics_providers") as mock_factory:
mock_factory.return_value = [mock_provider]
result = CorrectionOperations.search_lyrics_sources(
correction_result=correction_result,
artist="Artist",
title="Title",
cache_dir="/tmp",
)
assert "LRCLIB" in result["sources_not_found"]
assert result["updated_result"] is None
def test_provider_exception_appended_to_not_found(self):
"""Provider raising an exception is recorded in sources_not_found."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
correction_result = _make_correction_result()
mock_provider = self._mock_provider("Genius")
mock_provider.fetch_lyrics.side_effect = RuntimeError("network error")
with patch("karaoke_gen.lyrics_transcriber.correction.operations.create_lyrics_providers") as mock_factory:
mock_factory.return_value = [mock_provider]
result = CorrectionOperations.search_lyrics_sources(
correction_result=correction_result,
artist="Artist",
title="Title",
cache_dir="/tmp",
)
assert "Genius" in result["sources_not_found"]
def test_existing_source_skipped(self):
"""Provider whose name is already in reference_lyrics is skipped."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
existing_lyrics = {"Genius": _make_lyrics_data("Genius")}
correction_result = _make_correction_result(reference_lyrics=existing_lyrics)
mock_provider = self._mock_provider("Genius", lyrics_data=_make_lyrics_data("Genius"))
with patch("karaoke_gen.lyrics_transcriber.correction.operations.create_lyrics_providers") as mock_factory:
mock_factory.return_value = [mock_provider]
result = CorrectionOperations.search_lyrics_sources(
correction_result=correction_result,
artist="Artist",
title="Title",
cache_dir="/tmp",
)
# fetch_lyrics should NOT have been called
mock_provider.fetch_lyrics.assert_not_called()
assert result["updated_result"] is None # Nothing new to add
def test_lyrics_found_runs_corrector(self):
"""When lyrics are found, LyricsCorrector.run is called."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
correction_result = _make_correction_result()
lyrics_data = _make_lyrics_data("LRCLIB")
mock_provider = self._mock_provider("LRCLIB", lyrics_data=lyrics_data)
mock_corrector = MagicMock()
mock_corrector.all_handlers = []
mock_corrector.handlers = []
mock_updated = _make_correction_result(metadata={"audio_hash": "testhash"})
mock_corrector.run.return_value = mock_updated
with patch("karaoke_gen.lyrics_transcriber.correction.operations.create_lyrics_providers") as mock_factory, \
patch("karaoke_gen.lyrics_transcriber.correction.operations.LyricsCorrector") as MockCorrector:
mock_factory.return_value = [mock_provider]
MockCorrector.return_value = mock_corrector
result = CorrectionOperations.search_lyrics_sources(
correction_result=correction_result,
artist="Artist",
title="Title",
cache_dir="/tmp",
)
assert mock_corrector.run.called
def test_force_sources_bypass_rejection(self):
"""Sources in force_sources are added even if the corrector rejects them."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
correction_result = _make_correction_result()
lyrics_data = _make_lyrics_data("Genius")
mock_provider = self._mock_provider("Genius", lyrics_data=lyrics_data)
# Corrector result that puts "Genius" in rejected_sources
mock_corrector = MagicMock()
mock_corrector.all_handlers = []
mock_corrector.handlers = []
mock_updated = _make_correction_result(
reference_lyrics={}, # Corrector filtered it out
metadata={
"audio_hash": "testhash",
"rejected_sources": {
"Genius": {"relevance": 0.0, "matched_words": 0, "total_words": 10,
"track_name": "", "artist_names": ""},
},
}
)
mock_corrector.run.return_value = mock_updated
with patch("karaoke_gen.lyrics_transcriber.correction.operations.create_lyrics_providers") as mock_factory, \
patch("karaoke_gen.lyrics_transcriber.correction.operations.LyricsCorrector") as MockCorrector:
mock_factory.return_value = [mock_provider]
MockCorrector.return_value = mock_corrector
result = CorrectionOperations.search_lyrics_sources(
correction_result=correction_result,
artist="Artist",
title="Title",
cache_dir="/tmp",
force_sources=["Genius"],
)
# The forced source should be in sources_added, not rejected
assert "Genius" in result["sources_added"]
assert "Genius" not in result["sources_rejected"]
# And it should have been re-added to reference_lyrics
assert "Genius" in result["updated_result"].reference_lyrics
def test_audio_hash_preserved(self):
"""The audio_hash from the original correction_result is preserved."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
original_hash = "original-audio-hash-abc"
correction_result = _make_correction_result(metadata={"audio_hash": original_hash})
lyrics_data = _make_lyrics_data("LRCLIB")
mock_provider = self._mock_provider("LRCLIB", lyrics_data=lyrics_data)
mock_corrector = MagicMock()
mock_corrector.all_handlers = []
mock_corrector.handlers = []
mock_updated = _make_correction_result(metadata={}) # metadata without audio_hash
mock_corrector.run.return_value = mock_updated
with patch("karaoke_gen.lyrics_transcriber.correction.operations.create_lyrics_providers") as mock_factory, \
patch("karaoke_gen.lyrics_transcriber.correction.operations.LyricsCorrector") as MockCorrector:
mock_factory.return_value = [mock_provider]
MockCorrector.return_value = mock_corrector
result = CorrectionOperations.search_lyrics_sources(
correction_result=correction_result,
artist="Artist",
title="Title",
cache_dir="/tmp",
)
if result["updated_result"] is not None:
assert result["updated_result"].metadata.get("audio_hash") == original_hash
# ---------------------------------------------------------------------------
# Tests: CorrectionOperations.add_lyrics_source force parameter
# ---------------------------------------------------------------------------
class TestAddLyricsSourceForce:
"""Tests for the force parameter added to add_lyrics_source."""
def test_force_false_does_not_override_rejection(self):
"""With force=False (default), rejected sources remain rejected."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
correction_result = _make_correction_result()
mock_corrector = MagicMock()
mock_corrector.all_handlers = []
mock_corrector.handlers = []
mock_updated = _make_correction_result(
reference_lyrics={}, # source was filtered out
metadata={
"audio_hash": "testhash",
"rejected_sources": {
"custom": {"relevance": 0.0, "matched_words": 0, "total_words": 5,
"track_name": "", "artist_names": ""},
},
}
)
mock_corrector.run.return_value = mock_updated
with patch("karaoke_gen.lyrics_transcriber.correction.operations.LyricsCorrector") as MockCorrector:
MockCorrector.return_value = mock_corrector
result = CorrectionOperations.add_lyrics_source(
correction_result=correction_result,
source="custom",
lyrics_text="Hello world\nTest line",
cache_dir="/tmp",
force=False,
)
# Source should NOT be in reference_lyrics when force=False
assert "custom" not in result.reference_lyrics
def test_force_true_adds_source_even_if_rejected(self):
"""With force=True, source is added back even if the corrector rejected it."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
correction_result = _make_correction_result()
mock_corrector = MagicMock()
mock_corrector.all_handlers = []
mock_corrector.handlers = []
mock_updated = _make_correction_result(
reference_lyrics={}, # source was filtered out
metadata={
"audio_hash": "testhash",
"rejected_sources": {
"custom": {"relevance": 0.0, "matched_words": 0, "total_words": 5,
"track_name": "", "artist_names": ""},
},
}
)
mock_corrector.run.return_value = mock_updated
with patch("karaoke_gen.lyrics_transcriber.correction.operations.LyricsCorrector") as MockCorrector:
MockCorrector.return_value = mock_corrector
result = CorrectionOperations.add_lyrics_source(
correction_result=correction_result,
source="custom",
lyrics_text="Hello world\nTest line",
cache_dir="/tmp",
force=True,
)
# Source SHOULD be in reference_lyrics when force=True
assert "custom" in result.reference_lyrics
def test_force_true_no_op_when_source_not_rejected(self):
"""With force=True but source wasn't rejected, nothing extra happens."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
correction_result = _make_correction_result()
mock_corrector = MagicMock()
mock_corrector.all_handlers = []
mock_corrector.handlers = []
# Source is accepted (not in rejected_sources)
mock_updated = _make_correction_result(
reference_lyrics={"custom": _make_lyrics_data("custom")},
metadata={"audio_hash": "testhash"},
)
mock_corrector.run.return_value = mock_updated
with patch("karaoke_gen.lyrics_transcriber.correction.operations.LyricsCorrector") as MockCorrector:
MockCorrector.return_value = mock_corrector
result = CorrectionOperations.add_lyrics_source(
correction_result=correction_result,
source="custom",
lyrics_text="Hello world\nTest line",
cache_dir="/tmp",
force=True,
)
# Source remains in reference_lyrics normally
assert "custom" in result.reference_lyrics
# ---------------------------------------------------------------------------
# Tests: POST /{job_id}/search-lyrics API endpoint
# ---------------------------------------------------------------------------
class TestSearchLyricsEndpoint:
"""Tests for the POST /{job_id}/search-lyrics API endpoint."""
def test_endpoint_exists(self):
"""Verify the search-lyrics endpoint is registered in the router."""
from backend.api.routes.review import router
paths = [route.path for route in router.routes]
assert any("search-lyrics" in p for p in paths), f"search-lyrics not found in: {paths}"
def test_search_lyrics_requires_artist_and_title(self):
"""Document that the endpoint requires artist and title fields."""
valid_payload = {
"artist": "The Beatles",
"title": "Hey Jude",
}
assert "artist" in valid_payload
assert "title" in valid_payload
assert valid_payload["artist"].strip()
assert valid_payload["title"].strip()
def test_search_lyrics_accepts_force_sources(self):
"""Document that force_sources is an optional list of provider names."""
payload_with_force = {
"artist": "The Beatles",
"title": "Hey Jude",
"force_sources": ["Genius", "LRCLIB"],
}
assert isinstance(payload_with_force["force_sources"], list)
def test_success_response_format(self):
"""Document the expected success response format."""
example_success_response = {
"status": "success",
"data": {}, # CorrectionData dict
"sources_added": ["LRCLIB"],
"sources_rejected": {"Genius": {"relevance": 0.1}},
"sources_not_found": ["Spotify"],
}
assert example_success_response["status"] == "success"
assert "data" in example_success_response
assert "sources_added" in example_success_response
assert "sources_rejected" in example_success_response
assert "sources_not_found" in example_success_response
def test_no_results_response_format(self):
"""Document the expected no_results response format."""
example_no_results_response = {
"status": "no_results",
"message": "No matching lyrics found from any provider",
"sources_rejected": {},
"sources_not_found": ["Genius", "LRCLIB"],
}
assert example_no_results_response["status"] == "no_results"
assert "message" in example_no_results_response
assert "sources_rejected" in example_no_results_response
assert "sources_not_found" in example_no_results_response
def test_search_lyrics_uses_correction_operations(self):
"""Verify CorrectionOperations.search_lyrics_sources exists and is callable."""
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
assert hasattr(CorrectionOperations, "search_lyrics_sources")
method = getattr(CorrectionOperations, "search_lyrics_sources")
assert callable(method)
def test_add_lyrics_source_has_force_parameter(self):
"""Verify add_lyrics_source now accepts a force parameter."""
import inspect
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
sig = inspect.signature(CorrectionOperations.add_lyrics_source)
assert "force" in sig.parameters
# Default should be False
assert sig.parameters["force"].default is False
+46 -1
View File
@@ -336,9 +336,54 @@ class TestWorkerService:
assert "test123" in str(override_args)
class TestWorkerServiceWarmup:
"""Test encoding worker warmup in trigger methods."""
@pytest.mark.asyncio
async def test_trigger_video_worker_calls_warmup(self):
"""trigger_video_worker calls _warmup_encoding_worker before dispatching."""
with patch('backend.services.worker_service.httpx.AsyncClient') as mock_client_cls:
mock_client = AsyncMock()
mock_client_cls.return_value.__aenter__.return_value = mock_client
mock_response = Mock()
mock_response.status_code = 200
mock_client.post.return_value = mock_response
worker_service = get_worker_service()
with patch.object(worker_service, '_warmup_encoding_worker') as mock_warmup:
await worker_service.trigger_video_worker("test-job")
mock_warmup.assert_called_once_with("test-job")
@pytest.mark.asyncio
async def test_trigger_render_video_worker_calls_warmup(self):
"""trigger_render_video_worker calls _warmup_encoding_worker before dispatching."""
with patch('backend.services.worker_service.httpx.AsyncClient') as mock_client_cls:
mock_client = AsyncMock()
mock_client_cls.return_value.__aenter__.return_value = mock_client
mock_response = Mock()
mock_response.status_code = 200
mock_client.post.return_value = mock_response
worker_service = get_worker_service()
with patch.object(worker_service, '_warmup_encoding_worker') as mock_warmup:
await worker_service.trigger_render_video_worker("test-job")
mock_warmup.assert_called_once_with("test-job")
def test_warmup_swallows_exceptions(self):
"""Warmup failures are logged but never block worker dispatch."""
worker_service = get_worker_service()
with patch('backend.services.encoding_worker_manager.EncodingWorkerManager.ensure_primary_running',
side_effect=Exception("Compute API down")):
# Should not raise
worker_service._warmup_encoding_worker("test-job")
class TestWorkerServiceCloudTasks:
"""Test WorkerService Cloud Tasks integration."""
def test_should_use_cloud_tasks_default_false(self):
"""Test that Cloud Tasks is disabled by default."""
from backend.services.worker_service import WorkerService, reset_worker_service
@@ -0,0 +1,306 @@
"""
Unit tests for stale review processor.
Tests the logic for detecting stale review jobs, sending reminder emails,
and auto-expiring jobs that exceed the 48h threshold.
"""
import pytest
from datetime import datetime, timedelta, timezone
from unittest.mock import Mock, MagicMock, patch
# Mock Google Cloud before imports
import sys
sys.modules.setdefault('google.cloud.firestore', MagicMock())
sys.modules.setdefault('google.cloud.storage', MagicMock())
from backend.models.job import JobStatus
def _make_job(
job_id="job-123",
status=JobStatus.AWAITING_REVIEW,
hours_ago=30,
user_email="user@test.com",
artist="Test Artist",
title="Test Song",
made_for_you=False,
tenant_id="",
expiry_reminder_sent=False,
has_blocking_state=True,
):
"""Helper to create a mock job with configurable state_data."""
job = Mock()
job.job_id = job_id
job.status = status
job.user_email = user_email
job.artist = artist
job.title = title
job.made_for_you = made_for_you
job.tenant_id = tenant_id
if has_blocking_state:
entered_at = (datetime.now(timezone.utc) - timedelta(hours=hours_ago)).isoformat()
job.state_data = {
'blocking_state_entered_at': entered_at,
'blocking_action_type': 'lyrics',
'reminder_sent': True, # Existing idle reminder (always True for real jobs)
}
if expiry_reminder_sent:
job.state_data['expiry_reminder_sent'] = True
else:
job.state_data = {}
return job
@pytest.mark.asyncio
class TestProcessStaleReviews:
"""Test the main stale review processing function."""
@pytest.fixture
def mock_firestore(self):
service = Mock()
service.list_jobs.return_value = []
service.update_job = Mock()
return service
@pytest.fixture
def mock_job_manager(self):
manager = Mock()
manager.cancel_job.return_value = True
return manager
@pytest.fixture
def mock_email_service(self):
service = Mock()
service.send_review_reminder.return_value = True
service.send_review_expired.return_value = True
return service
@pytest.fixture
def mock_user_service(self):
service = Mock()
service.check_credits.return_value = 2
return service
def _patch_all(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
"""Return a context manager that patches all dependencies."""
from contextlib import contextmanager
@contextmanager
def patches():
with patch('backend.workers.stale_review_processor.FirestoreService', return_value=mock_firestore), \
patch('backend.workers.stale_review_processor.JobManager', return_value=mock_job_manager), \
patch('backend.workers.stale_review_processor.get_email_service', return_value=mock_email_service), \
patch('backend.services.user_service.get_user_service', return_value=mock_user_service):
yield
return patches()
async def test_no_stale_jobs(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
"""Should return zero counts when no jobs are in review."""
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
result = await process_stale_reviews()
assert result["reminders_sent"] == 0
assert result["jobs_expired"] == 0
assert result["status"] == "completed"
async def test_expires_job_over_48h(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
"""Should expire a job that's been in review for over 48 hours."""
job = _make_job(hours_ago=50)
mock_firestore.list_jobs.side_effect = [[job], []] # awaiting_review query, in_review query
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
result = await process_stale_reviews()
assert result["jobs_expired"] == 1
mock_job_manager.cancel_job.assert_called_once_with(
"job-123", reason="Review not completed within 48 hours"
)
mock_email_service.send_review_expired.assert_called_once_with(
to_email="user@test.com",
artist="Test Artist",
title="Test Song",
credits_balance=2,
)
async def test_expires_job_over_48h_with_reminder_already_sent(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
"""Should expire job >48h even if reminder was already sent (no duplicate reminder)."""
job = _make_job(hours_ago=50, expiry_reminder_sent=True)
mock_firestore.list_jobs.side_effect = [[job], []]
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
result = await process_stale_reviews()
assert result["jobs_expired"] == 1
# Reminder should NOT be sent again
mock_email_service.send_review_reminder.assert_not_called()
# But expiry email should still be sent
mock_email_service.send_review_expired.assert_called_once()
async def test_sends_reminder_24_to_48h(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
"""Should send reminder for job in 24-48h range."""
job = _make_job(hours_ago=30)
mock_firestore.list_jobs.side_effect = [[job], []]
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
result = await process_stale_reviews()
assert result["reminders_sent"] == 1
assert result["jobs_expired"] == 0
mock_email_service.send_review_reminder.assert_called_once_with(
to_email="user@test.com",
artist="Test Artist",
title="Test Song",
job_id="job-123",
)
# Should update state_data with expiry_reminder_sent flag
mock_firestore.update_job.assert_called_once()
call_args = mock_firestore.update_job.call_args
assert call_args[0][0] == "job-123"
assert call_args[0][1]['state_data.expiry_reminder_sent'] is True
assert 'state_data.expiry_reminder_sent_at' in call_args[0][1]
async def test_skips_if_expiry_reminder_already_sent(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
"""Should skip reminder if expiry_reminder_sent is already True."""
job = _make_job(hours_ago=30, expiry_reminder_sent=True)
mock_firestore.list_jobs.side_effect = [[job], []]
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
result = await process_stale_reviews()
assert result["reminders_sent"] == 0
assert result["jobs_expired"] == 0
mock_email_service.send_review_reminder.assert_not_called()
async def test_idle_reminder_sent_does_not_block_expiry_reminder(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
"""Existing idle reminder_sent=True should not prevent 24h expiry reminder."""
job = _make_job(hours_ago=30)
# reminder_sent is True (set by idle reminder system) but expiry_reminder_sent is not set
assert job.state_data['reminder_sent'] is True
assert 'expiry_reminder_sent' not in job.state_data
mock_firestore.list_jobs.side_effect = [[job], []]
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
result = await process_stale_reviews()
assert result["reminders_sent"] == 1
mock_email_service.send_review_reminder.assert_called_once()
async def test_no_action_under_24h(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
"""Should take no action for jobs under 24 hours old."""
job = _make_job(hours_ago=12)
mock_firestore.list_jobs.side_effect = [[job], []]
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
result = await process_stale_reviews()
assert result["reminders_sent"] == 0
assert result["jobs_expired"] == 0
mock_email_service.send_review_reminder.assert_not_called()
mock_job_manager.cancel_job.assert_not_called()
async def test_skips_made_for_you_jobs(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
"""Should skip made-for-you jobs regardless of age."""
job = _make_job(hours_ago=100, made_for_you=True)
mock_firestore.list_jobs.side_effect = [[job], []]
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
result = await process_stale_reviews()
assert result["jobs_expired"] == 0
assert result["reminders_sent"] == 0
mock_job_manager.cancel_job.assert_not_called()
async def test_skips_tenant_jobs(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
"""Should skip tenant/white-label jobs regardless of age."""
job = _make_job(hours_ago=100, tenant_id="vocalstar")
mock_firestore.list_jobs.side_effect = [[job], []]
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
result = await process_stale_reviews()
assert result["jobs_expired"] == 0
assert result["reminders_sent"] == 0
mock_job_manager.cancel_job.assert_not_called()
async def test_skips_job_without_blocking_state(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
"""Should skip jobs that have no blocking_state_entered_at."""
job = _make_job(hours_ago=50, has_blocking_state=False)
mock_firestore.list_jobs.side_effect = [[job], []]
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
result = await process_stale_reviews()
assert result["jobs_expired"] == 0
assert result["reminders_sent"] == 0
async def test_expires_job_without_email(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
"""Should still expire jobs with no user_email (just skip the email)."""
job = _make_job(hours_ago=50, user_email=None)
mock_firestore.list_jobs.side_effect = [[job], []]
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
result = await process_stale_reviews()
assert result["jobs_expired"] == 1
mock_job_manager.cancel_job.assert_called_once()
# No email sent because no user_email
mock_email_service.send_review_expired.assert_not_called()
async def test_error_in_one_job_doesnt_block_others(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
"""An error processing one job should not prevent processing others."""
job1 = _make_job(job_id="job-bad", hours_ago=50)
job2 = _make_job(job_id="job-good", hours_ago=50)
mock_firestore.list_jobs.side_effect = [[job1, job2], []]
# First cancel raises, second succeeds
mock_job_manager.cancel_job.side_effect = [Exception("DB error"), True]
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
result = await process_stale_reviews()
assert result["jobs_expired"] == 1 # Only job-good counted
assert len(result["errors"]) == 1
assert "job-bad" in result["errors"][0]
async def test_return_counts_correct(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
"""Return value should have correct counts for mixed batch."""
job_expire = _make_job(job_id="expire-1", hours_ago=50)
job_remind = _make_job(job_id="remind-1", hours_ago=30)
job_fresh = _make_job(job_id="fresh-1", hours_ago=12)
job_skip = _make_job(job_id="skip-1", hours_ago=50, made_for_you=True)
mock_firestore.list_jobs.side_effect = [[job_expire, job_remind, job_fresh, job_skip], []]
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
result = await process_stale_reviews()
assert result["jobs_expired"] == 1
assert result["reminders_sent"] == 1
assert len(result["errors"]) == 0
async def test_handles_in_review_status(self, mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
"""Should process jobs in IN_REVIEW status (user opened but abandoned)."""
job = _make_job(job_id="in-review-1", status=JobStatus.IN_REVIEW, hours_ago=50)
mock_firestore.list_jobs.side_effect = [[], [job]] # Empty awaiting, one in_review
with self._patch_all(mock_firestore, mock_job_manager, mock_email_service, mock_user_service):
from backend.workers.stale_review_processor import process_stale_reviews
result = await process_stale_reviews()
assert result["jobs_expired"] == 1
mock_job_manager.cancel_job.assert_called_once()
+2 -2
View File
@@ -180,8 +180,8 @@ class TestStyleHelper:
# Mock job with style assets
job = Mock()
job.job_id = "test-123"
job.style_assets = {"style_params": "uploads/test/style_params.json"}
job.style_params_gcs_path = "uploads/test/style_params.json"
job.style_assets = {"style_params": "jobs/test/style_params.json"}
job.style_params_gcs_path = "jobs/test/style_params.json"
# Mock storage to "download" the file
storage = Mock()
+3 -3
View File
@@ -36,7 +36,7 @@ def mock_job_manager():
@pytest.fixture
def mock_storage_service():
with patch('backend.api.routes.file_upload.storage_service') as mock:
mock.bucket_name = "test-bucket"
mock.bucket.name = "test-bucket"
yield mock
@@ -251,7 +251,7 @@ class TestCompleteStyleUploads:
self, mock_job_manager, mock_storage_service, admin_auth, pending_job
):
mock_job_manager.get_job.return_value = pending_job
mock_storage_service.list_files.return_value = ["uploads/job-abc/style/karaoke_background.png"]
mock_storage_service.list_files.return_value = ["jobs/job-abc/style/karaoke_background.png"]
# Mock theme service
with patch('backend.api.routes.file_upload.get_theme_service') as mock_get_ts:
@@ -287,7 +287,7 @@ class TestCompleteStyleUploads:
self, mock_job_manager, mock_storage_service, admin_auth, pending_job
):
mock_job_manager.get_job.return_value = pending_job
mock_storage_service.list_files.return_value = ["uploads/job-abc/style/intro_background.png"]
mock_storage_service.list_files.return_value = ["jobs/job-abc/style/intro_background.png"]
with patch('backend.api.routes.file_upload.get_theme_service') as mock_get_ts:
mock_ts = Mock()
@@ -0,0 +1,157 @@
"""Tests for the /api/health/system-status endpoint."""
import pytest
from unittest.mock import patch, MagicMock, AsyncMock
@pytest.fixture
def mock_encoding_status():
return {
"configured": True,
"enabled": True,
"available": True,
"status": "ok",
"active_jobs": 0,
"queue_length": 0,
"wheel_version": "0.155.3",
}
@pytest.fixture
def mock_flacfetch_status():
return {
"configured": True,
"available": True,
"status": "ok",
"version": "0.19.1",
}
@pytest.fixture
def mock_separator_status():
return {
"available": True,
"status": "ok",
"version": "0.4.3",
}
@pytest.fixture
def mock_encoding_worker_config():
"""Mock EncodingWorkerConfig dataclass."""
config = MagicMock()
config.primary_vm = "encoding-worker-b"
config.primary_ip = "34.10.189.118"
config.primary_version = "0.155.3"
config.primary_deployed_at = "2026-03-31T18:10:00Z"
config.secondary_vm = "encoding-worker-a"
config.secondary_ip = "34.57.78.246"
config.secondary_version = "0.155.2"
config.secondary_deployed_at = "2026-03-29T14:00:00Z"
config.last_swap_at = "2026-03-31T18:10:00Z"
config.deploy_in_progress = False
config.deploy_in_progress_since = None
config.last_activity_at = None
return config
class TestSystemStatusPublic:
"""Tests for unauthenticated /api/health/system-status."""
@pytest.mark.asyncio
async def test_returns_all_services(
self, mock_encoding_status, mock_flacfetch_status, mock_separator_status
):
from backend.api.routes.health import system_status
with patch("backend.api.routes.health.check_encoding_worker_status", new_callable=AsyncMock, return_value=mock_encoding_status), \
patch("backend.api.routes.health.check_flacfetch_service_status", new_callable=AsyncMock, return_value=mock_flacfetch_status), \
patch("backend.api.routes.health.check_audio_separator_status", return_value=mock_separator_status), \
patch("backend.api.routes.health.VERSION", "0.155.3"), \
patch("backend.api.routes.health.COMMIT_SHA", "8e2a949a"), \
patch("backend.api.routes.health.PR_NUMBER", "644"), \
patch("backend.api.routes.health.PR_TITLE", "fix: blue-green deploy"), \
patch("backend.api.routes.health.STARTUP_TIME", "2026-03-31T18:10:00Z"):
result = await system_status(auth=None)
assert "services" in result
services = result["services"]
# All 5 services present
assert "frontend" in services
assert "backend" in services
assert "encoder" in services
assert "flacfetch" in services
assert "separator" in services
# Backend has build metadata
backend_svc = services["backend"]
assert backend_svc["version"] == "0.155.3"
assert backend_svc["commit_sha"] == "8e2a949a"
assert backend_svc["pr_number"] == "644"
# Encoder has status
assert services["encoder"]["status"] == "ok"
assert services["encoder"]["version"] == "0.155.3"
# No admin_details without auth
assert "admin_details" not in services["encoder"]
@pytest.mark.asyncio
async def test_offline_service(self, mock_flacfetch_status, mock_separator_status):
from backend.api.routes.health import system_status
offline_encoding = {
"configured": True,
"enabled": True,
"available": False,
"error": "Connection refused",
}
with patch("backend.api.routes.health.check_encoding_worker_status", new_callable=AsyncMock, return_value=offline_encoding), \
patch("backend.api.routes.health.check_flacfetch_service_status", new_callable=AsyncMock, return_value=mock_flacfetch_status), \
patch("backend.api.routes.health.check_audio_separator_status", return_value=mock_separator_status), \
patch("backend.api.routes.health.VERSION", "0.155.3"), \
patch("backend.api.routes.health.COMMIT_SHA", ""), \
patch("backend.api.routes.health.PR_NUMBER", ""), \
patch("backend.api.routes.health.PR_TITLE", ""), \
patch("backend.api.routes.health.STARTUP_TIME", "2026-03-31T18:10:00Z"):
result = await system_status(auth=None)
assert result["services"]["encoder"]["status"] == "offline"
class TestSystemStatusAdmin:
"""Tests for admin-authenticated /api/health/system-status."""
@pytest.mark.asyncio
async def test_admin_gets_bluegreen_details(
self, mock_encoding_status, mock_flacfetch_status, mock_separator_status, mock_encoding_worker_config
):
from backend.api.routes.health import system_status
from backend.services.auth_service import UserType
mock_auth = ("token123", UserType.ADMIN, -1)
mock_manager = MagicMock()
mock_manager.get_config.return_value = mock_encoding_worker_config
with patch("backend.api.routes.health.check_encoding_worker_status", new_callable=AsyncMock, return_value=mock_encoding_status), \
patch("backend.api.routes.health.check_flacfetch_service_status", new_callable=AsyncMock, return_value=mock_flacfetch_status), \
patch("backend.api.routes.health.check_audio_separator_status", return_value=mock_separator_status), \
patch("backend.api.routes.health.VERSION", "0.155.3"), \
patch("backend.api.routes.health.COMMIT_SHA", ""), \
patch("backend.api.routes.health.PR_NUMBER", ""), \
patch("backend.api.routes.health.PR_TITLE", ""), \
patch("backend.api.routes.health.STARTUP_TIME", "2026-03-31T18:10:00Z"), \
patch("backend.api.routes.health._get_encoding_worker_manager", return_value=mock_manager):
result = await system_status(auth=mock_auth)
encoder = result["services"]["encoder"]
assert "admin_details" in encoder
admin = encoder["admin_details"]
assert admin["primary_vm"] == "encoding-worker-b"
assert admin["secondary_vm"] == "encoding-worker-a"
assert admin["last_swap_at"] == "2026-03-31T18:10:00Z"
assert admin["deploy_in_progress"] is False
+2 -2
View File
@@ -336,7 +336,7 @@ class TestThemeService:
# Should upload modified style_params.json
mock_storage.upload_json.assert_called_once()
assert style_path == "uploads/job123/style/style_params.json"
assert style_path == "jobs/job123/style/style_params.json"
def test_prepare_job_style_with_overrides(self, mock_storage, sample_metadata, sample_style_params):
"""Test prepare_job_style applies color overrides."""
@@ -355,7 +355,7 @@ class TestThemeService:
uploaded_path = call_args[0][0] # First positional arg is the path
uploaded_style = call_args[0][1] # Second positional arg is the data
assert uploaded_path == "uploads/job123/style/style_params.json"
assert uploaded_path == "jobs/job123/style/style_params.json"
# Check that artist_color override was applied
assert uploaded_style["intro"]["artist_color"] == "#FF0000"
assert uploaded_style["end"]["artist_color"] == "#FF0000"
@@ -399,8 +399,8 @@ class TestPackagingValidation:
"""
@pytest.mark.asyncio
async def test_cdg_validation_fails_when_enabled_but_not_produced(self):
"""Test that orchestrator raises when CDG enabled but not produced."""
async def test_cdg_validation_fails_when_enabled_but_not_produced_and_lrc_has_content(self):
"""Test that orchestrator raises when CDG enabled but not produced and LRC has lyrics."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
@@ -417,6 +417,7 @@ class TestPackagingValidation:
pass # CDG generation "failed" silently
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging), \
patch.object(orchestrator, "_lrc_has_lyrics_content", return_value=True), \
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock) as mock_encoding:
result = await orchestrator.run()
@@ -426,8 +427,37 @@ class TestPackagingValidation:
mock_encoding.assert_not_called() # Should not reach encoding
@pytest.mark.asyncio
async def test_txt_validation_fails_when_enabled_but_not_produced(self):
"""Test that orchestrator raises when TXT enabled but not produced."""
async def test_cdg_skipped_gracefully_when_lrc_has_no_content(self):
"""Test that CDG failure is a warning (not error) when LRC has no lyrics content."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
enable_cdg=True,
)
orchestrator = VideoWorkerOrchestrator(config)
async def mock_packaging():
pass # CDG generation "failed" silently
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging), \
patch.object(orchestrator, "_lrc_has_lyrics_content", return_value=False), \
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock) as mock_encoding, \
patch.object(orchestrator, "_run_organization", new_callable=AsyncMock), \
patch.object(orchestrator, "_run_distribution", new_callable=AsyncMock), \
patch.object(orchestrator, "_run_notifications", new_callable=AsyncMock):
result = await orchestrator.run()
assert result.success is True # Pipeline continues
mock_encoding.assert_called_once() # Encoding still runs
@pytest.mark.asyncio
async def test_txt_validation_fails_when_enabled_but_not_produced_and_lrc_has_content(self):
"""Test that orchestrator raises when TXT enabled but not produced and LRC has lyrics."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
@@ -443,6 +473,7 @@ class TestPackagingValidation:
pass # TXT generation "failed" silently
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging), \
patch.object(orchestrator, "_lrc_has_lyrics_content", return_value=True), \
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock) as mock_encoding:
result = await orchestrator.run()
@@ -506,7 +537,7 @@ class TestPackagingValidation:
@pytest.mark.asyncio
async def test_both_cdg_and_txt_validation_fail_together(self):
"""Test that orchestrator catches CDG failure when both CDG and TXT enabled."""
"""Test that orchestrator catches CDG failure when both CDG and TXT enabled and LRC has content."""
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
@@ -523,6 +554,7 @@ class TestPackagingValidation:
pass # Both CDG and TXT "failed" silently
with patch.object(orchestrator, "_run_packaging", side_effect=mock_packaging), \
patch.object(orchestrator, "_lrc_has_lyrics_content", return_value=True), \
patch.object(orchestrator, "_run_encoding", new_callable=AsyncMock) as mock_encoding:
result = await orchestrator.run()
@@ -1224,6 +1256,7 @@ class TestCreateOrchestratorConfigFromJob:
job.gdrive_folder_id = None
job.keep_brand_code = None
job.existing_instrumental_gcs_path = None
job.file_urls = {'screens': {'title_png': 'jobs/test-123/screens/title.png', 'end_png': 'jobs/test-123/screens/end.png'}}
config = create_orchestrator_config_from_job(
job=job,
@@ -1237,7 +1270,7 @@ class TestCreateOrchestratorConfigFromJob:
assert config.title == "Test Title"
assert config.enable_cdg is True
assert config.enable_youtube_upload is True
assert config.title_video_path == "/tmp/test/Test Artist - Test Title (Title).mov"
assert config.title_video_path == "/tmp/test/Test Artist - Test Title (Title).png"
assert config.instrumental_audio_path == "/tmp/test/Test Artist - Test Title (Instrumental Clean).flac"
def test_create_config_from_job_with_existing_instrumental(self):
@@ -1258,6 +1291,7 @@ class TestCreateOrchestratorConfigFromJob:
job.gdrive_folder_id = None
job.keep_brand_code = None
job.existing_instrumental_gcs_path = "gs://bucket/instrumental.mp3"
job.file_urls = {'screens': {'title_png': 'screens/title.png', 'end_png': 'screens/end.png'}}
config = create_orchestrator_config_from_job(
job=job,
@@ -1297,6 +1331,7 @@ class TestCreateOrchestratorConfigFromJob:
job.gdrive_folder_id = None
job.keep_brand_code = None
job.existing_instrumental_gcs_path = None
job.file_urls = {'screens': {'title_png': 'screens/title.png', 'end_png': 'screens/end.png'}}
config = create_orchestrator_config_from_job(
job=job,
@@ -1709,3 +1744,57 @@ class TestDistributionWarnings:
assert len(orchestrator.result.distribution_warnings) == 1
assert "Dropbox upload failed" in orchestrator.result.distribution_warnings[0]
class TestLrcHasLyricsContent:
"""Tests for _lrc_has_lyrics_content helper."""
def _make_orchestrator(self, lrc_file_path=None):
config = OrchestratorConfig(
job_id="test-job",
artist="Test Artist",
title="Test Title",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
lrc_file_path=lrc_file_path,
)
return VideoWorkerOrchestrator(config)
def test_returns_false_when_no_lrc_path(self):
orchestrator = self._make_orchestrator(lrc_file_path=None)
assert orchestrator._lrc_has_lyrics_content() is False
def test_returns_false_when_lrc_file_missing(self):
orchestrator = self._make_orchestrator(lrc_file_path="/nonexistent/path.lrc")
assert orchestrator._lrc_has_lyrics_content() is False
def test_returns_false_for_empty_lrc(self, tmp_path):
lrc_file = tmp_path / "empty.lrc"
lrc_file.write_text("[re:MidiCo]\n")
orchestrator = self._make_orchestrator(lrc_file_path=str(lrc_file))
assert orchestrator._lrc_has_lyrics_content() is False
def test_returns_true_for_lrc_with_lyrics(self, tmp_path):
lrc_file = tmp_path / "valid.lrc"
lrc_file.write_text("[re:MidiCo]\n[00:12.345]Hello world\n[00:15.678]Second line\n")
orchestrator = self._make_orchestrator(lrc_file_path=str(lrc_file))
assert orchestrator._lrc_has_lyrics_content() is True
def test_returns_true_for_centisecond_timestamps(self, tmp_path):
lrc_file = tmp_path / "centisecond.lrc"
lrc_file.write_text("[01:02.34]Lyric line\n")
orchestrator = self._make_orchestrator(lrc_file_path=str(lrc_file))
assert orchestrator._lrc_has_lyrics_content() is True
def test_returns_true_for_no_decimal_timestamps(self, tmp_path):
lrc_file = tmp_path / "nodecimal.lrc"
lrc_file.write_text("[01:30]Lyric line\n")
orchestrator = self._make_orchestrator(lrc_file_path=str(lrc_file))
assert orchestrator._lrc_has_lyrics_content() is True
def test_returns_false_for_metadata_only_lrc(self, tmp_path):
lrc_file = tmp_path / "meta.lrc"
lrc_file.write_text("[ti:Song Title]\n[ar:Artist Name]\n[re:MidiCo]\n")
orchestrator = self._make_orchestrator(lrc_file_path=str(lrc_file))
assert orchestrator._lrc_has_lyrics_content() is False
+223 -53
View File
@@ -179,48 +179,48 @@ class TestLyricsWorker:
return storage
@pytest.mark.asyncio
async def test_upload_lyrics_results_requires_job(self, mock_job_manager, mock_storage, mock_job):
"""Test that upload_lyrics_results correctly fetches job for artist/title.
This test would have caught the UnboundLocalError bug where job was used
before being defined.
async def test_upload_lyrics_results_finds_corrections_by_scan(self, mock_job_manager, mock_storage, mock_job):
"""Test that upload_lyrics_results finds corrections JSON by scanning the directory.
The function scans for files ending in '(Lyrics Corrections).json' rather than
reconstructing filenames from job.artist/title, since those may change mid-processing
(e.g. admin updates artist name while lyrics worker is running).
"""
with patch('backend.workers.lyrics_worker.JobManager', return_value=mock_job_manager), \
patch('backend.workers.lyrics_worker.StorageService', return_value=mock_storage):
from backend.workers.lyrics_worker import upload_lyrics_results
with tempfile.TemporaryDirectory() as temp_dir:
# Create mock lyrics directory and files
lyrics_dir = os.path.join(temp_dir, "lyrics")
os.makedirs(lyrics_dir)
# Create test LRC file
lrc_path = os.path.join(lyrics_dir, "ABBA - Waterloo (Karaoke).lrc")
with open(lrc_path, 'w') as f:
f.write("[00:00.00]Test lyrics\n")
# Create corrections JSON
corrections_path = os.path.join(lyrics_dir, "ABBA - Waterloo (Lyrics Corrections).json")
# Use a different artist than what's in the job to simulate mid-run rename
corrections_path = os.path.join(lyrics_dir, "OldArtist - Waterloo (Lyrics Corrections).json")
with open(corrections_path, 'w') as f:
json.dump({"lines": [], "corrections": []}, f)
transcription_result = {
"lrc_filepath": lrc_path,
"corrections_filepath": corrections_path
}
# This should NOT raise UnboundLocalError
await upload_lyrics_results(
"test123",
temp_dir,
transcription_result,
mock_storage,
"test123",
temp_dir,
transcription_result,
mock_storage,
mock_job_manager
)
# Verify job was fetched
mock_job_manager.get_job.assert_called_with("test123")
# Verify corrections file was found and uploaded as corrections.json
upload_calls = mock_storage.upload_file.call_args_list
corrections_uploads = [c for c in upload_calls if 'corrections.json' in str(c)]
assert len(corrections_uploads) == 1
@pytest.mark.asyncio
async def test_upload_lyrics_results_uploads_lrc_file(self, mock_job_manager, mock_storage, mock_job):
@@ -281,53 +281,68 @@ class TestLyricsWorker:
)
@pytest.mark.asyncio
async def test_upload_lyrics_results_uses_artist_title_from_job(self, mock_job_manager, mock_storage, mock_job):
"""Test that upload_lyrics_results correctly uses job.artist and job.title.
This test specifically validates the bug fix where job was not defined
when accessing job.artist and job.title for reference file lookups.
"""
async def test_upload_lyrics_results_raises_when_no_corrections(self, mock_job_manager, mock_storage, mock_job):
"""Test that upload_lyrics_results raises when no corrections file exists at all."""
from backend.workers.lyrics_worker import upload_lyrics_results
import json
with tempfile.TemporaryDirectory() as temp_dir:
lyrics_dir = os.path.join(temp_dir, "lyrics")
os.makedirs(lyrics_dir)
# Create LRC file
lrc_path = os.path.join(lyrics_dir, "test.lrc")
with open(lrc_path, 'w') as f:
f.write("[00:00.00]Test\n")
# Create required corrections.json file
corrections_path = os.path.join(lyrics_dir, "corrections.json")
# No corrections file at all
transcription_result = {"lrc_filepath": lrc_path}
with pytest.raises(Exception, match="No corrections JSON found"):
await upload_lyrics_results(
"test123", temp_dir, transcription_result,
mock_storage, mock_job_manager
)
@pytest.mark.asyncio
async def test_upload_lyrics_results_finds_reference_and_uncorrected_by_scan(self, mock_job_manager, mock_storage, mock_job):
"""Test that upload_lyrics_results finds reference and uncorrected files by scanning.
Files are found by suffix pattern, not by reconstructing from job.artist/title,
so mid-processing artist name changes don't break the upload.
"""
from backend.workers.lyrics_worker import upload_lyrics_results
import json
with tempfile.TemporaryDirectory() as temp_dir:
lyrics_dir = os.path.join(temp_dir, "lyrics")
os.makedirs(lyrics_dir)
lrc_path = os.path.join(lyrics_dir, "test.lrc")
with open(lrc_path, 'w') as f:
f.write("[00:00.00]Test\n")
corrections_path = os.path.join(lyrics_dir, "SomeArtist - SomeTitle (Lyrics Corrections).json")
with open(corrections_path, 'w') as f:
json.dump({"corrected_segments": []}, f)
# Create a reference lyrics file using the job's artist/title
ref_path = os.path.join(lyrics_dir, f"{mock_job.artist} - {mock_job.title} (Lyrics Genius).txt")
# Reference and uncorrected files with arbitrary artist name
ref_path = os.path.join(lyrics_dir, "SomeArtist - SomeTitle (Lyrics Genius).txt")
with open(ref_path, 'w') as f:
f.write("Reference lyrics content\n")
# Create uncorrected transcription file using job's artist/title
uncorrected_path = os.path.join(lyrics_dir, f"{mock_job.artist} - {mock_job.title} (Lyrics Uncorrected).txt")
uncorrected_path = os.path.join(lyrics_dir, "SomeArtist - SomeTitle (Lyrics Uncorrected).txt")
with open(uncorrected_path, 'w') as f:
f.write("Uncorrected transcription\n")
transcription_result = {"lrc_filepath": lrc_path}
# This should NOT raise UnboundLocalError for 'job'
await upload_lyrics_results(
"test123", temp_dir, transcription_result,
mock_storage, mock_job_manager
)
# Verify job was fetched to get artist/title
mock_job_manager.get_job.assert_called_with("test123")
# Verify files were uploaded (the reference and uncorrected files exist)
# Verify files were uploaded: LRC + corrections + genius ref + uncorrected = 4
upload_calls = mock_storage.upload_file.call_args_list
assert len(upload_calls) >= 2 # LRC + at least one reference or uncorrected
assert len(upload_calls) == 4
@pytest.mark.asyncio
async def test_process_lyrics_transcription_marks_failed_on_error(self, mock_job_manager, mock_storage):
@@ -621,7 +636,7 @@ class TestAudioWorkerModelConfiguration:
# Should use default models
assert call_kwargs['clean_instrumental_model'] == "model_bs_roformer_ep_317_sdr_12.9755.ckpt"
assert call_kwargs['backing_vocals_models'] == ["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"]
assert call_kwargs['other_stems_models'] == ["htdemucs_6s.yaml"]
assert call_kwargs['other_stems_models'] == []
def test_create_audio_processor_with_custom_clean_model(self):
"""Test creating AudioProcessor with custom clean instrumental model."""
@@ -762,7 +777,7 @@ class TestAudioWorkerModelConfiguration:
# Should fall back to defaults
assert call_kwargs['clean_instrumental_model'] == "model_bs_roformer_ep_317_sdr_12.9755.ckpt"
assert call_kwargs['backing_vocals_models'] == ["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"]
assert call_kwargs['other_stems_models'] == ["htdemucs_6s.yaml"]
assert call_kwargs['other_stems_models'] == []
class TestDownloadFromUrl:
@@ -1395,3 +1410,158 @@ class TestLyricsWorkerCountdownState:
assert lyrics_metadata['has_countdown_padding'] is True
assert lyrics_metadata['countdown_padding_seconds'] == 3.0
class TestVideoWorkerStateGuard:
"""Tests for video worker state validation."""
@pytest.fixture
def failed_job(self):
return Job(
job_id="test-failed",
status=JobStatus.FAILED,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test",
title="Song",
state_data={"instrumental_selection": "clean"},
file_urls={
"stems": {"instrumental_clean": "gs://test"},
"screens": {"title": "gs://t", "end": "gs://e"},
"videos": {"with_vocals": "gs://v"},
"lyrics": {"lrc": "gs://lrc"},
},
)
def test_validate_worker_can_run_rejects_failed_job(self, failed_job):
"""validate_worker_can_run returns error for failed jobs."""
from backend.services.job_health_service import validate_worker_can_run
result = validate_worker_can_run("video_worker", failed_job)
assert result is not None
assert "failed" in result.lower()
def test_validate_worker_can_run_accepts_instrumental_selected(self):
"""validate_worker_can_run allows instrumental_selected jobs."""
from backend.services.job_health_service import validate_worker_can_run
job = Job(
job_id="test-ok",
status=JobStatus.INSTRUMENTAL_SELECTED,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test",
title="Song",
)
result = validate_worker_can_run("video_worker", job)
assert result is None
class TestWorkerIdempotencyTerminalState:
"""Tests for _check_worker_idempotency terminal state handling."""
def test_idempotency_rejects_failed_job(self):
"""Idempotency check returns skip response for failed jobs."""
from backend.api.routes.internal import _check_worker_idempotency
failed_job = Job(
job_id="test-failed",
status=JobStatus.FAILED,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test",
title="Song",
)
with patch("backend.api.routes.internal.JobManager") as MockJM:
MockJM.return_value.get_job.return_value = failed_job
result = _check_worker_idempotency("test-failed", "video")
assert result is not None
assert result.status == "skipped"
assert "terminal state" in result.message.lower()
def test_idempotency_rejects_cancelled_job(self):
"""Idempotency check returns skip response for cancelled jobs."""
from backend.api.routes.internal import _check_worker_idempotency
cancelled_job = Job(
job_id="test-cancelled",
status=JobStatus.CANCELLED,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test",
title="Song",
)
with patch("backend.api.routes.internal.JobManager") as MockJM:
MockJM.return_value.get_job.return_value = cancelled_job
result = _check_worker_idempotency("test-cancelled", "video")
assert result is not None
assert result.status == "skipped"
def test_idempotency_allows_instrumental_selected_job(self):
"""Idempotency check allows jobs in non-terminal states."""
from backend.api.routes.internal import _check_worker_idempotency
job = Job(
job_id="test-ok",
status=JobStatus.INSTRUMENTAL_SELECTED,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test",
title="Song",
)
with patch("backend.api.routes.internal.JobManager") as MockJM:
mock_jm = MockJM.return_value
mock_jm.get_job.return_value = job
mock_jm.update_state_data.return_value = None
result = _check_worker_idempotency("test-ok", "video")
assert result is None
class TestDistributionWarningsContract:
"""Contract tests verifying distribution_warnings code paths don't crash.
Regression: generate_video_orchestrated() and _handle_native_distribution()
both called _send_distribution_warning_notification(settings=settings) but
never defined 'settings' in their scope. These tests ensure the notification
call site works without NameError.
"""
def test_send_distribution_warning_notification_works_without_settings(self):
"""_send_distribution_warning_notification handles settings=None."""
from backend.workers.video_worker import _send_distribution_warning_notification
# Should not crash — settings defaults to None and is fetched internally
with patch('backend.workers.video_worker.get_settings') as mock_settings:
mock_settings.return_value.get_secret.return_value = None # No pushbullet key
_send_distribution_warning_notification(
job_id="test-123",
artist="Test",
title="Song",
warnings=["Dropbox failed"],
)
mock_settings.assert_called_once()
def test_generate_video_orchestrated_no_settings_reference(self):
"""Verify generate_video_orchestrated doesn't reference undefined 'settings'.
Static analysis: scan the function source for 'settings=settings' which
would indicate a NameError if settings is not defined in scope.
"""
import inspect
from backend.workers.video_worker import generate_video_orchestrated
source = inspect.getsource(generate_video_orchestrated)
assert "settings=settings" not in source, (
"generate_video_orchestrated references 'settings=settings' but never defines 'settings'. "
"Use settings=None or omit the argument — _send_distribution_warning_notification "
"handles settings=None internally via get_settings()."
)
def test_handle_native_distribution_no_settings_reference(self):
"""Verify _handle_native_distribution doesn't reference undefined 'settings'.
Static analysis: same check as above for the other call site.
"""
import inspect
from backend.workers.video_worker import _handle_native_distribution
source = inspect.getsource(_handle_native_distribution)
assert "settings=settings" not in source, (
"_handle_native_distribution references 'settings=settings' but never defines 'settings'. "
"Use settings=None or omit the argument."
)
+23
View File
@@ -0,0 +1,23 @@
"""
Request utility helpers for extracting client information.
"""
from typing import Optional
from fastapi import Request
def get_client_ip(request: Request) -> Optional[str]:
"""
Extract real client IP address from a request.
Cloud Run and load balancers set X-Forwarded-For header with the
original client IP as the first entry. Falls back to request.client.host
for direct connections (local dev).
Returns None if no IP can be determined.
"""
forwarded = request.headers.get("x-forwarded-for", "")
if forwarded:
return forwarded.split(",")[0].strip()
if request.client:
return request.client.host
return None
+23 -1
View File
@@ -1,8 +1,11 @@
"""
Utilities for identifying test data.
Utilities for identifying test data and internal accounts.
Test data is generated by automated E2E tests and should be filterable
in admin dashboards to show only real user data by default.
Internal accounts belong to team members and should be excluded from
abuse investigation views.
"""
# Email domains used by automated testing frameworks
@@ -10,6 +13,12 @@ TEST_EMAIL_DOMAINS = [
"inbox.testmail.app", # Used by E2E happy path tests
]
# Email domains belonging to internal team members
INTERNAL_EMAIL_DOMAINS = [
"nomadkaraoke.com", # Team accounts
"beveridge.uk", # Founder's personal domain
]
def is_test_email(email: str) -> bool:
"""
@@ -25,3 +34,16 @@ def is_test_email(email: str) -> bool:
return False
email_lower = email.lower()
return any(email_lower.endswith(f"@{domain}") for domain in TEST_EMAIL_DOMAINS)
def is_internal_email(email: str) -> bool:
"""Check if an email address belongs to an internal team member."""
if not email:
return False
email_lower = email.lower()
return any(email_lower.endswith(f"@{domain}") for domain in INTERNAL_EMAIL_DOMAINS)
def is_internal_or_test_email(email: str) -> bool:
"""Check if an email is internal or automated test data."""
return is_test_email(email) or is_internal_email(email)
+15
View File
@@ -25,3 +25,18 @@ def get_version() -> str:
VERSION = get_version()
# Build metadata — set by CI during deployment
COMMIT_SHA = os.environ.get("COMMIT_SHA", "")
PR_NUMBER = os.environ.get("PR_NUMBER", "")
PR_TITLE = os.environ.get("PR_TITLE", "")
STARTUP_TIME = None # Set on first import
def _get_startup_time() -> str:
"""Record when the backend process started (proxy for deploy time)."""
from datetime import datetime, timezone
return datetime.now(timezone.utc).isoformat()
STARTUP_TIME = _get_startup_time()
+20
View File
@@ -140,6 +140,26 @@ async def process_audio_download(job_id: str) -> bool:
if job and job.state_data.get('requires_audio_edit'):
# Preserve the original input path before any edits
job_manager.update_state_data(job_id, 'original_input_media_gcs_path', audio_gcs_path)
# Pre-generate audio editor assets (OGG transcode + waveform data)
# so the editor UI loads instantly. Non-fatal if this fails.
waveform_cache_path = f"jobs/{job_id}/audio_edit/waveform_original.json"
try:
from backend.services.audio_transcoding_service import AudioTranscodingService
from backend.services.audio_analysis_service import AudioAnalysisService
transcoding = AudioTranscodingService()
transcoding.transcode_if_needed(audio_gcs_path)
logger.info(f"[job:{job_id}] Pre-transcoded input audio to OGG for editor")
analysis = AudioAnalysisService()
analysis.cache_waveform_data(audio_gcs_path, job_id, waveform_cache_path)
logger.info(f"[job:{job_id}] Pre-generated waveform data for editor")
job_manager.update_state_data(job_id, 'audio_edit_waveform_cache_path', waveform_cache_path)
except Exception as e:
logger.warning(f"[job:{job_id}] Failed to pre-generate editor assets (non-fatal): {e}")
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.AWAITING_AUDIO_EDIT,
+197 -51
View File
@@ -2,11 +2,13 @@
Audio separation worker.
Handles the audio processing track of parallel processing:
1. Stage 1: Clean instrumental separation (Modal API, 3-5 min)
2. Stage 2: Backing vocals separation (Modal API, 2-3 min)
1. Stage 1: Clean instrumental separation (GPU, 3-5 min)
2. Stage 2: Backing vocals separation (GPU, 2-3 min)
3. Post-processing: Combine instrumentals, normalize
Re-uses karaoke_gen.audio_processor.AudioProcessor for remote GPU separation.
Supports two modes:
- Local GPU: Runs Separator directly with L4 GPU (MODEL_DIR env var)
- Remote API: Calls audio-separator Cloud Run Service (AUDIO_SEPARATOR_API_URL env var)
Observability:
- All operations wrapped in tracing spans for Cloud Trace visibility
@@ -61,10 +63,15 @@ async def _trigger_lyrics_worker_after_url_download(job_id: str) -> None:
logger.error(f"Job {job_id}: Failed to trigger lyrics worker: {e}")
# Default model names - used by create_audio_processor and stored in state_data
# Default ensemble presets — resolved by audio-separator package into models + algorithm.
# To change models, update ensemble_presets.json in audio-separator and release a new version.
DEFAULT_INSTRUMENTAL_PRESET = "instrumental_clean" # Fv7z + Resurrection, SDR ~17.5
DEFAULT_KARAOKE_PRESET = "karaoke" # 3 karaoke models ensemble, SDR ~10.6
# Legacy model name constants — kept for backward compatibility with per-job overrides
DEFAULT_CLEAN_MODEL = "model_bs_roformer_ep_317_sdr_12.9755.ckpt"
DEFAULT_BACKING_MODELS = ["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"]
DEFAULT_OTHER_MODELS = ["htdemucs_6s.yaml"]
DEFAULT_OTHER_MODELS = [] # Demucs 6-stem dropped — no longer separating individual instruments
# Loggers to capture for audio worker
@@ -195,52 +202,71 @@ async def download_from_url(url: str, temp_dir: str, artist: str, title: str, jo
def create_audio_processor(
temp_dir: str,
model_file_dir: Optional[str] = None,
clean_instrumental_model: Optional[str] = None,
backing_vocals_models: Optional[list] = None,
other_stems_models: Optional[list] = None
other_stems_models: Optional[list] = None,
instrumental_preset: Optional[str] = None,
karaoke_preset: Optional[str] = None,
) -> AudioProcessor:
"""
Create an AudioProcessor instance configured for remote API processing.
This reuses the karaoke_gen AudioProcessor with settings optimized for Cloud Run:
- Uses remote Modal API (via AUDIO_SEPARATOR_API_URL env var)
- No local models needed (model_file_dir=None)
- FLAC output format for quality
- Model configurations from job or CLI defaults
Create an AudioProcessor instance configured for audio processing.
Supports two modes:
- Local GPU mode: When model_file_dir is set, uses the local Separator class
with GPU models loaded from that directory. No remote API calls.
- Remote API mode (default): When model_file_dir is None, delegates separation
to a remote audio-separator API server.
Within each mode, separation can be configured via:
- Preset mode (default): Uses ensemble presets for higher quality separation.
Presets are resolved by the audio-separator API server (remote) or local
preset definitions (local GPU).
- Model mode (legacy): Uses explicit model filenames for per-job overrides.
Args:
temp_dir: Temporary directory for processing
clean_instrumental_model: Model for clean instrumental separation (optional, uses default if not provided)
backing_vocals_models: List of models for backing vocals separation (optional, uses default if not provided)
other_stems_models: List of models for other stems separation (optional, uses default if not provided)
model_file_dir: Directory containing local model files for GPU separation.
When set, enables local GPU mode. When None (default), uses remote API.
clean_instrumental_model: Model for clean instrumental (legacy, overrides preset)
backing_vocals_models: Models for backing vocals (legacy, overrides preset)
other_stems_models: Models for other stems (legacy, default empty)
instrumental_preset: Ensemble preset for instrumental separation
karaoke_preset: Ensemble preset for karaoke/BV separation
Returns:
Configured AudioProcessor instance
"""
# Configure logger for AudioProcessor
audio_logger = logging.getLogger("karaoke_gen.audio_processor")
audio_logger.setLevel(logging.INFO)
# Model configurations - use provided values or defaults from module constants
# Determine effective configuration
# If explicit models are provided, use them (legacy per-job override)
# Otherwise use ensemble presets (default)
effective_clean_model = clean_instrumental_model or DEFAULT_CLEAN_MODEL
effective_backing_models = backing_vocals_models or DEFAULT_BACKING_MODELS
effective_other_models = other_stems_models or DEFAULT_OTHER_MODELS # For 6-stem separation (bass, drums, etc.)
# FFmpeg command for combining audio files (must be a string, not a list)
effective_other_models = other_stems_models or DEFAULT_OTHER_MODELS
ffmpeg_base_command = "ffmpeg -hide_banner -loglevel error -nostats -y"
return AudioProcessor(
processor = AudioProcessor(
logger=audio_logger,
log_level=logging.INFO,
log_formatter=None, # Not needed for our use case
model_file_dir=None, # No local models, using remote API
log_formatter=None,
model_file_dir=model_file_dir,
lossless_output_format="FLAC",
clean_instrumental_model=effective_clean_model,
backing_vocals_models=effective_backing_models,
other_stems_models=effective_other_models,
ffmpeg_base_command=ffmpeg_base_command
ffmpeg_base_command=ffmpeg_base_command,
)
# Set preset configuration (used by both remote and local paths)
processor.instrumental_preset = instrumental_preset or DEFAULT_INSTRUMENTAL_PRESET
processor.karaoke_preset = karaoke_preset or DEFAULT_KARAOKE_PRESET
return processor
async def process_audio_separation(job_id: str) -> bool:
"""
@@ -251,8 +277,8 @@ async def process_audio_separation(job_id: str) -> bool:
Workflow:
1. Download audio from GCS
2. Stage 1: Separate with clean instrumental + other stems models (Modal API)
3. Stage 2: Separate vocals for backing vocals (Modal API)
2. Stage 1: Separate with clean instrumental + other stems models (GPU)
3. Stage 2: Separate vocals for backing vocals (GPU)
4. Post-process: Combine instrumentals, normalize audio
5. Upload all stems to GCS
6. Mark job as AUDIO_COMPLETE
@@ -312,13 +338,22 @@ async def process_audio_separation(job_id: str) -> bool:
job_log.info(f"Starting audio separation for {job.artist} - {job.title}")
logger.info(f"[job:{job_id}] Starting audio separation for {job.artist} - {job.title}")
# Ensure AUDIO_SEPARATOR_API_URL is set
# Determine separation mode: local GPU or remote API
api_url = os.environ.get("AUDIO_SEPARATOR_API_URL")
if not api_url:
raise Exception("AUDIO_SEPARATOR_API_URL environment variable not set. "
"Cannot perform audio separation without remote API access.")
job_log.info(f"Audio separator API: {api_url}")
add_span_attribute("audio_separator_api", api_url)
model_dir = os.environ.get("MODEL_DIR")
if api_url:
job_log.info(f"Audio separator mode: remote API at {api_url}")
add_span_attribute("audio_separator_mode", "remote")
add_span_attribute("audio_separator_api", api_url)
elif model_dir:
job_log.info(f"Audio separator mode: local GPU (models at {model_dir})")
add_span_attribute("audio_separator_mode", "local_gpu")
add_span_attribute("model_dir", model_dir)
else:
raise Exception(
"Audio separation not configured. Set either AUDIO_SEPARATOR_API_URL "
"(remote API) or MODEL_DIR (local GPU with baked-in models)."
)
# Download audio file from GCS or URL
with job_span("download-audio", job_id) as download_span:
@@ -330,6 +365,9 @@ async def process_audio_separation(job_id: str) -> bool:
download_span.set_attribute("audio_file", os.path.basename(audio_path))
download_span.set_attribute("source", "url" if job.url else "gcs")
# Capture input audio properties via ffprobe (before any processing)
_store_audio_source_metadata(job_manager, job_id, audio_path, job_log)
# Update progress using state_data (don't change status during parallel processing)
# The status is managed at a higher level - workers just track their progress
job_manager.update_state_data(job_id, 'audio_progress', {
@@ -353,8 +391,15 @@ async def process_audio_separation(job_id: str) -> bool:
temp_dir,
clean_instrumental_model=job.clean_instrumental_model,
backing_vocals_models=job.backing_vocals_models,
other_stems_models=job.other_stems_models
other_stems_models=job.other_stems_models,
model_file_dir=model_dir,
)
audio_processor.job_id = job_id # Used as filename prefix (avoids artist/title encoding issues)
# Pass GCS URI so the separator can fetch directly from GCS (avoids 413 for large files)
if job.input_media_gcs_path:
audio_processor.input_gcs_uri = f"gs://{settings.gcs_bucket_name}/{job.input_media_gcs_path}"
job_log.info(f" GCS URI for separator: {audio_processor.input_gcs_uri}")
# Store effective model names in state_data for video_worker to use in file naming
# This ensures output filenames match local CLI behavior (e.g., "Instrumental model_bs_roformer_ep_317_sdr_12.9755.ckpt")
@@ -374,22 +419,42 @@ async def process_audio_separation(job_id: str) -> bool:
safe_title = sanitize_filename(job.title) if job.title else "Unknown"
artist_title = f"{safe_artist} - {safe_title}"
# Run audio separation (calls Modal API internally)
# Run audio separation (local GPU or remote API)
# This returns a dict with paths to all separated stems
with job_span("modal-separation", job_id) as sep_span:
with job_span("audio-separation", job_id) as sep_span:
sep_start = time.time()
job_log.info("Starting audio separation (this may take 5-10 minutes)...")
job_log.info(" Stage 1: Clean instrumental separation (MDX models)")
job_log.info(" Stage 2: Backing vocals separation (Demucs model)")
add_span_event("separation_started")
logger.info(f"[job:{job_id}] Calling Modal API for audio separation")
logger.info(f"[job:{job_id}] Starting audio separation")
with metrics.time_external_api("modal", job_id):
separation_result = audio_processor.process_audio_separation(
audio_file=audio_path,
artist_title=artist_title,
track_output_dir=temp_dir
)
# Retry with exponential backoff. The audio-separator GPU service
# may be busy processing other jobs for 5-10+ minutes each, so we
# need patience: 60s, 120s, 240s, 480s = ~15 min total wait.
max_retries = 5
for attempt in range(1, max_retries + 1):
try:
with metrics.time_external_api("audio_separation", job_id):
separation_result = audio_processor.process_audio_separation(
audio_file=audio_path,
artist_title=artist_title,
track_output_dir=temp_dir
)
break # Success
except Exception as e:
error_str = str(e)
if attempt < max_retries:
wait_time = 60 * (2 ** (attempt - 1)) # 60s, 120s, 240s, 480s
job_log.warning(
f"Audio separation attempt {attempt}/{max_retries} failed: {error_str}. "
f"Retrying in {wait_time}s..."
)
logger.warning(f"[job:{job_id}] Separation attempt {attempt} failed: {error_str}")
time.sleep(wait_time)
else:
job_log.error(f"Audio separation failed after {max_retries} attempts: {error_str}")
raise
sep_duration = time.time() - sep_start
sep_span.set_attribute("duration_seconds", sep_duration)
@@ -414,18 +479,38 @@ async def process_audio_separation(job_id: str) -> bool:
logger.info(f"[job:{job_id}] All stems uploaded successfully")
# Store processing metadata for separation provenance
duration = time.time() - start_time
job_manager.update_processing_metadata(job_id, "separation", {
"provider": "local_gpu" if model_dir else "remote_api",
"clean_model": effective_model_names['clean_instrumental_model'],
"backing_models": effective_model_names['backing_vocals_models'],
"other_models": effective_model_names['other_stems_models'],
"stems_generated": list(separation_result.keys()),
"duration_seconds": round(sep_duration, 1),
})
job_manager.update_processing_metadata(job_id, "timing.audio_worker_seconds", round(duration, 1))
# Analyze backing vocals for instrumental selection recommendation
# This must run here (after stems are uploaded) rather than in screens_worker,
# because screens_worker triggers on lyrics completion and audio may not be done yet
from backend.workers.screens_worker import _analyze_backing_vocals
try:
await _analyze_backing_vocals(job_id, job_manager, storage, job_log)
except Exception as e:
logger.warning(f"[job:{job_id}] Backing vocals analysis failed (non-fatal): {e}")
# Mark audio processing complete
# This will check if lyrics are also complete and transition to next stage if so
job_manager.mark_audio_complete(job_id)
duration = time.time() - start_time
root_span.set_attribute("duration_seconds", duration)
logger.info(f"[job:{job_id}] WORKER_END worker=audio status=success duration={duration:.1f}s")
return True
except Exception as e:
duration = time.time() - start_time
logger.error(f"[job:{job_id}] WORKER_END worker=audio status=error duration={duration:.1f}s error={e}")
logger.error(f"[job:{job_id}] WORKER_END worker=audio status=error duration={duration:.1f}s error={e}", exc_info=True)
job_manager.mark_job_failed(
job_id=job_id,
error_message=f"Audio separation failed: {str(e)}",
@@ -668,6 +753,67 @@ async def upload_separation_results(
logger.info(f"Job {job_id}: Stored instrumental options: {list(instrumental_options.keys())}")
def _store_audio_source_metadata(
job_manager: JobManager,
job_id: str,
audio_path: str,
job_log,
) -> None:
"""Run ffprobe on input audio and store properties in processing_metadata.
Captures format, codec, sample rate, channels, duration, file size, and bitrate.
Non-fatal: failures are logged but don't stop the job.
"""
import subprocess
import json as _json
try:
result = subprocess.run(
[
"ffprobe", "-v", "quiet", "-print_format", "json",
"-show_format", "-show_streams", audio_path,
],
capture_output=True, text=True, timeout=30,
)
if result.returncode != 0:
job_log.warning(f"ffprobe failed (rc={result.returncode}): {result.stderr[:200]}")
return
probe = _json.loads(result.stdout)
fmt = probe.get("format", {})
# Find audio stream
audio_stream = None
for stream in probe.get("streams", []):
if stream.get("codec_type") == "audio":
audio_stream = stream
break
metadata = {
"input_format": fmt.get("format_name", "").split(",")[0],
"input_duration_seconds": round(float(fmt.get("duration", 0)), 1),
"input_file_size_bytes": int(fmt.get("size", 0)),
"input_bitrate_kbps": round(int(fmt.get("bit_rate", 0)) / 1000) if fmt.get("bit_rate") else None,
}
if audio_stream:
metadata.update({
"input_codec": audio_stream.get("codec_name"),
"input_sample_rate": int(audio_stream.get("sample_rate", 0)) or None,
"input_channels": audio_stream.get("channels"),
"input_bit_depth": int(audio_stream.get("bits_per_raw_sample", 0)) or None,
})
job_manager.update_processing_metadata(job_id, "audio_source", metadata)
job_log.info(f"Audio source: {metadata.get('input_codec', '?')} "
f"{metadata.get('input_sample_rate', '?')}Hz "
f"{metadata.get('input_channels', '?')}ch "
f"{metadata.get('input_duration_seconds', '?')}s")
except Exception as e:
job_log.warning(f"Failed to capture audio source metadata (non-fatal): {e}")
logger.warning(f"Job {job_id}: ffprobe metadata capture failed: {e}")
# ==================== CLI Entry Point for Cloud Run Jobs ====================
# This allows the audio worker to be run as a standalone Cloud Run Job.
# Usage: python -m backend.workers.audio_worker --job-id <job_id>
@@ -686,7 +832,7 @@ def main():
Environment Variables:
GOOGLE_CLOUD_PROJECT: GCP project ID (required)
GCS_BUCKET_NAME: Storage bucket name (required)
AUDIO_SEPARATOR_API_URL: Modal API URL (required)
AUDIO_SEPARATOR_API_URL: Remote API URL (or MODEL_DIR for local GPU)
"""
import argparse
import asyncio
+149 -44
View File
@@ -29,7 +29,6 @@ from typing import Optional, Dict, Any
from pathlib import Path
from backend.models.job import JobStatus
from karaoke_gen.utils import sanitize_filename
from backend.services.job_manager import JobManager
from backend.services.storage_service import StorageService
from backend.services.job_health_service import validate_worker_can_run
@@ -420,6 +419,12 @@ async def process_lyrics_transcription(job_id: str) -> bool:
job_log.info("Transcription processing complete")
logger.info(f"[job:{job_id}] Transcription complete, uploading results")
# Store processing metadata for transcription + correction provenance
_store_lyrics_processing_metadata(
job_manager, job_id, result, trans_duration,
cache_stats if 'cache_stats' in locals() else None, job_log
)
# Upload lyrics results to GCS
with job_span("upload-lyrics-results", job_id):
@@ -458,6 +463,8 @@ async def process_lyrics_transcription(job_id: str) -> bool:
job_manager.mark_lyrics_complete(job_id)
duration = time.time() - start_time
# Store worker-level timing
job_manager.update_processing_metadata(job_id, "timing.lyrics_worker_seconds", round(duration, 1))
root_span.set_attribute("duration_seconds", duration)
logger.info(f"[job:{job_id}] WORKER_END worker=lyrics status=success duration={duration:.1f}s")
return True
@@ -591,10 +598,7 @@ async def upload_lyrics_results(
job_log: Optional JobLogger for remote debugging
"""
logger.info(f"Job {job_id}: Uploading lyrics results to GCS")
# Get job object for artist/title
job = job_manager.get_job(job_id)
lyrics_dir = os.path.join(temp_dir, "lyrics")
# Upload LRC file (timed lyrics)
@@ -606,17 +610,21 @@ async def upload_lyrics_results(
# Upload corrections JSON (for review interface)
# LyricsProcessor saves it as "{artist} - {title} (Lyrics Corrections).json"
# Sanitize artist/title to prevent path injection and match LyricsProcessor's sanitization
safe_artist = sanitize_filename(job.artist) if job.artist else "Unknown"
safe_title = sanitize_filename(job.title) if job.title else "Unknown"
corrections_filename = f"{safe_artist} - {safe_title} (Lyrics Corrections).json"
corrections_file = os.path.join(lyrics_dir, corrections_filename)
# Scan the directory instead of reconstructing the filename, because the artist/title
# in Firestore may have been updated (e.g. by admin) after LyricsProcessor generated the file.
corrections_file = None
if os.path.isdir(lyrics_dir):
for fname in os.listdir(lyrics_dir):
if fname.endswith("(Lyrics Corrections).json"):
corrections_file = os.path.join(lyrics_dir, fname)
break
# Fallback: check for generic corrections.json
if not corrections_file:
fallback = os.path.join(lyrics_dir, "corrections.json")
if os.path.exists(fallback):
corrections_file = fallback
# Also check for generic corrections.json (fallback)
if not os.path.exists(corrections_file):
corrections_file = os.path.join(lyrics_dir, "corrections.json")
if os.path.exists(corrections_file):
if corrections_file and os.path.exists(corrections_file):
# Always upload as corrections.json for consistent access
gcs_path = f"jobs/{job_id}/lyrics/corrections.json"
url = storage.upload_file(corrections_file, gcs_path)
@@ -652,33 +660,29 @@ async def upload_lyrics_results(
else:
# CRITICAL: corrections.json is required for the review UI
# If it's missing, the job cannot proceed to review
error_msg = f"No corrections JSON found at {corrections_file}. Transcription may have produced no lyrics."
error_msg = f"No corrections JSON found in {lyrics_dir}. Transcription may have produced no lyrics."
logger.error(f"Job {job_id}: {error_msg}")
raise Exception(error_msg)
# Upload ALL reference lyrics files (not just first) so they're available for distribution
# Note: Source names use .title() so "lrclib" -> "Lrclib", "genius" -> "Genius"
# Use sanitized artist/title to match LyricsProcessor's file naming
reference_files = [
(f"{safe_artist} - {safe_title} (Lyrics Genius).txt", "genius"),
(f"{safe_artist} - {safe_title} (Lyrics Spotify).txt", "spotify"),
(f"{safe_artist} - {safe_title} (Lyrics Musixmatch).txt", "musixmatch"),
(f"{safe_artist} - {safe_title} (Lyrics Lrclib).txt", "lrclib"),
]
# Scan directory for reference files instead of reconstructing filenames,
# since artist/title may have changed in Firestore after file generation.
source_keys = {"Genius": "genius", "Spotify": "spotify", "Musixmatch": "musixmatch", "Lrclib": "lrclib"}
found_references = []
for ref_filename, source_key in reference_files:
ref_path = os.path.join(lyrics_dir, ref_filename)
if os.path.exists(ref_path):
# Upload with original filename to preserve proper naming
gcs_path = f"jobs/{job_id}/lyrics/{ref_filename}"
url = storage.upload_file(ref_path, gcs_path)
# Track in job.files so video_worker can download for distribution
job_manager.update_file_url(job_id, 'lyrics', f'reference_{source_key}', url)
if job_log:
job_log.info(f"Found reference lyrics from {source_key}")
logger.info(f"Job {job_id}: Uploaded reference lyrics: {ref_filename}")
found_references.append(source_key)
if os.path.isdir(lyrics_dir):
for fname in os.listdir(lyrics_dir):
for source_label, source_key in source_keys.items():
if fname.endswith(f"(Lyrics {source_label}).txt"):
ref_path = os.path.join(lyrics_dir, fname)
gcs_path = f"jobs/{job_id}/lyrics/{fname}"
url = storage.upload_file(ref_path, gcs_path)
job_manager.update_file_url(job_id, 'lyrics', f'reference_{source_key}', url)
if job_log:
job_log.info(f"Found reference lyrics from {source_key}")
logger.info(f"Job {job_id}: Uploaded reference lyrics: {fname}")
found_references.append(source_key)
break
if not found_references:
if job_log:
@@ -687,18 +691,119 @@ async def upload_lyrics_results(
else:
logger.info(f"Job {job_id}: Found {len(found_references)} reference lyrics sources: {found_references}")
# Upload uncorrected transcription if available (preserve original filename for distribution)
uncorrected_filename = f"{safe_artist} - {safe_title} (Lyrics Uncorrected).txt"
uncorrected_file = os.path.join(lyrics_dir, uncorrected_filename)
if os.path.exists(uncorrected_file):
gcs_path = f"jobs/{job_id}/lyrics/{uncorrected_filename}"
url = storage.upload_file(uncorrected_file, gcs_path)
job_manager.update_file_url(job_id, 'lyrics', 'uncorrected', url)
logger.info(f"Job {job_id}: Uploaded uncorrected transcription: {uncorrected_filename}")
# Upload uncorrected transcription if available
# Scan directory instead of reconstructing filename (artist/title may have changed)
if os.path.isdir(lyrics_dir):
for fname in os.listdir(lyrics_dir):
if fname.endswith("(Lyrics Uncorrected).txt"):
uncorrected_file = os.path.join(lyrics_dir, fname)
gcs_path = f"jobs/{job_id}/lyrics/{fname}"
url = storage.upload_file(uncorrected_file, gcs_path)
job_manager.update_file_url(job_id, 'lyrics', 'uncorrected', url)
logger.info(f"Job {job_id}: Uploaded uncorrected transcription: {fname}")
break
logger.info(f"Job {job_id}: All lyrics results uploaded successfully")
def _store_lyrics_processing_metadata(
job_manager: JobManager,
job_id: str,
transcription_result: Dict[str, Any],
transcription_duration: float,
cache_stats: Optional[Dict[str, Any]],
job_log,
) -> None:
"""Store transcription and correction provenance in processing_metadata.
Extracts AudioShake task_id/asset_id, correction stats, reference sources,
and cache hit/miss info from the transcription result and stores them
permanently for future analytics, debugging, and data export.
"""
try:
# Load the corrections.json data from the result to get metadata
# The transcription_result is the dict returned by LyricsProcessor.transcribe_lyrics()
# which contains file paths, not the corrections data directly.
# We need to find and read the corrections JSON from the output directory.
corrections_metadata = {}
transcription_metadata = {}
# Try to find corrections file in the result's output directory
lyrics_dir = transcription_result.get("lyrics_dir") or ""
corrections_file = None
# Check common paths for corrections JSON
if lyrics_dir:
for fname in os.listdir(lyrics_dir) if os.path.isdir(lyrics_dir) else []:
if fname.endswith("(Lyrics Corrections).json") or fname == "corrections.json":
corrections_file = os.path.join(lyrics_dir, fname)
break
if corrections_file and os.path.exists(corrections_file):
with open(corrections_file, 'r', encoding='utf-8') as f:
corrections_data = json.load(f)
metadata = corrections_data.get("metadata", {})
# Extract AudioShake IDs from transcription_metadata passthrough
trans_meta = metadata.get("transcription_metadata", {})
if trans_meta:
transcription_metadata = {
"provider": "audioshake",
"audioshake_task_id": trans_meta.get("task_id"),
"audioshake_asset_id": trans_meta.get("asset_id"),
"language_detected": trans_meta.get("language"),
}
# Extract correction stats
corrections_metadata = {
"handlers_applied": metadata.get("enabled_handlers", []),
"corrections_made": corrections_data.get("corrections_made", 0),
"correction_ratio": metadata.get("correction_ratio"),
"agentic_routing": metadata.get("agentic_routing"),
"total_words": metadata.get("total_words"),
"anchor_sequences_count": metadata.get("anchor_sequences_count"),
"gap_sequences_count": metadata.get("gap_sequences_count"),
}
# Count segments and words from corrected_segments
corrected_segments = corrections_data.get("corrected_segments", [])
transcription_metadata["segment_count"] = len(corrected_segments)
transcription_metadata["word_count"] = sum(
len(seg.get("words", [])) for seg in corrected_segments
)
# Determine which reference sources were found
reference_lyrics = corrections_data.get("reference_lyrics", {})
if reference_lyrics:
corrections_metadata["reference_sources_found"] = list(reference_lyrics.keys())
# Add transcription duration
transcription_metadata["duration_seconds"] = round(transcription_duration, 1)
# Store transcription metadata
if transcription_metadata:
job_manager.update_processing_metadata(job_id, "transcription", transcription_metadata)
# Store correction metadata
if corrections_metadata:
job_manager.update_processing_metadata(job_id, "correction", corrections_metadata)
# Store cache stats
if cache_stats:
job_manager.update_processing_metadata(job_id, "cache", {
"transcription_cache_downloaded": cache_stats.get("downloaded", 0),
"transcription_cache_not_found": cache_stats.get("not_found", 0),
})
job_log.info("Stored processing metadata (transcription + correction provenance)")
except Exception as e:
# Never fail a job because metadata storage failed
job_log.warning(f"Failed to store lyrics processing metadata (non-fatal): {e}")
logger.warning(f"Job {job_id}: Failed to store lyrics processing metadata: {e}")
# ==================== CLI Entry Point for Cloud Run Jobs ====================
# This allows the lyrics worker to be run as a standalone Cloud Run Job.
# Usage: python -m backend.workers.lyrics_worker --job-id <job_id>
+366 -209
View File
@@ -40,11 +40,13 @@ from backend.services.job_health_service import validate_worker_can_run
from backend.config import get_settings
from backend.workers.worker_logging import create_job_logger, setup_job_logging, job_logging_context
from backend.services.tracing import job_span, add_span_event, add_span_attribute
from backend.services.encoding_service import get_encoding_service
# Import from lyrics_transcriber (submodule)
from karaoke_gen.lyrics_transcriber.output.generator import OutputGenerator
from karaoke_gen.lyrics_transcriber.output.countdown_processor import CountdownProcessor
from karaoke_gen.lyrics_transcriber.types import CorrectionResult
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
from karaoke_gen.lyrics_transcriber.core.config import OutputConfig
# Import from the unified style loader
@@ -118,248 +120,403 @@ async def process_render_video(job_id: str) -> bool:
# This ensures logs from third-party libraries (lyrics_transcriber.output) are only
# captured by this job's handler, not handlers from other concurrent jobs
with job_logging_context(job_id):
# Transition to RENDERING_VIDEO
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.RENDERING_VIDEO,
progress=75,
message="Rendering karaoke video with corrected lyrics"
)
with tempfile.TemporaryDirectory() as temp_dir:
job_log.info(f"Created temp directory: {temp_dir}")
# Try updated corrections first (from human review), fall back to original
corrections_gcs_updated = f"jobs/{job_id}/lyrics/corrections_updated.json"
corrections_gcs_original = f"jobs/{job_id}/lyrics/corrections.json"
# Get GCS path from file_urls
corrections_url = job.file_urls.get('lyrics', {}).get('corrections_updated')
if not corrections_url:
corrections_url = job.file_urls.get('lyrics', {}).get('corrections')
if not corrections_url:
# Try direct GCS paths
if storage.file_exists(corrections_gcs_updated):
corrections_gcs = corrections_gcs_updated
elif storage.file_exists(corrections_gcs_original):
corrections_gcs = corrections_gcs_original
else:
raise FileNotFoundError(f"No corrections file found for job {job_id}")
else:
# Extract GCS path from URL
corrections_gcs = _extract_gcs_path(corrections_url)
# 2. Load the ORIGINAL corrections (has full structure)
original_corrections_gcs = f"jobs/{job_id}/lyrics/corrections.json"
original_corrections_path = os.path.join(temp_dir, "corrections_original.json")
job_log.info(f"Downloading original corrections from {original_corrections_gcs}")
logger.info(f"Job {job_id}: Downloading original corrections from {original_corrections_gcs}")
storage.download_file(original_corrections_gcs, original_corrections_path)
with open(original_corrections_path, 'r', encoding='utf-8') as f:
original_data = json.load(f)
# 3. Check if there are updated corrections (from review UI)
# The frontend sends only partial data: {corrections, corrected_segments}
updated_corrections_gcs = f"jobs/{job_id}/lyrics/corrections_updated.json"
if storage.file_exists(updated_corrections_gcs):
job_log.info("Found updated corrections from review, merging")
logger.info(f"Job {job_id}: Found updated corrections, merging")
updated_path = os.path.join(temp_dir, "corrections_updated.json")
storage.download_file(updated_corrections_gcs, updated_path)
with open(updated_path, 'r', encoding='utf-8') as f:
updated_data = json.load(f)
# Merge: update the original with the user's corrections
if 'corrections' in updated_data:
original_data['corrections'] = updated_data['corrections']
if 'corrected_segments' in updated_data:
original_data['corrected_segments'] = updated_data['corrected_segments']
job_log.info("Merged user corrections into original data")
logger.info(f"Job {job_id}: Merged user corrections into original data")
# 4. Convert to CorrectionResult
correction_result = CorrectionResult.from_dict(original_data)
job_log.info(f"Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
logger.info(f"Job {job_id}: Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
# 5. Download audio file
audio_path = os.path.join(temp_dir, "audio.flac")
audio_gcs_path = job.input_media_gcs_path
if not audio_gcs_path:
raise FileNotFoundError(f"No input audio path for job {job_id}")
job_log.info(f"Downloading audio from {audio_gcs_path}")
logger.info(f"Job {job_id}: Downloading audio from {audio_gcs_path}")
storage.download_file(audio_gcs_path, audio_path)
job_log.info(f"Audio downloaded: {os.path.getsize(audio_path)} bytes")
# Process countdown intro if needed (for songs that start too quickly)
# This adds "3... 2... 1..." segment and pads audio with 3s silence
# Note: Countdown is deferred to this stage (not during lyrics transcription)
# so the review UI can show the original timing without the 3s shift
countdown_processor = CountdownProcessor(cache_dir=temp_dir, logger=logger)
correction_result, audio_path, padding_added, padding_seconds = countdown_processor.process(
correction_result=correction_result,
audio_filepath=audio_path,
)
if padding_added:
job_log.info(f"Countdown added: {padding_seconds}s padding applied to audio and timestamps shifted")
else:
job_log.info("No countdown needed - song starts after 3 seconds")
# Check if GCE encoding is enabled
encoding_service = get_encoding_service()
use_gce = encoding_service.is_enabled
# Update lyrics_metadata with countdown info so video_worker knows to pad instrumental
# This is critical for audio sync - without this, instrumental won't match padded vocals
if use_gce:
# ============ GCE RENDER VIDEO PATH ============
job_log.info("GCE encoding enabled - delegating render_video to encoding worker")
logger.info(f"[job:{job_id}] Using GCE encoding worker for render_video")
# Transition to RENDERING_VIDEO
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.RENDERING_VIDEO,
progress=75,
message="Rendering karaoke video on encoding worker"
)
# Build render config from job metadata (no downloads needed on Cloud Run!)
bucket_name = settings.gcs_bucket_name
# Check for updated corrections
updated_corrections_gcs = f"jobs/{job_id}/lyrics/corrections_updated.json"
has_updated = storage.file_exists(updated_corrections_gcs)
render_config = {
"original_corrections_gcs_path": f"gs://{bucket_name}/jobs/{job_id}/lyrics/corrections.json",
"audio_gcs_path": f"gs://{bucket_name}/{job.input_media_gcs_path}",
"output_gcs_prefix": f"gs://{bucket_name}/jobs/{job_id}/",
"artist": job.artist,
"title": job.title,
"subtitle_offset_ms": getattr(job, 'subtitle_offset_ms', 0) or 0,
"video_resolution": "4k",
}
if has_updated:
render_config["updated_corrections_gcs_path"] = f"gs://{bucket_name}/{updated_corrections_gcs}"
if job.style_params_gcs_path:
render_config["style_params_gcs_path"] = f"gs://{bucket_name}/{job.style_params_gcs_path}" if not job.style_params_gcs_path.startswith("gs://") else job.style_params_gcs_path
if job.style_assets:
render_config["style_assets"] = {
k: f"gs://{bucket_name}/{v}" if not v.startswith("gs://") else v
for k, v in job.style_assets.items()
}
def progress_callback(progress: int):
scaled = 75 + int(progress * 0.07) # Map 0-100 to 75-82
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.RENDERING_VIDEO,
progress=scaled,
message=f"Rendering video ({progress}%)"
)
with job_span("gce-render-video", job_id) as render_span:
render_start = time.time()
result = await encoding_service.render_video_on_gce(
job_id, render_config, progress_callback=progress_callback
)
render_duration = time.time() - render_start
render_span.set_attribute("duration_seconds", render_duration)
job_log.info(f"GCE render_video complete in {render_duration:.1f}s")
logger.info(f"[job:{job_id}] GCE render_video complete in {render_duration:.1f}s")
# Parse response and update Firestore
output_files = result.get("output_files", [])
metadata = result.get("metadata", {})
# Update file URLs from GCE response
for gcs_path in output_files:
blob_path = gcs_path
if blob_path.startswith("gs://"):
blob_path = blob_path.split("/", 3)[3] if blob_path.count("/") >= 3 else blob_path
if "with_vocals.mkv" in blob_path:
job_manager.update_file_url(job_id, 'videos', 'with_vocals', blob_path)
elif "karaoke.ass" in blob_path:
job_manager.update_file_url(job_id, 'lyrics', 'ass', blob_path)
elif "karaoke.lrc" in blob_path:
job_manager.update_file_url(job_id, 'lyrics', 'lrc', blob_path)
elif "corrected.txt" in blob_path:
job_manager.update_file_url(job_id, 'lyrics', 'corrected_txt', blob_path)
# Handle countdown padding metadata
padding_added = metadata.get("countdown_padding_added", False)
padding_seconds = metadata.get("countdown_padding_seconds", 0)
if padding_added:
existing_lyrics_metadata = job.state_data.get('lyrics_metadata', {})
existing_lyrics_metadata['has_countdown_padding'] = True
existing_lyrics_metadata['countdown_padding_seconds'] = padding_seconds
job_manager.update_state_data(job_id, 'lyrics_metadata', existing_lyrics_metadata)
job_log.info(f"Updated lyrics_metadata: has_countdown_padding=True, countdown_padding_seconds={padding_seconds}")
job_log.info(f"Countdown padding: {padding_seconds}s")
# 6. Get or create styles using the unified style loader
job_log.info("Loading style configuration...")
job_log.info(f" job.style_params_gcs_path: {job.style_params_gcs_path}")
job_log.info(f" job.style_assets: {list(job.style_assets.keys()) if job.style_assets else 'None'}")
styles_path, style_data = load_styles_from_gcs(
style_params_gcs_path=job.style_params_gcs_path,
style_assets=job.style_assets,
temp_dir=temp_dir,
download_func=storage.download_file,
logger=job_log,
)
# 7. Configure OutputGenerator
output_dir = os.path.join(temp_dir, "output")
cache_dir = os.path.join(temp_dir, "cache")
os.makedirs(output_dir, exist_ok=True)
os.makedirs(cache_dir, exist_ok=True)
job_log.info(f"Using styles from: {styles_path}")
# Get subtitle offset from job (user-specified timing adjustment)
subtitle_offset = getattr(job, 'subtitle_offset_ms', 0) or 0
if subtitle_offset != 0:
job_log.info(f"Applying subtitle offset: {subtitle_offset}ms")
config = OutputConfig(
output_dir=output_dir,
cache_dir=cache_dir,
output_styles_json=styles_path,
render_video=True,
generate_cdg=False, # CDG optional, generated separately
generate_plain_text=True,
generate_lrc=True,
video_resolution="4k",
subtitle_offset_ms=subtitle_offset
)
job_log.info(f"OutputConfig: output_styles_json={config.output_styles_json}, render_video={config.render_video}")
output_generator = OutputGenerator(config, logger)
# 8. Generate outputs (video, LRC, ASS, etc.)
# Sanitize artist/title to handle Unicode characters (curly quotes, em dashes, etc.)
safe_artist = sanitize_filename(job.artist) if job.artist else "Unknown"
safe_title = sanitize_filename(job.title) if job.title else "Unknown"
output_prefix = f"{safe_artist} - {safe_title}"
job_log.info(f"Generating outputs with prefix '{output_prefix}'")
logger.info(f"Job {job_id}: Generating outputs with prefix '{output_prefix}'")
outputs = output_generator.generate_outputs(
transcription_corrected=correction_result,
lyrics_results={}, # Reference lyrics already in correction_result
output_prefix=output_prefix,
audio_filepath=audio_path,
artist=job.artist,
title=job.title
)
# 9. Upload video to GCS
if outputs.video and os.path.exists(outputs.video):
video_size = os.path.getsize(outputs.video)
job_log.info(f"Video generated: {video_size} bytes")
video_gcs_path = f"jobs/{job_id}/videos/with_vocals.mkv"
video_url = storage.upload_file(outputs.video, video_gcs_path)
job_manager.update_file_url(job_id, 'videos', 'with_vocals', video_url)
job_log.info(f"Uploaded with_vocals.mkv to GCS")
logger.info(f"Job {job_id}: Uploaded with_vocals.mkv ({video_size} bytes)")
else:
job_log.error("Video generation failed - no output file produced!")
raise Exception("Video generation failed - no output file produced")
# 10. Upload LRC file
if outputs.lrc and os.path.exists(outputs.lrc):
lrc_gcs_path = f"jobs/{job_id}/lyrics/karaoke.lrc"
lrc_url = storage.upload_file(outputs.lrc, lrc_gcs_path)
job_manager.update_file_url(job_id, 'lyrics', 'lrc', lrc_url)
job_log.info("Uploaded karaoke.lrc")
logger.info(f"Job {job_id}: Uploaded karaoke.lrc")
# 11. Upload ASS subtitle file
if outputs.ass and os.path.exists(outputs.ass):
ass_gcs_path = f"jobs/{job_id}/lyrics/karaoke.ass"
ass_url = storage.upload_file(outputs.ass, ass_gcs_path)
job_manager.update_file_url(job_id, 'lyrics', 'ass', ass_url)
job_log.info("Uploaded karaoke.ass")
logger.info(f"Job {job_id}: Uploaded karaoke.ass")
# 12. Upload corrected text files
if outputs.corrected_txt and os.path.exists(outputs.corrected_txt):
txt_gcs_path = f"jobs/{job_id}/lyrics/corrected.txt"
txt_url = storage.upload_file(outputs.corrected_txt, txt_gcs_path)
job_manager.update_file_url(job_id, 'lyrics', 'corrected_txt', txt_url)
job_log.info("Uploaded corrected.txt")
logger.info(f"Job {job_id}: Uploaded corrected.txt")
# Store render timing
job_manager.update_processing_metadata(job_id, "rendering", {
"render_duration_seconds": round(render_duration, 1),
"countdown_padding_added": padding_added,
"countdown_padding_seconds": padding_seconds if padding_added else 0,
"rendered_on": "gce",
})
job_manager.update_processing_metadata(job_id, "timing.render_video_worker_seconds", round(render_duration, 1))
# 13. Transition based on prep_only flag
# Note: Instrumental selection was already made during combined review
# (stored in state_data['instrumental_selection'])
# Transition state (same as local path)
if getattr(job, 'prep_only', False):
# Prep-only mode: stop here and mark as prep complete
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.PREP_COMPLETE,
progress=100,
message="Prep phase complete - download outputs to continue locally"
)
job_log.info("=== RENDER VIDEO WORKER COMPLETE (PREP ONLY) ===")
job_log.info("=== RENDER VIDEO WORKER COMPLETE (PREP ONLY, GCE) ===")
duration = time.time() - start_time
root_span.set_attribute("duration_seconds", duration)
root_span.set_attribute("prep_only", True)
logger.info(f"[job:{job_id}] WORKER_END worker=render-video status=success duration={duration:.1f}s prep_only=true")
root_span.set_attribute("rendered_on", "gce")
logger.info(f"[job:{job_id}] WORKER_END worker=render-video status=success duration={duration:.1f}s gce=true prep_only=true")
else:
# Normal mode: instrumental was selected during combined review
# Transition directly to INSTRUMENTAL_SELECTED and trigger video worker
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.INSTRUMENTAL_SELECTED,
progress=82,
message="Video rendered, starting final encoding"
message="Video rendered on encoding worker, starting final encoding"
)
job_log.info("=== RENDER VIDEO WORKER COMPLETE ===")
job_log.info("=== RENDER VIDEO WORKER COMPLETE (GCE) ===")
duration = time.time() - start_time
root_span.set_attribute("duration_seconds", duration)
logger.info(f"[job:{job_id}] WORKER_END worker=render-video status=success duration={duration:.1f}s")
root_span.set_attribute("rendered_on", "gce")
logger.info(f"[job:{job_id}] WORKER_END worker=render-video status=success duration={duration:.1f}s gce=true")
# Trigger video worker for final encoding
from backend.services.worker_service import get_worker_service
worker_service = get_worker_service()
job_log.info("Triggering video worker for final encoding...")
await worker_service.trigger_video_worker(job_id)
# Mark render progress as complete for idempotency
# This allows the worker to be re-triggered after admin reset
job_manager.update_state_data(job_id, 'render_progress', {'stage': 'complete'})
return True
else:
# ============ LOCAL RENDER VIDEO PATH ============
# Transition to RENDERING_VIDEO
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.RENDERING_VIDEO,
progress=75,
message="Rendering karaoke video with corrected lyrics"
)
with tempfile.TemporaryDirectory() as temp_dir:
job_log.info(f"Created temp directory: {temp_dir}")
# Try updated corrections first (from human review), fall back to original
corrections_gcs_updated = f"jobs/{job_id}/lyrics/corrections_updated.json"
corrections_gcs_original = f"jobs/{job_id}/lyrics/corrections.json"
# Get GCS path from file_urls
corrections_url = job.file_urls.get('lyrics', {}).get('corrections_updated')
if not corrections_url:
corrections_url = job.file_urls.get('lyrics', {}).get('corrections')
if not corrections_url:
# Try direct GCS paths
if storage.file_exists(corrections_gcs_updated):
corrections_gcs = corrections_gcs_updated
elif storage.file_exists(corrections_gcs_original):
corrections_gcs = corrections_gcs_original
else:
raise FileNotFoundError(f"No corrections file found for job {job_id}")
else:
# Extract GCS path from URL
corrections_gcs = _extract_gcs_path(corrections_url)
# 2. Load the ORIGINAL corrections (has full structure)
original_corrections_gcs = f"jobs/{job_id}/lyrics/corrections.json"
original_corrections_path = os.path.join(temp_dir, "corrections_original.json")
job_log.info(f"Downloading original corrections from {original_corrections_gcs}")
logger.info(f"Job {job_id}: Downloading original corrections from {original_corrections_gcs}")
storage.download_file(original_corrections_gcs, original_corrections_path)
with open(original_corrections_path, 'r', encoding='utf-8') as f:
original_data = json.load(f)
# 3. Load base CorrectionResult from original data
base_result = CorrectionResult.from_dict(original_data)
# 4. Apply user corrections if available (from review UI)
# Uses the same method as preview generation to ensure
# identical CorrectionResult construction (DRY).
updated_corrections_gcs = f"jobs/{job_id}/lyrics/corrections_updated.json"
if storage.file_exists(updated_corrections_gcs):
job_log.info("Found updated corrections from review, applying via shared method")
logger.info(f"Job {job_id}: Found updated corrections, applying via shared method")
updated_path = os.path.join(temp_dir, "corrections_updated.json")
storage.download_file(updated_corrections_gcs, updated_path)
with open(updated_path, 'r', encoding='utf-8') as f:
updated_data = json.load(f)
if isinstance(updated_data, dict) and "corrections" in updated_data:
# Same construction path as preview — prevents divergence
correction_result = CorrectionOperations.update_correction_result_with_data(
base_result, updated_data
)
job_log.info("Applied user corrections via CorrectionOperations")
logger.info(f"Job {job_id}: Applied user corrections via CorrectionOperations")
else:
job_log.warning("corrections_updated.json exists but has no 'corrections' key, using base result")
logger.warning(f"Job {job_id}: corrections_updated.json has no 'corrections' key, using base result")
correction_result = base_result
else:
correction_result = base_result
job_log.info(f"Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
logger.info(f"Job {job_id}: Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
# 5. Download audio file
audio_path = os.path.join(temp_dir, "audio.flac")
audio_gcs_path = job.input_media_gcs_path
if not audio_gcs_path:
raise FileNotFoundError(f"No input audio path for job {job_id}")
job_log.info(f"Downloading audio from {audio_gcs_path}")
logger.info(f"Job {job_id}: Downloading audio from {audio_gcs_path}")
storage.download_file(audio_gcs_path, audio_path)
job_log.info(f"Audio downloaded: {os.path.getsize(audio_path)} bytes")
# Process countdown intro if needed (for songs that start too quickly)
# This adds "3... 2... 1..." segment and pads audio with 3s silence
# Note: Countdown is deferred to this stage (not during lyrics transcription)
# so the review UI can show the original timing without the 3s shift
countdown_processor = CountdownProcessor(cache_dir=temp_dir, logger=logger)
correction_result, audio_path, padding_added, padding_seconds = countdown_processor.process(
correction_result=correction_result,
audio_filepath=audio_path,
)
if padding_added:
job_log.info(f"Countdown added: {padding_seconds}s padding applied to audio and timestamps shifted")
else:
job_log.info("No countdown needed - song starts after 3 seconds")
# Update lyrics_metadata with countdown info so video_worker knows to pad instrumental
# This is critical for audio sync - without this, instrumental won't match padded vocals
if padding_added:
existing_lyrics_metadata = job.state_data.get('lyrics_metadata', {})
existing_lyrics_metadata['has_countdown_padding'] = True
existing_lyrics_metadata['countdown_padding_seconds'] = padding_seconds
job_manager.update_state_data(job_id, 'lyrics_metadata', existing_lyrics_metadata)
job_log.info(f"Updated lyrics_metadata: has_countdown_padding=True, countdown_padding_seconds={padding_seconds}")
# 6. Get or create styles using the unified style loader
job_log.info("Loading style configuration...")
job_log.info(f" job.style_params_gcs_path: {job.style_params_gcs_path}")
job_log.info(f" job.style_assets: {list(job.style_assets.keys()) if job.style_assets else 'None'}")
styles_path, style_data = load_styles_from_gcs(
style_params_gcs_path=job.style_params_gcs_path,
style_assets=job.style_assets,
temp_dir=temp_dir,
download_func=storage.download_file,
logger=job_log,
)
# 7. Configure OutputGenerator
output_dir = os.path.join(temp_dir, "output")
cache_dir = os.path.join(temp_dir, "cache")
os.makedirs(output_dir, exist_ok=True)
os.makedirs(cache_dir, exist_ok=True)
job_log.info(f"Using styles from: {styles_path}")
# Get subtitle offset from job (user-specified timing adjustment)
subtitle_offset = getattr(job, 'subtitle_offset_ms', 0) or 0
if subtitle_offset != 0:
job_log.info(f"Applying subtitle offset: {subtitle_offset}ms")
config = OutputConfig(
output_dir=output_dir,
cache_dir=cache_dir,
output_styles_json=styles_path,
render_video=True,
generate_cdg=False, # CDG optional, generated separately
generate_plain_text=True,
generate_lrc=True,
video_resolution="4k",
subtitle_offset_ms=subtitle_offset
)
job_log.info(f"OutputConfig: output_styles_json={config.output_styles_json}, render_video={config.render_video}")
output_generator = OutputGenerator(config, logger)
# 8. Generate outputs (video, LRC, ASS, etc.)
# Sanitize artist/title to handle Unicode characters (curly quotes, em dashes, etc.)
safe_artist = sanitize_filename(job.artist) if job.artist else "Unknown"
safe_title = sanitize_filename(job.title) if job.title else "Unknown"
output_prefix = f"{safe_artist} - {safe_title}"
job_log.info(f"Generating outputs with prefix '{output_prefix}'")
logger.info(f"Job {job_id}: Generating outputs with prefix '{output_prefix}'")
outputs = output_generator.generate_outputs(
transcription_corrected=correction_result,
lyrics_results={}, # Reference lyrics already in correction_result
output_prefix=output_prefix,
audio_filepath=audio_path,
artist=job.artist,
title=job.title
)
# 9. Upload video to GCS
if outputs.video and os.path.exists(outputs.video):
video_size = os.path.getsize(outputs.video)
job_log.info(f"Video generated: {video_size} bytes")
video_gcs_path = f"jobs/{job_id}/videos/with_vocals.mkv"
video_url = storage.upload_file(outputs.video, video_gcs_path)
job_manager.update_file_url(job_id, 'videos', 'with_vocals', video_url)
job_log.info(f"Uploaded with_vocals.mkv to GCS")
logger.info(f"Job {job_id}: Uploaded with_vocals.mkv ({video_size} bytes)")
else:
job_log.error("Video generation failed - no output file produced!")
raise Exception("Video generation failed - no output file produced")
# 10. Upload LRC file
if outputs.lrc and os.path.exists(outputs.lrc):
lrc_gcs_path = f"jobs/{job_id}/lyrics/karaoke.lrc"
lrc_url = storage.upload_file(outputs.lrc, lrc_gcs_path)
job_manager.update_file_url(job_id, 'lyrics', 'lrc', lrc_url)
job_log.info("Uploaded karaoke.lrc")
logger.info(f"Job {job_id}: Uploaded karaoke.lrc")
# 11. Upload ASS subtitle file
if outputs.ass and os.path.exists(outputs.ass):
ass_gcs_path = f"jobs/{job_id}/lyrics/karaoke.ass"
ass_url = storage.upload_file(outputs.ass, ass_gcs_path)
job_manager.update_file_url(job_id, 'lyrics', 'ass', ass_url)
job_log.info("Uploaded karaoke.ass")
logger.info(f"Job {job_id}: Uploaded karaoke.ass")
# 12. Upload corrected text files
if outputs.corrected_txt and os.path.exists(outputs.corrected_txt):
txt_gcs_path = f"jobs/{job_id}/lyrics/corrected.txt"
txt_url = storage.upload_file(outputs.corrected_txt, txt_gcs_path)
job_manager.update_file_url(job_id, 'lyrics', 'corrected_txt', txt_url)
job_log.info("Uploaded corrected.txt")
logger.info(f"Job {job_id}: Uploaded corrected.txt")
# Store render timing in processing metadata
render_duration = time.time() - start_time
job_manager.update_processing_metadata(job_id, "rendering", {
"render_duration_seconds": round(render_duration, 1),
"countdown_padding_added": padding_added,
"countdown_padding_seconds": padding_seconds if padding_added else 0,
})
job_manager.update_processing_metadata(job_id, "timing.render_video_worker_seconds", round(render_duration, 1))
# 13. Transition based on prep_only flag
# Note: Instrumental selection was already made during combined review
# (stored in state_data['instrumental_selection'])
if getattr(job, 'prep_only', False):
# Prep-only mode: stop here and mark as prep complete
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.PREP_COMPLETE,
progress=100,
message="Prep phase complete - download outputs to continue locally"
)
job_log.info("=== RENDER VIDEO WORKER COMPLETE (PREP ONLY) ===")
duration = time.time() - start_time
root_span.set_attribute("duration_seconds", duration)
root_span.set_attribute("prep_only", True)
logger.info(f"[job:{job_id}] WORKER_END worker=render-video status=success duration={duration:.1f}s prep_only=true")
else:
# Normal mode: instrumental was selected during combined review
# Transition directly to INSTRUMENTAL_SELECTED and trigger video worker
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.INSTRUMENTAL_SELECTED,
progress=82,
message="Video rendered, starting final encoding"
)
job_log.info("=== RENDER VIDEO WORKER COMPLETE ===")
duration = time.time() - start_time
root_span.set_attribute("duration_seconds", duration)
logger.info(f"[job:{job_id}] WORKER_END worker=render-video status=success duration={duration:.1f}s")
# Trigger video worker for final encoding
from backend.services.worker_service import get_worker_service
worker_service = get_worker_service()
job_log.info("Triggering video worker for final encoding...")
await worker_service.trigger_video_worker(job_id)
# Mark render progress as complete for idempotency
# This allows the worker to be re-triggered after admin reset
job_manager.update_state_data(job_id, 'render_progress', {'stage': 'complete'})
return True
except Exception as e:
duration = time.time() - start_time
+47 -52
View File
@@ -178,11 +178,8 @@ async def generate_screens(job_id: str) -> bool:
# Apply countdown padding if needed
await _apply_countdown_padding_if_needed(job_id, job_manager, job)
# Analyze backing vocals for combined review
# This runs BEFORE review so user can select instrumental during lyrics review
with job_span("analyze-backing-vocals", job_id):
job_log.info("Analyzing backing vocals for instrumental selection...")
await _analyze_backing_vocals(job_id, job_manager, storage, job_log)
# Note: backing vocals analysis now runs in audio_worker after stems are uploaded,
# since screens_worker triggers on lyrics completion and audio may not be done yet.
# Transcode review audio to OGG Opus for fast browser playback
# This runs BEFORE review so all files are cached when the user opens the UI
@@ -222,6 +219,8 @@ async def generate_screens(job_id: str) -> bool:
)
duration = time.time() - start_time
# Store worker-level timing
job_manager.update_processing_metadata(job_id, "timing.screens_worker_seconds", round(duration, 1))
root_span.set_attribute("duration_seconds", duration)
logger.info(f"[job:{job_id}] WORKER_END worker=screens status=success duration={duration:.1f}s")
@@ -256,7 +255,7 @@ async def generate_screens(job_id: str) -> bool:
def _validate_prerequisites(job) -> bool:
"""
Validate that both audio and lyrics processing are complete.
Validate that lyrics processing is complete (audio is no longer required).
Single Responsibility: Validation logic separated from main flow.
@@ -284,17 +283,19 @@ def _validate_prerequisites(job) -> bool:
)
return False
audio_complete = job.state_data.get('audio_complete', False)
lyrics_complete = job.state_data.get('lyrics_complete', False)
if not audio_complete:
logger.error(f"Job {job.job_id}: Audio processing not complete")
return False
audio_complete = job.state_data.get('audio_complete', False)
if not lyrics_complete:
logger.error(f"Job {job.job_id}: Lyrics processing not complete")
return False
# Audio separation is no longer a prerequisite for screens.
# Users can start lyrics review while separation runs in the background.
# The instrumental review page handles waiting for audio_complete.
if not audio_complete:
logger.info(f"Job {job.job_id}: Audio separation still in progress (not blocking screens)")
if not job.artist or not job.title:
logger.error(f"Job {job.job_id}: Missing artist or title")
return False
@@ -384,7 +385,9 @@ async def _generate_title_screen(
logger.info(f"Job {job_id}: Title format - bg_image: {title_format.get('background_image')}, font: {title_format.get('font')}")
# Generate title screen (synchronous method)
# Generate title screen images only (MOV video is generated on GCE encoding worker)
# Pass duration=0 to skip FFmpeg video creation — Cloud Run doesn't have enough
# memory for 4K H.264 encoding after right-sizing to 2Gi (PR #640).
video_generator.create_title_video(
artist=job.artist,
title=job.title,
@@ -392,12 +395,13 @@ async def _generate_title_screen(
output_image_filepath_noext=output_image_filepath_noext,
output_video_filepath=output_video_filepath,
existing_title_image=title_format.get('existing_image'),
intro_video_duration=intro_duration
intro_video_duration=0,
)
if os.path.exists(output_video_filepath):
logger.info(f"Job {job_id}: Title screen generated at {output_video_filepath}")
return output_video_filepath
output_png = f"{output_image_filepath_noext}.png"
if os.path.exists(output_png):
logger.info(f"Job {job_id}: Title screen image generated at {output_png}")
return output_png
else:
logger.error(f"Job {job_id}: Title screen generation returned no file")
return None
@@ -456,7 +460,9 @@ async def _generate_end_screen(
logger.info(f"Job {job_id}: End format - bg_image: {end_format.get('background_image')}, font: {end_format.get('font')}")
# Generate end screen (synchronous method)
# Generate end screen images only (MOV video is generated on GCE encoding worker)
# Pass duration=0 to skip FFmpeg video creation — Cloud Run doesn't have enough
# memory for 4K H.264 encoding after right-sizing to 2Gi (PR #640).
video_generator.create_end_video(
artist=job.artist,
title=job.title,
@@ -464,12 +470,13 @@ async def _generate_end_screen(
output_image_filepath_noext=output_image_filepath_noext,
output_video_filepath=output_video_filepath,
existing_end_image=end_format.get('existing_image'),
end_video_duration=end_duration
end_video_duration=0,
)
if os.path.exists(output_video_filepath):
logger.info(f"Job {job_id}: End screen generated at {output_video_filepath}")
return output_video_filepath
output_png = f"{output_image_filepath_noext}.png"
if os.path.exists(output_png):
logger.info(f"Job {job_id}: End screen image generated at {output_png}")
return output_png
else:
logger.error(f"Job {job_id}: End screen generation returned no file")
return None
@@ -487,46 +494,34 @@ async def _upload_screens(
end_screen_path: str
) -> None:
"""
Upload title and end screens to GCS (video + images).
Upload title and end screen images to GCS.
Single Responsibility: Only handles uploads.
VideoGenerator creates .mov, .jpg, and .png files when configured with
output_png=True and output_jpg=True. We upload all three formats
for feature parity with the local CLI.
VideoGenerator creates .jpg and .png files when configured with
output_png=True and output_jpg=True. MOV video generation is handled
by the GCE encoding worker (not Cloud Run) to avoid OOM with 4K H.264.
Args:
job_id: Job ID
job_manager: Job manager instance
storage: Storage service instance
title_screen_path: Path to title screen video (.mov)
end_screen_path: Path to end screen video (.mov)
title_screen_path: Path to title screen image (.png)
end_screen_path: Path to end screen image (.png)
"""
# Upload title screen video
title_gcs_path = f"jobs/{job_id}/screens/title.mov"
title_url = storage.upload_file(title_screen_path, title_gcs_path)
job_manager.update_file_url(job_id, 'screens', 'title', title_url)
logger.info(f"Job {job_id}: Uploaded title screen video")
# Upload title screen images (.jpg and .png - created by VideoGenerator)
title_base = title_screen_path.replace('.mov', '')
for ext, key in [('.jpg', 'title_jpg'), ('.png', 'title_png')]:
# Upload title screen images (.png and .jpg)
title_base = title_screen_path.replace('.png', '')
for ext, key in [('.png', 'title_png'), ('.jpg', 'title_jpg')]:
image_path = f"{title_base}{ext}"
if os.path.exists(image_path):
gcs_path = f"jobs/{job_id}/screens/title{ext}"
url = storage.upload_file(image_path, gcs_path)
job_manager.update_file_url(job_id, 'screens', key, url)
logger.info(f"Job {job_id}: Uploaded title screen image ({ext})")
# Upload end screen video
end_gcs_path = f"jobs/{job_id}/screens/end.mov"
end_url = storage.upload_file(end_screen_path, end_gcs_path)
job_manager.update_file_url(job_id, 'screens', 'end', end_url)
logger.info(f"Job {job_id}: Uploaded end screen video")
# Upload end screen images (.jpg and .png - created by VideoGenerator)
end_base = end_screen_path.replace('.mov', '')
for ext, key in [('.jpg', 'end_jpg'), ('.png', 'end_png')]:
# Upload end screen images (.png and .jpg)
end_base = end_screen_path.replace('.png', '')
for ext, key in [('.png', 'end_png'), ('.jpg', 'end_jpg')]:
image_path = f"{end_base}{ext}"
if os.path.exists(image_path):
gcs_path = f"jobs/{job_id}/screens/end{ext}"
@@ -638,7 +633,7 @@ async def _analyze_backing_vocals(
job_manager.update_state_data(job_id, 'backing_vocals_analysis', {
'has_audible_content': None,
'analysis_error': str(e),
'recommended_selection': 'review_needed',
'recommended_selection': 'clean',
})
+187
View File
@@ -0,0 +1,187 @@
"""
Stale review processor.
Detects jobs stuck in review (awaiting_review / in_review) and takes action:
- 24h: sends a gentle reminder email with expiry warning
- 48h: auto-cancels the job and refunds the user's credit
Called by Cloud Scheduler via an internal endpoint (hourly).
"""
import logging
from datetime import datetime, timezone
from typing import Any, Dict
from backend.models.job import JobStatus
from backend.services.email_service import get_email_service
from backend.services.firestore_service import FirestoreService
from backend.services.job_manager import JobManager
logger = logging.getLogger(__name__)
# Configurable thresholds (hours since blocking_state_entered_at)
REVIEW_REMINDER_HOURS = 24
REVIEW_EXPIRY_HOURS = 48
async def process_stale_reviews() -> Dict[str, Any]:
"""
Query for stale review jobs and take action.
- Jobs in review for >= 48h are auto-cancelled with credit refund
- Jobs in review for >= 24h (but < 48h) get a reminder email
Excludes made-for-you and tenant jobs.
Returns:
Summary dict with counts and any errors encountered.
"""
job_manager = JobManager()
firestore = FirestoreService()
email_service = get_email_service()
reminders_sent = 0
jobs_expired = 0
errors = []
# Query for jobs in both blocking review states
stale_jobs = []
for status in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
try:
jobs = firestore.list_jobs(status=status, limit=500)
stale_jobs.extend(jobs)
except Exception as e:
error_msg = f"Failed to query jobs with status {status.value}: {e}"
logger.error(error_msg)
errors.append(error_msg)
if not stale_jobs:
logger.info("No stale review jobs found")
return {
"status": "completed",
"reminders_sent": 0,
"jobs_expired": 0,
"errors": errors,
}
logger.info(f"Found {len(stale_jobs)} jobs in review states, checking for stale ones")
now = datetime.now(timezone.utc)
for job in stale_jobs:
try:
# Skip made-for-you jobs (admin-controlled)
if getattr(job, 'made_for_you', False):
continue
# Skip tenant/white-label jobs (B2B partners)
if getattr(job, 'tenant_id', '') and job.tenant_id:
continue
# Get blocking state entry time from state_data
state_data = job.state_data or {}
blocking_entered_at_str = state_data.get('blocking_state_entered_at')
if not blocking_entered_at_str:
continue
# Parse the naive UTC ISO string and make it timezone-aware
try:
blocking_entered_at = datetime.fromisoformat(blocking_entered_at_str)
if blocking_entered_at.tzinfo is None:
blocking_entered_at = blocking_entered_at.replace(tzinfo=timezone.utc)
except (ValueError, TypeError):
logger.warning(
f"Job {job.job_id}: invalid blocking_state_entered_at: {blocking_entered_at_str}"
)
continue
hours_elapsed = (now - blocking_entered_at).total_seconds() / 3600
if hours_elapsed >= REVIEW_EXPIRY_HOURS:
# Auto-expire: cancel job (which refunds credit)
logger.info(
f"Job {job.job_id}: review stale for {hours_elapsed:.1f}h (>={REVIEW_EXPIRY_HOURS}h), "
f"auto-expiring"
)
cancelled = job_manager.cancel_job(
job.job_id,
reason="Review not completed within 48 hours"
)
if cancelled:
jobs_expired += 1
# Send expiry notification email
if job.user_email:
try:
from backend.services.user_service import get_user_service
user_service = get_user_service()
credits_balance = user_service.check_credits(job.user_email)
email_service.send_review_expired(
to_email=job.user_email,
artist=job.artist,
title=job.title,
credits_balance=credits_balance,
)
except Exception as email_err:
logger.error(
f"Job {job.job_id}: failed to send expiry email: {email_err}"
)
else:
logger.warning(f"Job {job.job_id}: cancel_job returned False")
elif hours_elapsed >= REVIEW_REMINDER_HOURS:
# Check if expiry reminder was already sent
if state_data.get('expiry_reminder_sent'):
continue
logger.info(
f"Job {job.job_id}: review stale for {hours_elapsed:.1f}h (>={REVIEW_REMINDER_HOURS}h), "
f"sending reminder"
)
# Send reminder email
if job.user_email:
try:
email_service.send_review_reminder(
to_email=job.user_email,
artist=job.artist,
title=job.title,
job_id=job.job_id,
)
except Exception as email_err:
logger.error(
f"Job {job.job_id}: failed to send reminder email: {email_err}"
)
# Update state_data to mark reminder as sent (even if email failed,
# to avoid retrying every hour)
try:
firestore.update_job(job.job_id, {
'state_data.expiry_reminder_sent': True,
'state_data.expiry_reminder_sent_at': datetime.now(timezone.utc).isoformat(),
})
except Exception as update_err:
logger.error(
f"Job {job.job_id}: failed to update expiry_reminder_sent: {update_err}"
)
reminders_sent += 1
except Exception as e:
error_msg = f"Job {job.job_id}: unexpected error: {e}"
logger.exception(error_msg)
errors.append(error_msg)
logger.info(
f"Stale review processing complete: "
f"{reminders_sent} reminders sent, {jobs_expired} jobs expired, "
f"{len(errors)} errors"
)
return {
"status": "completed",
"reminders_sent": reminders_sent,
"jobs_expired": jobs_expired,
"errors": errors,
}
+114 -32
View File
@@ -121,13 +121,12 @@ async def _encode_via_gce(
def progress_callback(progress: int):
# Update job progress (encoding is 75-95% of total)
# Use update_job instead of transition_to_state since job is already in ENCODING state
scaled_progress = 75 + int(progress * 0.2) # Map 0-100 to 75-95
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.ENCODING,
progress=scaled_progress,
message=f"Encoding videos ({progress}%)"
)
job_manager.update_job(job_id, {
'progress': scaled_progress,
'message': f"Encoding videos ({progress}%)",
})
try:
# Submit and wait for encoding
@@ -173,6 +172,8 @@ async def _encode_via_gce(
local_files["final_video_lossy"] = local_path
elif "720p" in filename_lower:
local_files["final_video_720p"] = local_path
elif "with vocals" in filename_lower and filename.endswith(".mp4"):
local_files["final_with_vocals_mp4"] = local_path
job_log.info(f"Downloaded {len(local_files)} encoded files")
@@ -226,6 +227,14 @@ async def generate_video_orchestrated(job_id: str) -> bool:
logger.error(f"[job:{job_id}] Prerequisites not met for video generation")
return False
# Validate job status is appropriate for video worker
from backend.services.job_health_service import validate_worker_can_run
status_error = validate_worker_can_run("video_worker", job)
if status_error:
logger.warning(f"[job:{job_id}] {status_error}")
job_log.warning(status_error)
return False
# Create temporary working directory
temp_dir = tempfile.mkdtemp(prefix=f"karaoke_video_{job_id}_")
original_cwd = os.getcwd()
@@ -332,6 +341,7 @@ async def generate_video_orchestrated(job_id: str) -> bool:
'final_video_mkv': result.final_video_mkv,
'final_video_lossy': result.final_video_lossy,
'final_video_720p': result.final_video_720p,
'final_with_vocals_mp4': result.final_with_vocals_mp4,
'final_karaoke_cdg_zip': result.final_karaoke_cdg_zip,
'final_karaoke_txt_zip': result.final_karaoke_txt_zip,
})
@@ -360,11 +370,13 @@ async def generate_video_orchestrated(job_id: str) -> bool:
artist=job.artist,
title=job.title,
warnings=result.distribution_warnings,
settings=settings,
)
# Mark job as complete (triggers completion email with youtube_url now available)
# Store video processing metadata
duration = time.time() - start_time
_store_video_processing_metadata(job_manager, job_id, result, duration)
# Mark job as complete (triggers completion email with youtube_url now available)
completion_metadata = {
"action": "completed",
"brand_code": result.brand_code,
@@ -634,11 +646,19 @@ async def generate_video_legacy(job_id: str) -> bool:
if not _validate_prerequisites(job):
logger.error(f"[job:{job_id}] Prerequisites not met for video generation")
return False
# Validate job status is appropriate for video worker
from backend.services.job_health_service import validate_worker_can_run
status_error = validate_worker_can_run("video_worker", job)
if status_error:
logger.warning(f"[job:{job_id}] {status_error}")
job_log.warning(status_error)
return False
# Create temporary working directory
temp_dir = tempfile.mkdtemp(prefix=f"karaoke_video_{job_id}_")
original_cwd = os.getcwd()
# Set up rclone config if needed for Dropbox upload
rclone_service = None
if getattr(job, 'organised_dir_rclone_root', None):
@@ -1101,7 +1121,6 @@ async def _handle_native_distribution(
artist=job.artist,
title=job.title,
warnings=result['distribution_warnings'],
settings=settings,
)
@@ -1141,6 +1160,57 @@ def _send_distribution_warning_notification(
logger.warning(f"[job:{job_id}] Failed to send Pushbullet notification: {e}")
def _store_video_processing_metadata(
job_manager: JobManager,
job_id: str,
result,
total_duration: float,
) -> None:
"""Store encoding, distribution, and output metadata in processing_metadata."""
try:
# Encoding metadata
encoding_data = {
"encoding_time_seconds": round(result.encoding_time_seconds, 1) if result.encoding_time_seconds else None,
"output_formats": [],
}
# Track which output formats were generated and their sizes
output_sizes = {}
for attr, fmt_name in [
("final_video", "lossless_4k_mp4"),
("final_video_mkv", "lossless_4k_mkv"),
("final_video_lossy", "lossy_4k_mp4"),
("final_video_720p", "lossy_720p_mp4"),
]:
path = getattr(result, attr, None)
if path and os.path.exists(path):
encoding_data["output_formats"].append(fmt_name)
output_sizes[fmt_name] = os.path.getsize(path)
if output_sizes:
encoding_data["output_sizes_bytes"] = output_sizes
job_manager.update_processing_metadata(job_id, "encoding", encoding_data)
# Distribution metadata
distribution_data = {}
if result.youtube_url:
distribution_data["youtube_video_url"] = result.youtube_url
if result.youtube_upload_queued:
distribution_data["youtube_upload_queued"] = True
if result.dropbox_link:
distribution_data["dropbox_link"] = result.dropbox_link
if result.gdrive_files:
distribution_data["gdrive_file_count"] = len(result.gdrive_files)
if result.brand_code:
distribution_data["brand_code"] = result.brand_code
if distribution_data:
job_manager.update_processing_metadata(job_id, "distribution", distribution_data)
# Worker timing
job_manager.update_processing_metadata(job_id, "timing.video_worker_seconds", round(total_duration, 1))
except Exception as e:
logger.warning(f"Job {job_id}: Failed to store video processing metadata (non-fatal): {e}")
def _validate_prerequisites(job) -> bool:
"""Validate that all prerequisites are met for video generation."""
# Validate job status is appropriate for video worker
@@ -1148,7 +1218,7 @@ def _validate_prerequisites(job) -> bool:
status_error = validate_worker_can_run("video_worker", job)
if status_error:
logger.warning(f"Job {job.job_id}: {status_error}")
# Continue anyway - this is a safety net warning, not a hard failure
return False
# Check instrumental selection
instrumental_selection = job.state_data.get('instrumental_selection')
@@ -1161,9 +1231,11 @@ def _validate_prerequisites(job) -> bool:
logger.error(f"Job {job.job_id}: Invalid instrumental selection: {instrumental_selection}")
return False
# Check screens exist
# Check screens exist (MOV or PNG — MOV is no longer uploaded, PNG is the new default)
screens = job.file_urls.get('screens', {})
if not screens.get('title') or not screens.get('end'):
has_title = screens.get('title') or screens.get('title_png')
has_end = screens.get('end') or screens.get('end_png')
if not has_title or not has_end:
logger.error(f"Job {job.job_id}: Missing title or end screen")
return False
@@ -1217,24 +1289,31 @@ async def _setup_working_directory(
log_progress("Setting up working directory")
# Download title screen
log_progress("Downloading title screen...")
title_url = job.file_urls['screens']['title']
title_path = os.path.join(temp_dir, f"{base_name} (Title).mov")
storage.download_file(title_url, title_path)
log_progress("Downloaded title screen")
# Download end screen
log_progress("Downloading end screen...")
end_url = job.file_urls['screens']['end']
end_path = os.path.join(temp_dir, f"{base_name} (End).mov")
storage.download_file(end_url, end_path)
log_progress("Downloaded end screen")
# Download title screen (PNG — MOV video is generated by the GCE encoding worker)
screens = job.file_urls.get('screens', {})
title_url = screens.get('title') or screens.get('title_png')
if title_url:
ext = os.path.splitext(title_url)[1] or '.png'
title_path = os.path.join(temp_dir, f"{base_name} (Title){ext}")
log_progress(f"Downloading title screen ({ext})...")
storage.download_file(title_url, title_path)
log_progress("Downloaded title screen")
# Download end screen (PNG — MOV video is generated by the GCE encoding worker)
end_url = screens.get('end') or screens.get('end_png')
if end_url:
ext = os.path.splitext(end_url)[1] or '.png'
end_path = os.path.join(temp_dir, f"{base_name} (End){ext}")
log_progress(f"Downloading end screen ({ext})...")
storage.download_file(end_url, end_path)
log_progress("Downloaded end screen")
# Download lyrics video (with vocals) - this is the largest file, ~1-2GB
log_progress("Downloading karaoke video (largest file, may take 1-2 minutes)...")
lyrics_video_url = job.file_urls['videos']['with_vocals']
lyrics_video_path = os.path.join(temp_dir, f"{base_name} (With Vocals).mov")
# Use actual extension from GCS path (typically .mkv) instead of hardcoding .mov
lyrics_video_ext = os.path.splitext(lyrics_video_url)[1] or '.mkv'
lyrics_video_path = os.path.join(temp_dir, f"{base_name} (With Vocals){lyrics_video_ext}")
storage.download_file(lyrics_video_url, lyrics_video_path)
log_progress("Downloaded karaoke video")
@@ -1422,14 +1501,16 @@ async def _prepare_distribution_directory(
except Exception as e:
log_progress(f"Could not download {lyrics_key}: {e}")
# --- Download (With Vocals).mkv to lyrics/ subfolder ---
# --- Download (With Vocals) to lyrics/ subfolder ---
# Local CLI places the karaoke video with vocals in the lyrics folder
videos = job.file_urls.get('videos', {})
if videos.get('with_vocals'):
with_vocals_dest = os.path.join(lyrics_dir, f"{base_name} (With Vocals).mkv")
with_vocals_url = videos['with_vocals']
with_vocals_ext = os.path.splitext(with_vocals_url)[1] or '.mkv'
with_vocals_dest = os.path.join(lyrics_dir, f"{base_name} (With Vocals){with_vocals_ext}")
try:
storage.download_file(videos['with_vocals'], with_vocals_dest)
log_progress(f"Downloaded with_vocals to lyrics/{base_name} (With Vocals).mkv")
storage.download_file(with_vocals_url, with_vocals_dest)
log_progress(f"Downloaded with_vocals to lyrics/{base_name} (With Vocals){with_vocals_ext}")
except Exception as e:
log_progress(f"Could not download with_vocals to lyrics/: {e}")
@@ -1469,6 +1550,7 @@ async def _upload_results(
('final_video_mkv', 'finals', 'lossless_4k_mkv'),
('final_video_lossy', 'finals', 'lossy_4k_mp4'),
('final_video_720p', 'finals', 'lossy_720p_mp4'),
('final_with_vocals_mp4', 'finals', 'with_vocals_mp4'),
('final_karaoke_cdg_zip', 'packages', 'cdg_zip'),
('final_karaoke_txt_zip', 'packages', 'txt_zip'),
]
+64 -13
View File
@@ -18,6 +18,7 @@ Pipeline stages:
import logging
import os
import re
import time
from dataclasses import dataclass, field
from typing import Optional, Dict, Any, List
@@ -98,6 +99,7 @@ class OrchestratorResult:
final_video_mkv: Optional[str] = None # Lossless 4K MKV
final_video_lossy: Optional[str] = None # Lossy 4K MP4
final_video_720p: Optional[str] = None # Lossy 720p MP4
final_with_vocals_mp4: Optional[str] = None # With Vocals MP4 (encoded from raw MKV)
final_karaoke_cdg_zip: Optional[str] = None
final_karaoke_txt_zip: Optional[str] = None
@@ -233,16 +235,31 @@ class VideoWorkerOrchestrator:
await self._run_packaging()
# Validate required packaging outputs before expensive encoding
# If LRC has no lyrics content (e.g. input audio had no vocals),
# skip CDG/TXT gracefully instead of failing the entire job
lrc_has_content = self._lrc_has_lyrics_content()
if self.config.enable_cdg and not self.result.final_karaoke_cdg_zip:
raise RuntimeError(
"CDG generation was enabled but failed. "
"Check worker logs for CDG-related errors."
)
if lrc_has_content:
raise RuntimeError(
"CDG generation was enabled but failed. "
"Check worker logs for CDG-related errors."
)
else:
self.job_log.warning(
"CDG generation skipped: LRC file has no lyrics content. "
"Video will be generated without CDG package."
)
if self.config.enable_txt and not self.result.final_karaoke_txt_zip:
raise RuntimeError(
"TXT generation was enabled but failed. "
"Check worker logs for TXT-related errors."
)
if lrc_has_content:
raise RuntimeError(
"TXT generation was enabled but failed. "
"Check worker logs for TXT-related errors."
)
else:
self.job_log.warning(
"TXT generation skipped: LRC file has no lyrics content. "
"Video will be generated without TXT package."
)
# Stage 2: Encoding
await self._run_encoding()
@@ -275,6 +292,18 @@ class VideoWorkerOrchestrator:
return self.result
def _lrc_has_lyrics_content(self) -> bool:
"""Check if the LRC file has actual lyrics content (timestamp lines), not just metadata."""
if not self.config.lrc_file_path or not os.path.isfile(self.config.lrc_file_path):
return False
try:
with open(self.config.lrc_file_path, "r", encoding="utf-8") as f:
content = f.read()
# Match LRC timestamp lines: [MM:SS.xx] or [MM:SS.xxx] or [M:SS.xx]
return bool(re.search(r"\[\d{1,2}:\d{2}(?:\.\d{1,3})?\]", content))
except Exception:
return False
async def _run_packaging(self):
"""Run the packaging stage (CDG/TXT generation)."""
self.job_log.info("Starting packaging stage (CDG/TXT)")
@@ -287,7 +316,9 @@ class VideoWorkerOrchestrator:
self.job_log.warning("No LRC file available, skipping CDG/TXT packaging")
return
base_name = f"{self.config.artist} - {self.config.title}"
safe_artist = sanitize_filename(self.config.artist) if self.config.artist else "Unknown"
safe_title = sanitize_filename(self.config.title) if self.config.title else "Unknown"
base_name = f"{safe_artist} - {safe_title}"
packaging_service = self._get_packaging_service()
# Generate CDG package
@@ -421,6 +452,7 @@ class VideoWorkerOrchestrator:
self.result.final_video_mkv = output.lossless_mkv_path
self.result.final_video_lossy = output.lossy_4k_mp4_path
self.result.final_video_720p = output.lossy_720p_mp4_path
self.result.final_with_vocals_mp4 = output.with_vocals_mp4_path
self.result.encoding_time_seconds = output.encoding_time_seconds
# For GCE encoding, download the encoded files from GCS to local directory
@@ -450,6 +482,7 @@ class VideoWorkerOrchestrator:
self.result.final_video_mkv = output.lossless_mkv_path
self.result.final_video_lossy = output.lossy_4k_mp4_path
self.result.final_video_720p = output.lossy_720p_mp4_path
self.result.final_with_vocals_mp4 = output.with_vocals_mp4_path
self.result.encoding_time_seconds = output.encoding_time_seconds
await self._download_gce_encoded_files(output)
@@ -479,6 +512,7 @@ class VideoWorkerOrchestrator:
('lossless_mkv_path', 'final_video_mkv'),
('lossy_4k_mp4_path', 'final_video_lossy'),
('lossy_720p_mp4_path', 'final_video_720p'),
('with_vocals_mp4_path', 'final_with_vocals_mp4'),
]
downloaded_count = 0
@@ -802,6 +836,22 @@ class VideoWorkerOrchestrator:
# Never fail the pipeline for validation
def _screen_ext(job, screen_type: str) -> str:
"""Get the file extension for a screen (title/end) based on what's in GCS.
New jobs have only PNG (MOV is generated by GCE encoding worker).
Legacy jobs may still have MOV uploaded by the old screens_worker.
"""
screens = job.file_urls.get('screens', {})
# Check for MOV first (legacy), then fall back to PNG (new)
url = screens.get(screen_type) or screens.get(f'{screen_type}_png')
if url:
ext = os.path.splitext(url)[1]
if ext:
return ext
return '.png'
def create_orchestrator_config_from_job(
job,
temp_dir: str,
@@ -859,11 +909,12 @@ def create_orchestrator_config_from_job(
artist=job.artist,
title=job.title,
# Input files
title_video_path=os.path.join(temp_dir, f"{base_name} (Title).mov"),
karaoke_video_path=os.path.join(temp_dir, f"{base_name} (With Vocals).mov"),
# Input files — use actual extension from GCS (PNG for new jobs, MOV for legacy)
title_video_path=os.path.join(temp_dir, f"{base_name} (Title){_screen_ext(job, 'title')}"),
# Use actual extension from GCS path (typically .mkv) instead of hardcoding .mov
karaoke_video_path=os.path.join(temp_dir, f"{base_name} (With Vocals){os.path.splitext(job.file_urls.get('videos', {}).get('with_vocals', '.mkv'))[1] or '.mkv'}"),
instrumental_audio_path=instrumental_path,
end_video_path=os.path.join(temp_dir, f"{base_name} (End).mov"),
end_video_path=os.path.join(temp_dir, f"{base_name} (End){_screen_ext(job, 'end')}"),
lrc_file_path=os.path.join(temp_dir, f"{base_name} (Karaoke).lrc"),
title_jpg_path=os.path.join(temp_dir, f"{base_name} (Title).jpg"),
+155
View File
@@ -0,0 +1,155 @@
# AI-Powered Credit Gating
## Overview
Free credit grants (welcome credits and feedback bonus credits) are evaluated by an AI model before being approved. This prevents multi-account abuse where users create multiple accounts to farm free karaoke generation credits.
The system is **fail-closed**: if anything goes wrong (AI error, unclear response, network issue), credits are NOT granted automatically. Instead, the admin is notified to review manually.
## How It Works
```
User verifies email (or submits feedback)
↓
Collect abuse signals:
• Device fingerprint correlations (other accounts with same fingerprint)
• IP address correlations (other accounts from same IP)
• IP geolocation (country, ISP, VPN detection)
• Recent signup patterns (new accounts from same IP/fingerprint in last 24h)
• User agent string
• For feedback: the submitted feedback content
↓
Clean user? (no correlations, no recent signup spike)
→ YES: Grant credits immediately (no AI call needed)
→ NO: Call Gemini for evaluation
↓
Gemini decision:
• "grant" → Grant credits, user sees celebratory welcome screen
• "deny" → No credits, user gets rejection email (CC'd to Andrew)
• Error/uncertain → No credits, user told "team will review shortly",
Andrew gets review email with admin link
```
## Decision Outcomes
| Scenario | Credits | User Experience | Admin Notification |
|----------|---------|-----------------|-------------------|
| Clean user (no correlations) | Granted | "1 free credit!" interstitial | None |
| AI approves | Granted | Same | None |
| AI denies (abuse detected) | Not granted | "Couldn't grant free credits" + buy CTA | CC on rejection email to user |
| AI error / uncertain | Not granted | "Team will review shortly" + buy CTA | Review email with admin page link |
| Evaluation disabled | Granted | Same as clean | None |
## Frontend Flow
The verify page (`/auth/verify`) shows these states in sequence:
1. **"Verifying your sign-in link..."** — Token validation
2. **"Preparing your account..."** — AI evaluation running (2-5 seconds)
3. One of:
- **Credits granted** — Celebratory screen with credit count, gentle reminder not to abuse, "Start Creating Karaoke" button
- **Credits denied** — "Couldn't grant free credits" with buy credits CTA and link to dashboard
- **Credits pending review** — "Team will review shortly" with buy credits CTA and "Explore the App" button
- **Success** (returning user) — "Welcome back!" with auto-redirect
## Emails
### To User: Credit Denied
- Subject: "About your Nomad Karaoke free credits"
- CC: andrew@beveridge.uk
- Tone: Friendly but firm — explains costs, invites reply if mistake
- Includes buy credits link
### To Admin: Review Needed
- Subject: "Credit review needed: user@example.com (welcome)"
- To: andrew@beveridge.uk
- Includes direct link to user's admin page (`/admin/users/detail?email=...`)
- Explains what to do: grant credits if legitimate, do nothing if not
## Configuration
| Environment Variable | Default | Description |
|---------------------|---------|-------------|
| `CREDIT_EVAL_ENABLED` | `true` | Set to `false` to disable AI evaluation and auto-grant all credits |
| `CREDIT_EVAL_MODEL` | `gemini-3.1-pro-preview` | Gemini model to use for evaluation |
### Emergency Rollback
Set `CREDIT_EVAL_ENABLED=false` in Cloud Run environment variables. This immediately reverts to the old behavior of auto-granting all credits without AI evaluation.
## Audit Trail
Every evaluation is logged to the `credit_evaluations` Firestore collection:
```json
{
"id": "uuid",
"email": "user@example.com",
"grant_type": "welcome",
"decision": "grant",
"reasoning": "No suspicious correlations found — clean user",
"confidence": 1.0,
"error": null,
"model": "gemini-3.1-pro-preview",
"signals_snapshot": {
"fingerprint_match_count": 0,
"ip_match_count": 0,
"recent_signups_ip": 1,
"recent_signups_fp": 1,
"user_ip": "1.2.3.4",
"user_fingerprint": "abc123..."
},
"evaluated_at": "2026-03-23T21:00:00Z"
}
```
## Admin Workflow
When you receive a "Credit review needed" email:
1. Click the "Review User" link to go to their admin page
2. Check their abuse signals: fingerprint matches, IP matches, job history
3. If legitimate: Use the admin credits endpoint to grant 1 credit manually
4. If abusive: No action needed — they already have 0 credits
Note: For `pending_review` cases, the `welcome_credits_granted` flag is NOT set, so the system won't interfere if you grant credits manually later.
## Architecture
### Files
| File | Purpose |
|------|---------|
| `backend/services/credit_evaluation_service.py` | Core service: signal collection, Gemini prompt, response parsing, audit logging |
| `backend/config.py` | `CREDIT_EVAL_ENABLED`, `CREDIT_EVAL_MODEL` config |
| `backend/services/user_service.py` | `grant_welcome_credits_if_eligible()` integration |
| `backend/api/routes/users.py` | Feedback credit flow integration, verify response includes `credit_status` |
| `backend/services/email_service.py` | `send_credit_denied_email()`, `send_credit_review_needed_email()` |
| `backend/models/user.py` | `VerifyMagicLinkResponse.credit_status` field |
| `frontend/app/auth/verify/page.tsx` | 5-state verify flow with interstitials |
| `frontend/lib/types.ts` | `credit_status` type on verify response |
### Signal Collection
The evaluation service calls these existing methods to collect signals:
- `user_service.find_users_by_fingerprint()` — other accounts with same device fingerprint
- `user_service.find_users_by_signup_ip()` — other accounts from same IP
- `user_service.count_recent_signups_from_ip()` — new accounts from same IP in last 24h
- `user_service.count_recent_signups_from_fingerprint()` — new accounts from same fingerprint in last 24h
- `ip_geolocation_service.lookup_ip()` — country, ISP, org info
- Session collection query — latest user agent
### Gemini Prompt
The prompt instructs Gemini to:
- **DENY** if fingerprint matches other accounts (strong multi-accounting signal)
- **DENY** if IP matches + other suspicious patterns (same UA, no spend)
- **GRANT** if appears genuine or insufficient evidence
- **When in doubt, GRANT** — false positives worse than false negatives
The response is structured JSON: `{"decision": "grant"|"deny", "reasoning": "...", "confidence": 0.0-1.0}`
### Quick-Grant Optimization
If no correlations are found at all (no fingerprint matches, no IP matches, recent signup counts ≤ 1), the system skips the AI call entirely and grants immediately. This means most legitimate users experience zero additional latency.
+119 -7
View File
@@ -141,6 +141,7 @@ GET /api/jobs?status=complete
GET /api/jobs?limit=10&offset=0
GET /api/jobs?exclude_test=false
GET /api/jobs?fields=summary&hide_completed=true
GET /api/jobs?fields=summary&search=bohemian
```
Query parameters:
@@ -149,6 +150,7 @@ Query parameters:
- `limit` / `offset` - Pagination
- `fields` (string, optional) - Set to `summary` to return only dashboard-required fields using Firestore field projection. Reduces payload from ~16MB to <500KB for large job lists.
- `hide_completed` (bool, default: false) - Exclude successful completions (complete, prep_complete) server-side. Failed jobs remain visible.
- `search` (string, optional) - Text search filter (summary mode only). Case-insensitive substring match against artist, title, audio_search_artist, audio_search_title, and job_id. When active, fetches up to 1000 results internally and filters in Python.
#### Delete Job
@@ -441,6 +443,61 @@ Content-Type: application/json
Stores annotations to `jobs/{job_id}/lyrics/annotations.json`. Merges with existing annotations if present.
#### Add Reference Lyrics (Paste)
```http
POST /api/review/{job_id}/add-lyrics
Content-Type: application/json
{
"source": "manual",
"lyrics": "Full lyrics text...",
"force": false
}
```
Adds user-pasted lyrics as a new reference source, re-runs the correction pipeline with all sources, and uploads updated corrections to GCS. The `force` flag (default `false`) bypasses the relevance threshold — use when the transcription is poor and a low match % doesn't mean wrong song.
Returns `{ "status": "success", "data": <CorrectionData> }`.
#### Search Reference Lyrics
```http
POST /api/review/{job_id}/search-lyrics
Content-Type: application/json
{
"artist": "Billie Eilish",
"title": "What Was I Made For",
"force_sources": []
}
```
Searches all configured lyrics providers (Genius, Spotify, Musixmatch, LRCLIB) with the given artist/title. Results are filtered through the relevance threshold (30% word match minimum) — sources below are rejected as likely wrong-song matches. Sources in `force_sources` bypass the threshold.
**Success response** (at least one source passed):
```json
{
"status": "success",
"data": { "...CorrectionData..." },
"sources_added": ["genius", "lrclib"],
"sources_rejected": {
"spotify": { "relevance": 0.12, "matched_words": 18, "total_words": 150, "track_name": "...", "artist_names": "..." }
},
"sources_not_found": ["musixmatch"]
}
```
**No results response** (all filtered or nothing found):
```json
{
"status": "no_results",
"message": "No matching lyrics found from any provider",
"sources_rejected": { "genius": { "relevance": 0.05, "..." } },
"sources_not_found": ["lrclib", "musixmatch"]
}
```
#### Review Sessions
Server-side backup/restore of lyrics review editing sessions. Correction data is stored in GCS; metadata in Firestore subcollection `jobs/{job_id}/review_sessions/{session_id}`.
@@ -842,16 +899,18 @@ Common status codes:
POST /api/users/auth/magic-link
Content-Type: application/json
{"email": "user@example.com"}
{"email": "user@example.com", "device_fingerprint": "optional-fp-string"}
```
The `device_fingerprint` field is optional. If provided, it's used alongside the client IP for signup rate limiting (max 2 new accounts per IP or fingerprint per 24 hours). Existing users are never rate limited. Rate-limited requests receive a silent 200 response (anti-enumeration).
### Verify Magic Link
```http
GET /api/users/auth/verify?token=TOKEN
```
Returns session token and user info.
Returns session token, user info, and `credits_granted` (number of welcome credits granted on this verification, 0 for returning users). Welcome credits are granted on first verification, not at account creation.
**Admin Login Token**: The same endpoint supports admin login tokens embedded in notification emails. When a made-for-you order is received, the admin notification email includes a link with `?admin_token=TOKEN` that auto-logs the admin into the app. The frontend detects this parameter and calls the verify endpoint to authenticate. Admin tokens expire after 24 hours.
@@ -942,7 +1001,7 @@ Credits are checked and deducted at job creation time. The flow:
3. **Deduct** - `user_service.deduct_credit()` atomically deducts 1 credit (with job_id for audit trail)
4. **Refund on failure** - If the job fails, 1 credit is automatically refunded
Admin users bypass credit checks entirely. New users receive 2 welcome credits. Users can earn 2 additional free credits by submitting product feedback after completing 2+ jobs (see [User Feedback for Credits](#user-feedback-for-credits)).
Admin users bypass credit checks entirely. New users receive 1 welcome credit. Users can earn 1 additional free credit by submitting product feedback after completing 2+ jobs (see [User Feedback for Credits](#user-feedback-for-credits)).
#### 402 Response
@@ -967,7 +1026,7 @@ Handles `checkout.session.completed` events.
### User Feedback for Credits
Users who have completed 2+ jobs can submit feedback to earn 2 free credits.
Users who have completed 2+ jobs can submit feedback to earn 1 free credit.
#### Check Eligibility
@@ -982,7 +1041,7 @@ Response:
"eligible": true,
"has_submitted": false,
"jobs_completed": 3,
"credits_reward": 2
"credits_reward": 1
}
```
@@ -1011,7 +1070,7 @@ Requirements:
- At least one text field must have >50 characters
- User can only submit once (duplicate prevention)
Grants 2 credits on success. Feedback stored in `user_feedback` Firestore collection.
Grants 1 credit on success. Feedback stored in `user_feedback` Firestore collection.
The `/api/users/me` response includes `feedback_eligible: bool` so the frontend can show/hide feedback prompts without an extra API call.
@@ -1697,6 +1756,48 @@ Called by Cloud Tasks 5 minutes after a job enters a blocking state (primarily `
**Note**: With the combined review flow, users complete both lyrics review and instrumental selection in one session. The `awaiting_instrumental_selection` state is only used for finalise-only jobs.
### Admin Feedback
```http
GET /api/admin/feedback
GET /api/admin/feedback?search=user@example.com&exclude_test=true&limit=50&offset=0
Authorization: Bearer ADMIN_TOKEN
```
Lists all user feedback submissions with pagination, search, and aggregate stats.
Response:
```json
{
"items": [
{
"id": "uuid",
"user_email": "user@example.com",
"created_at": "2026-03-01T12:00:00",
"overall_rating": 4,
"ease_of_use_rating": 5,
"lyrics_accuracy_rating": 3,
"correction_experience_rating": 4,
"what_went_well": "...",
"what_could_improve": "...",
"additional_comments": null,
"would_recommend": true,
"would_use_again": true
}
],
"total": 2,
"offset": 0,
"limit": 50,
"has_more": false,
"avg_overall_rating": 4.0,
"avg_ease_of_use_rating": 4.5,
"avg_lyrics_accuracy_rating": 3.5,
"avg_correction_experience_rating": 4.0
}
```
An email notification is also sent to `admin@nomadkaraoke.com` (configurable via `ADMIN_NOTIFICATION_EMAIL` env var) whenever a user submits new feedback.
## Rate Limits & Abuse Prevention
### Usage Control
@@ -1713,12 +1814,16 @@ Job creation is controlled by credits (purchased or earned via feedback). There
GET /api/admin/rate-limits/blocklists
POST /api/admin/rate-limits/blocklists/disposable-domains
DELETE /api/admin/rate-limits/blocklists/disposable-domains/{domain}
POST /api/admin/rate-limits/blocklists/allowlisted-domains
DELETE /api/admin/rate-limits/blocklists/allowlisted-domains/{domain}
POST /api/admin/rate-limits/blocklists/sync
POST /api/admin/rate-limits/blocklists/blocked-emails
DELETE /api/admin/rate-limits/blocklists/blocked-emails/{email}
POST /api/admin/rate-limits/blocklists/blocked-ips
DELETE /api/admin/rate-limits/blocklists/blocked-ips/{ip}
POST /api/internal/sync-disposable-domains
```
Manage blocklists for disposable email domains, blocked emails, and blocked IPs.
Manage blocklists for disposable email domains, blocked emails, and blocked IPs. The disposable domain list auto-syncs daily from the [disposable-email-domains](https://github.com/disposable-email-domains/disposable-email-domains) repo (~4,800 domains). Admins can add manual domains, and allowlist false positives. The `GET` response includes `external_domains`, `manual_domains`, `allowlisted_domains`, `last_sync_at`, and `last_sync_count`.
### YouTube Upload Queue
@@ -1744,6 +1849,13 @@ POST /api/internal/youtube-queue/process
```
Called by Cloud Scheduler hourly. Processes queued uploads while quota is available. Returns summary of processed/failed/remaining uploads.
### Internal Stale Review Processing
```http
POST /api/internal/process-stale-reviews
```
Called by Cloud Scheduler hourly. Queries for jobs in `awaiting_review` or `in_review` status, sends reminder emails at 24h, and auto-cancels with credit refund at 48h. Excludes made-for-you and tenant jobs. Returns `{status: "started", message: "..."}` immediately; processing runs in background.
## Webhooks
Stripe webhooks implemented at `/api/users/webhooks/stripe`.
+102 -10
View File
@@ -16,7 +16,7 @@
│ https://api.nomadkaraoke.com │
│ │
│ Workers: │
│ • Audio Worker - Stem separation via Modal API │
│ • Audio Worker - Stem separation via Cloud Run GPU (L4) │
│ • Lyrics Worker - Transcription via AudioShake │
│ • Screens Worker - Title/end screen generation │
│ • Render Worker - Karaoke video with lyrics │
@@ -48,7 +48,7 @@
2. PARALLEL PROCESSING (with Worker Registry coordination)
┌─────────────────┐ ┌─────────────────┐
│ Audio Worker │ │ Lyrics Worker │
│ Modal API │ │ AudioShake │
│ Cloud Run GPU │ │ AudioShake │
│ 2-stage sep │ │ Auto-correct │
│ ↓ register() │ │ ↓ register() │
│ ↓ unregister() │ │ ↓ unregister() │
@@ -67,11 +67,12 @@
• Instrumental track selection (clean vs with_backing)
• Single submit saves both lyrics + instrumental choice
▼
5. VIDEO RENDERING
5. VIDEO RENDERING (optionally via GCE for speed + memory)
• Merge corrections with original data
• Generate karaoke video with lyrics
• Generate karaoke video with lyrics (OutputGenerator + ffmpeg/libass)
• Style assets cached on GCE worker disk between jobs
▼
6. FINAL VIDEO (INSTRUMENTAL_SELECTED)
6. FINAL VIDEO (INSTRUMENTAL_SELECTED, via GCE)
• Remux with selected instrumental
• Concatenate: title + karaoke + end
• Encode to 4 formats
@@ -126,8 +127,9 @@ jobs/{job_id}/
│ ├── title.mov
│ └── end.mov
├── videos/
│ └── with_vocals.mkv # Karaoke video
│ └── with_vocals.mkv # Raw karaoke video (FLAC audio, large)
└── finals/
├── with_vocals_mp4.mp4 # Encoded with-vocals (H264/AAC, ~3x smaller)
├── lossless_4k.mp4
├── lossless_4k.mkv
├── lossy_4k.mp4
@@ -160,7 +162,7 @@ LyricsTranscriber LyricsTranscriber
| Service | Purpose | Required |
|---------|---------|----------|
| Modal | GPU audio separation | Yes |
| Cloud Run GPU Job (L4, us-east4) | Audio stem separation — `Separator` runs directly in the audio worker Job (no HTTP hop) | Yes |
| AudioShake | Lyrics transcription | Yes |
| Vertex AI | Agentic AI correction (Gemini 3 Flash) | Default off (SKIP_CORRECTION=false to enable) |
| Genius | Reference lyrics | Yes |
@@ -175,6 +177,24 @@ LyricsTranscriber LyricsTranscriber
*Flacfetch runs on a dedicated GCE VM with YouTube cookies and tracker access. Without it, YouTube downloads will fail due to bot detection on Cloud Run IPs.
### Data Pipeline Cloud Functions
Three Cloud Functions manage the community karaoke data pipeline, running daily on automated schedules:
| Function | Schedule | Purpose |
|----------|----------|---------|
| `divebar-mirror` | Daily 2:00 AM ET | Indexes 48K+ files from [diveBar Karaoke Google Drive](https://drive.google.com/drive/folders/1zxnSZcE03gzy0YVGOdnTrEIi8It_3Wu8) into BigQuery `divebar_catalog` |
| `kn-data-sync` | Daily 3:05 AM + 4:30 AM ET | Fetches KaraokeNerds catalog (281K songs) and community tracks (58K with YouTube URLs) to BigQuery + GCS |
| `divebar-lookup` | Daily 6:00 AM ET + on-demand API | Public search/lookup API for KJ Controller; rebuilds KN↔Divebar cross-reference index |
**Infrastructure** (Pulumi-managed in `infrastructure/`):
- Service accounts: `divebar-mirror@`, `kn-data-sync@`, `divebar-lookup@` (least-privilege IAM)
- GCS: `nomadkaraoke-kn-data` (raw exports), 3 source buckets for function code
- BigQuery tables: `divebar_catalog`, `karaokenerds_community`, `kn_divebar_xref` (in `karaoke_decide` dataset)
- Secret: `karaokenerds-api-key` (KN API access)
**Source code:** `infrastructure/functions/{divebar_mirror,kn_data_sync,divebar_lookup}/`
## Firestore Collections
karaoke-gen shares a GCP project (`nomadkaraoke`) with karaoke-decide, but uses separate Firestore collections:
@@ -182,7 +202,7 @@ karaoke-gen shares a GCP project (`nomadkaraoke`) with karaoke-decide, but uses
| Collection | Purpose | Key Fields |
|------------|---------|------------|
| `gen_users` | karaoke-gen user accounts | email, credits, role, is_active |
| `jobs` | Karaoke generation jobs | job_id, user_email, status, state_data |
| `jobs` | Karaoke generation jobs | job_id, user_email, status, state_data, processing_metadata |
| `jobs/{job_id}/logs` | Worker log entries (subcollection) | timestamp, level, worker, message, ttl_expiry |
| `sessions` | Magic link auth sessions | user_email, token, expires_at |
| `magic_links` | Passwordless auth tokens | email, token, expires_at, used |
@@ -195,6 +215,52 @@ karaoke-gen shares a GCP project (`nomadkaraoke`) with karaoke-decide, but uses
**Worker Logs**: Stored in subcollection (`jobs/{job_id}/logs`) instead of embedded array to avoid Firestore's 1MB document size limit. TTL policy auto-deletes logs after 30 days. Feature flag: `USE_LOG_SUBCOLLECTION` (default: true). See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#firestore-document-1mb-limit-with-embedded-arrays).
## Encoding Worker Blue-Green Deployment
The GCE encoding worker uses a blue-green deployment pattern with two named VMs (`encoding-worker-a` and `encoding-worker-b`).
### Architecture
```text
Frontend → Backend (Cloud Run) → Firestore config → Primary VM (encoding-worker-a or b)
↑
Cloud Scheduler (5 min) → Cloud Function → checks idle + stops VMs
↑
CI (GitHub Actions) → deploys to secondary → health check → swap Firestore → stop old
```
### Key Components
**Two VMs (a/b)**: Both VMs are TERMINATED by default. One is designated "primary" and serves all encoding traffic. The secondary VM exists solely to receive new deployments before they go live.
**Firestore config doc** (`config/encoding-worker`): Single source of truth for routing. Fields: `primary` (a or b), `ip_a`, `ip_b`, `deploy_in_progress` flag, `activity_a`/`activity_b` timestamps.
**Backend routing** (`encoding_interface.py`): Reads the primary IP from the Firestore config doc with a 30-second TTL cache. All encoding requests route to the current primary.
**JIT startup**: When a user enters the lyrics review page, the backend starts the primary VM on demand. This gives ~60 seconds of natural warmup time before encoding is needed, avoiding both 24/7 costs and noticeable cold-start latency for the user.
**Idle auto-shutdown**: A Cloud Function (triggered every 5 minutes by Cloud Scheduler) checks the `activity_*` timestamps in Firestore and stops any VM that has been idle for more than 15 minutes. This is external to the VM — if the encoding worker code itself has a bug, the Cloud Function still shuts it down.
**Blue-green deploys**: CI builds a new wheel, deploys it to the secondary VM (not the live primary), runs a real encode test against the secondary, then atomically swaps the `primary` field in Firestore to point to the secondary. The old primary is stopped after the swap. If the health check fails, the primary is never updated.
### Seeding the Config
Initial setup or reset:
```bash
python scripts/seed-encoding-worker-config.py <ip-a> <ip-b>
```
### Deploy Flow
```text
1. CI builds new karaoke-gen wheel + pushes to GCS
2. CI starts secondary VM, waits for /health to respond
3. CI runs real encode test against secondary VM
4. If test passes: CI writes secondary name to Firestore `primary` field
5. CI stops the old primary VM
6. If test fails: CI stops secondary VM, primary unchanged
```
## Video Worker Orchestrator
The Video Worker uses an orchestrator pattern to ensure all features work regardless of encoding backend (local Cloud Run or GCE VM).
@@ -240,7 +306,7 @@ The Video Worker uses an orchestrator pattern to ensure all features work regard
| `job_notification_service.py` | Email orchestration (completion, reminders) |
| `audio_transcoding_service.py` | Transcode FLAC → OGG Opus for review UI playback |
| `youtube_quota_service.py` | Track YouTube API quota (GCP Cloud Monitoring + Firestore pending buffer) |
| `email_validation_service.py` | Email validation, disposable domain detection, blocklist management |
| `email_validation_service.py` | Email validation, tiered disposable domain detection (static list + DeBounce + verifymail.io APIs), blocklist management |
| `youtube_upload_queue_service.py` | Deferred YouTube upload queue management |
| `catalog_proxy_service.py` | Proxy to karaoke-decide catalog API (artist/track search) |
| `karaokenerds_service.py` | Scrape karaokenerds.com for community karaoke versions |
@@ -304,7 +370,7 @@ Audio and lyrics workers run as **Cloud Run Jobs** - standalone batch containers
│ │
│ audio-download-job - 30s-5 min (flacfetch/YouTube) │
│ lyrics-transcription-job - 5-15 min (AudioShake + correction)│
│ audio-separation-job - 10-20 min (Modal API) │
│ audio-separation-job - 10-20 min (L4 GPU, us-east4, direct) │
│ video-encoding-job - up to 60 min (optional) │
│ │
│ Triggered via: google.cloud.run_v2.JobsClient.run_job() │
@@ -341,6 +407,32 @@ Screens and render workers run via internal HTTP endpoints with BackgroundTasks,
- If workers active, calls `wait_for_completion(timeout=600)` (10 min max)
- Logs which workers are still running for debugging
## Audio Separation Architecture
Audio stem separation runs **directly inside the audio worker Cloud Run Job** — the `Separator` class from `audio-separator` is imported and called in-process. There is no separate GPU microservice.
```text
┌──────────────────────────────────────────────────────────────────┐
│ audio-separation-job (Cloud Run Job, L4 GPU, us-east4) │
│ │
│ AudioWorker │
│ ├── download audio from GCS │
│ ├── create_audio_processor() ← Separator(model_file_dir=...) │
│ ├── Stage 1: instrumental_clean preset │
│ │ └── produces: vocals.flac, instrumental_clean.flac │
│ ├── Stage 2: karaoke preset │
│ │ └── produces: instrumental_with_backing.flac │
│ └── upload stems to GCS │
└──────────────────────────────────────────────────────────────────┘
```
**Key decisions:**
- **Direct GPU** — No HTTP hop to a separate service. Jobs can run up to 24h; no timeout concerns.
- **Two-stage ensemble preset** — `instrumental_clean` (stage 1) + `karaoke` (stage 2).
- **Model cache** — Models are downloaded to `model_file_dir` (GCS-backed or local) and reused across executions.
**Rollback**: The old audio-separator Cloud Run Service (HTTP endpoint) is kept for rollback but no longer receives traffic. It will be removed in a future phase.
## Multitenancy
The platform supports white-label B2B portals where business customers get their own branded karaoke generation experience.
+65 -1
View File
@@ -170,7 +170,6 @@ The frontend's `detectTenantFromUrl()` checks for the `tenant` query param on lo
# Required
AUDIOSHAKE_API_TOKEN=...
GENIUS_ACCESS_TOKEN=...
AUDIO_SEPARATOR_API_URL=... # Modal API endpoint
# GCP (auto-configured in Cloud Run)
GOOGLE_CLOUD_PROJECT=...
@@ -208,6 +207,71 @@ TESTMAIL_NAMESPACE=... # testmail.app namespace
| `./scripts/setup-singa-tenant.py` | Generate Singa tenant assets and upload to GCS |
| `./scripts/setup-vocalstar-tenant.py` | Generate Vocal Star tenant assets and upload to GCS |
## Encoding Worker Operations
The encoding worker uses a blue-green deployment with two GCE VMs (`encoding-worker-a`, `encoding-worker-b`). See [ARCHITECTURE.md](ARCHITECTURE.md#encoding-worker-blue-green-deployment) for the full design.
### Seed Firestore config (initial setup or reset)
```bash
python scripts/seed-encoding-worker-config.py <ip-a> <ip-b>
```
### Check VM status
```bash
gcloud compute instances describe encoding-worker-a \
--zone=us-central1-c --project=nomadkaraoke \
--format='value(status)'
```
### Manually start / stop a VM
```bash
# Start
gcloud compute instances start encoding-worker-a \
--zone=us-central1-c --project=nomadkaraoke
# Stop
gcloud compute instances stop encoding-worker-a \
--zone=us-central1-c --project=nomadkaraoke
```
### Check worker health
```bash
IP=$(gcloud compute instances describe encoding-worker-a \
--zone=us-central1-c --project=nomadkaraoke \
--format='value(networkInterfaces[0].accessConfigs[0].natIP)')
curl http://$IP:8080/health
```
### Manually trigger idle shutdown
Go to Cloud Scheduler in the GCP console and click "Force run" on the `encoding-worker-idle-shutdown` job, or:
```bash
gcloud scheduler jobs run encoding-worker-idle-shutdown \
--location=us-central1 --project=nomadkaraoke
```
### Roll back a deploy
If a deploy went wrong, swap the Firestore config back to the old primary:
```bash
python3 << 'EOF'
import os
os.environ['GOOGLE_CLOUD_PROJECT'] = 'nomadkaraoke'
from google.cloud import firestore
db = firestore.Client(project='nomadkaraoke')
db.collection('config').document('encoding-worker').update({'primary': 'a'}) # or 'b'
print("Rolled back")
EOF
```
The backend's 30-second URL cache will pick up the change within 30 seconds.
## Project Structure
```
Loaded 100 of 366 files, more files were not shown because too many files have changed in this diff. Show more