Compare commits

...
59 Commits
Author SHA1 Message Date
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
Andrew Beveridge ☄️andClaude Opus 4.6 6c120b709c feat: audio edits admin dashboard + reset-to-audio-edit button (#521)
## Summary
- New admin page at `/admin/audio-edits` to view and inspect audio
editing sessions
- "Audio Edit" reset button in admin job actions to reset any job back
to audio edit phase
- Backend API endpoints for listing/viewing audio edit reviews

## Changes

### Admin Dashboard (`/admin/audio-edits`)
- List view: jobs with audio edits, searchable by artist/title/email
- Detail dialog with 3 tabs: Edit Stack, Sessions, Audio playback
- Raw data dialog with JSON copy
- Follows existing edit-reviews page pattern

### Reset to Audio Edit
- New "Audio Edit" button in admin job actions (between Audio and
Review)
- **Critical safety**: restores `input_media_gcs_path` to original when
resetting (the submit endpoint overwrites this with edited audio)
- Clears edit stack, redo stack, uploads, and all downstream processing
flags

### Backend
- `GET /api/admin/audio-edit-reviews` - list jobs with audio edits
- `GET /api/admin/audio-edit-reviews/{job_id}` - full detail with
sessions, signed audio URLs

## Test plan
- [x] All 64 backend tests pass (admin reset + audio edit routes)
- [x] All 701 frontend Jest tests pass (38 suites)
- [x] Reset to `awaiting_audio_edit` properly clears state data keys
- [x] `input_media_gcs_path` restored to original on audio edit reset

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 11:59:04 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 483ba9e11b fix: trigger workers in background after audio edit submit (#520)
## Summary
- The audio edit submit endpoint was `await`ing worker triggers (Cloud
Run Job calls) synchronously
- These calls take 30+ seconds, causing the browser `fetch` to time out
- The frontend never received the success response, so the
success/countdown screen never appeared
- Fix: use `asyncio.create_task()` to fire-and-forget the worker
triggers

## Changes
- `backend/api/routes/review.py`: Wrap worker trigger calls in a
background task so the HTTP response returns immediately

## Test plan
- [x] All 25 audio edit route tests pass
- [x] Submit endpoint still returns correct response shape
- [x] Workers still get triggered (just asynchronously)

<!-- @coderabbitai ignore -->

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 11:09:03 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 7d4a577dcb fix: worker valid statuses for audio_edit_complete + duration display (#519)
## Summary
- Workers (audio_worker, lyrics_worker) were immediately rejecting jobs
in `audio_edit_complete` status because that status wasn't in their
valid status lists
- `formatTimePrecise()` produced garbled output like "-2:-14.5" for
negative durations due to `Math.floor()` on negative numbers

## Changes
- Added `JobStatus.AUDIO_EDIT_COMPLETE` to `audio_worker` and
`lyrics_worker` valid statuses in `job_health_service.py`
- Fixed `formatTimePrecise()` in `AudioEditor.tsx` to use `Math.abs()`
and prepend sign separately

## Test plan
- [x] All 25 audio edit route tests pass
- [x] All 50 job health service tests pass
- [x] Verified negative duration formatting produces correct output

<!-- @coderabbitai ignore -->

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 23:48:19 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 10ad8b51a7 fix: Align audio edit apply/undo/redo response with frontend (#518)
## Summary
- `_build_audio_edit_response()` returned nested structure
(`edited_audio.*`, `edit_stack_size` integer) but frontend expected flat
fields (`current_audio_url`, `duration_after`, `edit_stack` array)
- This caused "can't access property 'length', t is undefined" when
trying to apply any edit operation (cut, trim, mute)
- Also added `duration_before`/`duration_after` tracking to edit entries

## Test plan
- [x] All 25 audio edit route tests pass
- [x] Full test suite passes (2490 backend + 189 Playwright)
- [ ] Verify edit operations work in production

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 23:13:15 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 7dab28b0ea fix: re-enable Cloud Run Jobs for video encoding to survive deployments (#517)
## Summary

- Re-enable `USE_CLOUD_RUN_JOBS_FOR_VIDEO=true` — this env var was
dropped during the CI migration from cloudbuild.yaml to GitHub Actions,
silently disabling the deployment-safe encoding path
- Add all required env vars and secrets to the `video-encoding-job`
Cloud Run Job in Pulumi (was missing encoding worker credentials,
distribution defaults, Discord, SendGrid, admin tokens)
- Add CI step to update the Cloud Run Job image on each deploy (was
stuck on Dec 2025 image)
- Add unit test verifying video worker routes to Cloud Run Jobs when
flag is enabled

**Incident:** Job `43c0d519` (Westlife - Medley) stuck at `encoding` for
4+ hours on 2026-03-08. A deployment rollout killed the Cloud Run
instance running the encoding orchestrator as a `BackgroundTask`. The
three-layer defense (PRs #413, #473) only protected the GCE encoding
worker, not the Cloud Run orchestrator lifecycle.

**Root cause:** `BackgroundTask` work runs after the HTTP response
returns, so Cloud Run can kill it during deployment drain. Cloud Run
Jobs run to completion and are immune to Service deployments.

See `docs/archive/2026-03-08-fix-encoding-deploy-survival.md` for full
incident analysis.

## Test plan
- [x] Backend tests pass (103 tests)
- [x] New unit test: `test_trigger_video_worker_routes_to_cloud_run_job`
- [x] Job `43c0d519` re-triggered and completed successfully
- [ ] After deploy: verify video worker dispatches Cloud Run Job (check
Cloud Run Jobs console)
- [ ] After deploy: run a test job end-to-end

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 22:57:03 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 2f19921328 fix: Align audio edit API response with frontend interface (#516)
## Summary
- Backend `input-audio-info` endpoint returned nested structure
(`original_audio.playback_url`) but frontend expected flat fields
(`original_audio_url`, `edit_stack`, etc.)
- Caused "can't access property 'length', t.edit_stack is undefined"
error on the audio edit page
- Added defensive `|| []` fallback for `edit_stack` access in frontend

## Test plan
- [x] Backend unit tests updated and passing (25/25)
- [ ] Verify audio edit page loads 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-08 22:41:39 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 26297fe7c4 feat: Add Edit Input Audio feature (trim, cut, mute, join) (#514)
## Summary

@coderabbitai ignore

Adds a complete "Edit Input Audio" feature that lets users optionally
trim, cut, mute, or join input audio before processing begins. This is
especially useful for live recordings from YouTube where users need to
skip talking/intros.

**5 phases implemented:**
- **Phase 1 (Backend):** 3 new job states, FFmpeg audio operations
service, 6 API endpoints, edit stack undo/redo
- **Phase 2 (Sessions):** Audio edit session persistence with Firestore
+ GCS, SHA256 deduplication
- **Phase 3 (Creation Flow):** Opt-in toggle in job creation,
requires_audio_edit flag across all 3 creation paths
- **Phase 4 (Editor UI):** Full audio editor with waveform
visualization, selection-based editing, playback controls, submit flow
- **Phase 5 (Restore):** Auto-save hook, session restore dialog, manual
save progress

**Key changes:**
- 3 new job states: `awaiting_audio_edit`, `in_audio_edit`,
`audio_edit_complete`
- Server-side FFmpeg operations (lossless FLAC internally, OGG Opus for
browser)
- Collapsible audio edit toggle in VisibilityStep (defaults to off)
- "Edit Audio" action button in JobCard for awaiting_audio_edit status
- Session auto-save every 3 edits + on page hide + before submit
- Session restore dialog when returning to an interrupted edit

## Test plan

- [x] All 706 frontend tests pass (38 suites)
- [x] All 2491 backend tests pass (1 pre-existing failure in unrelated
test)
- [x] 23 AudioEditor component tests (loading, rendering, undo/redo,
submit, restore, save)
- [x] 25 audio edit route tests
- [x] 18 audio edit service tests
- [x] 13 audio edit session tests
- [x] 5 VisibilityStep toggle tests
- [ ] Manual E2E test with real audio file (user to verify)

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 20:31:13 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 2131342fa1 Deduplicate catalog track suggestions (#513)
@coderabbitai ignore

## Summary
- Deduplicate song suggestions in the CatalogTrackList by artist + track
name before rendering
- Spotify returns the same song from multiple albums (deluxe, singles,
etc.), causing identical rows

## Test plan
- [x] Visual: "Etherwood - Weightless" no longer shows 5 identical rows
- [x] Logic: `findFuzzyMatches` already deduplicates for the Did You
Mean banner; this adds the same to the suggestion panel

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 12:13:11 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 93823b8a20 Move song suggestions to Step 2 with fuzzy typo correction (#512)
@coderabbitai ignore

## Summary

- **Simplified Step 1 (Song Info)**: Removed autocomplete — plain text
inputs for artist/title so users aren't confused by autocomplete
behavior
- **Step 2 song suggestions**: Catalog lookup + community version check
fire in parallel with audio search. Results appear as a "Song found in
our database" panel (exact match) or correction suggestion panel while
the user waits
- **Fuzzy "Did you mean?" correction**: When audio search returns poor
results (Tier 3) and catalog has no exact title match, fetches the
artist's discography and fuzzy-matches against the user's title. Shows
amber banner with one-click correction + expandable alternatives list.
Title-based fallback with artist tiebreaker handles garbled artist
fields
- **Visibility step reworked**: Action buttons at top for one-click
select+continue, "change later" note, removed Recommended badge
- **Minor UI polish**: Warning icon on community banner, "Recommended
Audio" heading, YouTube icon on community links, filename above release
in pick card

## Test plan

- [x] 70 new tests added (fuzzy matching, SongInfoStep, AudioSourceStep,
VisibilityStep, CommunityVersionBanner)
- [x] All 677 tests pass
- [x] Manual testing via Playwright: "Fox Stevenson / ruises" typo → Did
you mean Bruises; "fox stevenson bruises / bruises" garbled artist →
correct Fox Stevenson suggestion
- [x] CodeRabbit review completed, issues fixed

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 04:40:35 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 ef0bb20094 Fix review session autosave: use edit-count instead of timer (#511)
## Summary

- The 60s interval timer reset on every edit (React dependency
tracking), so active editing could delay saves indefinitely
- Replace with edit-count-based autosave: saves every 3 edits since last
backup
- Uses refs instead of callback dependencies so the save function stays
stable

## Changes

- `use-review-session-autosave.ts`: Replace `setInterval` with
`useEffect` on `historyLength` that checks `editsSinceBackup >= 3`
- Store data/initialData/historyLength in refs so `doSave` callback only
depends on `apiClient`
- Updated tests to match new behavior (11 tests passing)

## Testing
- [x] All 608 frontend tests pass
- [x] New tests for edit-count-based auto-save behavior

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 03:52:43 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 51cd0eadc5 Extend search session TTL to 7 days and handle expiry gracefully (#510)
## Summary
- Extended search session TTL from 30 minutes to 7 days so users who
leave a tab open mid-flow don't hit "Search expired"
- Added graceful frontend handling when sessions do expire — redirects
to re-search with a friendly message instead of raw error
- Updated API docs and tests to match

## Changes
- `backend/api/routes/audio_search.py`: TTL `timedelta(minutes=30)` →
`timedelta(days=7)`
- `frontend/components/job/GuidedJobFlow.tsx`: Catch 404/"Search
expired" errors, clear stale session, redirect to Step 2 with friendly
message preserving song info
- `backend/tests/test_standalone_search.py`: Updated test helper TTL to
match
- `docs/API.md`: Updated TTL reference from "30-min" to "7-day"

## Testing
- [x] All 31 search-specific tests pass
- [x] Full backend suite passes (2212 passed)

## Review
- [x] Local CodeRabbit review completed (no issues with these changes)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 03:23:46 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 f1ec70924e Add lyrics review session backup/restore system (#509)
## Summary

- Server-side auto-save of lyrics review sessions (every 60s if dirty,
on preview, on page hide) with SHA-256 deduplication
- Split-pane restore UI with session browser, edit diff preview, and
cross-job search
- Auto-prompts on load if saved sessions exist; falls back to
localStorage for local mode

## Changes

### Backend
- **New model**: `ReviewSession` + `ReviewSessionSummary` dataclasses
with Firestore serialization
- **5 new API endpoints** under `/api/review/`: save, list, get, delete
sessions + cross-job search
- **Firestore**: 8 new methods for review session CRUD using
subcollection pattern (`jobs/{jobId}/review_sessions/{sessionId}`)
- **GCS storage**: Correction data stored in GCS (can exceed Firestore's
1MB doc limit); metadata in Firestore
- **Deduplication**: SHA-256 hash comparison skips saving identical data

### Frontend
- **`useReviewSessionAutoSave` hook**: 60s interval auto-save,
visibilitychange save, exposed `saveSession()` for manual/preview
triggers
- **`SessionRestoreDialog`**: Split-pane modal with session list + edit
diff preview, "This Job"/"All Jobs" tabs, cross-job search, duration
mismatch warning
- **`LyricsAnalyzer` integration**: Auto-checks for saved sessions on
load, "Save Progress" and "Session History" toolbar buttons, triggers
save on preview

### Docs
- API.md: 5 new review session endpoints documented
- README.md: Feature added to Current State table + Recent Changes
- LESSONS-LEARNED.md: GCS + Firestore metadata pattern

### Also included (from #508)
- Job observability improvements: timeline metadata, `log_to_job()`
helper

## Testing
- [x] 18 backend unit tests (model serialization, all API endpoints,
deduplication, auth, 404s)
- [x] 10 auto-save hook tests (triggers, deduplication tracking,
interval, read-only, error handling, summary computation)
- [x] 16 SessionRestoreDialog tests (rendering, restore flow, tab
switching, cross-job search, empty states)
- [x] All 607 frontend tests pass
- [x] All 2409 backend tests pass

## Review
- [x] CodeRabbit CLI review completed locally (1 fix applied:
beforeunload → visibilitychange)
- [x] Test review completed (26 new frontend tests added)
- [x] Docs review completed

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 00:23:42 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 9d8bf3a952 Improve job observability with timeline metadata and log_to_job (#508)
@coderabbitai ignore

## Summary
- Add `metadata` field to `TimelineEvent` for structured output details
(brand codes, YouTube video IDs, Dropbox paths, GDrive file IDs)
- Add `log_to_job()` helper for API endpoints to write to Firestore job
log subcollections
- Plumb `timeline_metadata` through `job_manager.transition_to_state()`
and `firestore_service.update_job_status()`
- Capture output details in completion timeline events for full
traceability
- Log edit/delete cleanup operations to both Cloud Logging and Firestore
job logs
- Snapshot previous outputs before cleanup for audit trail
- Enhance distribution logging with video_id, folder path, and file IDs

## Context
After shipping "edit completed tracks," tracing edited jobs was
difficult because timeline events lacked output details, cleanup
operations weren't logged to Firestore, and previous outputs were
overwritten with no history. These changes make the job's Firestore
document self-documenting — any agent or human can read the timeline and
understand the full lifecycle.

## Test plan
- [x] 7 new unit tests for `TimelineEvent.metadata` and `log_to_job()`
helper
- [x] All 103 backend tests pass
- [ ] Verify in production after deploy: edit a test job and confirm
timeline metadata appears in Firestore

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 23:08:17 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 e04337fa5d Fix broken notification and CLI review URLs (#507)
## Summary
- Push notifications were sending users to `/review/{id}` and
`/instrumental/{id}` which 404 on Cloudflare Pages static hosting
- Remote CLI was opening browser to path-based URLs missing the `#/`
hash fragment
- Documentation referenced incorrect URL formats

All URLs now correctly use hash-based routing: `/app/jobs#/{id}/review`
and `/app/jobs#/{id}/instrumental`

## Changes
- **backend/services/push_notification_service.py** — Fixed notification
click URLs
- **backend/api/routes/jobs.py** — Fixed edit track response
`review_url`
- **karaoke_gen/utils/remote_cli.py** — Fixed CLI browser open URLs
- **karaoke_gen/utils/cli_args.py** — Fixed help text
- **Tests** — Updated assertions in push notification and remote CLI
tests
- **Docs** — Fixed URL examples in API.md, README.md, TESTING.md
- **pyproject.toml** — Bump version 0.137.0 → 0.137.1

## Test plan
- [x] Backend push notification tests pass (35 tests)
- [x] Remote CLI tests pass (174 tests)
- [x] Full backend test suite passes (103 tests)
- [x] Frontend unit tests pass (581 tests)

<!-- @coderabbitai ignore -->

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 21:22:28 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 3f568373fd Add edit completed tracks feature (#506)
## Summary

- Add ability to edit completed karaoke tracks: cleans up existing
outputs (YouTube, Dropbox, GDrive, GCS), recycles brand code, resets
state to AWAITING_REVIEW
- Support optional artist/title metadata updates during edit (triggers
screens regeneration)
- New `POST /api/jobs/{job_id}/edit` endpoint with cleanup tracking and
review URL response
- Edit button in OutputLinks for completed jobs with confirmation modal
explaining implications

## Changes

### Backend
- `backend/api/routes/jobs.py` - New edit endpoint with full output
cleanup (YouTube, Dropbox, GDrive, GCS finals), brand code recycling,
state transition, and optional metadata update
- `backend/models/job.py` - Added COMPLETE → AWAITING_REVIEW state
transition and `edit_count` field
- `backend/tests/test_edit_completed_track.py` - 14 unit tests covering
success, metadata updates, validation, and cleanup

### Frontend
- `frontend/components/job/EditTrackModal.tsx` - Confirmation modal with
optional artist/title editing
- `frontend/components/job/OutputLinks.tsx` - Edit button (amber) for
completed jobs with outputs
- `frontend/lib/api.ts` - `editCompletedTrack()` API method and
`EditTrackResponse` type
- `frontend/components/__tests__/OutputLinks.test.tsx` - 3 new tests for
Edit button visibility

### Docs
- `docs/API.md` - Documented new endpoint
- `docs/README.md` - Added recent changes entry
- `docs/archive/2026-03-06-edit-completed-tracks-plan.md` -
Implementation plan

## Test plan

- [x] 14 backend unit tests for edit endpoint (success, metadata,
validation, cleanup)
- [x] 3 frontend tests for Edit button visibility (complete job, deleted
outputs, non-complete)
- [x] All 576 frontend unit tests passing
- [ ] Manual: Edit a completed track, verify outputs are cleaned up and
review reopens
- [ ] Manual: Edit with metadata change, verify screens regenerate

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 02:23:38 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 4d0e3bd1fb Add job creation observability (creation_params + OTel spans) (#505)
## Summary

- Store user's original choices (`is_private`, `is_admin`,
`created_from`) in a `creation_params` dict on the job Firestore
document for permanent observability
- Add OTel span attributes (`job_id`, `job.source`, `job.is_private`) to
all 7 job creation endpoints for Cloud Trace searchability

## Context

Investigation of job `fdcc82a6` revealed that while the system correctly
recorded `is_private: true`, we had no way to definitively prove what
the frontend sent. Cloud Trace request sizes provided forensic evidence,
but this required manual byte-counting. These changes ensure future
investigations can answer "what did the user choose?" directly.

## Changes
- **`backend/models/job.py`** — Added `creation_params` field to Job
model
- **`backend/services/job_manager.py`** — Populate `creation_params` at
job creation
- **`backend/api/routes/jobs.py`** — Span attributes on URL + guided
search endpoints
- **`backend/api/routes/file_upload.py`** — Span attributes on upload,
signed URL, URL, and finalise endpoints
- **`backend/api/routes/audio_search.py`** — Span attributes on audio
search endpoint
- **`backend/api/routes/users.py`** — Span attributes on made-for-you
endpoint
- **`backend/tests/test_private_tracks.py`** — 2 new tests for
creation_params
- **`docs/LESSONS-LEARNED.md`** — Documented Cloud Trace forensic
technique

## Test plan
- [x] All 103 backend tests pass (including 27 private tracks tests)
- [x] 2 new unit tests verify creation_params population and defaults

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 02:01:53 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 5391ac8465 fix: prepare nomad theme style_params for visibility change (#504)
## Summary

Fixes screens worker failure when changing visibility from private to
public: `style_params_gcs_path is required`.

## Root Cause

`change_to_public()` was setting `style_params_gcs_path: None` when
resetting to the nomad theme. The screens worker requires this path to
generate title/end screens.

## Fix

Call `_prepare_theme_for_job("nomad")` to properly copy the nomad
theme's `style_params.json` to the job folder before updating the job
and triggering the screens worker.

## Testing

- [x] 22/22 backend visibility tests pass
- [x] Test now verifies `style_params_gcs_path` is set (not None)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 00:50:10 -05:00
Andrew Beveridge ☄️andClaude Opus 4.6 89ade0462c test: add visibility change button tests and lesson learned (#503)
## Summary

Follow-up to #501 and #502 — adds the frontend tests that would have
caught the summary projection bug, plus a lesson learned entry.

## Changes

- 5 new frontend tests for the Change Visibility button (`is_private`
rendering, tenant exclusion, in-progress guard, non-complete exclusion)
- Lesson learned in `docs/LESSONS-LEARNED.md` about always testing the
summary projection layer when adding new fields

## Testing

- [x] 14/14 OutputLinks tests pass (5 new)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 00:33:23 -05:00
201 changed files with 29936 additions and 1130 deletions

No files matched your search

@@ -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).
@@ -0,0 +1,149 @@
# Plan: Improve Job Observability
**Created:** 2026-03-07
**Branch:** feat/sess-20260307-2216-improve-job-observability
**Status:** Draft
## Overview
After shipping the "edit completed tracks" feature, we found it very difficult to trace what actually happened to edited jobs. Timeline events are too sparse (no output details), cleanup operations aren't logged to Cloud Logging or Firestore, state_data gets fully overwritten during re-processing (losing history of previous outputs), and API endpoints don't write to the job's Firestore log subcollection.
The goal is to make it trivially easy for future agents and humans to reconstruct the complete lifecycle of any job by reading its timeline and Firestore logs.
## Problem Analysis
### What we found investigating two edited jobs:
1. **Timeline events only have `status`, `timestamp`, `progress`, `message`** — no output details like YouTube video IDs, brand codes, Dropbox links, or GDrive file IDs
2. **Edit endpoint cleanup results never logged** — the `cleanup_results` dict is built and returned in the HTTP response but never logged to Cloud Logging or the job's Firestore log subcollection
3. **Distribution details incomplete in logs** — YouTube logs the URL but not video_id separately; Dropbox doesn't log folder path; GDrive doesn't log file IDs
4. **`state_data` fully overwritten on re-processing** — `video_worker.py:342-354` does `{**job.state_data, ...}`, so any `DELETE_FIELD` operations from the edit endpoint get lost when old keys are re-merged from the in-memory copy
5. **`outputs_deleted_at` cleared by video worker** — intentionally, but loses audit trail
6. **No Firestore job logs from API endpoints** — edit/admin endpoints only log to Cloud Run stdout, not to `jobs/{job_id}/logs/`
## Requirements
- [ ] Add `metadata` dict to `TimelineEvent` for structured output details
- [ ] Log all cleanup operations (success AND failure) to both Cloud Logging and Firestore job logs
- [ ] Log distribution output details (YouTube video ID, Dropbox path, brand code, GDrive file IDs) in timeline events and Firestore logs
- [ ] Preserve previous output details in timeline when a job is edited (snapshot before cleanup)
- [ ] Add helper to write Firestore job logs from API endpoints (not just workers)
- [ ] Ensure edit/admin delete endpoints write to Firestore job logs
- [ ] No breaking changes to existing timeline format (additive only)
## Technical Approach
### 1. Add `metadata` field to `TimelineEvent`
The `TimelineEvent` model gains an optional `metadata: Optional[Dict[str, Any]]` field. This allows any timeline event to carry structured data without changing the schema. The field is additive — existing events without metadata continue to work.
Key events that gain metadata:
- **`complete`**: `{youtube_url, youtube_video_id, dropbox_link, brand_code, gdrive_file_ids}`
- **Edit initiated**: `{previous_outputs: {youtube_url, dropbox_link, brand_code, gdrive_files}, cleanup_results: {...}}`
- **Outputs deleted**: `{deleted_outputs: {...}, cleanup_results: {...}}`
### 2. Write Firestore job logs from API endpoints
Create a simple helper function that API route handlers can call to append logs to the job's Firestore subcollection. Workers already have `JobLogAdapter` — we just need a lightweight equivalent for API routes:
```python
def log_to_job(job_id: str, worker: str, level: str, message: str, metadata: dict = None):
"""Write a log entry to the job's Firestore log subcollection."""
entry = WorkerLogEntry.create(job_id, worker, level, message, metadata)
FirestoreService().append_log_to_subcollection(job_id, entry)
```
### 3. Enhance distribution logging in video_worker_orchestrator
After each distribution upload succeeds, log the details with structured metadata:
- YouTube: video_id, video_url, channel
- Dropbox: folder_path, sharing_link
- GDrive: file_ids dict
- Brand code: code, prefix, allocated vs recycled
### 4. Snapshot previous outputs on edit
Before the edit endpoint clears state_data distribution keys, capture the current values in the timeline event's metadata. This preserves the history permanently in the timeline array (which is append-only via `ArrayUnion`).
### 5. Log cleanup results from edit/admin endpoints
After cleanup runs, log each step's result to both Cloud Logging and the Firestore job log subcollection with structured metadata.
## Implementation Steps
### Step 1: Add `metadata` to `TimelineEvent` model
- [ ] Add `metadata: Optional[Dict[str, Any]] = None` to `TimelineEvent` in `backend/models/job.py`
- [ ] No migration needed — Firestore is schemaless, existing events just won't have the field
### Step 2: Create `log_to_job` helper
- [ ] Add `log_to_job()` function in `backend/services/firestore_service.py` (or a small utility module)
- [ ] Takes `job_id`, `worker`, `level`, `message`, optional `metadata`
- [ ] Wraps `WorkerLogEntry.create()` + `append_log_to_subcollection()`
- [ ] Catches and suppresses errors (logging should never break the caller)
### Step 3: Update `transition_to_state` to accept metadata
- [ ] Add optional `timeline_metadata: Optional[Dict[str, Any]] = None` parameter to `job_manager.transition_to_state()`
- [ ] Pass through to `update_job_status()` → `TimelineEvent` construction
- [ ] Update `firestore_service.update_job_status()` to accept and pass `timeline_metadata`
### Step 4: Enhance edit endpoint logging
- [ ] Before cleanup: snapshot current distribution outputs (`youtube_url`, `dropbox_link`, `brand_code`, `gdrive_files`) into `previous_outputs` dict
- [ ] After each cleanup step: log result to Cloud Logging AND call `log_to_job()`
- [ ] After all cleanup: include `previous_outputs` and `cleanup_results` in the timeline event metadata
- [ ] The "Track edit initiated" timeline event gains metadata: `{initiated_by, previous_outputs, cleanup_results}`
### Step 5: Enhance admin delete-outputs endpoint logging
- [ ] Same pattern as edit endpoint: snapshot outputs, log each cleanup step, include in timeline metadata
- [ ] The "Outputs deleted by admin" timeline event gains metadata: `{deleted_by, deleted_outputs, cleanup_results}`
### Step 6: Enhance distribution logging in video_worker_orchestrator
- [ ] YouTube upload success: log video_id and video_url with metadata `{video_id, video_url}`
- [ ] Dropbox upload success: log folder_path and sharing_link with metadata `{folder_path, sharing_link}`
- [ ] GDrive upload success: log file_ids with metadata `{file_ids: {...}}`
- [ ] Brand code allocation: log with metadata `{brand_code, source: "allocated"|"recycled"}`
### Step 7: Add output details to `complete` timeline event
- [ ] When `video_worker.py` calls `transition_to_state(COMPLETE)`, pass `timeline_metadata` with distribution output details
- [ ] Include: `youtube_url`, `youtube_video_id`, `dropbox_link`, `brand_code`, `gdrive_file_ids`, `edit_count`
### Step 8: Tests
- [ ] Unit test: `TimelineEvent` with metadata serializes correctly
- [ ] Unit test: `log_to_job` writes to subcollection
- [ ] Unit test: edit endpoint includes `previous_outputs` and `cleanup_results` in timeline event
- [ ] Unit test: `complete` transition includes output metadata
- [ ] Verify existing tests still pass
## Files to Create/Modify
| File | Action | Description |
|------|--------|-------------|
| `backend/models/job.py` | Modify | Add `metadata` field to `TimelineEvent` |
| `backend/services/firestore_service.py` | Modify | Add `log_to_job()` helper, update `update_job_status()` to accept timeline metadata |
| `backend/services/job_manager.py` | Modify | Add `timeline_metadata` param to `transition_to_state()` |
| `backend/api/routes/jobs.py` | Modify | Enhance edit endpoint with cleanup logging, output snapshots, timeline metadata |
| `backend/api/routes/admin.py` | Modify | Enhance delete-outputs endpoint similarly |
| `backend/workers/video_worker_orchestrator.py` | Modify | Add structured metadata to distribution log messages |
| `backend/workers/video_worker.py` | Modify | Pass output metadata in `complete` transition (both orchestrator and legacy paths) |
| `backend/tests/test_edit_completed_track.py` | Modify | Verify timeline metadata in edit tests |
| `backend/tests/test_observability.py` | Create | Tests for TimelineEvent metadata and log_to_job |
## Testing Strategy
- **Unit tests**: TimelineEvent metadata serialization, log_to_job helper, edit endpoint timeline metadata assertions
- **Existing test verification**: `make test` must pass — changes are additive so existing tests should be unaffected
- **No E2E tests needed**: This is purely backend logging/observability — no UI changes
## What This Does NOT Include
- **Dedicated admin UI for viewing job logs** — existing admin page already shows timeline
- **Log aggregation/search UI** — Cloud Logging and Firestore viewer already serve this purpose
- **Changing state_data overwrite behavior** — the `{**job.state_data, ...}` pattern in video_worker.py is intentional; instead we preserve history in timeline events
- **Changing outputs_deleted_at clearing** — video worker clearing it after re-processing is correct behavior; the edit history lives in timeline metadata instead
## Rollback Plan
All changes are additive (new optional field on TimelineEvent, additional log writes). Rolling back just means deploying the previous version — no data migration needed.
## Open Questions
None — the approach is straightforward and low-risk.
+34 -2
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
@@ -1316,9 +1333,24 @@ jobs:
--min-instances 4 \
--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" \
--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-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 }}"
echo "📦 Updating Cloud Run Jobs to image: $IMAGE"
# Video encoding job - runs video worker to completion, immune to service deployments
gcloud run jobs update video-encoding-job \
--image "$IMAGE" \
--region us-central1 \
--project ${{ env.PROJECT_ID }} \
--quiet
echo "✅ Cloud Run Jobs updated"
- name: Verify deployment and version
run: |
EXPECTED_VERSION="${{ steps.version_check.outputs.version }}"
+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
+512 -1
View File
@@ -22,6 +22,7 @@ from backend.services.flacfetch_client import get_flacfetch_client, FlacfetchSer
from backend.services.storage_service import StorageService
from backend.services.audio_search_service import get_audio_search_service, NoResultsError, AudioSearchError
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 karaoke_gen.utils import sanitize_filename
@@ -1045,6 +1046,7 @@ class TriggerWorkerResponse(BaseModel):
ALLOWED_RESET_STATES = {
"pending",
"awaiting_audio_selection",
"awaiting_audio_edit", # Re-enter audio editing phase
"awaiting_review", # Combined review (lyrics + instrumental selection)
# Note: awaiting_instrumental_selection removed - deprecated by combined review flow (Jan 2026)
"instrumental_selected", # Re-run video generation with same settings
@@ -1081,6 +1083,22 @@ STATE_DATA_CLEAR_KEYS = {
"screens_progress",
"encoding_progress",
],
"awaiting_audio_edit": [
# Clear edit state so user starts fresh
"audio_edit_stack",
"audio_edit_redo_stack",
"audio_edit_uploads",
# Clear downstream processing flags
"audio_complete",
"lyrics_complete",
"review_complete",
"corrected_lyrics",
"instrumental_selection",
"video_progress",
"render_progress",
"screens_progress",
"encoding_progress",
],
"awaiting_review": [
# Combined review - user reviews lyrics AND selects instrumental in one step
"review_complete",
@@ -1202,6 +1220,18 @@ async def reset_job(
# Add timeline event
clear_updates["timeline"] = ArrayUnion([timeline_event])
# Special handling for awaiting_audio_edit: restore original input audio
# The submit endpoint copies edited audio to input_media_gcs_path,
# so we must restore the original path so the user starts fresh.
if target_state == "awaiting_audio_edit":
original_path = current_state_data.get("original_input_media_gcs_path")
if original_path:
clear_updates["input_media_gcs_path"] = original_path
logger.info(
f"Admin reset job {job_id}: Restoring input_media_gcs_path "
f"to original: {original_path}"
)
# Execute the update
job_ref.update(clear_updates)
@@ -1591,6 +1621,19 @@ async def delete_job_outputs(
"gdrive": {"status": "skipped", "reason": "no gdrive_files in state_data"},
}
# Snapshot current outputs before cleanup (preserved in timeline metadata)
deleted_outputs = {}
if state_data.get('youtube_url'):
deleted_outputs['youtube_url'] = state_data['youtube_url']
if state_data.get('dropbox_link'):
deleted_outputs['dropbox_link'] = state_data['dropbox_link']
if state_data.get('brand_code'):
deleted_outputs['brand_code'] = state_data['brand_code']
if state_data.get('gdrive_files'):
deleted_outputs['gdrive_files'] = state_data['gdrive_files']
log_to_job(job_id, "admin", "INFO", f"Output deletion initiated by {admin_email}", {"deleted_outputs": deleted_outputs})
# Clean up YouTube
youtube_url = state_data.get('youtube_url')
if youtube_url:
@@ -1717,11 +1760,17 @@ async def delete_job_outputs(
update_payload[f"state_data.{key}"] = DELETE_FIELD
cleared_keys.append(key)
# Add timeline event
# Add timeline event with structured metadata
timeline_event = {
"status": job.status, # Keep current status
"timestamp": deletion_timestamp.isoformat(),
"message": f"Outputs deleted by admin ({admin_email})",
"metadata": {
"action": "outputs_deleted",
"deleted_by": admin_email,
"deleted_outputs": deleted_outputs,
"cleanup_results": results,
},
}
update_payload["timeline"] = ArrayUnion([timeline_event])
@@ -1755,6 +1804,10 @@ async def delete_job_outputs(
f"Brand Code: {brand_code_status}. "
f"Cleared state_data keys: {cleared_keys}"
)
log_to_job(job_id, "admin", "INFO", f"Outputs deleted by {admin_email}: {overall_status}", {
"cleanup_results": results,
"cleared_keys": cleared_keys,
})
return DeleteOutputsResponse(
status=overall_status,
@@ -3250,3 +3303,461 @@ async def get_edit_review_detail(
"annotations": annotations,
"audio_url": audio_url,
}
# ─── Audio Edit Reviews ─────────────────────────────────────────────────────
class AudioEditReviewSummary(BaseModel):
job_id: str
artist: str
title: str
user_email: str
status: str
created_at: Optional[str] = None
updated_at: Optional[str] = None
session_count: int = 0
total_edits: int = 0
original_duration: Optional[float] = None
current_duration: Optional[float] = None
latest_trigger: Optional[str] = None
class AudioEditReviewListResponse(BaseModel):
reviews: List[AudioEditReviewSummary]
total: int
has_more: bool
@router.get("/audio-edit-reviews", response_model=AudioEditReviewListResponse)
def list_audio_edit_reviews(
limit: int = 50,
offset: int = 0,
exclude_test: bool = False,
search: Optional[str] = None,
auth_result: AuthResult = Depends(require_admin),
):
"""List jobs that have audio edit sessions."""
from backend.services.firestore_service import FirestoreService
user_service = get_user_service()
db = user_service.db
fs = FirestoreService()
STREAM_LIMIT = 10000
reviews = []
streamed = 0
for doc in db.collection("jobs").limit(STREAM_LIMIT).stream():
streamed += 1
data = doc.to_dict()
state_data = data.get("state_data") or {}
# Only include jobs that have been through audio edit
# (have edit stack or have audio edit sessions)
has_edit_stack = bool(state_data.get("audio_edit_stack"))
status = data.get("status", "")
is_in_audio_edit = status in (
"awaiting_audio_edit", "in_audio_edit", "audio_edit_complete"
)
if not has_edit_stack and not is_in_audio_edit:
# Quick check: does this job have any audio edit sessions subcollection?
sessions_ref = db.collection("jobs").document(doc.id).collection("audio_edit_sessions")
if not next(sessions_ref.limit(1).stream(), None):
continue
email = data.get("user_email", "")
if exclude_test and is_test_email(email):
continue
artist = data.get("artist", "")
title = data.get("title", "")
if search:
search_lower = search.lower()
if (
search_lower not in (artist or "").lower()
and search_lower not in (title or "").lower()
and search_lower not in (email or "").lower()
):
continue
# Get session summary info
sessions = fs.list_audio_edit_sessions(doc.id)
session_count = len(sessions)
total_edits = 0
latest_trigger = None
current_duration = None
original_duration = None
if sessions:
latest = sessions[0] # Already sorted by updated_at DESC
total_edits = latest.edit_count
latest_trigger = latest.trigger
current_duration = latest.audio_duration_seconds
original_duration = latest.original_duration_seconds
created_at = data.get("created_at")
updated_at = data.get("updated_at")
def _to_iso(val) -> Optional[str]:
if val is None:
return None
if hasattr(val, 'isoformat'):
return val.isoformat()
return str(val)
try:
reviews.append(AudioEditReviewSummary(
job_id=doc.id,
artist=artist or "",
title=title or "",
user_email=email or "",
status=status,
created_at=_to_iso(created_at),
updated_at=_to_iso(updated_at),
session_count=session_count,
total_edits=total_edits,
original_duration=original_duration,
current_duration=current_duration,
latest_trigger=latest_trigger,
))
except Exception as e:
logger.warning(f"Job {doc.id}: Error building audio edit review summary: {e}")
continue
if streamed >= STREAM_LIMIT:
logger.warning(f"Audio edit reviews stream hit limit ({STREAM_LIMIT}), results may be incomplete")
reviews.sort(
key=lambda r: r.updated_at or r.created_at or "",
reverse=True,
)
total = len(reviews)
paginated = reviews[offset : offset + limit]
return AudioEditReviewListResponse(
reviews=paginated,
total=total,
has_more=(offset + limit) < total,
)
@router.get("/audio-edit-reviews/{job_id}")
async def get_audio_edit_review_detail(
job_id: str,
auth_result: AuthResult = Depends(require_admin),
):
"""Get full audio edit review detail for one job, including all sessions."""
from backend.services.firestore_service import FirestoreService
from backend.services.audio_transcoding_service import AudioTranscodingService
job_manager = JobManager()
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
storage = StorageService()
fs = FirestoreService()
job_meta = {
"job_id": job.job_id,
"artist": job.artist,
"title": job.title,
"user_email": job.user_email,
"status": job.status.value if hasattr(job.status, "value") else str(job.status),
"created_at": job.created_at.isoformat() if job.created_at else None,
"updated_at": job.updated_at.isoformat() if job.updated_at else None,
}
# Get all sessions
sessions = fs.list_audio_edit_sessions(job_id)
sessions_data = []
for session in sessions:
session_dict = session.to_dict()
# Convert datetimes to ISO strings
for key in ("created_at", "updated_at"):
val = session_dict.get(key)
if hasattr(val, "isoformat"):
session_dict[key] = val.isoformat()
sessions_data.append(session_dict)
# Get current edit stack from state_data
state_data = job.state_data or {}
edit_stack = state_data.get("audio_edit_stack", [])
# Generate signed URLs for original and current audio
original_audio_url = None
current_audio_url = None
transcoding = AudioTranscodingService(storage_service=storage)
if job.input_media_gcs_path:
try:
current_audio_url = await transcoding.get_review_audio_url_async(
job.input_media_gcs_path, expiration_minutes=120
)
except Exception as e:
logger.warning(f"Job {job_id}: Could not generate current audio URL: {e}")
# Original audio (before edits)
original_path = state_data.get("original_input_media_gcs_path") or job.input_media_gcs_path
if original_path and original_path != job.input_media_gcs_path:
try:
original_audio_url = await transcoding.get_review_audio_url_async(
original_path, expiration_minutes=120
)
except Exception as e:
logger.warning(f"Job {job_id}: Could not generate original audio URL: {e}")
# Load edit log if it exists
edit_log = None
edit_log_path = f"jobs/{job_id}/audio_edit/edit_log.json"
try:
if storage.file_exists(edit_log_path):
edit_log = storage.download_json(edit_log_path)
except Exception as e:
logger.warning(f"Job {job_id}: Could not load audio edit log: {e}")
return {
"job": job_meta,
"sessions": sessions_data,
"edit_stack": edit_stack,
"edit_log": edit_log,
"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/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,
}
+32 -12
View File
@@ -50,6 +50,7 @@ from backend.api.dependencies import require_auth
from backend.services.auth_service import UserType, AuthResult
from backend.middleware.tenant import get_tenant_config_from_request
from backend.exceptions import InsufficientCreditsError
from backend.services.tracing import add_span_attribute
from backend.services.firestore_service import FirestoreService
from pathlib import Path
@@ -239,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,
@@ -266,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:
"""
@@ -632,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
@@ -692,6 +705,11 @@ async def search_audio(
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
job_id = job.job_id
# Trace attributes for observability
add_span_attribute("job_id", job_id)
add_span_attribute("job.source", "audio_search")
add_span_attribute("job.is_private", body.is_private)
logger.info(f"Created job {job_id} for audio search: {body.artist} - {body.title}")
# Update job with audio search fields
@@ -748,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(
@@ -1029,7 +1047,9 @@ async def search_audio_standalone(
)
results_dicts.append(r.to_dict())
# Store session in Firestore (TTL: 30 minutes)
# Store session in Firestore (TTL: 7 days)
# Long TTL so users who leave a tab open mid-flow don't hit "Search expired".
# Sessions are tiny docs (~2 KB) and cleaned up by Firestore TTL policy.
session_id = str(uuid.uuid4())
now = datetime.utcnow()
session_data = {
@@ -1041,7 +1061,7 @@ async def search_audio_standalone(
'results': results_dicts,
'remote_search_id': audio_search_service.last_remote_search_id,
'created_at': now.isoformat(),
'ttl_expiry': now + timedelta(minutes=30),
'ttl_expiry': now + timedelta(days=7),
}
firestore_service = FirestoreService()
firestore_service.create_search_session(session_data)
+71 -24
View File
@@ -40,6 +40,7 @@ from backend.api.dependencies import require_auth
from backend.services.auth_service import UserType, AuthResult
from backend.middleware.tenant import get_tenant_config_from_request
from backend.exceptions import InsufficientCreditsError
from backend.services.tracing import add_span_attribute
from backend.services.youtube_download_service import (
get_youtube_download_service,
YouTubeDownloadError,
@@ -161,6 +162,9 @@ class CreateJobFromUrlRequest(BaseModel):
# Private (non-published) track mode
is_private: bool = Field(False, description="Private track: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive")
# Audio editing
requires_audio_edit: bool = Field(False, description="Pause after download for user to edit input audio")
class CreateJobFromUrlResponse(BaseModel):
"""Response from creating a job from URL."""
@@ -264,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
@@ -276,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,
@@ -313,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'}
@@ -427,6 +444,8 @@ async def upload_and_create_job(
non_interactive: bool = Form(False, description="Skip interactive steps (lyrics review, instrumental selection)"),
# Private (non-published) track mode
is_private: bool = Form(False, description="Private track: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive"),
# Audio editing
requires_audio_edit: bool = Form(False, description="Pause after download for user to edit input audio"),
):
"""
Upload an audio file and create a karaoke generation job with full style configuration.
@@ -558,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] = {}
@@ -657,11 +676,20 @@ async def upload_and_create_job(
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
job_id = job.job_id
# Trace attributes for observability
add_span_attribute("job_id", job_id)
add_span_attribute("job.source", "upload")
add_span_attribute("job.is_private", is_private)
# Record job creation metric
metrics.record_job_created(job_id, source="upload")
logger.info(f"Created job {job_id} for {artist} - {title}")
# Store requires_audio_edit flag in state_data
if requires_audio_edit:
job_manager.update_state_data(job_id, 'requires_audio_edit', True)
# If theme is set and no custom style files are being uploaded, prepare theme style now
# This copies the theme's style_params.json to the job folder so LyricsTranscriber
# can access the style configuration for preview videos
@@ -694,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,
@@ -713,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,
@@ -724,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,
@@ -1048,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':
@@ -1180,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]
@@ -1230,6 +1258,11 @@ async def create_job_with_upload_urls(
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
job_id = job.job_id
# Trace attributes for observability
add_span_attribute("job_id", job_id)
add_span_attribute("job.source", "signed_url_upload")
add_span_attribute("job.is_private", effective_is_private)
# Record job creation metric
metrics.record_job_created(job_id, source="upload")
@@ -1340,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':
@@ -1643,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
@@ -1700,6 +1733,11 @@ async def create_job_from_url(
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
job_id = job.job_id
# Trace attributes for observability
add_span_attribute("job_id", job_id)
add_span_attribute("job.source", "url")
add_span_attribute("job.is_private", body.is_private)
# Record job creation metric
metrics.record_job_created(job_id, source="url")
@@ -1718,6 +1756,10 @@ async def create_job_from_url(
job_manager.update_job(job_id, update_data)
logger.info(f"Applied theme '{effective_theme_id}' to job {job_id}")
# Store requires_audio_edit flag in state_data
if body.requires_audio_edit:
job_manager.update_state_data(job_id, 'requires_audio_edit', True)
logger.info(f"Created URL-based job {job_id} for URL: {body.url}")
if artist:
logger.info(f" Artist: {artist}")
@@ -1828,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}"
@@ -1954,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
@@ -2002,6 +2044,11 @@ async def create_finalise_only_job(
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
job_id = job.job_id
# Trace attributes for observability
add_span_attribute("job_id", job_id)
add_span_attribute("job.source", "finalise")
add_span_attribute("job.is_private", body.is_private)
# Record job creation metric
metrics.record_job_created(job_id, source="finalise")
@@ -2155,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
@@ -2408,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(
@@ -2449,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
+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,
+347 -3
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,
@@ -33,13 +34,14 @@ from backend.services.worker_service import get_worker_service
from backend.services.storage_service import StorageService
from backend.services.theme_service import get_theme_service
from backend.config import get_settings
from backend.services.tracing import add_span_attribute
from backend.api.dependencies import require_admin, require_auth
from backend.services.auth_service import AuthResult
from backend.services.metrics import metrics
from backend.middleware.tenant import get_tenant_from_request
from backend.utils.test_data import is_test_email
from backend.exceptions import InsufficientCreditsError
from backend.services.firestore_service import FirestoreService
from backend.services.firestore_service import FirestoreService, log_to_job
from backend.models.requests import ChangeVisibilityRequest, ChangeVisibilityResponse
from pydantic import BaseModel, Field, validator
@@ -69,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:
@@ -131,9 +134,19 @@ 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")
add_span_attribute("job.is_private", job_create.is_private)
# Record job creation metric
metrics.record_job_created(job.job_id, source="url")
# Trigger both workers in parallel using asyncio.gather
# (FastAPI's BackgroundTasks runs async tasks sequentially)
background_tasks.add_task(_trigger_workers_parallel, job.job_id)
@@ -202,6 +215,303 @@ def _check_job_ownership(job: Job, auth_result: AuthResult) -> bool:
return True
class EditTrackRequest(BaseModel):
"""Request body for editing a completed track."""
artist: Optional[str] = None
title: Optional[str] = None
class EditTrackResponse(BaseModel):
"""Response from editing a completed track."""
status: str
job_id: str
message: str
review_url: str
review_token: str
metadata_updated: bool
cleanup_results: Dict[str, Any]
@router.post("/{job_id}/edit", response_model=EditTrackResponse)
async def edit_completed_track(
job_id: str,
request: EditTrackRequest,
background_tasks: BackgroundTasks,
auth_result: AuthResult = Depends(require_auth),
):
"""
Edit a completed track by cleaning up distributed outputs and reopening review.
This allows users to correct lyrics, change instrumental selection, or update
artist/title metadata on a completed job. The existing outputs (YouTube, Dropbox,
GDrive, GCS finals) are deleted, the brand code is recycled, and the job is
reset to AWAITING_REVIEW so the user can make changes and re-submit.
No additional credits are consumed — the original credit covers re-edits.
"""
import re
from datetime import timezone
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
# Check ownership
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail="You don't have permission to edit this job")
# Only completed jobs can be edited
if job.status != JobStatus.COMPLETE.value and job.status != "complete":
raise HTTPException(
status_code=400,
detail=f"Only completed jobs can be edited. Current status: {job.status}"
)
# Prevent editing if outputs already deleted (edit already in progress)
if job.outputs_deleted_at:
raise HTTPException(
status_code=400,
detail="This job is already being edited (outputs were already deleted)"
)
user_email = auth_result.user_email or "unknown"
state_data = job.state_data or {}
cleanup_results = {}
# Snapshot current outputs before cleanup (preserved in timeline metadata)
previous_outputs = {}
if state_data.get('youtube_url'):
previous_outputs['youtube_url'] = state_data['youtube_url']
if state_data.get('dropbox_link'):
previous_outputs['dropbox_link'] = state_data['dropbox_link']
if state_data.get('brand_code'):
previous_outputs['brand_code'] = state_data['brand_code']
if state_data.get('gdrive_files'):
previous_outputs['gdrive_files'] = state_data['gdrive_files']
log_to_job(job_id, "edit", "INFO", f"Edit initiated by {user_email}", {"previous_outputs": previous_outputs})
# --- Phase 1: Clean up distributed outputs ---
# Delete YouTube video
youtube_url = state_data.get('youtube_url')
if youtube_url:
try:
video_id_match = re.search(r'(?:youtu\.be/|youtube\.com/watch\?v=)([^&\s]+)', youtube_url)
if video_id_match:
video_id = video_id_match.group(1)
from karaoke_gen.karaoke_finalise.karaoke_finalise import KaraokeFinalise
from backend.services.youtube_service import get_youtube_service
youtube_service = get_youtube_service()
if youtube_service.is_configured:
finalise = KaraokeFinalise(
dry_run=False,
non_interactive=True,
user_youtube_credentials=youtube_service.get_credentials_dict()
)
success = finalise.delete_youtube_video(video_id)
cleanup_results["youtube"] = {"status": "success" if success else "failed", "video_id": video_id}
else:
cleanup_results["youtube"] = {"status": "skipped", "reason": "YouTube not configured"}
else:
cleanup_results["youtube"] = {"status": "failed", "reason": f"Could not extract video ID from {youtube_url}"}
except Exception as e:
logger.error(f"Error deleting YouTube video for job {job_id}: {e}", exc_info=True)
cleanup_results["youtube"] = {"status": "error", "error": str(e)}
else:
cleanup_results["youtube"] = {"status": "skipped", "reason": "no youtube_url"}
log_to_job(job_id, "edit", "INFO", f"YouTube cleanup: {cleanup_results['youtube'].get('status')}", cleanup_results["youtube"])
# Delete Dropbox folder
brand_code = state_data.get('brand_code')
dropbox_path = getattr(job, 'dropbox_path', None)
if brand_code and dropbox_path:
try:
from backend.services.dropbox_service import get_dropbox_service
dropbox = get_dropbox_service()
if dropbox.is_configured:
base_name = f"{job.artist} - {job.title}"
folder_name = f"{brand_code} - {base_name}"
full_path = f"{dropbox_path}/{folder_name}"
success = dropbox.delete_folder(full_path)
cleanup_results["dropbox"] = {"status": "success" if success else "failed", "path": full_path}
else:
cleanup_results["dropbox"] = {"status": "skipped", "reason": "Dropbox not configured"}
except Exception as e:
logger.error(f"Error deleting Dropbox folder for job {job_id}: {e}", exc_info=True)
cleanup_results["dropbox"] = {"status": "error", "error": str(e)}
else:
cleanup_results["dropbox"] = {"status": "skipped", "reason": "no brand_code or dropbox_path"}
log_to_job(job_id, "edit", "INFO", f"Dropbox cleanup: {cleanup_results['dropbox'].get('status')}", cleanup_results["dropbox"])
# Delete Google Drive files
gdrive_files = state_data.get('gdrive_files')
if gdrive_files:
try:
from backend.services.gdrive_service import get_gdrive_service
gdrive = get_gdrive_service()
if gdrive.is_configured:
file_ids = list(gdrive_files.values()) if isinstance(gdrive_files, dict) else []
delete_results = gdrive.delete_files(file_ids)
all_success = all(delete_results.values())
cleanup_results["gdrive"] = {"status": "success" if all_success else "partial", "files": delete_results}
else:
cleanup_results["gdrive"] = {"status": "skipped", "reason": "Google Drive not configured"}
except Exception as e:
logger.error(f"Error deleting Google Drive files for job {job_id}: {e}", exc_info=True)
cleanup_results["gdrive"] = {"status": "error", "error": str(e)}
else:
cleanup_results["gdrive"] = {"status": "skipped", "reason": "no gdrive_files"}
log_to_job(job_id, "edit", "INFO", f"GDrive cleanup: {cleanup_results['gdrive'].get('status')}", cleanup_results["gdrive"])
# Delete GCS finals folder
try:
storage = StorageService()
finals_prefix = f"jobs/{job_id}/finals/"
deleted_count = storage.delete_folder(finals_prefix)
cleanup_results["gcs_finals"] = {"status": "success", "deleted_count": deleted_count}
except Exception as e:
logger.error(f"Error deleting GCS finals for job {job_id}: {e}", exc_info=True)
cleanup_results["gcs_finals"] = {"status": "error", "error": str(e)}
# Recycle brand code if Dropbox + GDrive cleanup both succeeded
dropbox_ok = cleanup_results.get("dropbox", {}).get("status") in ("success", "skipped")
gdrive_ok = cleanup_results.get("gdrive", {}).get("status") in ("success", "skipped")
if brand_code and dropbox_ok and gdrive_ok:
try:
from backend.services.brand_code_service import BrandCodeService, get_brand_code_service
prefix, number = BrandCodeService.parse_brand_code(brand_code)
get_brand_code_service().recycle_brand_code(prefix, number)
cleanup_results["brand_code"] = {"status": "recycled", "code": brand_code}
logger.info(f"Recycled brand code {brand_code} during edit for job {job_id}")
except (ValueError, Exception) as e:
logger.warning(f"Failed to recycle brand code {brand_code}: {e}")
cleanup_results["brand_code"] = {"status": "failed", "error": str(e)}
# Check for critical cleanup failures before proceeding
critical_failures = [
svc for svc in ["dropbox", "gdrive"]
if cleanup_results.get(svc, {}).get("status") == "error"
]
if critical_failures:
raise HTTPException(
status_code=500,
detail=f"Cleanup failed for {', '.join(critical_failures)}. "
f"Job not modified. Please try again or contact support."
)
# --- Phase 2: Update job record ---
db = FirestoreService().db
job_ref = db.collection("jobs").document(job_id)
now = datetime.now(timezone.utc)
update_payload: Dict[str, Any] = {
"outputs_deleted_at": now,
"outputs_deleted_by": user_email,
"updated_at": now,
"edit_count": (job.edit_count if hasattr(job, 'edit_count') else 0) + 1,
}
# Clear distribution state_data keys
output_keys = ["youtube_url", "youtube_video_id", "dropbox_link", "brand_code", "gdrive_files"]
for key in output_keys:
if key in state_data:
update_payload[f"state_data.{key}"] = DELETE_FIELD
# Clear processing state so workers re-run from scratch
processing_keys = ["render_progress", "video_progress", "encoding_progress", "review_complete"]
for key in processing_keys:
if key in state_data:
update_payload[f"state_data.{key}"] = DELETE_FIELD
# --- Phase 3: Update metadata if provided ---
metadata_updated = False
if request.artist and request.artist != job.artist:
update_payload["artist"] = request.artist
metadata_updated = True
if request.title and request.title != job.title:
update_payload["title"] = request.title
metadata_updated = True
# If metadata changed, delete screens so they get regenerated
if metadata_updated:
try:
screens_prefix = f"jobs/{job_id}/screens/"
storage = StorageService()
storage.delete_folder(screens_prefix)
logger.info(f"Deleted screens for job {job_id} due to metadata change")
except Exception as e:
logger.warning(f"Failed to delete screens for job {job_id}: {e}")
# Clear screens progress so screens worker re-runs
if "screens_progress" in state_data:
update_payload[f"state_data.screens_progress"] = DELETE_FIELD
# Add timeline event with structured metadata
edit_number = (job.edit_count if hasattr(job, 'edit_count') else 0) + 1
timeline_event = {
"status": "complete",
"timestamp": now.isoformat(),
"message": f"Track edit initiated by {user_email} (edit #{edit_number})",
"metadata": {
"action": "edit_initiated",
"initiated_by": user_email,
"edit_number": edit_number,
"previous_outputs": previous_outputs,
"cleanup_results": cleanup_results,
},
}
update_payload["timeline"] = ArrayUnion([timeline_event])
# Apply Firestore update
job_ref.update(update_payload)
# --- Phase 4: Transition state to AWAITING_REVIEW ---
# This auto-generates a review token via transition_to_state
job_manager.transition_to_state(
job_id,
JobStatus.AWAITING_REVIEW,
progress=60,
message="Track reopened for editing",
)
# If metadata changed, trigger screens worker in background
if metadata_updated:
background_tasks.add_task(worker_service.trigger_screens_worker, job_id)
# Fetch updated job to get the review token
updated_job = job_manager.get_job(job_id)
if not updated_job:
logger.error(f"Job {job_id} not found after state transition to AWAITING_REVIEW")
raise HTTPException(status_code=500, detail="Job state update failed unexpectedly")
review_token = updated_job.review_token or ""
logger.info(
f"User {user_email} initiated edit #{edit_number} for job {job_id}. "
f"Metadata updated: {metadata_updated}. "
f"Cleanup: YouTube={cleanup_results.get('youtube', {}).get('status')}, "
f"Dropbox={cleanup_results.get('dropbox', {}).get('status')}, "
f"GDrive={cleanup_results.get('gdrive', {}).get('status')}"
)
log_to_job(job_id, "edit", "INFO", f"Edit #{edit_number} complete: reopened for review", {
"cleanup_results": cleanup_results,
"metadata_updated": metadata_updated,
})
return EditTrackResponse(
status="success",
job_id=job_id,
message="Track reopened for editing. Previous outputs have been removed.",
review_url=f"/app/jobs#/{job_id}/review",
review_token=review_token,
metadata_updated=metadata_updated,
cleanup_results=cleanup_results,
)
_SUMMARY_STATE_DATA_KEYS = {
'brand_code', 'youtube_url', 'dropbox_link',
'audio_progress', 'lyrics_progress',
@@ -974,6 +1284,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
@@ -1131,7 +1461,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
}
@@ -1782,6 +2113,7 @@ class CreateFromSearchRequest(BaseModel):
display_artist: Optional[str] = Field(None, description="Display artist override for title screens/filenames")
display_title: Optional[str] = Field(None, description="Display title override for title screens/filenames")
is_private: bool = Field(False, description="Private track: Dropbox only, no YouTube/GDrive")
requires_audio_edit: bool = Field(False, description="Pause after download for user to edit input audio")
@validator('display_artist', 'display_title')
def strip_whitespace(cls, v):
@@ -1930,8 +2262,18 @@ 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
add_span_attribute("job_id", job_id)
add_span_attribute("job.source", "guided_search")
add_span_attribute("job.is_private", body.is_private)
metrics.record_job_created(job_id, source="guided_search")
# Apply default theme style to job (copy style_params.json to job folder)
@@ -1959,6 +2301,8 @@ async def create_job_from_search(
}
if session.get('remote_search_id'):
state_data_update['remote_search_id'] = session['remote_search_id']
if body.requires_audio_edit:
state_data_update['requires_audio_edit'] = True
job_manager.update_job(job_id, {'state_data': state_data_update})
# Transition to DOWNLOADING_AUDIO (skips AWAITING_AUDIO_SELECTION entirely)
+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,
+887
View File
@@ -26,7 +26,9 @@ from fastapi.responses import FileResponse, RedirectResponse, StreamingResponse
from starlette.background import BackgroundTask
from backend.models.job import JobStatus
from backend.models.review_session import ReviewSession, ReviewSessionSummary
from backend.services.job_manager import JobManager
from backend.services.firestore_service import FirestoreService
from backend.services.storage_service import StorageService
from backend.services.job_logging import job_log_context, JobLogger
from backend.services.tracing import create_span, add_span_attribute, add_span_event
@@ -63,6 +65,27 @@ def _get_audio_hash(job_id: str) -> str:
return hashlib.md5(job_id.encode()).hexdigest()
# Cross-job search endpoint MUST be registered before {job_id} routes
# to avoid FastAPI matching "sessions" as a job_id path parameter.
@router.get("/sessions/search")
async def search_review_sessions(
q: str = "",
limit: int = 20,
auth_info: Tuple[str, str] = Depends(require_auth)
):
"""
Search review sessions across all jobs (admin only).
Query params:
- q: Search text (matches artist, title, or job_id)
- limit: Max results (default 20)
"""
firestore_svc = FirestoreService()
results = firestore_svc.search_review_sessions(query_text=q, limit=limit)
return {"sessions": results}
@router.get("/{job_id}/ping")
async def ping(job_id: str):
"""Health check endpoint expected by frontend."""
@@ -905,3 +928,867 @@ async def get_waveform_data(
except Exception as e:
logger.error(f"Job {job_id}: Error generating waveform data: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Error generating waveform: {str(e)}")
# ============================================
# Review Session Endpoints (backup/restore)
# ============================================
@router.post("/{job_id}/sessions")
async def save_review_session(
job_id: str,
data: Dict[str, Any],
auth_info: Tuple[str, str] = Depends(require_review_auth)
):
"""
Save a review session snapshot for backup/restore.
Stores correction data in GCS and metadata in Firestore subcollection.
Skips save if the data is identical to the most recent session (deduplication).
Request body:
- correction_data: Full CorrectionData object
- edit_count: Number of edits in this session
- trigger: "auto" | "preview" | "manual"
- summary: { total_segments, total_words, corrections_made, changed_words[] }
"""
job_manager = JobManager()
firestore_svc = FirestoreService()
storage = StorageService()
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
correction_data = data.get("correction_data")
if not correction_data:
raise HTTPException(status_code=400, detail="correction_data is required")
# Compute hash for deduplication
data_json = json.dumps(correction_data, sort_keys=True, default=str)
data_hash = hashlib.sha256(data_json.encode()).hexdigest()
# Check if identical to most recent session
latest_hash = firestore_svc.get_latest_review_session_hash(job_id)
if latest_hash == data_hash:
logger.info(f"Job {job_id}: Skipping duplicate review session save")
return {"status": "skipped", "reason": "identical_data"}
# Get audio duration from backing_vocals_analysis if available
audio_duration = None
backing_analysis = job.state_data.get("backing_vocals_analysis", {})
if backing_analysis:
audio_duration = backing_analysis.get("total_duration_seconds")
# Build session
user_email = auth_info[0] if auth_info else ""
summary_data = data.get("summary", {})
session = ReviewSession(
job_id=job_id,
user_email=user_email,
edit_count=data.get("edit_count", 0),
trigger=data.get("trigger", "auto"),
audio_duration_seconds=audio_duration,
artist=job.artist,
title=job.title,
summary=ReviewSessionSummary.from_dict(summary_data),
data_hash=data_hash,
)
# Upload correction data to GCS
gcs_path = f"jobs/{job_id}/review_sessions/{session.session_id}.json"
storage.upload_json(gcs_path, correction_data)
session.correction_data_gcs_path = gcs_path
# Save metadata to Firestore
firestore_svc.save_review_session(job_id, session)
logger.info(f"Job {job_id}: Saved review session {session.session_id} (trigger={session.trigger}, edits={session.edit_count})")
return {
"status": "saved",
"session_id": session.session_id,
"created_at": session.created_at.isoformat(),
}
@router.get("/{job_id}/sessions")
async def list_review_sessions(
job_id: str,
auth_info: Tuple[str, str] = Depends(require_review_auth)
):
"""
List all review sessions for a job (metadata only, no correction_data).
Ordered by updated_at descending (most recent first).
"""
firestore_svc = FirestoreService()
sessions = firestore_svc.list_review_sessions(job_id)
return {
"sessions": [
{
"session_id": s.session_id,
"job_id": s.job_id,
"user_email": s.user_email,
"created_at": s.created_at.isoformat() if s.created_at else None,
"updated_at": s.updated_at.isoformat() if s.updated_at else None,
"edit_count": s.edit_count,
"trigger": s.trigger,
"audio_duration_seconds": s.audio_duration_seconds,
"artist": s.artist,
"title": s.title,
"summary": s.summary.to_dict(),
}
for s in sessions
]
}
@router.get("/{job_id}/sessions/{session_id}")
async def get_review_session(
job_id: str,
session_id: str,
auth_info: Tuple[str, str] = Depends(require_review_auth)
):
"""
Get a single review session with full correction_data loaded from GCS.
"""
firestore_svc = FirestoreService()
storage = StorageService()
session = firestore_svc.get_review_session(job_id, session_id)
if not session:
raise HTTPException(status_code=404, detail="Review session not found")
# Load correction data from GCS
correction_data = None
if session.correction_data_gcs_path:
try:
correction_data = storage.download_json(session.correction_data_gcs_path)
except Exception as e:
logger.error(f"Job {job_id}: Error loading correction data for session {session_id}: {e}")
raise HTTPException(status_code=500, detail="Error loading session correction data")
return {
"session_id": session.session_id,
"job_id": session.job_id,
"user_email": session.user_email,
"created_at": session.created_at.isoformat() if session.created_at else None,
"updated_at": session.updated_at.isoformat() if session.updated_at else None,
"edit_count": session.edit_count,
"trigger": session.trigger,
"audio_duration_seconds": session.audio_duration_seconds,
"artist": session.artist,
"title": session.title,
"summary": session.summary.to_dict(),
"correction_data": correction_data,
}
@router.delete("/{job_id}/sessions/{session_id}")
async def delete_review_session(
job_id: str,
session_id: str,
auth_info: Tuple[str, str] = Depends(require_review_auth)
):
"""Delete a review session (metadata + GCS data)."""
firestore_svc = FirestoreService()
storage = StorageService()
session = firestore_svc.get_review_session(job_id, session_id)
if not session:
raise HTTPException(status_code=404, detail="Review session not found")
# Delete GCS data
if session.correction_data_gcs_path:
try:
storage.delete_file(session.correction_data_gcs_path)
except Exception:
logger.warning(f"Job {job_id}: Could not delete GCS file for session {session_id}")
# Delete Firestore doc
firestore_svc.delete_review_session(job_id, session_id)
return {"status": "deleted", "session_id": session_id}
# ============================================
# Audio Edit Session Endpoints (backup/restore)
# ============================================
@router.post("/{job_id}/audio-edit-sessions")
async def save_audio_edit_session(
job_id: str,
data: Dict[str, Any],
auth_info: Tuple[str, str] = Depends(require_review_auth),
):
"""Save an audio edit session snapshot."""
import hashlib
import json as json_mod
from backend.models.audio_edit_session import AudioEditSession, AudioEditSessionSummary
job_manager = JobManager()
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
user_email = auth_info[0] if isinstance(auth_info, tuple) else ""
edit_data = data.get("edit_data", {})
# Compute hash for deduplication
data_json = json_mod.dumps(edit_data, sort_keys=True, default=str)
data_hash = hashlib.sha256(data_json.encode()).hexdigest()
# Skip if identical to most recent
firestore_svc = FirestoreService()
latest_hash = firestore_svc.get_latest_audio_edit_session_hash(job_id)
if latest_hash == data_hash:
return {"status": "skipped", "reason": "identical_data"}
# Build session
summary_data = data.get("summary", {})
session = AudioEditSession(
job_id=job_id,
user_email=user_email,
edit_count=data.get("edit_count", 0),
trigger=data.get("trigger", "auto"),
audio_duration_seconds=summary_data.get("net_duration_seconds"),
original_duration_seconds=data.get("original_duration_seconds"),
artist=job.artist,
title=job.title,
summary=AudioEditSessionSummary.from_dict(summary_data),
data_hash=data_hash,
)
# Upload edit_data to GCS
storage = StorageService()
gcs_path = f"jobs/{job_id}/audio_edit_sessions/{session.session_id}.json"
storage.upload_json(gcs_path, edit_data)
session.edit_data_gcs_path = gcs_path
# Save metadata to Firestore
firestore_svc.save_audio_edit_session(job_id, session)
return {
"status": "saved",
"session_id": session.session_id,
"created_at": session.created_at.isoformat(),
}
@router.get("/{job_id}/audio-edit-sessions")
async def list_audio_edit_sessions(
job_id: str,
auth_info: Tuple[str, str] = Depends(require_review_auth),
):
"""List all audio edit sessions for a job (metadata only)."""
firestore_svc = FirestoreService()
sessions = firestore_svc.list_audio_edit_sessions(job_id)
return {
"sessions": [s.to_dict() for s in sessions]
}
@router.get("/{job_id}/audio-edit-sessions/{session_id}")
async def get_audio_edit_session(
job_id: str,
session_id: str,
auth_info: Tuple[str, str] = Depends(require_review_auth),
):
"""Get a single audio edit session with full edit_data loaded from GCS."""
firestore_svc = FirestoreService()
session = firestore_svc.get_audio_edit_session(job_id, session_id)
if not session:
raise HTTPException(status_code=404, detail="Session not found")
result = session.to_dict()
# Load edit data from GCS
if session.edit_data_gcs_path:
try:
storage = StorageService()
result["edit_data"] = storage.download_json(session.edit_data_gcs_path)
except Exception as e:
logger.warning(f"Could not load audio edit data from GCS for session {session_id}: {e}")
result["edit_data"] = None
else:
result["edit_data"] = None
return result
@router.delete("/{job_id}/audio-edit-sessions/{session_id}")
async def delete_audio_edit_session(
job_id: str,
session_id: str,
auth_info: Tuple[str, str] = Depends(require_review_auth),
):
"""Delete an audio edit session (metadata + GCS data)."""
firestore_svc = FirestoreService()
session = firestore_svc.get_audio_edit_session(job_id, session_id)
if not session:
raise HTTPException(status_code=404, detail="Session not found")
# Delete GCS data
if session.edit_data_gcs_path:
try:
storage = StorageService()
storage.delete_file(session.edit_data_gcs_path)
except Exception:
logger.warning(f"Could not delete GCS file for audio edit session {session_id}")
# Delete Firestore doc
firestore_svc.delete_audio_edit_session(job_id, session_id)
return {"status": "deleted", "session_id": session_id}
# ============================================
# Audio Edit Endpoints
# ============================================
def _get_current_audio_gcs_path(job) -> str:
"""Get the GCS path of the current audio (latest edit or original)."""
state_data = job.state_data or {}
edit_stack = state_data.get('audio_edit_stack', [])
if edit_stack:
return edit_stack[-1]['gcs_path']
return job.input_media_gcs_path
def _build_audio_edit_response(
job_id: str,
gcs_path: str,
edit_stack: list,
redo_stack: list,
edit_id: str | None = None,
) -> dict:
"""Build a standard response for audio edit operations matching AudioEditResponse interface."""
from backend.services.audio_analysis_service import AudioAnalysisService
from backend.services.audio_transcoding_service import AudioTranscodingService
analysis_service = AudioAnalysisService()
transcoding_service = AudioTranscodingService()
# Get waveform data for current audio
amplitudes, duration = analysis_service.get_waveform_data(
gcs_audio_path=gcs_path,
job_id=job_id,
num_points=1000,
)
# Get playback URL (OGG Opus)
playback_url = transcoding_service.get_review_audio_url(gcs_path)
# Build flat response matching frontend AudioEditResponse interface
response = {
"status": "success",
"duration_after": duration,
"current_audio_url": playback_url,
"waveform_data": {"amplitudes": list(amplitudes)},
"edit_stack": [
{
"edit_id": entry.get("edit_id", ""),
"operation": entry.get("operation", ""),
"params": entry.get("params", {}),
"duration_before": entry.get("duration_before", 0),
"duration_after": entry.get("duration_after", entry.get("duration_seconds", 0)),
"timestamp": entry.get("timestamp", ""),
}
for entry in edit_stack
],
"can_undo": len(edit_stack) > 0,
"can_redo": len(redo_stack) > 0,
}
if edit_id is not None:
response["edit_id"] = edit_id
return response
@router.get("/{job_id}/input-audio-info")
async def get_input_audio_info(
job_id: str,
auth_info: Tuple[str, str] = Depends(require_review_auth),
):
"""
Get metadata about the input audio for the audio editor UI.
Returns duration, waveform data, playback URL, and edit state.
"""
from backend.services.audio_analysis_service import AudioAnalysisService
from backend.services.audio_transcoding_service import AudioTranscodingService
from backend.services.audio_edit_service import AudioEditService
job_manager = JobManager()
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
if not job.input_media_gcs_path:
raise HTTPException(status_code=404, detail="No input audio available")
try:
edit_service = AudioEditService()
analysis_service = AudioAnalysisService()
transcoding_service = AudioTranscodingService()
state_data = job.state_data or {}
edit_stack = state_data.get('audio_edit_stack', [])
# 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,
)
original_playback_url = transcoding_service.get_review_audio_url(job.input_media_gcs_path)
# Determine current audio state
current_duration = orig_duration
current_audio_url = original_playback_url
current_waveform = orig_amplitudes
if edit_stack:
current_gcs_path = edit_stack[-1]['gcs_path']
current_waveform, current_duration = analysis_service.get_waveform_data(
gcs_audio_path=current_gcs_path,
job_id=job_id,
num_points=1000,
)
current_audio_url = transcoding_service.get_review_audio_url(current_gcs_path)
# Return flat structure matching AudioEditInfo frontend interface
result = {
"job_id": job_id,
"artist": job.artist,
"title": job.title,
"original_duration_seconds": orig_duration,
"current_duration_seconds": current_duration,
"original_audio_url": original_playback_url,
"current_audio_url": current_audio_url,
"waveform_data": {"amplitudes": list(current_waveform)},
"original_waveform_data": {"amplitudes": list(orig_amplitudes)},
"edit_stack": [
{
"edit_id": entry.get("edit_id", ""),
"operation": entry.get("operation", ""),
"params": entry.get("params", {}),
"duration_before": entry.get("duration_before", 0),
"duration_after": entry.get("duration_after", 0),
"timestamp": entry.get("timestamp", ""),
}
for entry in edit_stack
],
"can_undo": len(edit_stack) > 0,
"can_redo": len(state_data.get('audio_edit_redo_stack', [])) > 0,
}
return result
except Exception as e:
logger.error(f"Job {job_id}: Error getting input audio info: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Error getting audio info: {str(e)}")
@router.post("/{job_id}/audio-edit/apply")
async def apply_audio_edit(
job_id: str,
request: Request,
auth_info: Tuple[str, str] = Depends(require_review_auth),
):
"""
Apply an edit operation to the input audio.
Supported operations: trim_start, trim_end, cut, mute, join_start, join_end.
Returns updated waveform data and playback URL.
"""
import uuid
from backend.services.audio_edit_service import AudioEditService
body = await request.json()
operation = body.get("operation")
params = body.get("params", {})
edit_id = body.get("edit_id") or str(uuid.uuid4())
if not operation:
raise HTTPException(status_code=400, detail="Missing 'operation' field")
valid_operations = {"trim_start", "trim_end", "cut", "mute", "join_start", "join_end"}
if operation not in valid_operations:
raise HTTPException(status_code=400, detail=f"Invalid operation: {operation}. Valid: {valid_operations}")
job_manager = JobManager()
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_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT):
raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})")
# Transition to IN_AUDIO_EDIT if not already
if job.status == JobStatus.AWAITING_AUDIO_EDIT:
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.IN_AUDIO_EDIT,
progress=15,
message="Audio editing in progress"
)
# Resolve upload_id to GCS path for join operations
if operation in ("join_start", "join_end"):
upload_id = params.get("upload_id")
if not upload_id:
raise HTTPException(status_code=400, detail="Missing 'upload_id' for join operation")
state_data = job.state_data or {}
uploads = state_data.get('audio_edit_uploads', {})
upload_info = uploads.get(upload_id)
if not upload_info:
raise HTTPException(status_code=404, detail=f"Upload {upload_id} not found")
params["upload_gcs_path"] = upload_info["gcs_path"]
try:
edit_service = AudioEditService()
# Get current audio path and duration before edit
state_data = job.state_data or {}
existing_stack = state_data.get('audio_edit_stack', [])
current_gcs_path = _get_current_audio_gcs_path(job)
# Determine duration before this edit
if existing_stack:
duration_before = existing_stack[-1].get('duration_seconds', 0)
else:
before_metadata = edit_service.get_metadata_from_gcs(current_gcs_path)
duration_before = before_metadata.duration_seconds
output_gcs_path = f"jobs/{job_id}/audio_edit/edit_{edit_id}.flac"
# Apply the edit
metadata, result_path = edit_service.apply_edit(
input_gcs_path=current_gcs_path,
operation=operation,
params=params,
output_gcs_path=output_gcs_path,
job_id=job_id,
)
# Update edit stack in state_data
edit_stack = list(existing_stack)
edit_stack.append({
"edit_id": edit_id,
"operation": operation,
"params": {k: v for k, v in params.items() if k != "upload_gcs_path"},
"gcs_path": result_path,
"duration_before": duration_before,
"duration_after": metadata.duration_seconds,
"duration_seconds": metadata.duration_seconds,
"timestamp": __import__("datetime").datetime.utcnow().isoformat(),
})
# Clear redo stack on new edit
updated_state_data = {
**state_data,
'audio_edit_stack': edit_stack,
'audio_edit_redo_stack': [],
}
job_manager.update_job(job_id, {'state_data': updated_state_data})
return _build_audio_edit_response(
job_id=job_id,
gcs_path=result_path,
edit_stack=edit_stack,
redo_stack=[],
edit_id=edit_id,
)
except ValueError as e:
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
logger.error(f"Job {job_id}: Error applying audio edit: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Error applying edit: {str(e)}")
@router.post("/{job_id}/audio-edit/undo")
async def undo_audio_edit(
job_id: str,
auth_info: Tuple[str, str] = Depends(require_review_auth),
):
"""Undo the last audio edit operation."""
job_manager = JobManager()
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_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT):
raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})")
state_data = job.state_data or {}
edit_stack = list(state_data.get('audio_edit_stack', []))
redo_stack = list(state_data.get('audio_edit_redo_stack', []))
if not edit_stack:
raise HTTPException(status_code=400, detail="Nothing to undo")
# Pop from edit stack, push to redo stack
undone_edit = edit_stack.pop()
redo_stack.append(undone_edit)
updated_state_data = {
**state_data,
'audio_edit_stack': edit_stack,
'audio_edit_redo_stack': redo_stack,
}
job_manager.update_job(job_id, {'state_data': updated_state_data})
# Get the now-current audio (previous edit or original)
current_gcs_path = edit_stack[-1]['gcs_path'] if edit_stack else job.input_media_gcs_path
try:
return _build_audio_edit_response(
job_id=job_id,
gcs_path=current_gcs_path,
edit_stack=edit_stack,
redo_stack=redo_stack,
)
except Exception as e:
logger.error(f"Job {job_id}: Error building undo response: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Error during undo: {str(e)}")
@router.post("/{job_id}/audio-edit/redo")
async def redo_audio_edit(
job_id: str,
auth_info: Tuple[str, str] = Depends(require_review_auth),
):
"""Redo a previously undone audio edit."""
job_manager = JobManager()
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_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT):
raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})")
state_data = job.state_data or {}
edit_stack = list(state_data.get('audio_edit_stack', []))
redo_stack = list(state_data.get('audio_edit_redo_stack', []))
if not redo_stack:
raise HTTPException(status_code=400, detail="Nothing to redo")
# Pop from redo stack, push to edit stack
redone_edit = redo_stack.pop()
edit_stack.append(redone_edit)
updated_state_data = {
**state_data,
'audio_edit_stack': edit_stack,
'audio_edit_redo_stack': redo_stack,
}
job_manager.update_job(job_id, {'state_data': updated_state_data})
current_gcs_path = edit_stack[-1]['gcs_path']
try:
return _build_audio_edit_response(
job_id=job_id,
gcs_path=current_gcs_path,
edit_stack=edit_stack,
redo_stack=redo_stack,
)
except Exception as e:
logger.error(f"Job {job_id}: Error building redo response: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Error during redo: {str(e)}")
@router.post("/{job_id}/audio-edit/upload")
async def upload_audio_for_join(
job_id: str,
request: Request,
auth_info: Tuple[str, str] = Depends(require_review_auth),
):
"""
Upload additional audio for join operations.
Accepts multipart form upload. Returns upload_id and metadata.
"""
import uuid
from fastapi import UploadFile
from backend.services.audio_edit_service import AudioEditService
from backend.services.audio_analysis_service import AudioAnalysisService
job_manager = JobManager()
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_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT):
raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})")
# Parse multipart form
form = await request.form()
file = form.get("file")
if not file:
raise HTTPException(status_code=400, detail="Missing 'file' in form data")
# Validate file extension
filename = getattr(file, 'filename', 'unknown')
valid_extensions = {'.flac', '.wav', '.mp3', '.m4a', '.ogg'}
ext = os.path.splitext(filename)[1].lower()
if ext not in valid_extensions:
raise HTTPException(
status_code=400,
detail=f"Invalid file type '{ext}'. Accepted: {', '.join(valid_extensions)}"
)
upload_id = str(uuid.uuid4())
gcs_path = f"jobs/{job_id}/audio_edit/upload_{upload_id}{ext}"
try:
storage = StorageService()
edit_service = AudioEditService()
analysis_service = AudioAnalysisService()
# Save uploaded file to GCS
content = await file.read()
with tempfile.NamedTemporaryFile(suffix=ext, delete=False) as tmp:
tmp.write(content)
tmp_path = tmp.name
try:
storage.upload_file(tmp_path, gcs_path)
# Get metadata
metadata = edit_service.get_metadata(tmp_path)
# Get waveform data
from karaoke_gen.instrumental_review import WaveformGenerator
waveform_gen = WaveformGenerator()
amplitudes, duration = waveform_gen.generate_data_only(
audio_path=tmp_path,
num_points=1000,
)
finally:
os.unlink(tmp_path)
# Store upload info in state_data
state_data = job.state_data or {}
uploads = dict(state_data.get('audio_edit_uploads', {}))
uploads[upload_id] = {
"gcs_path": gcs_path,
"duration_seconds": metadata.duration_seconds,
"filename": filename,
}
updated_state_data = {**state_data, 'audio_edit_uploads': uploads}
job_manager.update_job(job_id, {'state_data': updated_state_data})
return {
"upload_id": upload_id,
"duration_seconds": metadata.duration_seconds,
"waveform_data": {
"amplitudes": amplitudes,
"duration": duration,
},
}
except Exception as e:
logger.error(f"Job {job_id}: Error uploading audio for join: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Error uploading audio: {str(e)}")
@router.post("/{job_id}/audio-edit/submit")
async def submit_audio_edit(
job_id: str,
request: Request,
auth_info: Tuple[str, str] = Depends(require_review_auth),
):
"""
Finalize the audio edit and continue processing.
Copies the current edited audio to the job's input path,
then triggers audio separation and lyrics transcription workers.
"""
from backend.services.worker_service import get_worker_service
job_manager = JobManager()
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_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT):
raise HTTPException(status_code=400, detail=f"Job is not in audio edit state (current: {job.status})")
state_data = job.state_data or {}
edit_stack = state_data.get('audio_edit_stack', [])
storage = StorageService()
# Save edit log if provided
body = await request.json() if request.headers.get("content-type", "").startswith("application/json") else {}
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_path, edit_log)
logger.info(f"Job {job_id}: Saved audio edit log to {edit_log_path}")
if edit_stack:
# Copy the latest edited audio to the canonical input path
current_edited_path = edit_stack[-1]['gcs_path']
edited_input_path = f"jobs/{job_id}/input/edited.flac"
# Download and re-upload to canonical path
with tempfile.TemporaryDirectory() as temp_dir:
local_path = os.path.join(temp_dir, "edited.flac")
storage.download_file(current_edited_path, local_path)
storage.upload_file(local_path, edited_input_path)
# Update job to use edited audio as input
job_manager.update_job(job_id, {
'input_media_gcs_path': edited_input_path,
})
logger.info(f"Job {job_id}: Audio edit submitted, using edited audio: {edited_input_path}")
else:
logger.info(f"Job {job_id}: Audio edit submitted with no edits, using original audio")
# Transition state
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.AUDIO_EDIT_COMPLETE,
progress=18,
message="Audio edit complete, starting processing"
)
# Trigger parallel workers in background so the HTTP response returns immediately.
# The worker triggers involve Cloud Run Job calls that can take 30+ seconds;
# waiting synchronously causes the browser request to time out.
worker_service = get_worker_service()
async def _trigger_workers():
try:
await asyncio.gather(
worker_service.trigger_audio_worker(job_id),
worker_service.trigger_lyrics_worker(job_id),
)
except Exception as e:
logger.error(f"Job {job_id}: Failed to trigger workers after audio edit: {e}")
asyncio.create_task(_trigger_workers())
return {
"status": "success",
"message": "Audio edit saved. Processing will continue with edited audio.",
"job_id": job_id,
"edits_applied": len(edit_stack),
}
+110 -16
View File
@@ -34,6 +34,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,
@@ -66,6 +67,8 @@ from backend.services.youtube_download_service import (
YouTubeDownloadError,
)
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__)
@@ -146,6 +149,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")
@@ -154,8 +201,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)
@@ -170,16 +215,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
@@ -229,7 +274,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)
@@ -252,12 +297,22 @@ 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 (not at account creation)
credits_granted = 0
if user_service.grant_welcome_credits_if_eligible(user.email):
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)
# 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
@@ -290,6 +345,7 @@ async def verify_magic_link(
user=user_public,
message="Successfully signed in",
tenant_subdomain=tenant_subdomain,
credits_granted=credits_granted,
)
@@ -578,6 +634,11 @@ async def _handle_made_for_you_order(
job = job_manager.create_job(job_create, is_admin=True)
job_id = job.job_id
# Trace attributes for observability
add_span_attribute("job_id", job_id)
add_span_attribute("job.source", "made_for_you")
add_span_attribute("job.is_private", False)
logger.info(f"Created made-for-you job {job_id} for {_mask_email(customer_email)} (owned by {_mask_email(ADMIN_EMAIL)})")
# Prepare theme style assets for the job (same as audio_search endpoint)
@@ -1195,9 +1256,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)
@@ -1238,6 +1307,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
@@ -1245,16 +1315,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', ''))]
@@ -1334,13 +1411,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 = []
@@ -1362,9 +1450,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,
)
+110
View File
@@ -0,0 +1,110 @@
"""
Audio edit session model for persisting input audio editing progress.
Stored as a Firestore subcollection: jobs/{job_id}/audio_edit_sessions/{session_id}
Full edit data is stored in GCS to avoid Firestore's 1MB document limit.
"""
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Optional, Dict, Any, List
import uuid
@dataclass
class AudioEditSessionSummary:
"""Compact summary of operations in an audio edit session, for list views."""
total_operations: int = 0
operations_breakdown: Dict[str, int] = field(default_factory=dict)
duration_change_seconds: float = 0.0
net_duration_seconds: float = 0.0
def to_dict(self) -> Dict[str, Any]:
return {
"total_operations": self.total_operations,
"operations_breakdown": self.operations_breakdown,
"duration_change_seconds": self.duration_change_seconds,
"net_duration_seconds": self.net_duration_seconds,
}
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "AudioEditSessionSummary":
return cls(
total_operations=data.get("total_operations", 0),
operations_breakdown=data.get("operations_breakdown", {}),
duration_change_seconds=data.get("duration_change_seconds", 0.0),
net_duration_seconds=data.get("net_duration_seconds", 0.0),
)
@dataclass
class AudioEditSession:
"""
A saved snapshot of an audio editing session.
Stored at: jobs/{job_id}/audio_edit_sessions/{session_id}
Edit data stored at: jobs/{job_id}/audio_edit_sessions/{session_id}.json (GCS)
"""
session_id: str = field(default_factory=lambda: str(uuid.uuid4()))
job_id: str = ""
user_email: str = ""
created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
updated_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
edit_count: int = 0
trigger: str = "auto" # "auto" | "manual" | "submit"
audio_duration_seconds: Optional[float] = None
original_duration_seconds: Optional[float] = None
artist: Optional[str] = None
title: Optional[str] = None
summary: AudioEditSessionSummary = field(default_factory=AudioEditSessionSummary)
edit_data_gcs_path: str = ""
# Hash of the edit data JSON, used to skip duplicate saves
data_hash: str = ""
def to_dict(self) -> Dict[str, Any]:
return {
"session_id": self.session_id,
"job_id": self.job_id,
"user_email": self.user_email,
"created_at": self.created_at,
"updated_at": self.updated_at,
"edit_count": self.edit_count,
"trigger": self.trigger,
"audio_duration_seconds": self.audio_duration_seconds,
"original_duration_seconds": self.original_duration_seconds,
"artist": self.artist,
"title": self.title,
"summary": self.summary.to_dict(),
"edit_data_gcs_path": self.edit_data_gcs_path,
"data_hash": self.data_hash,
}
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "AudioEditSession":
created_at = data.get("created_at")
if isinstance(created_at, str):
created_at = datetime.fromisoformat(created_at.rstrip("Z")).replace(tzinfo=timezone.utc)
updated_at = data.get("updated_at")
if isinstance(updated_at, str):
updated_at = datetime.fromisoformat(updated_at.rstrip("Z")).replace(tzinfo=timezone.utc)
summary_data = data.get("summary", {})
summary = AudioEditSessionSummary.from_dict(summary_data) if isinstance(summary_data, dict) else AudioEditSessionSummary()
return cls(
session_id=data.get("session_id", str(uuid.uuid4())),
job_id=data.get("job_id", ""),
user_email=data.get("user_email", ""),
created_at=created_at or datetime.now(timezone.utc),
updated_at=updated_at or datetime.now(timezone.utc),
edit_count=data.get("edit_count", 0),
trigger=data.get("trigger", "auto"),
audio_duration_seconds=data.get("audio_duration_seconds"),
original_duration_seconds=data.get("original_duration_seconds"),
artist=data.get("artist"),
title=data.get("title"),
summary=summary,
edit_data_gcs_path=data.get("edit_data_gcs_path", ""),
data_hash=data.get("data_hash", ""),
)
+63 -4
View File
@@ -16,8 +16,9 @@ class JobStatus(str, Enum):
"""
Job status enumeration - Complete state machine.
The workflow has 7 main stages with 2 human interaction points:
The workflow has 8 main stages with up to 3 human interaction points:
1. Input & Setup (may include audio source selection)
1b. Optional Audio Editing (BLOCKING) - trim/cut/mute/join input audio
2. Parallel Processing (audio + lyrics)
3. Title/End Screen Generation + Backing Vocals Analysis
4. Countdown Padding Synchronization
@@ -39,6 +40,11 @@ class JobStatus(str, Enum):
DOWNLOADING = "downloading" # Downloading from URL or processing upload
# Optional: Audio editing (before processing begins)
AWAITING_AUDIO_EDIT = "awaiting_audio_edit" # ⚠️ WAITING FOR USER - edit input audio
IN_AUDIO_EDIT = "in_audio_edit" # User is actively editing audio
AUDIO_EDIT_COMPLETE = "audio_edit_complete" # User submitted edited audio
# Stage 2a: Audio separation (parallel track 1)
SEPARATING_STAGE1 = "separating_stage1" # Clean instrumental separation (Modal API)
SEPARATING_STAGE2 = "separating_stage2" # Backing vocals separation (Modal API)
@@ -103,7 +109,13 @@ STATE_TRANSITIONS = {
JobStatus.DOWNLOADING_AUDIO: [JobStatus.DOWNLOADING, JobStatus.FAILED],
# DOWNLOADING allows parallel processing (audio + lyrics) and then screens when both complete
JobStatus.DOWNLOADING: [JobStatus.SEPARATING_STAGE1, JobStatus.TRANSCRIBING, JobStatus.GENERATING_SCREENS, JobStatus.FAILED],
# Can also enter optional audio edit phase if requires_audio_edit flag is set
JobStatus.DOWNLOADING: [JobStatus.SEPARATING_STAGE1, JobStatus.TRANSCRIBING, JobStatus.GENERATING_SCREENS, JobStatus.AWAITING_AUDIO_EDIT, JobStatus.FAILED],
# Optional audio edit phase (trim, cut, mute, join input audio before processing)
JobStatus.AWAITING_AUDIO_EDIT: [JobStatus.IN_AUDIO_EDIT, JobStatus.AUDIO_EDIT_COMPLETE, JobStatus.FAILED, JobStatus.CANCELLED],
JobStatus.IN_AUDIO_EDIT: [JobStatus.AWAITING_AUDIO_EDIT, JobStatus.AUDIO_EDIT_COMPLETE, JobStatus.FAILED, JobStatus.CANCELLED],
JobStatus.AUDIO_EDIT_COMPLETE: [JobStatus.SEPARATING_STAGE1, JobStatus.TRANSCRIBING, JobStatus.GENERATING_SCREENS, JobStatus.FAILED],
# Audio separation flow
JobStatus.SEPARATING_STAGE1: [JobStatus.SEPARATING_STAGE2, JobStatus.FAILED],
@@ -142,10 +154,10 @@ STATE_TRANSITIONS = {
JobStatus.UPLOADING: [JobStatus.NOTIFYING, JobStatus.COMPLETE, JobStatus.FAILED],
JobStatus.NOTIFYING: [JobStatus.COMPLETE, JobStatus.FAILED],
# Terminal states - COMPLETE allows visibility change re-processing
# Terminal states - COMPLETE allows edit (reopen review) and visibility change
# FAILED and CANCELLED allow retry transitions to resume from checkpoints
# PREP_COMPLETE allows continuation from combined review
JobStatus.COMPLETE: [JobStatus.LYRICS_COMPLETE], # Visibility change: private->public re-processing
JobStatus.COMPLETE: [JobStatus.AWAITING_REVIEW, JobStatus.LYRICS_COMPLETE], # Edit track or visibility change
JobStatus.PREP_COMPLETE: [JobStatus.AWAITING_REVIEW, JobStatus.FAILED], # Continue from combined review
JobStatus.FAILED: [
JobStatus.DOWNLOADING, # Retry from beginning (if input audio exists)
@@ -179,6 +191,7 @@ class TimelineEvent(BaseModel):
timestamp: str
progress: Optional[int] = None
message: Optional[str] = None
metadata: Optional[Dict[str, Any]] = None
class LogEntry(BaseModel):
@@ -305,6 +318,12 @@ class Job(BaseModel):
# Private (non-published) track mode
is_private: bool = False # Private tracks: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive
# 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
@@ -312,6 +331,9 @@ class Job(BaseModel):
# Credit refund tracking (prevents double-refund on cancel→delete or fail→delete)
credit_refunded: bool = False
# Edit tracking (how many times a completed track has been re-edited)
edit_count: int = 0
# Processing state
track_output_dir: Optional[str] = None # Local output directory (temp)
audio_hash: Optional[str] = None # Hash for deduplication
@@ -402,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)
"""
+107
View File
@@ -0,0 +1,107 @@
"""
Review session model for persisting lyrics review progress.
Stored as a Firestore subcollection: jobs/{job_id}/review_sessions/{session_id}
Full correction data is stored in GCS to avoid Firestore's 1MB document limit.
"""
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Optional, Dict, Any, List
import uuid
@dataclass
class ReviewSessionSummary:
"""Compact summary of edits in a review session, for list views."""
total_segments: int = 0
total_words: int = 0
corrections_made: int = 0
changed_words: List[Dict[str, Any]] = field(default_factory=list)
def to_dict(self) -> Dict[str, Any]:
return {
"total_segments": self.total_segments,
"total_words": self.total_words,
"corrections_made": self.corrections_made,
"changed_words": self.changed_words,
}
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "ReviewSessionSummary":
return cls(
total_segments=data.get("total_segments", 0),
total_words=data.get("total_words", 0),
corrections_made=data.get("corrections_made", 0),
changed_words=data.get("changed_words", []),
)
@dataclass
class ReviewSession:
"""
A saved snapshot of a lyrics review editing session.
Stored at: jobs/{job_id}/review_sessions/{session_id}
Correction data stored at: jobs/{job_id}/review_sessions/{session_id}.json (GCS)
"""
session_id: str = field(default_factory=lambda: str(uuid.uuid4()))
job_id: str = ""
user_email: str = ""
created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
updated_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
edit_count: int = 0
trigger: str = "auto" # "auto" | "preview" | "manual"
audio_duration_seconds: Optional[float] = None
artist: Optional[str] = None
title: Optional[str] = None
summary: ReviewSessionSummary = field(default_factory=ReviewSessionSummary)
correction_data_gcs_path: str = ""
# Hash of the correction data JSON, used to skip duplicate saves
data_hash: str = ""
def to_dict(self) -> Dict[str, Any]:
return {
"session_id": self.session_id,
"job_id": self.job_id,
"user_email": self.user_email,
"created_at": self.created_at,
"updated_at": self.updated_at,
"edit_count": self.edit_count,
"trigger": self.trigger,
"audio_duration_seconds": self.audio_duration_seconds,
"artist": self.artist,
"title": self.title,
"summary": self.summary.to_dict(),
"correction_data_gcs_path": self.correction_data_gcs_path,
"data_hash": self.data_hash,
}
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "ReviewSession":
created_at = data.get("created_at")
if isinstance(created_at, str):
created_at = datetime.fromisoformat(created_at.rstrip("Z")).replace(tzinfo=timezone.utc)
updated_at = data.get("updated_at")
if isinstance(updated_at, str):
updated_at = datetime.fromisoformat(updated_at.rstrip("Z")).replace(tzinfo=timezone.utc)
summary_data = data.get("summary", {})
summary = ReviewSessionSummary.from_dict(summary_data) if isinstance(summary_data, dict) else ReviewSessionSummary()
return cls(
session_id=data.get("session_id", str(uuid.uuid4())),
job_id=data.get("job_id", ""),
user_email=data.get("user_email", ""),
created_at=created_at or datetime.now(timezone.utc),
updated_at=updated_at or datetime.now(timezone.utc),
edit_count=data.get("edit_count", 0),
trigger=data.get("trigger", "auto"),
audio_duration_seconds=data.get("audio_duration_seconds"),
artist=data.get("artist"),
title=data.get("title"),
summary=summary,
correction_data_gcs_path=data.get("correction_data_gcs_path", ""),
data_hash=data.get("data_hash", ""),
)
+11
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,6 +124,7 @@ 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
@@ -138,6 +146,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 +158,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 +179,7 @@ class VerifyMagicLinkResponse(BaseModel):
user: "UserPublic"
message: str
tenant_subdomain: Optional[str] = None
credits_granted: int = 0
class UserPublic(BaseModel):
+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,
+180
View File
@@ -0,0 +1,180 @@
"""
Audio editing service — server-side FFmpeg operations for trim, cut, mute, join.
All operations are lossless (FLAC in, FLAC out). Playback URLs use OGG Opus
via the existing AudioTranscodingService.
"""
import logging
import os
import json
import subprocess
import tempfile
from dataclasses import dataclass, asdict
from backend.services.storage_service import StorageService
logger = logging.getLogger(__name__)
@dataclass
class AudioMetadata:
duration_seconds: float
sample_rate: int
channels: int
format: str
file_size_bytes: int
class AudioEditService:
"""Server-side audio editing via FFmpeg."""
def __init__(self, storage_service: StorageService | None = None):
self.storage = storage_service or StorageService()
def get_metadata(self, audio_path: str) -> AudioMetadata:
"""Get audio metadata from a local file using ffprobe."""
cmd = [
"ffprobe", "-v", "quiet", "-print_format", "json",
"-show_format", "-show_streams", audio_path,
]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
if result.returncode != 0:
raise RuntimeError(f"ffprobe failed: {result.stderr}")
info = json.loads(result.stdout)
fmt = info.get("format", {})
streams = info.get("streams", [])
audio_stream = next((s for s in streams if s.get("codec_type") == "audio"), {})
return AudioMetadata(
duration_seconds=float(fmt.get("duration", 0)),
sample_rate=int(audio_stream.get("sample_rate", 44100)),
channels=int(audio_stream.get("channels", 2)),
format=fmt.get("format_name", "unknown"),
file_size_bytes=int(fmt.get("size", 0)),
)
def get_metadata_from_gcs(self, gcs_path: str) -> AudioMetadata:
"""Download from GCS and get metadata."""
with tempfile.TemporaryDirectory() as temp_dir:
local_path = os.path.join(temp_dir, "audio")
self.storage.download_file(gcs_path, local_path)
return self.get_metadata(local_path)
def trim_start(self, input_path: str, end_seconds: float, output_path: str) -> AudioMetadata:
"""Remove audio from 0 to end_seconds (skip the first N seconds)."""
self._run_ffmpeg([
"-ss", str(end_seconds),
"-i", input_path,
"-c:a", "flac",
output_path,
])
return self.get_metadata(output_path)
def trim_end(self, input_path: str, start_seconds: float, output_path: str) -> AudioMetadata:
"""Keep audio from 0 to start_seconds (remove from start_seconds to end)."""
self._run_ffmpeg([
"-i", input_path,
"-t", str(start_seconds),
"-c:a", "flac",
output_path,
])
return self.get_metadata(output_path)
def cut_region(self, input_path: str, start: float, end: float, output_path: str) -> AudioMetadata:
"""Remove a region from start to end, joining the remaining parts."""
self._run_ffmpeg([
"-i", input_path,
"-filter_complex",
f"[0]atrim=0:{start},asetpts=PTS-STARTPTS[a];"
f"[0]atrim={end},asetpts=PTS-STARTPTS[b];"
f"[a][b]concat=n=2:v=0:a=1[out]",
"-map", "[out]",
"-c:a", "flac",
output_path,
])
return self.get_metadata(output_path)
def mute_region(self, input_path: str, start: float, end: float, output_path: str) -> AudioMetadata:
"""Silence a region (preserve duration)."""
self._run_ffmpeg([
"-i", input_path,
"-af", f"volume=enable='between(t,{start},{end})':volume=0",
"-c:a", "flac",
output_path,
])
return self.get_metadata(output_path)
def join_audio(self, input_path: str, other_path: str, position: str, output_path: str) -> AudioMetadata:
"""Join two audio files. position: 'start' (prepend other) or 'end' (append other)."""
if position == "start":
first, second = other_path, input_path
else:
first, second = input_path, other_path
self._run_ffmpeg([
"-i", first,
"-i", second,
"-filter_complex", "[0:a][1:a]concat=n=2:v=0:a=1[out]",
"-map", "[out]",
"-c:a", "flac",
output_path,
])
return self.get_metadata(output_path)
def apply_edit(
self,
input_gcs_path: str,
operation: str,
params: dict,
output_gcs_path: str,
job_id: str,
) -> tuple[AudioMetadata, str]:
"""
Apply an edit operation to an audio file in GCS.
Returns (metadata, output_gcs_path).
"""
with tempfile.TemporaryDirectory() as temp_dir:
local_input = os.path.join(temp_dir, "input.flac")
local_output = os.path.join(temp_dir, "output.flac")
# Download current audio
self.storage.download_file(input_gcs_path, local_input)
# Apply the operation
if operation == "trim_start":
metadata = self.trim_start(local_input, params["end_seconds"], local_output)
elif operation == "trim_end":
metadata = self.trim_end(local_input, params["start_seconds"], local_output)
elif operation == "cut":
metadata = self.cut_region(
local_input, params["start_seconds"], params["end_seconds"], local_output
)
elif operation == "mute":
metadata = self.mute_region(
local_input, params["start_seconds"], params["end_seconds"], local_output
)
elif operation in ("join_start", "join_end"):
# Download the upload file
upload_gcs_path = params["upload_gcs_path"]
local_other = os.path.join(temp_dir, "other.flac")
self.storage.download_file(upload_gcs_path, local_other)
position = "start" if operation == "join_start" else "end"
metadata = self.join_audio(local_input, local_other, position, local_output)
else:
raise ValueError(f"Unknown operation: {operation}")
# Upload edited audio
self.storage.upload_file(local_output, output_gcs_path)
logger.info(f"[{job_id}] Applied {operation}, uploaded to {output_gcs_path}")
return metadata, output_gcs_path
def _run_ffmpeg(self, args: list[str]) -> None:
"""Run an ffmpeg command with standard options."""
cmd = ["ffmpeg", "-hide_banner", "-loglevel", "error", "-y"] + args
result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
if result.returncode != 0:
raise RuntimeError(f"ffmpeg failed (exit {result.returncode}): {result.stderr}")
@@ -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
+188
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,
+400 -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,27 @@ 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
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,
"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(),
"blocked_emails": set(),
"blocked_ips": set(),
"verified_clean_domains": {},
}
# Update cache
@@ -316,6 +237,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 +257,188 @@ 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 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 +509,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 +543,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 +717,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
+366 -2
View File
@@ -10,6 +10,8 @@ from google.cloud.firestore_v1 import FieldFilter
from backend.config import settings
from backend.models.job import Job, JobStatus, TimelineEvent
from backend.models.worker_log import WorkerLogEntry
from backend.models.review_session import ReviewSession
from backend.models.audio_edit_session import AudioEditSession
logger = logging.getLogger(__name__)
@@ -75,18 +77,20 @@ class FirestoreService:
status: JobStatus,
progress: Optional[int] = None,
message: Optional[str] = None,
timeline_metadata: Optional[Dict[str, Any]] = None,
**additional_fields
) -> None:
"""Update job status and add timeline event."""
try:
doc_ref = self.db.collection(self.collection).document(job_id)
# Create timeline event
timeline_event = TimelineEvent(
status=status.value,
timestamp=datetime.utcnow().isoformat(),
progress=progress,
message=message
message=message,
metadata=timeline_metadata,
)
# Prepare updates
@@ -178,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(
@@ -673,6 +680,331 @@ class FirestoreService:
transaction = self.db.transaction()
return _read_and_delete(transaction, doc_ref)
# ============================================
# Review Session Subcollection Methods
# ============================================
# These methods store review session snapshots in a subcollection
# (jobs/{job_id}/review_sessions) for lyrics review backup/restore.
def save_review_session(self, job_id: str, session: ReviewSession) -> str:
"""
Save a review session to the subcollection.
Stores at: jobs/{job_id}/review_sessions/{session_id}
Args:
job_id: Job ID
session: ReviewSession instance
Returns:
session_id
"""
try:
session.job_id = job_id
sessions_ref = self.db.collection(self.collection).document(job_id).collection("review_sessions")
doc_ref = sessions_ref.document(session.session_id)
doc_ref.set(session.to_dict())
logger.info(f"Saved review session {session.session_id} for job {job_id}")
return session.session_id
except Exception as e:
logger.error(f"Error saving review session for job {job_id}: {e}")
raise
def list_review_sessions(self, job_id: str) -> List[ReviewSession]:
"""
List all review sessions for a job, ordered by updated_at descending.
Args:
job_id: Job ID
Returns:
List of ReviewSession instances (metadata only, no correction_data)
"""
try:
sessions_ref = self.db.collection(self.collection).document(job_id).collection("review_sessions")
query = sessions_ref.order_by("updated_at", direction=firestore.Query.DESCENDING)
docs = query.stream()
return [ReviewSession.from_dict(doc.to_dict()) for doc in docs]
except Exception as e:
logger.error(f"Error listing review sessions for job {job_id}: {e}")
return []
def get_review_session(self, job_id: str, session_id: str) -> Optional[ReviewSession]:
"""
Get a single review session by ID.
Args:
job_id: Job ID
session_id: Session ID
Returns:
ReviewSession or None
"""
try:
doc_ref = (
self.db.collection(self.collection)
.document(job_id)
.collection("review_sessions")
.document(session_id)
)
doc = doc_ref.get()
if not doc.exists:
return None
return ReviewSession.from_dict(doc.to_dict())
except Exception as e:
logger.error(f"Error getting review session {session_id} for job {job_id}: {e}")
raise
def delete_review_session(self, job_id: str, session_id: str) -> None:
"""
Delete a review session.
Args:
job_id: Job ID
session_id: Session ID
"""
try:
doc_ref = (
self.db.collection(self.collection)
.document(job_id)
.collection("review_sessions")
.document(session_id)
)
doc_ref.delete()
logger.info(f"Deleted review session {session_id} for job {job_id}")
except Exception as e:
logger.error(f"Error deleting review session {session_id} for job {job_id}: {e}")
raise
def delete_review_sessions_subcollection(self, job_id: str, batch_size: int = 500) -> int:
"""
Delete all review sessions for a job (used when deleting a job).
Args:
job_id: Job ID
batch_size: Number of documents to delete per batch
Returns:
Number of sessions deleted
"""
try:
sessions_ref = self.db.collection(self.collection).document(job_id).collection("review_sessions")
deleted_count = 0
while True:
docs = sessions_ref.limit(batch_size).stream()
deleted_in_batch = 0
batch = self.db.batch()
for doc in docs:
batch.delete(doc.reference)
deleted_in_batch += 1
if deleted_in_batch == 0:
break
batch.commit()
deleted_count += deleted_in_batch
if deleted_in_batch < batch_size:
break
if deleted_count > 0:
logger.info(f"Deleted {deleted_count} review sessions for job {job_id}")
return deleted_count
except Exception as e:
logger.error(f"Error deleting review sessions subcollection for job {job_id}: {e}")
return 0
def get_latest_review_session_hash(self, job_id: str) -> Optional[str]:
"""
Get the data_hash of the most recent review session for deduplication.
Args:
job_id: Job ID
Returns:
data_hash string or None if no sessions exist
"""
try:
sessions_ref = self.db.collection(self.collection).document(job_id).collection("review_sessions")
query = (
sessions_ref
.order_by("updated_at", direction=firestore.Query.DESCENDING)
.limit(1)
.select(["data_hash"])
)
docs = list(query.stream())
if docs:
return docs[0].to_dict().get("data_hash", "")
return None
except Exception as e:
logger.error(f"Error getting latest review session hash for job {job_id}: {e}")
return None
def search_review_sessions(
self,
query_text: str = "",
job_id: Optional[str] = None,
limit: int = 20,
) -> List[Dict[str, Any]]:
"""
Search review sessions across all jobs using collection group query.
Args:
query_text: Search text (prefix-matched against artist_lower or title_lower)
job_id: If provided, search only within this job
limit: Maximum results
Returns:
List of session dicts with job context
"""
try:
if job_id:
# Search within a specific job
sessions_ref = self.db.collection(self.collection).document(job_id).collection("review_sessions")
query = sessions_ref.order_by("updated_at", direction=firestore.Query.DESCENDING).limit(limit)
docs = query.stream()
return [doc.to_dict() for doc in docs]
# Collection group query across all jobs
sessions_ref = self.db.collection_group("review_sessions")
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
if q_lower in (r.get("artist") or "").lower()
or q_lower in (r.get("title") or "").lower()
or q_lower in (r.get("job_id") or "").lower()
]
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}")
return []
# ---- Audio Edit Sessions ----
def save_audio_edit_session(self, job_id: str, session: AudioEditSession) -> str:
"""Save an audio edit session to the subcollection."""
try:
session.job_id = job_id
sessions_ref = self.db.collection(self.collection).document(job_id).collection("audio_edit_sessions")
doc_ref = sessions_ref.document(session.session_id)
doc_ref.set(session.to_dict())
logger.info(f"Saved audio edit session {session.session_id} for job {job_id}")
return session.session_id
except Exception as e:
logger.error(f"Error saving audio edit session for job {job_id}: {e}")
raise
def list_audio_edit_sessions(self, job_id: str) -> List[AudioEditSession]:
"""List all audio edit sessions for a job, ordered by updated_at descending."""
try:
sessions_ref = self.db.collection(self.collection).document(job_id).collection("audio_edit_sessions")
query = sessions_ref.order_by("updated_at", direction=firestore.Query.DESCENDING)
docs = query.stream()
return [AudioEditSession.from_dict(doc.to_dict()) for doc in docs]
except Exception as e:
logger.error(f"Error listing audio edit sessions for job {job_id}: {e}")
return []
def get_audio_edit_session(self, job_id: str, session_id: str) -> Optional[AudioEditSession]:
"""Get a single audio edit session by ID."""
try:
doc_ref = (
self.db.collection(self.collection)
.document(job_id)
.collection("audio_edit_sessions")
.document(session_id)
)
doc = doc_ref.get()
if not doc.exists:
return None
return AudioEditSession.from_dict(doc.to_dict())
except Exception as e:
logger.error(f"Error getting audio edit session {session_id} for job {job_id}: {e}")
raise
def delete_audio_edit_session(self, job_id: str, session_id: str) -> None:
"""Delete a single audio edit session."""
try:
doc_ref = (
self.db.collection(self.collection)
.document(job_id)
.collection("audio_edit_sessions")
.document(session_id)
)
doc_ref.delete()
logger.info(f"Deleted audio edit session {session_id} for job {job_id}")
except Exception as e:
logger.error(f"Error deleting audio edit session {session_id} for job {job_id}: {e}")
raise
def delete_audio_edit_sessions_subcollection(self, job_id: str, batch_size: int = 500) -> int:
"""Delete all audio edit sessions for a job (used when deleting a job)."""
try:
sessions_ref = self.db.collection(self.collection).document(job_id).collection("audio_edit_sessions")
deleted_count = 0
while True:
docs = sessions_ref.limit(batch_size).stream()
deleted_in_batch = 0
batch = self.db.batch()
for doc in docs:
batch.delete(doc.reference)
deleted_in_batch += 1
if deleted_in_batch == 0:
break
batch.commit()
deleted_count += deleted_in_batch
if deleted_in_batch < batch_size:
break
if deleted_count > 0:
logger.info(f"Deleted {deleted_count} audio edit sessions for job {job_id}")
return deleted_count
except Exception as e:
logger.error(f"Error deleting audio edit sessions subcollection for job {job_id}: {e}")
return 0
def get_latest_audio_edit_session_hash(self, job_id: str) -> Optional[str]:
"""Get the data_hash of the most recent audio edit session for deduplication."""
try:
sessions_ref = self.db.collection(self.collection).document(job_id).collection("audio_edit_sessions")
query = (
sessions_ref
.order_by("updated_at", direction=firestore.Query.DESCENDING)
.limit(1)
.select(["data_hash"])
)
docs = list(query.stream())
if docs:
return docs[0].to_dict().get("data_hash", "")
return None
except Exception as e:
logger.error(f"Error getting latest audio edit session hash for job {job_id}: {e}")
return None
def delete_search_session(self, session_id: str) -> None:
"""Delete a search session after it has been consumed by job creation.
@@ -710,3 +1042,35 @@ def get_firestore_client() -> firestore.Client:
_firestore_client = firestore.Client(project=settings.google_cloud_project)
return _firestore_client
_log_service: Optional["FirestoreService"] = None
def _get_log_service() -> "FirestoreService":
"""Return a cached FirestoreService instance for log_to_job."""
global _log_service
if _log_service is None:
_log_service = FirestoreService()
return _log_service
def log_to_job(job_id: str, worker: str, level: str, message: str, metadata: Optional[Dict[str, Any]] = None) -> None:
"""
Write a log entry to a job's Firestore log subcollection.
This is a convenience function for API endpoints that need to log
to a job's log history (workers already have JobLogAdapter for this).
Args:
job_id: Job ID to log to
worker: Worker/source name (e.g., "api", "edit", "admin")
level: Log level (INFO, WARNING, ERROR)
message: Log message
metadata: Optional structured metadata dict
"""
try:
entry = WorkerLogEntry.create(job_id, worker, level, message, metadata)
_get_log_service().append_log_to_subcollection(job_id, entry)
except Exception as e:
logger.debug(f"Failed to write job log for {job_id}: {e}")
+4 -1
View File
@@ -329,7 +329,10 @@ 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
+8
View File
@@ -22,6 +22,9 @@ STATUSES_BEFORE_AUDIO_START = {
JobStatus.PENDING,
JobStatus.SEARCHING_AUDIO,
JobStatus.AWAITING_AUDIO_SELECTION,
JobStatus.AWAITING_AUDIO_EDIT,
JobStatus.IN_AUDIO_EDIT,
JobStatus.AUDIO_EDIT_COMPLETE,
}
# Jobs in these statuses should NOT have lyrics_complete flag set
@@ -29,6 +32,9 @@ STATUSES_BEFORE_LYRICS_START = {
JobStatus.PENDING,
JobStatus.SEARCHING_AUDIO,
JobStatus.AWAITING_AUDIO_SELECTION,
JobStatus.AWAITING_AUDIO_EDIT,
JobStatus.IN_AUDIO_EDIT,
JobStatus.AUDIO_EDIT_COMPLETE,
}
# Statuses where screens_progress.stage='complete' is valid
@@ -185,11 +191,13 @@ def get_worker_valid_statuses() -> Dict[str, List[JobStatus]]:
"audio_worker": [
JobStatus.DOWNLOADING,
JobStatus.DOWNLOADING_AUDIO,
JobStatus.AUDIO_EDIT_COMPLETE,
JobStatus.SEPARATING_STAGE1,
JobStatus.SEPARATING_STAGE2,
],
"lyrics_worker": [
JobStatus.DOWNLOADING,
JobStatus.AUDIO_EDIT_COMPLETE,
JobStatus.TRANSCRIBING,
JobStatus.CORRECTING,
],
+66 -13
View File
@@ -120,8 +120,14 @@ class JobManager:
customer_notes=job_create.customer_notes,
# Private (non-published) track mode
is_private=job_create.is_private,
# Capture creation-time decision params for observability
creation_params={
"is_private": job_create.is_private,
"is_admin": is_admin,
"created_from": job_create.request_metadata.get("created_from", "unknown"),
},
)
self.firestore.create_job(job)
logger.info(f"Created new job {job_id} with status PENDING")
@@ -344,6 +350,14 @@ class JobManager:
except Exception as e:
logger.warning(f"Error deleting logs subcollection for job {job_id}: {e}")
# Delete audio edit sessions subcollection
try:
deleted_sessions = self.firestore.delete_audio_edit_sessions_subcollection(job_id)
if deleted_sessions > 0:
logger.info(f"Deleted {deleted_sessions} audio edit sessions for job {job_id}")
except Exception as e:
logger.warning(f"Error deleting audio edit sessions for job {job_id}: {e}")
self.firestore.delete_job(job_id)
logger.info(f"Deleted job {job_id}")
@@ -407,7 +421,8 @@ class JobManager:
progress: Optional[int] = None,
message: Optional[str] = None,
state_data_updates: Optional[Dict[str, Any]] = None,
raise_on_invalid: bool = True
raise_on_invalid: bool = True,
timeline_metadata: Optional[Dict[str, Any]] = None,
) -> bool:
"""
Transition job to new state with validation.
@@ -420,6 +435,7 @@ class JobManager:
state_data_updates: Updates to state_data field
raise_on_invalid: If True (default), raise InvalidStateTransitionError
on invalid transitions. If False, return False silently.
timeline_metadata: Optional structured metadata to attach to the timeline event
Returns:
True if transition succeeded, False if failed (only when raise_on_invalid=False)
@@ -429,31 +445,31 @@ class JobManager:
"""
if not self.validate_state_transition(job_id, new_status, raise_on_invalid=raise_on_invalid):
return False
updates = {
'status': new_status,
'updated_at': datetime.utcnow()
}
if progress is not None:
updates['progress'] = progress
# Generate review token when entering AWAITING_REVIEW state
# Generate review token when entering blocking states that need user action
# Tokens don't expire - they're job-scoped so low risk, and natural expiry happens when job completes
if new_status == JobStatus.AWAITING_REVIEW:
if new_status in (JobStatus.AWAITING_REVIEW, JobStatus.AWAITING_AUDIO_EDIT):
from backend.api.dependencies import generate_review_token
review_token = generate_review_token()
updates['review_token'] = review_token
updates['review_token_expires_at'] = None # No expiry - token is job-scoped
logger.info(f"Generated review token for job {job_id} (no expiry)")
# If we have state_data_updates, merge them with existing state_data
merged_state_data = None
if state_data_updates:
job = self.get_job(job_id)
if job:
merged_state_data = {**job.state_data, **state_data_updates}
# Update job status (includes timeline event), passing state_data if present
if merged_state_data is not None:
self.update_job_status(
@@ -461,6 +477,7 @@ class JobManager:
status=new_status,
progress=progress,
message=message,
timeline_metadata=timeline_metadata,
state_data=merged_state_data
)
else:
@@ -468,7 +485,8 @@ class JobManager:
job_id=job_id,
status=new_status,
progress=progress,
message=message
message=message,
timeline_metadata=timeline_metadata,
)
# Apply review token update separately if generated
@@ -521,10 +539,15 @@ class JobManager:
self._send_push_notification(job, "complete")
# Idle reminder scheduling for blocking states
elif new_status in [JobStatus.AWAITING_REVIEW, JobStatus.AWAITING_INSTRUMENTAL_SELECTION]:
elif new_status in [JobStatus.AWAITING_REVIEW, JobStatus.AWAITING_INSTRUMENTAL_SELECTION, JobStatus.AWAITING_AUDIO_EDIT]:
self._schedule_idle_reminder(job, new_status)
# Send push notification for blocking states
action_type = "lyrics" if new_status == JobStatus.AWAITING_REVIEW else "instrumental"
if new_status == JobStatus.AWAITING_AUDIO_EDIT:
action_type = "audio_edit"
elif new_status == JobStatus.AWAITING_REVIEW:
action_type = "lyrics"
else:
action_type = "instrumental"
self._send_push_notification(job, action_type)
except Exception as e:
@@ -611,7 +634,12 @@ class JobManager:
# Record when we entered blocking state (for idle detection)
blocking_entered_at = datetime.utcnow().isoformat()
action_type = "lyrics" if new_status == JobStatus.AWAITING_REVIEW else "instrumental"
if new_status == JobStatus.AWAITING_AUDIO_EDIT:
action_type = "audio_edit"
elif new_status == JobStatus.AWAITING_REVIEW:
action_type = "lyrics"
else:
action_type = "instrumental"
# Update state_data with blocking state info (handle None state_data)
existing_state_data = job.state_data or {}
@@ -720,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.
@@ -61,6 +61,10 @@ class JobNotificationService:
# Use hash-based routing for static hosting compatibility
return f"{self.frontend_url}/app/jobs#/{job_id}/instrumental"
def _build_audio_edit_url(self, job_id: str) -> str:
"""Build the audio edit URL for a job."""
return f"{self.frontend_url}/app/jobs#/{job_id}/audio-edit"
async def send_job_completion_email(
self,
job_id: str,
@@ -213,6 +217,7 @@ class JobNotificationService:
action_type: Type of action needed:
- "lyrics": Combined review (lyrics + instrumental selection) for normal jobs
- "instrumental": Instrumental-only selection for finalise-only jobs
- "audio_edit": Audio editing before processing begins
user_name: User's display name
artist: Artist name
title: Song title
@@ -249,6 +254,15 @@ class JobNotificationService:
title=title,
instrumental_url=instrumental_url,
)
elif action_type == "audio_edit":
audio_edit_url = self._build_audio_edit_url(job_id)
# Reuse the lyrics template but with the audio edit URL and different subject
message_content = self.template_service.render_action_needed_lyrics(
name=user_name,
artist=artist,
title=title,
review_url=audio_edit_url,
)
else:
logger.error(f"Unknown action type: {action_type}")
return False
+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:
@@ -243,12 +243,12 @@ class PushNotificationService:
if action_type == "lyrics":
notif_title = "Review Lyrics"
notif_body = f'"{title}" by {artist} needs lyrics review'
url = f"/review/{job_id}"
url = f"/app/jobs#/{job_id}/review"
tag = f"lyrics-{job_id}"
else: # instrumental
notif_title = "Select Instrumental"
notif_body = f'"{title}" by {artist} needs instrumental selection'
url = f"/instrumental/{job_id}"
url = f"/app/jobs#/{job_id}/instrumental"
tag = f"instrumental-{job_id}"
return await self.send_push(
+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}")
+263 -17
View File
@@ -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,238 @@ 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) -> bool:
"""
Grant welcome credits on first magic link verification.
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.
Returns:
True if credits were granted, False if already received or user not found.
"""
try:
email = email.lower()
user = self.get_user(email)
if not user:
return False
# Primary check: dedicated flag (survives transaction list trimming)
if user.welcome_credits_granted:
return False
# Secondary check: look for existing welcome_credit transaction
for txn in user.credit_transactions:
if txn.reason == "welcome_credit":
return False # Already received
# 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
except Exception:
logger.exception(f"Error granting welcome credits to {email}")
return False
# =========================================================================
# 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)
"""
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:
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,
}
# =========================================================================
# Session Management
# =========================================================================
@@ -368,7 +611,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 +622,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 +634,7 @@ class UserService:
ip_address=ip_address,
user_agent=user_agent,
tenant_id=tenant_id,
device_fingerprint=device_fingerprint,
)
# Serialize and write to Firestore
+11 -5
View File
@@ -152,15 +152,21 @@ class VisibilityChangeService:
except Exception:
pass
# Step 3: Reset styles and update job fields
# Step 4: Set status to LYRICS_COMPLETE with regen_restore_status
# Step 5: Clear progress keys and set guard flag
# Step 3: Prepare nomad theme style files for the job
from backend.api.routes.file_upload import _prepare_theme_for_job
style_params_path, style_assets_dict, _youtube_desc = _prepare_theme_for_job(
job_id=job_id, theme_id="nomad"
)
# Step 4: Reset styles and update job fields
# Step 5: Set status to LYRICS_COMPLETE with regen_restore_status
# Step 6: Clear progress keys and set guard flag
update_payload = {
"is_private": False,
"theme_id": "nomad",
"color_overrides": {},
"style_assets": {},
"style_params_gcs_path": None,
"style_assets": style_assets_dict,
"style_params_gcs_path": style_params_path,
"status": JobStatus.LYRICS_COMPLETE.value,
"state_data.visibility_change_in_progress": True,
"state_data.regen_restore_status": "review_complete",
@@ -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
@@ -0,0 +1,279 @@
"""
Unit tests for admin audio edit review endpoints.
Tests the GET /api/admin/audio-edit-reviews and
GET /api/admin/audio-edit-reviews/{job_id} endpoints.
"""
import pytest
from unittest.mock import Mock, patch, AsyncMock
from fastapi.testclient import TestClient
from fastapi import FastAPI
from datetime import datetime, timezone
from backend.api.routes.admin import router
from backend.api.dependencies import require_admin
from backend.models.job import Job, JobStatus
from backend.models.audio_edit_session import AudioEditSession, AudioEditSessionSummary
# Create a test app with the admin router
app = FastAPI()
app.include_router(router, prefix="/api")
def get_mock_admin():
"""Override for require_admin dependency."""
from backend.api.dependencies import AuthResult, UserType
return AuthResult(
is_valid=True,
user_type=UserType.ADMIN,
remaining_uses=999,
message="Admin authenticated",
user_email="admin@example.com",
is_admin=True,
)
app.dependency_overrides[require_admin] = get_mock_admin
@pytest.fixture
def client():
return TestClient(app)
def _make_audio_edit_job_doc(job_id, artist="Test Artist", title="Test Song",
user_email="user@example.com", status="complete",
has_edit_stack=True):
"""Create a mock Firestore document for a job with audio edits."""
doc = Mock()
doc.id = job_id
now = datetime.now(timezone.utc)
state_data = {}
if has_edit_stack:
state_data["audio_edit_stack"] = [
{"edit_id": "e1", "operation": "cut", "gcs_path": f"jobs/{job_id}/edits/e1.flac"}
]
doc.to_dict.return_value = {
"artist": artist,
"title": title,
"user_email": user_email,
"status": status,
"state_data": state_data,
"file_urls": {},
"created_at": now,
"updated_at": now,
}
return doc
def _make_session(job_id, trigger="auto", edit_count=3):
"""Create a mock AudioEditSession."""
return AudioEditSession(
session_id="sess-1",
job_id=job_id,
user_email="user@example.com",
edit_count=edit_count,
trigger=trigger,
audio_duration_seconds=150.0,
original_duration_seconds=225.0,
artist="Test Artist",
title="Test Song",
summary=AudioEditSessionSummary(
total_operations=edit_count,
operations_breakdown={"cut": 2, "mute": 1},
duration_change_seconds=-75.0,
net_duration_seconds=150.0,
),
)
class TestListAudioEditReviews:
"""Tests for GET /api/admin/audio-edit-reviews."""
@patch("backend.services.firestore_service.FirestoreService")
@patch("backend.api.routes.admin.get_user_service")
def test_list_returns_jobs_with_edit_stacks(self, mock_get_user_service, MockFS, client):
"""Jobs with audio edit stacks should appear."""
mock_db = Mock()
mock_get_user_service.return_value.db = mock_db
docs = [
_make_audio_edit_job_doc("job-1", has_edit_stack=True),
_make_audio_edit_job_doc("job-2", has_edit_stack=False),
]
mock_db.collection.return_value.limit.return_value.stream.return_value = docs
# job-2 has no edit stack and no sessions subcollection
sessions_ref = Mock()
sessions_ref.limit.return_value.stream.return_value = iter([])
mock_db.collection.return_value.document.return_value.collection.return_value = sessions_ref
# Sessions for job-1
MockFS.return_value.list_audio_edit_sessions.return_value = [
_make_session("job-1")
]
response = client.get("/api/admin/audio-edit-reviews")
assert response.status_code == 200
data = response.json()
assert data["total"] == 1
assert data["reviews"][0]["job_id"] == "job-1"
assert data["reviews"][0]["session_count"] == 1
assert data["reviews"][0]["total_edits"] == 3
@patch("backend.services.firestore_service.FirestoreService")
@patch("backend.api.routes.admin.get_user_service")
def test_list_search_filter(self, mock_get_user_service, MockFS, client):
"""Search should filter by artist, title, and email."""
mock_db = Mock()
mock_get_user_service.return_value.db = mock_db
docs = [
_make_audio_edit_job_doc("job-1", artist="Beatles", title="Hey Jude"),
_make_audio_edit_job_doc("job-2", artist="Queen", title="Bohemian Rhapsody"),
]
mock_db.collection.return_value.limit.return_value.stream.return_value = docs
MockFS.return_value.list_audio_edit_sessions.return_value = [_make_session("job-1")]
response = client.get("/api/admin/audio-edit-reviews?search=beatles")
assert response.status_code == 200
data = response.json()
assert data["total"] == 1
assert data["reviews"][0]["artist"] == "Beatles"
@patch("backend.services.firestore_service.FirestoreService")
@patch("backend.api.routes.admin.get_user_service")
def test_list_pagination(self, mock_get_user_service, MockFS, client):
"""Pagination should work with offset and limit."""
mock_db = Mock()
mock_get_user_service.return_value.db = mock_db
docs = [_make_audio_edit_job_doc(f"job-{i}") for i in range(5)]
mock_db.collection.return_value.limit.return_value.stream.return_value = docs
MockFS.return_value.list_audio_edit_sessions.return_value = []
response = client.get("/api/admin/audio-edit-reviews?limit=2&offset=0")
data = response.json()
assert len(data["reviews"]) == 2
assert data["total"] == 5
assert data["has_more"] is True
@patch("backend.services.firestore_service.FirestoreService")
@patch("backend.api.routes.admin.get_user_service")
def test_list_exclude_test_emails(self, mock_get_user_service, MockFS, client):
"""Test emails should be excluded when exclude_test=true."""
mock_db = Mock()
mock_get_user_service.return_value.db = mock_db
docs = [
_make_audio_edit_job_doc("job-1", user_email="real@example.com"),
_make_audio_edit_job_doc("job-2", user_email="test@inbox.testmail.app"),
]
mock_db.collection.return_value.limit.return_value.stream.return_value = docs
MockFS.return_value.list_audio_edit_sessions.return_value = []
response = client.get("/api/admin/audio-edit-reviews?exclude_test=true")
data = response.json()
assert data["total"] == 1
assert data["reviews"][0]["user_email"] == "real@example.com"
@patch("backend.services.firestore_service.FirestoreService")
@patch("backend.api.routes.admin.get_user_service")
def test_list_includes_in_audio_edit_jobs(self, mock_get_user_service, MockFS, client):
"""Jobs in audio edit statuses should appear even without edit stack."""
mock_db = Mock()
mock_get_user_service.return_value.db = mock_db
docs = [
_make_audio_edit_job_doc("job-1", status="in_audio_edit", has_edit_stack=False),
]
mock_db.collection.return_value.limit.return_value.stream.return_value = docs
MockFS.return_value.list_audio_edit_sessions.return_value = []
response = client.get("/api/admin/audio-edit-reviews")
data = response.json()
assert data["total"] == 1
assert data["reviews"][0]["job_id"] == "job-1"
class TestGetAudioEditReviewDetail:
"""Tests for GET /api/admin/audio-edit-reviews/{job_id}."""
@patch("backend.api.routes.admin.StorageService")
@patch("backend.api.routes.admin.JobManager")
def test_returns_404_for_missing_job(self, MockJobManager, MockStorage, client):
MockJobManager.return_value.get_job.return_value = None
response = client.get("/api/admin/audio-edit-reviews/nonexistent")
assert response.status_code == 404
@patch("backend.services.audio_transcoding_service.AudioTranscodingService")
@patch("backend.services.firestore_service.FirestoreService")
@patch("backend.api.routes.admin.StorageService")
@patch("backend.api.routes.admin.JobManager")
def test_returns_full_detail(self, MockJobManager, MockStorage, MockFS, MockTranscoding, client):
"""Should return job metadata, sessions, edit stack, and audio URLs."""
job = Mock(spec=Job)
job.job_id = "test-job"
job.artist = "Test Artist"
job.title = "Test Song"
job.user_email = "user@example.com"
job.status = JobStatus.COMPLETE
job.created_at = datetime(2026, 3, 1, tzinfo=timezone.utc)
job.updated_at = datetime(2026, 3, 2, tzinfo=timezone.utc)
job.input_media_gcs_path = "jobs/test-job/input/edited.flac"
job.state_data = {
"audio_edit_stack": [
{"edit_id": "e1", "operation": "cut", "gcs_path": "jobs/test-job/edits/e1.flac",
"duration_before": 225, "duration_after": 150, "timestamp": "2026-03-01T10:00:00"},
],
"original_input_media_gcs_path": "jobs/test-job/input/original.flac",
}
MockJobManager.return_value.get_job.return_value = job
storage = MockStorage.return_value
storage.file_exists.return_value = False
session = _make_session("test-job", trigger="submit")
MockFS.return_value.list_audio_edit_sessions.return_value = [session]
response = client.get("/api/admin/audio-edit-reviews/test-job")
assert response.status_code == 200
data = response.json()
assert data["job"]["job_id"] == "test-job"
assert data["job"]["artist"] == "Test Artist"
assert len(data["sessions"]) == 1
assert data["sessions"][0]["trigger"] == "submit"
assert len(data["edit_stack"]) == 1
assert data["edit_stack"][0]["operation"] == "cut"
@patch("backend.services.firestore_service.FirestoreService")
@patch("backend.api.routes.admin.StorageService")
@patch("backend.api.routes.admin.JobManager")
def test_handles_empty_state_gracefully(self, MockJobManager, MockStorage, MockFS, client):
"""Should handle jobs with no edit data gracefully."""
job = Mock(spec=Job)
job.job_id = "test-job"
job.artist = "Test"
job.title = "Song"
job.user_email = "u@e.com"
job.status = JobStatus.AWAITING_AUDIO_EDIT
job.created_at = None
job.updated_at = None
job.input_media_gcs_path = None
job.state_data = {}
MockJobManager.return_value.get_job.return_value = job
storage = MockStorage.return_value
storage.file_exists.return_value = False
MockFS.return_value.list_audio_edit_sessions.return_value = []
response = client.get("/api/admin/audio-edit-reviews/test-job")
assert response.status_code == 200
data = response.json()
assert data["sessions"] == []
assert data["edit_stack"] == []
assert data["edit_log"] is None
+100
View File
@@ -1016,3 +1016,103 @@ class TestResetEndpointWithRealJobData:
assert response.status_code == 200
assert response.json()["status"] == "success"
assert response.json()["new_status"] == "pending"
class TestResetJobToAwaitingAudioEdit:
"""Tests for resetting job to AWAITING_AUDIO_EDIT state."""
def test_reset_to_awaiting_audio_edit_success(self, client, mock_job):
"""Test resetting a job to awaiting_audio_edit."""
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
mock_jm = Mock()
mock_jm.get_job.return_value = mock_job
mock_jm.update_job.return_value = None
mock_jm_class.return_value = mock_jm
response = client.post(
"/api/admin/jobs/test-job-123/reset",
json={"target_state": "awaiting_audio_edit"},
)
assert response.status_code == 200
data = response.json()
assert data["new_status"] == "awaiting_audio_edit"
def test_reset_clears_edit_stack_and_downstream_flags(self, client):
"""Test that resetting clears audio edit state and downstream processing flags."""
from datetime import UTC
job = Job(
job_id="test-job-123",
status=JobStatus.COMPLETE,
artist="Test",
title="Song",
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
state_data={
"audio_edit_stack": [{"edit_id": "e1"}],
"audio_edit_redo_stack": [{"edit_id": "e2"}],
"audio_complete": True,
"lyrics_complete": True,
"review_complete": True,
"screens_progress": {"stage": "complete"},
}
)
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
mock_jm = Mock()
mock_jm.get_job.return_value = job
mock_jm.update_job.return_value = None
mock_jm_class.return_value = mock_jm
response = client.post(
"/api/admin/jobs/test-job-123/reset",
json={"target_state": "awaiting_audio_edit"},
)
assert response.status_code == 200
data = response.json()
cleared = data.get("cleared_data", [])
assert "audio_edit_stack" in cleared
assert "audio_edit_redo_stack" in cleared
assert "audio_complete" in cleared
assert "lyrics_complete" in cleared
assert "review_complete" in cleared
assert "screens_progress" in cleared
def test_reset_restores_original_input_media_path(self, client):
"""Critical test: resetting to audio edit must restore the original
input_media_gcs_path. The submit endpoint overwrites this with edited
audio, so the reset must undo that to let the user start fresh."""
from datetime import UTC
job = Job(
job_id="test-job-123",
status=JobStatus.COMPLETE,
artist="Test",
title="Song",
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
input_media_gcs_path="jobs/test-job-123/input/edited.flac",
state_data={
"original_input_media_gcs_path": "jobs/test-job-123/input/original.flac",
"audio_edit_stack": [{"edit_id": "e1"}],
}
)
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
mock_jm = Mock()
mock_jm.get_job.return_value = job
mock_jm.update_job.return_value = None
mock_jm_class.return_value = mock_jm
response = client.post(
"/api/admin/jobs/test-job-123/reset",
json={"target_state": "awaiting_audio_edit"},
)
assert response.status_code == 200
# Verify the Firestore update included restoring the original path
# The update goes through job_ref.update() which is the mock_db call
# We check the update_job call for status change
update_args = mock_jm.update_job.call_args[0][1]
assert update_args["status"] == "awaiting_audio_edit"
+757
View File
@@ -0,0 +1,757 @@
"""
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()
result = service.grant_welcome_credits_if_eligible("new@example.com")
assert result 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'] == 2
assert update_args['welcome_credits_granted'] is True
@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()
result = service.grant_welcome_credits_if_eligible("existing@example.com")
assert result 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()
result = service.grant_welcome_credits_if_eligible("existing@example.com")
assert result 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()
result = service.grant_welcome_credits_if_eligible("ghost@example.com")
assert result is False
# =============================================================================
# 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 = 2
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
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 = 2
# 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"] == 2
mock_user_svc.grant_welcome_credits_if_eligible.assert_called_once()
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()
result = service.grant_welcome_credits_if_eligible("test@example.com")
assert result 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,295 @@
"""
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
# =============================================================================
# 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"
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 = 2
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
@@ -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."""
+549
View File
@@ -0,0 +1,549 @@
"""
Tests for audio edit API endpoints in backend/api/routes/review.py.
Tests the 6 new endpoints: input-audio-info, apply, undo, redo, upload, submit.
"""
import pytest
from datetime import datetime, UTC
from unittest.mock import Mock, patch, MagicMock, AsyncMock
from backend.models.job import Job, JobStatus
from backend.services.audio_edit_service import AudioMetadata
NOW = datetime.now(UTC)
# Patch paths - these are imported inside endpoint functions
PATCH_JM = "backend.api.routes.review.JobManager"
PATCH_EDIT_SVC = "backend.services.audio_edit_service.AudioEditService"
PATCH_ANALYSIS_SVC = "backend.services.audio_analysis_service.AudioAnalysisService"
PATCH_TRANSCODE_SVC = "backend.services.audio_transcoding_service.AudioTranscodingService"
PATCH_STORAGE_SVC = "backend.api.routes.review.StorageService"
PATCH_WORKER_SVC = "backend.services.worker_service.get_worker_service"
def _job(**kwargs):
"""Create a Job with required fields filled in."""
defaults = dict(created_at=NOW, updated_at=NOW)
defaults.update(kwargs)
return Job(**defaults)
# --- Fixtures ---
@pytest.fixture(autouse=True)
def _ensure_auth_overrides():
"""Ensure auth overrides are set for every test, even when conftest autouse is fragile."""
from backend.api.dependencies import require_auth, require_admin, require_review_auth
from backend.services.auth_service import UserType, AuthResult
from backend.main import app
async def mock_require_review_auth(job_id: str = "test123"):
return (job_id, "full")
async def mock_require_auth():
return AuthResult(is_valid=True, user_type=UserType.ADMIN, remaining_uses=999,
message="Test", is_admin=True, user_email="test@example.com")
app.dependency_overrides[require_review_auth] = mock_require_review_auth
app.dependency_overrides[require_auth] = mock_require_auth
app.dependency_overrides[require_admin] = mock_require_auth
yield
app.dependency_overrides.pop(require_review_auth, None)
app.dependency_overrides.pop(require_auth, None)
app.dependency_overrides.pop(require_admin, None)
@pytest.fixture
def mock_job_manager():
with patch(PATCH_JM) as MockJM:
jm = Mock()
MockJM.return_value = jm
yield jm
@pytest.fixture
def mock_services():
"""Mock all service dependencies used by audio edit endpoints."""
with patch(PATCH_EDIT_SVC) as MockES, \
patch(PATCH_ANALYSIS_SVC) as MockAS, \
patch(PATCH_TRANSCODE_SVC) as MockTS:
es = Mock()
MockES.return_value = es
# Default metadata for duration_before lookups
es.get_metadata_from_gcs.return_value = AudioMetadata(
duration_seconds=200.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=30000000,
)
as_inst = Mock()
MockAS.return_value = as_inst
as_inst.get_waveform_data.return_value = ([0.1, 0.5, 0.3], 200.0)
ts = Mock()
MockTS.return_value = ts
ts.get_review_audio_url.return_value = "https://example.com/audio.ogg"
yield {"edit": es, "analysis": as_inst, "transcode": ts}
@pytest.fixture
def audio_edit_job():
"""Job in awaiting_audio_edit state with input media."""
return _job(
job_id="edit-job-1",
status=JobStatus.AWAITING_AUDIO_EDIT,
progress=15,
input_media_gcs_path="jobs/edit-job-1/input/song.flac",
state_data={},
)
@pytest.fixture
def audio_edit_job_with_edits():
"""Job in in_audio_edit state with existing edit stack."""
return _job(
job_id="edit-job-2",
status=JobStatus.IN_AUDIO_EDIT,
progress=15,
input_media_gcs_path="jobs/edit-job-2/input/song.flac",
state_data={
"audio_edit_stack": [
{
"edit_id": "aaa",
"operation": "trim_start",
"params": {"end_seconds": 10.0},
"gcs_path": "jobs/edit-job-2/audio_edit/edit_aaa.flac",
"duration_seconds": 190.0,
"timestamp": "2026-03-08T12:00:00",
}
],
"audio_edit_redo_stack": [],
},
)
# --- GET /input-audio-info ---
class TestGetInputAudioInfo:
def test_returns_audio_info(self, test_client, mock_job_manager, mock_services, audio_edit_job):
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
data = resp.json()
assert data["job_id"] == "edit-job-1"
assert data["original_duration_seconds"] > 0
assert data["current_duration_seconds"] > 0
assert data["original_audio_url"] == "https://example.com/audio.ogg"
assert data["current_audio_url"] == "https://example.com/audio.ogg"
assert data["edit_stack"] == []
assert data["can_undo"] is False
assert "waveform_data" in data
assert "original_waveform_data" in data
def test_returns_edited_audio_when_edits_exist(self, test_client, mock_job_manager, mock_services, audio_edit_job_with_edits):
mock_job_manager.get_job.return_value = audio_edit_job_with_edits
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-2/input-audio-info")
assert resp.status_code == 200
data = resp.json()
assert len(data["edit_stack"]) == 1
assert data["can_undo"] is True
assert data["edit_stack"][0]["edit_id"] == "aaa"
assert data["edit_stack"][0]["operation"] == "trim_start"
def test_404_when_job_not_found(self, test_client, mock_job_manager):
mock_job_manager.get_job.return_value = None
resp = test_client.get("/api/review/nonexistent/input-audio-info")
assert resp.status_code == 404
def test_404_when_no_input_audio(self, test_client, mock_job_manager):
job = _job(job_id="no-audio", status=JobStatus.AWAITING_AUDIO_EDIT,
input_media_gcs_path=None, state_data={})
mock_job_manager.get_job.return_value = job
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 ---
class TestApplyAudioEdit:
def test_apply_trim_start(self, test_client, mock_job_manager, mock_services, audio_edit_job):
mock_job_manager.get_job.return_value = audio_edit_job
mock_services["edit"].apply_edit.return_value = (
AudioMetadata(duration_seconds=170.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=25000000),
"jobs/edit-job-1/audio_edit/edit_abc.flac",
)
resp = test_client.post("/api/review/edit-job-1/audio-edit/apply", json={
"operation": "trim_start",
"params": {"end_seconds": 30.0},
"edit_id": "abc",
})
assert resp.status_code == 200
data = resp.json()
assert data["status"] == "success"
assert data["edit_id"] == "abc"
assert data["can_undo"] is True
assert len(data["edit_stack"]) == 1
assert data["edit_stack"][0]["operation"] == "trim_start"
assert "current_audio_url" in data
assert "waveform_data" in data
assert "duration_after" in data
# Should transition to IN_AUDIO_EDIT
mock_job_manager.transition_to_state.assert_called_once()
def test_apply_transitions_to_in_audio_edit(self, test_client, mock_job_manager, mock_services, audio_edit_job):
mock_job_manager.get_job.return_value = audio_edit_job
mock_services["edit"].apply_edit.return_value = (
AudioMetadata(duration_seconds=170.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=25000000),
"jobs/edit-job-1/audio_edit/edit_abc.flac",
)
test_client.post("/api/review/edit-job-1/audio-edit/apply", json={
"operation": "trim_start",
"params": {"end_seconds": 30.0},
})
mock_job_manager.transition_to_state.assert_called_once_with(
job_id="edit-job-1",
new_status=JobStatus.IN_AUDIO_EDIT,
progress=15,
message="Audio editing in progress",
)
def test_apply_skips_transition_if_already_in_edit(self, test_client, mock_job_manager, mock_services, audio_edit_job_with_edits):
mock_job_manager.get_job.return_value = audio_edit_job_with_edits
mock_services["edit"].apply_edit.return_value = (
AudioMetadata(duration_seconds=170.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=25000000),
"jobs/edit-job-2/audio_edit/edit_xyz.flac",
)
test_client.post("/api/review/edit-job-2/audio-edit/apply", json={
"operation": "mute",
"params": {"start_seconds": 10.0, "end_seconds": 15.0},
})
mock_job_manager.transition_to_state.assert_not_called()
def test_apply_missing_operation(self, test_client, mock_job_manager, audio_edit_job):
mock_job_manager.get_job.return_value = audio_edit_job
resp = test_client.post("/api/review/edit-job-1/audio-edit/apply", json={
"params": {"end_seconds": 30.0},
})
assert resp.status_code == 400
assert "operation" in resp.json()["detail"].lower()
def test_apply_invalid_operation(self, test_client, mock_job_manager, audio_edit_job):
mock_job_manager.get_job.return_value = audio_edit_job
resp = test_client.post("/api/review/edit-job-1/audio-edit/apply", json={
"operation": "reverse",
"params": {},
})
assert resp.status_code == 400
assert "Invalid operation" in resp.json()["detail"]
def test_apply_wrong_status(self, test_client, mock_job_manager):
job = _job(job_id="wrong-status", status=JobStatus.COMPLETE,
input_media_gcs_path="jobs/x/input/song.flac", state_data={})
mock_job_manager.get_job.return_value = job
resp = test_client.post("/api/review/wrong-status/audio-edit/apply", json={
"operation": "trim_start",
"params": {"end_seconds": 10.0},
})
assert resp.status_code == 400
assert "not in audio edit state" in resp.json()["detail"]
def test_apply_join_requires_upload_id(self, test_client, mock_job_manager, audio_edit_job):
mock_job_manager.get_job.return_value = audio_edit_job
resp = test_client.post("/api/review/edit-job-1/audio-edit/apply", json={
"operation": "join_end",
"params": {},
})
assert resp.status_code == 400
assert "upload_id" in resp.json()["detail"].lower()
def test_apply_join_invalid_upload_id(self, test_client, mock_job_manager, audio_edit_job):
mock_job_manager.get_job.return_value = audio_edit_job
resp = test_client.post("/api/review/edit-job-1/audio-edit/apply", json={
"operation": "join_end",
"params": {"upload_id": "nonexistent"},
})
assert resp.status_code == 404
assert "not found" in resp.json()["detail"].lower()
def test_apply_clears_redo_stack(self, test_client, mock_job_manager, mock_services):
"""When applying a new edit, the redo stack should be cleared."""
job = _job(
job_id="redo-clear",
status=JobStatus.IN_AUDIO_EDIT,
input_media_gcs_path="jobs/redo-clear/input/song.flac",
state_data={
"audio_edit_stack": [],
"audio_edit_redo_stack": [{"edit_id": "old", "gcs_path": "old.flac"}],
},
)
mock_job_manager.get_job.return_value = job
mock_services["edit"].apply_edit.return_value = (
AudioMetadata(duration_seconds=180.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=25000000),
"jobs/redo-clear/audio_edit/edit_new.flac",
)
resp = test_client.post("/api/review/redo-clear/audio-edit/apply", json={
"operation": "mute",
"params": {"start_seconds": 5.0, "end_seconds": 10.0},
})
assert resp.status_code == 200
data = resp.json()
assert data["can_redo"] is False
# --- POST /audio-edit/undo ---
class TestUndoAudioEdit:
def test_undo_pops_edit_stack(self, test_client, mock_job_manager, mock_services, audio_edit_job_with_edits):
mock_job_manager.get_job.return_value = audio_edit_job_with_edits
resp = test_client.post("/api/review/edit-job-2/audio-edit/undo")
assert resp.status_code == 200
data = resp.json()
assert len(data["edit_stack"]) == 0
assert data["can_undo"] is False
assert data["can_redo"] is True
# Verify state_data was updated
update_call = mock_job_manager.update_job.call_args[0]
state_data = update_call[1]["state_data"]
assert len(state_data["audio_edit_stack"]) == 0
assert len(state_data["audio_edit_redo_stack"]) == 1
def test_undo_nothing_to_undo(self, test_client, mock_job_manager, audio_edit_job):
mock_job_manager.get_job.return_value = audio_edit_job
resp = test_client.post("/api/review/edit-job-1/audio-edit/undo")
assert resp.status_code == 400
assert "Nothing to undo" in resp.json()["detail"]
def test_undo_wrong_status(self, test_client, mock_job_manager):
job = _job(job_id="done", status=JobStatus.COMPLETE, state_data={})
mock_job_manager.get_job.return_value = job
resp = test_client.post("/api/review/done/audio-edit/undo")
assert resp.status_code == 400
# --- POST /audio-edit/redo ---
class TestRedoAudioEdit:
def test_redo_pops_redo_stack(self, test_client, mock_job_manager, mock_services):
job = _job(
job_id="redo-job",
status=JobStatus.IN_AUDIO_EDIT,
input_media_gcs_path="jobs/redo-job/input/song.flac",
state_data={
"audio_edit_stack": [],
"audio_edit_redo_stack": [
{
"edit_id": "bbb",
"operation": "trim_end",
"params": {"end_seconds": 180.0},
"gcs_path": "jobs/redo-job/audio_edit/edit_bbb.flac",
"duration_seconds": 180.0,
}
],
},
)
mock_job_manager.get_job.return_value = job
resp = test_client.post("/api/review/redo-job/audio-edit/redo")
assert resp.status_code == 200
data = resp.json()
assert len(data["edit_stack"]) == 1
assert data["can_undo"] is True
assert data["can_redo"] is False
def test_redo_nothing_to_redo(self, test_client, mock_job_manager, audio_edit_job_with_edits):
mock_job_manager.get_job.return_value = audio_edit_job_with_edits
resp = test_client.post("/api/review/edit-job-2/audio-edit/redo")
assert resp.status_code == 400
assert "Nothing to redo" in resp.json()["detail"]
# --- POST /audio-edit/submit ---
class TestSubmitAudioEdit:
def test_submit_with_edits_copies_audio(self, test_client, mock_job_manager, audio_edit_job_with_edits):
mock_job_manager.get_job.return_value = audio_edit_job_with_edits
with patch(PATCH_STORAGE_SVC) as MockStorage, \
patch(PATCH_WORKER_SVC) as mock_get_ws:
mock_ws = AsyncMock()
mock_get_ws.return_value = mock_ws
resp = test_client.post("/api/review/edit-job-2/audio-edit/submit",
json={})
assert resp.status_code == 200
data = resp.json()
assert data["status"] == "success"
assert data["edits_applied"] == 1
# Should copy edited audio to canonical path
storage_inst = MockStorage.return_value
storage_inst.download_file.assert_called_once()
storage_inst.upload_file.assert_called_once()
# Should update input_media_gcs_path
update_call = mock_job_manager.update_job.call_args[0]
assert update_call[1]["input_media_gcs_path"] == "jobs/edit-job-2/input/edited.flac"
# Should transition to AUDIO_EDIT_COMPLETE
mock_job_manager.transition_to_state.assert_called_once_with(
job_id="edit-job-2",
new_status=JobStatus.AUDIO_EDIT_COMPLETE,
progress=18,
message="Audio edit complete, starting processing",
)
def test_submit_without_edits_uses_original(self, test_client, mock_job_manager, audio_edit_job):
mock_job_manager.get_job.return_value = audio_edit_job
with patch(PATCH_STORAGE_SVC) as MockStorage, \
patch(PATCH_WORKER_SVC) as mock_get_ws:
mock_ws = AsyncMock()
mock_get_ws.return_value = mock_ws
resp = test_client.post("/api/review/edit-job-1/audio-edit/submit",
json={})
assert resp.status_code == 200
data = resp.json()
assert data["edits_applied"] == 0
# Should NOT copy any files
MockStorage.return_value.download_file.assert_not_called()
# Should NOT update input_media_gcs_path
mock_job_manager.update_job.assert_not_called()
def test_submit_wrong_status(self, test_client, mock_job_manager):
job = _job(job_id="done", status=JobStatus.COMPLETE, state_data={})
mock_job_manager.get_job.return_value = job
resp = test_client.post("/api/review/done/audio-edit/submit", json={})
assert resp.status_code == 400
def test_submit_job_not_found(self, test_client, mock_job_manager):
mock_job_manager.get_job.return_value = None
resp = test_client.post("/api/review/nonexistent/audio-edit/submit", json={})
assert resp.status_code == 404
# --- Helper function tests ---
class TestHelperFunctions:
def test_get_current_audio_gcs_path_no_edits(self):
from backend.api.routes.review import _get_current_audio_gcs_path
job = _job(
job_id="test",
status=JobStatus.AWAITING_AUDIO_EDIT,
input_media_gcs_path="jobs/test/input/song.flac",
state_data={},
)
assert _get_current_audio_gcs_path(job) == "jobs/test/input/song.flac"
def test_get_current_audio_gcs_path_with_edits(self):
from backend.api.routes.review import _get_current_audio_gcs_path
job = _job(
job_id="test",
status=JobStatus.IN_AUDIO_EDIT,
input_media_gcs_path="jobs/test/input/song.flac",
state_data={
"audio_edit_stack": [
{"gcs_path": "jobs/test/audio_edit/edit_1.flac"},
{"gcs_path": "jobs/test/audio_edit/edit_2.flac"},
],
},
)
assert _get_current_audio_gcs_path(job) == "jobs/test/audio_edit/edit_2.flac"
def test_get_current_audio_gcs_path_empty_state_data(self):
from backend.api.routes.review import _get_current_audio_gcs_path
job = _job(
job_id="test",
status=JobStatus.AWAITING_AUDIO_EDIT,
input_media_gcs_path="jobs/test/input/song.flac",
state_data={},
)
assert _get_current_audio_gcs_path(job) == "jobs/test/input/song.flac"
+320
View File
@@ -0,0 +1,320 @@
"""
Tests for audio_edit_service.py — server-side FFmpeg audio editing.
Tests use mocked subprocess calls since we can't guarantee ffmpeg is
available in CI. Integration tests with real audio files are in a
separate test module.
"""
import json
import os
import pytest
from unittest.mock import Mock, patch, MagicMock, call
from backend.services.audio_edit_service import AudioEditService, AudioMetadata
class TestGetMetadata:
"""Test get_metadata and get_metadata_from_gcs."""
@patch("backend.services.audio_edit_service.subprocess.run")
def test_get_metadata_parses_ffprobe(self, mock_run):
mock_run.return_value = MagicMock(
returncode=0,
stdout=json.dumps({
"format": {
"duration": "245.3",
"format_name": "flac",
"size": "35000000",
},
"streams": [{
"codec_type": "audio",
"sample_rate": "44100",
"channels": 2,
}],
}),
)
service = AudioEditService(storage_service=Mock())
meta = service.get_metadata("/tmp/test.flac")
assert meta.duration_seconds == 245.3
assert meta.sample_rate == 44100
assert meta.channels == 2
assert meta.format == "flac"
assert meta.file_size_bytes == 35000000
@patch("backend.services.audio_edit_service.subprocess.run")
def test_get_metadata_ffprobe_failure(self, mock_run):
mock_run.return_value = MagicMock(
returncode=1,
stderr="ffprobe error",
)
service = AudioEditService(storage_service=Mock())
with pytest.raises(RuntimeError, match="ffprobe failed"):
service.get_metadata("/tmp/test.flac")
@patch("backend.services.audio_edit_service.subprocess.run")
@patch("backend.services.audio_edit_service.tempfile.TemporaryDirectory")
def test_get_metadata_from_gcs(self, mock_tmpdir, mock_run):
mock_tmpdir.return_value.__enter__ = Mock(return_value="/tmp/test")
mock_tmpdir.return_value.__exit__ = Mock(return_value=False)
mock_run.return_value = MagicMock(
returncode=0,
stdout=json.dumps({
"format": {"duration": "100.0", "format_name": "flac", "size": "1000"},
"streams": [{"codec_type": "audio", "sample_rate": "44100", "channels": 2}],
}),
)
mock_storage = Mock()
service = AudioEditService(storage_service=mock_storage)
meta = service.get_metadata_from_gcs("jobs/123/input/song.flac")
mock_storage.download_file.assert_called_once()
assert meta.duration_seconds == 100.0
class TestFFmpegOperations:
"""Test trim, cut, mute, join operations via FFmpeg."""
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
@patch("backend.services.audio_edit_service.subprocess.run")
def test_trim_start(self, mock_run, mock_meta):
mock_run.return_value = MagicMock(returncode=0)
mock_meta.return_value = AudioMetadata(
duration_seconds=200.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=30000000,
)
service = AudioEditService(storage_service=Mock())
result = service.trim_start("/tmp/input.flac", 30.0, "/tmp/output.flac")
# Check ffmpeg was called with -ss
cmd = mock_run.call_args[0][0]
assert "-ss" in cmd
assert "30.0" in cmd
assert result.duration_seconds == 200.0
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
@patch("backend.services.audio_edit_service.subprocess.run")
def test_trim_end(self, mock_run, mock_meta):
mock_run.return_value = MagicMock(returncode=0)
mock_meta.return_value = AudioMetadata(
duration_seconds=120.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=20000000,
)
service = AudioEditService(storage_service=Mock())
result = service.trim_end("/tmp/input.flac", 120.0, "/tmp/output.flac")
cmd = mock_run.call_args[0][0]
assert "-t" in cmd
assert "120.0" in cmd
assert result.duration_seconds == 120.0
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
@patch("backend.services.audio_edit_service.subprocess.run")
def test_cut_region(self, mock_run, mock_meta):
mock_run.return_value = MagicMock(returncode=0)
mock_meta.return_value = AudioMetadata(
duration_seconds=180.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=25000000,
)
service = AudioEditService(storage_service=Mock())
result = service.cut_region("/tmp/input.flac", 30.0, 45.0, "/tmp/output.flac")
cmd = mock_run.call_args[0][0]
assert "-filter_complex" in cmd
filter_str = cmd[cmd.index("-filter_complex") + 1]
assert "atrim=0:30.0" in filter_str
assert "atrim=45.0" in filter_str
assert "concat=n=2" in filter_str
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
@patch("backend.services.audio_edit_service.subprocess.run")
def test_mute_region(self, mock_run, mock_meta):
mock_run.return_value = MagicMock(returncode=0)
mock_meta.return_value = AudioMetadata(
duration_seconds=245.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=35000000,
)
service = AudioEditService(storage_service=Mock())
result = service.mute_region("/tmp/input.flac", 10.0, 15.0, "/tmp/output.flac")
cmd = mock_run.call_args[0][0]
assert "-af" in cmd
af_str = cmd[cmd.index("-af") + 1]
assert "volume=enable='between(t,10.0,15.0)':volume=0" in af_str
assert result.duration_seconds == 245.0 # Duration preserved
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
@patch("backend.services.audio_edit_service.subprocess.run")
def test_join_audio_end(self, mock_run, mock_meta):
mock_run.return_value = MagicMock(returncode=0)
mock_meta.return_value = AudioMetadata(
duration_seconds=260.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=40000000,
)
service = AudioEditService(storage_service=Mock())
result = service.join_audio("/tmp/main.flac", "/tmp/extra.flac", "end", "/tmp/output.flac")
cmd = mock_run.call_args[0][0]
assert "-filter_complex" in cmd
# For "end", main comes first, extra second
assert cmd[cmd.index("-i") + 1] == "/tmp/main.flac"
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
@patch("backend.services.audio_edit_service.subprocess.run")
def test_join_audio_start(self, mock_run, mock_meta):
mock_run.return_value = MagicMock(returncode=0)
mock_meta.return_value = AudioMetadata(
duration_seconds=260.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=40000000,
)
service = AudioEditService(storage_service=Mock())
result = service.join_audio("/tmp/main.flac", "/tmp/extra.flac", "start", "/tmp/output.flac")
cmd = mock_run.call_args[0][0]
# For "start", extra comes first, main second
first_input_idx = cmd.index("-i") + 1
assert cmd[first_input_idx] == "/tmp/extra.flac"
@patch("backend.services.audio_edit_service.subprocess.run")
def test_ffmpeg_failure_raises(self, mock_run):
mock_run.return_value = MagicMock(
returncode=1,
stderr="Error: something went wrong",
)
service = AudioEditService(storage_service=Mock())
with pytest.raises(RuntimeError, match="ffmpeg failed"):
service.trim_start("/tmp/input.flac", 30.0, "/tmp/output.flac")
class TestApplyEdit:
"""Test the apply_edit method that orchestrates download/edit/upload."""
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
@patch("backend.services.audio_edit_service.subprocess.run")
@patch("backend.services.audio_edit_service.tempfile.TemporaryDirectory")
def test_apply_edit_trim_start(self, mock_tmpdir, mock_run, mock_meta):
mock_tmpdir.return_value.__enter__ = Mock(return_value="/tmp/edit")
mock_tmpdir.return_value.__exit__ = Mock(return_value=False)
mock_run.return_value = MagicMock(returncode=0)
mock_meta.return_value = AudioMetadata(
duration_seconds=200.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=30000000,
)
mock_storage = Mock()
service = AudioEditService(storage_service=mock_storage)
metadata, result_path = service.apply_edit(
input_gcs_path="jobs/123/input/song.flac",
operation="trim_start",
params={"end_seconds": 30.0},
output_gcs_path="jobs/123/audio_edit/edit_abc.flac",
job_id="123",
)
mock_storage.download_file.assert_called_once()
mock_storage.upload_file.assert_called_once()
assert result_path == "jobs/123/audio_edit/edit_abc.flac"
assert metadata.duration_seconds == 200.0
@patch("backend.services.audio_edit_service.AudioEditService.get_metadata")
@patch("backend.services.audio_edit_service.subprocess.run")
@patch("backend.services.audio_edit_service.tempfile.TemporaryDirectory")
def test_apply_edit_join_downloads_both_files(self, mock_tmpdir, mock_run, mock_meta):
mock_tmpdir.return_value.__enter__ = Mock(return_value="/tmp/edit")
mock_tmpdir.return_value.__exit__ = Mock(return_value=False)
mock_run.return_value = MagicMock(returncode=0)
mock_meta.return_value = AudioMetadata(
duration_seconds=260.0, sample_rate=44100, channels=2,
format="flac", file_size_bytes=40000000,
)
mock_storage = Mock()
service = AudioEditService(storage_service=mock_storage)
metadata, result_path = service.apply_edit(
input_gcs_path="jobs/123/input/song.flac",
operation="join_end",
params={"upload_gcs_path": "jobs/123/audio_edit/upload_xyz.flac"},
output_gcs_path="jobs/123/audio_edit/edit_abc.flac",
job_id="123",
)
# Should download both the main audio and the upload
assert mock_storage.download_file.call_count == 2
@patch("backend.services.audio_edit_service.tempfile.TemporaryDirectory")
def test_apply_edit_unknown_operation(self, mock_tmpdir):
mock_tmpdir.return_value.__enter__ = Mock(return_value="/tmp/edit")
mock_tmpdir.return_value.__exit__ = Mock(return_value=False)
mock_storage = Mock()
service = AudioEditService(storage_service=mock_storage)
with pytest.raises(ValueError, match="Unknown operation"):
service.apply_edit(
input_gcs_path="jobs/123/input/song.flac",
operation="reverse",
params={},
output_gcs_path="jobs/123/audio_edit/edit_abc.flac",
job_id="123",
)
class TestStateTransitions:
"""Test that new job states and transitions are correctly defined."""
def test_new_states_exist(self):
from backend.models.job import JobStatus
assert hasattr(JobStatus, 'AWAITING_AUDIO_EDIT')
assert hasattr(JobStatus, 'IN_AUDIO_EDIT')
assert hasattr(JobStatus, 'AUDIO_EDIT_COMPLETE')
assert JobStatus.AWAITING_AUDIO_EDIT.value == "awaiting_audio_edit"
assert JobStatus.IN_AUDIO_EDIT.value == "in_audio_edit"
assert JobStatus.AUDIO_EDIT_COMPLETE.value == "audio_edit_complete"
def test_downloading_can_transition_to_awaiting_audio_edit(self):
from backend.models.job import JobStatus, STATE_TRANSITIONS
allowed = STATE_TRANSITIONS[JobStatus.DOWNLOADING]
assert JobStatus.AWAITING_AUDIO_EDIT in allowed
def test_awaiting_audio_edit_transitions(self):
from backend.models.job import JobStatus, STATE_TRANSITIONS
allowed = STATE_TRANSITIONS[JobStatus.AWAITING_AUDIO_EDIT]
assert JobStatus.IN_AUDIO_EDIT in allowed
assert JobStatus.AUDIO_EDIT_COMPLETE in allowed
assert JobStatus.FAILED in allowed
assert JobStatus.CANCELLED in allowed
def test_in_audio_edit_transitions(self):
from backend.models.job import JobStatus, STATE_TRANSITIONS
allowed = STATE_TRANSITIONS[JobStatus.IN_AUDIO_EDIT]
assert JobStatus.AWAITING_AUDIO_EDIT in allowed
assert JobStatus.AUDIO_EDIT_COMPLETE in allowed
assert JobStatus.FAILED in allowed
assert JobStatus.CANCELLED in allowed
def test_audio_edit_complete_continues_to_processing(self):
from backend.models.job import JobStatus, STATE_TRANSITIONS
allowed = STATE_TRANSITIONS[JobStatus.AUDIO_EDIT_COMPLETE]
assert JobStatus.SEPARATING_STAGE1 in allowed
assert JobStatus.TRANSCRIBING in allowed
assert JobStatus.GENERATING_SCREENS in allowed
assert JobStatus.FAILED in allowed
+258
View File
@@ -0,0 +1,258 @@
"""
Tests for audio edit session persistence (Phase 2).
Tests the model, API endpoints, and deduplication logic.
"""
import hashlib
import json
import pytest
from datetime import datetime, UTC, timezone
from unittest.mock import Mock, patch, MagicMock
from backend.models.audio_edit_session import AudioEditSession, AudioEditSessionSummary
from backend.models.job import Job, JobStatus
NOW = datetime.now(UTC)
PATCH_JM = "backend.api.routes.review.JobManager"
PATCH_FS = "backend.api.routes.review.FirestoreService"
PATCH_STORAGE = "backend.api.routes.review.StorageService"
def _job(**kwargs):
defaults = dict(created_at=NOW, updated_at=NOW)
defaults.update(kwargs)
return Job(**defaults)
# --- Model Tests ---
class TestAudioEditSessionModel:
def test_to_dict_and_from_dict_roundtrip(self):
summary = AudioEditSessionSummary(
total_operations=3,
operations_breakdown={"trim_start": 1, "mute": 2},
duration_change_seconds=-15.5,
net_duration_seconds=184.5,
)
session = AudioEditSession(
session_id="test-id",
job_id="job-1",
user_email="user@example.com",
edit_count=3,
trigger="manual",
audio_duration_seconds=184.5,
original_duration_seconds=200.0,
artist="Test Artist",
title="Test Song",
summary=summary,
edit_data_gcs_path="jobs/job-1/audio_edit_sessions/test-id.json",
data_hash="abc123",
)
d = session.to_dict()
restored = AudioEditSession.from_dict(d)
assert restored.session_id == "test-id"
assert restored.job_id == "job-1"
assert restored.edit_count == 3
assert restored.trigger == "manual"
assert restored.audio_duration_seconds == 184.5
assert restored.original_duration_seconds == 200.0
assert restored.artist == "Test Artist"
assert restored.summary.total_operations == 3
assert restored.summary.operations_breakdown == {"trim_start": 1, "mute": 2}
assert restored.data_hash == "abc123"
def test_from_dict_with_string_datetimes(self):
data = {
"session_id": "sid",
"created_at": "2026-03-08T12:00:00",
"updated_at": "2026-03-08T12:30:00",
}
session = AudioEditSession.from_dict(data)
assert session.created_at.year == 2026
assert session.updated_at.minute == 30
def test_from_dict_defaults(self):
session = AudioEditSession.from_dict({})
assert session.edit_count == 0
assert session.trigger == "auto"
assert session.summary.total_operations == 0
def test_summary_to_dict_and_from_dict(self):
s = AudioEditSessionSummary(total_operations=5, operations_breakdown={"cut": 5})
d = s.to_dict()
restored = AudioEditSessionSummary.from_dict(d)
assert restored.total_operations == 5
assert restored.operations_breakdown == {"cut": 5}
# --- API Endpoint Tests ---
@pytest.fixture(autouse=True)
def _ensure_auth_overrides():
"""Ensure auth overrides are set for every test."""
from backend.api.dependencies import require_auth, require_admin, require_review_auth
from backend.services.auth_service import UserType, AuthResult
from backend.main import app
async def mock_require_review_auth(job_id: str = "test123"):
return (job_id, "full")
async def mock_require_auth():
return AuthResult(is_valid=True, user_type=UserType.ADMIN, remaining_uses=999,
message="Test", is_admin=True, user_email="test@example.com")
app.dependency_overrides[require_review_auth] = mock_require_review_auth
app.dependency_overrides[require_auth] = mock_require_auth
app.dependency_overrides[require_admin] = mock_require_auth
yield
app.dependency_overrides.pop(require_review_auth, None)
app.dependency_overrides.pop(require_auth, None)
app.dependency_overrides.pop(require_admin, None)
@pytest.fixture
def mock_job_manager():
with patch(PATCH_JM) as MockJM:
jm = Mock()
MockJM.return_value = jm
yield jm
@pytest.fixture
def mock_firestore_svc():
with patch(PATCH_FS) as MockFS:
fs = Mock()
MockFS.return_value = fs
yield fs
@pytest.fixture
def mock_storage_svc():
with patch(PATCH_STORAGE) as MockS:
s = Mock()
MockS.return_value = s
yield s
class TestSaveAudioEditSession:
def test_save_new_session(self, test_client, mock_job_manager, mock_firestore_svc, mock_storage_svc):
job = _job(job_id="j1", status=JobStatus.IN_AUDIO_EDIT,
artist="Artist", title="Song", state_data={})
mock_job_manager.get_job.return_value = job
mock_firestore_svc.get_latest_audio_edit_session_hash.return_value = None
edit_data = {"entries": [{"operation": "trim_start", "params": {"end_seconds": 30}}]}
resp = test_client.post("/api/review/j1/audio-edit-sessions", json={
"edit_data": edit_data,
"edit_count": 1,
"trigger": "auto",
"summary": {
"total_operations": 1,
"operations_breakdown": {"trim_start": 1},
"duration_change_seconds": -30.0,
"net_duration_seconds": 170.0,
},
})
assert resp.status_code == 200
data = resp.json()
assert data["status"] == "saved"
assert "session_id" in data
# Should upload to GCS and save to Firestore
mock_storage_svc.upload_json.assert_called_once()
mock_firestore_svc.save_audio_edit_session.assert_called_once()
def test_skip_duplicate_session(self, test_client, mock_job_manager, mock_firestore_svc):
job = _job(job_id="j2", status=JobStatus.IN_AUDIO_EDIT, state_data={})
mock_job_manager.get_job.return_value = job
edit_data = {"entries": []}
data_json = json.dumps(edit_data, sort_keys=True, default=str)
existing_hash = hashlib.sha256(data_json.encode()).hexdigest()
mock_firestore_svc.get_latest_audio_edit_session_hash.return_value = existing_hash
resp = test_client.post("/api/review/j2/audio-edit-sessions", json={
"edit_data": edit_data,
"edit_count": 0,
})
assert resp.status_code == 200
data = resp.json()
assert data["status"] == "skipped"
assert data["reason"] == "identical_data"
def test_save_job_not_found(self, test_client, mock_job_manager):
mock_job_manager.get_job.return_value = None
resp = test_client.post("/api/review/missing/audio-edit-sessions", json={
"edit_data": {},
})
assert resp.status_code == 404
class TestListAudioEditSessions:
def test_list_sessions(self, test_client, mock_firestore_svc):
session = AudioEditSession(
session_id="s1", job_id="j1", edit_count=2,
summary=AudioEditSessionSummary(total_operations=2),
)
mock_firestore_svc.list_audio_edit_sessions.return_value = [session]
resp = test_client.get("/api/review/j1/audio-edit-sessions")
assert resp.status_code == 200
data = resp.json()
assert len(data["sessions"]) == 1
assert data["sessions"][0]["session_id"] == "s1"
def test_list_empty(self, test_client, mock_firestore_svc):
mock_firestore_svc.list_audio_edit_sessions.return_value = []
resp = test_client.get("/api/review/j1/audio-edit-sessions")
assert resp.status_code == 200
assert len(resp.json()["sessions"]) == 0
class TestGetAudioEditSession:
def test_get_with_gcs_data(self, test_client, mock_firestore_svc, mock_storage_svc):
session = AudioEditSession(
session_id="s1", job_id="j1",
edit_data_gcs_path="jobs/j1/audio_edit_sessions/s1.json",
)
mock_firestore_svc.get_audio_edit_session.return_value = session
mock_storage_svc.download_json.return_value = {"entries": [{"op": "trim"}]}
resp = test_client.get("/api/review/j1/audio-edit-sessions/s1")
assert resp.status_code == 200
data = resp.json()
assert data["session_id"] == "s1"
assert data["edit_data"] == {"entries": [{"op": "trim"}]}
def test_get_not_found(self, test_client, mock_firestore_svc):
mock_firestore_svc.get_audio_edit_session.return_value = None
resp = test_client.get("/api/review/j1/audio-edit-sessions/missing")
assert resp.status_code == 404
class TestDeleteAudioEditSession:
def test_delete_session(self, test_client, mock_firestore_svc, mock_storage_svc):
session = AudioEditSession(
session_id="s1", job_id="j1",
edit_data_gcs_path="jobs/j1/audio_edit_sessions/s1.json",
)
mock_firestore_svc.get_audio_edit_session.return_value = session
resp = test_client.delete("/api/review/j1/audio-edit-sessions/s1")
assert resp.status_code == 200
assert resp.json()["status"] == "deleted"
mock_storage_svc.delete_file.assert_called_once_with("jobs/j1/audio_edit_sessions/s1.json")
mock_firestore_svc.delete_audio_edit_session.assert_called_once_with("j1", "s1")
def test_delete_not_found(self, test_client, mock_firestore_svc):
mock_firestore_svc.get_audio_edit_session.return_value = None
resp = test_client.delete("/api/review/j1/audio-edit-sessions/missing")
assert resp.status_code == 404
@@ -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"
+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,
)
+6 -1
View File
@@ -163,6 +163,7 @@ class TestChangeToPublic:
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock), \
patch("backend.services.visibility_change_service.StorageService") as mock_storage_cls, \
patch("backend.api.routes.file_upload._prepare_theme_for_job", return_value=("jobs/test-123/style/style_params.json", {"bg": "bg.png"}, None)) as mock_theme, \
patch("backend.services.worker_service.get_worker_service") as mock_worker_svc:
mock_storage = MagicMock()
@@ -176,6 +177,7 @@ class TestChangeToPublic:
assert result["status"] == "processing"
assert result["reprocessing_required"] is True
mock_worker.trigger_screens_worker.assert_called_once_with("test-123")
mock_theme.assert_called_once_with(job_id="test-123", theme_id="nomad")
@pytest.mark.asyncio
async def test_resets_styles_to_nomad_theme(self):
@@ -188,6 +190,7 @@ class TestChangeToPublic:
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock), \
patch("backend.services.visibility_change_service.StorageService") as mock_storage_cls, \
patch("backend.api.routes.file_upload._prepare_theme_for_job", return_value=("jobs/test-123/style/style_params.json", {"bg": "bg.png"}, None)), \
patch("backend.services.worker_service.get_worker_service") as mock_worker_svc:
mock_storage_cls.return_value = MagicMock()
@@ -210,7 +213,8 @@ class TestChangeToPublic:
assert style_update is not None
assert style_update["theme_id"] == "nomad"
assert style_update["color_overrides"] == {}
assert style_update["style_assets"] == {}
assert style_update["style_assets"] == {"bg": "bg.png"}
assert style_update["style_params_gcs_path"] == "jobs/test-123/style/style_params.json"
assert style_update["is_private"] is False
assert style_update["status"] == "lyrics_complete"
@@ -225,6 +229,7 @@ class TestChangeToPublic:
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock), \
patch("backend.services.visibility_change_service.StorageService") as mock_storage_cls, \
patch("backend.api.routes.file_upload._prepare_theme_for_job", return_value=("jobs/test-123/style/style_params.json", {}, None)), \
patch("backend.services.worker_service.get_worker_service") as mock_worker_svc:
mock_storage_cls.return_value = MagicMock()
@@ -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'],
)
+251
View File
@@ -0,0 +1,251 @@
"""
Unit tests for the edit completed track endpoint.
Tests POST /api/jobs/{job_id}/edit which allows users to reopen
completed tracks for editing (lyrics, instrumental, metadata).
"""
import pytest
from datetime import datetime, UTC
from unittest.mock import MagicMock, AsyncMock, patch, Mock
from backend.models.job import Job, JobStatus
@pytest.fixture
def complete_job():
"""A completed job with distribution data."""
return Job(
job_id="test-edit-123",
status="complete",
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test Artist",
title="Test Song",
user_email="user@example.com",
dropbox_path="/Karaoke/Organized",
edit_count=0,
state_data={
"youtube_url": "https://youtu.be/abc123",
"brand_code": "NOMAD-1234",
"dropbox_link": "https://dropbox.com/...",
"gdrive_files": {"mp4": "file_id_1", "mp4_720p": "file_id_2"},
"audio_complete": True,
"lyrics_complete": True,
"render_progress": {"stage": "complete"},
"video_progress": {"stage": "complete"},
"encoding_progress": {"stage": "complete"},
"review_complete": True,
"corrected_lyrics": {"segments": []},
"instrumental_selection": "clean",
},
)
@pytest.fixture
def mock_job_manager(complete_job):
"""Mock JobManager with common methods."""
manager = MagicMock()
manager.get_job.return_value = complete_job
manager.transition_to_state.return_value = True
return manager
@pytest.fixture
def mock_worker_service():
"""Mock WorkerService."""
service = MagicMock()
service.trigger_audio_worker = AsyncMock(return_value=True)
service.trigger_lyrics_worker = AsyncMock(return_value=True)
service.trigger_screens_worker = AsyncMock(return_value=True)
service.trigger_video_worker = AsyncMock(return_value=True)
service.trigger_render_video_worker = AsyncMock(return_value=True)
return service
@pytest.fixture
def client(mock_job_manager, mock_worker_service):
"""Create TestClient with mocked dependencies."""
mock_creds = MagicMock()
mock_creds.universe_domain = 'googleapis.com'
mock_theme_service = MagicMock()
mock_theme_service.get_default_theme_id.return_value = "nomad"
def mock_job_manager_factory(*args, **kwargs):
return mock_job_manager
# After edit, return updated job with review token
updated_job = Job(
job_id="test-edit-123",
status="awaiting_review",
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test Artist",
title="Test Song",
user_email="user@example.com",
review_token="test-review-token-abc",
edit_count=1,
)
def get_job_side_effect(job_id):
# First call returns complete job, second returns updated job
if mock_job_manager.get_job.call_count <= 1:
return mock_job_manager.get_job.return_value
return updated_job
mock_job_manager.get_job.side_effect = get_job_side_effect
with patch('backend.api.routes.jobs.job_manager', mock_job_manager), \
patch('backend.api.routes.jobs.worker_service', mock_worker_service), \
patch('backend.api.routes.jobs.get_theme_service', return_value=mock_theme_service), \
patch('backend.api.routes.jobs.StorageService') as mock_storage_cls, \
patch('backend.api.routes.jobs.FirestoreService') as mock_fs_cls, \
patch('backend.services.job_manager.JobManager', mock_job_manager_factory), \
patch('backend.services.firestore_service.firestore'), \
patch('backend.services.storage_service.storage'), \
patch('google.auth.default', return_value=(mock_creds, 'test-project')):
mock_storage_cls.return_value.delete_folder.return_value = 3
from backend.main import app
from fastapi.testclient import TestClient
yield TestClient(app)
class TestEditCompletedTrackSuccess:
"""Tests for successful edit initiation."""
def test_edit_returns_200(self, client, auth_headers):
"""Edit a completed job returns 200."""
response = client.post("/api/jobs/test-edit-123/edit", headers=auth_headers, json={})
assert response.status_code == 200
def test_edit_returns_review_url(self, client, auth_headers):
"""Response includes review URL."""
response = client.post("/api/jobs/test-edit-123/edit", headers=auth_headers, json={})
data = response.json()
assert "review_url" in data
assert "test-edit-123" in data["review_url"]
assert "review" in data["review_url"]
def test_edit_returns_review_token(self, client, auth_headers):
"""Response includes review token."""
response = client.post("/api/jobs/test-edit-123/edit", headers=auth_headers, json={})
data = response.json()
assert data["review_token"] == "test-review-token-abc"
def test_edit_transitions_to_awaiting_review(self, client, mock_job_manager, auth_headers):
"""Job state transitions to AWAITING_REVIEW."""
client.post("/api/jobs/test-edit-123/edit", headers=auth_headers, json={})
mock_job_manager.transition_to_state.assert_called_once_with(
"test-edit-123",
JobStatus.AWAITING_REVIEW,
progress=60,
message="Track reopened for editing",
)
def test_edit_without_metadata_change(self, client, auth_headers):
"""Edit without metadata returns metadata_updated=false."""
response = client.post("/api/jobs/test-edit-123/edit", headers=auth_headers, json={})
data = response.json()
assert data["metadata_updated"] is False
def test_edit_does_not_trigger_screens_without_metadata(self, client, mock_worker_service, auth_headers):
"""Screens worker not triggered when metadata unchanged."""
client.post("/api/jobs/test-edit-123/edit", headers=auth_headers, json={})
mock_worker_service.trigger_screens_worker.assert_not_called()
class TestEditWithMetadataUpdate:
"""Tests for editing with artist/title changes."""
def test_edit_with_artist_change(self, client, auth_headers):
"""Edit with new artist returns metadata_updated=true."""
response = client.post(
"/api/jobs/test-edit-123/edit",
headers=auth_headers,
json={"artist": "New Artist"},
)
data = response.json()
assert data["metadata_updated"] is True
def test_edit_with_title_change(self, client, auth_headers):
"""Edit with new title returns metadata_updated=true."""
response = client.post(
"/api/jobs/test-edit-123/edit",
headers=auth_headers,
json={"title": "New Song Title"},
)
data = response.json()
assert data["metadata_updated"] is True
def test_edit_with_same_artist_no_metadata_update(self, client, auth_headers):
"""Edit with same artist does not flag metadata_updated."""
response = client.post(
"/api/jobs/test-edit-123/edit",
headers=auth_headers,
json={"artist": "Test Artist"},
)
data = response.json()
assert data["metadata_updated"] is False
def test_edit_triggers_screens_on_metadata_change(self, client, mock_worker_service, auth_headers):
"""Screens worker triggered when metadata changes."""
client.post(
"/api/jobs/test-edit-123/edit",
headers=auth_headers,
json={"artist": "New Artist"},
)
mock_worker_service.trigger_screens_worker.assert_called_once_with("test-edit-123")
class TestEditValidation:
"""Tests for validation and error cases."""
def test_edit_non_complete_job_returns_400(self, client, mock_job_manager, auth_headers):
"""Cannot edit a job that isn't complete."""
pending_job = Job(
job_id="test-pending",
status="pending",
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
)
mock_job_manager.get_job.side_effect = None
mock_job_manager.get_job.return_value = pending_job
response = client.post("/api/jobs/test-pending/edit", headers=auth_headers, json={})
assert response.status_code == 400
assert "completed" in response.json()["detail"].lower() or "complete" in response.json()["detail"].lower()
def test_edit_already_deleted_outputs_returns_400(self, client, mock_job_manager, auth_headers):
"""Cannot edit a job whose outputs are already deleted."""
deleted_job = Job(
job_id="test-deleted",
status="complete",
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
outputs_deleted_at=datetime.now(UTC),
)
mock_job_manager.get_job.side_effect = None
mock_job_manager.get_job.return_value = deleted_job
response = client.post("/api/jobs/test-deleted/edit", headers=auth_headers, json={})
assert response.status_code == 400
assert "already" in response.json()["detail"].lower()
def test_edit_nonexistent_job_returns_404(self, client, mock_job_manager, auth_headers):
"""Cannot edit a job that doesn't exist."""
mock_job_manager.get_job.side_effect = None
mock_job_manager.get_job.return_value = None
response = client.post("/api/jobs/nonexistent/edit", headers=auth_headers, json={})
assert response.status_code == 404
class TestEditCleanup:
"""Tests for output cleanup during edit."""
def test_cleanup_results_in_response(self, client, auth_headers):
"""Response includes cleanup results."""
response = client.post("/api/jobs/test-edit-123/edit", headers=auth_headers, json={})
data = response.json()
assert "cleanup_results" in data
assert "gcs_finals" in data["cleanup_results"]
+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
+639 -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,375 @@ 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()
# =========================================================================
# 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."""
+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."""
+132
View File
@@ -0,0 +1,132 @@
"""
Tests for job observability improvements.
Covers:
- TimelineEvent metadata field
- log_to_job helper function
- Timeline metadata in state transitions
"""
import pytest
from unittest.mock import patch, MagicMock
from datetime import datetime, timezone
from backend.models.job import TimelineEvent
class TestTimelineEventMetadata:
"""Tests for the metadata field on TimelineEvent."""
def test_timeline_event_without_metadata(self):
"""Existing events without metadata still work."""
event = TimelineEvent(
status="complete",
timestamp="2026-03-07T12:00:00",
progress=100,
message="Done!",
)
data = event.model_dump(mode='json')
assert data["status"] == "complete"
assert data["metadata"] is None
def test_timeline_event_with_metadata(self):
"""Events can include structured metadata."""
metadata = {
"action": "completed",
"brand_code": "NOMAD-1234",
"youtube_url": "https://youtube.com/watch?v=abc123",
"gdrive_file_ids": {"mp4": "file1", "cdg": "file2"},
}
event = TimelineEvent(
status="complete",
timestamp="2026-03-07T12:00:00",
progress=100,
message="Karaoke generation complete!",
metadata=metadata,
)
data = event.model_dump(mode='json')
assert data["metadata"]["brand_code"] == "NOMAD-1234"
assert data["metadata"]["youtube_url"] == "https://youtube.com/watch?v=abc123"
assert data["metadata"]["gdrive_file_ids"]["mp4"] == "file1"
def test_timeline_event_with_edit_metadata(self):
"""Edit-initiated events include previous outputs and cleanup results."""
metadata = {
"action": "edit_initiated",
"initiated_by": "user@example.com",
"edit_number": 1,
"previous_outputs": {
"youtube_url": "https://youtube.com/watch?v=old123",
"brand_code": "NOMAD-0042",
"dropbox_link": "https://dropbox.com/sh/old",
},
"cleanup_results": {
"youtube": {"status": "success", "video_id": "old123"},
"dropbox": {"status": "success", "path": "/Karaoke/NOMAD-0042"},
"gdrive": {"status": "skipped", "reason": "no gdrive_files"},
},
}
event = TimelineEvent(
status="complete",
timestamp="2026-03-07T12:00:00",
message="Track edit initiated by user@example.com (edit #1)",
metadata=metadata,
)
data = event.model_dump(mode='json')
assert data["metadata"]["previous_outputs"]["youtube_url"] == "https://youtube.com/watch?v=old123"
assert data["metadata"]["cleanup_results"]["youtube"]["status"] == "success"
def test_timeline_event_metadata_roundtrip(self):
"""Metadata survives serialization/deserialization."""
metadata = {"brand_code": "NOMAD-1234", "nested": {"key": "value"}}
event = TimelineEvent(
status="complete",
timestamp="2026-03-07T12:00:00",
metadata=metadata,
)
data = event.model_dump(mode='json')
restored = TimelineEvent(**data)
assert restored.metadata == metadata
class TestLogToJob:
"""Tests for the log_to_job helper function."""
@patch('backend.services.firestore_service._get_log_service')
def test_log_to_job_writes_to_subcollection(self, mock_get_service):
"""log_to_job creates a WorkerLogEntry and writes to Firestore."""
mock_service = MagicMock()
mock_get_service.return_value = mock_service
from backend.services.firestore_service import log_to_job
log_to_job("job123", "edit", "INFO", "Edit started", {"key": "value"})
mock_service.append_log_to_subcollection.assert_called_once()
call_args = mock_service.append_log_to_subcollection.call_args
assert call_args[0][0] == "job123"
entry = call_args[0][1]
assert entry.worker == "edit"
assert entry.level == "INFO"
assert entry.message == "Edit started"
assert entry.metadata == {"key": "value"}
@patch('backend.services.firestore_service._get_log_service')
def test_log_to_job_suppresses_errors(self, mock_get_service):
"""log_to_job should never raise — logging failures must be silent."""
mock_get_service.side_effect = Exception("Firestore down")
from backend.services.firestore_service import log_to_job
# Should not raise
log_to_job("job123", "edit", "INFO", "Edit started")
@patch('backend.services.firestore_service._get_log_service')
def test_log_to_job_without_metadata(self, mock_get_service):
"""log_to_job works without metadata."""
mock_service = MagicMock()
mock_get_service.return_value = mock_service
from backend.services.firestore_service import log_to_job
log_to_job("job123", "admin", "WARNING", "Something happened")
mock_service.append_log_to_subcollection.assert_called_once()
entry = mock_service.append_log_to_subcollection.call_args[0][1]
assert entry.metadata is None
+44
View File
@@ -85,6 +85,50 @@ class TestJobModelIsPrivate:
assert job.is_private is False
def test_create_job_stores_creation_params(self):
"""JobManager.create_job should store creation_params for observability."""
from backend.services.job_manager import JobManager
manager = JobManager()
manager.firestore = Mock()
manager.firestore.create_job = Mock()
job_create = JobCreate(
artist="Test",
title="Song",
theme_id="nomad",
is_private=True,
request_metadata={"created_from": "guided_flow"},
)
job = manager.create_job(job_create, is_admin=False)
assert job.creation_params == {
"is_private": True,
"is_admin": False,
"created_from": "guided_flow",
}
def test_creation_params_defaults_created_from_unknown(self):
"""creation_params should default created_from to 'unknown' when not in metadata."""
from backend.services.job_manager import JobManager
manager = JobManager()
manager.firestore = Mock()
manager.firestore.create_job = Mock()
job_create = JobCreate(
artist="Test",
title="Song",
theme_id="nomad",
)
job = manager.create_job(job_create, is_admin=True)
assert job.creation_params["created_from"] == "unknown"
assert job.creation_params["is_private"] is False
assert job.creation_params["is_admin"] is True
class TestGetEffectiveDistributionForJob:
"""Tests for get_effective_distribution_for_job() helper."""
+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"
@@ -772,7 +772,7 @@ class TestNotificationFormatting:
assert payload["title"] == "Review Lyrics"
assert "Test Song" in payload["body"]
assert "Test Artist" in payload["body"]
assert "/review/test-job-123" in payload["url"]
assert "/app/jobs#/test-job-123/review" in payload["url"]
@pytest.mark.asyncio
async def test_send_blocking_notification_instrumental(self, push_service):
@@ -802,7 +802,7 @@ class TestNotificationFormatting:
import json
payload = json.loads(call_args[1]["data"])
assert payload["title"] == "Select Instrumental"
assert "/instrumental/test-job-123" in payload["url"]
assert "/app/jobs#/test-job-123/instrumental" in payload["url"]
@pytest.mark.asyncio
async def test_send_completion_notification(self, push_service):
+312
View File
@@ -0,0 +1,312 @@
"""
Unit tests for review session backup/restore feature.
Tests the ReviewSession model, Firestore CRUD methods, and API endpoints.
"""
import pytest
import json
import hashlib
from datetime import datetime, timezone
from unittest.mock import patch, MagicMock, AsyncMock
from backend.models.review_session import ReviewSession, ReviewSessionSummary
from backend.models.job import Job, JobStatus
@pytest.fixture(autouse=True)
def ensure_auth_overrides():
"""Ensure auth dependency overrides are set for endpoint tests.
The global conftest autouse fixture should handle this, but some tests
in the broader suite can leave dependency_overrides in a dirty state.
This fixture ensures a clean slate for review session endpoint tests.
"""
from backend.main import app
from backend.api.dependencies import require_auth, require_review_auth
async def mock_require_auth():
from backend.services.auth_service import UserType, AuthResult
return AuthResult(
is_valid=True,
user_type=UserType.ADMIN,
remaining_uses=999,
message="Test admin token",
is_admin=True,
user_email="test@example.com",
)
async def mock_require_review_auth(job_id: str = "test123"):
return (job_id, "full")
app.dependency_overrides[require_auth] = mock_require_auth
app.dependency_overrides[require_review_auth] = mock_require_review_auth
yield
app.dependency_overrides.pop(require_auth, None)
app.dependency_overrides.pop(require_review_auth, None)
# ============================================
# Model Tests
# ============================================
class TestReviewSessionSummary:
def test_to_dict(self):
summary = ReviewSessionSummary(
total_segments=10,
total_words=100,
corrections_made=5,
changed_words=[{"original": "hello", "corrected": "hallo", "segment_index": 0}],
)
d = summary.to_dict()
assert d["total_segments"] == 10
assert d["corrections_made"] == 5
assert len(d["changed_words"]) == 1
def test_from_dict(self):
data = {
"total_segments": 15,
"total_words": 200,
"corrections_made": 8,
"changed_words": [],
}
summary = ReviewSessionSummary.from_dict(data)
assert summary.total_segments == 15
assert summary.corrections_made == 8
def test_from_dict_missing_fields(self):
summary = ReviewSessionSummary.from_dict({})
assert summary.total_segments == 0
assert summary.changed_words == []
class TestReviewSession:
def test_to_dict_and_from_dict_roundtrip(self):
session = ReviewSession(
session_id="test-session-1",
job_id="job-123",
user_email="user@example.com",
edit_count=42,
trigger="preview",
audio_duration_seconds=222.5,
artist="Test Artist",
title="Test Song",
data_hash="abc123hash",
correction_data_gcs_path="jobs/job-123/review_sessions/test-session-1.json",
summary=ReviewSessionSummary(total_segments=10, total_words=100, corrections_made=5),
)
d = session.to_dict()
restored = ReviewSession.from_dict(d)
assert restored.session_id == "test-session-1"
assert restored.job_id == "job-123"
assert restored.edit_count == 42
assert restored.trigger == "preview"
assert restored.audio_duration_seconds == 222.5
assert restored.artist == "Test Artist"
assert restored.data_hash == "abc123hash"
assert restored.summary.total_segments == 10
def test_from_dict_string_timestamps(self):
data = {
"session_id": "s1",
"created_at": "2026-03-07T12:00:00Z",
"updated_at": "2026-03-07T12:15:00Z",
}
session = ReviewSession.from_dict(data)
assert session.created_at.year == 2026
assert session.updated_at.minute == 15
def test_default_values(self):
session = ReviewSession()
assert session.trigger == "auto"
assert session.edit_count == 0
assert session.audio_duration_seconds is None
assert session.session_id # auto-generated
# ============================================
# API Endpoint Tests
# ============================================
class TestSaveReviewSessionEndpoint:
"""Tests for POST /api/review/{job_id}/sessions"""
@patch("backend.api.routes.review.StorageService")
@patch("backend.api.routes.review.FirestoreService")
@patch("backend.api.routes.review.JobManager")
def test_save_session_success(self, MockJobManager, MockFirestore, MockStorage, test_client):
mock_job = MagicMock(spec=Job)
mock_job.artist = "Test Artist"
mock_job.title = "Test Song"
mock_job.state_data = {"backing_vocals_analysis": {"total_duration_seconds": 180.0}}
MockJobManager.return_value.get_job.return_value = mock_job
MockFirestore.return_value.get_latest_review_session_hash.return_value = None
MockStorage.return_value.upload_json.return_value = None
MockFirestore.return_value.save_review_session.return_value = "session-id"
response = test_client.post(
"/api/review/job-123/sessions",
json={
"correction_data": {"corrected_segments": [], "original_segments": []},
"edit_count": 5,
"trigger": "manual",
"summary": {"total_segments": 10, "total_words": 100, "corrections_made": 5},
},
)
assert response.status_code == 200
data = response.json()
assert data["status"] == "saved"
assert "session_id" in data
@patch("backend.api.routes.review.StorageService")
@patch("backend.api.routes.review.FirestoreService")
@patch("backend.api.routes.review.JobManager")
def test_save_session_deduplication(self, MockJobManager, MockFirestore, MockStorage, test_client):
"""Should skip save if data hash matches latest session."""
mock_job = MagicMock(spec=Job)
mock_job.artist = "Test Artist"
mock_job.title = "Test Song"
mock_job.state_data = {}
correction_data = {"corrected_segments": [{"text": "hello"}], "original_segments": []}
data_json = json.dumps(correction_data, sort_keys=True, default=str)
expected_hash = hashlib.sha256(data_json.encode()).hexdigest()
MockJobManager.return_value.get_job.return_value = mock_job
MockFirestore.return_value.get_latest_review_session_hash.return_value = expected_hash
response = test_client.post(
"/api/review/job-123/sessions",
json={"correction_data": correction_data, "edit_count": 5, "trigger": "auto"},
)
assert response.status_code == 200
assert response.json()["status"] == "skipped"
assert response.json()["reason"] == "identical_data"
# GCS upload should NOT have been called
MockStorage.return_value.upload_json.assert_not_called()
@patch("backend.api.routes.review.JobManager")
def test_save_session_job_not_found(self, MockJobManager, test_client):
MockJobManager.return_value.get_job.return_value = None
response = test_client.post(
"/api/review/job-123/sessions",
json={"correction_data": {"foo": "bar"}, "edit_count": 1},
)
assert response.status_code == 404
@patch("backend.api.routes.review.JobManager")
def test_save_session_missing_correction_data(self, MockJobManager, test_client):
mock_job = MagicMock(spec=Job)
MockJobManager.return_value.get_job.return_value = mock_job
response = test_client.post(
"/api/review/job-123/sessions",
json={"edit_count": 1},
)
assert response.status_code == 400
class TestListReviewSessionsEndpoint:
"""Tests for GET /api/review/{job_id}/sessions"""
@patch("backend.api.routes.review.FirestoreService")
def test_list_sessions(self, MockFirestore, test_client):
session = ReviewSession(
session_id="s1",
job_id="job-123",
user_email="user@test.com",
edit_count=10,
trigger="auto",
artist="Artist",
title="Song",
)
MockFirestore.return_value.list_review_sessions.return_value = [session]
response = test_client.get("/api/review/job-123/sessions")
assert response.status_code == 200
data = response.json()
assert len(data["sessions"]) == 1
assert data["sessions"][0]["session_id"] == "s1"
assert data["sessions"][0]["edit_count"] == 10
@patch("backend.api.routes.review.FirestoreService")
def test_list_sessions_empty(self, MockFirestore, test_client):
MockFirestore.return_value.list_review_sessions.return_value = []
response = test_client.get("/api/review/job-123/sessions")
assert response.status_code == 200
assert response.json()["sessions"] == []
class TestGetReviewSessionEndpoint:
"""Tests for GET /api/review/{job_id}/sessions/{session_id}"""
@patch("backend.api.routes.review.StorageService")
@patch("backend.api.routes.review.FirestoreService")
def test_get_session_with_data(self, MockFirestore, MockStorage, test_client):
session = ReviewSession(
session_id="s1",
job_id="job-123",
correction_data_gcs_path="jobs/job-123/review_sessions/s1.json",
)
MockFirestore.return_value.get_review_session.return_value = session
MockStorage.return_value.download_json.return_value = {"corrected_segments": []}
response = test_client.get("/api/review/job-123/sessions/s1")
assert response.status_code == 200
data = response.json()
assert data["session_id"] == "s1"
assert data["correction_data"] == {"corrected_segments": []}
@patch("backend.api.routes.review.FirestoreService")
def test_get_session_not_found(self, MockFirestore, test_client):
MockFirestore.return_value.get_review_session.return_value = None
response = test_client.get("/api/review/job-123/sessions/nonexistent")
assert response.status_code == 404
class TestDeleteReviewSessionEndpoint:
"""Tests for DELETE /api/review/{job_id}/sessions/{session_id}"""
@patch("backend.api.routes.review.StorageService")
@patch("backend.api.routes.review.FirestoreService")
def test_delete_session(self, MockFirestore, MockStorage, test_client):
session = ReviewSession(
session_id="s1",
job_id="job-123",
correction_data_gcs_path="jobs/job-123/review_sessions/s1.json",
)
MockFirestore.return_value.get_review_session.return_value = session
response = test_client.delete("/api/review/job-123/sessions/s1")
assert response.status_code == 200
assert response.json()["status"] == "deleted"
MockStorage.return_value.delete_file.assert_called_once()
MockFirestore.return_value.delete_review_session.assert_called_once()
@patch("backend.api.routes.review.FirestoreService")
def test_delete_session_not_found(self, MockFirestore, test_client):
MockFirestore.return_value.get_review_session.return_value = None
response = test_client.delete("/api/review/job-123/sessions/nonexistent")
assert response.status_code == 404
class TestSearchReviewSessionsEndpoint:
"""Tests for GET /api/review/sessions/search"""
@patch("backend.api.routes.review.FirestoreService")
def test_search_sessions(self, MockFirestore, test_client):
MockFirestore.return_value.search_review_sessions.return_value = [
{"session_id": "s1", "job_id": "j1", "artist": "Artist A"},
]
response = test_client.get("/api/review/sessions/search?q=Artist")
assert response.status_code == 200
assert len(response.json()["sessions"]) == 1
@patch("backend.api.routes.review.FirestoreService")
def test_search_sessions_empty(self, MockFirestore, test_client):
MockFirestore.return_value.search_review_sessions.return_value = []
response = test_client.get("/api/review/sessions/search?q=nonexistent")
assert response.status_code == 200
assert response.json()["sessions"] == []
+14
View File
@@ -446,6 +446,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
+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,
+54 -4
View File
@@ -271,20 +271,70 @@ class TestWorkerService:
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()
await worker_service.trigger_video_worker("test123")
# Verify HTTP POST was made
mock_client.post.assert_called_once()
call_args = mock_client.post.call_args
assert "/api/internal/workers/video" in str(call_args)
@pytest.mark.asyncio
async def test_trigger_video_worker_routes_to_cloud_run_job(self):
"""Test that video worker routes to Cloud Run Jobs when enabled.
When USE_CLOUD_RUN_JOBS_FOR_VIDEO=true and ENABLE_CLOUD_TASKS=true,
trigger_video_worker should dispatch a Cloud Run Job instead of
posting to the internal HTTP endpoint. This ensures the encoding
orchestrator runs to completion, immune to Cloud Run Service
deployment rollouts (see incident 2026-03-08, job 43c0d519).
"""
from backend.services.worker_service import WorkerService, reset_worker_service
reset_worker_service()
with patch('backend.services.worker_service.get_settings') as mock_settings:
mock_settings.return_value.admin_tokens = "test-token"
mock_settings.return_value.google_cloud_project = "test-project"
mock_settings.return_value.enable_cloud_tasks = True
mock_settings.return_value.gcp_region = "us-central1"
mock_settings.return_value.use_cloud_run_jobs_for_video = True
mock_jobs_client = MagicMock()
mock_operation = MagicMock()
mock_operation.metadata = "test-metadata"
mock_jobs_client.run_job.return_value = mock_operation
mock_run_v2 = MagicMock()
mock_run_v2.JobsClient.return_value = mock_jobs_client
mock_run_v2.RunJobRequest = MagicMock()
mock_run_v2.RunJobRequest.Overrides = MagicMock()
mock_run_v2.RunJobRequest.Overrides.ContainerOverride = MagicMock()
import google.cloud
with patch.dict('sys.modules', {'google.cloud.run_v2': mock_run_v2}), \
patch.object(google.cloud, 'run_v2', mock_run_v2, create=True):
service = WorkerService()
result = await service.trigger_video_worker("test123")
assert result is True
mock_jobs_client.run_job.assert_called_once()
# Verify correct Cloud Run Job name
call_args = mock_run_v2.RunJobRequest.call_args
assert call_args is not None
assert "video-encoding-job" in str(call_args)
# Verify job_id is passed via container args override
override_args = mock_run_v2.RunJobRequest.Overrides.ContainerOverride.call_args
assert "--job-id" in str(override_args)
assert "test123" in str(override_args)
class TestWorkerServiceCloudTasks:
"""Test WorkerService Cloud Tasks integration."""
@@ -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()
+1 -1
View File
@@ -45,7 +45,7 @@ def _make_mock_job_manager(job=None):
def _make_search_session(user_email="test@example.com", expired=False, tenant_id=None):
now = datetime.utcnow()
ttl = now - timedelta(hours=1) if expired else now + timedelta(minutes=30)
ttl = now - timedelta(hours=1) if expired else now + timedelta(days=7)
return {
"session_id": "sess-abc-123",
"user_email": user_email,
+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()
+2 -2
View File
@@ -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()
+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()
@@ -1709,3 +1741,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
+155
View File
@@ -1395,3 +1395,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
+34
View File
@@ -135,6 +135,40 @@ async def process_audio_download(job_id: str) -> bool:
message="Audio downloaded, starting processing"
)
# Check if audio editing was requested — enter blocking state instead of processing
job = job_manager.get_job(job_id)
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,
progress=15,
message="Audio downloaded. Please review and edit the audio before processing."
)
logger.info(f"[job:{job_id}] Audio download complete, awaiting audio edit")
return True
# Trigger audio separation and lyrics workers
worker_service = get_worker_service()
await asyncio.gather(
+78 -3
View File
@@ -330,6 +330,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', {
@@ -414,18 +417,29 @@ 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": "modal",
"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))
# 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 +682,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>
+106
View File
@@ -420,6 +420,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 +464,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
@@ -699,6 +707,104 @@ async def upload_lyrics_results(
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>
+9
View File
@@ -319,6 +319,15 @@ async def process_render_video(job_id: str) -> bool:
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'])
+2
View File
@@ -222,6 +222,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")
+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,
}
+112 -13
View File
@@ -173,6 +173,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 +228,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 +342,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,18 +371,33 @@ async def generate_video_orchestrated(job_id: str) -> bool:
artist=job.artist,
title=job.title,
warnings=result.distribution_warnings,
settings=settings,
)
# 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,
"youtube_url": result.youtube_url,
"youtube_upload_queued": result.youtube_upload_queued,
"dropbox_link": result.dropbox_link,
"gdrive_file_ids": result.gdrive_files,
"edit_count": getattr(job, 'edit_count', 0),
"duration_seconds": round(duration, 1),
}
if result.distribution_warnings:
completion_metadata["distribution_warnings"] = result.distribution_warnings
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.COMPLETE,
progress=100,
message="Karaoke generation complete!"
message="Karaoke generation complete!",
timeline_metadata=completion_metadata,
)
duration = time.time() - start_time
root_span.set_attribute("duration_seconds", duration)
root_span.set_attribute("brand_code", result.brand_code or '')
logger.info(f"[job:{job_id}] WORKER_END worker=video orchestrator=true status=success duration={duration:.1f}s")
@@ -621,11 +647,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):
@@ -859,14 +893,24 @@ async def generate_video_legacy(job_id: str) -> bool:
})
# Mark job as complete (triggers completion email with youtube_url now available)
duration = time.time() - start_time
completion_metadata = {
"action": "completed",
"brand_code": result.get('brand_code'),
"youtube_url": result.get('youtube_url'),
"dropbox_link": result.get('dropbox_link'),
"gdrive_file_ids": result.get('gdrive_files'),
"edit_count": getattr(job, 'edit_count', 0),
"duration_seconds": round(duration, 1),
}
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.COMPLETE,
progress=100,
message="Karaoke generation complete!"
message="Karaoke generation complete!",
timeline_metadata=completion_metadata,
)
duration = time.time() - start_time
root_span.set_attribute("duration_seconds", duration)
root_span.set_attribute("brand_code", result.get('brand_code', ''))
logger.info(f"[job:{job_id}] WORKER_END worker=video status=success duration={duration:.1f}s")
@@ -1078,7 +1122,6 @@ async def _handle_native_distribution(
artist=job.artist,
title=job.title,
warnings=result['distribution_warnings'],
settings=settings,
)
@@ -1118,6 +1161,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
@@ -1211,7 +1305,9 @@ async def _setup_working_directory(
# 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")
@@ -1399,14 +1495,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}")
@@ -1446,6 +1544,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'),
]
+48 -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
@@ -638,7 +672,7 @@ class VideoWorkerOrchestrator:
if video_url:
self.result.youtube_url = video_url
self.job_log.info(f"Uploaded to YouTube: {video_url}")
self.job_log.info(f"Uploaded to YouTube: {video_url} (video_id={video_id})")
# Record upload in pending buffer (bridges ~7min GCP monitoring delay)
try:
@@ -715,7 +749,7 @@ class VideoWorkerOrchestrator:
except Exception as e:
self.job_log.warning(f"Failed to create Dropbox sharing link: {e}")
self.job_log.info("Dropbox upload complete")
self.job_log.info(f"Dropbox upload complete: {remote_folder}")
except Exception as e:
self.job_log.error(f"Dropbox upload failed: {e}")
@@ -752,7 +786,7 @@ class VideoWorkerOrchestrator:
)
self.result.gdrive_files = uploaded
self.job_log.info(f"Google Drive upload complete: {len(uploaded)} files")
self.job_log.info(f"Google Drive upload complete: {len(uploaded)} files (ids={uploaded})")
except Exception as e:
self.job_log.error(f"Google Drive upload failed: {e}")
@@ -861,7 +895,8 @@ def create_orchestrator_config_from_job(
# 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"),
# 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"),
lrc_file_path=os.path.join(temp_dir, f"{base_name} (Karaoke).lrc"),
+113 -4
View File
@@ -295,6 +295,43 @@ Error (duration mismatch):
}
```
#### Edit Completed Track
```http
POST /api/jobs/{job_id}/edit
Content-Type: application/json
{
"artist": "Updated Artist", // optional, only if changing
"title": "Updated Title" // optional, only if changing
}
```
Reopens a completed track for editing. Cleans up all distributed outputs (YouTube, Dropbox, GDrive, GCS finals), recycles the brand code, and resets the job to `awaiting_review`. A new review token is issued automatically. No additional credits consumed.
If `artist` or `title` are provided and differ from current values, title/end screens are deleted and the screens worker is triggered to regenerate them in the background.
Response:
```json
{
"status": "success",
"job_id": "abc123",
"message": "Track reopened for editing. Previous outputs have been removed.",
"review_url": "/app/jobs#/abc123/review",
"review_token": "...",
"metadata_updated": true,
"cleanup_results": {
"youtube": {"status": "success", "video_id": "xyz"},
"dropbox": {"status": "success", "path": "/Karaoke/..."},
"gdrive": {"status": "success"},
"gcs_finals": {"status": "success", "deleted_count": 4},
"brand_code": {"status": "recycled", "code": "NOMAD-1234"}
}
}
```
**Requirements:** Job must be in `complete` state with `outputs_deleted_at` not set. User must own the job or be admin.
#### Get Style Upload URLs
```http
@@ -404,6 +441,65 @@ Content-Type: application/json
Stores annotations to `jobs/{job_id}/lyrics/annotations.json`. Merges with existing annotations if present.
#### 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}`.
##### Save Review Session
```http
POST /api/review/{job_id}/sessions
Content-Type: application/json
{
"correction_data": { "corrected_segments": [...], "original_segments": [...] },
"edit_count": 5,
"trigger": "auto", // "auto" | "preview" | "manual"
"summary": {
"total_segments": 10,
"total_words": 100,
"corrections_made": 5,
"changed_words": [{"original": "hello", "corrected": "hallo", "segment_index": 0}]
}
}
```
Deduplicates via SHA-256 hash of correction_data. Returns `{"status": "skipped", "reason": "identical_data"}` if data hasn't changed since last save.
Auth: Review token (same as correction data access).
##### List Review Sessions
```http
GET /api/review/{job_id}/sessions
```
Returns session metadata (no correction_data). Ordered by most recent first.
##### Get Review Session
```http
GET /api/review/{job_id}/sessions/{session_id}
```
Returns full session including correction_data downloaded from GCS.
##### Delete Review Session
```http
DELETE /api/review/{job_id}/sessions/{session_id}
```
Deletes both GCS data and Firestore metadata.
##### Search Review Sessions (Cross-Job)
```http
GET /api/review/sessions/search?q=artist+name&limit=20
```
Searches across all jobs. Requires admin auth. Matches against artist, title, and job_id fields.
### Instrumental Selection (Finalise-Only Jobs)
For finalise-only jobs (where audio prep was done externally), instrumental selection is handled separately:
@@ -565,7 +661,7 @@ Content-Type: application/json
}
```
Searches for audio **without creating a job**. Returns a short-lived search session (30-min TTL).
Searches for audio **without creating a job**. Returns a search session (7-day TTL).
Credits are checked here but **not deducted** — deduction happens at job creation.
**Response:**
@@ -746,16 +842,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.
@@ -1617,12 +1715,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
@@ -1648,6 +1750,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`.
+22 -3
View File
@@ -126,8 +126,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
@@ -175,6 +176,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 +201,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 |
@@ -240,7 +259,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 |
+7 -5
View File
@@ -24,18 +24,20 @@ Analyzed GCP billing data and identified $1,440+/month in immediate savings thro
### ✅ GitHub Actions Runners Auto-Scaling
**Status:** Deployed and operational (February 10, 2026)
**Status:** Fixed and operational (March 17, 2026)
**Changes Made:**
- Reduced from 20 VMs to 3 Spot/Preemptible instances
- Reduced from 20 VMs to 3 general + 1 build + 3 GPU runners
- Implemented auto-start on CI job queue (via GitHub webhook)
- Implemented auto-stop after 1 hour idle (via Cloud Scheduler)
- Removed external IPs (using Cloud NAT instead)
**March 2026 Fix:** The initial auto-scaling implementation had critical bugs that prevented idle shutdown — runners were running 24/7 despite the auto-stop mechanism. See `docs/SELF-HOSTED-RUNNERS.md` for full details. Bugs fixed: metadata writes not awaited, "set now and keep" infinite loop, pending jobs resetting all timestamps, missing IAM permission (`iam.serviceAccountUser`), no STOPPING state handling, sequential (slow) stops.
**Cost Impact:**
- **Before:** 20 VMs × $72/month = $1,440/month
- **After:** 3 Spot VMs × $25/month × ~20% utilization = $50-100/month
- **Savings:** ~$1,340-1,390/month (93% reduction)
- **Before:** 7 VMs running 24/7 = ~$1,648/month
- **After (fixed):** ~$50-150/month (estimated, with proper idle shutdown)
- **Savings:** ~$1,500/month
**Implementation:**
- PRs: [#376](https://github.com/nomadkaraoke/karaoke-gen/pull/376), [#383](https://github.com/nomadkaraoke/karaoke-gen/pull/383), [#385](https://github.com/nomadkaraoke/karaoke-gen/pull/385)
+99 -2
View File
@@ -14,8 +14,30 @@ For UI that renders differently based on data (e.g., audio search result tiers),
### Filename Matching Normalization
When comparing filenames to search titles, treat underscores/hyphens/dots as word separators BEFORE stripping non-alphanumeric chars. Also require a minimum substring length (3 chars) to prevent false matches like filename "K" matching title "KoREH". For non-Latin scripts (Hebrew, etc.), return an indeterminate result rather than a false match or false mismatch.
### Autocomplete UX: Less Is More (Mar 2026)
When adding autocomplete to a multi-field form (artist + title), a single autocomplete on the **primary search field** (title) that overwrites both fields on selection is better than separate autocompletes on each field. Two autocompletes feel "janky" — they compete for attention, spam the backend with double the requests, and confuse users about which one to interact with first. Instead: plain text input for the first field (artist), autocomplete on the second field (title) that only activates when the first field is filled, and selection overwrites both fields with canonical values.
### Song Suggestions: Don't Block Input, Enhance Later (Mar 2026)
Autocomplete on the artist/title input fields confused users — it wasn't clear why they should wait for results or what selecting one would do. Better approach: let users type freely on Step 1, then show catalog suggestions **in parallel with the audio search** on Step 2 (while they're already waiting). This way suggestions feel like a helpful enhancement rather than an obstacle. Two modes work well: (1) exact match → green "Song found" panel for formatting correction, (2) no match + poor audio results → amber "Did you mean?" fuzzy correction banner.
### Fuzzy Search: Artist Tiebreaker for Title-Based Fallback (Mar 2026)
When fuzzy-matching by title returns multiple artists with the same song name (e.g. "Bruises" by Lewis Capaldi vs Fox Stevenson), use the user's garbled artist input as a tiebreaker — `stringSimilarity(userInput, track.artist_name) * 0.2` as a bonus score. Also: Spotify's `q` parameter searches track names, not artist names, so `searchCatalogTracks(artist, artist, 20)` (artist as both query and filter) returns nothing. Use `searchCatalogTracks(artist, undefined, 20)` to get the artist's tracks via general search.
### Pipeline Robustness Patterns (Mar 2026)
Three patterns from investigating production job failures where errors cascaded far from their root cause:
1. **Validate every stage's outputs, not just some** — stage 1 of audio separation had validation for expected stems, stage 2 didn't. The missing validation let a transient Modal API failure propagate through 3 more functions before crashing with a confusing NoneType error.
2. **Block impossible downstream work early** — AudioShake returning 0 lyrics segments was treated as "success", letting the user submit an empty review that only failed at CDG generation. Validate at the boundary: if transcription returns 0 segments, fail with a user-friendly error, not 4 steps later.
3. **File handles in retry loops** — when wrapping HTTP calls with retry (e.g. tenacity), ensure file handles are re-opened on each attempt. A `with open()` wrapping a retried `requests.post(files=...)` exhausts the file handle on the first attempt; subsequent retries send empty data.
---
## Infrastructure
### GCE Metadata Writes Must Be Awaited (Mar 2026)
`compute_v1.InstancesClient.set_metadata()` returns an Operation object. Without calling `.result()`, the write completes asynchronously and fingerprint conflicts from concurrent calls are swallowed silently. This caused the runner manager's `last-activity` metadata to never persist, preventing idle shutdown entirely. Always await metadata operations.
### "Set Now and Keep" Anti-Pattern (Mar 2026)
When a metadata key is missing, don't set it to "now" and skip the action — this creates an infinite loop where the key never appears old enough to trigger the action. Instead, fall back to `creationTimestamp` (always available on GCE instances) as the baseline for idle time calculation.
### Pending Jobs Guard Must Not Reset Idle Timestamps (Mar 2026)
When pending CI jobs are detected, keep runners alive but don't refresh their `last-activity` timestamps. Refreshing timestamps resets the idle timer, so runners can never accumulate enough idle time to be stopped — even after all jobs complete.
---
@@ -36,6 +58,9 @@ Audio separation and lyrics transcription run in parallel. Both can fail indepen
### GCE Instance Selection for FFmpeg
AMD EPYC (C4D series) significantly outperforms Intel Xeon (C4 series) for CPU-bound FFmpeg encoding with libass. C4D-highcpu-32 is ~5x faster than C4-standard-8. C4D requires `hyperdisk-balanced` disk type.
### Large Documents: GCS + Firestore Metadata (Mar 2026)
When a document's payload can exceed Firestore's 1MB limit (e.g., CorrectionData at 100KB+ per session), store the payload in GCS and keep only metadata in Firestore. Use SHA-256 hash deduplication to avoid re-uploading identical data. For cross-document queries (e.g., searching sessions across jobs), use Firestore collection group queries on the metadata subcollection with Python-side text filtering — Firestore doesn't support LIKE/substring queries natively.
### Queue Instead of Skip for External API Limits (Mar 2026)
When an external API has a daily quota (e.g., YouTube Data API v3's 10,000 units/day), **never silently skip** the operation when the limit is reached. Instead: (1) Track actual quota units consumed, not just operation counts — a hard "10 uploads/day" limit was far too conservative when each upload costs ~300 of 10,000 available units, (2) Queue failed operations for automatic retry when quota resets — users expected YouTube uploads and got nothing, with no notification, (3) Send follow-up notifications when deferred operations complete. **GCP Cloud Monitoring as single source of truth**: Initially we self-tracked per-operation costs in Firestore, but the estimates drifted from reality (4,493 estimated vs 2,682 actual). GCP Cloud Monitoring's `serviceruntime.googleapis.com/quota/rate/net_usage` metric has only ~7 min delay — viable as the primary data source. Use a lightweight Firestore "pending buffer" for the delay window, with entries auto-expiring after 10 min. Sum raw per-minute datapoints (no aggregation) to match the GCP Console number. Use the external API's timezone for reset calculations (YouTube resets at midnight Pacific Time, not UTC).
@@ -453,6 +478,9 @@ except Exception as e:
## Testing Insights
### New Features Must Test the Summary Projection (Mar 2026)
When adding new fields that the dashboard needs, you must add them to **both** `SUMMARY_FIELD_PATHS` (Firestore projection) and `_SUMMARY_STATE_DATA_KEYS` (Python prune allowlist). The dashboard uses `fields=summary` which projects only listed fields — any unlisted field comes back as `undefined`. Unit tests that mock the job object directly won't catch this because they bypass the projection layer entirely. **Always add a regression test** asserting the field is in `SUMMARY_FIELD_PATHS` when introducing new fields the frontend depends on. The Change Visibility feature shipped with `is_private` missing from the projection, causing the button to always show "Make Private".
### Test Webhook Handlers with Unit Tests
Webhook handlers contain critical business logic. Test exact parameters passed to service methods, not just that "something happened."
@@ -764,6 +792,9 @@ Firestore returns timezone-aware datetimes. Compare with `datetime.now(timezone.
### GCS Blob Paths vs URIs
Methods that accept paths typically want `bucket/path`, not `gs://bucket/path`.
### GCS Lifecycle Rules Can Delete Job Data
The GCS bucket has a lifecycle rule deleting objects under `uploads/` and `temp/` prefixes after 7 days. Style configuration (`style_params.json`) was stored under `uploads/{job_id}/style/` and silently disappeared for jobs not completed within a week. Fix: store job-scoped data under `jobs/` prefix (not subject to lifecycle rules), keeping `uploads/` only for genuinely temporary staging files.
### Library Caches Need GCS Sync
External library caches (like LyricsTranscriber) need explicit sync to GCS for persistence across Cloud Run instances.
@@ -789,6 +820,9 @@ When adding alternative implementations (GCE vs local encoding), audit ALL side
### External Response Validation
Add defensive type checking for all external service responses. Lists vs dicts, missing fields cause cryptic failures.
### Thread All Encoding Outputs Through OrchestratorResult (Mar 2026)
The encoding pipeline (`LocalEncodingService`) created a `(With Vocals).mp4` file (3.4x smaller than the raw MKV), but `OrchestratorResult` had no field for it so it was silently dropped. Users got the 134MB raw MKV instead of the 39MB encoded MP4. **Pattern**: When adding output files to encoding, verify the full chain: `EncodingOutput` → `OrchestratorResult` → `_upload_results()` file_mappings → Firestore `file_urls`. Also beware of hardcoded file extensions — the temp directory saved `.mkv` files as `.mov`, causing Dropbox to receive mislabeled files.
### Brand Code Allocation Must Be Atomic (Feb 2026)
Two concurrent jobs both got brand code `NOMADNP-0012` because `get_next_brand_code()` scanned Dropbox folders to find the next number — a classic TOCTOU race condition. Jobs processed 0.86s apart both saw the same state. **Fix**: `brand_code_service.py` uses Firestore transactions to atomically allocate codes. Counter doc per prefix (`NOMAD`, `NOMADNP`) with `next_number` and `recycled` pool. E2E cleanup recycles numbers via `recycle_brand_code()`.
@@ -846,6 +880,16 @@ Even with idempotent endpoints (PR #413) and basic retry logic (PR #242), jobs c
**Key insight:** Defense in depth matters. The CI drain prevents *most* conflicts, extended retries handle the *remaining edge cases*, and poll tolerance protects *jobs already in progress*. No single layer is sufficient alone.
### Deployment-Safe Encoding: Cloud Run Jobs (Mar 2026)
The three-layer defense above protects against the **GCE encoding worker** being restarted, but not against the **Cloud Run orchestrator** being killed. Job `43c0d519` (2026-03-08) got stuck because a Cloud Run Service deployment rolled out a new revision while the video worker was running as a `BackgroundTask`. Since the HTTP response had already been sent, Cloud Run treated the request as complete and killed the old instance — terminating the encoding orchestration mid-flight.
**Root cause:** `BackgroundTask` work runs after the HTTP response, so Cloud Run can kill it during deployment drain. The three-layer defense only protects the GCE worker connection, not the orchestrator's lifecycle.
**Fix:** Re-enabled Cloud Run Jobs for video encoding (`USE_CLOUD_RUN_JOBS_FOR_VIDEO=true`). This was built in PR #155 (Dec 2025) but the env var was dropped during the CI migration from `cloudbuild.yaml` to GitHub Actions. Cloud Run Jobs run to completion (up to 24h), immune to Service deployment rollouts.
**Key insight:** When migrating CI systems (cloudbuild.yaml → GitHub Actions), audit env vars carefully. A missing feature flag can silently disable critical protections. The infrastructure (Pulumi) and code existed but were inert without the env var.
---
## What We'd Do Differently
@@ -870,3 +914,56 @@ Even with idempotent endpoints (PR #413) and basic retry logic (PR #242), jobs c
3. **Cloud Run service naming matters for debugging** — The service is `karaoke-backend`, not `karaoke-gen-api`. Wrong name returns empty logs, wasting investigation time.
4. **Cross-folder gap detection needs global context** — Per-folder max misses trailing gaps when folders have different highest numbers. Use the global max across all folders as the upper bound.
### Verifying Request Bodies via Cloud Trace Request Size (2026-03-07)
**Problem:** A job was created with `is_private=true` but the user believed they selected "Published." No request body logging existed to prove what the frontend actually sent.
**Solution:** Cloud Trace captures `/http/request/size` on every span. By computing the exact byte length of the JSON body with `is_private: true` vs `is_private: false` (compact serialization, no spaces), the sizes matched exactly — 143 bytes for `true`, confirming the frontend sent `is_private: true`.
**Prevention:** Added two observability mechanisms:
1. **`creation_params`** — A dict stored on the job Firestore document capturing the user's original choices (`is_private`, `is_admin`, `created_from`). Persists forever, no log retention concerns.
2. **OTel span attributes** — `job.is_private`, `job.source`, `job_id` added to all 4 job creation endpoint spans. Searchable in Cloud Trace for 30 days.
**Key insight:** When investigating "what did the client send?", Cloud Trace request size can serve as a forensic tool even without request body logging. Compact JSON serialization (`JSON.stringify` with no spaces) is deterministic, so byte-level size matching is reliable.
### Timeline Metadata for Job Traceability (2026-03-07)
**Problem:** After shipping the "edit completed tracks" feature, tracing what happened to edited jobs was very difficult. Timeline events only had `status`, `timestamp`, `progress`, `message` — no output details. Cleanup operations (YouTube deletion, Dropbox removal) weren't logged to Firestore. Previous outputs were overwritten in `state_data` with no history. API endpoints (edit, admin-delete) logged to Cloud Run stdout but not to the job's Firestore log subcollection.
**Solution:**
1. **`TimelineEvent.metadata`** — Optional `Dict[str, Any]` field on timeline events. Completion events now capture `brand_code`, `youtube_url`, `dropbox_link`, `gdrive_file_ids`, `duration_seconds`. Edit/delete events capture `previous_outputs` and `cleanup_results`.
2. **`log_to_job()` helper** — Module-level function in `firestore_service.py` that writes to the job's Firestore log subcollection. Wraps errors silently so logging never breaks the caller. Used by API endpoints that previously only logged to stdout.
3. **Plumbed `timeline_metadata`** through `job_manager.transition_to_state()` → `firestore_service.update_job_status()`.
**Key insight:** The job's Firestore document (timeline + log subcollection) should be the single source of truth for "what happened to this job." Cloud Logging has retention limits and requires knowing which service to search. Timeline metadata makes the job self-documenting — any agent or human can read the timeline and understand the full lifecycle without cross-referencing logs.
### Store Processing Metadata When You Have It (Mar 2026)
**Problem:** During a data export for AudioShake lyrics correction feedback, we discovered that AudioShake `task_id` and `asset_id` were only held in memory during processing and never persisted. Recovery required paginating the AudioShake API and cross-referencing Cloud Logging — a multi-hour effort for data that was trivially available during processing.
**Solution:** Added `processing_metadata` as a top-level dict on the Job model, separate from `state_data` (mutable workflow state). Each worker writes its own section (transcription, separation, rendering, etc.) via `job_manager.update_processing_metadata(job_id, section, data)`, which uses Firestore dot-notation to atomically update one section without overwriting others. All metadata writes are wrapped in try/except — failures are logged but never fail jobs.
**Key insight:** "Store it when you have it." The cost of persisting a few extra fields is negligible; the cost of not having them later (log spelunking, API pagination, one-off recovery scripts) is enormous. When data flows through a worker during processing, capture the provenance metadata before it's lost. See `docs/archive/2026-03-10-store-job-processing-metadata.md` for the full design.
### Test the Contract, Not Just the Function (Mar 2026)
**Problem:** The processing metadata feature shipped with a silent bug: `_store_lyrics_processing_metadata()` expected `result["lyrics_dir"]` but `transcribe_lyrics()` never included `lyrics_dir` in its return dict. AudioShake IDs and correction stats were silently lost in production. The test suite had 24 passing tests and didn't catch it.
**Root cause (testing):** 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 provides that input. The mock was "too helpful."
**Pattern — Contract tests:** When function A calls function B with data, test both:
1. **Unit test B** with controlled input (existing approach — still valuable)
2. **Contract test** verifying A's output contains the keys B expects
For this bug, the missing test was: "does `transcribe_lyrics()` return `lyrics_dir`?" — a one-line assertion that would have caught the bug before merge.
**Broader principle:** Non-fatal code paths (try/except that swallows errors) are especially dangerous. The metadata storage was designed to never fail jobs, which is correct — but it also meant the bug was completely silent. When testing non-fatal paths, assert on the *positive outcome* (metadata was stored), not just the absence of exceptions. A test that only checks "didn't crash" provides false confidence when the code is designed to never crash.
### Static Disposable Email Lists Are Insufficient (Mar 2026)
**Problem:** A community-curated blocklist of ~5,339 disposable domains (synced from GitHub) missed 40% of disposable signups in a 4-day period. Domains like `lxbeta.com`, `nghienplus.store`, and custom `.io.vn` vanity domains slipped through because they're too niche or new to be in any static list.
**Solution:** Tiered external API checking as a fallback after the static list: DeBounce (free, catches most) → verifymail.io ($25/mo, catches niche domains the free service misses). Auto-learn persists flagged domains to `manual_domains` so each domain only requires one API call ever. Clean domains are cached for 7 days.
**Key insight:** For abuse prevention, static lists give you a floor but not a ceiling. Real-time API verification services maintain much larger and more current databases. The tiered approach (free service first, paid service only for edge cases) keeps costs minimal while dramatically improving detection. In our test of 60 recent signups, the free DeBounce API caught 6 disposable accounts and verifymail.io caught 4 more that DeBounce missed.
+19 -3
View File
@@ -26,14 +26,16 @@
| Payment flow (Stripe) | Working |
| Feedback-for-credits | Working (2+ jobs → 2 free credits) |
| Admin dashboard | Working |
| Abuse prevention & YouTube quota | Working (blocklists, quota-aware YouTube uploads) |
| Abuse prevention & YouTube quota | Working (blocklists, IP/fingerprint rate limiting, credits on verification, quota-aware YouTube uploads) |
| CI/CD self-hosted runner | Working (GCP) |
| E2E happy path test | Working (~20-25 min full pipeline) |
| **White-label B2B portals** | Working (Vocal Star, Singa) |
| **Private (non-published) tracks** | Working |
| **Custom video styling (private jobs)** | Working |
| **Song lookup autocomplete** | Working (via karaoke-decide catalog) |
| **Song suggestions & fuzzy correction** | Working (catalog lookup on Step 2 + "Did you mean?" typo correction) |
| **Community version detection** | Working (via karaokenerds.com) |
| **Review session backup/restore** | Working (auto-save + restore UI) |
| **Review reminder & auto-expiry** | Working (24h reminder, 48h cancel + refund) |
## Known Issues
@@ -45,6 +47,18 @@
## Recent Changes
- **Anti-Abuse: Credits on Verification + Rate Limiting** (2026-03-21): Three-layer defense against free credit abuse. (1) Welcome credits now granted on first magic link verification, not account creation — unverified accounts get 0 credits. (2) Per-IP signup rate limiting: max 2 new accounts per IP per 24 hours, silent reject. (3) Device fingerprinting (FingerprintJS open source): browser fingerprint sent with magic link request, combined with IP for rate limiting. Either signal hitting 2/day triggers block. Returning users are never rate limited. Graceful degradation if fingerprinting fails. Frontend verify page shows "You received N free credits" on first login. See [archive/2026-03-21-anti-abuse-credits.plan.md](archive/2026-03-21-anti-abuse-credits.plan.md).
- **Review Reminder & Auto-Expiry** (2026-03-19): Jobs stuck in review (`awaiting_review` / `in_review`) now get automatic cleanup. At 24 hours, a gentle reminder email is sent with a review link, help offer, and warning. At 48 hours, the job is auto-cancelled and the user's credit is refunded. Expiry notification email confirms the refund and current balance. Excludes made-for-you and tenant jobs. Powered by hourly Cloud Scheduler cron (`stale-review-hourly`). New endpoint: `POST /api/internal/process-stale-reviews`. Also fixed `make test` hanging on frontend Playwright E2E tests by splitting into `test-frontend` (Jest unit only) and `test-frontend-e2e` (Playwright, run manually). See [archive/2026-03-19-review-reminder-autoexpiry.plan.md](archive/2026-03-19-review-reminder-autoexpiry.plan.md).
- **Step 2 Song Suggestions & Fuzzy Correction** (2026-03-08): Replaced the Step 1 autocomplete with a simpler approach: plain text inputs on Step 1, then catalog lookup + community version check fire in parallel with the audio search on Step 2. Results appear as a "Song found in our database" panel (exact match) or correction suggestion panel while the user waits. Added fuzzy "Did you mean?" correction — when audio search returns poor results (Tier 3) and catalog has no exact title match, fetches the artist's discography and fuzzy-matches against the user's title using LCS similarity. Shows an amber banner with one-click correction + expandable alternatives list. Handles garbled artist fields via title-based fallback with artist tiebreaker. Visibility step reworked with action buttons at top for one-click select+continue. See [archive/2026-03-08-step2-song-suggestions.plan.md](archive/2026-03-08-step2-song-suggestions.plan.md) and [archive/2026-03-08-fuzzy-did-you-mean.plan.md](archive/2026-03-08-fuzzy-did-you-mean.plan.md).
- **Review Session Backup/Restore** (2026-03-08): Server-side auto-save of lyrics review sessions replaces fragile localStorage-only mechanism. Sessions auto-save every 60s (if dirty), on preview video generation, and on page unload. Deduplication via SHA-256 hash prevents redundant saves. Correction data stored in GCS (can exceed Firestore's 1MB doc limit); metadata in Firestore subcollection (`jobs/{jobId}/review_sessions/{sessionId}`). Restore UI shows split-pane session browser with edit diff preview. Cross-job session search allows reusing edits across different jobs (with duration mismatch warning). On load, automatically prompts to restore if saved sessions exist. See [archive/2026-03-07-lyrics-review-sessions-plan.md](archive/2026-03-07-lyrics-review-sessions-plan.md).
- **Job Observability Improvements** (2026-03-07): Enhanced timeline events with a `metadata` field to capture structured output details (brand codes, YouTube video IDs, Dropbox paths, GDrive file IDs) at key moments — job completion, edit initiation, and admin output deletion. Added `log_to_job()` helper for API endpoints to write to Firestore job log subcollections (previously only workers logged there). Edit and admin-delete endpoints now snapshot previous outputs before cleanup and log each cleanup step. Distribution logging enhanced with video IDs, folder paths, and file IDs. See [plans/improve-job-observability.plan.md](../.claude/plans/improve-job-observability.plan.md).
- **Edit Completed Tracks** (2026-03-06): Users can now edit completed karaoke tracks — correcting lyrics, changing instrumental selection, or updating artist/title metadata — without consuming additional credits. Clicking "Edit" on a completed job opens a confirmation modal (with optional artist/title editing), then cleans up all distributed outputs (YouTube video deleted, Dropbox folder removed, GDrive files deleted, GCS finals purged, brand code recycled), resets the job to `awaiting_review`, and redirects to the existing review screen. After re-review, the standard pipeline re-renders and re-distributes with a fresh brand code. New endpoint: `POST /api/jobs/{job_id}/edit`. New Job model field: `edit_count`. State machine updated: `COMPLETE → AWAITING_REVIEW` transition allowed. See [archive/2026-03-06-edit-completed-tracks-plan.md](archive/2026-03-06-edit-completed-tracks-plan.md) and [API.md](API.md#edit-completed-track).
- **Change Visibility** (2026-03-06): Users can now toggle completed jobs between public and private via a "Make Public"/"Make Private" button on the job card. Two distinct flows: Public→Private is fast (~1-2 min, redistributes existing finals), Private→Public is slow (~15-30 min, resets styles to Nomad theme, regenerates screens, re-renders video). Confirmation modal explains the implications. Tenant jobs excluded. See [archive/2026-03-06-change-visibility-plan.md](archive/2026-03-06-change-visibility-plan.md) and [API.md](API.md#change-visibility).
- **Tenant Portal UI Rework** (2026-03-04): Replaced the multi-step consumer wizard with a streamlined 4-field form (Artist, Title, Mixed Audio, Instrumental Audio) for B2B tenant portals. Vocal Star's portal now uses the new `TenantJobFlow` component instead of `GuidedJobFlow`. All tenant jobs are automatically private with tenant-specific distribution: Dropbox delivery to `/MediaUnsynced/Karaoke/Tracks-VocalStar`, Google Drive upload to tenant folder, VSTAR brand prefix. Backend adds `_apply_tenant_overrides()` helper that forces private, applies locked theme, and overlays tenant distribution settings. Private tenant jobs now use their own Dropbox/GDrive paths instead of the NonPublished override. Frontend conditionally renders `TenantJobFlow` vs `GuidedJobFlow` based on tenant detection. See [archive/2026-03-04-tenant-portal-ui-rework.md](archive/2026-03-04-tenant-portal-ui-rework.md).
@@ -84,6 +98,8 @@
- **Custom Instrumental Upload Fix** (2026-02-26): Fixed critical bug where uploaded custom instrumentals were ignored during encoding — GCE encoding worker and orchestrator had no `"custom"` case, falling back to clean instrumental instead. Upload endpoint now converts all formats to FLAC for pipeline consistency. Three fixes: (1) GCE encoding worker `find_file` now searches for `custom_instrumental*.flac` when selection is `"custom"`, (2) orchestrator config constructs correct `(Instrumental Custom).flac` path, (3) upload endpoint converts mp3/m4a/wav/etc. to FLAC before storing. Added 10 new regression tests for GCE resolution and orchestrator paths. See [API.md](API.md#upload-custom-instrumental).
- **Store Processing Metadata Permanently** (2026-03-10): Added `processing_metadata` field to the Job model — a top-level dict where each worker writes immutable provenance data during processing. Stores AudioShake task_id/asset_id (the original ask — these were previously lost after processing), worker timing, separation model names, ffprobe audio properties, correction stats, cache hit/miss data, video encoding details, and auth context at job creation. All metadata writes are non-fatal (wrapped in try/except). Includes `update_processing_metadata` helper on JobManager using Firestore dot-notation for atomic section updates. 23 tests covering model, helpers, all worker functions, and a SUMMARY_FIELD_PATHS regression guard. See [archive/2026-03-10-store-job-processing-metadata.md](archive/2026-03-10-store-job-processing-metadata.md) and [LESSONS-LEARNED.md](LESSONS-LEARNED.md#store-processing-metadata-when-you-have-it-mar-2026).
- **Custom Instrumental Upload** (2026-02-25): Added `POST /api/jobs/{job_id}/upload-instrumental` endpoint — was missing from backend, causing 404 in production when users tried to upload custom instrumental files during review. Validates uploaded audio duration matches original (±0.5s tolerance) using ffprobe on GCS signed URLs. Fixed frontend bug where "uploaded" selection type was sent to API instead of "custom" (the only value the backend accepts). Added 22 tests covering upload validation, duration checks, and frontend/backend contract. See [API.md](API.md#upload-custom-instrumental).
- **Unicode Filename Fix** (2026-02-04): Fixed FFmpeg failures (exit code 183) when processing songs with non-ASCII characters in titles. Job `1eab1172` with Russian title "я куплю тебе дом" failed because Python's `str.isalnum()` returns True for ALL Unicode alphanumeric characters (Cyrillic, Arabic, Chinese, emoji, etc.), not just ASCII. These Unicode characters in temp subtitle file paths (`temp_subtitles_zivert___я_куплю_тебе_дом_1770150285852.ass`) caused FFmpeg to fail. **Fix**: Changed filename sanitization from `c.isalnum()` to `c.isascii() and c.isalnum()` in three locations: `video.py:222` (generate_video), `video.py:282` (generate_preview_video), and `remote_cli.py:1970` (output folders). Added comprehensive test suite covering Cyrillic, Chinese, Arabic, emoji, and accented characters. See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#unicode-in-file-paths-feb-2026).
@@ -124,7 +140,7 @@
- **Fast Preview Video Option** (2026-01-10): Added toggle in lyrics review UI to render preview videos with black background (~10s) instead of theme background image (~30-60s). Default is now black background for faster iteration during review. Users can enable theme background via checkbox when they want to verify the final look. See [API.md](API.md#generate-preview).
- **Frontend Consolidation** (2026-01-09): Consolidated three separate frontends into a single Next.js application. Previously: (1) Main frontend (Next.js + Tailwind), (2) Lyrics Review (React + Vite + MUI, ~14k lines), and (3) Instrumental Review (vanilla HTML/JS, ~1.7k lines) were deployed separately. Now all UIs are unified in the main frontend at `/app/jobs/{id}/review` and `/app/jobs/{id}/instrumental`. Benefits: single deployment to Cloudflare Pages, no external redirects during user workflows, unified design system (Radix/Tailwind), simpler authentication via job ownership model. See [archive/2026-01-09-frontend-consolidation-plan.md](archive/2026-01-09-frontend-consolidation-plan.md) and [tasks/](tasks/).
- **Frontend Consolidation** (2026-01-09): Consolidated three separate frontends into a single Next.js application. Previously: (1) Main frontend (Next.js + Tailwind), (2) Lyrics Review (React + Vite + MUI, ~14k lines), and (3) Instrumental Review (vanilla HTML/JS, ~1.7k lines) were deployed separately. Now all UIs are unified in the main frontend at `/app/jobs#/{id}/review` and `/app/jobs#/{id}/instrumental`. Benefits: single deployment to Cloudflare Pages, no external redirects during user workflows, unified design system (Radix/Tailwind), simpler authentication via job ownership model. See [archive/2026-01-09-frontend-consolidation-plan.md](archive/2026-01-09-frontend-consolidation-plan.md) and [tasks/](tasks/).
- **Admin Login Token for Made-For-You Orders** (2026-01-10): Added one-click admin login via email. When a made-for-you order is placed, the admin notification email now includes a direct link with an embedded login token (`?admin_token=TOKEN`). Clicking this link auto-authenticates the admin and opens the job directly - no manual login required. Tokens expire after 24 hours. Also added: BCC to `done@nomadkaraoke.com` on all job completion emails, fixed timezone display (EST→ET for DST correctness). See [API.md](API.md#verify-magic-link).
+261
View File
@@ -0,0 +1,261 @@
# Self-Hosted GitHub Actions Runners
Single source of truth for how Nomad Karaoke CI/CD runners work — architecture, cost model, auto-scaling, and troubleshooting.
## Why Self-Hosted Runners?
GitHub-hosted runners work but are slower (2 vCPU, 7GB RAM) and costs scale linearly with CI minutes. Self-hosted runners on GCP give us:
- **Faster builds** — persistent Docker caches, more CPU/RAM
- **GPU access** — T4 GPUs for audio separation model testing
- **Scale-to-zero** — runners shut down automatically when idle, so we only pay for active CI time
- **Dedicated build runner** — 8 vCPU for Docker image builds
## Architecture
```
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ GitHub Webhook │────>│ Cloud Function │────>│ Start Runner │
│ (workflow_job) │ │ (runner-manager) │ │ VMs │
└─────────────────┘ └──────────────────┘ └─────────────────┘
│
v
┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Cloud Scheduler│────>│ Cloud Function │────>│ Stop Idle │
│ (every 15 min) │ │ (runner-manager) │ │ Runner VMs │
└─────────────────┘ └──────────────────┘ └─────────────────┘
```
### Components
| Component | Spec | Purpose |
|-----------|------|---------|
| General runners | 3x `github-runner-{1..3}`, `e2-standard-4`, 200GB SSD | Execute CI jobs (lint, test, type check, build) |
| Build runner | 1x `github-build-runner`, `e2-standard-8`, 200GB SSD | Docker image builds (needs more CPU/RAM) |
| GPU runners | 3x `github-gpu-runner-{1..3}`, `n1-standard-4` + T4 GPU, 200GB SSD | Audio separation model testing |
| Cloud Function | `github-runner-manager`, Gen2, Python 3.12, 5min timeout | Start/stop VMs based on webhooks and idle checks |
| Cloud Scheduler | `runner-manager-idle-check`, every 15 min | Trigger idle runner checks |
| Cloud NAT | `github-runners-nat` + `github-runners-router` | Outbound internet for VMs (no external IPs) |
All runner VMs are in `us-central1-a`.
### Service Accounts
| Account | Purpose | Key Permissions |
|---------|---------|-----------------|
| `github-runner` | Runner VMs | `artifactregistry.reader`, `secretmanager.secretAccessor` |
| `runner-manager` | Cloud Function | `compute.instanceAdmin.v1`, `iam.serviceAccountUser` on `github-runner`, secret access |
| `runner-manager-scheduler` | Cloud Scheduler | `cloudfunctions.invoker` on the function |
### Runner Labels
| Label Set | VMs | Used By |
|-----------|-----|---------|
| `[self-hosted, linux, x64, gcp, large-disk]` | general runners | Most CI jobs |
| `[self-hosted, linux, x64, gcp, large-disk, docker-build]` | build runner | Docker image builds |
| `[self-hosted, linux, x64, gcp, gpu]` | GPU runners | Audio separation tests |
## How Auto-Scaling Works
### Starting Runners (Webhook-Driven)
1. Developer pushes code or opens a PR
2. GitHub Actions queues CI jobs with labels `[self-hosted, linux, gcp]`
3. GitHub sends a `workflow_job.queued` webhook to the Cloud Function
4. The function iterates over all runner VM names (from `RUNNER_NAMES` env var)
5. Any TERMINATED VMs are started in parallel via `ThreadPoolExecutor`
6. If VMs are in STOPPING state (from an overlapping idle shutdown), the function polls until they become TERMINATED (up to 90s), then starts them
7. VMs boot in ~2-3 minutes, run the startup script, register with GitHub, and pick up queued jobs
### Tracking Activity (Metadata-Based)
When a job completes, GitHub sends a `workflow_job.completed` webhook. The function updates a `last-activity` metadata key on the **specific runner** that ran the job (identified by `runner_name` from the webhook payload). Only updating the specific runner avoids fingerprint conflicts from concurrent webhook calls.
### Stopping Idle Runners (Scheduler-Driven)
Every 15 minutes, Cloud Scheduler triggers the function with `?action=check_idle`:
1. **Check for pending work:** Query GitHub API for queued/in-progress runs. If anything is pending, keep all runners alive (but do NOT refresh timestamps — that would reset idle tracking).
2. **Check each runner's idle time:** For each RUNNING VM, read `last-activity` metadata. If missing, fall back to `creationTimestamp` (the VM's creation date).
3. **Stop idle runners:** Any runner idle for 1+ hour is queued for shutdown. All stops execute in parallel to minimize the race window.
### The Race Condition (and How We Handle It)
During active development, new work can arrive while the idle check is shutting down runners:
- **Idle check** fires all stop operations in parallel (~60s window)
- **Webhook** arrives with new `workflow_job.queued` event
- **start_runners** finds some VMs in `STOPPING` state
Solution: `start_runners()` detects STOPPING VMs and **polls them every 5 seconds** (up to 90s) until they become TERMINATED, then starts them immediately.
## Cost Model
### Monthly Estimates
| Scenario | Runner Uptime | Monthly Cost |
|----------|---------------|--------------|
| Active development (8h/day) | ~10-12h/day | ~$100-150 |
| Light usage (solo dev) | ~3-5h/day | ~$50-80 |
| No activity (all stopped) | 0h | ~$35 (NAT + scheduler only) |
### Fixed Costs
| Component | Monthly Cost |
|-----------|-------------|
| Cloud NAT | ~$30 |
| Cloud Scheduler | <$1 |
| Cloud Function | <$5 |
| **Total fixed** | **~$35** |
### Variable Costs
| VM Type | Hourly Cost | 24/7 Monthly |
|---------|-------------|--------------|
| e2-standard-4 (general) × 3 | $0.402 | $289 |
| e2-standard-8 (build) × 1 | $0.268 | $193 |
| n1-standard-4 + T4 (GPU) × 3 | $1.62 | $1,166 |
| **All 7 VMs** | **$2.29/hr** | **$1,648** |
This is why idle shutdown is critical — the difference between working and broken auto-scaling is ~$1,600/month.
## Historical Bugs and Fixes (March 2026)
The initial runner manager implementation had several bugs that prevented idle shutdown. Runners were running 24/7 for weeks, wasting ~$1,600/month of GCP credits.
### Bug 1: Metadata Writes Not Awaited
**Problem:** `client.set_metadata()` returns an Operation object. Without calling `.result()`, the write completes asynchronously and fingerprint conflicts from concurrent calls are swallowed silently. `last-activity` metadata never persisted.
**Fix:** Added `operation.result(timeout=60)` to all metadata writes.
### Bug 2: "Set Now and Keep" Infinite Loop
**Problem:** When `last-activity` was missing, the function set it to "now" and kept the runner. Since the metadata write failed silently (Bug 1), every 15-minute idle check repeated: "No last-activity metadata, setting now" → keeps running → forever.
**Fix:** Use `creationTimestamp` as fallback instead of "now". VMs without metadata are treated as having been idle since creation.
### Bug 3: Pending Jobs Reset All Timestamps
**Problem:** When any queued run existed, the function refreshed `last-activity` on ALL runners. This reset idle tracking so runners could never accumulate enough idle time to be stopped.
**Fix:** When jobs are pending, keep runners alive but do NOT refresh timestamps.
### Bug 4: Missing IAM Permission
**Problem:** The `runner-manager` SA needed `iam.serviceAccountUser` on the `github-runner` SA to set metadata on VMs running as that account. Without it, metadata writes failed with `SERVICE_ACCOUNT_ACCESS_DENIED`.
**Fix:** Added `roles/iam.serviceAccountUser` binding in Pulumi.
### Bug 5: No STOPPING State Handling
**Problem:** VMs in STOPPING state (from an overlapping idle check) were skipped by `start_runners()`, potentially leaving all runners unreachable.
**Fix:** Poll STOPPING VMs until they become TERMINATED (up to 90s), then start them.
### Bug 6: Sequential Stops
**Problem:** Stopping VMs one at a time created a wide race window where new webhooks could overlap.
**Fix:** Stop all idle VMs in parallel using `ThreadPoolExecutor`.
### Bug 7: All Runners Updated on Job Completion
**Problem:** `in_progress` and `completed` webhooks updated metadata on ALL running instances, causing fingerprint conflicts when multiple jobs completed simultaneously.
**Fix:** Only update the specific runner identified by `runner_name` in the webhook payload. Removed the `in_progress` handler entirely.
### Bug 8: Flaky "docker: command not found" (Exit Code 127)
**Problem:** Backend Emulator Integration Tests intermittently failed with `docker: command not found` (exit code 127). Re-running the job always succeeded. Root cause: When a stopped VM restarts, the GHA runner systemd service (installed via `svc.sh install` on a previous boot) auto-starts immediately, accepting CI jobs before the GCE startup script has finished setting up Docker and other dependencies.
**Fix (two-part):**
1. **Startup script:** Stop the runner service at the very top of the script, before any package installations, preventing premature job acceptance.
2. **CI workflow:** Added a Docker readiness check step with 60-second retry loop in `backend-emulator-tests`, providing defense-in-depth.
## Troubleshooting
### Runners Not Starting
```bash
# 1. Check VM status
gcloud compute instances list --filter="name~github-runner" --format="table(name,status)" --project=nomadkaraoke
# 2. Check GitHub registration
gh api /orgs/nomadkaraoke/actions/runners --jq '.runners[] | {name, status, busy}'
# 3. Check Cloud Function logs
gcloud functions logs read github-runner-manager --limit=20 --gen2 --region=us-central1 --project=nomadkaraoke
# 4. Manual start if needed
gcloud compute instances start github-runner-{1..3} github-build-runner --zone=us-central1-a --project=nomadkaraoke
```
### Runners Not Stopping
```bash
# 1. Check last-activity metadata
for i in 1 2 3; do
echo -n "github-runner-$i: "
gcloud compute instances describe "github-runner-$i" --zone=us-central1-a --project=nomadkaraoke \
--format="json(metadata.items)" | python3 -c "
import sys,json; items=json.load(sys.stdin).get('metadata',{}).get('items',[])
[print(i['value']) for i in items if i['key']=='last-activity']" 2>/dev/null || echo "no metadata"
done
# 2. Check for pending jobs
gh run list --limit 5 --json status,name --repo nomadkaraoke/karaoke-gen
# 3. Check function logs for idle check results
gcloud functions logs read github-runner-manager --limit=30 --gen2 --region=us-central1 --project=nomadkaraoke | grep -E "(Scheduler|idle|stop|pending)"
```
**Common causes:**
- `last-activity` metadata not being set (check for IAM errors in function logs)
- Scheduled workflows sending `workflow_job.queued` events
- Function timeout exceeded
### Webhook Not Triggering
1. Check https://github.com/organizations/nomadkaraoke/settings/hooks
2. Look at "Recent Deliveries" for the Cloud Function webhook
3. Common issues: secret mismatch, function URL changed after deploy
## Infrastructure Files
| File | Purpose |
|------|---------|
| `infrastructure/config.py` | `NUM_GITHUB_RUNNERS`, `NUM_GPU_RUNNERS`, `RunnerManagerConfig` |
| `infrastructure/compute/github_runners.py` | VM instances, Cloud NAT |
| `infrastructure/modules/runner_manager.py` | Cloud Function, Cloud Scheduler, IAM bindings |
| `infrastructure/functions/runner_manager/main.py` | Cloud Function code (webhook handler, idle check) |
| `infrastructure/compute/startup_scripts/github_runner.sh` | General runner VM bootstrap |
| `infrastructure/compute/startup_scripts/github_runner_gpu.sh` | GPU runner VM bootstrap |
## Secrets
| Secret | Purpose | Rotation |
|--------|---------|----------|
| `github-runner-pat` | Runner registration (PAT with `admin:org` > `manage_runners:org`) | Create new PAT, update secret, reset VMs |
| `github-webhook-secret` | Webhook signature verification | Generate new hex, update secret + GitHub webhook config |
## Manual Operations
### Starting / Stopping All Runners
```bash
# Start all
gcloud compute instances start github-runner-{1..3} github-build-runner github-gpu-runner-{1..3} --zone=us-central1-a --project=nomadkaraoke
# Stop all
gcloud compute instances stop github-runner-{1..3} github-build-runner github-gpu-runner-{1..3} --zone=us-central1-a --project=nomadkaraoke
```
### Verifying Auto-Stop Works
```bash
# After last CI job completes, wait 1+ hour, then check:
gcloud compute instances list --filter="name~github-runner OR name~github-build OR name~github-gpu" \
--format="table(name,status)" --project=nomadkaraoke
# Expected: all TERMINATED
```
+31 -1
View File
@@ -182,6 +182,36 @@ mock_service.update_job.return_value = None # Match real API
**Before writing a mock**, check the actual method's return type. Void methods should mock `return_value = None`. Methods that raise on error (rather than returning False) should have mocks that raise exceptions for error cases. See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#mocks-must-match-real-return-values-feb-2026) for a production bug caused by this.
**Critical: Test the Contract Between Caller and Callee**
When function A calls function B, it's not enough to test B with hand-crafted ideal inputs. You must also verify A actually produces those inputs. This is a "contract test."
```python
# ❌ BAD: Tests _store_metadata in isolation with hand-crafted input
# If transcribe_lyrics() never includes "lyrics_dir", this test still passes
# but production silently loses all metadata
def test_stores_audioshake_ids(tmp_path):
_store_lyrics_processing_metadata(
transcription_result={"lyrics_dir": str(tmp_path)}, # Too helpful!
...
)
assert call_args["audioshake_task_id"] == "task-abc" # ✅ passes, but useless
# ✅ GOOD: Also test that the caller produces the expected input
def test_transcribe_lyrics_returns_lyrics_dir(tmp_path):
result = processor.transcribe_lyrics(audio, artist, title, tmp_path)
assert "lyrics_dir" in result # Catches the actual bug
```
**When to write contract tests:**
- Function A builds a dict/object and passes it to function B
- Function B reads specific keys/fields from that dict/object
- The dict/object shape is implicit (no schema, no TypedDict, no dataclass)
**Especially dangerous:** Non-fatal code paths (try/except that swallows errors). If the function is designed to never crash, a test that only checks "didn't raise" provides zero signal. Assert on the *positive outcome* (data was stored, value was returned) not just the absence of exceptions.
See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#test-the-contract-not-just-the-function-mar-2026) for the production bug this pattern caused.
### Integration Tests (`tests/integration/`)
**Purpose:** Test CLI workflows and component interactions.
@@ -495,7 +525,7 @@ async function debug() {
const page = await browser.newContext().then(c => c.newPage());
await page.addInitScript(t => localStorage.setItem('karaoke_access_token', t), TOKEN);
await page.goto(`https://gen.nomadkaraoke.com/app/jobs/${JOB_ID}/review/`);
await page.goto(`https://gen.nomadkaraoke.com/app/jobs#/${JOB_ID}/review`);
// Debug interactively - the browser stays open
await page.pause(); // Opens Playwright inspector
+31 -1
View File
@@ -56,7 +56,7 @@ curl -X POST "https://api.nomadkaraoke.com/api/internal/workers/video" \
**Note:** SSH-restarting the encoding worker is **not needed** since v0.119.6 (PR #413). The `/encode` endpoint is now idempotent — re-triggering the video worker is sufficient.
**Prevention (since v0.126.2):** CI now performs a graceful drain before restarting the encoding worker — it waits for active jobs to finish (up to 10 min). Additionally, the encoding client retries for ~90s (up from ~14s), and status polling tolerates up to 5 consecutive failures. These three layers together should prevent this issue from recurring.
**Prevention:** The video worker now runs as a **Cloud Run Job** (`USE_CLOUD_RUN_JOBS_FOR_VIDEO=true`), which runs to completion and is immune to Cloud Run Service deployment rollouts. This replaces the `BackgroundTask` pattern that was vulnerable to instance termination during deployments. Additionally, CI performs a graceful drain before restarting the GCE encoding worker, the encoding client retries for ~90s, and status polling tolerates up to 5 consecutive failures.
---
@@ -136,3 +136,33 @@ python scripts/backfill_gdrive_uploads.py --all-missing
# Specific jobs
python scripts/backfill_gdrive_uploads.py --job-ids JOB1,JOB2
```
---
## Job failed: "CDG generation was enabled but failed"
**Cause:** The LRC file has no lyrics content (just metadata like `[re:MidiCo]`). This happens when AudioShake returns 0 segments — typically because the input audio has no vocals (e.g. user uploaded a karaoke track).
**Fix (v0.135+):** The video orchestrator now skips CDG/TXT gracefully when the LRC has no content. The `complete_review` endpoint also blocks 0-segment submissions with a user-friendly error, and the frontend shows a warning with guidance.
**For older jobs:** Retry won't help unless the user provides different audio or pastes lyrics manually via "Replace All".
---
## Job failed: "Audio separation failed: expected str, bytes or os.PathLike object, not NoneType"
**Cause:** Modal API intermittently returned fewer stems than expected from stage 2 (backing vocals) separation. Missing stems caused NoneType crashes in downstream processing.
**Fix (v0.135+):** Stage 2 now validates that all expected stems are present (matching existing stage 1 validation). Defensive null checks prevent confusing TypeError messages. Full tracebacks are logged with `exc_info=True`.
**Recovery:** Retry the job — the failure is transient (Modal API intermittent). Long-term fix: migrate audio separation from Modal to GCP (see `docs/archive/2026-03-21-modal-to-gcp-migration-plan.md`).
---
## Job failed: "Lyrics transcription failed: 502 Server Error: Bad Gateway for url: https://api.audioshake.ai/tasks"
**Cause:** AudioShake API returned a transient 5xx error.
**Fix (v0.135+):** AudioShake API calls now retry up to 5 times with exponential backoff (60s base, 3x multiplier, ~40 minutes total spread). Retries on 5xx, 429, connection errors, and timeouts.
**For older jobs:** Simply retry the job via admin dashboard.
@@ -0,0 +1,262 @@
# Edit Completed Tracks — Implementation Plan
> Created: 2026-03-06
> Branch: feat/sess-20260306-1705-edit-completed-tracks
## Overview
Allow users to edit completed karaoke tracks — correcting lyrics, changing instrumental selection, or updating artist/title metadata — without consuming additional credits. The existing outputs are cleaned up (YouTube, Dropbox, GDrive, GCS) before re-opening the review screens, and a fresh brand code is allocated when the edited track is re-distributed.
## Design Decisions
| Decision | Answer |
|----------|--------|
| Brand code on edit | New code allocated (old one recycled) |
| Credit cost | Free (credit already consumed at job creation) |
| Edit limit | None |
| Metadata edits (artist/title) | Supported via confirmation modal |
| UX approach | Reopen review on same job (approach A) |
## User Flow
```
Completed job detail page
→ User clicks "Edit Track"
→ Confirmation modal appears:
- Explains: existing outputs will be deleted, track re-rendered after review
- Asks: "Do you need to update the artist or title?"
- If yes: shows editable artist/title input fields (pre-filled)
- If no: fields hidden
- [Cancel] [Confirm & Edit]
→ On confirm:
- Frontend calls POST /api/jobs/{job_id}/edit
- Backend: cleanup outputs → reset state → issue review token
- Frontend redirects to review screen (/app/jobs#/{jobId}/review)
→ User edits lyrics / instrumental as usual
→ User submits review
→ Standard pipeline: render → encode → distribute (new brand code)
→ Job returns to COMPLETE with fresh outputs
```
## Implementation
### Phase 1: Backend — Edit Endpoint
**New endpoint: `POST /api/jobs/{job_id}/edit`**
File: `backend/api/routes/jobs.py` (or new `backend/api/routes/edit.py`)
Request body:
```json
{
"artist": "Updated Artist", // optional, only if user wants to change
"title": "Updated Title" // optional, only if user wants to change
}
```
Auth: Job owner (via session token) OR admin.
Logic:
1. **Validate** job is in `COMPLETE` state and user owns it
2. **Validate** `outputs_deleted_at` is not set (prevent editing already-in-progress edits)
3. **Cleanup distributed outputs** (reuse logic from admin `delete-outputs`):
a. Delete YouTube video (if exists)
b. Delete Dropbox folder (if exists)
c. Delete Google Drive files (if exists)
d. Delete GCS `finals/` folder
e. Recycle brand code (if Dropbox + GDrive both succeeded)
f. Clear state_data keys: `youtube_url`, `youtube_video_id`, `brand_code`, `dropbox_link`, `gdrive_files`
g. Set `outputs_deleted_at` + `outputs_deleted_by`
4. **Update metadata** (if provided):
a. Update `artist` and/or `title` fields on the job
b. If metadata changed: delete existing screen files from GCS (`screens/` folder)
c. Clear `screens_progress` from state_data so screens worker re-runs
5. **Reset processing state**:
a. Clear state_data keys: `render_progress`, `video_progress`, `encoding_progress`, `review_complete`
b. Keep: `audio_complete`, `lyrics_complete`, `corrected_lyrics`, `instrumental_selection`, `instrumental_options`
c. Keep all stems and lyrics files in GCS
6. **Transition state**: `COMPLETE` → `AWAITING_REVIEW`
7. **Issue review token**: Generate new `review_token` with expiration
8. **Increment edit counter**: `edit_count += 1` (new field)
9. **Log timeline event**: `"Track edit initiated by {user_email} (edit #{edit_count})"`
10. **Return** review URL + token
Response:
```json
{
"review_url": "/app/jobs#/{jobId}/review",
"review_token": "abc123..."
}
```
**Error cases:**
- Job not in COMPLETE state → 400
- User doesn't own job → 403
- Cleanup fails critically (Dropbox folder still exists) → 500, don't reset state
- Job already being edited (status != COMPLETE) → 400
### Phase 2: Backend — State Machine Updates
File: `backend/models/job.py`
1. Add `COMPLETE → AWAITING_REVIEW` to `STATE_TRANSITIONS` dict (conditional on edit endpoint)
2. Add new field to Job model:
```python
edit_count: int = 0
```
### Phase 3: Backend — Post-Review Pipeline Adjustments
File: `backend/workers/screens_worker.py`
- When triggered after an edit with metadata changes, screens worker already handles regeneration
- The edit endpoint clears `screens_progress` and deletes screen files, so screens worker will re-run naturally
- No changes needed if screens worker already checks for missing screen files
File: `backend/workers/render_video_worker.py`
- No changes needed — render worker reads current `corrected_lyrics` and `instrumental_selection` from state_data
- Will pick up whatever the user selected during re-review
File: `backend/workers/video_worker_orchestrator.py`
- Already clears `outputs_deleted_at` after successful distribution (lines 564-578)
- Already allocates new brand code via `allocate_brand_code()` during distribution
- No changes needed
### Phase 4: Frontend — Edit Button + Confirmation Modal
**Edit button on completed job view**
File: `frontend/app/app/jobs/[[...slug]]/client.tsx` (or wherever job detail is rendered)
- Show "Edit Track" button only when job status is `complete`
- Button opens the confirmation modal
**Confirmation modal component**
New file: `frontend/components/job/EditTrackModal.tsx`
Content:
- Warning text: "This will remove your current video from YouTube, Dropbox, and Google Drive. After you complete the review again, a new version will be rendered and re-distributed."
- Toggle/checkbox: "I need to update the artist or title"
- When checked, show:
- Artist input (pre-filled with current `job.artist`)
- Title input (pre-filled with current `job.title`)
- [Cancel] button
- [Confirm & Edit] button → calls API, shows loading state, redirects to review on success
**API call**
File: `frontend/lib/api.ts`
Add:
```typescript
editCompletedTrack(jobId: string, updates?: { artist?: string; title?: string }): Promise<{ review_url: string; review_token: string }>
```
### Phase 5: Frontend — Review Screen Adjustments
File: `frontend/app/app/jobs/[[...slug]]/client.tsx` (JobRouterClient)
- Currently only renders review screens for `AWAITING_REVIEW` / `IN_REVIEW` states — this already works
- The edit endpoint transitions the job to `AWAITING_REVIEW`, so existing routing handles it
**One adjustment needed:** If the user edited metadata (artist/title), the screens worker needs to run before or after review. Two options:
- **Option A (simpler):** Edit endpoint triggers screens worker immediately after resetting state. Screens regenerate in background while user reviews lyrics. By the time review is submitted, screens should be ready. The existing coordination logic (screens_progress check) handles this.
- **Option B:** Defer screen regeneration to after review submission, same as initial flow. Slightly slower end-to-end but no parallel coordination concerns.
**Recommendation:** Option A — trigger screens worker during edit if metadata changed. The 30-second screen generation will finish well before the user completes their review edits.
### Phase 6: Testing
**Backend unit tests:**
- `test_edit_completed_track.py`:
- Happy path: COMPLETE job → edit → state becomes AWAITING_REVIEW
- With metadata: artist/title updated, screens cleared
- Without metadata: artist/title unchanged, screens preserved
- Auth: owner can edit, non-owner gets 403
- State guard: non-COMPLETE jobs rejected
- Cleanup: verify YouTube/Dropbox/GDrive/GCS deletion called
- Brand code: verify recycled during cleanup
- Edit count: incremented correctly
- Timeline: event logged
**Frontend tests:**
- EditTrackModal renders correctly
- Toggle shows/hides metadata fields
- Confirm calls API with correct payload
- Loading state during API call
- Redirect to review on success
- Error display on failure
**E2E production test:**
- Create job → complete → edit → re-review → verify new outputs
## Files to Create/Modify
### New Files
- `frontend/components/job/EditTrackModal.tsx` — Confirmation modal
- `backend/tests/test_edit_completed_track.py` — Backend tests
### Modified Files
- `backend/api/routes/jobs.py` — Add edit endpoint (or create `edit.py`)
- `backend/models/job.py` — Add `edit_count` field, update STATE_TRANSITIONS
- `frontend/lib/api.ts` — Add `editCompletedTrack()` method
- `frontend/app/app/jobs/[[...slug]]/client.tsx` — Add Edit button to completed job view
### No Changes Needed
- `backend/workers/render_video_worker.py` — Already reads current state_data
- `backend/workers/video_worker_orchestrator.py` — Already allocates new brand code, clears outputs_deleted_at
- `backend/workers/screens_worker.py` — Already handles missing screens
- `backend/services/brand_code_service.py` — Allocation/recycling already works
- `frontend/components/lyrics-review/LyricsAnalyzer.tsx` — Reused as-is
- `frontend/components/instrumental-review/InstrumentalSelector.tsx` — Reused as-is
## Sequence Diagram
```
User Frontend Backend Workers
| | | |
|-- Click "Edit" ----->| | |
| |-- Show modal ------->| |
|-- Confirm edit ----->| | |
| |-- POST /edit ------->| |
| | |-- Delete YouTube --->|
| | |-- Delete Dropbox --->|
| | |-- Delete GDrive ---->|
| | |-- Delete GCS ------->|
| | |-- Recycle brand code |
| | |-- Reset state ------>|
| | |-- Issue review token |
| | |-- (if metadata changed:
| | | trigger screens worker)
| |<-- review_url -------| |
|<-- Redirect to review| | |
| | | |
|-- Edit lyrics ------>| | |
|-- Select instrumental| | |
|-- Submit review ---->| | |
| |-- POST /complete --->| |
| | |-- Trigger render --->|
| | | |-- Render video
| | | |-- Encode formats
| | | |-- Allocate brand code
| | | |-- Upload YouTube
| | | |-- Upload Dropbox
| | | |-- Upload GDrive
| | | |-- Clear outputs_deleted_at
| | |<-- COMPLETE ---------|
|<-- Job complete -----| | |
```
## Risk Assessment
| Risk | Mitigation |
|------|------------|
| Cleanup fails mid-way (e.g., YouTube deleted but Dropbox fails) | Don't reset job state on critical failure. User sees error, job stays COMPLETE with partial cleanup. Admin can investigate. |
| User abandons review after edit (outputs deleted, never re-submitted) | Job sits in AWAITING_REVIEW. Same as any unreviewed job. Could add reminder email after 24h. |
| Race condition: two edit requests simultaneously | Use Firestore transaction for state transition. Second request fails validation (job no longer COMPLETE). |
| Screens not ready when user submits review quickly | Existing coordination logic in pipeline handles this — render worker waits for screens_complete flag. |
@@ -0,0 +1,464 @@
# Lyrics Review Session Backup & Restore
**Date:** 2026-03-07
**Branch:** `feat/sess-20260307-2332-lyrics-review-sessions`
**Status:** Planning
## Problem
The lyrics review process can take 1+ hours for difficult songs. Currently, progress is saved to browser localStorage using a fragile key based on a hash of the first segment's text. This has several issues:
1. **Fragile matching** — hash of first segment text can collide or mismatch across jobs
2. **Browser-local only** — lost on browser clear, different device, or incognito
3. **No history** — only stores the latest state, no way to browse previous sessions
4. **Confusing restore UX** — bare `window.confirm()` dialog with no context about what's being restored
5. **No cross-job restore** — can't apply edits from a previous job to a new one (needed for style-change redeliveries)
## Solution Overview
Server-side review session storage with automatic periodic backup, rich restore UI, and cross-job session search.
### Phases
| Phase | Scope | Description |
|-------|-------|-------------|
| 1 | Backend API + storage | Firestore subcollection, save/list/get endpoints |
| 2 | Auto-save from frontend | Periodic backup (60s interval, on preview, on dirty changes) |
| 3 | Restore UI | Session browser with edit preview, auto-prompt on load |
| 4 | Cross-job restore | Search sessions across jobs, duration mismatch warning |
---
## Phase 1: Backend API + Storage
### Data Model
Store sessions in a Firestore **subcollection**: `jobs/{jobId}/review_sessions/{sessionId}`
This follows the existing pattern used for worker logs (`jobs/{jobId}/logs/{logId}`).
#### `ReviewSession` document schema
```python
{
"session_id": str, # Auto-generated document ID
"job_id": str, # Parent job ID (denormalized for cross-job queries)
"user_email": str, # Who created this session
"created_at": datetime, # First save timestamp
"updated_at": datetime, # Last save timestamp
"edit_count": int, # Number of edits in this session
"is_auto_save": bool, # True for periodic auto-saves, False for manual saves
"trigger": str, # "auto" | "preview" | "manual"
"audio_duration_seconds": float | None, # Input audio duration (for cross-job matching)
"artist": str | None, # From correction_data.metadata
"title": str | None, # From correction_data.metadata
# Summary for list view (avoid loading full correction_data)
"summary": {
"total_segments": int,
"total_words": int,
"corrections_made": int,
"changed_words": [ # First N changed words for preview
{"original": str, "corrected": str, "segment_index": int}
],
},
# Full correction data (stored in GCS, NOT in Firestore doc)
"correction_data_gcs_path": str, # "jobs/{jobId}/review_sessions/{sessionId}.json"
}
```
**Why GCS for correction_data?** CorrectionData can be large (100KB+). Firestore has a 1MB document limit, and storing large blobs in Firestore is inefficient for reads/writes. The summary field provides enough info for list views without loading full data.
#### Store audio duration on Job
Add `input_audio_duration_seconds: Optional[float]` to the `Job` model. Populate it during job creation (audio worker already has access to ffprobe). This enables cross-job duration comparison without re-computing.
### API Endpoints
All under the existing review router (`/api/review/{job_id}/...`), using the existing `require_review_auth` dependency.
#### `POST /api/review/{job_id}/sessions`
Save a review session snapshot.
**Request body:**
```json
{
"correction_data": { ... },
"edit_count": 42,
"trigger": "auto",
"summary": {
"total_segments": 15,
"total_words": 230,
"corrections_made": 12,
"changed_words": [
{"original": "world", "corrected": "word", "segment_index": 3}
]
}
}
```
**Response:** `{ "session_id": "abc123", "created_at": "..." }`
**Logic:**
1. Upload `correction_data` to GCS at `jobs/{jobId}/review_sessions/{sessionId}.json`
2. Create Firestore subcollection document with metadata + summary
3. Denormalize `job_id`, `artist`, `title`, `audio_duration_seconds` from parent job
#### `GET /api/review/{job_id}/sessions`
List all sessions for a job (metadata only, no correction_data).
**Response:**
```json
{
"sessions": [
{
"session_id": "abc123",
"created_at": "2026-03-07T12:00:00Z",
"updated_at": "2026-03-07T12:15:00Z",
"edit_count": 42,
"trigger": "auto",
"summary": { ... },
"user_email": "andrew@..."
}
]
}
```
Ordered by `updated_at` descending. No pagination needed initially (unlikely to exceed 50 sessions per job).
#### `GET /api/review/{job_id}/sessions/{session_id}`
Get full session data (loads correction_data from GCS).
**Response:** Full session document + `correction_data` from GCS.
#### `DELETE /api/review/{job_id}/sessions/{session_id}`
Delete a session (admin only). Removes both Firestore doc and GCS file.
#### `GET /api/review/sessions/search` (Phase 4)
Cross-job session search. Requires admin auth.
**Query params:** `?q=<search>&limit=20`
Search by artist, title, or job_id across all jobs. Uses Firestore collection group query on `review_sessions`.
**Response:** Same as list endpoint but includes `job_id`, `artist`, `title` per session.
### Backend Implementation Files
| File | Changes |
|------|---------|
| `backend/models/review_session.py` | New: `ReviewSession` dataclass |
| `backend/models/job.py` | Add `input_audio_duration_seconds` field |
| `backend/services/firestore_service.py` | Add session CRUD methods using subcollection pattern |
| `backend/api/routes/review.py` | Add session endpoints |
| `backend/workers/audio_worker.py` | Store audio duration on job after ffprobe |
### Cleanup / Retention
- Auto-save sessions older than 90 days: eligible for cleanup (can add TTL field like worker logs)
- Manual/preview-triggered sessions: kept indefinitely
- When a job is deleted, cascade delete its review_sessions subcollection
---
## Phase 2: Auto-Save from Frontend
### Save Strategy
Replace the current localStorage-on-every-edit approach with a smarter dual strategy:
1. **localStorage** — continues to save on every edit (instant, for crash recovery within same browser)
2. **Server backup** — periodic saves to the backend API
### Server Backup Triggers
| Trigger | Condition | `trigger` field |
|---------|-----------|-----------------|
| Periodic timer | Every 60 seconds, IF at least 1 edit since last backup | `"auto"` |
| Preview video | When user generates a preview video | `"preview"` |
| Page unload | `beforeunload` event, IF dirty since last backup | `"auto"` |
| Manual save | User clicks explicit "Save Progress" button | `"manual"` |
### Dirty Tracking
Track a `lastBackupEditCount` ref. Compare against current `history.length` to determine if there are new edits since last backup.
### Implementation
New custom hook: `useReviewSessionAutoSave()`
```typescript
// frontend/hooks/use-review-session-autosave.ts
function useReviewSessionAutoSave({
jobId: string,
data: CorrectionData,
initialData: CorrectionData,
historyLength: number,
isReadOnly: boolean,
apiClient: ReviewApiClient,
}) {
// Track last backup state
const lastBackupEditCount = useRef(0)
// Compute summary from data diff (changed words, counts)
const computeSummary = useCallback(...)
// Save function (called by timer, preview trigger, etc.)
const saveSession = useCallback(async (trigger: string) => {
if (historyLength <= 1) return // No edits yet
if (historyLength === lastBackupEditCount.current) return // No new edits
await apiClient.saveReviewSession(jobId, {
correction_data: data,
edit_count: historyLength - 1,
trigger,
summary: computeSummary(initialData, data),
})
lastBackupEditCount.current = historyLength
}, [data, historyLength, ...])
// 60-second interval
useEffect(() => {
if (isReadOnly) return
const timer = setInterval(() => saveSession("auto"), 60_000)
return () => clearInterval(timer)
}, [saveSession, isReadOnly])
// beforeunload
useEffect(() => {
const handler = () => saveSession("auto")
window.addEventListener("beforeunload", handler)
return () => window.removeEventListener("beforeunload", handler)
}, [saveSession])
return { saveSession } // Expose for preview trigger
}
```
### Frontend API Client Additions
```typescript
// In frontend/lib/api.ts - lyricsReviewApi
async saveReviewSession(jobId, data): Promise<{ session_id: string }>
async listReviewSessions(jobId): Promise<{ sessions: ReviewSession[] }>
async getReviewSession(jobId, sessionId): Promise<ReviewSessionFull>
async deleteReviewSession(jobId, sessionId): Promise<void>
async searchReviewSessions(query): Promise<{ sessions: ReviewSession[] }> // Phase 4
```
### Frontend Files
| File | Changes |
|------|---------|
| `frontend/hooks/use-review-session-autosave.ts` | New: auto-save hook |
| `frontend/lib/api.ts` | Add session API methods |
| `frontend/lib/lyrics-review/types.ts` | Add `ReviewSession`, `ReviewSessionSummary` types |
| `frontend/components/lyrics-review/LyricsAnalyzer.tsx` | Wire up auto-save hook, add "Save Progress" button |
---
## Phase 3: Restore UI
### Behavior on Load
When `LyricsAnalyzer` mounts:
1. Call `GET /api/review/{job_id}/sessions` to check for saved sessions
2. **If sessions exist**: show the Session Restore dialog (replaces the old `window.confirm`)
3. **If no sessions**: proceed normally (also check localStorage as fallback for backward compat)
### Session Restore Dialog
A modal dialog with a split-pane layout:
```
┌─────────────────────────────────────────────────────────┐
│ Saved Review Sessions [×] │
├───────────────────────┬─────────────────────────────────┤
│ Session List │ Edit Preview │
│ │ │
│ ▸ Mar 7, 2:15 PM │ Segment 3: │
│ 42 edits · preview │ "hello world" → "hello word" │
│ [Most recent] │ │
│ │ Segment 7: │
│ ▸ Mar 7, 1:30 PM │ "singing loud" → "singing out"│
│ 38 edits · auto │ │
│ │ Segment 12: │
│ ▸ Mar 6, 11:00 PM │ (deleted word "um") │
│ 15 edits · auto │ │
│ │ ... +39 more changes │
│ │ │
├───────────────────────┴─────────────────────────────────┤
│ [Start Fresh] [Restore Selected] │
└─────────────────────────────────────────────────────────┘
```
#### Session List (left pane)
Each session shows:
- Date/time (relative: "2 hours ago", absolute on hover)
- Edit count
- Trigger badge: `auto` / `preview` / `manual`
- Selected state (highlight)
#### Edit Preview (right pane)
When a session is selected, show a compact diff view:
- List of changed words grouped by segment
- Show original → corrected text
- Color-coded: green for additions, red for deletions, yellow for changes
- Scroll if many edits, with a summary count at bottom
#### Actions
- **Start Fresh** — dismiss dialog, use initial data (no restore)
- **Restore Selected** — load the selected session's full `correction_data`, replace current state
### "Save Progress" Button & Session Browser
Add to the LyricsAnalyzer toolbar:
- **Save Progress** button (triggers manual save)
- **Session History** button — opens the same Session Restore dialog at any time (not just on load)
### Frontend Files
| File | Changes |
|------|---------|
| `frontend/components/lyrics-review/SessionRestoreDialog.tsx` | New: the restore modal |
| `frontend/components/lyrics-review/SessionListItem.tsx` | New: session list item component |
| `frontend/components/lyrics-review/SessionEditPreview.tsx` | New: edit diff preview |
| `frontend/components/lyrics-review/LyricsAnalyzer.tsx` | Mount dialog on load, add toolbar buttons |
---
## Phase 4: Cross-Job Session Restore
### Power User Feature
Add a tab/toggle in the Session Restore dialog: **"This Job"** | **"All Jobs"**
When "All Jobs" is selected:
- Show a search box (search by artist, title, or job ID)
- Query `GET /api/review/sessions/search?q=...`
- Results show sessions from other jobs with job context (artist - title, job ID)
### Duration Mismatch Warning
When restoring from a different job:
1. Compare `session.audio_duration_seconds` with current job's `audio_duration_seconds`
2. If durations differ by more than 2 seconds, show a warning:
```
⚠️ Duration Mismatch
The selected session is from a track with a different duration:
This job: 3:42 (222s)
Source session: 4:01 (241s)
Timing alignment may not match. Word timestamps from the
source session will be preserved as-is.
[Cancel] [Restore Anyway]
```
3. If durations match (within 2s), restore silently
### Collection Group Index
Firestore collection group queries require a **composite index** on `review_sessions`:
- Fields: `artist` (ASC), `title` (ASC), `updated_at` (DESC)
- Add via `firestore.indexes.json` or Pulumi
### Backend: Search Implementation
The search endpoint uses Firestore collection group query:
```python
@router.get("/sessions/search")
async def search_sessions(q: str, limit: int = 20, auth=Depends(require_admin)):
# Collection group query across all jobs' review_sessions
sessions_ref = db.collection_group("review_sessions")
# Search by artist OR title containing query (case-insensitive prefix)
# Firestore doesn't support LIKE queries, so we use range queries
# for prefix matching, or store lowercase variants for matching
results = sessions_ref.where("artist_lower", ">=", q.lower())
.where("artist_lower", "<=", q.lower() + "\uf8ff")
.limit(limit)
.get()
# Also search by title and job_id, merge results
...
```
**Note:** Firestore's text search is limited. For the MVP, searching by exact job_id + prefix matching on artist/title should be sufficient. If full-text search is needed later, consider Algolia or a simple in-memory filter on the client after fetching recent sessions.
### Frontend Files
| File | Changes |
|------|---------|
| `frontend/components/lyrics-review/SessionRestoreDialog.tsx` | Add "All Jobs" tab, search input |
| `frontend/components/lyrics-review/DurationWarning.tsx` | New: duration mismatch warning |
| `frontend/lib/api.ts` | Add `searchReviewSessions()` |
---
## Testing Strategy
### Backend Tests
| Test | Type | What |
|------|------|------|
| `test_review_session_crud.py` | Unit | Create, list, get, delete sessions via Firestore service |
| `test_review_session_endpoints.py` | Integration | API endpoint tests with auth |
| `test_review_session_gcs.py` | Unit | GCS upload/download of correction data |
| `test_audio_duration_storage.py` | Unit | Duration stored on job creation |
### Frontend Tests
| Test | Type | What |
|------|------|------|
| `SessionRestoreDialog.test.tsx` | Unit | Renders session list, selection, restore action |
| `SessionEditPreview.test.tsx` | Unit | Diff computation and display |
| `use-review-session-autosave.test.ts` | Unit | Timer behavior, dirty tracking, save triggers |
| `lyrics-review-sessions.spec.ts` | E2E | Full flow: edit → auto-save → reload → restore |
---
## Migration / Backward Compatibility
1. **localStorage fallback** — keep the existing localStorage load/save as a fallback. If no server sessions exist, check localStorage. Gradually phase out once server sessions are proven reliable.
2. **No schema migration needed** — new Firestore subcollection, new GCS paths. No existing data affected.
3. **Feature flag** — not needed; server session save is additive. The restore dialog replaces `window.confirm()` which is strictly better.
---
## Open Questions
1. **Session limit per job?** — Should we cap at e.g. 50 sessions per job and auto-prune oldest auto-saves? Probably yes to avoid unbounded growth.
2. **Session deduplication** — If user makes 0 additional edits between auto-save intervals, we skip the save (dirty tracking handles this). But should we also deduplicate if the correction_data hasn't actually changed (e.g. undo then redo)?
3. **Compression** — CorrectionData JSON can be large. Should we gzip before storing in GCS? Probably not for MVP; GCS handles compression at the storage layer.
---
## Estimated Scope
| Phase | Backend | Frontend | Total |
|-------|---------|----------|-------|
| 1 | ~300 lines | 0 | Medium |
| 2 | 0 | ~150 lines | Small |
| 3 | 0 | ~400 lines | Medium |
| 4 | ~100 lines | ~200 lines | Medium |
| Tests | ~300 lines | ~300 lines | Medium |
Phases 1-3 form the core feature. Phase 4 (cross-job) can be deferred to a follow-up PR if needed.
@@ -0,0 +1,95 @@
# Edit Input Audio — Master Plan
**Date:** 2026-03-08
**Branch:** `feat/sess-20260308-1232-edit-input-audio`
**Status:** Complete
## Problem
A common request from clients is to use a live performance from YouTube but skip the first MM:SS of talking/intro before the band starts playing. Currently there's no way to trim, cut, mute, or otherwise edit the input audio before it enters the processing pipeline (separation, transcription, etc.). Users must provide a pre-edited file themselves or accept the full audio as-is.
## Solution Overview
Add an optional **"Edit Input Audio"** phase after audio download completes but before separation/transcription begins. Users opt in during the guided job creation flow. When enabled, the job pauses at a new blocking state (`awaiting_audio_edit`) where users can trim, cut, mute, or join audio using a waveform-based editor UI similar to the existing instrumental review UI. The edited audio replaces the original as input for all subsequent processing stages.
The editor includes full undo/redo support and session persistence (auto-save + restore) following the same pattern built for lyrics review sessions.
## Phases
| Phase | Title | Scope | Dependencies |
|-------|-------|-------|-------------|
| 1 | [State Machine & Backend API](2026-03-08-edit-input-audio-phase1-backend.md) | New job state, audio processing endpoints (trim/cut/mute/join), waveform data generation for input audio | None |
| 2 | [Session Persistence](2026-03-08-edit-input-audio-phase2-sessions.md) | Audio edit session save/restore, Firestore subcollection, GCS storage, deduplication | Phase 1 |
| 3 | [Job Creation Flow Integration](2026-03-08-edit-input-audio-phase3-creation-flow.md) | Opt-in toggle during "Choose Audio" step, job creation with `requires_audio_edit` flag | Phase 1 |
| 4 | [Audio Editor UI](2026-03-08-edit-input-audio-phase4-editor-ui.md) | Waveform viewer, trim/cut/mute/join controls, undo/redo, playback, original vs edited tabs | Phase 1 |
| 5 | [Session Restore & Admin Dashboard](2026-03-08-edit-input-audio-phase5-restore-admin.md) | Auto-save hook, restore dialog on page load, admin dashboard for viewing/replaying audio edit sessions | Phases 2, 4 |
## Key Design Decisions
1. **Opt-in, not default** — Most users don't need audio editing. The option appears as a secondary question after audio selection (for all sources including file uploads), keeping the default flow unchanged.
2. **Server-side audio processing** — Trim, cut, mute, and join operations are performed server-side via FFmpeg. The frontend sends edit descriptors (timestamps, regions) and the backend produces the edited audio file. This avoids loading large audio files into the browser and ensures consistent processing.
3. **Waveform rendered client-side** — Like the instrumental review UI, the frontend renders waveforms on canvas using amplitude data from the backend API. After each edit, the backend returns updated waveform data for the edited audio. All playback uses OGG Opus (not FLAC) to keep streaming fast.
4. **Edit operations are non-destructive** — Each edit creates a new version. The original audio is always preserved. Users can undo/redo freely and always compare original vs edited.
5. **Session persistence follows lyrics review pattern** — Firestore subcollection + GCS for full edit history, deduplication via hash, auto-save every N edits + on page hide.
6. **Blocking state with notifications** — The `awaiting_audio_edit` state follows the same pattern as `awaiting_review`: generates a review token, sends an email notification, and waits for user action.
## Architecture Overview
```
Job Creation (with requires_audio_edit=true)
↓
DOWNLOADING / DOWNLOADING_AUDIO (existing)
↓
Audio download complete
↓
AWAITING_AUDIO_EDIT ← NEW blocking state
↓
[User opens audio editor UI]
↓
IN_AUDIO_EDIT ← NEW (user actively editing)
↓
[User submits edited audio]
↓
AUDIO_EDIT_COMPLETE ← NEW
↓
[Edited audio saved to GCS, replaces input_media_gcs_path]
↓
Trigger workers (separation + transcription) — existing flow continues
```
## Additional Decisions
- **Available for file uploads too** — Users may not be comfortable with external audio editors; our in-app editing makes basic operations accessible.
- **Server-side only processing** — All edit operations use FFmpeg server-side. No client-side Web Audio API. This ensures the preview is perfectly representative of the final result.
- **Admin can reset to audio edit** — Admins can reset a job to `awaiting_audio_edit` via AdminJobActions, useful when a client requests a trim after job creation.
- **Join limited to start/end** — No arbitrary insert. Users can work around by cutting and re-joining.
- **Playback uses OGG Opus** — All preview audio is transcoded to OGG Opus before streaming to the browser. No FLAC streaming.
## Implementation Approach
Implement each phase sequentially on this branch. After each phase:
1. Run `/test-review` and `/docs-review`
2. Commit and push
After all phases complete, test locally with a real audio file (frontend + backend) before `/shipit`.
## GCS File Structure (additions)
```
jobs/{job_id}/
├── input/
│ ├── original.flac # Original downloaded audio (never modified)
│ └── edited.flac # Edited audio (after user submits)
├── audio_edit/
│ ├── waveform_original.json # Cached waveform data for original
│ ├── waveform_edited.json # Cached waveform data for current edit
│ └── preview_{operation_id}.flac # Temporary previews during editing
├── audio_edit_sessions/
│ └── {session_id}.json # Full edit history for session restore
└── ... (existing structure)
```
@@ -0,0 +1,398 @@
# Edit Input Audio — Phase 1: State Machine & Backend API
**Date:** 2026-03-08
**Parent:** [Master Plan](2026-03-08-edit-input-audio-master-plan.md)
**Status:** Planning
## Goal
Add the backend infrastructure for the "edit input audio" feature: new job states, audio processing endpoints (trim, cut, mute, join), waveform data generation for input audio, and the submit/finalize flow.
---
## 1. New Job States
### State Enum Additions
Add to `backend/models/job.py` `JobStatus`:
```python
AWAITING_AUDIO_EDIT = "awaiting_audio_edit" # Blocking: waiting for user to edit audio
IN_AUDIO_EDIT = "in_audio_edit" # User is actively editing
AUDIO_EDIT_COMPLETE = "audio_edit_complete" # User submitted edited audio
```
### State Transitions
Add to `STATE_TRANSITIONS` in `backend/models/job.py`:
```python
# After download, can optionally enter audio edit phase
JobStatus.DOWNLOADING: [
..., # existing transitions
JobStatus.AWAITING_AUDIO_EDIT, # NEW: if requires_audio_edit
],
# Audio edit phase
JobStatus.AWAITING_AUDIO_EDIT: [
JobStatus.IN_AUDIO_EDIT,
JobStatus.FAILED,
JobStatus.CANCELLED,
],
JobStatus.IN_AUDIO_EDIT: [
JobStatus.AWAITING_AUDIO_EDIT, # User leaves without submitting
JobStatus.AUDIO_EDIT_COMPLETE,
JobStatus.FAILED,
JobStatus.CANCELLED,
],
JobStatus.AUDIO_EDIT_COMPLETE: [
JobStatus.SEPARATING_STAGE1, # Continue to normal processing
JobStatus.TRANSCRIBING,
JobStatus.GENERATING_SCREENS,
JobStatus.FAILED,
],
```
### Audio Download Worker Changes
In `backend/workers/audio_download_worker.py`, after audio download completes:
```python
# Check if audio editing was requested
if job.state_data.get('requires_audio_edit'):
# Transition to blocking audio edit state instead of triggering workers
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.AWAITING_AUDIO_EDIT,
progress=15,
message="Audio downloaded. Please review and edit the audio before processing."
)
# Don't trigger workers yet — wait for user to complete audio edit
return True
# Existing flow: trigger workers immediately
await _trigger_workers_parallel(job_id)
```
### Review Token Generation
In `job_manager.py` `transition_to_state()`, add `AWAITING_AUDIO_EDIT` to the review token generation check:
```python
if new_status in (JobStatus.AWAITING_REVIEW, JobStatus.AWAITING_AUDIO_EDIT):
review_token = generate_review_token()
updates['review_token'] = review_token
```
### Notification
In `job_notification_service.py`, add email notification for `AWAITING_AUDIO_EDIT`:
```python
async def send_audio_edit_email(self, job_id, user_email, artist, title):
edit_url = f"{self.frontend_url}/app/jobs#/{job_id}/audio-edit"
# Use existing email template pattern with new template
```
---
## 2. Audio Processing API Endpoints
All endpoints under the existing review router, authenticated via review token.
### `GET /api/review/{job_id}/input-audio-info`
Returns metadata about the input audio for the editor UI.
**Response:**
```json
{
"duration_seconds": 245.3,
"sample_rate": 44100,
"channels": 2,
"format": "flac",
"file_size_bytes": 35000000,
"waveform_data": {
"amplitudes": [0.1, 0.3, 0.8, ...], // 1000 points
"duration": 245.3
},
"playback_url": "https://storage.googleapis.com/...", // Signed URL (OGG Opus)
"has_edits": false,
"edit_count": 0
}
```
**Implementation:**
1. Read audio metadata from GCS (or cache in state_data after download)
2. Generate waveform data using existing `audio_analysis_service.get_waveform_data()`
3. Generate signed URL for playback (transcode to OGG if not already done)
### `POST /api/review/{job_id}/audio-edit/apply`
Apply an edit operation to the current audio. Returns updated metadata + waveform.
**Request body:**
```json
{
"operation": "trim",
"params": {
"start_seconds": 0,
"end_seconds": 32.5
},
"edit_id": "uuid-from-frontend"
}
```
**Supported operations:**
| Operation | Params | Description |
|-----------|--------|-------------|
| `trim_start` | `{ end_seconds: float }` | Remove audio from 0 to end_seconds |
| `trim_end` | `{ start_seconds: float }` | Remove audio from start_seconds to end |
| `cut` | `{ start_seconds: float, end_seconds: float }` | Remove a region, join remaining |
| `mute` | `{ start_seconds: float, end_seconds: float }` | Silence a region (preserve duration) |
| `join_start` | `{ upload_id: string }` | Prepend uploaded audio |
| `join_end` | `{ upload_id: string }` | Append uploaded audio |
**Response:**
```json
{
"status": "success",
"edit_id": "uuid",
"edited_audio": {
"duration_seconds": 212.8,
"waveform_data": {
"amplitudes": [...],
"duration": 212.8
},
"playback_url": "https://...", // Signed URL for edited audio
},
"edit_stack_size": 3,
"can_undo": true,
"can_redo": false
}
```
**Implementation (backend, server-side FFmpeg):**
1. Download current audio from GCS (original or latest edit)
2. Apply operation using FFmpeg:
- `trim_start`: `ffmpeg -ss {end_seconds} -i input.flac output.flac`
- `trim_end`: `ffmpeg -t {start_seconds} -i input.flac output.flac`
- `cut`: `ffmpeg -filter_complex "[0]atrim=0:{start}[a];[0]atrim={end}[b];[a][b]concat=n=2:v=0:a=1"`
- `mute`: `ffmpeg -af "volume=enable='between(t,{start},{end})':volume=0"`
- `join_start/end`: `ffmpeg -filter_complex "[0][1]concat=n=2:v=0:a=1"`
3. Upload edited audio to GCS at `jobs/{job_id}/audio_edit/edit_{edit_id}.flac`
4. Transcode to OGG Opus for playback
5. Generate waveform data for edited audio
6. Update job state_data with edit stack
### `POST /api/review/{job_id}/audio-edit/undo`
Undo the last edit operation.
**Response:** Same as apply — returns the state after undo (previous edit or original).
**Implementation:**
- Maintain an edit stack in job `state_data`:
```python
state_data['audio_edit_stack'] = [
{"edit_id": "uuid1", "gcs_path": "jobs/.../edit_uuid1.flac", "operation": "trim_start", ...},
{"edit_id": "uuid2", "gcs_path": "jobs/.../edit_uuid2.flac", "operation": "mute", ...},
]
state_data['audio_edit_redo_stack'] = []
```
- Undo pops from edit_stack, pushes to redo_stack
- Returns waveform + playback URL for the now-current version
### `POST /api/review/{job_id}/audio-edit/redo`
Redo a previously undone edit.
**Implementation:** Pop from redo_stack, push to edit_stack.
### `POST /api/review/{job_id}/audio-edit/upload`
Upload additional audio for join operations.
**Request:** Multipart file upload (FLAC, WAV, MP3, M4A, OGG)
**Response:**
```json
{
"upload_id": "uuid",
"duration_seconds": 15.2,
"waveform_data": { "amplitudes": [...], "duration": 15.2 }
}
```
**Implementation:**
1. Save to GCS at `jobs/{job_id}/audio_edit/upload_{upload_id}.flac`
2. Transcode to FLAC if not already
3. Return metadata + waveform
### `POST /api/review/{job_id}/audio-edit/submit`
Finalize the audio edit and continue processing.
**Request body:**
```json
{
"edit_log": {
"session_id": "uuid",
"entries": [...],
"started_at": "2026-03-08T12:00:00Z"
}
}
```
**Response:**
```json
{
"status": "success",
"message": "Audio edit saved. Processing will continue with edited audio.",
"job_id": "..."
}
```
**Implementation:**
1. Take the current top-of-stack audio (or original if no edits)
2. Copy to `jobs/{job_id}/input/edited.flac`
3. Update `job.input_media_gcs_path` to point to edited file
4. Save edit log to GCS
5. Transition state: `IN_AUDIO_EDIT` → `AUDIO_EDIT_COMPLETE`
6. Trigger parallel workers (audio separation + lyrics transcription)
7. Clean up intermediate edit files (optional, can defer)
---
## 3. Audio Processing Service
New service: `backend/services/audio_edit_service.py`
Encapsulates all FFmpeg operations for audio editing:
```python
class AudioEditService:
def __init__(self, storage_service: StorageService):
self.storage = storage_service
def trim_start(self, input_path: str, end_seconds: float, output_path: str) -> AudioMetadata:
"""Remove audio from 0 to end_seconds."""
def trim_end(self, input_path: str, start_seconds: float, output_path: str) -> AudioMetadata:
"""Remove audio from start_seconds to end."""
def cut_region(self, input_path: str, start: float, end: float, output_path: str) -> AudioMetadata:
"""Remove a region and join remaining parts."""
def mute_region(self, input_path: str, start: float, end: float, output_path: str) -> AudioMetadata:
"""Silence a region (preserve duration)."""
def join_audio(self, input_path: str, other_path: str, position: str, output_path: str) -> AudioMetadata:
"""Join two audio files (position: 'start' or 'end')."""
def get_metadata(self, audio_path: str) -> AudioMetadata:
"""Get duration, sample rate, channels, format."""
```
Each method returns `AudioMetadata(duration_seconds, sample_rate, channels, format, file_size_bytes)`.
---
## 4. State Data Schema
The job's `state_data` dict gets these new fields:
```python
{
"requires_audio_edit": bool, # Set during job creation
"audio_edit_stack": [ # Edit history for undo/redo
{
"edit_id": str,
"operation": str,
"params": dict,
"gcs_path": str, # Path to audio file after this edit
"duration_seconds": float,
"timestamp": str,
}
],
"audio_edit_redo_stack": [...], # Undone edits available for redo
"audio_edit_uploads": { # Uploaded audio for join operations
"upload_id": { "gcs_path": str, "duration_seconds": float }
},
"original_input_media_gcs_path": str, # Preserved original before edit
}
```
---
## 5. AutoProcessor Integration
Update `frontend/components/AutoProcessor.tsx` to handle `awaiting_audio_edit`:
For `non_interactive=true` jobs, auto-skip the audio edit phase (submit with no edits):
```typescript
case 'awaiting_audio_edit':
processJob(job, 'audio_edit') // Auto-submit with no edits
break
```
---
## 6. Job Status Display
Update `frontend/lib/job-status.ts` to include new states:
```typescript
awaiting_audio_edit: {
label: "Edit Audio",
description: "Review and edit the input audio",
color: "yellow",
actionRequired: true,
},
in_audio_edit: {
label: "Editing Audio",
description: "Audio is being edited",
color: "blue",
},
audio_edit_complete: {
label: "Audio Edited",
description: "Audio edit complete, starting processing",
color: "green",
},
```
---
## Files Changed
| File | Type | Changes |
|------|------|---------|
| `backend/models/job.py` | Edit | Add 3 new states, update STATE_TRANSITIONS |
| `backend/services/job_manager.py` | Edit | Review token for AWAITING_AUDIO_EDIT, notification trigger |
| `backend/services/audio_edit_service.py` | New | FFmpeg audio editing operations |
| `backend/api/routes/review.py` | Edit | Add 6 new endpoints for audio editing |
| `backend/workers/audio_download_worker.py` | Edit | Check requires_audio_edit, conditional state transition |
| `backend/services/job_notification_service.py` | Edit | Email notification for awaiting_audio_edit |
| `frontend/lib/job-status.ts` | Edit | New state display config |
| `frontend/components/AutoProcessor.tsx` | Edit | Handle awaiting_audio_edit for non-interactive |
## Testing Strategy
| Test | Type | What |
|------|------|------|
| `test_audio_edit_service.py` | Unit | FFmpeg operations (trim, cut, mute, join) with real audio files |
| `test_audio_edit_endpoints.py` | Integration | API endpoint tests with auth, state validation |
| `test_audio_edit_state_transitions.py` | Unit | State machine transitions for new states |
| `test_audio_download_edit_flag.py` | Unit | Download worker respects requires_audio_edit flag |
## Open Questions
1. **Edit stack size limit?** — Should we cap the number of edits before requiring the user to submit? Probably not; let them edit freely. But we should clean up intermediate GCS files after submission.
2. **Real-time preview vs apply-then-preview?** — For MVP, each operation applies server-side and returns the result (apply-then-preview). Real-time client-side preview could come later using Web Audio API for simple operations like mute.
3. **Concurrent editing protection?** — Should we prevent multiple browser tabs from editing the same job? The `in_audio_edit` state transition provides some protection, but we should also use optimistic locking on the edit stack.
4. **Audio format for edits?** — Keep everything in FLAC for lossless quality. Transcode to OGG Opus for all playback URLs (same pattern as existing review audio transcoding). Users should never wait for large FLAC files to stream.
@@ -0,0 +1,228 @@
# Edit Input Audio — Phase 2: Session Persistence
**Date:** 2026-03-08
**Parent:** [Master Plan](2026-03-08-edit-input-audio-master-plan.md)
**Status:** Planning
**Depends on:** Phase 1
## Goal
Persist every audio edit operation so users can resume editing after closing their browser, and admins can review/replay audio edit sessions in the dashboard. Follows the same architectural pattern as lyrics review session persistence.
---
## 1. Data Model
### Firestore Subcollection
`jobs/{job_id}/audio_edit_sessions/{session_id}`
Follows the existing `review_sessions` subcollection pattern.
```python
# backend/models/audio_edit_session.py
@dataclass
class AudioEditSession:
session_id: str # UUID
job_id: str # Parent job ID (denormalized)
user_email: str # Who created this session
created_at: datetime # First save timestamp
updated_at: datetime # Last modification
edit_count: int # Number of edit operations
trigger: str # "auto" | "manual" | "submit"
audio_duration_seconds: float | None # Current edited audio duration
original_duration_seconds: float | None # Original audio duration
artist: str | None # Denormalized from job
title: str | None # Denormalized from job
data_hash: str # SHA256 of edit_data for deduplication
# Summary for list views
summary: AudioEditSessionSummary
# Full edit data stored in GCS (NOT in Firestore doc)
edit_data_gcs_path: str # "jobs/{jobId}/audio_edit_sessions/{sessionId}.json"
@dataclass
class AudioEditSessionSummary:
total_operations: int # Number of edit operations
operations_breakdown: dict[str, int] # {"trim_start": 2, "mute": 1, ...}
duration_change_seconds: float # How much duration changed
net_duration_seconds: float # Current audio duration
```
### GCS Edit Data
Stored at `jobs/{job_id}/audio_edit_sessions/{session_id}.json`:
```json
{
"session_id": "uuid",
"job_id": "abc123",
"started_at": "2026-03-08T12:00:00Z",
"entries": [
{
"id": "uuid-entry-1",
"timestamp": "2026-03-08T12:01:30Z",
"operation": "trim_start",
"params": { "end_seconds": 32.5 },
"duration_before": 245.3,
"duration_after": 212.8,
"audio_gcs_path": "jobs/abc123/audio_edit/edit_uuid1.flac"
},
{
"id": "uuid-entry-2",
"timestamp": "2026-03-08T12:03:15Z",
"operation": "mute",
"params": { "start_seconds": 45.0, "end_seconds": 48.2 },
"duration_before": 212.8,
"duration_after": 212.8,
"audio_gcs_path": "jobs/abc123/audio_edit/edit_uuid2.flac"
}
],
"undo_count": 0,
"redo_count": 0
}
```
---
## 2. API Endpoints
### `POST /api/review/{job_id}/audio-edit-sessions`
Save an audio edit session snapshot.
**Request body:**
```json
{
"edit_data": {
"entries": [...],
"started_at": "..."
},
"edit_count": 5,
"trigger": "auto",
"summary": {
"total_operations": 5,
"operations_breakdown": { "trim_start": 1, "mute": 2, "cut": 2 },
"duration_change_seconds": -32.5,
"net_duration_seconds": 212.8
}
}
```
**Response:**
```json
{
"status": "saved" | "skipped",
"session_id": "uuid",
"created_at": "...",
"reason": "identical_data" // Only if skipped
}
```
**Implementation:**
1. Compute SHA256 hash of `edit_data`
2. Compare with latest session's `data_hash` — skip if identical
3. Upload `edit_data` to GCS
4. Save metadata to Firestore subcollection
### `GET /api/review/{job_id}/audio-edit-sessions`
List all audio edit sessions for a job (metadata only).
**Response:**
```json
{
"sessions": [
{
"session_id": "...",
"created_at": "...",
"updated_at": "...",
"edit_count": 5,
"trigger": "auto",
"summary": { ... }
}
]
}
```
Ordered by `updated_at` descending.
### `GET /api/review/{job_id}/audio-edit-sessions/{session_id}`
Get full session with edit_data loaded from GCS.
### `DELETE /api/review/{job_id}/audio-edit-sessions/{session_id}`
Delete a session (admin or session owner).
---
## 3. Firestore Service Methods
Add to `backend/services/firestore_service.py`:
```python
def save_audio_edit_session(self, job_id: str, session: AudioEditSession) -> None
def list_audio_edit_sessions(self, job_id: str) -> list[AudioEditSession]
def get_audio_edit_session(self, job_id: str, session_id: str) -> AudioEditSession | None
def delete_audio_edit_session(self, job_id: str, session_id: str) -> None
def delete_audio_edit_sessions_subcollection(self, job_id: str) -> None
def get_latest_audio_edit_session_hash(self, job_id: str) -> str | None
```
These follow the exact same pattern as the existing `review_sessions` methods.
---
## 4. Deduplication Strategy
Same as lyrics review sessions:
- Compute SHA256 hash of the `edit_data` JSON (sorted keys)
- Skip save if hash matches the most recent session's `data_hash`
- Prevents duplicate saves during rapid edits or undo/redo cycles
---
## 5. Job Deletion Cascade
When a job is deleted, cascade delete:
- `audio_edit_sessions` subcollection (all Firestore docs)
- `jobs/{job_id}/audio_edit_sessions/` GCS prefix (all session files)
- `jobs/{job_id}/audio_edit/` GCS prefix (all intermediate edit files)
Add to existing job deletion logic in `job_manager.py`.
---
## 6. Retention Policy
| Session Type | Retention |
|-------------|-----------|
| Auto-save (`trigger: "auto"`) | 90 days TTL |
| Manual save (`trigger: "manual"`) | Indefinite |
| Submit save (`trigger: "submit"`) | Indefinite |
Follow the same TTL approach as lyrics review sessions.
---
## Files Changed
| File | Type | Changes |
|------|------|---------|
| `backend/models/audio_edit_session.py` | New | AudioEditSession dataclass |
| `backend/services/firestore_service.py` | Edit | Add CRUD methods for audio_edit_sessions subcollection |
| `backend/api/routes/review.py` | Edit | Add session save/list/get/delete endpoints |
| `backend/services/job_manager.py` | Edit | Cascade delete audio_edit_sessions on job deletion |
## Testing Strategy
| Test | Type | What |
|------|------|------|
| `test_audio_edit_session_crud.py` | Unit | Create, list, get, delete sessions |
| `test_audio_edit_session_dedup.py` | Unit | Hash-based deduplication |
| `test_audio_edit_session_endpoints.py` | Integration | API endpoints with auth |
| `test_audio_edit_session_cascade.py` | Unit | Job deletion cleans up sessions |
@@ -0,0 +1,214 @@
# Edit Input Audio — Phase 3: Job Creation Flow Integration
**Date:** 2026-03-08
**Parent:** [Master Plan](2026-03-08-edit-input-audio-master-plan.md)
**Status:** Planning
**Depends on:** Phase 1
## Goal
Add an opt-in toggle during the guided job creation flow so users can indicate they want to edit the input audio before processing begins. This must not add friction for the majority of users who don't need it.
---
## 1. UX Design
### Where the Toggle Appears
After the user selects their audio source in **Step 2: Choose Audio** (in `AudioSourceStep.tsx`), a secondary question appears below their selection:
```
┌─────────────────────────────────────────────────────┐
│ ✓ Selected: "Bohemian Rhapsody - Live at Wembley" │
│ YouTube · 6:03 · HD Audio │
│ │
│ ┌─────────────────────────────────────────────────┐ │
│ │ ✂️ Want to trim or edit this audio first? │ │
│ │ │ │
│ │ If this is a live recording with talking/intro │ │
│ │ you want to skip, or if you need to remove a │ │
│ │ section, you can edit the audio after it's │ │
│ │ downloaded — before lyrics are transcribed. │ │
│ │ │ │
│ │ ( ) No, use as-is (default, selected) │ │
│ │ ( ) Yes, I'll edit it first │ │
│ └─────────────────────────────────────────────────┘ │
│ │
│ [Continue →] │
└─────────────────────────────────────────────────────┘
```
### Design Principles
1. **Default is "No"** — The toggle defaults to "No, use as-is" so the existing flow is unaffected for most users.
2. **Collapsed by default** — The edit option panel is collapsed into a single line link ("Need to trim or edit this audio?") that expands on click. This keeps the UI clean.
3. **Only shown after selection** — The panel only appears after the user has selected/confirmed an audio source.
4. **Shown for all audio sources including file uploads** — Even if users upload their own files, they may not be comfortable with external audio editors. Our in-app editing makes basic operations (trim, cut, mute) accessible to everyone.
### Collapsed State
```
✓ Selected: "Bohemian Rhapsody - Live at Wembley"
YouTube · 6:03 · HD Audio
✂️ Need to trim or edit this audio? ▸
[Continue →]
```
Clicking the link expands the panel with the radio buttons.
---
## 2. Frontend Changes
### `AudioSourceStep.tsx`
Add state:
```typescript
const [wantsAudioEdit, setWantsAudioEdit] = useState(false)
const [showEditOption, setShowEditOption] = useState(false)
```
Pass `wantsAudioEdit` up to parent via callback:
```typescript
onAudioEditToggle?: (wants: boolean) => void
```
New sub-component: `AudioEditToggle.tsx`
```typescript
interface AudioEditToggleProps {
value: boolean
onChange: (wants: boolean) => void
}
```
### `GuidedJobFlow.tsx`
Add state tracking:
```typescript
const [wantsAudioEdit, setWantsAudioEdit] = useState(false)
```
Pass to job creation call:
```typescript
// In handleConfirm(), add to request body:
requires_audio_edit: wantsAudioEdit
```
### Success Screen Update
When `wantsAudioEdit` is true, update the timeline on the success screen:
```
What happens next:
1. Audio downloading (~1 min) — automatic
2. ✂️ You edit audio — trim, cut, or mute sections ← NEW
3. Audio processing (~10 min) — automatic
4. You review — lyrics & instrumental
5. Video delivered (~10 min) — automatic
```
---
## 3. Backend Changes
### Job Creation Endpoints
Both `POST /api/jobs/create-from-search` and `POST /api/jobs/create-from-url` need to accept:
```python
class CreateFromSearchRequest(BaseModel):
# ... existing fields ...
requires_audio_edit: bool = False # NEW
```
Store in job's `state_data`:
```python
if request.requires_audio_edit:
state_data['requires_audio_edit'] = True
```
### File Upload Path
For `POST /api/jobs/upload` (direct file upload), add a query parameter or form field:
```python
requires_audio_edit: bool = Form(False)
```
---
## 4. Tenant Feature Control
Add to `TenantConfig.features`:
```python
audio_editing: bool = True # Enable/disable audio editing for tenant
```
Default: `True` for all tenants. Can be disabled per-tenant if they don't want the extra step.
Frontend check:
```typescript
const { features } = useTenant()
// Only show the edit toggle if tenant allows it
{features.audio_editing && <AudioEditToggle ... />}
```
---
## 5. Job Card Status Display
When a job is in `awaiting_audio_edit` state, the `JobCard` component should show:
```
┌────────────────────────────────────────┐
│ Bohemian Rhapsody - Queen │
│ Status: Edit Audio Required │
│ Your audio is ready for editing. │
│ │
│ [Edit Audio →] │
└────────────────────────────────────────┘
```
The "Edit Audio" button navigates to `/app/jobs#/{jobId}/audio-edit`.
Update `JobCard.tsx`:
```typescript
case 'awaiting_audio_edit':
return (
<ActionButton href={`/app/jobs#/${job.job_id}/audio-edit`}>
Edit Audio
</ActionButton>
)
```
---
## Files Changed
| File | Type | Changes |
|------|------|---------|
| `frontend/components/job/steps/AudioSourceStep.tsx` | Edit | Add AudioEditToggle panel |
| `frontend/components/job/steps/AudioEditToggle.tsx` | New | Collapsed/expanded toggle component |
| `frontend/components/job/GuidedJobFlow.tsx` | Edit | Track wantsAudioEdit state, pass to API, update success screen |
| `frontend/components/job/JobCard.tsx` | Edit | Handle awaiting_audio_edit state with action button |
| `backend/api/routes/jobs.py` | Edit | Accept requires_audio_edit in create endpoints |
| `backend/api/routes/audio_search.py` | Edit | Accept requires_audio_edit in select endpoint |
| `backend/models/tenant.py` | Edit | Add audio_editing feature flag |
## Testing Strategy
| Test | Type | What |
|------|------|------|
| `AudioEditToggle.test.tsx` | Unit | Toggle renders, defaults to off, calls onChange |
| `GuidedJobFlow.test.tsx` | Unit | Toggle state flows through to job creation |
| `test_create_from_search_edit_flag.py` | Integration | API accepts and stores requires_audio_edit |
| `guided-flow-audio-edit.spec.ts` | E2E | Full flow: select audio → enable edit → create job → verify state |
## Resolved Questions
1. **Show for file uploads?** — **Yes.** Users may not be comfortable with external audio editors. Our in-app editing makes basic operations accessible to everyone.
2. **Admin override?** — **Yes.** Admins can reset a job to `awaiting_audio_edit` state via AdminJobActions. Useful when a client requests a trim after job creation.
3. **Remember preference?** — No — it should be a per-job decision.
@@ -0,0 +1,375 @@
# Edit Input Audio — Phase 4: Audio Editor UI
**Date:** 2026-03-08
**Parent:** [Master Plan](2026-03-08-edit-input-audio-master-plan.md)
**Status:** Planning
**Depends on:** Phase 1
## Goal
Build the audio editor UI that lets users trim, cut, mute, and join audio before processing. The UI is modeled on the existing instrumental review UI (waveform viewer, tabs, playback) but adds editing controls and an undo/redo system.
---
## 1. Page Routing
### Hash-based Route
New route: `/app/jobs#/{jobId}/audio-edit`
Add to the existing hash-based router in `frontend/app/app/jobs/[[...slug]]/client.tsx`:
```typescript
function getRouteType(hash: string): RouteType {
if (hash.includes('/audio-edit')) return 'audio-edit'
if (hash.includes('/instrumental')) return 'instrumental'
if (hash.includes('/review')) return 'review'
return 'unknown'
}
function getExpectedStates(routeType: RouteType): string[] {
switch (routeType) {
case 'audio-edit':
return ['awaiting_audio_edit', 'in_audio_edit']
// ... existing cases
}
}
```
### Review Token Auth
The audio edit page uses the same review token auth as lyrics/instrumental review. The token is generated when entering `awaiting_audio_edit` state (Phase 1).
---
## 2. Component Architecture
```
AudioEditor (main container)
├── AudioEditorToolbar
│ ├── UndoRedoControls
│ ├── EditModeSelector (trim/cut/mute)
│ ├── JoinUploadButton
│ └── SubmitButton
├── WaveformEditor (extended WaveformViewer)
│ ├── Canvas (amplitude visualization)
│ ├── TimeRuler
│ ├── SelectionOverlay (for cut/mute regions)
│ ├── TrimHandles (draggable start/end markers)
│ └── Playhead
├── AudioTabSwitcher
│ ├── "Original" tab
│ └── "Edited" tab
├── PlaybackControls
│ ├── Play/Pause
│ ├── Current time / Total duration
│ └── PlaybackSpeed (0.5x, 1x, 1.5x, 2x)
├── EditHistoryPanel (collapsible sidebar)
│ └── List of applied edits with undo points
└── AudioEditorGuidance (help/tips panel)
```
---
## 3. WaveformEditor Component
Extends the existing `WaveformViewer.tsx` pattern but adds interactive editing.
### Canvas Rendering
Same as instrumental review:
- Dark background (#0d1117)
- Blue amplitude bars (#60a5fa)
- Time ruler at bottom
- White playhead line with dot
- 3 zoom levels (1x, 2x, 4x)
### New Interactive Elements
**Trim Handles** (for trim_start / trim_end):
- Draggable vertical lines at the start and end of the waveform
- Drag start handle right → marks region for trimming from start
- Drag end handle left → marks region for trimming from end
- Trimmed region shown with red-tinted overlay and crosshatch pattern
- Snaps to 0.1 second intervals
**Selection Overlay** (for cut / mute):
- Click and drag to select a region
- Selected region highlighted with yellow border and semi-transparent fill
- Context menu or toolbar buttons to apply "Cut" or "Mute" to selection
- Muted regions shown with very dim bars (like instrumental review)
- Cut regions shown with red-tinted overlay
**Interaction Modes:**
| Mode | Click Behavior | Drag Behavior |
|------|---------------|---------------|
| Play | Seek to position | — |
| Trim | — | Drag trim handles |
| Select | Seek to position | Create selection for cut/mute |
### Waveform Data Updates
After each edit operation:
1. Frontend calls `POST /api/review/{job_id}/audio-edit/apply`
2. Backend returns new `waveform_data.amplitudes` for the edited audio
3. Canvas re-renders with new data
4. Duration display updates
### Tab Switching (Original vs Edited)
Two tabs above the waveform:
- **Original**: Shows original audio waveform, plays original audio
- **Edited**: Shows edited audio waveform (after latest edit), plays edited audio
Tab behavior:
- Switching tabs loads the corresponding waveform data and audio URL
- Maintains playback position proportionally (if audio duration changed, map position)
- Shows loading spinner during tab switch (same as instrumental review)
- "Original" tab always shows the unmodified waveform
- "Edited" tab shows the waveform after the most recent edit
---
## 4. Editing Operations UI
### Trim Start
1. User drags the start trim handle to the right
2. Trimmed region turns red with "Remove" label
3. User clicks "Apply Trim" button (or double-clicks the handle)
4. API call to `POST /audio-edit/apply` with `{ operation: "trim_start", params: { end_seconds: X } }`
5. Waveform updates to show trimmed audio
6. "Edited" tab auto-selected
### Trim End
Same as trim start but from the right side.
### Cut Region
1. User switches to "Select" mode
2. Drags to select a region on the waveform
3. Selection highlighted with yellow border
4. User clicks "Cut" in toolbar (or keyboard shortcut: Delete/Backspace)
5. Confirmation tooltip: "Remove 3.2s of audio from 1:23 to 1:26?"
6. API call to `POST /audio-edit/apply` with `{ operation: "cut", params: { start_seconds, end_seconds } }`
7. Waveform updates — region removed, audio joined
### Mute Region
1. Same selection as cut
2. User clicks "Mute" in toolbar (or keyboard shortcut: M)
3. API call with `{ operation: "mute", params: { start_seconds, end_seconds } }`
4. Waveform shows muted region with dim bars
5. Audio duration unchanged
### Join Audio
1. User clicks "Join" button in toolbar
2. File picker opens (accepts FLAC, WAV, MP3, M4A, OGG)
3. File uploaded via `POST /audio-edit/upload`
4. Small dialog appears: "Add to [Start] or [End]?"
5. API call with `{ operation: "join_start" or "join_end", params: { upload_id } }`
6. Waveform expands to include joined audio
**Note:** Join is limited to start/end only (no insert at arbitrary middle position). This is a niche feature that will rarely be used. Users who need to insert in the middle can work around it by cutting and re-joining.
---
## 5. Undo/Redo System
### Frontend State
```typescript
interface EditState {
editStack: EditEntry[] // Applied edits (from backend)
redoStack: EditEntry[] // Undone edits available for redo
canUndo: boolean
canRedo: boolean
}
interface EditEntry {
editId: string
operation: string
params: Record<string, unknown>
durationBefore: number
durationAfter: number
timestamp: string
}
```
### Controls
- Undo button (⟲) — calls `POST /audio-edit/undo`
- Redo button (⟳) — calls `POST /audio-edit/redo`
- Keyboard shortcuts: Ctrl/Cmd+Z (undo), Ctrl/Cmd+Shift+Z (redo)
- Buttons disabled when stack is empty
### Backend Coordination
Each undo/redo returns the same response as apply — updated waveform data and playback URL for the now-current version. The backend maintains the edit/redo stacks in `state_data`.
---
## 6. Playback Controls
### Audio Element
Single hidden `<audio>` element (same pattern as instrumental review):
- Dynamically updates `src` when switching original/edited tabs
- Maintains position across tab switches
### Controls
```
[⏮] [▶/⏸] [⏭] 0:45 / 3:32 Speed: [1x ▾]
```
- Previous: jump 5 seconds back
- Play/Pause: toggle playback
- Next: jump 5 seconds forward
- Time display: current / total
- Speed selector: 0.5x, 1x, 1.5x, 2x
### Click-to-Seek
Click anywhere on the waveform to seek to that position (same as instrumental review).
---
## 7. Edit History Panel
Collapsible sidebar showing the list of applied edits:
```
Edit History
─────────────────
3. Mute 1:45-1:48
(silenced 3.2s)
2. Cut 0:32-0:45
(removed 13s)
1. Trim start → 0:15
(removed 15s intro)
─────────────────
Original: 4:05
Current: 3:34 (-31s)
```
Each entry shows:
- Operation type and parameters
- Duration impact
- Click to preview the state at that point (optional, stretch goal)
---
## 8. Guidance Panel
A collapsible help panel (same pattern as `InstrumentalGuidancePanel`):
```
┌───────────────────────────────────────────────┐
│ ✂️ Audio Editor Tips [×] │
│ │
│ • Trim: Drag the handles at the start/end │
│ to remove intros or outros │
│ • Cut: Select a region and press Delete to │
│ remove it from the middle │
│ • Mute: Select a region and press M to │
│ silence it without changing the duration │
│ • Join: Upload additional audio to add to │
│ the start or end │
│ • Undo/Redo: Ctrl+Z / Ctrl+Shift+Z │
│ • Click anywhere on the waveform to listen │
│ │
│ When you're done, click "Submit" to continue │
│ with processing. │
└───────────────────────────────────────────────┘
```
Dismissible via localStorage (same pattern as instrumental guidance).
---
## 9. Submit Flow
1. User clicks "Submit & Continue" button
2. Confirmation dialog:
```
Submit Edited Audio?
Original duration: 4:05
Edited duration: 3:34
Edits applied: 3
The edited audio will be used for separation and
lyrics transcription. The original is preserved.
[Cancel] [Submit]
```
3. API call to `POST /api/review/{job_id}/audio-edit/submit`
4. Success screen with countdown (same pattern as instrumental review):
```
✓ Audio edit complete!
Processing will continue with your edited audio.
You'll receive an email when lyrics are ready for review.
Redirecting in 3...
```
5. Redirect to `/app` after 3 seconds
### Submit with No Edits
If the user opens the editor but doesn't make any changes:
- "Submit" button text changes to "Continue Without Editing"
- No confirmation dialog needed
- Submits immediately
---
## 10. Mobile Responsiveness
The editor should work on tablet/desktop. Mobile phone support is a stretch goal due to the precision needed for waveform interactions.
- **Desktop (>1024px)**: Full layout with sidebar edit history
- **Tablet (768-1024px)**: Edit history collapsed by default, narrower waveform
- **Mobile (<768px)**: Simplified layout, larger touch targets for trim handles, edit history in a bottom sheet
---
## Files
| File | Type | Description |
|------|------|-------------|
| `frontend/components/audio-editor/AudioEditor.tsx` | New | Main container component |
| `frontend/components/audio-editor/WaveformEditor.tsx` | New | Interactive waveform with trim handles and selection |
| `frontend/components/audio-editor/AudioEditorToolbar.tsx` | New | Undo/redo, mode selector, join, submit |
| `frontend/components/audio-editor/PlaybackControls.tsx` | New | Play/pause, seek, speed |
| `frontend/components/audio-editor/AudioTabSwitcher.tsx` | New | Original vs Edited tabs |
| `frontend/components/audio-editor/EditHistoryPanel.tsx` | New | List of applied edits |
| `frontend/components/audio-editor/AudioEditorGuidance.tsx` | New | Help/tips panel |
| `frontend/components/audio-editor/TrimHandle.tsx` | New | Draggable trim markers |
| `frontend/components/audio-editor/SelectionOverlay.tsx` | New | Cut/mute selection region |
| `frontend/components/audio-editor/index.ts` | New | Exports |
| `frontend/app/app/jobs/[[...slug]]/client.tsx` | Edit | Add audio-edit route |
| `frontend/lib/api.ts` | Edit | Add audio edit API methods |
## Testing Strategy
| Test | Type | What |
|------|------|------|
| `AudioEditor.test.tsx` | Unit | Renders, loads audio info, displays waveform |
| `WaveformEditor.test.tsx` | Unit | Canvas rendering, click-to-seek, selection interactions |
| `AudioEditorToolbar.test.tsx` | Unit | Mode switching, undo/redo state |
| `PlaybackControls.test.tsx` | Unit | Play/pause, speed changes |
| `audio-editor.spec.ts` | E2E | Full flow: open editor → trim → submit → verify job continues |
## Resolved Questions
1. **Client-side preview before apply?** — **No.** All processing is server-side only. This ensures the preview is perfectly representative of the final result. FFmpeg operations should complete in a few seconds.
2. **Keyboard shortcuts scope** — Waveform-focused to avoid conflicts with other page elements.
3. **Max audio duration for editing?** — No limit for MVP. Add one later if performance issues arise.
4. **Zoom-to-selection?** — Defer to post-MVP. Nice UX but adds complexity.
@@ -0,0 +1,302 @@
# Edit Input Audio — Phase 5: Session Restore & Admin Dashboard
**Date:** 2026-03-08
**Parent:** [Master Plan](2026-03-08-edit-input-audio-master-plan.md)
**Status:** Complete
**Depends on:** Phases 2, 4
## Goal
Wire up auto-save during audio editing, provide a restore dialog when users return to an in-progress edit, and give admins the ability to view/replay audio edit sessions in the dashboard.
---
## 1. Auto-Save Hook
### `useAudioEditAutoSave`
New hook following the exact pattern of `useReviewSessionAutoSave`:
```typescript
// frontend/hooks/use-audio-edit-autosave.ts
function useAudioEditAutoSave({
jobId: string,
editStack: EditEntry[],
originalDuration: number,
currentDuration: number,
isReadOnly: boolean,
apiClient: ReviewApiClient,
}) {
const lastBackupStackSize = useRef(0)
const computeSummary = useCallback((): AudioEditSessionSummary => {
const breakdown: Record<string, number> = {}
for (const entry of editStack) {
breakdown[entry.operation] = (breakdown[entry.operation] || 0) + 1
}
return {
total_operations: editStack.length,
operations_breakdown: breakdown,
duration_change_seconds: currentDuration - originalDuration,
net_duration_seconds: currentDuration,
}
}, [editStack, originalDuration, currentDuration])
const saveSession = useCallback(async (trigger: string) => {
if (editStack.length === 0) return
if (editStack.length === lastBackupStackSize.current) return
await apiClient.saveAudioEditSession(jobId, {
edit_data: { entries: editStack, started_at: ... },
edit_count: editStack.length,
trigger,
summary: computeSummary(),
})
lastBackupStackSize.current = editStack.length
}, [editStack, ...])
// Save triggers
// 1. Every 3 edits (same cadence as lyrics review)
useEffect(() => {
if (editStack.length > 0 && editStack.length % 3 === 0) {
saveSession("auto")
}
}, [editStack.length, saveSession])
// 2. On page visibility change
useEffect(() => {
const handler = () => {
if (document.hidden) saveSession("auto")
}
document.addEventListener("visibilitychange", handler)
return () => document.removeEventListener("visibilitychange", handler)
}, [saveSession])
return { saveSession }
}
```
### Save Triggers
| Trigger | Condition | `trigger` field |
|---------|-----------|-----------------|
| Every N edits | Every 3 edits | `"auto"` |
| Page hide | `visibilitychange` when tab loses focus | `"auto"` |
| Before submit | Just before submitting edited audio | `"submit"` |
| Manual | User clicks "Save Progress" button | `"manual"` |
---
## 2. Session Restore Dialog
### When It Appears
When the `AudioEditor` component mounts:
1. Call `GET /api/review/{job_id}/audio-edit-sessions` to check for saved sessions
2. If sessions exist → show `AudioEditRestoreDialog`
3. If no sessions → proceed to fresh editor
### Dialog Design
Same split-pane layout as the lyrics review `SessionRestoreDialog`:
```
┌─────────────────────────────────────────────────────┐
│ Saved Audio Edit Sessions [×] │
├──────────────────────┬──────────────────────────────┤
│ Session List │ Edit Preview │
│ │ │
│ ▸ Mar 8, 2:15 PM │ Operations applied: │
│ 3 edits · auto │ │
│ [Most recent] │ 1. Trim start → 0:15 │
│ │ Removed 15s intro │
│ ▸ Mar 8, 1:45 PM │ │
│ 1 edit · auto │ 2. Cut 0:32-0:45 │
│ │ Removed 13s │
│ │ │
│ │ 3. Mute 1:45-1:48 │
│ │ Silenced 3.2s │
│ │ │
│ │ Duration: 4:05 → 3:34 (-31s) │
│ │ │
├──────────────────────┴──────────────────────────────┤
│ [Start Fresh] [Restore Selected] │
└─────────────────────────────────────────────────────┘
```
### Restore Behavior
When user clicks "Restore Selected":
1. Load full session data: `GET /api/review/{job_id}/audio-edit-sessions/{session_id}`
2. Replay edit entries:
- For each entry in `edit_data.entries`, call `POST /audio-edit/apply` sequentially
- Show progress indicator: "Restoring edit 2 of 3..."
- Each apply returns the updated waveform and audio
3. After all edits replayed, editor is in the same state as when the session was saved
4. User can continue editing from where they left off
### Alternative: Server-side Replay
Instead of replaying edits client-side, the backend could:
1. Accept a session_id in a new endpoint: `POST /audio-edit/restore-session`
2. Backend replays all operations server-side
3. Returns final state (waveform, playback URL, edit stack)
This is faster and more reliable. The frontend just needs to load the final state.
**Recommendation:** Server-side replay for MVP. Client-side replay only needed if we want to show animated step-by-step restoration.
---
## 3. "Save Progress" Button
Add to the `AudioEditorToolbar`:
```
[⟲ Undo] [⟳ Redo] | [✂️ Trim] [✂ Cut] [🔇 Mute] [📎 Join] | [💾 Save] | [Submit & Continue →]
```
- "Save" button triggers `saveSession("manual")`
- Shows toast notification: "Progress saved" / "No new changes"
- Disabled when no edits have been made
---
## 4. Admin Dashboard
### Audio Edit Reviews Page
New admin page: `/admin/audio-edits`
Follows the same pattern as `/admin/edit-reviews` for lyrics.
### List View
```
┌──────────────────────────────────────────────────────────┐
│ Audio Edit Reviews [Search 🔍] │
├──────────────────────────────────────────────────────────┤
│ Job ID │ Artist │ Title │ Edits │ Status │
│──────────────────────────────────────────────────────────│
│ abc12345 │ Queen │ Bohemian... │ 3 │ ✓ Done │
│ def67890 │ Taylor Swift │ Shake It... │ 1 │ ⏳ In Progress │
└──────────────────────────────────────────────────────────┘
```
### Detail View
Click a job to see its audio edit history:
```
┌──────────────────────────────────────────────────────────┐
│ Audio Edit: Queen - Bohemian Rhapsody (abc12345) │
├──────────────────────────────────────────────────────────┤
│ │
│ Original Audio │
│ [▶ Play] Duration: 4:05 │
│ ██████████████████████████████████████████████ (waveform)│
│ │
│ Edited Audio │
│ [▶ Play] Duration: 3:34 │
│ ████████████████████████████████████████ (waveform) │
│ │
│ Edit Log: │
│ ───────── │
│ 1. [12:01:30] trim_start → removed 0:00-0:15 (15s) │
│ 2. [12:03:15] cut → removed 0:17-0:30 (13s) │
│ 3. [12:05:42] mute → silenced 1:30-1:33 (3.2s) │
│ │
│ Sessions: 2 auto-saves, 1 submit │
│ User: andrew@nomadkaraoke.com │
│ Submitted: Mar 8, 2026 12:06 PM │
└──────────────────────────────────────────────────────────┘
```
### Admin API Endpoints
Add to `backend/api/routes/admin.py`:
#### `GET /api/admin/audio-edit-reviews`
List jobs that have audio edit sessions.
**Query params:**
- `q`: Search by artist, title, job_id
- `exclude_test`: Filter test emails
- `limit`: Max results (default 50)
**Implementation:**
- Query jobs where `state_data.requires_audio_edit == true`
- Return summary with job metadata + edit count
#### `GET /api/admin/audio-edit-reviews/{job_id}`
Get full audio edit review for a job.
**Response:**
```json
{
"job_id": "abc123",
"artist": "Queen",
"title": "Bohemian Rhapsody",
"user_email": "andrew@...",
"original_audio_url": "https://...", // Signed URL
"edited_audio_url": "https://...", // Signed URL
"original_waveform": { "amplitudes": [...], "duration": 245.3 },
"edited_waveform": { "amplitudes": [...], "duration": 212.8 },
"edit_sessions": [
{
"session_id": "...",
"trigger": "submit",
"edit_count": 3,
"summary": { ... },
"edit_data": { "entries": [...] }
}
]
}
```
---
## 5. Admin Navigation
Add "Audio Edits" link to admin sidebar, alongside existing "Edit Reviews" link:
```typescript
// In admin layout
{ href: "/admin/audio-edits", label: "Audio Edits", icon: Scissors }
```
---
## Files Changed
| File | Type | Changes |
|------|------|---------|
| `frontend/hooks/use-audio-edit-autosave.ts` | New | Auto-save hook |
| `frontend/components/audio-editor/AudioEditRestoreDialog.tsx` | New | Session restore modal |
| `frontend/components/audio-editor/AudioEditor.tsx` | Edit | Wire up auto-save + restore |
| `frontend/components/audio-editor/AudioEditorToolbar.tsx` | Edit | Add Save button |
| `frontend/app/admin/audio-edits/page.tsx` | New | Admin list view |
| `frontend/app/admin/audio-edits/[jobId]/page.tsx` | New | Admin detail view |
| `frontend/lib/api.ts` | Edit | Add audio edit session API methods + admin endpoints |
| `backend/api/routes/admin.py` | Edit | Add audio edit review endpoints |
## Testing Strategy
| Test | Type | What |
|------|------|------|
| `use-audio-edit-autosave.test.ts` | Unit | Save triggers, dirty tracking, dedup |
| `AudioEditRestoreDialog.test.tsx` | Unit | Session list, selection, restore action |
| `admin-audio-edits.test.tsx` | Unit | Admin list and detail views render |
| `audio-edit-session-restore.spec.ts` | E2E | Full flow: edit → close → reopen → restore → continue |
## Resolved Questions
1. **Cross-job session restore?** — **No.** Audio edits are position-specific and unlikely to transfer across jobs.
2. **Admin replay animation?** — **No for MVP.** Show the edit log as a list + before/after waveforms and audio playback.
3. **Session pruning?** — Cap at 20 sessions per job. Auto-prune oldest auto-saves when limit is reached.
@@ -0,0 +1,200 @@
# Fix: Encoding Orchestration Killed by Cloud Run Deployments
**Date:** 2026-03-08
**Incident:** Job `43c0d519` (Westlife - Medley) stuck at `encoding` status for 4+ hours
**Branch:** `feat/sess-20260308-2013-fix-encoding-deploy-survival`
---
## Incident Analysis
### What Happened
1. **16:18:18** — Video worker HTTP request returned `200` after 80s. The encoding orchestration (submit to GCE, poll, download, upload) continued as a FastAPI `BackgroundTask`.
2. **16:19:19** — GitHub Actions deployed new Cloud Run revision `karaoke-backend-00573-glx`.
3. **16:19:25** — `DEPLOYMENT_ROLLOUT`: new instances started, old instances began draining.
4. **16:19:39** — Old instance (still running background encoding task) submitted encoding to GCE worker.
5. **16:20:10** — GCE worker connection failed (attempt 1/8). Old instance was being terminated.
6. **After 16:20:10** — No more logs. Instance killed. Job stuck permanently at `encoding` status.
### Why Existing Protections Didn't Help
The three-layer defense (PRs #413, #473) protects against the **GCE encoding worker** being restarted:
| Layer | What It Protects | Why It Didn't Help Here |
|-------|-----------------|------------------------|
| CI graceful drain | GCE worker restart waits for active FFmpeg jobs | The GCE worker wasn't restarted — Cloud Run was |
| Extended retries (90s) | Connection failures to GCE worker during restart | Cloud Run killed the instance before retries completed |
| Poll failure tolerance | Transient poll errors during GCE worker restart | The poller itself was killed, not just failing |
**The gap:** All protections assume the Cloud Run orchestrator stays alive. None protect against the orchestrator itself being killed during a deployment.
### Root Cause: `BackgroundTask` Pattern
The video worker endpoint (`internal.py:264`) uses FastAPI's `BackgroundTask`:
```python
background_tasks.add_task(generate_video, job_id) # Fire-and-forget
return WorkerResponse(status="started", ...) # HTTP response returns immediately
```
Cloud Run considers the request "complete" once the response is sent. During a deployment rollout:
- Old instances are **drained** (no new requests routed to them)
- Once no active HTTP requests remain, old instances are **terminated**
- `BackgroundTask` work is silently killed
The encoding orchestration (which takes 2-5+ minutes) runs entirely after the HTTP response, making it vulnerable to termination at any time.
### The Fix Already Exists (But Is Disabled)
**Cloud Run Jobs support was already built** in PR #155 (Dec 2025) for exactly this reason:
- **Infrastructure:** `video-encoding-job` Cloud Run Job provisioned via Pulumi (`infrastructure/modules/cloud_run.py:374`)
- **Code:** `worker_service.py:427` has `_trigger_cloud_run_job()` that dispatches to Cloud Run Jobs
- **Feature flag:** `USE_CLOUD_RUN_JOBS_FOR_VIDEO` env var controls the routing
Cloud Run Jobs run to completion (up to 24h) with no HTTP request lifecycle — they're immune to deployment rollouts.
**Why it's disabled:** The env var `USE_CLOUD_RUN_JOBS_FOR_VIDEO=true` was set in the old `cloudbuild.yaml` (commit `db2c5a03`) but was **dropped when CI migrated to GitHub Actions** (`.github/workflows/ci.yml`). The current CI env vars on line 1319 include `USE_GCE_ENCODING=true` but not `USE_CLOUD_RUN_JOBS_FOR_VIDEO=true`.
---
## Implementation Plan
### Option A: Re-enable Cloud Run Jobs for Video (Recommended)
**Effort:** Small (env var + verification)
**Risk:** Low (infrastructure and code already exist and were previously deployed)
#### Step 1: Add missing env var to CI
In `.github/workflows/ci.yml` line 1319, add `USE_CLOUD_RUN_JOBS_FOR_VIDEO=true` to the `--set-env-vars` string.
#### Step 2: Verify Cloud Run Job infrastructure is current
```bash
# Check the job exists and has the right image
gcloud run jobs describe video-encoding-job --region=us-central1 --project=nomadkaraoke
```
The Cloud Run Job uses the `latest` image tag, so it should already be using the current backend image. Verify:
- Image matches current backend image
- Timeout is 3600s (1 hour)
- Service account has correct permissions
- Environment variables include necessary secrets
#### Step 3: Ensure Cloud Run Job has all required env vars and secrets
The Cloud Run Job defined in Pulumi (`infrastructure/modules/cloud_run.py:407-416`) only has `GOOGLE_CLOUD_PROJECT` and `GCS_BUCKET_NAME`. It's missing critical env vars and secrets that the video worker needs:
- `USE_GCE_ENCODING=true`
- `ENCODING_WORKER_URL` and `ENCODING_WORKER_API_KEY` (secrets)
- `DEFAULT_DROPBOX_PATH`, `DEFAULT_GDRIVE_FOLDER_ID`, etc.
- `DEFAULT_ENABLE_YOUTUBE_UPLOAD`, `DEFAULT_BRAND_PREFIX`
- All the secrets the backend needs (Discord webhook, Stripe, etc.)
**This is likely why it was disabled** — the Cloud Run Job env was incomplete.
Options:
a. **Mirror all env vars/secrets from the Cloud Run Service** to the Job in Pulumi (tedious but correct)
b. **Have the Job fetch config from Secret Manager at runtime** (more elegant but requires code changes)
c. **Use a shared env config module in Pulumi** that both Service and Job reference
#### Step 4: Update the Cloud Run Job image in CI
The CI workflow deploys new images to Cloud Run Service but doesn't update the Cloud Run Job's image. Need to add a step:
```bash
gcloud run jobs update video-encoding-job \
--image="${REGION}-docker.pkg.dev/${PROJECT_ID}/karaoke-repo/karaoke-backend:${VERSION}" \
--region=us-central1 \
--project=${PROJECT_ID}
```
#### Step 5: Test with a real job
1. Deploy the changes
2. Trigger a video worker for a test job
3. Verify it runs as a Cloud Run Job (check Cloud Run Jobs console)
4. Verify encoding completes and all outputs are uploaded
#### Step 6: Add deployment protection test
Create a test that:
- Triggers video encoding via Cloud Run Job
- Simulates a deployment (deploy new Cloud Run Service revision) mid-encoding
- Verifies the Job completes unaffected
### Option B: SIGTERM Handler + Re-enqueue (Alternative)
**Effort:** Medium
**Risk:** Medium (new code path, race conditions)
Add a SIGTERM handler to the Cloud Run Service that:
1. Catches SIGTERM during background task execution
2. Checks if encoding is in-flight
3. Re-triggers the video worker via Cloud Tasks (which will run on a new instance)
This is more complex and has edge cases (what if re-trigger also gets killed?). Option A is simpler.
### Option C: Keep Connection Open (Alternative)
**Effort:** Small
**Risk:** Low but has timeout implications
Instead of `background_tasks.add_task()`, run the video worker inline within the HTTP request handler. This keeps the connection active, preventing Cloud Run from killing the instance during drain.
```python
# Instead of:
background_tasks.add_task(generate_video, job_id)
return WorkerResponse(status="started", ...)
# Do:
success = await generate_video(job_id)
return WorkerResponse(status="completed" if success else "failed", ...)
```
**Pros:** Simple change, no infrastructure needed
**Cons:**
- Cloud Run request timeout is 1800s (30 min) — encoding can exceed this
- Cloud Tasks dispatch deadline might conflict
- The caller must keep the connection open for the full duration
- During drain, Cloud Run waits for active requests but has a grace period limit
---
## Recommendation
**Option A (re-enable Cloud Run Jobs)** is the right fix because:
1. Infrastructure already provisioned and code already written
2. Cloud Run Jobs are purpose-built for long-running batch work
3. Immune to deployment rollouts by design
4. Already used successfully for audio downloads (PR #496)
**However**, Step 3 (env vars/secrets) is the critical blocker — the Job needs the same configuration as the Service. This was likely why it was disabled after the cloudbuild.yaml migration.
**Immediate fix for job `43c0d519`:** Re-trigger the video worker manually:
```bash
curl -X POST "https://api.nomadkaraoke.com/api/internal/workers/video" \
-H "X-Admin-Token: $(gcloud secrets versions access latest --secret=admin-tokens --project=nomadkaraoke)" \
-H "Content-Type: application/json" \
-d '{"job_id": "43c0d519"}'
```
---
## Files to Change
| File | Change |
|------|--------|
| `.github/workflows/ci.yml` | Add `USE_CLOUD_RUN_JOBS_FOR_VIDEO=true` to env vars |
| `.github/workflows/ci.yml` | Add step to update Cloud Run Job image on deploy |
| `infrastructure/modules/cloud_run.py` | Add all required env vars and secrets to `video-encoding-job` |
| `docs/LESSONS-LEARNED.md` | Add lesson about env vars dropped during CI migration |
| `docs/TROUBLESHOOTING.md` | Update "stuck at encoding" section with this new failure mode |
## Testing Strategy
- **Unit tests:** Verify `trigger_video_worker` routes to Cloud Run Jobs when `USE_CLOUD_RUN_JOBS_FOR_VIDEO=true`
- **Integration test:** Trigger video worker and verify Cloud Run Job is created
- **Production verification:** Run a test job end-to-end after deployment
@@ -0,0 +1,40 @@
# Plan: Fuzzy "Did you mean?" correction for typos
**Created:** 2026-03-08
**Branch:** feat/sess-20260308-0139-step2-song-suggestions
**Status:** Draft
## Overview
When a user types a misspelled song title (e.g. "ruises" instead of "Bruises"), the audio search returns poor results (Tier 3 / no lossless) and the catalog search returns nothing. The user has no signal they made a typo. We add a second-pass fuzzy search that triggers when results are poor: fetch the artist's discography from the catalog, fuzzy-match against the user's title, and show a "Did you mean X?" banner. Clicking "Yes" corrects the title and restarts the audio search.
## Technical Approach
1. **Trigger condition:** Audio search completes with Tier 3 or no results AND catalog search returned 0 results
2. **Fuzzy search:** Call `api.searchCatalogTracks(artist, artist, 20)` — search the artist's name as the query with artist filter to get their top tracks. This is a broader search that doesn't require matching the title.
3. **Client-side fuzzy match:** Compare each returned track name against the user's title using simple Levenshtein-like similarity (normalized). Pick the best match above a threshold (e.g. 0.6 similarity).
4. **"Did you mean?" banner:** Prominent amber banner with the suggested correction. "Yes, search again" button restarts audio search with corrected artist/title.
5. **Restart flow:** Reset search state, update artist/title via parent callback, re-trigger `doSearch()`.
## Fuzzy Matching Algorithm
Simple approach — no external dependency needed:
- Lowercase both strings
- Calculate longest common subsequence (LCS) ratio: `2 * LCS_length / (len(a) + len(b))`
- Also check if user's title is a substring of the track name or vice versa
- Threshold: 0.6 for LCS ratio, or substring match with length >= 3
- Pick the highest-scoring match
## Files to Modify
| File | Action | Description |
|------|--------|-------------|
| `frontend/components/job/steps/AudioSourceStep.tsx` | Modify | Add fuzzy search trigger, "Did you mean?" banner, restart logic |
## Implementation Steps
1. Add `fuzzyMatch()` utility function (inline in AudioSourceStep)
2. Add state for fuzzy suggestion (`fuzzySuggestion`, `fuzzyDismissed`)
3. Add `useEffect` that triggers fuzzy search when audio search completes with poor results + no catalog results
4. Add `DidYouMeanBanner` component
5. Add restart handler that clears state and re-runs search with corrected name
@@ -0,0 +1,85 @@
# Plan: Move Song DB Suggestions from Step 1 to Step 2
**Created:** 2026-03-08
**Branch:** feat/sess-20260308-0139-step2-song-suggestions
**Status:** Implemented
## Overview
The autocomplete on Step 1's title field is confusing — users don't know why they should wait for it or select a suggestion. Instead, we'll remove autocomplete from Step 1 (making it a simple text entry) and show song DB suggestions in Step 2 while the audio search is loading. This uses the ~15-30s wait time productively and presents suggestions with clear context about what they are and why.
## Requirements
- [x] Remove `AutocompleteInput` from Step 1 title field → plain `<Input>`
- [x] Keep community version check in Step 1 (non-blocking, useful)
- [x] Fire `api.searchCatalogTracks()` in parallel with `api.searchStandalone()` on Step 2 mount
- [x] Show catalog results in Step 2 as a "song name correction" panel
- [x] Clicking a suggestion updates artist/title (the search artist/title used for job creation)
- [x] Panel is dismissible, doesn't appear if no results
- [x] Catalog search failure is silent (doesn't affect audio search)
- [x] Works well on mobile
## Technical Approach
**No new API endpoints needed** — we already have `api.searchCatalogTracks()`.
**Data flow change:** In Step 2, `AudioSourceStep` gets two new props:
- `onArtistTitleCorrection(artist: string, title: string)` — called when user picks a suggestion
- The parent (`GuidedJobFlow`) updates `artist`/`title` state, which re-renders the "Searching for X - Y" header
**Key decision:** When the user corrects artist/title via catalog suggestion, this updates the *search* artist/title (used in `createJobFromSearch`). It does NOT restart the audio search — that would be confusing and waste time. The audio search already happened with the original terms.
## Implementation Steps
### Step 1: Simplify SongInfoStep (remove autocomplete)
1. [x] Replace `AutocompleteInput` with plain `<Input>` for the title field
2. [x] Remove `fetchTrackSuggestions` callback and `AutocompleteInput` import
3. [x] Keep all other functionality (community check, tips, form validation)
### Step 2: Add catalog search to AudioSourceStep
4. [x] Add `onArtistTitleCorrection` prop to `AudioSourceStepProps`
5. [x] Add state: `catalogResults`, `catalogLoading`, `catalogDismissed`
6. [x] Fire `api.searchCatalogTracks(title, artist, 5)` in parallel with `doSearch()` in the mount effect
7. [x] Build `SongSuggestionPanel` inline component showing results
### Step 3: Wire up GuidedJobFlow
8. [x] Add handler in `GuidedJobFlow` that updates `artist`/`title` when catalog suggestion selected
9. [x] Pass handler to `AudioSourceStep` as `onArtistTitleCorrection`
### Step 4: Testing
10. [ ] Run existing E2E tests to verify no regressions
11. [ ] Manual visual check in dev server
## Files to Create/Modify
| File | Action | Description |
|------|--------|-------------|
| `frontend/components/job/steps/SongInfoStep.tsx` | Modify | Remove AutocompleteInput, use plain Input for title |
| `frontend/components/job/steps/AudioSourceStep.tsx` | Modify | Add parallel catalog search + suggestion panel |
| `frontend/components/job/GuidedJobFlow.tsx` | Modify | Add artist/title correction handler, pass to Step 2 |
## SongSuggestionPanel Design
```
┌─────────────────────────────────────────────┐
│ 🔍 Found matching songs │
│ Click to use the official formatting: │
│ │
│ ┌─ Fox Stevenson - Don't Care Crown ──── ┐ │
│ └──────────────────────────────────────── ┘ │
│ ┌─ Fox Stevenson - Don't Care Crown... ─ ┐ │
│ └──────────────────────────────────────── ┘ │
│ Dismiss ↗ │
└─────────────────────────────────────────────┘
```
- Appears between the "Searching for X - Y" header and the loading spinner
- Uses existing design language (card with border, muted colors)
- Each result is a clickable row showing `Artist - Track` with a subtle "Use" button
- When selected: row highlights briefly, artist/title update, panel auto-dismisses
- "Dismiss" link at bottom to hide permanently
- If already matches exactly, skip showing that result
## Rollback Plan
Revert the branch. No backend changes, no data migrations.
@@ -0,0 +1,159 @@
# Plan: Visibility Step Layout Rework
**Date**: 2026-03-08
**Branch**: `feat/visibility-step-layout`
**Status**: Implemented
## Problem
The Visibility step requires scrolling past two detailed info cards to reach the Continue button. Users who already know what they want (especially repeat users) are forced to scroll every time.
Screenshot shows: header → Published card (large) → Private card (large) → Continue button (below fold).
## Design Decision
**Chosen approach: Action buttons at top, detail cards below as reference.**
Two prominent, descriptive buttons placed immediately after the header let users select-and-continue in one click. The existing detail cards remain below for first-time users who want to understand the implications before choosing.
### Why this over alternatives
| Approach | Pros | Cons |
|----------|------|------|
| **Action buttons at top** (chosen) | Zero scroll for decisive users; details still visible for cautious users; single click to proceed | Two interaction patterns (buttons vs cards) |
| Move Continue to top | Simple change | Still requires scrolling to understand options before clicking |
| Collapsible detail cards | Compact | Hides important info by default; extra click to expand |
| Sticky bottom button | Easy to implement | Overlaps content on small screens; still generic "Continue" |
| Auto-advance on card select | Fewest clicks | No chance to change mind; jarring UX |
## Design Spec
### New Layout (top to bottom)
```
Header: "How should your video be shared?"
Subtitle + Back button (unchanged)
┌─────────────────────────────────────────────────┐
│ [🌐 Publish & Share →] [🔒 Keep Private →] │
│ Recommended │
└─────────────────────────────────────────────────┘
── What's the difference? ──────────────── (divider)
[Published detail card] (informational, still clickable to select)
[Private detail card] (informational, still clickable to select)
```
### Action Buttons Detail
- **Two buttons side-by-side** in a flex row with `gap-3`
- Each button is a bordered card-style button (~equal width via `flex-1`)
- **"Publish & Share"** button: Globe icon, "Recommended" badge below, pink border/highlight when Published is currently selected
- **"Keep Private"** button: Lock icon, neutral border, pink highlight when Private is currently selected
- **Clicking either button calls both `onPrivateChange()` AND `onNext()`** — single action to select and continue
- Arrow icon (→) on each button reinforces that clicking advances the flow
- Desktop: side by side. Mobile (`< sm`): stack vertically
### Detail Cards
- Keep the existing Published and Private cards **exactly as-is** content-wise
- They remain clickable (toggling the selection) but do **not** auto-advance
- Add a subtle text divider above them: "What's the difference?" in muted text with horizontal rules
- When a user clicks a detail card, it updates the selection and the action buttons above visually reflect the change — but the user still needs to click an action button (or scroll back up) to continue. This is intentional: clicking a card means "I'm still reading/deciding."
- Consider slightly reducing vertical padding on cards (`p-4` → `p-3`) to reduce total page height
### Visual Treatment
- Action buttons use the same `var(--brand-pink)` theming as the rest of the step
- Selected action button: pink border + subtle glow (matching current card selection style)
- Unselected action button: `var(--card-border)` border, muted icon
- Both buttons have hover states with border color transition
- The "Recommended" label sits under the Publish button (not inside it) as a small badge
### Responsive Behavior
- **Desktop (≥640px / `sm`)**: Action buttons side-by-side
- **Mobile (<640px)**: Action buttons stack vertically, Publish on top
## Implementation
### Files to Change
1. **`frontend/components/job/steps/VisibilityStep.tsx`** — the only file that needs changes
### Steps
1. **Add action buttons section** after the header div and before the detail cards
- Two `<button>` elements in a flex container
- Each calls `onPrivateChange(value)` then `onNext()` on click
- Styled as card-like buttons with icon + label + optional badge
- Use existing CSS variable theming
2. **Add divider** between action buttons and detail cards
- Simple flex row with horizontal rules and muted text: "What's the difference?"
3. **Keep existing detail cards** unchanged (content, styling, click handlers)
- Only change: remove the bottom Continue button entirely
4. **Remove the bottom Continue button** — no longer needed since action buttons serve this purpose
### Code Sketch
```tsx
{/* Action buttons - select and continue */}
<div className="flex flex-col sm:flex-row gap-3">
<button
type="button"
onClick={() => { onPrivateChange(false); onNext(); }}
disabled={disabled}
className={`flex-1 rounded-lg border-2 p-4 transition-all text-center ${
!isPrivate
? 'border-[var(--brand-pink)] shadow-[0_0_12px_rgba(255,122,204,0.2)]'
: 'border-[var(--card-border)] hover:border-[var(--text-muted)]'
}`}
>
<Globe />
<span>Publish & Share</span>
<ArrowRight />
{/* Recommended badge below */}
</button>
<button
type="button"
onClick={() => { onPrivateChange(true); onNext(); }}
disabled={disabled}
className={`flex-1 rounded-lg border-2 p-4 transition-all text-center ${
isPrivate
? 'border-[var(--brand-pink)] shadow-[0_0_12px_rgba(255,122,204,0.2)]'
: 'border-[var(--card-border)] hover:border-[var(--text-muted)]'
}`}
>
<Lock />
<span>Keep Private</span>
<ArrowRight />
</button>
</div>
{/* Divider */}
<div className="flex items-center gap-3">
<div className="flex-1 h-px bg-[var(--card-border)]" />
<span className="text-xs text-[var(--text-muted)]">What's the difference?</span>
<div className="flex-1 h-px bg-[var(--card-border)]" />
</div>
{/* Existing detail cards (unchanged) */}
```
## Testing
- Visual: verify no-scroll path works on common viewport sizes (desktop, tablet, mobile)
- Functional: clicking action buttons correctly sets visibility AND advances to step 4
- Functional: clicking detail cards still toggles selection without advancing
- Functional: Back button still works
- Functional: disabled state prevents all interactions
- Accessibility: buttons are keyboard navigable, focus states visible
## Estimate
Small change — single component, ~40 lines added, ~6 lines removed. Should take one implementation session.
@@ -0,0 +1,58 @@
# Plan: Pre-generate Audio Editor Assets
**Created:** 2026-03-09
**Branch:** feat/sess-20260309-1749-pregenerate-audio-editor
**Status:** In Progress
## Overview
The audio editor UI takes 10-20 seconds to load because it generates waveform data and transcodes FLAC→OGG on-demand when the user opens the editor. The lyrics/instrumental review UI doesn't have this problem because `screens_worker` eagerly pre-generates all assets before the job reaches `awaiting_review`.
We need the same eager pre-generation for audio editing: transcode the input audio to OGG and generate waveform data *during* the download worker, before the job transitions to `awaiting_audio_edit`. Then the `input-audio-info` endpoint serves cached data instead of computing it from scratch.
## Current Flow (Slow)
```
audio_download_worker: downloads FLAC → saves to GCS → transitions to awaiting_audio_edit
(no pre-generation)
User opens editor → GET /input-audio-info →
1. download FLAC from GCS to Cloud Run tmp (~5-8s)
2. generate waveform from FLAC (pydub) (~2-3s)
3. transcode FLAC→OGG + upload to GCS (~3-5s)
4. generate signed URL (~0.5s)
Total: ~10-20s
```
## Target Flow (Fast)
```
audio_download_worker: downloads FLAC → saves to GCS →
pre-generate:
1. transcode FLAC→OGG (reuse AudioTranscodingService)
2. generate waveform data → save as JSON to GCS
→ transitions to awaiting_audio_edit
User opens editor → GET /input-audio-info →
1. load cached waveform JSON from GCS (~0.5s)
2. generate signed URL for cached OGG (~0.5s)
Total: ~1s
```
## Implementation Steps
1. [ ] Add `cache_waveform_data` and `load_cached_waveform` to `AudioAnalysisService`
2. [ ] Add pre-generation to `audio_download_worker` before `awaiting_audio_edit` transition
3. [ ] Modify `input-audio-info` endpoint to use cached waveform when available
4. [ ] Add unit tests for cache methods, download worker, and endpoint cache hit/miss
5. [ ] Run full test suite
## Files to Modify
| File | Description |
|------|-------------|
| `backend/services/audio_analysis_service.py` | Add waveform cache/load methods |
| `backend/workers/audio_download_worker.py` | Add pre-generation before state transition |
| `backend/api/routes/review.py` | Use cached waveform in `input-audio-info` |
| `backend/tests/test_audio_edit_routes.py` | Tests for cache hit/miss |
| `backend/tests/test_audio_download_worker.py` | Test for pre-generation call |
@@ -0,0 +1,294 @@
# Plan: Store Job Processing Metadata Permanently
**Date**: 2026-03-10
**Branch**: `feat/sess-20260309-2358-store-audioshake-ids`
**Status**: Implemented (all 6 phases)
## Problem
During a data export for AudioShake (lyrics correction feedback), we discovered that AudioShake task_id and asset_id were only stored ephemerally during processing and never persisted. We had to do a complex one-off recovery from Cloud Logging + AudioShake API pagination to reconstruct the mapping.
This is symptomatic of a broader issue: many pieces of valuable metadata generated during job processing are only logged or held in memory, then discarded. When a future data export, debugging, or analytics need arises, we're left scrambling to recover from logs (which have limited retention).
## Goals
1. **Immediate**: Persist AudioShake task_id and asset_id permanently with each job
2. **Broader**: Identify and store other high-value processing metadata that would be painful to reconstruct later
3. **Principle**: "Store it when you have it" - the cost of storing a few extra fields is negligible compared to the cost of not having them later
## Design: `processing_metadata` Field
Add a new top-level dict field `processing_metadata` to the Job model, separate from `state_data` (which is mutable workflow state). `processing_metadata` is **write-once** data captured during processing that describes _how_ the job was processed.
### Why Not `state_data`?
- `state_data` is for mutable workflow state (current stems, build IDs, etc.)
- `processing_metadata` is for immutable audit/provenance data
- Keeps concerns separate: "what stage is the job in" vs "how was it processed"
- Easier to project in queries (one field to include vs picking through state_data keys)
### Schema
```python
# In Job model
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": "cmmjpbo7f...",
"audioshake_asset_id": "cmmjpbma4...",
"language_detected": "en",
"duration_seconds": 125.5,
"word_count": 358,
"segment_count": 42,
},
"correction": {
"handlers_applied": ["anchor_sequence", "gap_word_count", ...],
"corrections_made": 12,
"correction_ratio": 0.034,
"reference_sources_found": ["genius", "spotify", "lrclib"],
"agentic_routing": "rule-based",
"duration_seconds": 33.2,
},
"separation": {
"provider": "modal",
"clean_model": "model_bs_roformer_ep_317_sdr_12.9755.ckpt",
"backing_models": ["mel_band_roformer_karaoke_aufr33_viperx_sdr_10.1956.ckpt"],
"stems_generated": ["clean", "with_backing", "vocals", "backing_vocals"],
"duration_seconds": 420.5,
},
"audio_source": {
"input_format": "flac",
"input_sample_rate": 44100,
"input_channels": 2,
"input_duration_seconds": 210.4,
"input_file_size_bytes": 26541900,
},
"rendering": {
"render_duration_seconds": 18.7,
"encoding_duration_seconds": 180.5,
"output_formats": ["lossless_4k_mkv", "lossless_4k_mp4", "lossy_4k_mp4", "lossy_720p_mp4"],
"output_sizes_bytes": {
"lossless_4k_mkv": 45168200,
"lossy_720p_mp4": 34571800,
},
},
"review": {
"review_duration_seconds": 450.2,
"corrections_made_by_human": 5,
"total_words_reviewed": 358,
"instrumental_selected": "clean",
},
"distribution": {
"youtube_video_id": "dQw4w9WgXcQ",
"youtube_upload_duration_seconds": 240.5,
"dropbox_upload_duration_seconds": 120.5,
"gdrive_upload_duration_seconds": 95.3,
},
"cache": {
"transcription_cache_hit": true,
"lyrics_cache_hits": {"genius": true, "spotify": true, "lrclib": false},
},
"timing": {
"total_processing_seconds": 890.2,
"worker_durations": {
"audio": 420.5,
"lyrics": 125.3,
"screens": 45.2,
"render_video": 18.7,
"video": 180.2,
},
},
}
```
### Field Projection
Per the known gotcha (MEMORY.md), when adding new fields the dashboard needs, must add to BOTH:
1. `SUMMARY_FIELD_PATHS` in `backend/services/firestore_service.py`
2. `_SUMMARY_STATE_DATA_KEYS` in `backend/api/routes/jobs.py`
For `processing_metadata`, we'll add it to `SUMMARY_FIELD_PATHS` so it's available in job list queries. Since it's a top-level field (not under `state_data`), it doesn't need `_SUMMARY_STATE_DATA_KEYS`.
## Implementation Plan
### Phase 1: AudioShake IDs (Priority - the original ask)
**Files to modify:**
1. **`backend/models/job.py`** - Add `processing_metadata` field to Job model
2. **`karaoke_gen/lyrics_transcriber/core/controller.py`** - Pass transcription metadata (including task_id) through to CorrectionResult.metadata
3. **`backend/workers/lyrics_worker.py`** - Extract AudioShake IDs + transcription metadata from corrections.json and store in `processing_metadata.transcription`
4. **`backend/services/firestore_service.py`** - Add `processing_metadata` to `SUMMARY_FIELD_PATHS`
5. **`backend/api/routes/jobs.py`** - Ensure `processing_metadata` is included in job responses
**Detail:**
In `controller.py`, the `_convert_result_format` method on AudioShakeTranscriber already stores `task_id` in `TranscriptionData.metadata`. The issue is that `LyricsCorrector.run()` builds a new `CorrectionResult.metadata` dict that doesn't include this data. Fix:
- In `corrector.py`, pass through the primary transcription's metadata into the CorrectionResult metadata dict
- In `lyrics_worker.py`, after loading corrections.json, extract `metadata.transcription_metadata` and write to `processing_metadata`
Alternatively (simpler): in `lyrics_worker.py`, we already have access to the transcription result object. We can extract the AudioShake IDs directly from it before they're lost, and store them in `processing_metadata`.
**Chosen approach**: Store in `lyrics_worker.py` right after transcription completes, since we have direct access to the result there. Also flow the metadata through corrections.json for data integrity.
### Phase 2: Worker Timing & Processing Stats
**Files to modify:**
6. **`backend/workers/lyrics_worker.py`** - Add timing data + correction stats to `processing_metadata`
7. **`backend/workers/audio_worker.py`** - Add separation timing + model info to `processing_metadata`
8. **`backend/workers/screens_worker.py`** - Add screen generation timing
9. **`backend/workers/render_video_worker.py`** - Add render timing
10. **`backend/workers/video_worker.py`** / **`video_worker_orchestrator.py`** - Add encoding timing + output file sizes
**For each worker, the pattern is:**
```python
# At the end of successful processing:
job_manager.update_processing_metadata(job_id, 'separation', {
'provider': 'modal',
'clean_model': model_names.get('clean'),
'duration_seconds': round(sep_duration, 1),
...
})
```
### Phase 3: Audio Source & Cache Metadata
**Files to modify:**
11. **`backend/workers/lyrics_worker.py`** - Cache hit/miss stats
12. **`backend/api/routes/jobs.py`** or audio download handler - Input audio metadata (format, sample rate, duration, file size)
### Phase 4: Review & Distribution Metadata
**Files to modify:**
13. **`backend/api/routes/review.py`** - Review completion metadata (duration, corrections count)
14. **`backend/workers/video_worker.py`** - YouTube upload metadata (video ID is probably already stored, but upload timing is not)
### JobManager Helper
Add a helper method to JobManager for appending to `processing_metadata` without overwriting:
```python
def update_processing_metadata(self, job_id: str, section: str, data: dict):
"""Merge data into processing_metadata[section]. Write-once per section."""
from google.cloud.firestore_v1 import transforms
self.db.collection("jobs").document(job_id).update({
f"processing_metadata.{section}": data,
})
```
## Testing Strategy
### Unit Tests
- **`backend/tests/test_job_model.py`**: Verify `processing_metadata` field exists and defaults to empty dict
- **`backend/tests/test_lyrics_worker.py`**: Mock transcription result with AudioShake metadata, verify it's stored in `processing_metadata.transcription`
- **`backend/tests/test_audio_worker.py`**: Verify separation metadata stored
- **`backend/tests/test_job_manager.py`**: Test `update_processing_metadata` helper
### Integration Tests
- **`backend/tests/integration/`**: Firestore emulator test that processes a job through lyrics worker and verifies `processing_metadata` is written correctly
### Regression Test
- Add a test asserting `processing_metadata` is in `SUMMARY_FIELD_PATHS` (per the known gotcha)
## Migration
No migration needed for existing jobs - `processing_metadata` defaults to `{}`. New jobs will populate it as they process. The extraction script (`extract_audioshake_corrections.py`) already handles the one-off backfill for historical AudioShake IDs.
### Phase 5: Input Audio Metadata (ffprobe at ingest)
Currently we have ffprobe and pydub available in workers, but never store audio properties permanently. When a user uploads or we download audio, run ffprobe once and store the results.
**Files to modify:**
15. **`backend/workers/audio_worker.py`** (or wherever audio is first downloaded to disk) - Run ffprobe on the input audio file and store:
```json
"audio_source": {
"input_format": "flac",
"input_codec": "flac",
"input_sample_rate": 44100,
"input_bit_depth": 16,
"input_channels": 2,
"input_duration_seconds": 210.4,
"input_file_size_bytes": 26541900,
"input_bitrate_kbps": 1411
}
```
This is valuable for:
- Understanding what quality of source material produces the best results
- Debugging encoding/quality issues
- Analytics on user upload patterns
- Detecting re-encoded or low-quality uploads
### Phase 6: User & Abuse-Related Metadata
**Current state**: `request_metadata` already captures IP, User-Agent, client_id, and custom headers at job creation time. This is good for basic abuse investigation. However, some gaps:
**6a. Auth context at job creation**
Store which auth method was used and user tier, so we can correlate job creation patterns with account types during abuse investigation.
16. **`backend/api/routes/file_upload.py`** - Add to `extract_request_metadata()`:
```python
# Add auth context (already available from auth_result)
request_metadata['auth_method'] = auth_result.auth_method # "session", "api_key", "admin_token"
request_metadata['user_type'] = auth_result.user_type.value # "admin", "unlimited", "limited", etc.
request_metadata['credits_at_creation'] = auth_result.remaining_uses # snapshot of credits when job created
```
**6b. Audio search metadata (for audio search flow jobs)**
When a job is created from audio search, we know the search query, number of results, and which result was selected. Store these so we can understand search patterns and detect gaming.
17. **`backend/api/routes/audio_search.py`** - When creating a job from search, store:
```json
"request_metadata": {
...existing fields...,
"search_query": {"artist": "...", "title": "..."},
"search_results_count": 8,
"selected_result_rank": 1,
"selected_source": "RED"
}
```
**Not adding (already handled):**
- IP address: Already in `request_metadata.client_ip`
- User-Agent: Already in `request_metadata.user_agent`
- Email: Already in `job.user_email`
- Tenant: Already in `job.tenant_id`
- IP blocklist: Already exists in `blocklists/config`
- Session IP/UA: Already stored in session documents
- Magic link IP/UA: Already stored in magic link documents
## Scope & Boundaries
- **In scope**: Storing metadata that already exists in memory during processing
- **Out of scope**: Computing new metrics, changing external API calls, frontend changes
- **Out of scope**: Backfilling historical jobs (the one-off script handles AudioShake IDs)
- **Principle**: Each worker writes its own section. No worker reads another worker's metadata.
## Estimated Changes
| Phase | Files | Complexity | Notes |
|-------|-------|-----------|-------|
| 1 | 5 | Low | AudioShake IDs - the critical fix |
| 2 | 5 | Low | Timing data - already computed, just needs storing |
| 3 | 2 | Low | Source/cache metadata |
| 4 | 2 | Low | Review/distribution metadata |
| 5 | 1-2 | Low | ffprobe on input audio, store properties |
| 6 | 2 | Low | Auth context + search metadata at job creation |
| Tests | 4-5 | Medium | Unit + integration tests |
Total: ~18 files, mostly small additions (5-15 lines per file).
Loaded 100 of 201 files, more files were not shown because too many files have changed in this diff. Show more