Compare commits

..
Author SHA1 Message Date
Andrew BeveridgeandClaude Opus 4.8 0ca8dabf44 fix(ci): bump GHA runner 2.334.0 → 2.336.0 (deprecated, wedging all self-hosted CI)
GitHub deprecated actions/runner v2.334.0. Ephemeral runners run with
disableUpdate (JIT config), so they can't self-update: each VM boots,
connects, is rejected with "Runner version v2.334.0 is deprecated and cannot
receive messages", the listener exits, and the trap shutdown terminates the
VM — leaving every self-hosted CI job (backend unit + emulator) queued
forever. Confirmed via live serial console of a dispatched runner VM.

Bumps the pin to the current latest (v2.336.0) in the image-bake provision
script and both baked startup scripts. Requires rebuilding the gha-runner-*
images (Build GHA Runner Images workflow) so the ephemeral dispatcher picks
up the new binary.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-12 12:01:02 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 b389927351 fix: surface made-for-you orders on dashboard + deep-link admin email (#900)
## Problem

A paid **"Made for you"** Stripe order *does* auto-create a job — the
`checkout.session.completed` webhook runs `_handle_made_for_you_order`,
which builds the job with the customer email, artist, and title,
searches audio, and parks it at `awaiting_audio_selection` for an admin
to pick the source. Verified in prod: order for *Kenny Chesney – Burn my
Boat* correctly created job `b092648c` within seconds and emailed
`madeforyou@nomadkaraoke.com`.

But the job was **invisible in practice**, so the operator re-created it
by hand (duplicate):

1. **Dashboard hid it.** `/app` filtered out *all*
`awaiting_audio_selection` jobs — a filter meant to hide self-service
jobs mid-wizard. Made-for-you jobs are created server-side by the
webhook with no active wizard session, so they got silently dropped.
2. **Email link went to the page that hides it.** The admin
notification's "Open Job" button linked to bare `/app/`.

## Changes

- **`firestore_service.py`** — add `made_for_you` + `customer_email` to
`SUMMARY_FIELD_PATHS` so the dashboard summary payload carries them.
- **`job-status.ts`** — new `shouldShowJobOnDashboard()` helper: hide
self-service `awaiting_audio_selection` jobs, but keep `made_for_you`
ones visible (their `JobCard` already has an "Open Audio Selection"
button).
- **`app/[locale]/app/page.tsx`** — use the helper; honor a `?status=`
URL param so email links can deep-link to the awaiting-audio-selection
queue.
- **`email_service.py`** — made-for-you admin "Open Job" link now points
to `/app/?admin_token=…&status=awaiting_audio_selection` (HTML + text).
- **Docs** — LESSONS-LEARNED entry: server-created jobs must fit
dashboard UI assumptions.

## Testing

- Backend: `test_routes_jobs.py` summary-projection assertion for
`made_for_you`; `test_email_service.py` asserts the deep-link carries
both `admin_token` and `status=awaiting_audio_selection` (HTML + text).
Affected files: **194 passed, 5 skipped**.
- Frontend: `job-status.test.ts` unit tests for
`shouldShowJobOnDashboard` (**79 passed**). ESLint clean on changed
files.
- CodeRabbit local review: **No findings** across all 9 files.

## Notes

- No new user-facing strings (email is backend English-only), so no i18n
changes needed.
- Version bumped `0.192.4 → 0.192.5`.

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-08 04:47:34 +02:00
Andrew Beveridge ☄️andClaude Opus 4.8 46cc4012ac fix: harden admin reset against render/video worker supersession race (#899)
## Summary
- Fixes the admin-reset / render race that flipped job `7f457087` to
**failed** with *"Invalid state transition … in_review ->
instrumental_selected"*. Hitting an admin **Reset** button (e.g.
"Review") on a `rendering_video` job left the in-flight render running;
when it finished it attempted its normal `rendering_video ->
instrumental_selected` transition — now illegal — and the worker's
generic handler clobbered the operator's reset with a spurious failure.
- Long-running render/video workers are now **fenced against
supersession**, so any reset / cancel / re-trigger causes an in-flight
worker to discard its stale result quietly instead of failing the job or
overwriting fresher outputs. Resetting a rendering job is safe at any
timing.

## Changes
- **`backend/workers/supersede.py`** (new): shared fencing helper with
two independent nets — a **status fence** (job no longer in the status
the worker owns) and a **generation fence**
(`state_data.worker_generation`).
- **`JobManager.bump_worker_generation()`**: atomic Firestore
`Increment(1)` on the fence (best-effort; never blocks dispatch).
- Fence bumped at every supersede point: the
`trigger_render_video_worker` / `trigger_video_worker` choke points, and
atomically within `admin.py reset_job`.
- **Render worker**: captures generation at start; supersede-checks
before writing outputs (GCE + local paths); guards the progress callback
so a stale render can't drag a reset job's progress bar; and — key fix —
its `except InvalidStateTransitionError` now **confirms** supersession
via `check_superseded()` before bailing gracefully, otherwise falls
through to the real failure path so genuine workflow defects still
surface.
- **Video worker**: same graceful/confirmed
`InvalidStateTransitionError` handling in both the orchestrated and
legacy paths.
- Docs: `TROUBLESHOOTING.md` (new reset/render-race runbook) +
`LESSONS-LEARNED.md` (fencing principles).

## Known follow-up (documented in code)
Fully closing the residual GCS/metadata write window (a stale render can
leave transient bytes under the shared `jobs/{job_id}/` prefix before
the read-time check) requires **generation-scoped output prefixes + a
conditional promote on the encoder side** — a larger cross-service
change, deliberately deferred. The failed-job incident and any bad
downstream trigger are fully fixed here; the worst residual is a
transient stale object that a newer generation overwrites.

## Testing
- [x] `backend/tests/test_worker_supersede_race.py` (new): helper unit
tests, atomic-increment, progress-callback guard, and render-worker
scenarios — status-reset, generation-bump,
confirmed-supersession-is-graceful (the `7f457087` repro),
**not-superseded-still-fails**, and normal-completion.
- [x] `test_admin_job_reset.py`: reset bumps the generation fence.
- [x] Full backend suite green (3767 passed).

## Review
- [x] Local CodeRabbit review completed (3 cycles; final pass: no new
findings)
- [x] Feedback addressed (over-broad `InvalidStateTransitionError`
suppression fixed; TOCTOU residuals documented with a deferred
follow-up)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-07 21:25:04 +02:00
Andrew Beveridge ☄️andClaude Opus 4.8 c716c79022 feat(resilience): auto-recover stuck renders + transient downloads; retry 503 blips (#898)
## Why

Investigating two stuck real-user jobs (a render frozen at "[7/10]
Rendering video" for ~1.3 days, and a torrent download that gave up
after ~1h) surfaced a common gap: **a job can dead-end when a downstream
resource (encoding VM / torrent seeders / tracker) is briefly
unavailable, with no automatic recovery.** All three fixes apply the
same proven **park + periodic-retry-up-to-24h** pattern, folded into the
**existing** `recover-stuck-jobs` cron (every 5 min) — **no new
infra/Cloud Scheduler**.

## What

**1. Render staleness watchdog** (`job_health_service` +
`recover-stuck-jobs`)
A render worker killed mid-render (instance recycle / SIGKILL / lost VM)
left the job frozen at `RENDERING_VIDEO` forever — invisible to the
capacity-retry cron (which only queries `RENDER_PENDING_CAPACITY`), no
watchdog, and (per the UI) no Retry button. Now: `rendering_video` with
no progress for >45 min → re-park into `RENDER_PENDING_CAPACITY` so the
existing retry cron resets it to `REVIEW_COMPLETE` and re-renders (same
24h ceiling).

**2. Transient torrent-download retry** (new `DOWNLOAD_PENDING_RETRY`
status)
Rare tracks with few/intermittent seeders and brief tracker outages hit
gen's ~1h give-up and failed permanently ("Audio download timed out …
Use retry"). Now a stuck **RED/OPS** download parks into
`DOWNLOAD_PENDING_RETRY` and is auto-retried for up to 24h with a
friendly "we'll keep trying automatically" message; permanent failure
only after 24h. Non-torrent sources (YouTube/Spotify/URL) still fail
fast (deterministic). Per-tick dispatch cap prevents fan-out during an
audio-worker outage.

**3. VM-start 503 whole-set retry**
(`encoding_worker_manager.ensure_any_running`)
A transient `503 SERVICE_UNAVAILABLE` (distinct from a capacity
`STOCKOUT`) that hits all zones at once is retried across the whole
candidate set with backoff before giving up — but **only when every
candidate failure was transient** (a capacity or `PERMISSION_DENIED`
failure raises immediately; the 24h park handles a real shortage).
Per-candidate zone failover is unchanged.

**Frontend:** friendly i18n labels for `download_pending_retry` and
`render_pending_capacity` (the latter previously fell through to a raw
status), translated to all 33 locales.

## Verification
- The two triggering jobs were unstuck live: **`87eb17c3` completed +
published**; `7f457087` is a genuinely seedless release right now (RED
healthy for others) — exactly the case Feature 2 now auto-retries for
24h.
- Tests: render/download watchdog + retry paths, per-tick cap, 503
whole-set retry incl. the mixed non-transient case. Full backend suite
green locally.

Local CodeRabbit review completed; both findings (all-transient retry
guard; per-tick dispatch counting) were addressed with tests.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **New Features**
- Added automatic recovery and retries for stalled audio downloads and
video rendering jobs.
  - Jobs can wait for processing capacity and resume automatically.
  - Downloads now retry for up to 24 hours before permanent failure.

- **Bug Fixes**
- Improved handling of stuck downloads, renders, and transient capacity
errors.

- **Localization**
- Added retry and capacity-waiting status messages in supported
languages.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-07 11:20:05 +02:00
Andrew Beveridge ☄️andClaude Opus 4.8 d6361ca7ad fix(error-monitor): stop transient-capacity + bot crashes from paging (#897)
## Why

Two alert-channel noise sources surfaced during the flacfetch download
incident. Neither was a real production problem, but both page — so we
fix the **monitor's signal quality** rather than mute them.

### 1. Transient encoding-worker capacity retries
`[job:…] Encoding worker start failed, aborting retries: VM … 503 —
SERVICE UNAVAILABLE` is a transient GCP zonal-capacity event.
`render_video_worker` catches `EncodingWorkerStartError` and **parks the
job for auto-retry** (`_park_job_for_capacity_retry`) — the job is *not*
lost, and a genuine give-up fails the job via a separate ERROR. Added a
`known_issues` suppression **scoped to the transient signal only** (503
/ `SERVICE UNAVAILABLE` or a capacity code:
`ZONE_RESOURCE_POOL_EXHAUSTED` / `STOCKOUT` / `QUOTA_EXCEEDED`). A
non-transient `EncodingWorkerStartError` (other/unknown code) shares the
prefix but **still pages**.

### 2. One incident → N alerts (normalizer gap)
The same failure produced *two* alerts (same job, two preview-render
IDs). `preview_<jobid>_<renderid>` is underscore-joined, and the generic
hex normalizer is `\b`-anchored (`_` is a word char), so every preview
render hashed to a distinct "new pattern." Added a normalizer rule that
collapses `preview_<hex>_<hex>` → `preview_<ID>`.

### 3. Bot/crawler browser crashes
`NotFoundError: removeChild` on `/en/r/` came from **bingbot** running
headless Chrome — a React DOM-reconciliation error no real user hits (0
real-user occurrences in 7d). Reports from bot/crawler user-agents are
now dropped at the `/client-errors` ingestion edge (still `202` so the
client won't retry), instead of being persisted/alerted.

## Tests
- `known_issues`: transient 503 **and** capacity-code variants
suppressed; non-transient start failure + genuine job failure still
alert.
- `normalizer`: preview-ID collapse; two renders of one job → same hash.
- `is_bot_user_agent`: crawler matrix true, real-browser/empty/None
false.
- API: a bingbot report is accepted (`202`, `is_new=false`) but **not
upserted**.

`133 passed`. Local CodeRabbit review completed and its two findings
(scope the capacity regex; sanitize the logged bot URL) were addressed;
a confirming re-review was blocked by the free-tier rate limit, so
leaving the bot review on.

## Notes
The actual outage in this incident (daily E2E download failure) was a
**flacfetch** bug, fixed + deployed separately (flacfetch #36). This PR
only removes the alert noise those investigations surfaced.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **Bug Fixes**
- Bot and crawler error reports are acknowledged without being persisted
or triggering alerts.
- Transient encoding-worker capacity failures are filtered as retryable
infrastructure noise.
- Preview render job identifiers are normalized consistently for
improved error grouping.

- **Maintenance**
  - Updated the application version to 0.192.2.
- Expanded validation for bot detection, error filtering, and preview
error normalization.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-07 10:20:47 +02:00
Andrew Beveridge ☄️andClaude Opus 4.8 c94abbf7f4 docs: Cloudflare edge security (WAF + origin lock) — persistent-doc coverage (#889)
Documents the 2026-07-20 edge cutover (shipped in #886 + #888) in the
persistent docs.

## Changes
- **ARCHITECTURE.md**: Cloudflare edge added to the System Overview
request path + new **§ Edge Security (Cloudflare)** (WAF, rate limit,
origin lock, SSL "full" rationale).
- **LESSONS-LEARNED.md**: the SSL "dragon" resolution (managed cert
can't provision behind CF, but "full" mode makes it work + renewal-safe
→ never use "full (strict)") + Free-plan WAF/rate-limit constraints +
origin-lock-without-breaking-internal-callers.
- **README.md**: Recent Changes entry + Current State row.
- **API.md**: origin-lock note (direct-to-`*.run.app` → 403 without
`X-Edge-Auth`).

Docs-only; no version bump.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-21 02:37:11 +00:00
Andrew Beveridge ☄️andClaude Opus 4.8 d9ecc0d0d0 Edge cutover complete: api.nomadkaraoke.com behind Cloudflare (WAF + origin lock enforced) (#888)
Completes the edge-security rollout started in #886. **The prod cutover
is done and validated** — `api.nomadkaraoke.com` now serves all traffic
through Cloudflare with WAF + rate-limiting, and the origin lock is
enforced.

## Cutover (applied via targeted `pulumi up`, validated live)
1. Imported the existing prod `api` DNS record (adopt, not duplicate)
2. Provisioned prod WAF/rate-limit/header rules while `api` stayed
DNS-only
3. Flipped `api` to proxied (the one reversible change)
4. `EDGE_AUTH_MODE` off → warn → **enforce** (validated safe via prod
E2E)

## Validation results (2026-07-20)
- `api.nomadkaraoke.com` → **200 + cf-ray**, exploit paths → **403**
(WAF), `/api/health` → 200, **CORS ok**, frontend loads, **0 backend
errors**
- **Daily prod E2E PASSED** (real Stripe payment + karaoke generation
through the edge)
- **0 edge-auth warnings** during the full E2E → enforce enabled
- Origin lock verified: direct-to-`*.run.app` non-exempt → **403**;
health/root exempt → 200

## Key finding: SSL "full" mode resolves the cert dragon
The Cloud Run managed cert can't provision behind Cloudflare (ACME
challenge not visible), **but the zone SSL mode is "full" (not strict)**
so Cloudflare doesn't validate the origin cert — the edge works and is
**renewal-safe** with no run.app Origin Rule / LB / cert wait. Rule:
keep zone SSL on "full", never "full (strict)".

## Free-plan constraints handled (in #886)
WAF `contains` not regex; rate-limit `period=10`+`cf.colo.id`; managed
OWASP off.

## Changes
- `config.py`: SSL-"full" note (replaces the reverted run.app-origin
config)
- `Pulumi.prod.yaml`: cutover config (`rolloutStage=prod`,
`proxyProdApi=true`, `proxyStaging=true`)
- `ci.yml`: `EDGE_AUTH_MODE=enforce` (persist the origin lock across
deploys)
- Plan §4 + runbook Phase B: the resolution + actual results

## Rollback
`pulumi config set edge:proxyProdApi false && pulumi up --target
…api-dns` (DNS-only within a TTL); `EDGE_AUTH_MODE=off` disables the
lock.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-21 00:25:25 +00:00
Andrew Beveridge ☄️andClaude Opus 4.8 fb2bd6b108 Cloudflare edge security (WAF + rate limit + origin lock) for karaoke-backend (#886)
## Summary
Puts `api.nomadkaraoke.com` behind the Cloudflare edge that already
fronts the rest of the domain, after a vuln-scanner hammered the
directly-exposed Cloud Run origin on 2026-07-20 (`/.env`,
`/.ssh/id_rsa`, `wp-config.php`… — all 404'd, but the burst of 404s
tripped the "High Error Rate" alert). The API was the one
internet-facing surface with **no WAF, no rate limiting** — DNS-only
CNAME straight to `ghs.googlehosted.com`, Cloud Run ingress `all`.

**Zero-downtime by construction:** everything is gated behind
`edge:enabled` (default off) and staged via two independent switches
(`edge:rolloutStage` for rule scope, `edge:proxyProdApi` for the DNS
flip). The whole Cloud-Run×Cloudflare interaction is validated on a
throwaway staging host first; the only prod-affecting action is a
single, instantly-reversible DNS proxy flip. Full sequence in
`docs/archive/2026-07-20-edge-security-cutover-runbook.md`.

## Changes
- **`infrastructure/modules/edge_security.py`** (new) —
`pulumi_cloudflare` WAF (exploit-path block), per-IP rate limiting
(excludes `/api/internal/*`), origin-lock header transform, zone
security; staging + prod DNS records. Managed OWASP ruleset gated off
(zone is Free plan).
- **`backend/middleware/edge_auth.py`** (new) — off/warn/enforce origin
lock via a secret header Cloudflare injects; **fails closed (503) in
enforce** when the secret is missing; health/root exempt. +13 unit
tests.
- **`monitoring.py`** — retune the high-error-rate alert to **5xx-only**
(+ fix the rate-vs-ratio naming) so client/bot 404 bursts no longer
page.
- Wiring: `secrets.py` (edge-origin-secret container), `config.py`,
`__main__.py`, pinned `pulumi-cloudflare==6.18.0`, `ci.yml`
(`EDGE_AUTH_MODE=off` + secret ref), `Pulumi.prod.yaml` (encrypted
`edge:originSecret`).
- Docs: hardening plan + cutover runbook in `docs/archive/`.

## Already applied to prod (targeted `pulumi up`)
- ✅ `edge-origin-secret` Secret Manager container + v1 value
- ✅ 5xx error-rate alert retune (fixes the original paging issue
immediately)
- Everything else stays dormant: `edge:enabled=false`, backend
`EDGE_AUTH_MODE=off`.

## Testing
- [x] `make test` — full backend + frontend suite green (1085 frontend
tests; backend incl. 13 new edge-auth tests)
- [x] Cloudflare token verified against live API (DNS create+delete,
rulesets, zone settings)
- [x] `pulumi preview` clean (targeted apply of only the 2 additive
resources)
- [ ] Staging validation + prod cutover — follow the runbook (separate,
gated)

## Review
- [x] CodeRabbit CLI review completed locally; findings addressed
(fail-closed enforce, decoupled cutover, fixed origin-lock test,
threshold wording). One pre-existing PR_TITLE shell-interp finding in
the deploy step left out of scope.

## Notes for reviewer
- Nothing here touches prod behavior until someone sets `edge:enabled
true` and walks the runbook. The prod `api` DNS record must be `pulumi
import`ed (already exists) — documented in runbook step 4a.
- Pre-existing cross-worktree Cloud Function source drift is visible in
a full `pulumi preview`; not introduced here (applied via `--target` to
avoid it).

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-20 19:12:28 -04:00
Andrew Beveridge ☄️andClaude Fable 5 83557af210 fix(runner-manager): reap TERMINATED ephemeral VMs immediately (frees GPU quota) (#885)
Stopped VMs with GPUs attached still count against `NVIDIA_T4_GPUS`
quota until deleted. Self-shutdown ephemeral runners sat as TERMINATED
corpses for up to ~45 min, so back-to-back CI waves exhausted quota and
the fire-and-forget dispatcher silently stranded queued jobs — the async
`QUOTA_EXCEEDED` operation failure is invisible (observed repeatedly
today, at quota 4 and after the bump to 8; e.g. operations from run
29770005437's dispatch at 18:58Z).

A TERMINATED single-use VM can never work again → delete on the next
cleanup pass regardless of age/registration, with a serial-console dump
first when it never registered.

43/43 tests pass (2 new). Will `pulumi up` before merge.

@coderabbitai ignore

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

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 15:13:44 -04:00
Andrew Beveridge ☄️andClaude Fable 5 7698bfd1ba fix(runner-images): bake VC++ runtime into gpu-windows image (#884)
torch (`c10.dll`) and onnxruntime fail with `[WinError 126]` on the
fresh Windows Server image — they need the MSVC 2015-2022 runtime. The
`windows-directml` job installs it per-run as of
nomadkaraoke/python-audio-separator#296; this bakes it in (with the
standard 0/1638/3010 exit-code tolerance) so the image is correct by
default. Picked up at the next bake.

@coderabbitai ignore

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

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 14:59:56 -04:00
Andrew Beveridge ☄️andClaude Fable 5 2d2e41e036 fix(runner-images): enable Windows long paths in gpu-windows image (#883)
First `windows-directml` CI run hit `[WinError 206]` (260-char MAX_PATH)
during `pip install onnx`. The job now sets `LongPathsEnabled` per-run;
this bakes it into the image so any future consumer is correct by
default. Picked up at the next image bake — no urgent rebake needed.

@coderabbitai ignore

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

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 14:53:04 -04:00
Andrew Beveridge ☄️andClaude Fable 5 ca5b294cfd fix(runner-images): authenticate NVIDIA bucket listing in Windows bake (#882)
First `gpu-windows` bake (run 29767011825) failed fast: anonymous
listing of `gs://nvidia-drivers-us-public` returns 401. Objects download
anonymously but listing needs an authenticated Google identity — use the
build VM's service-account token from the metadata server for the two
listing calls. Verified locally against the live bucket (latest dir
`GRID/vGPU20.1/`, installer matches the `*server2022*.exe` selector).

Follow-up to #881; re-bake after merge.

@coderabbitai ignore

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

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 14:24:33 -04:00
Andrew Beveridge ☄️andClaude Fable 5 ac4d7f7b3d feat(runner-manager): Windows GPU ephemeral runner family (gpu-windows) (#881)
## Summary

Adds a Windows Server + T4 family to the ephemeral GHA runner fleet,
following the existing pattern exactly (JIT-config single-use VMs from
pre-baked image families). Built for python-audio-separator's upcoming
`windows-directml` integration tests — part 2 of the RoFormer-on-Windows
plan (nomadkaraoke/python-audio-separator#292; see plan in
nomadkaraoke/python-audio-separator#294).

### Dispatcher (`ephemeral.py`)
- `FamilySpec.os_label` (default `linux`) replaces the hardcoded `linux`
advertised label
- New `gpu-windows` family: n1-standard-4 + T4, `gha-runner-gpu-windows`
image family, 100GB disk
- `resolve_family` precedence: windows → gpu → build → general
- Windows VMs get the JIT startup script via the
`windows-startup-script-ps1` metadata key (`run.cmd --jitconfig` +
guaranteed shutdown in `finally`); Linux families unchanged
- +8 unit tests (41 pass): family routing, advertised labels, per-family
startup metadata key, TERMINATE scheduling

### Image bake
- `runner-image-provision.ps1`: NVIDIA **GRID** driver (WDDM mode — the
datacenter driver runs T4 in TCC mode with no DirectX, which breaks
DirectML), with TCC→WDDM switch + bounded reboot retries; Python 3.12
(torch-directml has no 3.13 wheels); Git, FFmpeg, system-wide Poetry,
actions-runner win-x64; lean DirectML model set at
`C:\audio-separator-models`. Idempotent via phase markers (startup
scripts re-run every boot); emits the same READY/FAILED serial-console
markers as the Linux provisioner so the existing wait step works
unchanged.
- `build-runner-images.yml`: `gpu-windows` variant
(windows-cloud/`windows-2022` base, per-variant image + startup-metadata
flags), included in monthly "all" builds
- `docs/EPHEMERAL-GHA-RUNNERS.md`: fourth image family + label-routing
rules

## Deploy sequence (operator)

1. **Before merge: `pulumi up` locally** (runner-manager function
redeploys with the new family — my ADC is read-only so I could not run
it)
2. Merge, then bake the first image: `gh workflow run
build-runner-images.yml -f variants=gpu-windows`
3. First consumer job (`windows-directml`, `runs-on: [self-hosted,
windows, gpu]`) lands in python-audio-separator next — it doubles as the
verification job

The companion label fix (`runs-on: [self-hosted, linux, gpu]` on
existing jobs, so Windows runners can't steal Linux jobs) is already in
nomadkaraoke/python-audio-separator#294.

## Testing

- `test_ephemeral.py`: 41/41 pass
- Workflow YAML validated; CodeRabbit local review run, findings applied
(windows-2022 family name, bounded WDDM retry, reboot on installer exit
1, atomic downloads)
- Real-world validation happens at first bake + first `windows-directml`
job (next PR)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-20 14:15:38 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 6b8ce07188 fix: split CJK (Japanese) lyric lines by display width to prevent overlap (#880)
## Summary

Japanese (and other CJK) karaoke videos rendered with **overlapping
lyric lines** that ran off both screen edges — reported for job
`4dcca2d6` (レッツゴー!陰陽師).

**Root cause:** `SegmentResizer` split lines using raw **character
count** (`len(text) <= max_line_length`), a proxy for visual width
calibrated for Latin. East-Asian Wide/Fullwidth glyphs render ~2.5× a
Latin character and CJK has no inter-word spaces, so a Japanese line
well under the *character* budget was ~2× too wide for the 4K frame.
With no `WrapStyle` set, libass smart-wraps the too-wide line onto a
second physical row that lands on the next slot's fixed Y position →
overlap.

## Changes

- **Display-width metric** (`display_width`,
`unicodedata.east_asian_width` W/F → `WIDE_RATIO=2.7` units, else 1).
For pure ASCII/Latin `display_width == len`, so **English/European
output is byte-for-byte unchanged** (the Latin natural-break splitter is
untouched).
- Only the **oversize gate** uses display width; wide-script segments
are then split by **word-token packing** (`_pack_words_into_lines`) —
boundary-safe (never cuts inside a multi-char CJK token like `立ち向かう`)
and counts the inter-token space the renderer emits.
- **Preserve wordless oversized segments** instead of dropping them
(guards a latent pre-existing bug).
- `WIDE_RATIO=2.7` calibrated against the real render (libass ~0.70×
effective size; Montserrat/Avenir vs Noto/Hiragino): ~14 CJK
glyphs/line, ~83% of 3840px.

## Testing

- New `test_segment_resizer_cjk.py` (13 tests): JP/ZH/KO splitting,
mixed CJK+Latin, `display_width` units, **exact** English byte-for-byte
output, multi-char CJK token non-fragmentation, wordless-segment
preservation.
- Full backend unit suite: **1701 passed**, 8 skipped.
- **End-to-end verified:** re-rendered job `4dcca2d6` through the
production `generate_outputs` path with the fix — over-budget lines
**21/36 → 0**, and rendered 4K frames confirm no overlap (same
timestamps as the original bug report).

## Review

Reviewed locally with CodeRabbit (3 cycles → no findings). Findings
fixed: CJK-token fragmentation, wordless-segment lyric drop, exact-ASSII
test assertion.

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-18 16:28:16 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 eac3dac910 fix: recognize Turbopack chunk-load errors for post-deploy auto-reload (#879)
## Problem

Prod error-monitor alert:

```
Error: Failed to load chunk /_next/static/chunks/<ID>.js from module <NUM>
    at https://gen.nomadkaraoke.com/_next/static/chunks/turbopack-*.js
```

The gen frontend is a static export (`output: 'export'`) served from
GitHub Pages with hashed chunk filenames. On deploy, old chunk hashes
vanish, so a user with an already-loaded tab hits a **post-deploy
mismatch** when the app lazy-loads a stale chunk. The frontend is
designed to auto-recover from this via `hardReload()` in
`client-error-setup.ts` — but the recovery wasn't firing.

## Root cause

`isChunkLoadError()` in `frontend/lib/version-check.ts` only recognized
webpack/native-ESM phrasings (`ChunkLoadError`, `Loading chunk <id>
failed`, `Failed to fetch dynamically imported module`, `Importing a
module script failed`).

**Next.js 16 defaults to Turbopack**, whose browser runtime throws a
plain `Error` (name `"Error"`, *not* `ChunkLoadError`) with a different
message: `Failed to load chunk <path> from module <n>` (also `… as a
runtime dependency of chunk <id>` / `… from an HMR update`). Confirmed
by inspecting the built runtime
`out/_next/static/chunks/turbopack-*.js`.

None of the regexes matched → the auto-hard-reload never triggered (user
saw a broken page) **and** the error was reported to the monitor → this
alert.

## Fix

- Add `/Failed to load chunk/i` to `isChunkLoadError()`'s regex list,
documenting all three bundler families.
- Add the first tests for `isChunkLoadError` (webpack, Turbopack ×3
variants, native ESM, negatives).
- Bump `0.191.1` → `0.191.2`.

Left the crash-reporter's `isBenignError` untouched: a chunk error that
survives the 60s reload circuit-breaker *should* still be reported
(persistent = a real problem like missing CDN files, not mere
staleness).

## Notes

- Users who already saw the error recover with a manual reload — this
fix makes future post-deploy mismatches self-heal automatically.
- The error store aggregates by pattern and does not persist
`user_email`, so the affected visitor can't be identified (and this hit
was on the logged-out `/zh/` homepage anyway).

## Testing

- `npx jest __tests__/version-check.test.ts
__tests__/CrashReport.test.tsx` → 20/20 pass
- `npx eslint` on changed files → clean

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-17 12:01:24 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 1578984f5b fix: filter benign ResizeObserver-loop noise from client error monitor (#878)
## Summary
The error monitor fired a 🔴 New Error Pattern alert for \`ResizeObserver
loop completed with undelivered notifications\` (on \`singa.\`, build
ad3c0bff). This is a **benign, spec-defined browser signal** — not a
crash. Chrome hides it from its own console; every page using
ResizeObserver (TimelineCanvas, FlyerPreview, VNC toolbar) emits it
occasionally. It reached the monitor because the global
\`window.onerror\` handler reports everything with no benign-noise
filter.

## Changes
- Extend the existing \`isBenignError\` filter in
\`frontend/lib/crash-reporter.ts\` (which already drops media
\`AbortError\`) to also skip both ResizeObserver-loop phrasings
(\`completed with undelivered notifications\` + legacy \`loop limit
exceeded\`).
- Add \`crash-reporter\` unit tests (benign detection + that a genuine
error still POSTs).

## Testing
- [x] \`npx jest lib/__tests__/crash-reporter.test.ts\` — 5/5 pass
- [x] Verified real errors (e.g. the \`currentTime\` TypeError) are NOT
suppressed

## Review
- [x] Local CodeRabbit review (1 minor finding — test fetch-mock leak —
fixed)
- [x] Version bumped 0.191.0 → 0.191.1

## Context
Unrelated to the karaoke \`currentTime\` fix shipped in #877. Also
confirmed the same-day E2E "Happy Path" alert was a landing-page
\`page.goto\` timeout flake (site healthy), re-running to confirm.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-16 17:04:04 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 ad3c0bffc0 fix: harden 4 prod error paths (seek non-finite, auto-correct 429, download race + timeout) (#877)
## Summary
Investigated and fixed four production error patterns flagged by the
error monitor, each with tests.

## Changes
**Frontend — `TypeError: currentTime non-finite`** (`/en/app/jobs`
review UI)
- Guard lyrics-review/audio-editor seek sinks
(`AudioPlayer.seekAndPlay`/`handleSeek`, `AudioEditor.seekTo`) and the
`handlePlaySegment` dispatcher with `Number.isFinite`; harden
`TimelineEditor.handleTimelineClick` against a zero-width container.
Restores parity with instrumental-review, which already had these
guards.

**Backend — auto-correct Vertex `429 RESOURCE_EXHAUSTED` surfaced as
generic 502**
- Retry model calls with exponential backoff on transient
(rate-limit/overload) errors via `_is_transient_model_error`; surface a
distinct **retryable 429** instead of 502. Retry env knobs parsed
defensively (clamp + warn, never crash at import).

**Backend — `audio-download-job` `InvalidStateTransitionError:
downloading -> downloading`**
- Root cause: a manual `/retry` raced the Cloud Run auto-retry; the
losing run's post-download transition raised and the generic `except`
`fail_job`'d a job the winner had already advanced. Fix: idempotent
transition — re-read status first, treat an already-advanced job as
success, and use `raise_on_invalid=False` so a race never fails a live
job.

**Backend/infra — `audio-download-job` 600s task-timeout SIGKILL**
- Internal `wait_for_download` timeout equalled the Cloud Run task
timeout, so slow torrents were SIGKILLed before failing gracefully
(leaving the orphaned retry that fed the race above). New
`DOWNLOAD_WAIT_TIMEOUT_SECONDS=1080` kept strictly below the task
timeout, raised `600s → 1200s`. **Infra already applied to prod via
`pulumi up` (targeted); stack is clean.**

## Testing
- [x] Backend: 122 tests across touched suites pass (auto_correct incl.
10 retry/env, audio_download_worker incl. 3 race/timeout, review API,
proactive)
- [x] Frontend: full jest suite 1073/1073 pass (incl. new AudioPlayer
non-finite guard test); `tsc` clean for changed files
- [x] Infra: `pulumi preview` clean (273 unchanged) after applying
timeout + reconciling pre-existing divebar drift

## Review
- [x] Local CodeRabbit review completed (1 major finding — retry env
validation — fixed + tested)
- [x] Version bumped 0.190.5 → 0.191.0

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-15 17:40:04 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 b8e67e6ba6 feat: emit + push original-vocals guide on NOMAD render (write-path) (#875)
## Summary

Makes the kjbox **"Original Vocals"** sing-along guide
**self-maintaining**. When karaoke-gen finalises a new public NOMAD
master, it now automatically emits an aligned original-vocals guide and
pushes it to GCS — no re-run of the kjbox retro-fit pipeline.

**Key insight:** at render time karaoke-gen already has the isolated
`mixed_vocals` stem (a byproduct of the karaoke instrumental) and knows
the exact intro offset (the job's style `intro_video_duration`). So the
guide is simply `silence[intro] + vocals`, capped to the master's
duration — **no correlation, no review, no alignment measurement**.

## Changes

- `backend/services/original_vocals_guide.py` (new): pure ffmpeg builder
(`adelay` + `-f flac`, atomic `.part` rename) + `probe_duration`.
Best-effort, never raises.
- `nomad_master_mirror`: `push_vocals_guide` +
`delete_vocals_guides_by_brand` (siblings of the 720p methods);
brand-recycle cleanup now clears guides too.
- `video_worker_orchestrator`: `_emit_original_vocals_guide` pulls the
`mixed_vocals` stem from `jobs/{id}/stems/vocals_clean.flac`, resolves
the **actual** intro duration (long-intro styles honoured; `0`
preserved), caps to the master, registers it in `output_files`.
- `gdrive_service`: pushes the guide beside the 720p master (same
Nomad-brand gating + best-effort/distribution-warning contract).
- `config`: `nomad_vocals_guide_gcs_prefix` (`files/Nomad
Karaoke/vocals-padded`).

## Behaviour

- **Public NOMAD only** (`is_nomad_public_brand`, skips `NOMADNP`).
Shares the `nomad_master_fast_sync_enabled` gate.
- **Inert** until the kjbox device pulls the new prefix into
`NOMAD-vocals-padded/` (separate kjbox PR) — guides just accumulate in
GCS. Existing 1,459 device guides untouched.
- Every step best-effort: a guide failure is a distribution warning,
never fatal.

## Testing

- Builder unit tests (synthetic tone+silence): offset, duration cap,
valid flac, best-effort `None` paths.
- Mirror push/delete + gating; gdrive + orchestrator wiring; intro=0 /
long-intro resolution.
- Full backend suite: **3711 passed** (excl. emulator). CodeRabbit: 1
finding (intro-0 truthiness) fixed.

Design spec:
`docs/superpowers/specs/2026-07-09-original-vocals-writepath-design.md`

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 01:26:11 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 6f86b3d901 test(e2e): rewrite tenant daily E2E as a faithful frontend journey (#873)
## Why

The daily tenant E2E (`scripts/e2e/tenant_e2e.py`) drove the whole flow
via **direct backend API calls**, bypassing the frontend. Two problems:
1. **Not representative** — it never exercised the tenant portal UI a
real operator uses.
2. **Intermittent stuck-render orphans** (Run #31 vocalstar, #32 singa)
— because it never loaded the lyrics-review page, it never fired
`encoding-worker/warmup`, so the encoder was cold when the render
started and the job orphaned in `rendering_video` (no recovery).
Root-caused this session; the fix is to make the test faithful, which
fires the warmup a real user fires.

## What

Replaces `tenant_e2e.py` with
**`frontend/e2e/production/tenant-happy-path.spec.ts`** — a Playwright
journey mirroring `happy-path-real-user.spec.ts`, run per-tenant via the
existing `e2e-tenant-daily.yml` matrix (vocalstar, singa; `max-parallel:
1`):

login (real magic-link UI) → submit track (tenant form + real audio
upload) → wait for transcription → **open review UI (fires warmup)** →
approve → wait for render → assert tenant distribution (Dropbox present,
no YouTube, downloads, `is_private`) → cleanup.

- **Tenant auth**: added `inbox.testmail.app` to both tenants'
`allowed_email_domains` (setup scripts + live GCS config via
`scripts/e2e/update_tenant_allowlist.py`) so the test signs in through
the real magic-link UI.
- **Test audio**: short 60s clips fetched from private GCS in CI
(`scripts/e2e/fetch_test_audio.sh`) — fast, reliable uploads and quick
renders.
- Workflow reworked to Node/Playwright; `tenant_e2e.py` deleted; version
`0.190.3 → 0.190.4`.

## Findings surfaced (validating the exercise)

- **Browser upload was CORS-blocked in Playwright** by the shared
config's global `x-playwright-test` header (it made the GCS signed-URL
PUT preflight request a header the bucket's CORS doesn't allow).
Verified the same PUT succeeds in a real browser — a **test-harness
artifact, not a product bug**. Worked around by stripping the header for
`storage.googleapis.com` requests. (Note: any prod E2E doing a browser
signed-URL upload is affected by this global header.)

## Verification

Both tenants run **green end-to-end against prod** locally (login →
submit → review → render → distribution; render completed without
orphaning). Reworked workflow dispatched on this branch to confirm CI
wiring (Node setup + private-audio fetch + secrets).

Test-only + CI + tenant-config change. No product code.

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

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-05 02:33:20 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 f93d5f6923 fix(e2e): click 'Complete Sign-In' gate in magic-link auth tests (#872)
## Problem

The daily E2E (`e2e-daily.yml`) **Stage 1 (Credit Purchase) failed**
(Run #87), with **Stage 2 (Happy Path) skipped** only because its `if`
requires Stage 1 success.

Root cause: yesterday's `fix(auth): gate magic-link verify behind
explicit click` (#870). The `/auth/verify` page no longer auto-consumes
the token on mount — it now shows a **"Complete Sign-In"** confirm gate,
and the token is only spent when that button is clicked (protects the
link from email scanners).

The three magic-link E2E specs navigate to the link then *immediately*
wait for the post-sign-in text ("Successfully signed in!" / "Welcome to
Nomad Karaoke!"). That text now only appears **after** clicking the gate
→ 30s timeout → failure. All three were affected (Stage 2 has the same
bug; it just never ran).

## Fix

New shared helper `clickCompleteSignInGate(page)` in
`frontend/e2e/helpers/auth.ts`:
- waits for the gate button (`getByRole('button', { name: /complete
sign-?in/i })`)
- races it against the `/sign-in failed/i` UI so a genuinely dead link
throws a diagnostic error instead of a bare timeout
- clicks the gate

Called after `page.goto(magicLink)` in:
- `credit-purchase-real.spec.ts` (Stage 1)
- `happy-path-real-user.spec.ts` (Stage 2)
- `full-user-journey.spec.ts`

## Verification

- `playwright test --list` compiles all three specs; ESLint clean;
CodeRabbit 0 findings.
- **Live against prod v0.190.2:** minted a real magic-link token via
`POST /api/users/auth/magic-link`, drove it in an isolated browser →
gate **"Complete Sign-In"** renders → click → **"Welcome to Nomad
Karaoke!"** interstitial → **"Start Creating Karaoke"** → `/app`. Every
selector in the fix and downstream test logic confirmed.

Test-only change (+ version bump 0.190.2 → 0.190.3).

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

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-04 14:30:45 -04:00
Andrew Beveridge ☄️ d84a827be3 feat(auth): show already-used/expired message upfront on verify page (#871)
@coderabbitai ignore

Follow-up to #870. That PR added the "Complete Sign-In" gate so email
link-scanners can't burn a magic link before the user clicks. This PR
improves the case where the link is **genuinely already used or
expired**: instead of showing a "Complete Sign-In" button that only
fails when clicked, the verify page now shows the "link expired or
already used" message (with one-click resend) **upfront**.

### How it stays scanner-safe

The decision uses a **read-only** status probe that does **not** consume
the token:

- New `GET /api/users/auth/link-status` +
`UserService.get_magic_link_status()` return `valid` / `used` /
`expired` / `invalid` without mutating the doc (verified by a unit test
asserting `update`/`set` are never called).
- The verify page calls it on mount:
- `valid` → show the **Complete Sign-In** gate (token still spent only
on the explicit click).
- `used`/`expired`/`invalid` → show the failure UI + resend immediately.
- probe **errors** → fall back to the gate, so a transient
status-endpoint failure never blocks a user holding a valid link.

Because the probe is non-mutating, a scanner rendering the page still
can't burn a valid token — consumption remains gated behind the click,
exactly as in #870.

### Notes

- Reuses existing i18n strings (`pleaseWait`, `verifyingWait`,
`linkExpiredOrUsed`) — no new translation keys.
- The status endpoint is an unauthenticated read, same trust model as
`/auth/verify` (the 256-bit token is the only credential); it reveals
only valid/used/expired for a token the caller already holds.

### Testing

- **Backend (9):** service returns correct status for
valid/used/expired/missing/empty **and does not consume** a valid token;
endpoint returns the status and short-circuits empty tokens without
hitting Firestore.
- **Frontend (8):** valid → gate, no verify on mount; dead link →
failure UI upfront with no gate and no verify call; probe-error → gate
fallback; resend recovery intact.
- Full frontend suite green (1072); backend auth suite green (75); `tsc`
+ `eslint` clean; CodeRabbit local: 0 findings.
- Version `0.190.1 → 0.190.2`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-07-03 19:40:52 +00:00
Andrew Beveridge ☄️ 2b258cd8f0 fix(auth): gate magic-link verify behind explicit click to survive email scanners (#870)
@coderabbitai ignore

## Problem

Magic-link sign-in could fail with **"This link has already been used"**
even on a fresh link. Root cause: the verify page (`/auth/verify`)
auto-consumed the single-use token on mount via a `useEffect` — **no
user gesture** — against the state-mutating `GET
/api/users/auth/verify`. Anything that *renders the page and runs its
JS* (Gmail/Safe-Browsing link scanners, corporate security proxies)
therefore burned the token and created a throwaway session before the
real user could click.

### Evidence (user `valhalla.gansett@gmail.com`, 2026-07-03, UTC)

Two of his login links were consumed within ~60s of delivery by **Google
LLC** IPs (`2607:f8b0…`, Chrome/149 headless). Cloud Run logs show his
own click losing an 82ms race for token `_VBC4O…`:

| Time | Result | IP | Owner | Browser |
|------|--------|----|-------|---------|
| 00:56:00.176 | **200 (burned it)** | `2607:f8b0…::12` | Google LLC |
Chrome/149 |
| 00:56:00.223 | 401 already-used | `2607:f8b0…::7` | Google (2nd edge)
| Chrome/149 |
| 00:56:00.258 | 401 already-used | `173.245.209.177` | Jacob's VPN |
Chrome/148 |

He got in only via a third link the scanner happened not to prefetch.
Scope check: last 30d, only 2/115 login sessions were consumed from
Google IPs, all his — so it's his specific mail/security setup tripping
a latent design weakness, not a mass outage.

## Fix

The verify page now opens on a **"Complete Sign-In" confirm gate** and
spends the token only on an explicit click. Scanners render the page but
don't click, so the token survives for the real user (standard
magic-link mitigation).

- Mount-time effect is now side-effect-free (stores referral code,
remembers the token) and does **not** verify.
- Verification moved into a `handleConfirm` click handler with a
re-entrancy guard against double-clicks.
- New i18n strings (`confirmTitle`, `confirmBody`, `confirmButton`)
translated to all 33 locales.

Note: switching GET→POST alone would **not** help — a JS-executing
scanner runs the fetch regardless of method. The user-gesture gate is
the robust fix.

## Not in scope

The admin one-click login path (`/app?admin_token=…`) auto-verifies the
same way and has the same latent exposure, but it's admin-only and
low-volume. Flagged in `LESSONS-LEARNED.md` for a follow-up rather than
changing that flow's UX here.

## Testing

- New unit tests: verify page does **not** call `verifyMagicLink` on
mount; verifies only after the "Complete Sign-In" click. Existing
resend-recovery tests updated to click through the gate.
- Full frontend unit suite green (1070 tests); `tsc` + `eslint` clean;
CodeRabbit local review: 0 findings.
- Version bumped `0.190.0 → 0.190.1`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-07-03 13:49:37 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 0fc67d2838 feat: remove Nomad GCS master on delete/edit/private (Phase 2) (#869)
## Why

Phase 1 pushes new Nomad 720p masters to the GCS mirror (→ kjbox in
minutes). This adds the **delete side** so an edit or delete also
propagates: the *latest* cut wins on the box, and stale/renamed masters
don't linger. Per the agreed policy — **Nomad deletes OK; community
keep-forever**.

## What

- **`NomadMasterMirror.delete_masters_by_brand(brand_code)`** — deletes
every 720p master object matched by the unique `"{brand_code} - "`
prefix. Keying on `brand_code` (not a reconstructed title) **covers
renames for free**: every title a release was published under shares the
same `NOMAD-#### - ` prefix.
- **Hard safety guard:** refuses unless the brand is a full `NOMAD-####`
code (non-empty suffix), so a bare/empty prefix can never over-delete.
The `" - "` (space-dash-space) separator makes prefixes collision-proof
across brand lengths (`NOMAD-15` can't match `NOMAD-150…`).
- **`cleanup_nomad_masters(brand_code)`** — best-effort, Nomad-only,
never raises. Wired after the existing Drive/Dropbox output deletes at
the four flows that remove a job's public outputs: job delete/edit
cleanup, re-finalize/re-encode (so a rename drops the old cut; the
re-run's push re-adds the new), admin delete-outputs, and visibility
public→private.

Same-name re-edits already self-heal via Phase 1 (push overwrites; kjbox
rsync updates on size change). This handles **deletes and renames**.

## Testing
- 26 unit tests: prefix delete, rename coverage, the `NOMAD-####` safety
guard (refuses bare/empty/`NOMADNP`/other brands), non-fatal on error,
`cleanup_nomad_masters` delegation/no-op.
- Integration wiring test: admin delete-outputs endpoint calls
`cleanup_nomad_masters` with the job's `brand_code`.
- Local: mirror + gdrive + jobs-API + admin-delete + visibility suites
green.

## Review
Local `feature-dev:code-reviewer` — verified the over-deletion safety
(prefix collision-proofness, brand gating, IAM scope) is sound; added
the wiring test it recommended.

Phase 2 of the nomad-master fast-sync work. Pairs with the kjbox
true-mirror change (Phase 3) so deletes reconcile onto the device.
(Phases 1 & 4 already shipped: #866, #867.)

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 22:11:45 +00:00
Andrew Beveridge ☄️andClaude Fable 5 e97f249efd fix: parse-titles auto-chunks large batches into concurrent Gemini calls (v0.189.1) (#868)
## Summary
Fixes the last loose end from the download-naming handoff: a 100-item
`POST /api/parse-karaoke-titles` batch rode a **single** Gemini call
that exceeded the 20s `parse_titles_timeout_ms`, blanking the whole
batch — forcing kjbox's `refine_titles.py` to run `--batch-size 10`. The
service now auto-chunks internally, so clients can send up to
`parse_titles_max_items` (200) in one request.

## Changes
- `service.parse_titles` splits any batch into **concurrent** chunks of
`parse_titles_chunk_size` (new setting, default 10, env
`PARSE_TITLES_CHUNK_SIZE`) via `asyncio.gather` — no single Gemini call
can outgrow the timeout, and a 100-item batch costs ~1 round-trip of
latency, not 10.
- Graceful degrade is now **per chunk**: a failed/mis-sized chunk blanks
only its own items instead of the whole batch. Kill-switch, `max_items`
tail-blanking, and id-alignment unchanged.

## Testing (TDD — all watched fail first)
- 25 items → exactly 3 calls of 10/10/5, id-aligned results
- Middle-chunk failure blanks only items 10–19
- Concurrency proven with a 3-way barrier (sequential execution would
deadlock)
- Configured chunk size respected (4/4/2)
- Full backend suite: 3663 passed, 139 env skips

## Review
- [x] CodeRabbit CLI: 0 findings

## After deploy
kjbox `refine_titles.py` can drop the `--batch-size 10` workaround
(default batch works).

@coderabbitai ignore

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

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 21:48:54 +00:00
Andrew Beveridge ☄️andClaude Opus 4.8 f42e7321d2 fix(divebar): make 'Refresh catalog' reliably sync just-published tracks (Phase 4) (#867)
## Why

Clicking "Refresh catalog" (or the nightly-equivalent on demand)
advertised "trigger the GCS file sync now", but a just-published track
was indexed (searchable) yet **not byte-synced to GCS** until the next
nightly run. Verified 2026-07-02: the refresh fired all 3 divebar
scheduler jobs **concurrently**, but the file-sync VM only copies files
already in the BigQuery index — and it finished (~3 min) before the slow
index rebuild added the new rows. So the sync raced ahead of the index
and missed the new files.

## What

**Chain-on-completion, gated to the refresh path:**
- The index function (`divebar_mirror`) now, on a successful build,
triggers the index-dependent jobs itself — the file-sync VM + xref
rebuild — via `scheduler_v1.run_job`. This fires at the index's **actual
completion** (which outlasts the caller's HTTP timeout), so ordering is
guaranteed.
- The chain only fires when the request sets `chain_downstream`. A new
**refresh-only** scheduler job (`divebar-mirror-refresh`) carries that
flag in its body; the `refresh` action force-runs it instead of
`divebar-mirror-daily`.
- **The nightly pipeline is 100% untouched** — `divebar-mirror-daily` (2
AM) omits the flag, so it does not chain, and the standalone nightly
`divebar-sync-vm-daily` (3 AM) + `divebar-xref-rebuild-daily` (6 AM) run
once as before. No double-run; the nightly sync's safety net is
preserved.

## Files
- `functions/divebar_mirror/main.py`: `_wants_downstream_chain` +
`_trigger_downstream_jobs`, gated call, `GCP_REGION`.
- `functions/divebar_mirror/requirements.txt`: `google-cloud-scheduler`.
- `modules/divebar_mirror.py`: `GCP_REGION` env + new
`divebar-mirror-refresh` scheduler job (flag body, parked cron, run via
forceRun).
- `functions/divebar_lookup/main.py`: `refresh` triggers only
`divebar-mirror-refresh`.
- `__main__.py`: grant the mirror SA the existing
`divebarSchedulerRunner` role.

## Review
Local `feature-dev:code-reviewer`. It flagged (confidence 82) that an
earlier unconditional-chain version would double-run the nightly
sync/xref — fixed via the refresh-only flag+job above so the nightly
path is untouched.

## Testing
- `divebar_mirror/test_main.py`: downstream-trigger job paths,
partial-failure isolation, flag parsing (chains on flag, NOT on
absent/false).
- `divebar_lookup/test_main.py`: regression guard that refresh triggers
only `divebar-mirror-refresh` (never sync/xref/mirror-daily).

## Deploy
Infra-only. **Already applied to prod** via `pulumi up` (mirror+lookup
functions redeployed, `divebar-mirror-refresh` job created, mirror-SA
scheduler-runner grant). Verified the deployed job POSTs
`{"chain_downstream": true}` to the mirror function.

Phase 4 of the nomad-master fast-sync work. (Phase 1 shipped in #866.)

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 17:17:08 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 a9700b7897 feat: fast-sync Nomad 720p masters to Divebar GCS mirror (Phase 1) (#866)
## Why

New Nomad releases upload to Google Drive at finalize time, but the
**Drive→GCS byte-sync VM only runs nightly (3 AM ET)**, and kjbox
mirrors that GCS folder to `/opt/nomad/downloads/NOMAD-720p/` every 5
min. So a release made during the day sat up to **~24h** before it could
reach kjbox. The "within minutes" expectation only ever held for the
GCS→kjbox hop; the Drive→GCS hop was the daily bottleneck.

Full diagnosis + phased plan:
`docs/archive/2026-07-02-nomad-master-fast-sync-plan.md`.

## What (Phase 1 — the push)

At finalize, push the 720p master **straight to GCS**
(`gs://nomadkaraoke-divebar-files/files/Nomad
Karaoke/MP4-720p/{brand_code} - {name}.mp4`) — the exact object the
nightly VM would produce — so kjbox's existing 5-min timer delivers it
within minutes. No kjbox change needed.

- **`backend/services/nomad_master_mirror.py`** (new):
`NomadMasterMirror.push_720p/delete_720p` + `is_nomad_public_brand`
gate.
- **`gdrive_service.upload_to_public_share`**: guarded
`_fast_sync_nomad_master` after the 720p Drive upload.
- **Config**: `DIVEBAR_FILES_BUCKET`, `NOMAD_MASTER_GCS_PREFIX`,
`NOMAD_MASTER_FAST_SYNC_ENABLED` (kill switch).
- **Infra**: grant `karaoke-backend` SA `objectAdmin` on the divebar
bucket. **Already applied to prod** via targeted `pulumi up` (update
#760).

## Guarantees

- **Idempotent** with the nightly VM (identical object name+size → its
additive rsync skips it); the VM stays the backfill safety net.
- **Nomad-brand only** — excludes `NOMADNP` private tracks and all other
brands/tenants.
- **Best-effort / non-fatal** — a push failure never breaks the
pipeline; it is surfaced as a `distribution_warnings` entry (drives the
admin alert) so it can't silently rot into "nightly-only".

## Testing

- New unit tests (`test_nomad_master_mirror.py`): gate matrix, exact GCS
object name, non-fatal on error, delete/404.
- `upload_to_public_share` integration tests: Nomad push happens with
correct name; non-Nomad/NOMADNP skipped; mirror failure non-fatal +
warning surfaced.
- Local: affected suites green (mirror, gdrive, distribution,
video_worker orchestrator). Full suite runs in CI.

## Scope / follow-ups

This is **Phase 1 of 4**. Follow-ups (separate PRs): Phase 2 gen
delete/replace on Nomad edit/delete; Phase 3 kjbox true-mirror so
deletes/renames reconcile onto the box; Phase 4 fix the "Refresh
catalog" button to run the divebar jobs sequentially (currently races
index vs sync).

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 16:43:41 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 aecd73cb97 feat(api): POST /api/parse-karaoke-titles — batch karaoke-filename parser (#864)
## Summary
New admin endpoint **`POST /api/parse-karaoke-titles`** that turns messy
karaoke filenames into canonical `{artist, title, confidence}` using the
Vertex Gemini stack (reuses the match-judge client pattern). This is
**PR-A of the kjbox download-naming Phase 2** initiative — kjbox will
call it to canonicalise downloaded-file names (esp. fixing artist/title
order, e.g. KaraFun-reversed).

## Contract
- Request: `{items:[{id, filename, channel?, source?}]}`
- Response: `{results:[{id, artist, title, confidence}]}` — one
id-aligned result per input.
- Auth: `require_admin` (`X-Admin-Token`).

## Behaviour
- Batched single Gemini call (JSON response schema, temperature 0,
`location="global"`, Vertex — no API keys).
- **Never 500s on a model error:** kill-switch (`PARSE_TITLES_ENABLED`)
off, any model failure, or a batch length-mismatch → blank results
(`confidence: 0.0`). Fails closed if settings can't load. kjbox degrades
to its deterministic guess when this is unavailable.
- New settings: `parse_titles_enabled` / `_model` (gemini-3.5-flash) /
`_timeout_ms` (20s) / `_max_items` (200).

## Testing
- `backend/tests/test_parse_titles.py` (11 assertions: prompt build,
id-alignment, garbage-response, kill-switch, degrade-on-error, happy
path) + `test_parse_titles_route.py` (admin gate + happy path). All
green locally.

## Design
`kjbox/docs/archive/2026-06-30-download-naming-normalization-design.md`
§4; plan `2026-07-01-download-naming-p2-plan.md` (PR-A).

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 00:45:54 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 d1d7c50ad2 fix(divebar): retry transient download failures so a sync run drains to 0 (#865)
## Summary

Follow-up to #863. Marking dead links fixed the percentage *math*, but
the real reason the GCS mirror sat just under 100% turned out to be
**transient download failures** — a handful of network/5xx blips
scattered across the ~50k-file worklist (observed draining 217 → 37 → 6
→ 1 across successive runs, `marked_dead=0` throughout). Each was left
`NULL` and only cleared on a later night's run, so the KJ status %
hovered at 99.9% and only rounded to 100%.

This makes a **single** sync run reliably drain its worklist to zero.

## Change
`download_and_upload` now retries **transient** failures (5xx / network
/ timeout) up to **3 attempts with exponential backoff (2s, 4s)**. A
**404/410** (file gone from Drive) stays permanent and is returned
immediately **without** retrying (still marked `missing:drive_404`
upstream). After exhausting retries a transient failure returns `(False,
0, False)` — row stays `NULL`, retried next run. No unnecessary sleep
after the final attempt.

Net effect: the mirror lands on a solid **100% "Fully synced" (green)**
on its own each run, rather than depending on rounding.

## Testing
- +3 cases: transient retried-then-succeeds; transient exhausts attempts
→ stays retryable `NULL`; 404 not retried (`call_count == 1`). Autouse
fixture no-ops `time.sleep` so the suite stays fast. **11/11 pass.**
- Reviewed by local `code-reviewer` agent (CodeRabbit was rate-limited):
no issues ≥80 confidence; retry counting, backoff schedule, last-attempt
no-sleep, and 404-skip-retry all verified.

## Rollout
Deploys via the sync VM's `git pull origin main` on its next run (no
Pulumi, no restart).

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 00:29:40 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 2d186e8fb2 fix(divebar): mirror sync % reaches 100% (green) when fully caught up (#863)
## Summary

The KJ **Divebar Catalog Status** modal never reached a
fully-green/complete state — the GCS-mirror figure was pinned at **99.6%
synced** with a permanent "217 pending". Those 217 are Drive files that
now **404** (deleted/renamed since indexing); they sat at `gcs_path IS
NULL` forever, counted as "pending" *and* re-attempted every nightly
sync.

kjbox needs **no change** — its display already renders `>=95%` green
and `==100%` "Fully synced". The fix is entirely upstream in gen: make
"synced" mean *"everything that can be mirrored is"*.

## Changes

**`infrastructure/scripts/divebar_file_sync.py`**
- Classify download failures: a **404/410** (file gone from Drive) now
marks `gcs_path='missing:drive_404'` — a sentinel mirroring the existing
`skipped:too_large` — so it drops out of the `WHERE gcs_path IS NULL`
worklist (no more nightly re-attempts) and out of "pending".
**Transient** errors (5xx/network) still leave `gcs_path` NULL to retry.
- New **"unavailable"** tally in the run summary; progress-log cadence
and `get_sync_stats` updated to count only real `gs://` paths as synced.

**`infrastructure/functions/divebar_lookup/main.py`
(`_get_full_stats`)**
- `synced` = `COUNTIF(gcs_path LIKE 'gs://%')`; split out an
**`unavailable`** bucket (`missing:*`/`skipped:*`); `percent = synced /
(total - unavailable)`.
- A fully-caught-up mirror now reports **100%**. Payload also exposes
`unavailable`, `unavailable_gb`, `syncable_total` for transparent
display.

## Testing
- New `infrastructure/scripts/test_divebar_file_sync.py` (8 tests):
404/410-gone vs transient/5xx classification; each `sync_file` sentinel
path (dead-link, transient, success, too-large).
- +4 `_get_full_stats` percent cases in `divebar_lookup/test_main.py`
(100% when no pending; pending holds <100%; unavailable excluded from
denominator; zero-syncable guard). 23/23 pass.
- Stats SQL validated read-only against prod: `gcs_unavailable=1` today;
`percent → 100` once the sync marks the 217 dead links.
- CodeRabbit: 2 cycles → 0 findings.

## Rollout
- `divebar-lookup` deploys via `pulumi up` (run locally before merge).
- `divebar_file_sync.py` deploys via the sync VM's `git pull origin
main` on its next run; the first post-merge sync marks the 217 dead
links, after which the modal shows **100% "Fully synced" (green)**.

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 23:47:46 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 107542ac39 fix(encoding): scope worker warmup/heartbeat to review-auth, not admin (#862)
## Summary

The lyrics-review page pre-warms the encoding VM on load (and heartbeats
while the reviewer edits) so it's booted by the time they preview a
render. Both endpoints — `POST /api/internal/encoding-worker/warmup` and
`/heartbeat` — required `require_admin` since they were introduced (Mar
25 2026, #595). So **every non-admin customer got a 403 and the JIT
pre-warm silently never fired**. Renders still completed (the encoding
flow's own `ensure_any_running()` boots the VM on demand), but customers
paid the full cold-boot latency the pre-warm was meant to hide. Reported
via 403s in the review-screen devtools console.

## Root cause

`require_admin` is an admin-only gate; the callers are ordinary
customers on a customer-facing page. Admin was the wrong altitude — the
rest of the review surface (`submitCorrections`, `handlers`,
annotations, audio-edit…) uses `require_review_auth`, which the review
page's token already satisfies.

## Fix

Re-scope both endpoints to `require_review_auth` with a `{job_id}` path
param:

- **Backend** (`encoding_worker.py`): `POST /warmup/{job_id}` and
`/heartbeat/{job_id}`, gated on `require_review_auth`. Warming the
shared VM now authorizes exactly like the review page's other calls, so
warmup/heartbeat succeed **precisely when** the review page works —
owners, admins (bypass), and `review_token` users included. Abuse
posture is unchanged: you can only warm the VM if you already have
review access to a real job.
- **Frontend** (`api.ts`, `LyricsAnalyzer.tsx`): thread `jobId` through
`warmupEncodingWorker`/`heartbeatEncodingWorker`, only fire in cloud
mode (`jobId` present — no cloud VM to warm in local mode).

## Changes

- `backend/api/routes/encoding_worker.py` — review-auth + `{job_id}`
path
- `frontend/lib/api.ts` — job-scoped URLs, `jobId` param + guard
- `frontend/components/lyrics-review/LyricsAnalyzer.tsx` — pass `jobId`,
gate on it
- `backend/tests/test_encoding_worker_routes.py` — review-auth contract
+ regression guard that these routes are **not** admin-gated
- `docs/TROUBLESHOOTING.md` — note the auth change and 403 diagnosis
- `pyproject.toml` — 0.188.8 → 0.188.9

## Testing

- Backend: `test_encoding_worker_routes.py` (11) +
manager/persistence/system-status/retry (67 total) +
`test_api_routes.py` (17) — all green. New regression test asserts the
routes depend on `require_review_auth` and **never** `require_admin`,
plus 401-on-no-auth and 404-on-jobless-path.
- Frontend: `jest` lyrics-review + api (319) green; `tsc` clean on both
changed files.
- Prod verification to follow after deploy: open a review page as a
non-admin customer and confirm warmup/heartbeat return 200 (not 403).

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 22:25:05 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 8aa41e960c fix(lyrics-review): recompute segment times on Ctrl+click word delete (#861)
## Summary
- Ctrl+click "delete word" mode in the lyrics review Synchronizer
removed the word but left the **segment's** `start_time`/`end_time`
pointing at the deleted word — deleting the first word left the segment
starting too early; the last word left it ending too late.
- This diverged from the Edit-segment modal, which recomputes the
segment bounds on every word change. The two paths now behave
identically.

## Root cause
`deleteWord()` in
`frontend/lib/lyrics-review/utils/segmentOperations.ts` built the
updated segment with `{ ...segment, words, text }`, spreading the stale
`start_time`/`end_time` and never recomputing them from the remaining
words. The correct path (`EditModal.updateSegment`) filters the
remaining timed words and takes `Math.min`/`Math.max` (or `null` when
none remain). `LyricsAnalyzer.tsx:667` is the sole caller of
`deleteWord`.

## Changes
- `deleteWord` now recomputes `start_time`/`end_time` from the remaining
words (null when no timed words remain), mirroring
`EditModal.updateSegment`.
- Added 5 unit tests to `segmentOperations.test.ts`:
first/last/middle-word deletion, all-untimed remainder → null bounds,
and only-word deletion → whole segment removed.

## Testing
- [x] New `deleteWord` tests: red before fix, green after
- [x] Full `segmentOperations` suite: 11/11 pass
- [x] Full frontend jest suite: 82 suites / 1068 tests pass
- [x] `tsc --noEmit`: no new type errors in changed files

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

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 21:31:32 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 4fd9a85810 fix(custom-lyrics): don't 500 when a repair call returns an empty response (#860)
## Summary

Fixes the custom-lyrics **"NetworkError when attempting to fetch
resource"** failure (job `dc60ebf4`) and the recurring
**`custom_lyrics_repair_call_failed`** production alert (Count 2).

## Root cause
From prod logs, the flow for `dc60ebf4`:
1. Initial Gemini generation **succeeds** and validates (~2 min).
2. A **repair** iteration's response comes back with `response.text =
None` (safety block / MAX_TOKENS / empty candidate).
3. `_parse_lines(None)` → `TypeError: the JSON object must be str, bytes
or bytearray, not NoneType`.

That `TypeError`:
- was **re-raised by the repair loop** — throwing away the *successful
initial result*, and
- escaped as an **uncaught 500 with no CORS headers**, so the browser
(Firefox) showed an opaque `NetworkError` instead of any real message.

`api.nomadkaraoke.com` is direct Cloud Run (`server: Google Frontend`,
no Cloudflare, 1800s timeout), so this was **not** a proxy/latency
cutoff — the 500 itself was the failure.

## Fixes
- **`_call_gemini`**: treat `response.text = None` as a clean
`CustomLyricsServiceError(502)` with a diagnosable reason
(`prompt_block` / `finish_reason`). The endpoint already maps that to a
proper HTTP error **with CORS** — never a raw `TypeError`.
- **Repair loop**: a failed repair is best-effort → fall back to the
best candidate so far (new `StopReason.REPAIR_FAILED`) instead of
re-raising. The user gets their successful initial generation instead of
losing everything.
- **Log severity**: `custom_lyrics_repair_call_failed` downgraded from
`logger.exception` (ERROR) to `logger.warning` — now that it's
handled/non-fatal it shouldn't trip the error monitor; traceback
breadcrumb kept for diagnosing Gemini empties.

## Testing
- `test_repair_failure_falls_back_to_best` — initial succeeds, repair
raises → result is the initial lines, `stop_reason == REPAIR_FAILED`, no
exception.
- `test_empty_gemini_response_raises_clean_error` — `response.text=None`
→ `CustomLyricsServiceError(502)`, not `TypeError`.
- Full custom_lyrics suite green (60). CodeRabbit: 0 findings.

## Follow-up (not in this PR)
The initial Gemini call took ~2 min for this job — the end-to-end
latency (and the spinner UX during it) is a separate concern worth
optimizing (fewer repair iterations, faster model, or an async/polling
endpoint).

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 18:38:18 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 37b405b9c6 fix: reject untimed lyrics before render + retry transient GDrive drops (#859)
## Summary

Triage + fix for a batch of Discord prod error alerts. Grouped into 3
root causes; fixed the two actionable ones.

### Group A — render/preview crash on untimed lyrics (PRIMARY,
job-breaking)
All the `unsupported format string passed to NoneType.__format__` and
`'<' not supported between instances of 'NoneType' and 'float'` alerts
were **one root cause**. Job `231806a4` ("Nelly Furtado - Maneater") had
Danish custom parody lyrics with **all 50 segments + 364 words
`start_time`/`end_time` = null** — the user pasted lyrics into the
Synchronizer's *Edit Lyrics* modal (which creates untimed segments as an
intermediate state) but never tap-synced, then triggered preview +
render. The output pipeline crashed cryptically at ~6 None-unsafe timing
sites instead of rejecting cleanly.

**Fix — fail loudly with an actionable message instead of crashing:**
- New shared gate `validate_segment_timing()` (`LyricsTimingError`) at
the top of `OutputGenerator.generate_outputs()` — covers preview + local
render + encoder.
- `render_video_worker` gates right after loading corrections,
**before** any expensive work or encoder dispatch — stops the
GCE-encoder crash *now*, without an encoder-wheel redeploy.
- Preview endpoint maps `LyricsTimingError` → **422** "synchronize
first" (was a cryptic 500).
- Defense-in-depth: `segment_resizer` debug logging is now None-safe (a
log line must never crash the pipeline).
- Frontend: block **Submit** when untimed words remain, pointing the
user to the synchronizer (`countUntimedWords` mirrors the backend gate).

### Group B — GDrive "brand_code search incomplete: N/3 subfolder(s)
failed"
Transient connection drops (`SSL: UNEXPECTED_EOF_WHILE_READING`, `Broken
pipe`) against idle Cloud Run containers. Wrapped the per-subfolder
Drive lookups in the existing retry-with-backoff + service-reset so
single drops self-heal.

### Group C — investigated, transient, no code change
- `request_audit_error` + "Exception in ASGI application" = one
Firestore *transaction-expiry* on
`/api/admin/rate-limits/blocklists/allowlisted-domains` (count 1,
admin-only).
- `Default STARTUP TCP probe failed … DEADLINE_EXCEEDED` = one slow cold
start that **succeeded on retry** at 12:10.

## Testing
- `test_timing_validation.py` (incl. all-null regression fixture
matching job 231806a4)
- None-safe resizer logging test
- GDrive transient-recovery + retry-exhaustion tests
- Frontend `countUntimedWords` Jest tests
- Re-ran output/, gdrive, render-worker, review-custom-lyrics,
generate_outputs-consumer suites — all green. CodeRabbit: 0 findings.

## Notes
- Frontend guard toast uses a plain string to match the existing
hardcoded toasts in `handleSubmitToServer` (no new i18n key → no locale
churn).
- Detail: `docs/archive/2026-07-01-render-untimed-lyrics-crash-plan.md`.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 16:54:10 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 7655a2ea06 fix(divebar): repair nightly Drive→GCS sync scheduler (doubled URL + wrong token type) (#858)
## Summary

The `divebar-sync-vm-daily` Cloud Scheduler job — which starts the
`divebar-sync` GCE VM that copies community karaoke files **Drive → GCS
mirror** nightly — has never successfully started the VM. As a result
the byte sync silently stalled: the BigQuery index (`divebar_catalog`)
kept refreshing nightly, but **no new file bytes reached
`gs://nomadkaraoke-divebar-files`** since ~2026-05-16 (VM
`lastStartTimestamp` and newest GCS objects both 2026-05-16, ~6 weeks
stale).

Downstream impact: kjbox showed recent community/Nomad tracks as
"available from mirror" (index is fresh) but **fell back to YouTube on
download** because the bytes weren't in GCS. In the Nomad 720p folder
alone, 98 of 1,496 indexed releases (NOMAD-1406→1497) were missing from
GCS.

## Root cause — two bugs in the scheduler's `http_target`

1. **Doubled URL → HTTP 404 NOT_FOUND.** `instance.self_link` already
resolves to a full URL (`https://www.googleapis.com/compute/v1/...`);
the code prepended another compute host on top, producing
`.../compute/v1/https://www.googleapis.com/compute/v1/...`. Now the
`compute.instances.start` endpoint is built explicitly from
`PROJECT_ID`/`ZONE`/`name`.
2. **Wrong token type → HTTP 401 UNAUTHENTICATED** (masked by the 404
until #1 was fixed). `compute.googleapis.com` is a native Google API and
requires an **OAuth 2.0 access token** with `cloud-platform` scope, not
an OIDC identity token. Swapped `oidc_token` → `oauth_token`.

## Testing / deployment

Deployed to prod via **targeted** `pulumi up` (scheduler job resource
only — the other diffs in a full preview were non-reproducible
`FileArchive` re-hashes of unchanged function source, deliberately
excluded):

- Before: manual trigger → HTTP 404 (code 5), then HTTP 401 (code 2)
after the URL fix.
- After: manual trigger → **HTTP 200**, VM transitions to **RUNNING**,
startup script logs `=== Divebar file sync starting ===` and runs the
catch-up sync, then self-shuts-down.

No behavior change to any other resource; provider pin
(`pulumi-gcp==9.22.0`) held (269 unchanged).

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 16:06:29 -04:00
170 changed files with 9725 additions and 564 deletions

No files matched your search

+30 -9
View File
@@ -1,12 +1,16 @@
name: Build GHA Runner Images
# Produces three custom GCE images used by the ephemeral GitHub Actions runner
# dispatcher: gha-runner-general, gha-runner-build, gha-runner-gpu.
# Produces the custom GCE images used by the ephemeral GitHub Actions runner
# dispatcher: gha-runner-general, gha-runner-build, gha-runner-gpu,
# gha-runner-gpu-windows.
#
# Flow per variant:
# 1. Create a temporary build VM from debian-cloud/debian-12 with
# infrastructure/scripts/runner-image-provision.sh as metadata-startup-script.
# 2. Poll for /opt/runner-image-ready via gcloud ssh (survives kernel-upgrade reboots).
# 1. Create a temporary build VM from the variant's base image with the
# variant's provisioning script as its startup script:
# - Linux variants: debian-12 + runner-image-provision.sh (startup-script)
# - gpu-windows: windows-2022 + runner-image-provision.ps1
# (windows-startup-script-ps1)
# 2. Poll the serial console for the READY/FAILED marker (survives reboots).
# 3. Stop the VM, snapshot its boot disk to a new image in the `gha-runner-<variant>`
# image family with name gha-runner-<variant>-<timestamp>.
# 4. Delete the build VM (boot disk auto-deletes).
@@ -16,7 +20,7 @@ on:
workflow_dispatch:
inputs:
variants:
description: 'Comma-separated variants to build (general,build,gpu) or "all"'
description: 'Comma-separated variants to build (general,build,gpu,gpu-windows) or "all"'
required: false
default: 'all'
skip_prune:
@@ -50,7 +54,7 @@ jobs:
run: |
requested='${{ github.event.inputs.variants || 'all' }}'
if [[ "$requested" == "all" || -z "$requested" ]]; then
echo 'variants=["general","build","gpu"]' >> "$GITHUB_OUTPUT"
echo 'variants=["general","build","gpu","gpu-windows"]' >> "$GITHUB_OUTPUT"
else
json="$(echo "$requested" | tr ',' '\n' | jq -R . | jq -sc .)"
echo "variants=$json" >> "$GITHUB_OUTPUT"
@@ -88,6 +92,11 @@ jobs:
family="gha-runner-${variant}"
vm="gha-image-build-${variant}-${ts}"
# Per-variant base image + startup-script metadata key: Windows
# VMs only execute scripts under windows-startup-script-ps1.
image_flag="--image=${{ env.BASE_IMAGE }}"
metadata_file="startup-script=infrastructure/scripts/runner-image-provision.sh"
case "$variant" in
general|build)
machine="n2-standard-8"
@@ -101,6 +110,16 @@ jobs:
disk_size="200"
accel="--maintenance-policy=TERMINATE --accelerator=type=nvidia-tesla-t4,count=1"
;;
gpu-windows)
# T4 attached so the GRID driver install can validate WDDM mode
# (required for DirectML). Keep disk in sync with the
# gpu-windows FamilySpec in runner_manager/ephemeral.py.
machine="n1-standard-4"
disk_size="100"
accel="--maintenance-policy=TERMINATE --accelerator=type=nvidia-tesla-t4,count=1"
image_flag="--image-family=windows-2022 --image-project=windows-cloud"
metadata_file="windows-startup-script-ps1=infrastructure/scripts/runner-image-provision.ps1"
;;
*)
echo "Unknown variant: $variant" >&2
exit 1
@@ -114,6 +133,8 @@ jobs:
echo "machine=$machine"
echo "disk_size=$disk_size"
echo "accel=$accel"
echo "image_flag=$image_flag"
echo "metadata_file=$metadata_file"
} >> "$GITHUB_OUTPUT"
- name: Create build VM
@@ -123,14 +144,14 @@ jobs:
--project='${{ env.GCP_PROJECT }}' \
--zone='${{ env.BUILD_ZONE }}' \
--machine-type='${{ steps.params.outputs.machine }}' \
--image='${{ env.BASE_IMAGE }}' \
${{ steps.params.outputs.image_flag }} \
--boot-disk-size='${{ steps.params.outputs.disk_size }}GB' \
--boot-disk-type=pd-balanced \
--boot-disk-auto-delete \
--service-account="${{ secrets.GCP_SERVICE_ACCOUNT }}" \
--scopes=https://www.googleapis.com/auth/cloud-platform \
--metadata=enable-oslogin=TRUE,image-variant='${{ matrix.variant }}' \
--metadata-from-file=startup-script=infrastructure/scripts/runner-image-provision.sh \
--metadata-from-file='${{ steps.params.outputs.metadata_file }}' \
--labels=purpose=gha-runner-image-builder,variant='${{ matrix.variant }}' \
${{ steps.params.outputs.accel }}
+9 -3
View File
@@ -1657,7 +1657,13 @@ jobs:
# ============================================
# Deploy to Cloud Run
# ============================================
# EDGE-SECURITY: the `edge-origin-secret` Secret Manager secret is
# referenced in --set-secrets below (created 2026-07-20; has a value).
# EDGE_AUTH_MODE=enforce (in --set-env-vars) means the backend rejects
# requests to public routes that lack the Cloudflare-injected X-Edge-Auth
# header — i.e. direct-to-origin traffic bypassing the edge (health/root
# exempt). Cutover done 2026-07-20; validated via prod E2E with 0 blocked
# legit callers. To disable, set EDGE_AUTH_MODE=off here and redeploy.
- name: Deploy to Cloud Run
run: |
VERSION="${{ steps.version_check.outputs.version }}"
@@ -1683,8 +1689,8 @@ jobs:
--min-instances 1 \
--vpc-connector projects/nomadkaraoke/locations/us-central1/connectors/cloud-run-connector \
--vpc-egress private-ranges-only \
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,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,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-opus-4-8,AUTO_CORRECT_COMPARE_MODELS=claude-opus-4-8;gemini-3.1-pro-preview,AUTO_CORRECT_PROACTIVE_ENABLED=true,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
--set-secrets "ANTHROPIC_API_KEY=anthropic-api-key:latest,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,POSTMARK_SERVER_TOKEN=postmark-server-token: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,ENCODING_WORKER_FALLBACK_VMS=encoding-worker-fallback-vms: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"
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-opus-4-8,AUTO_CORRECT_COMPARE_MODELS=claude-opus-4-8;gemini-3.1-pro-preview,AUTO_CORRECT_PROACTIVE_ENABLED=true,EDGE_AUTH_MODE=enforce,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
--set-secrets "ANTHROPIC_API_KEY=anthropic-api-key:latest,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,POSTMARK_SERVER_TOKEN=postmark-server-token: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,ENCODING_WORKER_FALLBACK_VMS=encoding-worker-fallback-vms: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,EDGE_ORIGIN_SECRET=edge-origin-secret:latest"
- name: Update Cloud Run Jobs with new image
run: |
+39 -11
View File
@@ -34,10 +34,12 @@ jobs:
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Python
uses: actions/setup-python@v5
- name: Setup Node.js
uses: actions/setup-node@v4
with:
python-version: '3.11'
node-version: '20'
cache: 'npm'
cache-dependency-path: frontend/package-lock.json
- name: Authenticate to GCP
uses: google-github-actions/auth@v2
@@ -46,15 +48,38 @@ jobs:
service_account: ${{ secrets.GCP_SERVICE_ACCOUNT }}
- name: Install dependencies
run: pip install google-cloud-storage google-cloud-secret-manager
working-directory: frontend
run: npm ci --legacy-peer-deps
- name: Run tenant E2E
id: run_test
env:
KARAOKE_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
- name: Install Playwright browsers
working-directory: frontend
run: npx playwright install --with-deps chromium
- name: Fetch test audio (private GCS)
run: bash scripts/e2e/fetch_test_audio.sh frontend/e2e/fixtures
- name: Ensure testmail.app domain is allowlisted (rate limit)
run: |
echo "=== Tenant E2E: ${{ matrix.tenant }} ==="
python scripts/e2e/tenant_e2e.py ${{ matrix.tenant }} 2>&1 | tee e2e-output.log
curl -sf -X POST \
"https://api.nomadkaraoke.com/api/admin/rate-limits/blocklists/allowlisted-domains" \
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" \
-H "Content-Type: application/json" \
-d '{"domain": "inbox.testmail.app"}' || echo "Warning: allowlist may already exist"
- name: Run tenant E2E (frontend journey)
id: run_test
working-directory: frontend
env:
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
TESTMAIL_NAMESPACE: ${{ secrets.TESTMAIL_NAMESPACE }}
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
TENANT_ID: ${{ matrix.tenant }}
TENANT_PORTAL_URL: https://${{ matrix.tenant }}.nomadkaraoke.com
run: |
echo "=== Tenant E2E (frontend): ${{ matrix.tenant }} ==="
npx playwright test tenant-happy-path.spec.ts \
--config=playwright.production.config.ts --project=chromium \
--reporter=list --timeout=2400000 2>&1 | tee e2e-output.log
echo "exit_code=${PIPESTATUS[0]}" >> "$GITHUB_OUTPUT"
continue-on-error: true
@@ -63,7 +88,10 @@ jobs:
uses: actions/upload-artifact@v4
with:
name: e2e-tenant-${{ matrix.tenant }}-${{ github.run_number }}
path: e2e-output.log
path: |
frontend/e2e-output.log
frontend/test-results/
frontend/playwright-report/
retention-days: 14
- name: Discord notification (failure)
+15 -1
View File
@@ -1203,7 +1203,7 @@ async def reset_job(
job_manager.update_job(job_id, updates)
# Clear the state data keys and error state using direct Firestore update
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion, Increment
job_ref = user_service.db.collection("jobs").document(job_id)
@@ -1219,6 +1219,14 @@ async def reset_job(
clear_updates["error_message"] = DELETE_FIELD
clear_updates["error_details"] = DELETE_FIELD
# Advance the supersession fence: a reset is a "stop what you're doing" event.
# Any render/video worker still in flight (e.g. the operator hit "Review"
# mid-render) will observe the bumped generation and discard its stale result
# instead of overwriting fresh outputs or failing this reset. See
# backend/workers/supersede.py. Atomic with the clears above so an in-flight
# worker can never observe a half-applied reset.
clear_updates["state_data.worker_generation"] = Increment(1)
# Add timeline event
clear_updates["timeline"] = ArrayUnion([timeline_event])
@@ -1709,6 +1717,12 @@ async def delete_job_outputs(
logger.error(f"Error deleting Google Drive files for job {job_id}: {e}", exc_info=True)
results["gdrive"] = {"status": "error", "error": str(e)}
# Remove the Nomad 720p master(s) from the GCS fast-sync mirror too (prefix-keyed
# by brand_code, covers renames). Non-fatal, Nomad-only, no-op otherwise.
if brand_code:
from backend.services.nomad_master_mirror import cleanup_nomad_masters
cleanup_nomad_masters(brand_code)
# Clean up GCS finals folder - prevents stale files from being picked up during re-encoding
try:
from backend.services.storage_service import StorageService
+16
View File
@@ -18,6 +18,8 @@ from backend.services.error_monitor.frontend_ingestion import (
FrontendErrorReport,
RateLimiter,
build_pattern_data,
is_bot_user_agent,
sanitize_url,
)
logger = logging.getLogger(__name__)
@@ -64,6 +66,20 @@ def report_client_error(payload: ClientErrorPayload, request: Request) -> Client
if not _limiter.allow(client_ip, time.monotonic()):
raise HTTPException(status_code=429, detail="too many reports")
# Crawler/bot crashes are pure alert noise (bots run headless Chrome and trip
# DOM errors no real user hits). Accept the report so the client doesn't retry,
# but don't persist/alert on it.
if is_bot_user_agent(payload.user_agent):
# Log the bot UA (not sensitive) + sanitized URL (query/token stripped)
# for visibility into what's being dropped, without persisting/alerting.
logger.info(
"frontend_crash_ignored_bot ua=%r url=%s source=%s",
payload.user_agent[:120],
sanitize_url(payload.url),
payload.source,
)
return ClientErrorResponse(pattern_id="bot-ignored", is_new=False)
report = FrontendErrorReport(
message=payload.message,
stack=payload.stack,
+27 -9
View File
@@ -2,13 +2,21 @@
Encoding worker lifecycle endpoints.
Provides warmup and heartbeat endpoints for the blue-green
encoding worker VMs. Called by the frontend to ensure the
primary VM is running before encoding requests.
encoding worker VMs. Called by the lyrics-review frontend to ensure the
primary VM is running before the reviewer previews a render.
Auth: these are gated on ``require_review_auth`` (review access to a specific
job), NOT ``require_admin``. The callers are ordinary customers on the
lyrics-review page — gating on admin makes every non-admin caller 403, which
silently defeats the JIT pre-warm. Scoping to the job being reviewed keeps the
abuse posture identical to the rest of the review surface: you can only warm
the shared encoding VM if you already have review access to a real job.
"""
import logging
from typing import Tuple
from fastapi import APIRouter, Depends
from backend.api.dependencies import require_admin
from backend.api.dependencies import require_review_auth
from backend.services.encoding_worker_manager import EncodingWorkerManager
from backend.services.encoding_errors import EncodingWorkerStartError
@@ -36,12 +44,17 @@ def get_worker_manager():
return _manager
@router.post("/warmup")
@router.post("/warmup/{job_id}")
async def warmup_encoding_worker(
_admin=Depends(require_admin),
job_id: str,
_auth: Tuple[str, str] = Depends(require_review_auth),
manager=Depends(get_worker_manager),
):
"""Start the primary encoding worker VM if it's stopped."""
"""Start the primary encoding worker VM if it's stopped.
Called on lyrics-review page load so the VM is warm by the time the
reviewer previews a render. ``job_id`` scopes auth to the job under review.
"""
try:
result = manager.ensure_primary_running()
if result["started"]:
@@ -64,12 +77,17 @@ async def warmup_encoding_worker(
return {"started": False, "error": str(e)}
@router.post("/heartbeat")
@router.post("/heartbeat/{job_id}")
async def heartbeat_encoding_worker(
_admin=Depends(require_admin),
job_id: str,
_auth: Tuple[str, str] = Depends(require_review_auth),
manager=Depends(get_worker_manager),
):
"""Update activity timestamp to prevent idle shutdown."""
"""Update activity timestamp to prevent idle shutdown.
Called periodically while the reviewer works. ``job_id`` scopes auth to the
job under review.
"""
try:
manager.update_activity()
return {"status": "ok"}
+216 -20
View File
@@ -796,58 +796,254 @@ async def recover_stuck_jobs(
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
):
"""
Detect and recover jobs stuck in downloading_audio status.
Detect and recover jobs stuck in a processing status.
Called by Cloud Scheduler (every 5 minutes) or manually from admin.
Finds jobs stuck in DOWNLOADING_AUDIO for >10 minutes and fails them
so they can be retried.
- DOWNLOADING_AUDIO stuck >10 min:
* torrent sources (RED/OPS) → park into DOWNLOAD_PENDING_RETRY and keep
auto-retrying for up to 24h (handles rare tracks with intermittent
seeders and transient tracker outages gracefully).
* other sources → fail so the user can retry.
- DOWNLOAD_PENDING_RETRY → re-trigger the download; permanently fail after 24h.
- RENDERING_VIDEO stuck with no progress (worker died mid-render) →
re-park into RENDER_PENDING_CAPACITY so the existing
retry-pending-render-jobs cron resumes it automatically. Closes the orphan
gap where a hard-killed render worker leaves the job frozen at
"rendering_video" forever with no error and no Retry button.
"""
from backend.services.job_health_service import check_job_consistency
from backend.services.worker_service import get_worker_service
from backend.models.job import JobStatus
trace_context = extract_trace_context(dict(http_request.headers))
extract_trace_context(dict(http_request.headers))
logger.info("RECOVER_STUCK_JOBS starting")
add_span_attribute("operation", "recover_stuck_jobs")
job_manager = JobManager()
worker_service = get_worker_service()
# Query jobs in downloading_audio status
from google.cloud.firestore_v1 import FieldFilter
jobs_ref = job_manager.firestore.db.collection("jobs")
recovered = [] # download jobs failed for user retry
download_parked = [] # transient torrent downloads parked for auto-retry
download_retried = [] # parked downloads re-triggered this tick
download_timed_out = [] # parked downloads that exceeded the 24h ceiling
reparked = [] # render jobs re-parked for auto-retry
# --- Stuck audio downloads: park torrents for auto-retry, else fail ---
stuck_query = jobs_ref.where(
filter=FieldFilter("status", "==", "downloading_audio")
filter=FieldFilter("status", "==", JobStatus.DOWNLOADING_AUDIO.value)
).stream()
recovered = []
for doc in stuck_query:
job_data = doc.to_dict()
job_id = job_data.get("job_id", doc.id)
# Use the health service to check if actually stuck
job_id = (doc.to_dict() or {}).get("job_id", doc.id)
job = job_manager.get_job(job_id)
if not job:
continue
issues = check_job_consistency(job)
stuck_issues = [i for i in issues if "downloading_audio_stuck" in i]
if stuck_issues:
logger.warning(f"[job:{job_id}] Recovering stuck download: {stuck_issues[0]}")
if not any("downloading_audio_stuck" in i for i in check_job_consistency(job)):
continue
if _is_retryable_torrent_source(job):
logger.warning(f"[job:{job_id}] Parking stuck torrent download for auto-retry")
if _park_download_for_retry(job_manager, job_id, "download stalled (>10 min)"):
download_parked.append(job_id)
else:
logger.warning(f"[job:{job_id}] Recovering stuck download (non-torrent)")
job_manager.fail_job(
job_id,
"Audio download timed out (stuck >10 minutes). Use retry to re-attempt."
)
recovered.append(job_id)
logger.info(f"RECOVER_STUCK_JOBS complete: recovered={len(recovered)} jobs")
add_span_event("recovery_complete", {"recovered_count": len(recovered)})
# --- Parked downloads: re-trigger, or permanently fail after 24h ---
retried_this_tick = 0
pending_query = jobs_ref.where(
filter=FieldFilter("status", "==", JobStatus.DOWNLOAD_PENDING_RETRY.value)
).limit(100).stream()
for doc in pending_query:
job_id = (doc.to_dict() or {}).get("job_id", doc.id)
job = job_manager.get_job(job_id)
if not job:
continue
meta = (job.state_data or {}).get("download_retry", {}) or {}
first_seen = meta.get("first_seen_at")
if _download_retry_expired(first_seen):
hours = int(DOWNLOAD_RETRY_MAX_SECONDS // 3600)
logger.error(f"[job:{job_id}] Download retries exhausted after {hours}h — failing")
job_manager.fail_job(
job_id,
f"Couldn't find a working source for this track after {hours}h of "
"automatic retries. It may be too rare to source right now — please "
"try a different version or contact support.",
error_details={"stage": "audio_download", "permanent_download_timeout": True},
)
download_timed_out.append(job_id)
continue
if retried_this_tick >= DOWNLOAD_RETRIES_PER_TICK:
continue
# Count the dispatch ATTEMPT against the per-tick cap before awaiting, so
# a failing audio-worker (helper returns False after an external dispatch)
# can't fan out to every queried job in one tick.
retried_this_tick += 1
if await _retrigger_parked_download(job_manager, worker_service, job_id):
download_retried.append(job_id)
# --- Orphaned renders: re-park for automatic retry ---
render_query = jobs_ref.where(
filter=FieldFilter("status", "==", JobStatus.RENDERING_VIDEO.value)
).stream()
for doc in render_query:
job_id = (doc.to_dict() or {}).get("job_id", doc.id)
job = job_manager.get_job(job_id)
if not job:
continue
if any("rendering_video_stuck" in i for i in check_job_consistency(job)):
logger.warning(f"[job:{job_id}] Re-parking orphaned render for auto-retry")
if _repark_stalled_render(job_manager, job_id):
reparked.append(job_id)
logger.info(
f"RECOVER_STUCK_JOBS complete: recovered={len(recovered)} "
f"download_parked={len(download_parked)} download_retried={len(download_retried)} "
f"download_timed_out={len(download_timed_out)} reparked={len(reparked)}"
)
add_span_event("recovery_complete", {
"recovered_count": len(recovered),
"download_parked_count": len(download_parked),
"download_retried_count": len(download_retried),
"download_timed_out_count": len(download_timed_out),
"reparked_count": len(reparked),
})
return {
"status": "success",
"recovered_jobs": recovered,
"recovered_count": len(recovered),
"download_parked_jobs": download_parked,
"download_retried_jobs": download_retried,
"download_timed_out_jobs": download_timed_out,
"reparked_render_jobs": reparked,
"reparked_render_count": len(reparked),
}
# Torrent sources whose downloads are worth auto-retrying over a long window —
# they fail transiently when a rare release has few/intermittent seeders or the
# private tracker is briefly unreachable. Non-torrent sources (YouTube/Spotify/
# URL) fail deterministically, so they are not auto-retried here.
RETRYABLE_TORRENT_SOURCES = frozenset({"RED", "OPS"})
DOWNLOAD_RETRY_MAX_SECONDS = 24 * 60 * 60 # keep retrying a transient download for 24h
DOWNLOAD_RETRIES_PER_TICK = 10 # cap re-triggers per 5-min tick
def _is_retryable_torrent_source(job) -> bool:
"""True if the job's audio came from a torrent tracker (RED/OPS)."""
return (getattr(job, "source_name", "") or "").upper() in RETRYABLE_TORRENT_SOURCES
def _download_retry_expired(first_seen_at: Optional[str]) -> bool:
"""True if the first parked failure is older than the 24h retry ceiling."""
if not first_seen_at:
return False
from datetime import datetime, UTC
try:
age = datetime.now(UTC) - datetime.fromisoformat(first_seen_at)
except (ValueError, TypeError):
return False
return age.total_seconds() > DOWNLOAD_RETRY_MAX_SECONDS
def _park_download_for_retry(job_manager: JobManager, job_id: str, reason: str) -> bool:
"""Park a transient torrent-download failure into DOWNLOAD_PENDING_RETRY.
The recover-stuck cron re-triggers parked downloads on later ticks (up to
24h) instead of dead-ending the job at FAILED after ~1h.
"""
from datetime import datetime, UTC
from backend.models.job import JobStatus
now = datetime.now(UTC).isoformat()
job = job_manager.get_job(job_id)
existing = (job.state_data or {}).get("download_retry", {}) if job else {}
meta = {
"first_seen_at": existing.get("first_seen_at") or now,
"last_attempt_at": now,
"attempt_count": int(existing.get("attempt_count", 0)) + 1,
"last_reason": str(reason)[:300],
}
job_manager.update_state_data(job_id, "download_retry", meta)
# Clear any Cloud Run auto-retry marker so the UI reflects the parked state.
job_manager.update_state_data(job_id, "cloud_run_retry_pending", None)
return bool(job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.DOWNLOAD_PENDING_RETRY,
progress=12,
message=(
"Still finding a good source for this track — it may be rare, or a "
"source is temporarily offline. We'll keep trying automatically for up "
"to 24 hours; no action needed."
),
raise_on_invalid=False,
))
async def _retrigger_parked_download(job_manager: JobManager, worker_service, job_id: str) -> bool:
"""Re-trigger the audio download for a DOWNLOAD_PENDING_RETRY job."""
from backend.models.job import JobStatus
job_manager.update_job(job_id, {"error_message": None, "error_details": None})
if not job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.DOWNLOADING_AUDIO,
progress=12,
message="Retrying audio download — checking sources again",
raise_on_invalid=False,
):
logger.warning(f"[job:{job_id}] Could not transition parked download for retry")
return False
try:
await worker_service.trigger_audio_download_worker(job_id)
logger.info(f"[job:{job_id}] Parked download re-triggered")
return True
except Exception as e: # noqa: BLE001
logger.error(f"[job:{job_id}] Failed to re-trigger parked download: {e}")
return False
def _repark_stalled_render(job_manager: JobManager, job_id: str) -> bool:
"""Re-park a render orphaned at RENDERING_VIDEO into RENDER_PENDING_CAPACITY.
Mirrors render_video_worker._park_job_for_capacity_retry but for a mid-render
stall (no EncodingWorkerStartError to carry). The existing
retry-pending-render-jobs cron then resets it to REVIEW_COMPLETE and
re-triggers the render, with the same 24h permanent-failure ceiling.
"""
from datetime import datetime, UTC
from backend.models.job import JobStatus
now = datetime.now(UTC).isoformat()
job = job_manager.get_job(job_id)
existing = (job.state_data or {}).get("render_pending_capacity", {}) if job else {}
pending_meta = {
"first_seen_at": existing.get("first_seen_at") or now,
"last_attempt_at": now,
"attempt_count": int(existing.get("attempt_count", 0)) + 1,
"last_code": "render_stalled",
"last_zone": existing.get("last_zone", ""),
"last_vm": existing.get("last_vm", ""),
}
job_manager.update_state_data(job_id, "render_pending_capacity", pending_meta)
return bool(job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.RENDER_PENDING_CAPACITY,
progress=70,
message=(
"The render was interrupted (a worker was recycled). Your job will "
"retry automatically — no action needed."
),
raise_on_invalid=False,
))
@router.get("/health")
async def internal_health(
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
+13
View File
@@ -396,6 +396,11 @@ async def edit_completed_track(
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}
# Also remove the Nomad 720p master from the GCS fast-sync mirror
# (prefix-keyed by brand_code, so it covers renames). Non-fatal,
# Nomad-brand only, no-op otherwise.
from backend.services.nomad_master_mirror import cleanup_nomad_masters
cleanup_nomad_masters(brand_code)
else:
cleanup_results["gdrive"] = {"status": "skipped", "reason": "Google Drive not configured"}
except Exception as e:
@@ -2282,6 +2287,14 @@ async def cleanup_distribution(
"status": "skipped",
"reason": "no files found to delete",
}
# Remove the Nomad 720p master(s) from the GCS fast-sync mirror too, so a
# re-finalise (incl. artist/title rename) doesn't leave the old cut on
# kjbox. Prefix-keyed by brand_code (covers renames); the subsequent
# re-run's push re-adds the new master. Non-fatal, Nomad-only.
if brand_code:
from backend.services.nomad_master_mirror import cleanup_nomad_masters
cleanup_nomad_masters(brand_code)
else:
results["gdrive"] = {
"status": "failed",
+52
View File
@@ -0,0 +1,52 @@
"""POST /api/parse-karaoke-titles — batch karaoke-filename → artist/title.
Internal admin endpoint used by kjbox to canonicalise downloaded-file names.
Reuses the Vertex Gemini parser; never blocks the caller (kjbox degrades to a
deterministic guess when this is unavailable).
"""
import logging
from typing import Optional
from fastapi import APIRouter, Depends
from pydantic import BaseModel
from backend.api.dependencies import require_admin
from backend.services.auth_service import AuthResult
from backend.services.parse_titles import parse_titles
logger = logging.getLogger(__name__)
router = APIRouter(tags=["parse-titles"])
class ParseItem(BaseModel):
id: str
filename: str
channel: Optional[str] = None
source: Optional[str] = None
class ParseRequest(BaseModel):
items: list[ParseItem]
class ParseResult(BaseModel):
id: str
artist: str
title: str
confidence: float
class ParseResponse(BaseModel):
results: list[ParseResult]
@router.post("/parse-karaoke-titles", response_model=ParseResponse)
async def parse_karaoke_titles(
body: ParseRequest,
auth_result: AuthResult = Depends(require_admin),
):
items = [i.model_dump() for i in body.items]
results = await parse_titles(items)
logger.info("parse-karaoke-titles: %d items", len(items))
return {"results": results}
+8
View File
@@ -185,6 +185,7 @@ def _synthesized_segments(target_lines: list[str]) -> list[dict]:
from karaoke_gen.lyrics_transcriber.types import CorrectionResult
from karaoke_gen.lyrics_transcriber.core.config import OutputConfig
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
from karaoke_gen.lyrics_transcriber.output.timing_validation import LyricsTimingError
# Import from the unified style loader
from karaoke_gen.style_loader import load_styles_from_gcs
@@ -1226,6 +1227,13 @@ async def generate_preview_video(
return {"status": "success", "preview_hash": preview_hash}
except LyricsTimingError as timing_err:
# Untimed lyrics (e.g. custom lyrics not yet tap-synced) — this is a
# user-fixable input problem, not a server fault. Return 422 with an
# actionable message instead of a cryptic 500.
logger.warning(f"Job {job_id}: Preview blocked — lyrics not synchronized: {timing_err}")
span.set_attribute("error", "lyrics_not_synchronized")
raise HTTPException(status_code=422, detail=str(timing_err)) from timing_err
except Exception as e:
logger.error(f"Job {job_id}: Failed to generate preview video: {e}", exc_info=True)
span.set_attribute("error", str(e))
+26
View File
@@ -481,6 +481,32 @@ async def verify_magic_link(
)
class MagicLinkStatusResponse(BaseModel):
status: str # "valid" | "used" | "expired" | "invalid"
@router.get("/auth/link-status", response_model=MagicLinkStatusResponse)
async def magic_link_status(
token: str,
user_service: UserService = Depends(get_user_service),
):
"""
Read-only status of a magic link — does NOT consume it.
The verify page calls this on load so it can show the correct UI upfront:
the "Complete Sign-In" gate for a valid link, or an "already used / expired"
message for a dead one — without making the user click only to then fail.
This endpoint is intentionally non-mutating so that an email link-scanner
which renders the verify page (and triggers this read) cannot burn a still-
valid token before the real user clicks. Token consumption happens only in
the separate GET /auth/verify, which requires an explicit user click.
"""
if not token or not token.strip():
return MagicLinkStatusResponse(status="invalid")
return MagicLinkStatusResponse(status=user_service.get_magic_link_status(token))
@router.post("/auth/resend-from-token", response_model=ResendFromTokenResponse)
async def resend_magic_link_from_token(
request: ResendFromTokenRequest,
+24
View File
@@ -20,6 +20,17 @@ class Settings(BaseSettings):
gcs_temp_bucket: str = os.getenv("GCS_TEMP_BUCKET", "karaoke-gen-temp")
gcs_output_bucket: str = os.getenv("GCS_OUTPUT_BUCKET", "karaoke-gen-outputs")
firestore_collection: str = os.getenv("FIRESTORE_COLLECTION", "jobs")
# Nomad master fast-sync: push freshly-published Nomad 720p masters straight to the
# Divebar GCS mirror so kjbox (which mirrors that folder every 5 min) picks them up
# within minutes instead of waiting for the nightly Drive->GCS VM. Nomad-brand only.
divebar_files_bucket: str = os.getenv("DIVEBAR_FILES_BUCKET", "nomadkaraoke-divebar-files")
nomad_master_gcs_prefix: str = os.getenv("NOMAD_MASTER_GCS_PREFIX", "files/Nomad Karaoke/MP4-720p")
nomad_master_fast_sync_enabled: bool = os.getenv("NOMAD_MASTER_FAST_SYNC_ENABLED", "true").lower() == "true"
# Original-vocals guide: a padded isolated-vocals file (silence[intro] + vocals) pushed to
# a sibling prefix in the same Divebar bucket, which kjbox mirrors into NOMAD-vocals-padded/
# to power the "Original Vocals" sing-along slider. Same brand gating as the master push.
nomad_vocals_guide_gcs_prefix: str = os.getenv("NOMAD_VOCALS_GUIDE_GCS_PREFIX", "files/Nomad Karaoke/vocals-padded")
# Audio Separator API (for GPU processing)
audio_separator_api_url: Optional[str] = os.getenv("AUDIO_SEPARATOR_API_URL")
@@ -117,6 +128,19 @@ class Settings(BaseSettings):
# call still runs off the critical path and degrades to "none" on timeout.
match_judge_timeout_ms: int = int(os.getenv("MATCH_JUDGE_TIMEOUT_MS", "12000"))
# Batch karaoke-filename parser (kjbox download-naming). Reuses the Vertex
# Gemini stack. Larger timeout than match_judge because it batches ~200 items.
parse_titles_enabled: bool = os.getenv("PARSE_TITLES_ENABLED", "true").lower() in (
"1", "true", "yes",
)
parse_titles_model: str = os.getenv("PARSE_TITLES_MODEL", "gemini-3.5-flash")
parse_titles_timeout_ms: int = int(os.getenv("PARSE_TITLES_TIMEOUT_MS", "20000"))
parse_titles_max_items: int = int(os.getenv("PARSE_TITLES_MAX_ITEMS", "200"))
# Items per Gemini call: large client batches are split into concurrent
# chunks of this size so one call never outgrows parse_titles_timeout_ms
# (a 100-item single call did, blanking the whole batch).
parse_titles_chunk_size: int = int(os.getenv("PARSE_TITLES_CHUNK_SIZE", "10"))
# Cloud Tasks (for scalable worker coordination)
# When enabled, workers are triggered via Cloud Tasks for guaranteed delivery
# When disabled (default), workers are triggered via direct HTTP (for development)
+9 -1
View File
@@ -10,7 +10,7 @@ from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from backend.config import settings
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, rate_limits, push, catalog, encoding_worker, client_errors, bulk
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, rate_limits, push, catalog, encoding_worker, client_errors, bulk, parse_titles
from backend.services.tracing import setup_tracing, instrument_app, get_current_trace_id
from backend.services.structured_logging import setup_structured_logging
from backend.services.spacy_preloader import preload_spacy_model
@@ -18,6 +18,7 @@ from backend.services.nltk_preloader import preload_all_nltk_resources
from backend.services.langfuse_preloader import preload_langfuse_handler
from backend.middleware.audit_logging import AuditLoggingMiddleware
from backend.middleware.tenant import TenantMiddleware
from backend.middleware.edge_auth import EdgeAuthMiddleware
from backend.workers.registry import worker_registry
@@ -170,6 +171,12 @@ app.add_middleware(AuditLoggingMiddleware)
# Add tenant detection middleware (extracts tenant from subdomain/headers)
app.add_middleware(TenantMiddleware)
# Edge origin lock (added last = outermost, runs first). Rejects direct-to-origin
# requests that bypassed the Cloudflare edge, before tenant/audit middleware do
# any work. No-op unless EDGE_AUTH_MODE is warn/enforce. See
# backend/middleware/edge_auth.py.
app.add_middleware(EdgeAuthMiddleware)
# Include routers
app.include_router(health.router, prefix="/api")
app.include_router(jobs.router, prefix="/api")
@@ -187,6 +194,7 @@ app.include_router(admin.router, prefix="/api") # Admin dashboard and managemen
app.include_router(rate_limits.router, prefix="/api") # Rate limits admin management
app.include_router(push.router, prefix="/api") # Push notification subscription management
app.include_router(catalog.router, prefix="/api") # Catalog proxy for song/artist autocomplete
app.include_router(parse_titles.router, prefix="/api") # kjbox karaoke-filename parser
app.include_router(bulk.router, prefix="/api") # Bulk Mode: multi-job submission
app.include_router(client_errors.router, prefix="/api") # Frontend crash reports
app.include_router(tenant.router) # Tenant/white-label configuration (no /api prefix, router has it)
+115
View File
@@ -0,0 +1,115 @@
"""
Edge origin-lock middleware.
Cloudflare fronts ``api.nomadkaraoke.com`` (WAF + rate limiting). To stop
attackers from bypassing the edge by hitting the Cloud Run origin directly
(``*.run.app`` / ``ghs.googlehosted.com``), Cloudflare injects a shared-secret
header (``X-Edge-Auth``) on every proxied request via a Transform Rule. This
middleware rejects public requests that lack the correct header.
A Cloud Run *domain mapping* can't use ``ingress=internal-and-cloud-load-balancing``
(that needs a load balancer), so this app-layer check is how we lock the origin.
Modes (env ``EDGE_AUTH_MODE``, default ``off``):
off - passthrough, no checks (deploy-dormant; behaviour unchanged).
warn - log requests missing/failing the header, but ALLOW them. Use to
confirm nothing legit is missing the header before enforcing.
enforce - reject requests missing/failing the header with 403.
Secret: env ``EDGE_ORIGIN_SECRET`` (same value Cloudflare injects). If enforce
mode is set but the secret is unconfigured, the middleware FAILS CLOSED (503) —
a security control must not silently allow direct-origin traffic. (Low risk:
Cloud Run won't start a revision whose secret ref is missing, and enforce is
only enabled after staging confirms the secret.) In warn mode it still allows.
Exemptions (always allowed, even in enforce mode):
* Health / root endpoints and Cloud Run probes, which hit the origin
directly (not via Cloudflare) and legitimately lack the header.
"""
import hmac
import logging
import os
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.requests import Request
from starlette.responses import JSONResponse, Response
logger = logging.getLogger(__name__)
# Header Cloudflare injects (must match CloudflareConfig.ORIGIN_AUTH_HEADER in
# infrastructure/modules/edge_security.py).
EDGE_AUTH_HEADER = "X-Edge-Auth"
# Paths always allowed without the edge header. These are non-sensitive and are
# probed directly on the origin by Cloud Run startup/liveness checks and GCP
# uptime monitoring, which don't traverse Cloudflare.
_EXEMPT_EXACT = {"/", "/api/health", "/api/health/"}
_EXEMPT_PREFIXES = ("/api/health/",)
_VALID_MODES = {"off", "warn", "enforce"}
def _mode() -> str:
mode = os.environ.get("EDGE_AUTH_MODE", "off").lower().strip()
return mode if mode in _VALID_MODES else "off"
def _is_exempt(path: str) -> bool:
if path in _EXEMPT_EXACT:
return True
return any(path.startswith(p) for p in _EXEMPT_PREFIXES)
class EdgeAuthMiddleware(BaseHTTPMiddleware):
"""Reject origin requests that didn't come through the Cloudflare edge."""
async def dispatch(self, request: Request, call_next) -> Response:
mode = _mode()
if mode == "off":
return await call_next(request)
if _is_exempt(request.url.path):
return await call_next(request)
secret = os.environ.get("EDGE_ORIGIN_SECRET", "")
if not secret:
# Misconfiguration: enforce is requested but no secret is wired up.
# In enforce mode, fail CLOSED (503) — a security control must not
# silently allow direct-origin traffic when it can't do its job.
# This is low-risk operationally: Cloud Run won't even start a
# revision whose --set-secrets ref is missing, and enforce is only
# turned on after staging confirms the secret. In warn mode we still
# allow (observational only).
logger.error(
"EDGE_AUTH_MODE=%s but EDGE_ORIGIN_SECRET is unset.", mode,
)
if mode == "enforce":
return JSONResponse(
status_code=503,
content={"detail": "Origin authentication unavailable"},
)
return await call_next(request)
provided = request.headers.get(EDGE_AUTH_HEADER, "")
# Constant-time comparison to avoid leaking the secret via timing.
ok = bool(provided) and hmac.compare_digest(provided, secret)
if ok:
return await call_next(request)
client = request.client.host if request.client else "?"
if mode == "warn":
logger.warning(
"edge-auth: request missing/invalid %s header (warn mode, "
"allowing). path=%s ip=%s",
EDGE_AUTH_HEADER, request.url.path, client,
)
return await call_next(request)
# enforce
logger.warning(
"edge-auth: blocked direct-to-origin request. path=%s ip=%s",
request.url.path, client,
)
return JSONResponse(status_code=403, content={"detail": "Forbidden"})
+6 -1
View File
@@ -37,6 +37,7 @@ class JobStatus(str, Enum):
SEARCHING_AUDIO = "searching_audio" # Searching for audio sources via flacfetch
AWAITING_AUDIO_SELECTION = "awaiting_audio_selection" # ⚠️ WAITING FOR USER - select audio source
DOWNLOADING_AUDIO = "downloading_audio" # Downloading selected audio from source
DOWNLOAD_PENDING_RETRY = "download_pending_retry" # Download hit a transient issue (few/no seeders, tracker blip); auto-retrying for up to 24h
DOWNLOADING = "downloading" # Downloading from URL or processing upload
@@ -110,7 +111,11 @@ STATE_TRANSITIONS = {
# Audio search flow (for artist+title search mode)
JobStatus.SEARCHING_AUDIO: [JobStatus.AWAITING_AUDIO_SELECTION, JobStatus.DOWNLOADING_AUDIO, JobStatus.FAILED],
JobStatus.AWAITING_AUDIO_SELECTION: [JobStatus.DOWNLOADING_AUDIO, JobStatus.FAILED, JobStatus.CANCELLED],
JobStatus.DOWNLOADING_AUDIO: [JobStatus.DOWNLOADING, JobStatus.AWAITING_DURATION_CONFIRM, JobStatus.FAILED],
JobStatus.DOWNLOADING_AUDIO: [JobStatus.DOWNLOADING, JobStatus.AWAITING_DURATION_CONFIRM, JobStatus.DOWNLOAD_PENDING_RETRY, JobStatus.FAILED],
# DOWNLOAD_PENDING_RETRY = parked when a torrent download hits a transient
# issue (few/no seeders, tracker outage); auto-retried by the recover-stuck
# cron for up to 24h before failing permanently.
JobStatus.DOWNLOAD_PENDING_RETRY: [JobStatus.DOWNLOADING_AUDIO, JobStatus.FAILED, JobStatus.CANCELLED],
# DOWNLOADING allows parallel processing (audio + lyrics) and then screens when both complete
# Can also enter optional audio edit phase if requires_audio_edit flag is set
+103 -7
View File
@@ -4,6 +4,7 @@ from __future__ import annotations
import hashlib
import json
import logging
import os
import time
import uuid
from dataclasses import asdict, dataclass, field
@@ -35,9 +36,63 @@ VALID_CATEGORIES = {
class AutoCorrectServiceError(Exception):
def __init__(self, message: str, *, status_code: int = 400) -> None:
def __init__(
self, message: str, *, status_code: int = 400, retryable: bool = False
) -> None:
super().__init__(message)
self.status_code = status_code
# True for transient provider conditions (rate limits, overload) the
# caller may safely retry; drives backoff in _call_model.
self.retryable = retryable
# Retry knobs for a single model call. Vertex 429 RESOURCE_EXHAUSTED is a
# recurring, transient condition; a short app-level backoff lets quota recover
# where the SDK's fast internal retry cannot. Kept small so a request never
# stalls the review UI for long. Parsed defensively: a malformed env override
# clamps to a safe value with a warning rather than crashing the backend at
# import or breaking the retry loop.
def _env_number(name: str, default: float, *, minimum: float, is_int: bool) -> float:
raw = os.environ.get(name)
if raw is None:
return default
try:
val: float = int(raw) if is_int else float(raw)
except ValueError:
logger.warning("invalid %s=%r; using default %s", name, raw, default)
return default
import math as _math
if not _math.isfinite(val) or val < minimum:
logger.warning(
"%s=%s out of range (min %s); clamping to %s", name, val, minimum, minimum
)
return minimum
return val
_MODEL_CALL_MAX_ATTEMPTS = int(
_env_number("AUTO_CORRECT_MODEL_MAX_ATTEMPTS", 3, minimum=1, is_int=True)
)
_MODEL_CALL_BACKOFF_SECONDS = float(
_env_number("AUTO_CORRECT_MODEL_BACKOFF_SECONDS", 2.0, minimum=0.0, is_int=False)
)
def _is_transient_model_error(exc: BaseException) -> bool:
"""True when a provider exception is a retryable rate-limit/overload.
Matches both structured status codes (google-genai ClientError/ServerError
expose ``code``; Anthropic errors expose ``status_code``) and, as a
fallback, the textual markers Vertex/Anthropic use — so detection survives
SDK exception-class churn.
"""
code = getattr(exc, "code", None) or getattr(exc, "status_code", None)
if isinstance(code, int) and code in {429, 500, 502, 503, 529}:
return True
text = str(exc).upper()
markers = ("RESOURCE_EXHAUSTED", "UNAVAILABLE", "OVERLOADED", "429", "503", "529")
return any(m in text for m in markers)
@dataclass
@@ -388,10 +443,33 @@ class AutoCorrectService:
def _call_model(
self, model: str, system_prompt: str, user_prompt: str, *, job_id: str
) -> tuple[Any, Optional[TokenUsage]]:
"""Return (parsed_json, token_usage). Usage is None if unreadable."""
if model.startswith("claude"):
return self._call_anthropic(model, system_prompt, user_prompt, job_id=job_id)
return self._call_gemini(model, system_prompt, user_prompt, job_id=job_id)
"""Return (parsed_json, token_usage). Usage is None if unreadable.
Transient provider errors (rate limits / overload, flagged
``retryable``) are retried with exponential backoff. Permanent errors
(misconfig, malformed output) fail fast.
"""
for attempt in range(1, _MODEL_CALL_MAX_ATTEMPTS + 1):
try:
if model.startswith("claude"):
return self._call_anthropic(
model, system_prompt, user_prompt, job_id=job_id
)
return self._call_gemini(
model, system_prompt, user_prompt, job_id=job_id
)
except AutoCorrectServiceError as exc:
if not exc.retryable or attempt == _MODEL_CALL_MAX_ATTEMPTS:
raise
backoff = _MODEL_CALL_BACKOFF_SECONDS * (2 ** (attempt - 1))
logger.warning(
"auto-correct model call transient failure job=%s model=%s "
"attempt=%d/%d; retrying in %.1fs (%s)",
job_id, model, attempt, _MODEL_CALL_MAX_ATTEMPTS, backoff, exc,
)
time.sleep(backoff)
# Unreachable: the loop either returns or raises on the final attempt.
raise AssertionError("retry loop exited without returning or raising")
@staticmethod
def _anthropic_usage(response: Any) -> Optional[TokenUsage]:
@@ -440,8 +518,6 @@ class AutoCorrectService:
def _call_anthropic(
self, model: str, system_prompt: str, user_prompt: str, *, job_id: str
) -> tuple[Any, Optional[TokenUsage]]:
import os
import anthropic
if not os.environ.get("ANTHROPIC_API_KEY"):
@@ -478,6 +554,16 @@ class AutoCorrectService:
output_config={"format": {"type": "json_schema", "schema": strict_schema}},
)
except Exception as exc:
if _is_transient_model_error(exc):
logger.warning(
"auto-correct model rate-limited/overloaded job=%s model=%s (%s)",
job_id, model, exc,
)
raise AutoCorrectServiceError(
"AI model is temporarily rate-limited",
status_code=429,
retryable=True,
) from exc
logger.exception("auto-correct model call failed job=%s model=%s", job_id, model)
raise AutoCorrectServiceError(
"AI model call failed", status_code=502
@@ -520,6 +606,16 @@ class AutoCorrectService:
),
)
except Exception as exc: # surface as 502, never a stuck job
if _is_transient_model_error(exc):
logger.warning(
"auto-correct model rate-limited/overloaded job=%s model=%s (%s)",
job_id, model, exc,
)
raise AutoCorrectServiceError(
"AI model is temporarily rate-limited",
status_code=429,
retryable=True,
) from exc
logger.exception("auto-correct model call failed job=%s model=%s", job_id, model)
raise AutoCorrectServiceError(
"AI model call failed", status_code=502
+3
View File
@@ -15,6 +15,9 @@ class StopReason(str, Enum):
MAX_ITERS_REACHED = "max_iters_reached"
LINE_COUNT_MISMATCH = "line_count_mismatch"
VERBATIM_SKIP = "verbatim_skip"
# A repair iteration failed (e.g. the model returned an empty/blocked
# response); we keep the best result found so far instead of failing.
REPAIR_FAILED = "repair_failed"
@dataclass
+45 -3
View File
@@ -247,11 +247,20 @@ class CustomLyricsService:
settings=settings,
)
except Exception:
logger.exception(
# Repair is a best-effort *improvement* step. If a repair call
# fails (e.g. the model returned an empty/blocked response, or a
# transient Vertex error), we must NOT throw away the successful
# initial result — that turned a working generation into a 500 and
# a browser "NetworkError". Keep the best candidate found so far.
# WARNING (not exception/ERROR): this is now a handled, non-fatal
# degradation, so it should not trip the production error monitor.
logger.warning(
"custom_lyrics_repair_call_failed",
exc_info=True,
extra={"job_id": job_id, "iteration": iter_num, "stage": "repair"},
)
raise
stop_reason = StopReason.REPAIR_FAILED
break
validations = self._validate_with_length_handling(
candidate_lines, target_lines, target_segments,
tolerance=params.tolerance, fixed=settings.fixed_line_count,
@@ -564,7 +573,40 @@ class CustomLyricsService:
},
),
)
return self._parse_lines(response.text)
# The model can return no text (safety block, MAX_TOKENS with no content,
# empty candidate). `response.text` is then None and json.loads(None) would
# raise a raw TypeError -> uncaught 500 without CORS headers -> the browser
# reports a confusing "NetworkError". Surface a clean, diagnosable error.
text = response.text
if text is None:
raise CustomLyricsServiceError(
f"The AI returned an empty response ({self._describe_empty_response(response)}). "
f"Please try again.",
status_code=502,
)
return self._parse_lines(text)
@staticmethod
def _describe_empty_response(response: Any) -> str:
"""Best-effort reason for an empty model response, for logs and messages."""
parts: list[str] = []
try:
block_reason = getattr(getattr(response, "prompt_feedback", None), "block_reason", None)
if block_reason:
parts.append(f"prompt_block={getattr(block_reason, 'name', block_reason)}")
except Exception: # pragma: no cover - defensive
pass
try:
candidates = getattr(response, "candidates", None) or []
if candidates:
finish = getattr(candidates[0], "finish_reason", None)
if finish is not None:
parts.append(f"finish_reason={getattr(finish, 'name', finish)}")
else:
parts.append("no_candidates")
except Exception: # pragma: no cover - defensive
pass
return ", ".join(parts) if parts else "unknown"
@staticmethod
def _parse_lines(text: str) -> list[str]:
+7 -2
View File
@@ -1705,8 +1705,13 @@ class EmailService:
# Use "ET" (Eastern Time) to be correct for both EST and EDT
deadline_str = deadline_eastern.strftime("%B %d, %Y at %I:%M %p") + " ET"
# Link to /app/ with admin login token for one-click access
app_url = f"{self.frontend_url.rstrip('/')}/app/?admin_token={admin_login_token}"
# Link to /app/ with admin login token for one-click access, deep-linked to the
# awaiting-audio-selection queue so the made-for-you order is shown immediately
# (made-for-you cards render there; the status param pre-selects the filter).
app_url = (
f"{self.frontend_url.rstrip('/')}/app/"
f"?admin_token={admin_login_token}&status=awaiting_audio_selection"
)
content = f"""
<div class="order-info">
+73 -2
View File
@@ -27,6 +27,7 @@ Usage:
import asyncio
import logging
import time
from dataclasses import dataclass
from datetime import datetime, UTC
from typing import Any, Optional
@@ -48,7 +49,35 @@ logger = logging.getLogger(__name__)
# or returned an immediate error like ZONE_RESOURCE_POOL_EXHAUSTED.
START_OPERATION_TIMEOUT_SECONDS = 30.0
# A GCE instances.start returning 503 SERVICE_UNAVAILABLE (or 500/INTERNAL) is a
# transient GCP control-plane error — distinct from a capacity STOCKOUT — and
# usually succeeds on a quick retry. Retry the start a few times in-zone with
# backoff before letting the caller fail over to another zone.
START_TRANSIENT_MAX_RETRIES = 3
START_TRANSIENT_BACKOFF_SECONDS = 5.0
# Substrings (matched case-insensitively against the GCE error code/message)
# that mark a retryable transient control-plane failure.
_TRANSIENT_START_MARKERS = (
"503",
"service unavailable",
"internal error",
"internalerror",
"backenderror",
"500",
)
CONFIG_COLLECTION = "config"
def _is_transient_start_error(error: "EncodingWorkerStartError") -> bool:
"""True if a VM-start failure looks like a retryable transient GCP error.
Capacity errors (ZONE_RESOURCE_POOL_EXHAUSTED etc.) are NOT transient in the
same zone — retrying in-zone is pointless, the caller should fail over. Those
are a distinct subclass and are excluded by the caller.
"""
haystack = f"{getattr(error, 'code', '') or ''} {error}".lower()
return any(marker in haystack for marker in _TRANSIENT_START_MARKERS)
CONFIG_DOCUMENT = "encoding-worker"
ENCODING_WORKER_PORT = 8080
@@ -322,6 +351,38 @@ class EncodingWorkerManager:
}
def ensure_any_running(self, candidates: list) -> dict:
"""Start any candidate VM; retry the whole set on an all-zones transient blip.
Delegates to :meth:`_ensure_any_running_once` (one attempt per candidate).
If EVERY candidate fails with a *transient* error — e.g. a brief 503
SERVICE_UNAVAILABLE control-plane blip that hits all zones at once — and
none hit real capacity exhaustion, retry the whole candidate set a few
times with backoff before giving up. Capacity exhaustion is NOT spun on
here (retrying in seconds won't conjure hardware); the render worker parks
the job and the 24h auto-retry cron handles a sustained shortage.
"""
if not candidates:
raise ValueError("ensure_any_running requires at least one candidate")
attempt = 0
while True:
attempt += 1
try:
return self._ensure_any_running_once(candidates)
except EncodingWorkerCapacityError:
raise
except EncodingWorkerStartError as e:
if attempt <= START_TRANSIENT_MAX_RETRIES and _is_transient_start_error(e):
backoff = START_TRANSIENT_BACKOFF_SECONDS * attempt
logger.warning(
"All encoding candidates failed transiently (pass %d/%d): %s — "
"retrying whole set in %.0fs",
attempt, START_TRANSIENT_MAX_RETRIES + 1, e, backoff,
)
time.sleep(backoff)
continue
raise
def _ensure_any_running_once(self, candidates: list) -> dict:
"""Start the first candidate VM that GCE accepts; raise if all are exhausted.
Iterates `candidates` in order, attempting to start each one. A
@@ -359,6 +420,7 @@ class EncodingWorkerManager:
# capacity exhaustion (transient, retry on a different VM/zone helps).
last_capacity_error: Optional[EncodingWorkerCapacityError] = None
last_start_error: Optional[EncodingWorkerStartError] = None
last_non_transient_error: Optional[EncodingWorkerStartError] = None
for index, candidate in enumerate(candidates):
try:
status = self.get_vm_status(candidate.vm_name, zone=candidate.zone)
@@ -405,12 +467,21 @@ class EncodingWorkerManager:
candidate.vm_name, candidate.zone, start_err.code or "no-code",
)
last_start_error = start_err
if not _is_transient_start_error(start_err):
last_non_transient_error = start_err
continue
# Every candidate failed. Prefer raising the capacity error if any
# candidate hit one (more actionable for the caller / user message).
# Every candidate failed. Raise the most actionable / least-retryable
# representative error so the caller (ensure_any_running) retries the
# whole set ONLY when every failure was a transient blip:
# capacity > non-transient start error > transient start error
# A capacity error means a real shortage (park + 24h retry handles it);
# a non-transient error (e.g. PERMISSION_DENIED) means something is
# actually broken — neither should trigger the fast whole-set retry.
if last_capacity_error is not None:
raise last_capacity_error
if last_non_transient_error is not None:
raise last_non_transient_error
assert last_start_error is not None
raise last_start_error
@@ -6,6 +6,7 @@ Cloud Run Job handle all alerting / Discord plumbing.
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from datetime import datetime, timezone
from urllib.parse import urlsplit, urlunsplit
@@ -19,6 +20,35 @@ from backend.services.error_monitor.normalizer import (
MAX_SAMPLE_MESSAGE_CHARS = 4000
MAX_URL_CHARS = 512
# Crawlers/bots execute our JS (e.g. bingbot/Googlebot run headless Chrome) and
# trip React DOM-reconciliation errors that no real user ever sees. Their reports
# are pure alert-channel noise, so we drop them at ingestion. Matches the common
# crawler tokens plus the generic bot/crawler/spider/headless markers that
# well-behaved automated agents put in their UA string.
_BOT_UA_RE = re.compile(
# Generic markers. The bot forms are anchored so we never match the "bot"
# inside ordinary words like "robot": a standalone "bot" token (\bbot\b does
# not match inside "robot" — no word boundary there) or the crawler
# "<name>bot/<version>" convention, with "robot/" explicitly excluded.
r"\bbot\b|(?<!ro)bot/|spider|crawler|crawl\b|slurp|bingpreview|headless|"
# Explicit crawler names (some don't use the "/version" convention).
r"googlebot|bingbot|applebot|yandex|baiduspider|duckduckbot|"
r"ahrefs|semrush|petalbot|facebookexternalhit|"
r"chrome-lighthouse|google page speed|python-requests|curl/|wget/",
re.IGNORECASE,
)
def is_bot_user_agent(user_agent: str | None) -> bool:
"""Return True if the UA looks like a crawler/bot/automated agent.
Conservative: only matches explicit bot markers, so a real browser UA (which
never contains these tokens) is never misclassified.
"""
if not user_agent:
return False
return bool(_BOT_UA_RE.search(user_agent))
@dataclass
class FrontendErrorReport:
@@ -56,6 +56,33 @@ _IGNORE_PATTERNS: list[tuple[str, re.Pattern, str]] = [
re.compile(r"stopping idle encoding worker", re.IGNORECASE),
"Encoding worker idle shutdown — expected behaviour when no jobs are queued",
),
(
"encoding_worker_capacity_retry",
# Only the TRANSIENT start failures: GCE 503/SERVICE UNAVAILABLE or a
# capacity code (ZONE_RESOURCE_POOL_EXHAUSTED / STOCKOUT / QUOTA_EXCEEDED
# — see encoding_errors.CAPACITY_ERROR_CODES). The render worker parks
# these for auto-retry. A non-transient EncodingWorkerStartError (other /
# unknown code) shares the "aborting retries" prefix but must still page,
# so we require the transient signal, not just the prefix.
# Bind the transient signal to the GCE error CODE field — which appears
# immediately after "start failed in <zone>: " / "could not be started in
# <zone>: " (see encoding_errors.classify_gce_error). Matching the code in
# position (not anywhere in the line) prevents a non-transient failure
# whose message text merely contains "503" from being suppressed.
re.compile(
r"encoding worker start failed, aborting retries:.*?"
r"(?:start failed|could not be started) in [\w.-]+:\s*"
r"(?:503\b|service unavailable|zone_resource_pool_exhausted"
r"|stockout|quota_exceeded)",
re.IGNORECASE,
),
(
"GCE encoding worker VM start hit a transient GCP condition (zone "
"capacity exhaustion or 503 SERVICE UNAVAILABLE) — the render worker "
"parks the job for auto-retry rather than failing it. Non-transient "
"start failures still alert."
),
),
(
"health_check_404",
re.compile(
@@ -79,6 +79,15 @@ _NORMALIZERS: list[tuple[re.Pattern, str]] = [
re.compile(r"/jobs/[A-Za-z0-9]+"),
"/jobs/<ID>",
),
# 9b. Preview render job IDs: preview_<jobid>_<renderid> (underscore-joined
# hex runs). The generic hex rule (11) is \b-anchored and '_' is a word
# char, so it can't reach these — leaving every preview render of the
# same job as a distinct pattern (N alerts for one incident). Collapse
# the whole token so they map to a single pattern.
(
re.compile(r"\bpreview_[0-9a-fA-F]{6,}(?:_[0-9a-fA-F]{6,})+\b"),
"preview_<ID>",
),
# 10. Firebase UIDs (20–28 mixed-case alphanumeric characters)
# Firebase Auth UIDs are typically 28 chars; allow 20-28 for flexibility.
# Must contain both letters and digits (to avoid replacing plain words).
+1
View File
@@ -198,6 +198,7 @@ class FirestoreService:
SUMMARY_FIELD_PATHS = [
'job_id', 'status', 'progress', 'created_at', 'artist', 'title',
'error_message', 'non_interactive', 'outputs_deleted_at', 'user_email', 'is_private',
'made_for_you', 'customer_email',
'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',
+158 -36
View File
@@ -266,6 +266,7 @@ class GoogleDriveService:
brand_code: str,
base_name: str,
output_files: dict,
warnings: Optional[list] = None,
) -> Dict[str, str]:
"""
Upload final files to public share folder structure.
@@ -322,6 +323,30 @@ class GoogleDriveService:
uploaded_files["mp4_720p"] = file_id
logger.info(f"Uploaded 720p MP4 to MP4-720p/ folder")
# Fast-sync the 720p master straight to the Divebar GCS mirror so kjbox
# (which mirrors that folder every 5 min) picks it up within minutes,
# instead of waiting for the nightly Drive->GCS VM. Nomad-brand only,
# best-effort, never fatal to the Drive upload. A failure is surfaced as
# a distribution warning (drives the admin alert) so this can't silently
# rot into "nightly VM only" — the nightly VM stays the backfill net.
fast_sync_warning = self._fast_sync_nomad_master(
brand_code, mp4_720p_path, f"{filename_base}.mp4"
)
if fast_sync_warning and warnings is not None:
warnings.append(fast_sync_warning)
# Push the padded original-vocals guide (silence[intro] + mixed_vocals) to the
# vocals prefix in the same Divebar mirror, so kjbox can layer it under the master
# at the "Original Vocals" slider. Same Nomad-brand gating + best-effort contract
# as the 720p push; the guide was pre-built by the orchestrator when available.
guide_path = output_files.get("original_vocals_guide")
if guide_path and os.path.exists(guide_path):
guide_warning = self._fast_sync_vocals_guide(
brand_code, guide_path, f"{filename_base}.flac"
)
if guide_warning and warnings is not None:
warnings.append(guide_warning)
# Upload CDG ZIP to CDG/
cdg_zip_path = output_files.get("final_karaoke_cdg_zip")
if cdg_zip_path and os.path.exists(cdg_zip_path):
@@ -337,6 +362,74 @@ class GoogleDriveService:
logger.info(f"Public share upload complete: {len(uploaded_files)} files uploaded")
return uploaded_files
def _fast_sync_nomad_master(
self, brand_code: str, local_720p_path: str, filename: str
) -> Optional[str]:
"""Best-effort push of a freshly-published Nomad 720p master to the Divebar
GCS mirror so kjbox picks it up within minutes (vs the nightly VM).
No-op unless the fast-sync is enabled and this is a public Nomad release
(``NOMAD-####``, excluding ``NOMADNP`` private tracks). Never raises — the
Drive upload has already succeeded and the nightly VM is the backfill net.
Returns a human-readable warning string on failure (so the caller can surface
it via ``distribution_warnings`` / the admin alert), or ``None`` on
success or when skipped.
"""
try:
from backend.config import settings
from backend.services.nomad_master_mirror import (
NomadMasterMirror,
is_nomad_public_brand,
)
if not settings.nomad_master_fast_sync_enabled:
return None
if not is_nomad_public_brand(brand_code):
return None
if NomadMasterMirror().push_720p(local_720p_path, filename):
return None
return (
f"Nomad master fast-sync to the GCS mirror failed for {filename} "
f"(the nightly Drive->GCS VM will backfill it)"
)
except Exception as e: # noqa: BLE001 - never fatal to the pipeline
logger.warning(f"Nomad master fast-sync skipped (unexpected error): {e}")
return f"Nomad master fast-sync errored for {filename}: {e}"
def _fast_sync_vocals_guide(
self, brand_code: str, local_path: str, filename: str
) -> Optional[str]:
"""Best-effort push of a freshly-built original-vocals guide to the Divebar GCS
mirror's vocals prefix so kjbox can pull it into ``NOMAD-vocals-padded/``.
No-op unless the fast-sync is enabled and this is a public Nomad release
(``NOMAD-####``, excluding ``NOMADNP``). Never raises — nothing downstream
depends on the guide. Returns a human-readable warning on failure (surfaced via
``distribution_warnings`` / the admin alert), or ``None`` on success or skip.
"""
try:
from backend.config import settings
from backend.services.nomad_master_mirror import (
NomadMasterMirror,
is_nomad_public_brand,
)
if not settings.nomad_master_fast_sync_enabled:
return None
if not is_nomad_public_brand(brand_code):
return None
if NomadMasterMirror().push_vocals_guide(local_path, filename):
return None
return (
f"Original-vocals guide sync to the GCS mirror failed for {filename}"
)
except Exception as e: # noqa: BLE001 - never fatal to the pipeline
logger.warning(f"Original-vocals guide sync skipped (unexpected error): {e}")
return f"Original-vocals guide sync errored for {filename}: {e}"
def delete_file(self, file_id: str) -> bool:
"""
Delete a file from Google Drive.
@@ -387,6 +480,69 @@ class GoogleDriveService:
results[file_id] = self.delete_file(file_id)
return results
def _search_subfolder_for_brand(
self, root_folder_id: str, subfolder: str, brand_code: str
) -> list[str]:
"""Return file IDs in ``subfolder`` whose name starts with ``{brand_code} - ``.
Read-only Drive lookups, wrapped in retry-with-backoff so transient
connection drops (SSL EOF / BrokenPipe against idle Cloud Run containers)
self-heal instead of surfacing as "GDrive brand_code search incomplete".
Non-transient errors reraise immediately for the caller to record.
"""
def _do_search() -> list[str]:
ids: list[str] = []
# Find the subfolder
escaped_subfolder = subfolder.replace("'", "\\'")
query = (
f"name='{escaped_subfolder}' and '{root_folder_id}' in parents "
f"and mimeType='application/vnd.google-apps.folder' and trashed=false"
)
results = self.service.files().list(
q=query, fields="files(id, name)", supportsAllDrives=True,
includeItemsFromAllDrives=True
).execute()
if not results.get("files"):
logger.debug(f"Subfolder '{subfolder}' not found in {root_folder_id}")
return ids
subfolder_id = results["files"][0]["id"]
# Search for files whose name starts with the brand code
# Use contains for efficiency, then filter by exact prefix
escaped_brand = brand_code.replace("'", "\\'")
file_query = (
f"name contains '{escaped_brand}' and '{subfolder_id}' in parents "
f"and trashed=false"
)
file_results = self.service.files().list(
q=file_query, fields="files(id, name)", supportsAllDrives=True,
includeItemsFromAllDrives=True
).execute()
for f in file_results.get("files", []):
if f["name"].startswith(f"{brand_code} - "):
ids.append(f["id"])
logger.info(
f"Found GDrive file to clean up in {subfolder}/: "
f"{f['name']} ({f['id']})"
)
return ids
for attempt in Retrying(
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=1, min=2, max=8),
retry=retry_if_exception_type(TRANSIENT_ERRORS),
before_sleep=lambda retry_state: self._reset_service(),
reraise=True,
):
with attempt:
return _do_search()
return [] # pragma: no cover - Retrying always returns or raises
def find_files_by_brand_code(self, root_folder_id: str, brand_code: str) -> list[str]:
"""
Search for files in public share subfolders matching a brand code prefix.
@@ -411,43 +567,9 @@ class GoogleDriveService:
for subfolder in subfolders:
try:
# Find the subfolder
escaped_subfolder = subfolder.replace("'", "\\'")
query = (
f"name='{escaped_subfolder}' and '{root_folder_id}' in parents "
f"and mimeType='application/vnd.google-apps.folder' and trashed=false"
found_ids.extend(
self._search_subfolder_for_brand(root_folder_id, subfolder, brand_code)
)
results = self.service.files().list(
q=query, fields="files(id, name)", supportsAllDrives=True,
includeItemsFromAllDrives=True
).execute()
if not results.get("files"):
logger.debug(f"Subfolder '{subfolder}' not found in {root_folder_id}")
continue
subfolder_id = results["files"][0]["id"]
# Search for files whose name starts with the brand code
# Use contains for efficiency, then filter by exact prefix
escaped_brand = brand_code.replace("'", "\\'")
file_query = (
f"name contains '{escaped_brand}' and '{subfolder_id}' in parents "
f"and trashed=false"
)
file_results = self.service.files().list(
q=file_query, fields="files(id, name)", supportsAllDrives=True,
includeItemsFromAllDrives=True
).execute()
for f in file_results.get("files", []):
if f["name"].startswith(f"{brand_code} - "):
found_ids.append(f["id"])
logger.info(
f"Found GDrive file to clean up in {subfolder}/: "
f"{f['name']} ({f['id']})"
)
except Exception as e:
logger.error(
f"Error searching for brand_code '{brand_code}' in '{subfolder}': {e}",
+27
View File
@@ -16,6 +16,15 @@ from backend.models.job import Job, JobStatus
logger = logging.getLogger(__name__)
# A render that started (status=rendering_video) but whose worker died mid-way
# (Cloud Run instance recycle / SIGKILL / lost GCE VM) stops advancing
# updated_at. The render worker's own timeout is ~1h, so if a job sits here far
# longer than that with no update, no live worker is driving it — it's orphaned
# and must be re-parked for retry. Kept above the worst-case gap between render
# progress callbacks to avoid re-parking a slow-but-alive render.
RENDERING_VIDEO_STUCK_MINUTES = 45
# Jobs in these statuses should NOT have audio_complete flag set
# (unless they're actively processing or beyond)
STATUSES_BEFORE_AUDIO_START = {
@@ -141,6 +150,24 @@ def check_job_consistency(job: Job) -> List[str]:
f"downloading_audio_stuck: status=downloading_audio for {minutes} min without update (updated_at={updated_at.isoformat()})"
)
# Check: job stuck in rendering_video status with no progress.
# If the render worker died mid-render (hard kill / lost VM), updated_at
# stops advancing and NO existing mechanism recovers it: the capacity-retry
# cron only looks at render_pending_capacity, recover-stuck-jobs only looked
# at downloading_audio, and the render Cloud Task has finite attempts. This
# detects that orphan so the recovery sweep can re-park it for auto-retry.
if status == JobStatus.RENDERING_VIDEO and job.updated_at:
now = datetime.now(timezone.utc)
updated_at = job.updated_at
if updated_at.tzinfo is None:
updated_at = updated_at.replace(tzinfo=timezone.utc)
render_age = now - updated_at
if render_age > timedelta(minutes=RENDERING_VIDEO_STUCK_MINUTES):
minutes = int(render_age.total_seconds() / 60)
issues.append(
f"rendering_video_stuck: status=rendering_video for {minutes} min without update (updated_at={updated_at.isoformat()})"
)
return issues
+28
View File
@@ -786,6 +786,34 @@ class JobManager:
self.update_job(job_id, {'state_data': state_data})
logger.debug(f"Job {job_id} state_data updated: {key} = {value}")
def bump_worker_generation(self, job_id: str) -> Optional[int]:
"""
Atomically increment the ``state_data.worker_generation`` fence.
Every trigger of a long-running render/video worker bumps this counter.
A worker captures the value at start; if it later differs, a newer run
has superseded it and its (now stale) result must be discarded rather
than written back or used to fail the job. See
:mod:`backend.workers.supersede`.
Returns the new generation, or ``None`` if the update failed (best-effort
— a failed bump must never block triggering the worker).
"""
try:
from google.cloud.firestore_v1 import Increment
self.firestore.update_job(job_id, {
'state_data.worker_generation': Increment(1),
})
job = self.get_job(job_id)
new_generation = (job.state_data or {}).get('worker_generation') if job else None
logger.info(f"Job {job_id}: bumped worker_generation to {new_generation}")
return new_generation
except Exception as e:
# Never let a fence bump block worker dispatch — the status fence
# (Layer A) still protects against the reset race on its own.
logger.warning(f"Job {job_id}: failed to bump worker_generation: {e}")
return None
def update_processing_metadata(self, job_id: str, section: str, data) -> None:
"""
Write data into processing_metadata[section] using Firestore dot-notation.
+186
View File
@@ -0,0 +1,186 @@
"""
Fast-path mirror of freshly-published Nomad masters into the Divebar GCS bucket.
New Nomad releases are uploaded to Google Drive at finalize time, but the Drive->GCS
byte-sync VM only runs nightly, so kjbox (which mirrors that GCS folder every 5 min)
would otherwise wait up to ~24h for a new master. This pushes the 720p master straight
to the exact GCS object the nightly VM would produce, so kjbox picks it up within minutes.
Idempotent with the nightly VM: identical object name + size means its additive
`gcloud storage rsync` sees the file already present and skips it.
Scoped to public Nomad Karaoke masters only (brand prefix ``NOMAD``, excluding the
``NOMADNP`` private-track prefix). Every operation is best-effort / non-fatal: a failure
here must never break the distribution pipeline — the nightly VM remains the safety net.
"""
import logging
from typing import Optional
from google.cloud import storage
from google.cloud.exceptions import NotFound
from backend.config import settings
logger = logging.getLogger(__name__)
def is_nomad_public_brand(brand_code: Optional[str]) -> bool:
"""True only for public Nomad releases (``NOMAD-####``), not ``NOMADNP`` privates."""
if not brand_code:
return False
prefix = brand_code.split("-", 1)[0].strip().upper()
return prefix == "NOMAD"
class NomadMasterMirror:
"""Push/remove Nomad 720p masters in the Divebar GCS bucket that kjbox mirrors."""
def __init__(self, client: Optional[storage.Client] = None):
self._client = client or storage.Client(project=settings.google_cloud_project)
self._bucket = self._client.bucket(settings.divebar_files_bucket)
def _blob_name(self, filename: str) -> str:
prefix = settings.nomad_master_gcs_prefix.strip("/")
return f"{prefix}/{filename}"
def _vocals_blob_name(self, filename: str) -> str:
prefix = settings.nomad_vocals_guide_gcs_prefix.strip("/")
return f"{prefix}/{filename}"
def push_720p(self, local_path: str, filename: str) -> bool:
"""Upload a 720p master to the divebar GCS mirror. Best-effort; returns success."""
blob_name = self._blob_name(filename)
try:
blob = self._bucket.blob(blob_name)
blob.upload_from_filename(local_path)
logger.info(
"Fast-synced Nomad master to gs://%s/%s",
settings.divebar_files_bucket,
blob_name,
)
return True
except Exception as e: # noqa: BLE001 - never fatal to the pipeline
logger.warning("Nomad master fast-sync push failed for %s: %s", blob_name, e)
return False
def delete_720p(self, filename: str) -> bool:
"""Delete a 720p master from the mirror. Best-effort; 404 == already gone."""
blob_name = self._blob_name(filename)
try:
self._bucket.blob(blob_name).delete()
logger.info(
"Removed Nomad master from gs://%s/%s",
settings.divebar_files_bucket,
blob_name,
)
return True
except NotFound:
logger.debug("Nomad master already absent in mirror: %s", blob_name)
return False
except Exception as e: # noqa: BLE001 - never fatal to the pipeline
logger.warning("Nomad master mirror delete failed for %s: %s", blob_name, e)
return False
def push_vocals_guide(self, local_path: str, filename: str) -> bool:
"""Upload a padded original-vocals guide to the divebar GCS mirror's vocals
prefix (which kjbox pulls into ``NOMAD-vocals-padded/``). Best-effort."""
blob_name = self._vocals_blob_name(filename)
try:
blob = self._bucket.blob(blob_name)
blob.upload_from_filename(local_path)
logger.info(
"Pushed original-vocals guide to gs://%s/%s",
settings.divebar_files_bucket,
blob_name,
)
return True
except Exception as e: # noqa: BLE001 - never fatal to the pipeline
logger.warning("Vocals-guide push failed for %s: %s", blob_name, e)
return False
def delete_vocals_guides_by_brand(self, brand_code: str) -> int:
"""Delete ALL original-vocals guide objects for a Nomad release, matched by the
unique ``{brand_code} - `` filename prefix (covers renames). Best-effort; returns
the count deleted. Refuses a non-Nomad / bare brand code (same guardrail as the
master prefix-delete) so a broad prefix can never wipe unrelated objects."""
if not is_nomad_public_brand(brand_code):
return 0
suffix = brand_code.split("-", 1)[1] if "-" in brand_code else ""
if not suffix.strip():
return 0
prefix = f"{settings.nomad_vocals_guide_gcs_prefix.strip('/')}/{brand_code} - "
deleted = 0
try:
for blob in self._bucket.list_blobs(prefix=prefix):
try:
blob.delete()
deleted += 1
except Exception as e: # noqa: BLE001
logger.warning("Failed to delete vocals-guide object %s: %s", blob.name, e)
if deleted:
logger.info(
"Removed %d original-vocals guide object(s) from gs://%s/%s*",
deleted, settings.divebar_files_bucket, prefix,
)
except Exception as e: # noqa: BLE001 - never fatal to the pipeline
logger.warning("Vocals-guide mirror prefix-delete failed for %s: %s", prefix, e)
return deleted
def delete_masters_by_brand(self, brand_code: str) -> int:
"""Delete ALL 720p master objects for a Nomad release, matched by the unique
``{brand_code} - `` filename prefix.
Keying on the brand_code prefix (rather than a reconstructed title) covers
renames for free: every artist/title variant a release was ever published
under shares the same ``NOMAD-#### - `` prefix. Best-effort; returns the count
deleted. Refuses to run for a non-Nomad / empty brand code so a broad prefix
can never match unrelated objects.
"""
if not is_nomad_public_brand(brand_code):
return 0
# Require a full ``NOMAD-####`` code (non-empty suffix after the hyphen) so the
# delete prefix is always specific to one release — never a bare ``NOMAD``.
suffix = brand_code.split("-", 1)[1] if "-" in brand_code else ""
if not suffix.strip():
return 0
prefix = f"{settings.nomad_master_gcs_prefix.strip('/')}/{brand_code} - "
deleted = 0
try:
for blob in self._bucket.list_blobs(prefix=prefix):
try:
blob.delete()
deleted += 1
except Exception as e: # noqa: BLE001
logger.warning("Failed to delete mirror object %s: %s", blob.name, e)
if deleted:
logger.info(
"Removed %d Nomad master object(s) from gs://%s/%s*",
deleted, settings.divebar_files_bucket, prefix,
)
except Exception as e: # noqa: BLE001 - never fatal to the pipeline
logger.warning("Nomad master mirror prefix-delete failed for %s: %s", prefix, e)
return deleted
def cleanup_nomad_masters(brand_code: Optional[str]) -> int:
"""Best-effort removal of a Nomad release's 720p master(s) from the GCS mirror,
keyed by brand_code prefix (covers renames). No-op for non-Nomad / ``NOMADNP``
brands or when fast-sync is disabled. Never raises — a cleanup failure must not
break job delete/edit flows (the object just lingers until overwritten). Call this
wherever the pipeline deletes a job's Drive/Dropbox outputs.
"""
try:
if not settings.nomad_master_fast_sync_enabled:
return 0
if not is_nomad_public_brand(brand_code):
return 0
mirror = NomadMasterMirror()
deleted = mirror.delete_masters_by_brand(brand_code)
# A recycled brand must not keep serving its old original-vocals guide, so remove
# the GCS guide(s) too. (Note: with the device's additive-only vocals sync this
# won't auto-remove an already-downloaded device copy — a documented limitation.)
mirror.delete_vocals_guides_by_brand(brand_code)
return deleted
except Exception as e: # noqa: BLE001 - never fatal to the caller
logger.warning("Nomad master mirror cleanup skipped: %s", e)
return 0
+106
View File
@@ -0,0 +1,106 @@
"""Build the padded original-vocals guide that feeds kjbox's "Original Vocals" slider.
At render time karaoke-gen already has the isolated ``mixed_vocals`` stem (a byproduct
of making the karaoke instrumental) and knows the exact intro offset (the master is
``[silent title-card intro] + song + [tail]`` and the intro length is the job's style
``intro_video_duration``). So the guide is simply ``silence[intro] + vocals``, capped to
the master's duration — no cross-correlation, no human review, no alignment measurement.
This is byte-compatible with what the kjbox retro-fit ``pad_vocals.sh`` produced.
Every function here is best-effort: it returns ``None`` / ``0`` on any failure and never
raises, so a guide problem can never break the distribution pipeline.
"""
import logging
import os
import subprocess
from typing import Optional
logger = logging.getLogger(__name__)
def probe_duration(path: str, ffprobe_path: str = "ffprobe") -> Optional[float]:
"""Return a media file's duration in seconds, or ``None`` if it can't be measured."""
try:
if not path or not os.path.isfile(path):
return None
result = subprocess.run(
[
ffprobe_path, "-v", "error", "-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1", path,
],
capture_output=True, text=True, timeout=60,
)
if result.returncode != 0:
return None
return float(result.stdout.strip())
except Exception as e: # noqa: BLE001 - never fatal
logger.warning("Could not probe duration for %s: %s", path, e)
return None
def build_original_vocals_guide(
mixed_vocals_path: str,
intro_seconds: float,
dest_path: str,
master_duration: Optional[float] = None,
ffmpeg_path: str = "ffmpeg",
) -> Optional[str]:
"""Emit ``silence[intro] + mixed_vocals`` as a FLAC guide aligned to the master.
Args:
mixed_vocals_path: The isolated vocals stem (all vocals: lead + backing).
intro_seconds: The master's silent title-card length (job's ``intro_video_duration``).
dest_path: Where to write the guide (``.flac``).
master_duration: If given, the output is capped to this length (``-t``) so the
guide can never bleed past the master. Omit to leave the vocals' own length.
ffmpeg_path: ffmpeg binary.
Returns:
``dest_path`` on success, else ``None`` (missing input / ffmpeg failure). Never raises.
"""
try:
if not mixed_vocals_path or not os.path.isfile(mixed_vocals_path):
logger.warning("Vocals guide: missing mixed-vocals stem %s", mixed_vocals_path)
return None
if intro_seconds is None or intro_seconds < 0:
logger.warning("Vocals guide: invalid intro_seconds %r", intro_seconds)
return None
delay_ms = int(round(float(intro_seconds) * 1000))
os.makedirs(os.path.dirname(dest_path) or ".", exist_ok=True)
tmp_path = dest_path + ".part"
cmd = [
ffmpeg_path, "-y", "-hide_banner", "-nostats", "-loglevel", "error",
"-i", mixed_vocals_path,
"-af", f"adelay={delay_ms}:all=1",
]
if master_duration and master_duration > 0:
cmd += ["-t", f"{float(master_duration):.3f}"]
# ``-f flac`` is mandatory: the ``.part`` extension would otherwise make the
# muxer guess the container from the extension and fail.
cmd += ["-c:a", "flac", "-f", "flac", tmp_path]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=600)
if result.returncode != 0 or not os.path.isfile(tmp_path):
logger.warning(
"Vocals guide: ffmpeg failed (rc=%s) for %s: %s",
result.returncode, mixed_vocals_path, (result.stderr or "")[-200:].strip(),
)
_quiet_remove(tmp_path)
return None
os.replace(tmp_path, dest_path)
logger.info("Built original-vocals guide: %s", dest_path)
return dest_path
except Exception as e: # noqa: BLE001 - never fatal to the pipeline
logger.warning("Vocals guide build failed for %s: %s", mixed_vocals_path, e)
_quiet_remove(dest_path + ".part")
return None
def _quiet_remove(path: str) -> None:
try:
os.remove(path)
except OSError:
pass
@@ -0,0 +1,2 @@
"""Batch karaoke-filename → {artist, title, confidence} parser (Vertex Gemini)."""
from backend.services.parse_titles.service import parse_titles # noqa: F401
+148
View File
@@ -0,0 +1,148 @@
"""Vertex-Gemini layer for batch karaoke-filename parsing.
Turns messy karaoke *filenames* (YouTube titles, community/producer naming,
KaraFun-reversed order) into canonical {artist, title, confidence}. Distinct
from match_judge (which judges an already-split artist/title). The model call
is injectable for tests.
"""
from __future__ import annotations
import asyncio
import copy
import json
import logging
from typing import Awaitable, Callable, Optional
logger = logging.getLogger(__name__)
Generate = Callable[[str, str, str], Awaitable[dict]]
_SYSTEM_PROMPT = (
"You extract canonical song metadata from karaoke video/file names for a "
"karaoke library. Each item has an id and a filename (sometimes a channel or "
"source). Filenames are noisy: they carry karaoke markers ('(Karaoke Version)', "
"'KARAOKE', '[karaoke]', 'Instrumental', producer/brand tags), YouTube ids or "
"channel names, and inconsistent separators. Crucially the artist/title ORDER "
"is inconsistent — most are 'Artist - Title' but some sources (e.g. KaraFun) are "
"'Title - Artist'. Use your knowledge of real songs to put artist and title in "
"the correct fields.\n"
"Return JSON: {\"results\": [{\"id\", \"artist\", \"title\", \"confidence\"}]}. "
"Return exactly one result per input id, echoing the id verbatim.\n"
"artist/title: official formatting, karaoke noise removed, no brand codes or "
"YouTube ids. If you cannot identify one field, return it as an empty string.\n"
"confidence: 0.0-1.0 — your certainty the artist/title (and their order) are "
"correct. Be honest; low confidence for ambiguous or unknown songs. Never invent "
"a song; if unsure, return best-effort split with low confidence."
)
RESPONSE_SCHEMA = {
"type": "object",
"properties": {
"results": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {"type": "string"},
"artist": {"type": "string"},
"title": {"type": "string"},
"confidence": {"type": "number"},
},
"required": ["id"],
},
}
},
"required": ["results"],
}
def _model() -> str:
try:
from backend.config import settings
return getattr(settings, "parse_titles_model", "gemini-3.5-flash")
except Exception: # pragma: no cover - config guard
return "gemini-3.5-flash"
def build_prompts(items: list[dict]) -> tuple[str, str]:
lines = ["Parse these karaoke filenames:"]
for it in items:
parts = [f'id={it.get("id")!r}', f'filename={it.get("filename", "")!r}']
if it.get("channel"):
parts.append(f'channel={it["channel"]!r}')
if it.get("source"):
parts.append(f'source={it["source"]!r}')
lines.append("- " + " ".join(parts))
return _SYSTEM_PROMPT, "\n".join(lines)
def _clean(v) -> str:
return (v or "").strip() if isinstance(v, str) else ""
def _conf(v) -> float:
try:
f = float(v)
except (TypeError, ValueError):
return 0.0
return max(0.0, min(1.0, f))
def parse_map_from_response(data: object, items: list[dict]) -> list[dict]:
"""Return one id-aligned result per input, filling any misses with blanks."""
by_id: dict[str, dict] = {}
if isinstance(data, dict):
for r in data.get("results") or []:
if isinstance(r, dict) and r.get("id") is not None:
by_id[str(r["id"])] = r
out = []
for it in items:
rid = str(it.get("id"))
r = by_id.get(rid, {})
out.append({
"id": rid,
"artist": _clean(r.get("artist")),
"title": _clean(r.get("title")),
"confidence": _conf(r.get("confidence")),
})
return out
async def ai_parse(
items: list[dict], *, model: Optional[str] = None,
generate: Optional[Generate] = None,
) -> list[dict]:
gen = generate or _default_generate
system, user = build_prompts(items)
data = await gen(model or _model(), system, user)
return parse_map_from_response(data, items)
async def _default_generate(model: str, system: str, user: str) -> dict:
return await asyncio.to_thread(_blocking_generate, model, system, user)
def _blocking_generate(model: str, system: str, user: str) -> dict:
from google import genai
from google.genai import types
from backend.config import settings
timeout_ms = int(getattr(settings, "parse_titles_timeout_ms", 20000))
client = genai.Client(
vertexai=True,
project=settings.google_cloud_project,
location="global",
http_options=types.HttpOptions(timeout=timeout_ms),
)
response = client.models.generate_content(
model=model,
contents=[user],
config=types.GenerateContentConfig(
system_instruction=system,
response_mime_type="application/json",
response_schema=copy.deepcopy(RESPONSE_SCHEMA),
temperature=0,
),
)
return json.loads(response.text)
+68
View File
@@ -0,0 +1,68 @@
"""Batch orchestration + graceful degrade for karaoke-filename parsing."""
from __future__ import annotations
import asyncio
import logging
from backend.services.parse_titles import ai
logger = logging.getLogger(__name__)
def _blanks(items: list[dict]) -> list[dict]:
return [
{"id": str(it.get("id")), "artist": "", "title": "", "confidence": 0.0}
for it in items
]
async def parse_titles(
items: list[dict], *, model=None, generate=None
) -> list[dict]:
"""Parse a batch of filenames → id-aligned {id, artist, title, confidence}.
Large batches are split into concurrent chunks of parse_titles_chunk_size
so a single Gemini call never outgrows parse_titles_timeout_ms (a 100-item
single call did, and the timeout blanked the whole batch).
Never raises: a disabled kill-switch or any model failure yields blank
results — per chunk, so one bad chunk doesn't blank its neighbours — and
the (kjbox) caller keeps its deterministic guess.
"""
if not items:
return []
try:
from backend.config import settings
enabled = getattr(settings, "parse_titles_enabled", True)
max_items = int(getattr(settings, "parse_titles_max_items", 200))
chunk_size = max(1, int(getattr(settings, "parse_titles_chunk_size", 10)))
except Exception: # pragma: no cover
# Fail closed: if config can't load, don't reach for the external AI.
logger.warning("parse_titles settings unavailable; disabling parser")
enabled, max_items, chunk_size = False, 200, 10
if not enabled:
return _blanks(items)
head, tail = items[:max_items], items[max_items:]
chunks = [head[i:i + chunk_size] for i in range(0, len(head), chunk_size)]
parsed = await asyncio.gather(
*(_parse_chunk(chunk, model=model, generate=generate) for chunk in chunks)
)
return [r for chunk_results in parsed for r in chunk_results] + _blanks(tail)
async def _parse_chunk(chunk: list[dict], *, model, generate) -> list[dict]:
"""One Gemini call; any failure degrades to blanks for this chunk only."""
try:
results = await ai.ai_parse(chunk, model=model, generate=generate)
except Exception as exc:
logger.warning(
"parse_titles chunk degraded (%s); blanks for %d items", exc, len(chunk))
return _blanks(chunk)
# ai_parse is id-aligned by construction; guard the contract defensively so a
# future refactor can't silently return a mis-aligned/short batch.
if len(results) != len(chunk):
logger.warning(
"parse_titles chunk length mismatch; blanks for %d items", len(chunk))
return _blanks(chunk)
return results
+30
View File
@@ -373,6 +373,36 @@ class UserService:
logger.exception("Error verifying magic link")
return False, None, "An error occurred during verification"
def get_magic_link_status(self, token: str) -> str:
"""
Read-only check of a magic link's status WITHOUT consuming it.
Used by the verify page on load to decide whether to show the
"Complete Sign-In" gate (valid) or a dead-link message (used/expired).
Crucially this must never mutate the token: an email link-scanner that
renders the verify page triggers this read, but must not burn a still-
valid link before the real user clicks.
Returns one of: "valid", "used", "expired", "invalid".
"""
try:
if not token or not token.strip():
return "invalid"
doc = self.db.collection(MAGIC_LINKS_COLLECTION).document(token).get()
if not doc.exists:
return "invalid"
magic_link = MagicLinkToken(**doc.to_dict())
if magic_link.used:
return "used"
if datetime.utcnow() > magic_link.expires_at:
return "expired"
return "valid"
except Exception:
logger.exception("Error checking magic link status")
return "invalid"
def grant_welcome_credits_if_eligible(
self,
email: str,
@@ -269,6 +269,12 @@ class VisibilityChangeService:
except Exception as e:
logger.warning(f"[job:{job_id}] Failed to delete Google Drive files: {e}")
# A track going private should also leave the public Nomad GCS fast-sync mirror
# (and thus kjbox). Prefix-keyed by brand_code, non-fatal, Nomad-only.
if brand_code:
from backend.services.nomad_master_mirror import cleanup_nomad_masters
cleanup_nomad_masters(brand_code)
# Delete GCS finals if requested
if not keep_gcs_finals:
try:
+19
View File
@@ -513,6 +513,7 @@ class WorkerService:
uses Cloud Run Jobs for execution (supports >30 min encoding).
Otherwise, uses Cloud Tasks or direct HTTP.
"""
self._bump_worker_generation(job_id)
self._warmup_encoding_worker(job_id)
if self._use_cloud_tasks and self.settings.use_cloud_run_jobs_for_video:
return await self._trigger_cloud_run_job(job_id)
@@ -606,9 +607,27 @@ class WorkerService:
async def trigger_render_video_worker(self, job_id: str) -> bool:
"""Trigger render video worker (post-review)."""
self._bump_worker_generation(job_id)
self._warmup_encoding_worker(job_id)
return await self.trigger_worker("render-video", job_id)
def _bump_worker_generation(self, job_id: str) -> None:
"""
Advance the supersession fence before dispatching a render/video worker.
Bumping here (the single choke point for both workers) means every run
captures a unique generation at start. If an older run of the same stage
is still in flight — because an admin reset then re-triggered the job —
it will observe the newer generation and discard its stale result
instead of overwriting fresh outputs or failing the job. Best-effort:
a failed bump is logged and ignored (the status fence still applies).
"""
try:
from backend.services.job_manager import JobManager
JobManager().bump_worker_generation(job_id)
except Exception as e:
logger.warning(f"[job:{job_id}] Failed to bump worker generation before trigger: {e}")
async def schedule_idle_reminder(
self,
job_id: str,
+12
View File
@@ -55,6 +55,18 @@ def test_accepts_valid_report_and_upserts(client):
assert pd.resource_type == "browser"
def test_bot_report_is_accepted_but_not_persisted(client):
bot_ua = (
"Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; "
"bingbot/2.0; +http://www.bing.com/bingbot.htm) Chrome/136.0.0.0 Safari/537.36"
)
resp = client.post("/api/client-errors", json=_payload(user_agent=bot_ua))
# Accepted (so the bot won't retry) but never upserted / alerted.
assert resp.status_code == 202
assert resp.json()["is_new"] is False
client.fake_adapter.upsert_pattern.assert_not_called()
def test_rejects_missing_message(client):
resp = client.post("/api/client-errors", json=_payload(message=""))
assert resp.status_code == 422
@@ -0,0 +1,129 @@
"""Tests for model-call retry/backoff on transient Vertex/Anthropic errors.
A Vertex 429 RESOURCE_EXHAUSTED is a recurring, transient condition (other
call sites like parse_titles degrade gracefully). Auto-correct should retry
with backoff and only surface a distinct, retryable 429 to the caller when
the rate limit persists — never a generic 502 that reads as a hard failure.
"""
from __future__ import annotations
from unittest.mock import patch
import pytest
from backend.services.auto_correct.service import (
AutoCorrectService,
AutoCorrectServiceError,
_env_number,
_is_transient_model_error,
)
class _FakeClientError(Exception):
"""Mimics google.genai.errors.ClientError (has a numeric ``code``)."""
def __init__(self, code: int, message: str) -> None:
super().__init__(message)
self.code = code
def _service() -> AutoCorrectService:
return AutoCorrectService()
def test_is_transient_detects_429_resource_exhausted() -> None:
exc = _FakeClientError(429, "429 RESOURCE_EXHAUSTED. Resource exhausted.")
assert _is_transient_model_error(exc) is True
def test_is_transient_detects_503_and_overloaded() -> None:
assert _is_transient_model_error(_FakeClientError(503, "UNAVAILABLE")) is True
assert _is_transient_model_error(Exception("529 overloaded_error")) is True
def test_is_transient_ignores_permanent_client_errors() -> None:
assert _is_transient_model_error(_FakeClientError(400, "INVALID_ARGUMENT")) is False
assert _is_transient_model_error(ValueError("bad schema")) is False
def test_env_number_uses_default_when_unset(monkeypatch) -> None:
monkeypatch.delenv("AC_TEST_KNOB", raising=False)
assert _env_number("AC_TEST_KNOB", 3, minimum=1, is_int=True) == 3
def test_env_number_clamps_below_minimum(monkeypatch) -> None:
monkeypatch.setenv("AC_TEST_KNOB", "0")
assert _env_number("AC_TEST_KNOB", 3, minimum=1, is_int=True) == 1
def test_env_number_falls_back_on_garbage(monkeypatch) -> None:
monkeypatch.setenv("AC_TEST_KNOB", "not-a-number")
assert _env_number("AC_TEST_KNOB", 2.0, minimum=0.0, is_int=False) == 2.0
def test_env_number_rejects_non_finite(monkeypatch) -> None:
monkeypatch.setenv("AC_TEST_KNOB", "inf")
assert _env_number("AC_TEST_KNOB", 2.0, minimum=0.0, is_int=False) == 0.0
def test_retryable_call_retries_then_succeeds() -> None:
"""A transient failure is retried; a later success is returned."""
service = _service()
attempts = {"n": 0}
def flaky(model, system_prompt, user_prompt, *, job_id):
attempts["n"] += 1
if attempts["n"] < 3:
raise AutoCorrectServiceError(
"AI model is rate-limited", status_code=429, retryable=True
)
return {"suggestions": []}, None
with patch.object(service, "_call_gemini", side_effect=flaky), \
patch.object(service, "_call_anthropic", side_effect=flaky), \
patch("backend.services.auto_correct.service.time.sleep") as sleep:
raw, usage = service._call_model(
"gemini-3.1-pro-preview", "sys", "user", job_id="job-1"
)
assert raw == {"suggestions": []}
assert attempts["n"] == 3
assert sleep.call_count == 2 # slept before each retry
def test_retryable_call_exhausts_and_raises_429() -> None:
"""Persistent rate-limit surfaces a retryable 429, not a generic 502."""
service = _service()
def always_rate_limited(model, system_prompt, user_prompt, *, job_id):
raise AutoCorrectServiceError(
"AI model is rate-limited", status_code=429, retryable=True
)
with patch.object(service, "_call_gemini", side_effect=always_rate_limited), \
patch("backend.services.auto_correct.service.time.sleep"), \
patch("backend.services.auto_correct.service._MODEL_CALL_MAX_ATTEMPTS", 3):
with pytest.raises(AutoCorrectServiceError) as ei:
service._call_model("gemini-3.1-pro-preview", "sys", "user", job_id="j")
assert ei.value.status_code == 429
assert ei.value.retryable is True
def test_non_retryable_error_fails_fast_without_sleeping() -> None:
"""A permanent error (e.g. bad output) is not retried."""
service = _service()
calls = {"n": 0}
def bad_output(model, system_prompt, user_prompt, *, job_id):
calls["n"] += 1
raise AutoCorrectServiceError("AI returned non-JSON output", status_code=502)
with patch.object(service, "_call_gemini", side_effect=bad_output), \
patch("backend.services.auto_correct.service.time.sleep") as sleep:
with pytest.raises(AutoCorrectServiceError) as ei:
service._call_model("gemini-3.1-pro-preview", "sys", "user", job_id="j")
assert calls["n"] == 1
assert ei.value.status_code == 502
sleep.assert_not_called()
@@ -6,7 +6,7 @@ from unittest.mock import MagicMock, patch
import pytest
from backend.services.custom_lyrics.result import StopReason
from backend.services.custom_lyrics.service import CustomLyricsService
from backend.services.custom_lyrics.service import CustomLyricsService, CustomLyricsServiceError
from backend.services.custom_lyrics.settings import GenerationSettings, StrictnessLevel
@@ -97,6 +97,67 @@ def test_repairs_one_line(service: CustomLyricsService) -> None:
assert result.stop_reason is StopReason.SUCCESS
def test_repair_failure_falls_back_to_best(service: CustomLyricsService) -> None:
"""A failed repair call must keep the successful initial result, not 500.
Regression for job dc60ebf4: the initial generation succeeded but the repair
Gemini call returned response.text=None -> json.loads(None) TypeError ->
uncaught 500 (no CORS headers) -> browser "NetworkError". The whole good
generation was thrown away by a best-effort improvement step.
"""
target_segments = [_segment(0.0, 1.0, "aa"), _segment(1.0, 2.0, "bb")]
target_lines = ["aa", "bb"]
calls = {"n": 0}
def _fake_call(*args, **kwargs):
calls["n"] += 1
if calls["n"] == 1:
return ["xx yy zz qq", "yy"] # initial: 1 violation → triggers a repair
raise RuntimeError("Gemini returned an empty response") # repair blows up
with patch.object(CustomLyricsService, "_call_gemini", side_effect=_fake_call):
result = service.generate(
job_id="j1",
target_lines=target_lines,
target_segments=target_segments,
artist=None, title=None, custom_text="c",
file_bytes=None, file_mime=None, file_name=None,
notes=None,
settings=GenerationSettings(strictness=StrictnessLevel.BALANCED),
)
assert result.stop_reason is StopReason.REPAIR_FAILED
assert result.lines == ["xx yy zz qq", "yy"] # fell back to the initial (best)
assert calls["n"] == 2 # initial + exactly one failed repair, then stop
def test_empty_gemini_response_raises_clean_error(service: CustomLyricsService) -> None:
"""response.text=None -> CustomLyricsServiceError(502), never a raw TypeError.
The endpoint maps CustomLyricsServiceError to a proper HTTP error (with CORS);
a raw TypeError escapes to a 500 with no CORS headers, which the browser shows
as an opaque "NetworkError".
"""
fake_response = MagicMock()
fake_response.text = None
fake_response.candidates = []
fake_response.prompt_feedback = None
fake_client = MagicMock()
fake_client.models.generate_content.return_value = fake_response
with patch("backend.services.custom_lyrics.service.genai.Client", return_value=fake_client):
with pytest.raises(CustomLyricsServiceError) as exc:
service._call_gemini(
system_prompt="s",
user_prompt="u",
pdf_bytes=None,
settings=GenerationSettings(),
)
assert exc.value.status_code == 502
assert "empty response" in str(exc.value).lower()
def test_plateau_detection(service: CustomLyricsService) -> None:
target_segments = [_segment(0.0, 1.0, "aa")]
target_lines = ["aa"]
@@ -108,6 +108,24 @@ class TestDeleteOutputsSuccess:
assert data["job_id"] == "test-job-123"
assert "outputs_deleted_at" in data
def test_delete_outputs_removes_nomad_gcs_master(self, client, mock_complete_job):
"""Deleting a NOMAD job's outputs must also remove its 720p master from the
GCS fast-sync mirror (wiring guard for the delete side)."""
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
patch('backend.api.routes.admin.get_user_service') as mock_user_service, \
patch('backend.services.nomad_master_mirror.cleanup_nomad_masters') as mock_cleanup:
mock_jm = Mock()
mock_jm.get_job.return_value = mock_complete_job # brand_code = "NOMAD-1234"
mock_jm_class.return_value = mock_jm
mock_db = Mock()
mock_db.collection.return_value.document.return_value = Mock()
mock_user_service.return_value.db = mock_db
response = client.post("/api/admin/jobs/test-job-123/delete-outputs")
assert response.status_code == 200
mock_cleanup.assert_called_once_with("NOMAD-1234")
def test_delete_outputs_clears_state_data_keys(self, client, mock_complete_job):
"""Test that output-related state_data keys are listed as cleared."""
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
+48
View File
@@ -1116,3 +1116,51 @@ class TestResetJobToAwaitingAudioEdit:
# 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"
class TestResetBumpsWorkerGenerationFence:
"""A reset is a 'stop what you're doing' event for in-flight workers.
It must atomically bump state_data.worker_generation so a render/video worker
that is still running (e.g. operator hit "Review" mid-render) detects it has
been superseded and discards its stale result instead of failing the reset.
Regression guard for the 7f457087 admin-reset race.
"""
def test_reset_increments_worker_generation(self, client, mock_job):
from backend.services.user_service import get_user_service
mock_user_service = Mock()
mock_job_ref = Mock()
mock_user_service.db.collection.return_value.document.return_value = mock_job_ref
app.dependency_overrides[get_user_service] = lambda: mock_user_service
try:
# Patch the Increment symbol the endpoint imports so the assertion is
# robust even when another test replaced firestore_v1 with a mock.
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
patch('google.cloud.firestore_v1.Increment') as mock_incr:
mock_incr.return_value = "INCREMENT(1)"
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_review"},
)
finally:
del app.dependency_overrides[get_user_service]
assert response.status_code == 200
mock_incr.assert_called_once_with(1) # atomic +1 on the fence
# The clear_updates payload sent to job_ref.update() must carry the fence bump.
update_payloads = [c.args[0] for c in mock_job_ref.update.call_args_list if c.args]
fence_updates = [
p for p in update_payloads
if isinstance(p, dict) and "state_data.worker_generation" in p
]
assert fence_updates, "Reset must bump state_data.worker_generation"
assert fence_updates[-1]["state_data.worker_generation"] == "INCREMENT(1)"
+108
View File
@@ -14,10 +14,41 @@ from backend.workers.audio_download_worker import (
process_audio_download,
_extract_gcs_path,
_download_audio,
DOWNLOAD_WAIT_TIMEOUT_SECONDS,
)
from backend.services.audio_search_service import DownloadError
def _cloud_run_task_timeout_seconds() -> int:
"""Parse the audio-download-job task timeout from the Pulumi module."""
import pathlib
import re
src = (
pathlib.Path(__file__).resolve().parents[2]
/ "infrastructure" / "modules" / "cloud_run.py"
).read_text()
# The audio-download job block sets timeout="NNNNs" right before max_retries.
m = re.search(r'timeout="(\d+)s",\s*\n\s*max_retries=2,\s*\n\s*vpc_access=', src)
assert m, "could not locate audio-download-job timeout in cloud_run.py"
return int(m.group(1))
def test_download_wait_timeout_below_cloud_run_task_timeout():
"""The in-worker download wait MUST expire before Cloud Run SIGKILLs the task.
If they are equal (the old 600s/600s), the SIGKILL bypasses graceful
failure handling and leaves an in-flight auto-retry racing manual retries
(job 1cd29294). Keep meaningful headroom for the final upload + transition.
"""
task_timeout = _cloud_run_task_timeout_seconds()
assert DOWNLOAD_WAIT_TIMEOUT_SECONDS < task_timeout, (
f"download wait {DOWNLOAD_WAIT_TIMEOUT_SECONDS}s must be < Cloud Run "
f"task timeout {task_timeout}s"
)
assert task_timeout - DOWNLOAD_WAIT_TIMEOUT_SECONDS >= 60
def _make_job(
job_id: str = "test-job-123",
status=JobStatus.DOWNLOADING_AUDIO,
@@ -195,6 +226,83 @@ class TestProcessAudioDownload:
mock_ws.trigger_audio_worker.assert_not_awaited()
mock_ws.trigger_lyrics_worker.assert_not_awaited()
@pytest.mark.asyncio
async def test_concurrent_run_completing_mid_download_is_idempotent(self):
"""A second run finishing while we download must not fail the job.
Regression for job 1cd29294: a manual /retry raced this task's Cloud
Run auto-retry. The loser downloaded, then tried DOWNLOADING ->
DOWNLOADING, which raised InvalidStateTransitionError, and the generic
except marked a job the winner had already advanced as FAILED. The
loser must instead detect the advance and return success without
transitioning, failing, or re-triggering downstream workers.
"""
entry_job = _make_job(status=JobStatus.DOWNLOADING_AUDIO)
# By the time our download finishes, a concurrent run advanced the job.
advanced_job = _make_job(status=JobStatus.DOWNLOADING)
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.workers.audio_download_worker.get_worker_service") as mock_ws_factory:
mock_jm = MagicMock()
# Entry sees DOWNLOADING_AUDIO; the pre-transition re-read sees the
# concurrent run's advance to DOWNLOADING.
mock_jm.get_job.side_effect = [entry_job, advanced_job]
mock_jm_cls.return_value = mock_jm
mock_dl.return_value = ("uploads/test-job-123/audio/song.mp3", "song.mp3")
mock_ws = AsyncMock()
mock_ws_factory.return_value = mock_ws
result = await process_audio_download("test-job-123")
assert result is True
mock_dl.assert_awaited_once() # we did download before detecting the race
mock_jm.transition_to_state.assert_not_called()
mock_jm.fail_job.assert_not_called()
mock_ws.trigger_audio_worker.assert_not_awaited()
mock_ws.trigger_lyrics_worker.assert_not_awaited()
@pytest.mark.asyncio
async def test_invalid_transition_at_commit_treated_as_success_if_advanced(self):
"""A race that slips past the guard still must not fail the job.
If the job advances between the pre-transition re-read and the
transition itself, transition_to_state returns False (raise_on_invalid
is off); we re-read, see the advance, and return success.
"""
entry_job = _make_job(status=JobStatus.DOWNLOADING_AUDIO)
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.workers.audio_download_worker.get_worker_service") as mock_ws_factory:
mock_jm = MagicMock()
# Entry + pre-transition guard both see DOWNLOADING_AUDIO (guard
# passes); the transition fails; the post-failure re-read sees the
# concurrent advance.
mock_jm.get_job.side_effect = [
entry_job,
_make_job(status=JobStatus.DOWNLOADING_AUDIO),
_make_job(status=JobStatus.DOWNLOADING),
]
mock_jm.transition_to_state.return_value = False
mock_jm_cls.return_value = mock_jm
mock_dl.return_value = ("uploads/test-job-123/audio/song.mp3", "song.mp3")
mock_ws = AsyncMock()
mock_ws_factory.return_value = mock_ws
result = await process_audio_download("test-job-123")
assert result is True
mock_jm.fail_job.assert_not_called()
mock_ws.trigger_audio_worker.assert_not_awaited()
@pytest.mark.asyncio
async def test_uses_state_data_selection_when_available(self):
"""Should prefer state_data search results over job-level params."""
+139
View File
@@ -0,0 +1,139 @@
"""
Unit tests for EdgeAuthMiddleware (Cloudflare origin lock).
Exercises the off/warn/enforce modes, header validation, exemptions, and the
fail-open-on-misconfiguration behaviour end-to-end via a minimal ASGI app.
"""
import pytest
from fastapi import FastAPI
from starlette.testclient import TestClient
from backend.middleware.edge_auth import EdgeAuthMiddleware, EDGE_AUTH_HEADER
SECRET = "s3cr3t-origin-value"
@pytest.fixture
def client():
"""Minimal app with the middleware installed and a few routes."""
app = FastAPI()
app.add_middleware(EdgeAuthMiddleware)
@app.get("/")
async def root():
return {"ok": "root"}
@app.get("/api/health")
async def health():
return {"ok": "health"}
@app.get("/api/test")
async def protected():
return {"ok": "protected"}
@app.post("/api/internal/recover-stuck-jobs")
async def internal():
return {"ok": "internal"}
return TestClient(app)
def _set(monkeypatch, mode=None, secret=None):
for key, val in (("EDGE_AUTH_MODE", mode), ("EDGE_ORIGIN_SECRET", secret)):
if val is None:
monkeypatch.delenv(key, raising=False)
else:
monkeypatch.setenv(key, val)
# --------------------------------------------------------------------------- #
# off mode (default) — pure passthrough
# --------------------------------------------------------------------------- #
def test_off_mode_is_default_passthrough(client, monkeypatch):
_set(monkeypatch, mode=None, secret=SECRET) # unset mode -> defaults to off
assert client.get("/api/test").status_code == 200
def test_invalid_mode_treated_as_off(client, monkeypatch):
_set(monkeypatch, mode="bogus", secret=SECRET)
assert client.get("/api/test").status_code == 200
# --------------------------------------------------------------------------- #
# enforce mode
# --------------------------------------------------------------------------- #
def test_enforce_blocks_missing_header(client, monkeypatch):
_set(monkeypatch, mode="enforce", secret=SECRET)
resp = client.get("/api/test")
assert resp.status_code == 403
assert resp.json()["detail"] == "Forbidden"
def test_enforce_blocks_wrong_header(client, monkeypatch):
_set(monkeypatch, mode="enforce", secret=SECRET)
resp = client.get("/api/test", headers={EDGE_AUTH_HEADER: "nope"})
assert resp.status_code == 403
def test_enforce_allows_valid_header(client, monkeypatch):
_set(monkeypatch, mode="enforce", secret=SECRET)
resp = client.get("/api/test", headers={EDGE_AUTH_HEADER: SECRET})
assert resp.status_code == 200
assert resp.json()["ok"] == "protected"
def test_enforce_internal_path_requires_header(client, monkeypatch):
"""Internal endpoints traverse Cloudflare (public host) so they DO get the
header — they are not exempt from the origin lock."""
_set(monkeypatch, mode="enforce", secret=SECRET)
assert client.post("/api/internal/recover-stuck-jobs").status_code == 403
ok = client.post(
"/api/internal/recover-stuck-jobs", headers={EDGE_AUTH_HEADER: SECRET}
)
assert ok.status_code == 200
# --------------------------------------------------------------------------- #
# exemptions — health/root probes hit the origin directly, no header
# --------------------------------------------------------------------------- #
@pytest.mark.parametrize("path", ["/", "/api/health"])
def test_enforce_exempts_health_and_root(client, monkeypatch, path):
_set(monkeypatch, mode="enforce", secret=SECRET)
assert client.get(path).status_code == 200
# --------------------------------------------------------------------------- #
# warn mode — logs but allows
# --------------------------------------------------------------------------- #
def test_warn_allows_missing_header(client, monkeypatch):
_set(monkeypatch, mode="warn", secret=SECRET)
assert client.get("/api/test").status_code == 200
def test_warn_allows_valid_header(client, monkeypatch):
_set(monkeypatch, mode="warn", secret=SECRET)
assert client.get("/api/test", headers={EDGE_AUTH_HEADER: SECRET}).status_code == 200
# --------------------------------------------------------------------------- #
# misconfiguration — enforce but no secret set
# --------------------------------------------------------------------------- #
def test_enforce_without_secret_fails_closed(client, monkeypatch):
# A security control must fail closed: enforce with no secret → 503, not open.
_set(monkeypatch, mode="enforce", secret=None)
resp = client.get("/api/test")
assert resp.status_code == 503
assert resp.json()["detail"] == "Origin authentication unavailable"
def test_enforce_without_secret_still_exempts_health(client, monkeypatch):
# Health/root stay reachable even in the misconfigured state (probes).
_set(monkeypatch, mode="enforce", secret=None)
assert client.get("/api/health").status_code == 200
def test_warn_without_secret_allows(client, monkeypatch):
# warn mode is observational only — never blocks, even with no secret.
_set(monkeypatch, mode="warn", secret=None)
assert client.get("/api/test").status_code == 200
+24
View File
@@ -670,6 +670,30 @@ class TestMadeForYouAdminNotification:
html_content = call_kwargs.get('html_content')
assert "abc-def-123" in html_content
def test_send_admin_notification_link_deep_links_to_audio_queue(self):
"""Admin 'Open Job' link must one-click login AND deep-link to the
awaiting-audio-selection queue so the made-for-you order is visible
(a bare /app link lands on a dashboard that filters it out)."""
service = EmailService()
service.provider = Mock()
service.provider.send_email.return_value = True
service.send_made_for_you_admin_notification(
to_email="admin@nomadkaraoke.com",
customer_email="customer@example.com",
artist="Test Artist",
title="Test Song",
job_id="job-123",
admin_login_token="tok-xyz",
)
call_kwargs = service.provider.send_email.call_args.kwargs
html_content = call_kwargs.get('html_content')
text_content = call_kwargs.get('text_content')
for body in (html_content, text_content):
assert "admin_token=tok-xyz" in body
assert "status=awaiting_audio_selection" in body
def test_send_admin_notification_includes_audio_count(self):
"""Test admin notification includes audio source count."""
service = EmailService()
+97 -8
View File
@@ -260,6 +260,16 @@ class TestVMLifecycle:
manager.start_vm("encoding-worker-blue")
mock_compute.start.assert_not_called()
def test_is_transient_start_error_classification(self):
from backend.services.encoding_worker_manager import _is_transient_start_error
from backend.services.encoding_errors import EncodingWorkerStartError
assert _is_transient_start_error(
EncodingWorkerStartError("VM x start failed: 503 — SERVICE UNAVAILABLE", code="503")
)
assert not _is_transient_start_error(
EncodingWorkerStartError("VM x start failed: PERMISSION_DENIED", code="PERMISSION_DENIED")
)
def test_stop_vm_calls_compute_stop(self, manager, mock_compute):
mock_instance = MagicMock()
mock_instance.status = "RUNNING"
@@ -588,22 +598,101 @@ class TestEnsureAnyRunning:
mock_instance.status = "TERMINATED"
mock_compute.get.return_value = mock_instance
op_503 = MagicMock()
op_503.error_code = "503"
op_503.error_message = "SERVICE UNAVAILABLE"
op_503.result.return_value = None
mock_compute.start.side_effect = [op_503, op_503]
def _op_503():
op = MagicMock()
op.error_code = "503"
op.error_message = "SERVICE UNAVAILABLE"
op.result.return_value = None
return op
# All-transient: the whole candidate set is retried a few times before
# giving up, so provide enough operations for every pass.
mock_compute.start.side_effect = [_op_503() for _ in range(20)]
candidates = [
EncodingWorkerCandidate(vm_name="primary", zone="us-central1-c", ip="10.0.0.1"),
EncodingWorkerCandidate(vm_name="fb-a", zone="us-central1-a", ip="10.0.0.2"),
]
with pytest.raises(EncodingWorkerStartError) as exc_info:
manager.ensure_any_running(candidates)
with patch("backend.services.encoding_worker_manager.time.sleep") as sleep:
with pytest.raises(EncodingWorkerStartError) as exc_info:
manager.ensure_any_running(candidates)
# Should NOT be a capacity error — there were none in this scenario.
assert not isinstance(exc_info.value, EncodingWorkerCapacityError)
assert mock_compute.start.call_count == 2
# Retried the whole 2-candidate set across multiple passes before failing.
assert mock_compute.start.call_count > 2
assert sleep.called
def test_retries_whole_set_on_all_transient_then_succeeds(self, manager, mock_db, mock_compute):
"""A brief all-zones 503 blip: first pass fails everywhere, retry succeeds."""
mock_instance = MagicMock()
mock_instance.status = "TERMINATED"
mock_compute.get.return_value = mock_instance
def _op_503():
op = MagicMock(); op.error_code = "503"; op.error_message = "SERVICE UNAVAILABLE"
op.result.return_value = None
return op
# Pass 1: both candidates 503. Pass 2: primary succeeds.
mock_compute.start.side_effect = [_op_503(), _op_503(), _ok_op()]
candidates = [
EncodingWorkerCandidate(vm_name="primary", zone="us-central1-c", ip="10.0.0.1"),
EncodingWorkerCandidate(vm_name="fb-a", zone="us-central1-a", ip="10.0.0.2"),
]
with patch("backend.services.encoding_worker_manager.time.sleep") as sleep, \
patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
mock_dt.now.return_value = datetime(2026, 5, 6, 17, 0, 0, tzinfo=UTC)
mock_dt.side_effect = lambda *a, **kw: datetime(*a, **kw)
result = manager.ensure_any_running(candidates)
assert result["vm_name"] == "primary"
assert result["fell_back"] is False
assert mock_compute.start.call_count == 3
sleep.assert_called_once()
def test_does_not_retry_whole_set_on_mixed_nontransient(self, manager, mock_db, mock_compute):
"""If any candidate fails non-transiently (PERMISSION_DENIED), do NOT retry
the whole set even though the last failure was a transient 503."""
from backend.services.encoding_errors import EncodingWorkerStartError
mock_instance = MagicMock()
mock_instance.status = "TERMINATED"
mock_compute.get.return_value = mock_instance
op_perm = MagicMock()
op_perm.error_code = "PERMISSION_DENIED"; op_perm.error_message = "denied"
op_perm.result.return_value = None
op_503 = MagicMock()
op_503.error_code = "503"; op_503.error_message = "SERVICE UNAVAILABLE"
op_503.result.return_value = None
# primary: PERMISSION_DENIED (non-transient); fallback: 503 (transient/last)
mock_compute.start.side_effect = [op_perm, op_503]
candidates = [
EncodingWorkerCandidate(vm_name="primary", zone="us-central1-c", ip="10.0.0.1"),
EncodingWorkerCandidate(vm_name="fb-a", zone="us-central1-a", ip="10.0.0.2"),
]
with patch("backend.services.encoding_worker_manager.time.sleep") as sleep:
with pytest.raises(EncodingWorkerStartError) as exc:
manager.ensure_any_running(candidates)
assert exc.value.code == "PERMISSION_DENIED" # non-transient surfaced
assert mock_compute.start.call_count == 2 # one pass only
sleep.assert_not_called()
def test_does_not_retry_whole_set_on_capacity(self, manager, mock_db, mock_compute):
"""Capacity exhaustion is not spun on — it raises immediately for the park path."""
from backend.services.encoding_errors import EncodingWorkerCapacityError
mock_instance = MagicMock()
mock_instance.status = "TERMINATED"
mock_compute.get.return_value = mock_instance
mock_compute.start.side_effect = [_capacity_op(), _capacity_op()]
candidates = [
EncodingWorkerCandidate(vm_name="primary", zone="us-central1-c", ip="10.0.0.1"),
EncodingWorkerCandidate(vm_name="fb-a", zone="us-central1-a", ip="10.0.0.2"),
]
with patch("backend.services.encoding_worker_manager.time.sleep") as sleep:
with pytest.raises(EncodingWorkerCapacityError):
manager.ensure_any_running(candidates)
assert mock_compute.start.call_count == 2 # one pass only, no whole-set retry
sleep.assert_not_called()
def test_prefers_capacity_error_when_mixed_failures(self, manager, mock_db, mock_compute):
"""When some candidates hit capacity and others hit generic errors, prefer raising
+77 -14
View File
@@ -2,6 +2,12 @@
Unit tests for encoding worker lifecycle endpoints.
Tests the warmup and heartbeat API endpoints.
These endpoints are called from the customer-facing lyrics-review page to
pre-warm the encoding VM. They are therefore gated on ``require_review_auth``
(review access to a specific job), NOT ``require_admin`` — otherwise every
non-admin customer 403s and the pre-warm silently never happens (the bug this
suite guards against).
"""
import logging
@@ -10,16 +16,24 @@ from unittest.mock import MagicMock
from fastapi import FastAPI
from fastapi.testclient import TestClient
from backend.api.routes.encoding_worker import router, get_worker_manager
from backend.api.dependencies import require_admin
from backend.api.dependencies import require_admin, require_review_auth
from backend.services.encoding_errors import (
EncodingWorkerCapacityError,
EncodingWorkerStartError,
)
JOB_ID = "test-job-123"
WARMUP_URL = f"/api/internal/encoding-worker/warmup/{JOB_ID}"
HEARTBEAT_URL = f"/api/internal/encoding-worker/heartbeat/{JOB_ID}"
def get_mock_admin():
"""Override for require_admin dependency."""
return ("admin-token", "admin", 0)
async def fake_review_auth():
"""Override for require_review_auth — stands in for a review user.
Deliberately returns a *non-admin* auth result (auth_type="full") so the
tests exercise the review-scoped path, not admin access.
"""
return (JOB_ID, "full")
class TestWarmupEndpoint:
@@ -27,7 +41,7 @@ class TestWarmupEndpoint:
self.mock_manager = MagicMock()
self.app = FastAPI()
self.app.include_router(router, prefix="/api")
self.app.dependency_overrides[require_admin] = get_mock_admin
self.app.dependency_overrides[require_review_auth] = fake_review_auth
self.app.dependency_overrides[get_worker_manager] = lambda: self.mock_manager
self.client = TestClient(self.app)
@@ -37,7 +51,7 @@ class TestWarmupEndpoint:
"vm_name": "encoding-worker-a",
"primary_url": "http://34.1.2.3:8080",
}
response = self.client.post("/api/internal/encoding-worker/warmup")
response = self.client.post(WARMUP_URL)
assert response.status_code == 200
data = response.json()
assert data["started"] is True
@@ -49,7 +63,7 @@ class TestWarmupEndpoint:
"vm_name": "encoding-worker-a",
"primary_url": "http://34.1.2.3:8080",
}
response = self.client.post("/api/internal/encoding-worker/warmup")
response = self.client.post(WARMUP_URL)
assert response.status_code == 200
assert response.json()["started"] is False
@@ -57,7 +71,7 @@ class TestWarmupEndpoint:
self.mock_manager.ensure_primary_running.side_effect = RuntimeError(
"VM not found"
)
response = self.client.post("/api/internal/encoding-worker/warmup")
response = self.client.post(WARMUP_URL)
assert response.status_code == 200
assert response.json()["started"] is False
assert "error" in response.json()
@@ -78,7 +92,7 @@ class TestWarmupEndpoint:
)
)
with caplog.at_level(logging.WARNING):
response = self.client.post("/api/internal/encoding-worker/warmup")
response = self.client.post(WARMUP_URL)
assert response.status_code == 200
assert response.json()["started"] is False
warmup_records = [
@@ -106,7 +120,7 @@ class TestWarmupEndpoint:
)
)
with caplog.at_level(logging.WARNING):
response = self.client.post("/api/internal/encoding-worker/warmup")
response = self.client.post(WARMUP_URL)
assert response.status_code == 200
assert not [
r
@@ -121,7 +135,7 @@ class TestWarmupEndpoint:
"misconfigured service account"
)
with caplog.at_level(logging.WARNING):
response = self.client.post("/api/internal/encoding-worker/warmup")
response = self.client.post(WARMUP_URL)
assert response.status_code == 200
error_records = [
r
@@ -137,12 +151,12 @@ class TestHeartbeatEndpoint:
self.mock_manager = MagicMock()
self.app = FastAPI()
self.app.include_router(router, prefix="/api")
self.app.dependency_overrides[require_admin] = get_mock_admin
self.app.dependency_overrides[require_review_auth] = fake_review_auth
self.app.dependency_overrides[get_worker_manager] = lambda: self.mock_manager
self.client = TestClient(self.app)
def test_heartbeat_updates_activity(self):
response = self.client.post("/api/internal/encoding-worker/heartbeat")
response = self.client.post(HEARTBEAT_URL)
assert response.status_code == 200
assert response.json()["status"] == "ok"
self.mock_manager.update_activity.assert_called_once()
@@ -151,6 +165,55 @@ class TestHeartbeatEndpoint:
self.mock_manager.update_activity.side_effect = RuntimeError(
"Firestore error"
)
response = self.client.post("/api/internal/encoding-worker/heartbeat")
response = self.client.post(HEARTBEAT_URL)
assert response.status_code == 200
assert response.json()["status"] == "error"
class TestReviewAuthGating:
"""Regression guard: these endpoints must be review-auth gated, not admin.
Before this fix they used ``require_admin``, so every non-admin customer on
the lyrics-review page got a 403 and the JIT pre-warm never happened.
"""
def test_routes_depend_on_review_auth_not_admin(self):
"""The route dependencies reference require_review_auth, never require_admin."""
deps = set()
for route in router.routes:
dependant = getattr(route, "dependant", None)
if dependant is None:
continue
# Flatten the whole dependency tree for the route.
stack = list(dependant.dependencies)
while stack:
d = stack.pop()
deps.add(d.call)
stack.extend(d.dependencies)
assert require_review_auth in deps, (
"warmup/heartbeat must be gated on require_review_auth"
)
assert require_admin not in deps, (
"warmup/heartbeat must NOT require admin (regresses pre-warm for "
"all non-admin customers)"
)
def test_unauthenticated_request_is_rejected(self):
"""With real auth (no override, no token), warmup is rejected — not 200/500."""
app = FastAPI()
app.include_router(router, prefix="/api")
app.dependency_overrides[get_worker_manager] = lambda: MagicMock()
client = TestClient(app, raise_server_exceptions=False)
response = client.post(WARMUP_URL)
# require_review_auth with no credentials raises 401.
assert response.status_code == 401
def test_job_id_is_required_in_path(self):
"""The old job-less path no longer exists (404), forcing job scoping."""
app = FastAPI()
app.include_router(router, prefix="/api")
app.dependency_overrides[require_review_auth] = fake_review_auth
app.dependency_overrides[get_worker_manager] = lambda: MagicMock()
client = TestClient(app)
response = client.post("/api/internal/encoding-worker/warmup")
assert response.status_code == 404
+216 -9
View File
@@ -419,10 +419,11 @@ class TestUploadToPublicShare:
cdg_file.write_bytes(b"cdg package")
service = GoogleDriveService()
# Mock methods
with patch.object(service, "get_or_create_folder") as mock_get_folder:
with patch.object(service, "upload_file") as mock_upload:
with patch.object(service, "get_or_create_folder") as mock_get_folder, \
patch.object(service, "upload_file") as mock_upload, \
patch("backend.services.nomad_master_mirror.NomadMasterMirror") as mock_mirror_cls:
mock_get_folder.side_effect = [
"mp4-folder-id",
"mp4-720-folder-id",
@@ -433,31 +434,187 @@ class TestUploadToPublicShare:
"720p-file-id",
"cdg-file-id",
]
output_files = {
"final_karaoke_lossy_mp4": str(mp4_file),
"final_karaoke_lossy_720p_mp4": str(mp4_720_file),
"final_karaoke_cdg_zip": str(cdg_file),
}
result = service.upload_to_public_share(
root_folder_id="root-123",
brand_code="NOMAD-1163",
base_name="Artist - Title",
output_files=output_files,
)
# Should have created/found 3 folders
assert mock_get_folder.call_count == 3
# Should have uploaded 3 files
assert mock_upload.call_count == 3
# Check result
assert result["mp4"] == "mp4-file-id"
assert result["mp4_720p"] == "720p-file-id"
assert result["cdg"] == "cdg-file-id"
# Nomad brand → the 720p master is fast-synced to the Divebar GCS
# mirror with the exact "{brand_code} - {base_name}.mp4" object name.
mock_mirror_cls.return_value.push_720p.assert_called_once_with(
str(mp4_720_file), "NOMAD-1163 - Artist - Title.mp4"
)
@patch("backend.services.gdrive_service.get_settings")
def test_public_share_no_fast_sync_for_non_nomad_brand(self, mock_get_settings, tmp_path):
"""Non-Nomad brands (and NOMADNP privates) must NOT touch the divebar mirror."""
from backend.services.gdrive_service import GoogleDriveService
mock_settings = Mock()
mock_settings.get_secret.return_value = json.dumps({
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
})
mock_get_settings.return_value = mock_settings
mp4_720_file = tmp_path / "output_720p.mp4"
mp4_720_file.write_bytes(b"720p video")
service = GoogleDriveService()
with patch.object(service, "get_or_create_folder", return_value="f"), \
patch.object(service, "upload_file", return_value="id"), \
patch("backend.services.nomad_master_mirror.NomadMasterMirror") as mock_mirror_cls:
for brand in ("VOCALSTAR-12", "NOMADNP-1163"):
service.upload_to_public_share(
root_folder_id="root-123",
brand_code=brand,
base_name="Artist - Title",
output_files={"final_karaoke_lossy_720p_mp4": str(mp4_720_file)},
)
mock_mirror_cls.assert_not_called()
@patch("backend.services.gdrive_service.get_settings")
def test_public_share_fast_sync_failure_is_non_fatal(self, mock_get_settings, tmp_path):
"""A mirror failure must never break the (already-succeeded) Drive upload."""
from backend.services.gdrive_service import GoogleDriveService
mock_settings = Mock()
mock_settings.get_secret.return_value = json.dumps({
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
})
mock_get_settings.return_value = mock_settings
mp4_720_file = tmp_path / "output_720p.mp4"
mp4_720_file.write_bytes(b"720p video")
service = GoogleDriveService()
warnings: list = []
with patch.object(service, "get_or_create_folder", return_value="f"), \
patch.object(service, "upload_file", return_value="720p-file-id"), \
patch("backend.services.nomad_master_mirror.NomadMasterMirror",
side_effect=RuntimeError("gcs down")):
result = service.upload_to_public_share(
root_folder_id="root-123",
brand_code="NOMAD-1163",
base_name="Artist - Title",
output_files={"final_karaoke_lossy_720p_mp4": str(mp4_720_file)},
warnings=warnings,
)
# Drive upload still reports success despite the mirror blowing up...
assert result["mp4_720p"] == "720p-file-id"
# ...and the failure is surfaced as a distribution warning (admin alert),
# not silently swallowed.
assert any("fast-sync" in w for w in warnings)
@patch("backend.services.gdrive_service.get_settings")
def test_public_share_pushes_vocals_guide_for_nomad(self, mock_get_settings, tmp_path):
"""A pre-built original-vocals guide is pushed to the vocals prefix with the exact
"{brand_code} - {base_name}.flac" object name (matches the master's naming)."""
from backend.services.gdrive_service import GoogleDriveService
mock_settings = Mock()
mock_settings.get_secret.return_value = json.dumps({
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
})
mock_get_settings.return_value = mock_settings
mp4_720_file = tmp_path / "output_720p.mp4"
mp4_720_file.write_bytes(b"720p video")
guide_file = tmp_path / "original_vocals_guide.flac"
guide_file.write_bytes(b"guide flac")
service = GoogleDriveService()
with patch.object(service, "get_or_create_folder", return_value="f"), \
patch.object(service, "upload_file", return_value="id"), \
patch("backend.services.nomad_master_mirror.NomadMasterMirror") as mock_mirror_cls:
mock_mirror_cls.return_value.push_vocals_guide.return_value = True
service.upload_to_public_share(
root_folder_id="root-123",
brand_code="NOMAD-1163",
base_name="Artist - Title",
output_files={
"final_karaoke_lossy_720p_mp4": str(mp4_720_file),
"original_vocals_guide": str(guide_file),
},
)
mock_mirror_cls.return_value.push_vocals_guide.assert_called_once_with(
str(guide_file), "NOMAD-1163 - Artist - Title.flac"
)
@patch("backend.services.gdrive_service.get_settings")
def test_public_share_no_vocals_guide_for_non_nomad(self, mock_get_settings, tmp_path):
"""Non-Nomad / NOMADNP brands must never push a guide to the public mirror."""
from backend.services.gdrive_service import GoogleDriveService
mock_settings = Mock()
mock_settings.get_secret.return_value = json.dumps({
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
})
mock_get_settings.return_value = mock_settings
guide_file = tmp_path / "original_vocals_guide.flac"
guide_file.write_bytes(b"guide flac")
service = GoogleDriveService()
with patch.object(service, "get_or_create_folder", return_value="f"), \
patch.object(service, "upload_file", return_value="id"), \
patch("backend.services.nomad_master_mirror.NomadMasterMirror") as mock_mirror_cls:
service.upload_to_public_share(
root_folder_id="root-123",
brand_code="NOMADNP-1163",
base_name="Artist - Title",
output_files={"original_vocals_guide": str(guide_file)},
)
mock_mirror_cls.assert_not_called()
@patch("backend.services.gdrive_service.get_settings")
def test_public_share_vocals_guide_failure_is_non_fatal(self, mock_get_settings, tmp_path):
"""A guide push failure surfaces a warning but never breaks the Drive upload."""
from backend.services.gdrive_service import GoogleDriveService
mock_settings = Mock()
mock_settings.get_secret.return_value = json.dumps({
"refresh_token": "token", "client_id": "id", "client_secret": "secret",
})
mock_get_settings.return_value = mock_settings
guide_file = tmp_path / "original_vocals_guide.flac"
guide_file.write_bytes(b"guide flac")
service = GoogleDriveService()
warnings: list = []
with patch.object(service, "get_or_create_folder", return_value="f"), \
patch.object(service, "upload_file", return_value="id"), \
patch("backend.services.nomad_master_mirror.NomadMasterMirror") as mock_mirror_cls:
mock_mirror_cls.return_value.push_vocals_guide.return_value = False
service.upload_to_public_share(
root_folder_id="root-123",
brand_code="NOMAD-1163",
base_name="Artist - Title",
output_files={"original_vocals_guide": str(guide_file)},
warnings=warnings,
)
assert any("guide" in w.lower() for w in warnings)
@patch("backend.services.gdrive_service.get_settings")
def test_upload_to_public_share_skips_missing_files(
self, mock_get_settings, tmp_path
@@ -928,6 +1085,56 @@ class TestFindFilesByBrandCode:
with pytest.raises(RuntimeError, match="search incomplete"):
service.find_files_by_brand_code("root-folder", "NOMAD-1271")
@patch("backend.services.gdrive_service.get_settings")
def test_recovers_from_transient_connection_error(self, mock_get_settings):
"""A transient BrokenPipe/SSL EOF within a subfolder search is retried, not fatal.
Regression for the "GDrive brand_code search incomplete: 2/3 subfolder(s) failed"
alerts caused by [SSL: UNEXPECTED_EOF_WHILE_READING] / [Errno 32] Broken pipe
against idle Cloud Run containers.
"""
service = self._make_service(mock_get_settings)
# Prevent _reset_service (called in before_sleep) from nulling our mock.
service._reset_service = Mock()
mock_files_api = Mock()
mock_list_result = Mock()
mock_list_result.execute.side_effect = [
{"files": [{"id": "cdg-folder"}]}, # CDG subfolder found
BrokenPipeError("Errno 32 Broken pipe"), # transient drop mid-search
{"files": [{"id": "cdg-folder"}]}, # retry: subfolder found again
{"files": [{"id": "cdg-file-1", "name": "NOMAD-1271 - piri - dog.zip"}]},
{"files": []}, # MP4 not found
{"files": []}, # MP4-720p not found
]
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
result = service.find_files_by_brand_code("root-folder", "NOMAD-1271")
assert result == ["cdg-file-1"]
service._reset_service.assert_called() # a retry actually happened
@patch("backend.services.gdrive_service.get_settings")
def test_persistent_transient_error_still_raises_incomplete(self, mock_get_settings):
"""If retries are exhausted, the search is still reported as incomplete (not clean)."""
service = self._make_service(mock_get_settings)
service._reset_service = Mock()
mock_files_api = Mock()
mock_list_result = Mock()
# Every call drops the connection — retries exhaust for all subfolders.
mock_list_result.execute.side_effect = BrokenPipeError("Errno 32 Broken pipe")
mock_files_api.list.return_value = mock_list_result
mock_drive = Mock()
mock_drive.files.return_value = mock_files_api
service._service = mock_drive
with pytest.raises(RuntimeError, match="search incomplete"):
service.find_files_by_brand_code("root-folder", "NOMAD-1271")
class TestGetGdriveService:
"""Test get_gdrive_service singleton."""
+30
View File
@@ -202,6 +202,36 @@ class TestCheckJobConsistency:
issues = check_job_consistency(job)
assert not any("downloading_audio_stuck" in i for i in issues)
def test_rendering_video_recently_updated_not_flagged(self):
"""A render that updated 20 min ago (< 45) should not be flagged."""
job = create_test_job(status=JobStatus.RENDERING_VIDEO)
job.updated_at = datetime.now(timezone.utc) - timedelta(minutes=20)
issues = check_job_consistency(job)
assert not any("rendering_video_stuck" in i for i in issues)
def test_rendering_video_stuck_60_min_flagged(self):
"""A render with no update for 60 min (worker died) should be flagged."""
job = create_test_job(status=JobStatus.RENDERING_VIDEO)
job.updated_at = datetime.now(timezone.utc) - timedelta(minutes=60)
issues = check_job_consistency(job)
assert any("rendering_video_stuck" in i for i in issues)
stuck_issue = [i for i in issues if "rendering_video_stuck" in i][0]
assert "60 min" in stuck_issue
def test_rendering_video_at_44_min_not_flagged(self):
"""At 44 min it must not flag yet (threshold is 45)."""
job = create_test_job(status=JobStatus.RENDERING_VIDEO)
job.updated_at = datetime.now(timezone.utc) - timedelta(minutes=44)
issues = check_job_consistency(job)
assert not any("rendering_video_stuck" in i for i in issues)
def test_rendering_video_stuck_with_naive_datetime(self):
"""rendering_video_stuck handles naive datetime (no tzinfo)."""
job = create_test_job(status=JobStatus.RENDERING_VIDEO)
job.updated_at = datetime.utcnow() - timedelta(minutes=50)
issues = check_job_consistency(job)
assert any("rendering_video_stuck" in i for i in issues)
class TestCheckJobConsistencyDetailed:
"""Tests for check_job_consistency_detailed function."""
+132
View File
@@ -0,0 +1,132 @@
"""
Unit tests for UserService.get_magic_link_status.
This is a READ-ONLY status check used by the verify page to decide, on load,
whether to show the "Complete Sign-In" gate (valid link) or an "already used /
expired" message (dead link). It must NEVER consume the token — otherwise an
email link-scanner that renders the verify page would burn a valid link before
the real user clicks, which is exactly the bug this whole feature prevents.
"""
import sys
from datetime import datetime, timedelta
from unittest.mock import MagicMock, patch
import pytest
# Mock Firestore before importing modules that use it.
sys.modules.setdefault('google.cloud.firestore', MagicMock())
sys.modules.setdefault('google.cloud.firestore_v1', MagicMock())
from fastapi.testclient import TestClient
def _service_with_doc(mock_fs, mock_settings, doc_dict, exists=True):
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 = exists
mock_doc.to_dict.return_value = doc_dict
mock_db.collection.return_value.document.return_value.get.return_value = mock_doc
from backend.services.user_service import UserService
return UserService(), mock_db
def _link_dict(**overrides):
d = {
'token': 'tok123',
'email': 'user@example.com',
'created_at': datetime.utcnow(),
'expires_at': datetime.utcnow() + timedelta(hours=1),
'used': False,
'used_at': None,
}
d.update(overrides)
return d
class TestGetMagicLinkStatus:
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_valid_link_returns_valid(self, mock_fs, mock_settings):
service, _ = _service_with_doc(mock_fs, mock_settings, _link_dict())
assert service.get_magic_link_status('tok123') == 'valid'
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_valid_link_is_not_consumed(self, mock_fs, mock_settings):
"""The scanner-safety guarantee: a status check must not mutate the token."""
service, mock_db = _service_with_doc(mock_fs, mock_settings, _link_dict())
service.get_magic_link_status('tok123')
doc_ref = mock_db.collection.return_value.document.return_value
doc_ref.update.assert_not_called()
doc_ref.set.assert_not_called()
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_used_link_returns_used(self, mock_fs, mock_settings):
service, _ = _service_with_doc(
mock_fs, mock_settings, _link_dict(used=True, used_at=datetime.utcnow())
)
assert service.get_magic_link_status('tok123') == 'used'
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_expired_link_returns_expired(self, mock_fs, mock_settings):
service, _ = _service_with_doc(
mock_fs, mock_settings, _link_dict(expires_at=datetime.utcnow() - timedelta(minutes=1))
)
assert service.get_magic_link_status('tok123') == 'expired'
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_missing_link_returns_invalid(self, mock_fs, mock_settings):
service, _ = _service_with_doc(mock_fs, mock_settings, {}, exists=False)
assert service.get_magic_link_status('missing') == 'invalid'
@patch('backend.services.user_service.get_settings')
@patch('backend.services.user_service.firestore')
def test_empty_token_returns_invalid(self, mock_fs, mock_settings):
service, _ = _service_with_doc(mock_fs, mock_settings, _link_dict())
assert service.get_magic_link_status(' ') == 'invalid'
class TestLinkStatusEndpoint:
"""GET /api/users/auth/link-status — thin, read-only wrapper over the service."""
def _client(self, status_value):
from backend.main import app
from backend.services.user_service import get_user_service
svc = MagicMock()
svc.get_magic_link_status.return_value = status_value
app.dependency_overrides[get_user_service] = lambda: svc
return TestClient(app), app, svc
def test_endpoint_returns_status_for_valid(self):
client, app, svc = self._client("valid")
try:
r = client.get("/api/users/auth/link-status", params={"token": "tok123"})
assert r.status_code == 200
assert r.json()["status"] == "valid"
svc.get_magic_link_status.assert_called_once_with("tok123")
finally:
app.dependency_overrides.clear()
def test_endpoint_returns_used(self):
client, app, svc = self._client("used")
try:
r = client.get("/api/users/auth/link-status", params={"token": "burned"})
assert r.status_code == 200
assert r.json()["status"] == "used"
finally:
app.dependency_overrides.clear()
def test_endpoint_returns_invalid_for_empty_token_without_touching_firestore(self):
client, app, svc = self._client("valid") # service would say valid, but route must short-circuit
try:
r = client.get("/api/users/auth/link-status", params={"token": " "})
assert r.status_code == 200
assert r.json()["status"] == "invalid"
svc.get_magic_link_status.assert_not_called()
finally:
app.dependency_overrides.clear()
+208
View File
@@ -0,0 +1,208 @@
"""Unit tests for the Nomad master fast-sync mirror (Phase 1)."""
from unittest.mock import MagicMock
import pytest
from google.cloud.exceptions import NotFound
from backend.services.nomad_master_mirror import (
NomadMasterMirror,
is_nomad_public_brand,
)
@pytest.mark.parametrize(
"brand_code, expected",
[
("NOMAD-1500", True),
("NOMAD-0001", True),
("NOMAD-1500", True),
("NOMADNP-1234", False), # private tracks must never enter the public mirror
("nomadnp-1", False),
("TRACK-0000", False),
("VOCALSTAR-12", False),
("", False),
(None, False),
],
)
def test_is_nomad_public_brand(brand_code, expected):
assert is_nomad_public_brand(brand_code) is expected
def _mirror_with_mock():
"""NomadMasterMirror wired to a mock GCS client; returns (mirror, blob)."""
blob = MagicMock()
bucket = MagicMock()
bucket.blob.return_value = blob
client = MagicMock()
client.bucket.return_value = bucket
mirror = NomadMasterMirror(client=client)
return mirror, bucket, blob
def test_push_720p_uses_exact_divebar_object_name_and_uploads():
mirror, bucket, blob = _mirror_with_mock()
ok = mirror.push_720p(
"/tmp/out/NOMAD-1500 - Rush - The Spirit of Radio.mp4",
"NOMAD-1500 - Rush - The Spirit of Radio.mp4",
)
assert ok is True
# Object name MUST match the nightly VM's layout exactly (idempotency).
bucket.blob.assert_called_once_with(
"files/Nomad Karaoke/MP4-720p/NOMAD-1500 - Rush - The Spirit of Radio.mp4"
)
blob.upload_from_filename.assert_called_once_with(
"/tmp/out/NOMAD-1500 - Rush - The Spirit of Radio.mp4"
)
def test_push_720p_is_non_fatal_on_error():
mirror, _bucket, blob = _mirror_with_mock()
blob.upload_from_filename.side_effect = RuntimeError("boom")
# Must not raise; returns False so the pipeline continues.
assert mirror.push_720p("/tmp/x.mp4", "NOMAD-1 - A - B.mp4") is False
def test_delete_720p_removes_blob():
mirror, bucket, blob = _mirror_with_mock()
assert mirror.delete_720p("NOMAD-1500 - Rush - The Spirit of Radio.mp4") is True
bucket.blob.assert_called_once_with(
"files/Nomad Karaoke/MP4-720p/NOMAD-1500 - Rush - The Spirit of Radio.mp4"
)
blob.delete.assert_called_once()
def test_delete_720p_missing_is_noop():
mirror, _bucket, blob = _mirror_with_mock()
blob.delete.side_effect = NotFound("gone")
assert mirror.delete_720p("NOMAD-9 - X - Y.mp4") is False
def test_delete_720p_is_non_fatal_on_error():
mirror, _bucket, blob = _mirror_with_mock()
blob.delete.side_effect = RuntimeError("boom")
assert mirror.delete_720p("NOMAD-9 - X - Y.mp4") is False
# --- delete_masters_by_brand (prefix delete; covers renames) ---
def _mirror_with_blobs(names):
blobs = []
for n in names:
b = MagicMock()
b.name = n
blobs.append(b)
bucket = MagicMock()
bucket.list_blobs.return_value = blobs
client = MagicMock()
client.bucket.return_value = bucket
return NomadMasterMirror(client=client), bucket, blobs
def test_delete_masters_by_brand_deletes_all_matching_by_prefix():
# Two objects for the same release (e.g. an old + renamed title) both go.
mirror, bucket, blobs = _mirror_with_blobs([
"files/Nomad Karaoke/MP4-720p/NOMAD-1500 - Rush - Spirit of Radio.mp4",
"files/Nomad Karaoke/MP4-720p/NOMAD-1500 - Rush - The Spirit of Radio.mp4",
])
n = mirror.delete_masters_by_brand("NOMAD-1500")
assert n == 2
bucket.list_blobs.assert_called_once_with(
prefix="files/Nomad Karaoke/MP4-720p/NOMAD-1500 - "
)
for b in blobs:
b.delete.assert_called_once()
@pytest.mark.parametrize("brand", ["NOMADNP-1500", "VOCALSTAR-1", "", None, "NOMAD"])
def test_delete_masters_by_brand_refuses_non_nomad_or_bare(brand):
# Must never list/delete for a non-Nomad or bare brand — a broad prefix could
# wipe unrelated objects.
mirror, bucket, _blobs = _mirror_with_blobs([])
assert mirror.delete_masters_by_brand(brand) == 0
bucket.list_blobs.assert_not_called()
def test_delete_masters_by_brand_is_non_fatal_on_list_error():
mirror, bucket, _blobs = _mirror_with_blobs([])
bucket.list_blobs.side_effect = RuntimeError("gcs down")
assert mirror.delete_masters_by_brand("NOMAD-1500") == 0
# --- vocals guide push / delete (parallel to the master methods) ---
def test_push_vocals_guide_uses_vocals_prefix_and_uploads():
mirror, bucket, blob = _mirror_with_mock()
ok = mirror.push_vocals_guide(
"/tmp/out/NOMAD-1500 - Rush - The Spirit of Radio.flac",
"NOMAD-1500 - Rush - The Spirit of Radio.flac",
)
assert ok is True
bucket.blob.assert_called_once_with(
"files/Nomad Karaoke/vocals-padded/NOMAD-1500 - Rush - The Spirit of Radio.flac"
)
blob.upload_from_filename.assert_called_once_with(
"/tmp/out/NOMAD-1500 - Rush - The Spirit of Radio.flac"
)
def test_push_vocals_guide_is_non_fatal_on_error():
mirror, _bucket, blob = _mirror_with_mock()
blob.upload_from_filename.side_effect = RuntimeError("boom")
assert mirror.push_vocals_guide("/tmp/x.flac", "NOMAD-1 - A - B.flac") is False
def test_delete_vocals_guides_by_brand_deletes_all_matching_by_prefix():
mirror, bucket, blobs = _mirror_with_blobs([
"files/Nomad Karaoke/vocals-padded/NOMAD-1500 - Rush - Spirit of Radio.flac",
"files/Nomad Karaoke/vocals-padded/NOMAD-1500 - Rush - The Spirit of Radio.flac",
])
n = mirror.delete_vocals_guides_by_brand("NOMAD-1500")
assert n == 2
bucket.list_blobs.assert_called_once_with(
prefix="files/Nomad Karaoke/vocals-padded/NOMAD-1500 - "
)
for b in blobs:
b.delete.assert_called_once()
@pytest.mark.parametrize("brand", ["NOMADNP-1500", "VOCALSTAR-1", "", None, "NOMAD"])
def test_delete_vocals_guides_by_brand_refuses_non_nomad_or_bare(brand):
mirror, bucket, _blobs = _mirror_with_blobs([])
assert mirror.delete_vocals_guides_by_brand(brand) == 0
bucket.list_blobs.assert_not_called()
def test_delete_vocals_guides_by_brand_is_non_fatal_on_list_error():
mirror, bucket, _blobs = _mirror_with_blobs([])
bucket.list_blobs.side_effect = RuntimeError("gcs down")
assert mirror.delete_vocals_guides_by_brand("NOMAD-1500") == 0
def test_cleanup_nomad_masters_delegates_for_nomad(monkeypatch):
from backend.services import nomad_master_mirror as mod
inst = MagicMock()
inst.delete_masters_by_brand.return_value = 3
monkeypatch.setattr(mod, "NomadMasterMirror", lambda: inst)
assert mod.cleanup_nomad_masters("NOMAD-1500") == 3
inst.delete_masters_by_brand.assert_called_once_with("NOMAD-1500")
# Brand recycle must also clear the release's original-vocals guide(s).
inst.delete_vocals_guides_by_brand.assert_called_once_with("NOMAD-1500")
@pytest.mark.parametrize("brand", ["NOMADNP-1", "OTHER-1", "", None])
def test_cleanup_nomad_masters_noop_for_non_nomad(brand, monkeypatch):
from backend.services import nomad_master_mirror as mod
# Must not even construct the mirror (no GCS client) for non-Nomad brands.
monkeypatch.setattr(mod, "NomadMasterMirror", lambda: (_ for _ in ()).throw(AssertionError("should not construct")))
assert mod.cleanup_nomad_masters(brand) == 0
+112
View File
@@ -0,0 +1,112 @@
"""Unit tests for the padded original-vocals guide builder."""
import os
import shutil
import subprocess
import pytest
from backend.services.original_vocals_guide import (
build_original_vocals_guide,
probe_duration,
)
pytestmark = pytest.mark.skipif(
shutil.which("ffmpeg") is None or shutil.which("ffprobe") is None,
reason="ffmpeg/ffprobe not available",
)
@pytest.fixture
def tone(tmp_path):
"""A 4-second 440Hz tone standing in for the mixed-vocals stem."""
src = tmp_path / "vocals.flac"
subprocess.run(
["ffmpeg", "-y", "-loglevel", "error", "-f", "lavfi",
"-i", "sine=frequency=440:duration=4", "-c:a", "flac", str(src)],
check=True,
)
return str(src)
def _first_sound_onset(path):
"""Seconds until audio first exceeds the silence threshold (leading-silence length)."""
out = subprocess.run(
["ffmpeg", "-hide_banner", "-i", path, "-af",
"silencedetect=noise=-50dB:d=0.1", "-f", "null", "-"],
capture_output=True, text=True,
).stderr
# A guide with N seconds of leading silence reports "silence_end: N".
for line in out.splitlines():
if "silence_end:" in line:
return float(line.split("silence_end:")[1].split("|")[0].strip())
return 0.0
def test_prepends_intro_silence_and_reports_expected_duration(tmp_path, tone):
dest = str(tmp_path / "NOMAD-1500 - A - B.flac")
out = build_original_vocals_guide(tone, intro_seconds=5, dest_path=dest)
assert out == dest
assert os.path.isfile(dest)
# silence[5] + 4s tone ≈ 9s total, with the tone starting ~5s in.
total = probe_duration(dest)
assert total == pytest.approx(9.0, abs=0.3)
assert _first_sound_onset(dest) == pytest.approx(5.0, abs=0.3)
def test_respects_non_default_intro(tmp_path, tone):
dest = str(tmp_path / "guide.flac")
build_original_vocals_guide(tone, intro_seconds=10, dest_path=dest)
# Proves we honour the job's actual intro, not a hardcoded 5s.
assert _first_sound_onset(dest) == pytest.approx(10.0, abs=0.3)
def test_caps_to_master_duration(tmp_path, tone):
dest = str(tmp_path / "guide.flac")
# silence[5] + 4s tone would be 9s; cap to 7s.
build_original_vocals_guide(tone, intro_seconds=5, dest_path=dest, master_duration=7.0)
assert probe_duration(dest) == pytest.approx(7.0, abs=0.3)
def test_output_is_valid_flac(tmp_path, tone):
dest = str(tmp_path / "guide.flac")
build_original_vocals_guide(tone, intro_seconds=1, dest_path=dest)
codec = subprocess.run(
["ffprobe", "-v", "error", "-select_streams", "a:0",
"-show_entries", "stream=codec_name", "-of",
"default=noprint_wrappers=1:nokey=1", dest],
capture_output=True, text=True,
).stdout.strip()
assert codec == "flac"
def test_no_part_file_left_behind(tmp_path, tone):
dest = str(tmp_path / "guide.flac")
build_original_vocals_guide(tone, intro_seconds=1, dest_path=dest)
assert not os.path.exists(dest + ".part")
def test_missing_input_returns_none(tmp_path):
out = build_original_vocals_guide(
str(tmp_path / "nope.flac"), intro_seconds=5, dest_path=str(tmp_path / "g.flac")
)
assert out is None
assert not os.path.exists(tmp_path / "g.flac")
def test_negative_intro_returns_none(tmp_path, tone):
assert build_original_vocals_guide(tone, intro_seconds=-1, dest_path=str(tmp_path / "g.flac")) is None
def test_ffmpeg_failure_is_non_fatal(tmp_path, tone):
# A bogus ffmpeg binary must not raise; just returns None.
out = build_original_vocals_guide(
tone, intro_seconds=5, dest_path=str(tmp_path / "g.flac"),
ffmpeg_path="/nonexistent/ffmpeg",
)
assert out is None
assert not os.path.exists(str(tmp_path / "g.flac") + ".part")
def test_probe_duration_missing_file_returns_none(tmp_path):
assert probe_duration(str(tmp_path / "nope.flac")) is None
+174
View File
@@ -0,0 +1,174 @@
import asyncio
from backend.services.parse_titles import ai
from backend.services.parse_titles import service
def test_settings_parse_titles_defaults():
from backend.config import Settings
s = Settings()
assert s.parse_titles_enabled is True
assert s.parse_titles_model == "gemini-3.5-flash"
assert s.parse_titles_timeout_ms == 20000
assert s.parse_titles_max_items == 200
def test_build_prompts_lists_items_with_ids():
system, user = ai.build_prompts(
[{"id": "a", "filename": "Santeria - Sublime _ Karaoke _ KaraFun.mp4",
"channel": "KaraFun", "source": "youtube"}]
)
assert "artist" in system.lower() and "title" in system.lower()
assert "id='a'" in user or '"a"' in user or "id=a" in user # id must be echoed
assert "Santeria" in user
def test_parse_map_from_response_aligns_by_id_and_fills_misses():
items = [{"id": "a", "filename": "x"}, {"id": "b", "filename": "y"}]
data = {"results": [{"id": "a", "artist": "Sublime", "title": "Santeria",
"confidence": 0.9}]}
out = ai.parse_map_from_response(data, items)
assert {r["id"] for r in out} == {"a", "b"}
a = next(r for r in out if r["id"] == "a")
assert (a["artist"], a["title"]) == ("Sublime", "Santeria")
b = next(r for r in out if r["id"] == "b")
assert b["artist"] == "" and b["title"] == "" and b["confidence"] == 0.0
def test_ai_parse_uses_injected_generate():
items = [{"id": "a", "filename": "Bella Kay - iloveit (Karaoke Version).mp4"}]
async def fake_generate(model, system, user):
return {"results": [{"id": "a", "artist": "Bella Kay",
"title": "iloveit", "confidence": 0.82}]}
out = asyncio.run(ai.ai_parse(items, generate=fake_generate))
assert out[0]["artist"] == "Bella Kay" and out[0]["confidence"] == 0.82
def test_parse_map_handles_garbage_response():
items = [{"id": "a", "filename": "x"}]
assert ai.parse_map_from_response("not a dict", items) == [
{"id": "a", "artist": "", "title": "", "confidence": 0.0}
]
def test_parse_titles_disabled_returns_blanks(monkeypatch):
from backend.config import settings
monkeypatch.setattr(settings, "parse_titles_enabled", False)
out = asyncio.run(service.parse_titles([{"id": "a", "filename": "x"}]))
assert out == [{"id": "a", "artist": "", "title": "", "confidence": 0.0}]
def test_parse_titles_degrades_on_generate_error(monkeypatch):
from backend.config import settings
monkeypatch.setattr(settings, "parse_titles_enabled", True)
async def boom(model, system, user):
raise RuntimeError("vertex down")
out = asyncio.run(service.parse_titles(
[{"id": "a", "filename": "x"}], generate=boom))
assert out == [{"id": "a", "artist": "", "title": "", "confidence": 0.0}]
def test_parse_titles_happy_path(monkeypatch):
from backend.config import settings
monkeypatch.setattr(settings, "parse_titles_enabled", True)
async def gen(model, system, user):
return {"results": [{"id": "a", "artist": "Queen",
"title": "Bohemian Rhapsody", "confidence": 0.95}]}
out = asyncio.run(service.parse_titles([{"id": "a", "filename": "x"}], generate=gen))
assert out[0]["artist"] == "Queen" and out[0]["confidence"] == 0.95
def test_parse_titles_empty_returns_empty():
assert asyncio.run(service.parse_titles([])) == []
# --- auto-chunking: large batches must not ride one >20s Gemini call ---
def _items(n):
return [{"id": str(i), "filename": f"file {i}.mp4"} for i in range(n)]
def _ok_results(model, system, user):
"""Echo one parsed result per '- id=' line in the user prompt."""
ids = [line.split("id='", 1)[1].split("'", 1)[0]
for line in user.splitlines() if line.startswith("- id=")]
return {"results": [{"id": i, "artist": f"A{i}", "title": f"T{i}",
"confidence": 0.9} for i in ids]}
def test_settings_parse_titles_chunk_size_default():
from backend.config import Settings
assert Settings().parse_titles_chunk_size == 10
def test_parse_titles_chunks_large_batches(monkeypatch):
from backend.config import settings
monkeypatch.setattr(settings, "parse_titles_enabled", True)
calls = []
async def gen(model, system, user):
n = sum(1 for line in user.splitlines() if line.startswith("- id="))
calls.append(n)
return _ok_results(model, system, user)
out = asyncio.run(service.parse_titles(_items(25), generate=gen))
assert sorted(calls, reverse=True) == [10, 10, 5] # 25 items -> 3 Gemini calls
assert [r["id"] for r in out] == [str(i) for i in range(25)] # id-aligned
assert all(r["artist"] == f'A{r["id"]}' for r in out)
def test_parse_titles_chunk_failure_degrades_only_that_chunk(monkeypatch):
from backend.config import settings
monkeypatch.setattr(settings, "parse_titles_enabled", True)
async def gen(model, system, user):
if "id='10'" in user: # the middle chunk (items 10-19)
raise RuntimeError("vertex timeout")
return _ok_results(model, system, user)
out = asyncio.run(service.parse_titles(_items(25), generate=gen))
assert out[0]["artist"] == "A0" and out[24]["artist"] == "A24"
assert all(out[i]["artist"] == "" and out[i]["confidence"] == 0.0
for i in range(10, 20)) # only that chunk blank
assert [r["id"] for r in out] == [str(i) for i in range(25)]
def test_parse_titles_chunks_run_concurrently(monkeypatch):
"""The chunks must be issued in parallel — a 100-item batch shouldn't pay
10 sequential Gemini round-trips."""
from backend.config import settings
monkeypatch.setattr(settings, "parse_titles_enabled", True)
started = 0
all_started = asyncio.Event()
async def gen(model, system, user):
nonlocal started
started += 1
if started == 3:
all_started.set()
# Sequential execution would deadlock here on the first chunk.
await asyncio.wait_for(all_started.wait(), timeout=5)
return _ok_results(model, system, user)
out = asyncio.run(service.parse_titles(_items(25), generate=gen))
assert len(out) == 25 and out[0]["artist"] == "A0"
def test_parse_titles_respects_configured_chunk_size(monkeypatch):
from backend.config import settings
monkeypatch.setattr(settings, "parse_titles_enabled", True)
monkeypatch.setattr(settings, "parse_titles_chunk_size", 4, raising=False)
calls = []
async def gen(model, system, user):
calls.append(sum(1 for line in user.splitlines() if line.startswith("- id=")))
return _ok_results(model, system, user)
asyncio.run(service.parse_titles(_items(10), generate=gen))
assert sorted(calls, reverse=True) == [4, 4, 2]
+59
View File
@@ -0,0 +1,59 @@
from fastapi.testclient import TestClient
from backend.main import app
from backend.api.dependencies import require_admin
def _admin_result():
from backend.services.auth_service import AuthResult, UserType
return AuthResult(is_valid=True, user_type=UserType.ADMIN, remaining_uses=-1,
message="ok", user_email="a@nomadkaraoke.com", is_admin=True)
def test_parse_route_happy_path(monkeypatch):
# Self-contained: set our own admin override rather than relying on the
# conftest autouse fixture (which can be disturbed by earlier tests in a
# full-suite run and leave the endpoint returning 401).
from backend.api.routes import parse_titles as route
async def fake_parse(items, **kw):
return [{"id": str(it["id"]), "artist": "Queen",
"title": "Bohemian Rhapsody", "confidence": 0.9} for it in items]
monkeypatch.setattr(route, "parse_titles", fake_parse)
original = app.dependency_overrides.get(require_admin)
app.dependency_overrides[require_admin] = _admin_result
try:
client = TestClient(app)
resp = client.post("/api/parse-karaoke-titles", json={
"items": [{"id": "1", "filename": "x.mp4", "source": "youtube"}]})
assert resp.status_code == 200
body = resp.json()
assert body["results"][0]["id"] == "1"
assert body["results"][0]["artist"] == "Queen"
finally:
if original is not None:
app.dependency_overrides[require_admin] = original
else:
app.dependency_overrides.pop(require_admin, None)
def test_parse_route_requires_admin():
"""The route is gated by require_admin: a non-admin dependency -> 403."""
original = app.dependency_overrides.get(require_admin)
def non_admin():
from fastapi import HTTPException
raise HTTPException(status_code=403, detail="Admin access required")
app.dependency_overrides[require_admin] = non_admin
try:
client = TestClient(app)
resp = client.post("/api/parse-karaoke-titles",
json={"items": [{"id": "1", "filename": "x"}]})
assert resp.status_code == 403
finally:
if original is not None:
app.dependency_overrides[require_admin] = original
else:
app.dependency_overrides.pop(require_admin, None)
@@ -0,0 +1,177 @@
"""Tests for POST /api/internal/recover-stuck-jobs resilience paths.
Covers the three recovery behaviours the endpoint drives every 5 min:
1. Stuck torrent downloads (RED/OPS) → parked into DOWNLOAD_PENDING_RETRY and
re-tried for up to 24h (rare tracks / intermittent seeders / tracker blips).
2. Parked downloads → re-triggered, or permanently failed after 24h.
3. Orphaned renders stuck at RENDERING_VIDEO → re-parked into
RENDER_PENDING_CAPACITY so the existing retry cron resumes them.
"""
from datetime import datetime, timedelta, timezone
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from fastapi.testclient import TestClient
from backend.api.dependencies import require_admin
from backend.main import app
from backend.models.job import Job, JobStatus
from backend.services.auth_service import AuthResult, UserType
@pytest.fixture
def client():
async def fake_admin():
return AuthResult(
is_valid=True, user_type=UserType.ADMIN, remaining_uses=999,
message="test admin", is_admin=True, user_email="test@example.com",
)
app.dependency_overrides[require_admin] = fake_admin
try:
yield TestClient(app)
finally:
app.dependency_overrides.pop(require_admin, None)
def _doc(job_id, status):
doc = MagicMock()
doc.id = job_id
doc.to_dict.return_value = {"job_id": job_id, "status": status.value}
return doc
def _job(job_id, status, *, minutes_stale=0, source_name=None, download_retry=None):
sd = {}
if download_retry is not None:
sd["download_retry"] = download_retry
return Job(
job_id=job_id, artist="A", title="B", status=status,
created_at=datetime.now(timezone.utc) - timedelta(hours=2),
updated_at=datetime.now(timezone.utc) - timedelta(minutes=minutes_stale),
state_data=sd, source_name=source_name, audio_source_type="audio_search",
source_id="123",
)
def _mock_jm(*, downloading=None, pending=None, rendering=None, jobs=None):
"""Wire a JobManager mock for the endpoint's 3 status queries.
downloading/rendering use .where().stream(); pending uses .where().limit().stream().
`jobs` maps job_id -> Job returned by get_job().
"""
mock_jm = MagicMock()
where = mock_jm.firestore.db.collection.return_value.where.return_value
# Two non-limited .stream() calls in order: downloading_audio, rendering_video
where.stream.side_effect = [iter(downloading or []), iter(rendering or [])]
# One .limit().stream() call: download_pending_retry
where.limit.return_value.stream.return_value = iter(pending or [])
mock_jm.get_job.side_effect = lambda jid: (jobs or {}).get(jid)
mock_jm.transition_to_state.return_value = True
return mock_jm
def _run(client, mock_jm):
mock_ws = MagicMock()
mock_ws.trigger_audio_download_worker = AsyncMock(return_value=True)
with patch("backend.api.routes.internal.JobManager", return_value=mock_jm), \
patch("backend.services.worker_service.get_worker_service", return_value=mock_ws):
resp = client.post("/api/internal/recover-stuck-jobs")
return resp, mock_ws
def test_stuck_torrent_download_is_parked(client):
"""A stuck RED download is parked into DOWNLOAD_PENDING_RETRY, not failed."""
job = _job("dl1", JobStatus.DOWNLOADING_AUDIO, minutes_stale=15, source_name="RED")
mock_jm = _mock_jm(downloading=[_doc("dl1", JobStatus.DOWNLOADING_AUDIO)], jobs={"dl1": job})
resp, _ = _run(client, mock_jm)
data = resp.json()
assert data["download_parked_jobs"] == ["dl1"]
assert data["recovered_count"] == 0
assert mock_jm.transition_to_state.call_args.kwargs["new_status"] == JobStatus.DOWNLOAD_PENDING_RETRY
mock_jm.fail_job.assert_not_called()
def test_stuck_nontorrent_download_is_failed(client):
"""A stuck YouTube download still fails (deterministic source, no auto-retry)."""
job = _job("dl2", JobStatus.DOWNLOADING_AUDIO, minutes_stale=15, source_name="YouTube")
mock_jm = _mock_jm(downloading=[_doc("dl2", JobStatus.DOWNLOADING_AUDIO)], jobs={"dl2": job})
resp, _ = _run(client, mock_jm)
data = resp.json()
assert data["recovered_jobs"] == ["dl2"]
assert data["download_parked_jobs"] == []
mock_jm.fail_job.assert_called_once()
def test_parked_download_is_retriggered(client):
"""A parked download within 24h is re-triggered."""
job = _job("dl3", JobStatus.DOWNLOAD_PENDING_RETRY,
download_retry={"first_seen_at": (datetime.now(timezone.utc) - timedelta(hours=2)).isoformat(),
"attempt_count": 3})
mock_jm = _mock_jm(pending=[_doc("dl3", JobStatus.DOWNLOAD_PENDING_RETRY)], jobs={"dl3": job})
resp, mock_ws = _run(client, mock_jm)
data = resp.json()
assert data["download_retried_jobs"] == ["dl3"]
mock_ws.trigger_audio_download_worker.assert_awaited_once_with("dl3")
def test_parked_download_retry_cap_counts_failed_dispatches(client):
"""Dispatch attempts count against the per-tick cap even when the audio
worker trigger fails, so an outage can't fan out to every queried job."""
import backend.api.routes.internal as mod
fresh = (datetime.now(timezone.utc) - timedelta(hours=1)).isoformat()
n = mod.DOWNLOAD_RETRIES_PER_TICK + 5
docs = [_doc(f"p{i}", JobStatus.DOWNLOAD_PENDING_RETRY) for i in range(n)]
jobs = {f"p{i}": _job(f"p{i}", JobStatus.DOWNLOAD_PENDING_RETRY,
download_retry={"first_seen_at": fresh, "attempt_count": 1})
for i in range(n)}
mock_jm = _mock_jm(pending=docs, jobs=jobs)
mock_ws = MagicMock()
# Every dispatch raises → helper returns False, but attempts must still be capped.
mock_ws.trigger_audio_download_worker = AsyncMock(side_effect=RuntimeError("audio worker down"))
with patch("backend.api.routes.internal.JobManager", return_value=mock_jm), \
patch("backend.services.worker_service.get_worker_service", return_value=mock_ws):
resp = client.post("/api/internal/recover-stuck-jobs")
assert resp.status_code == 200
# No more than the per-tick cap of dispatch attempts, despite n>cap parked jobs.
assert mock_ws.trigger_audio_download_worker.await_count == mod.DOWNLOAD_RETRIES_PER_TICK
assert resp.json()["download_retried_jobs"] == [] # all dispatches failed
def test_parked_download_times_out_after_24h(client):
"""A parked download older than 24h is permanently failed."""
job = _job("dl4", JobStatus.DOWNLOAD_PENDING_RETRY,
download_retry={"first_seen_at": (datetime.now(timezone.utc) - timedelta(hours=25)).isoformat(),
"attempt_count": 40})
mock_jm = _mock_jm(pending=[_doc("dl4", JobStatus.DOWNLOAD_PENDING_RETRY)], jobs={"dl4": job})
resp, mock_ws = _run(client, mock_jm)
data = resp.json()
assert data["download_timed_out_jobs"] == ["dl4"]
assert data["download_retried_jobs"] == []
mock_jm.fail_job.assert_called_once()
mock_ws.trigger_audio_download_worker.assert_not_awaited()
def test_orphaned_render_is_reparked(client):
"""A render stale >45 min is re-parked into RENDER_PENDING_CAPACITY."""
job = _job("r1", JobStatus.RENDERING_VIDEO, minutes_stale=60)
mock_jm = _mock_jm(rendering=[_doc("r1", JobStatus.RENDERING_VIDEO)], jobs={"r1": job})
resp, _ = _run(client, mock_jm)
data = resp.json()
assert data["reparked_render_jobs"] == ["r1"]
assert mock_jm.transition_to_state.call_args.kwargs["new_status"] == JobStatus.RENDER_PENDING_CAPACITY
meta = mock_jm.update_state_data.call_args.args[2]
assert meta["last_code"] == "render_stalled"
def test_fresh_render_not_reparked(client):
"""A render updated 10 min ago is NOT re-parked."""
job = _job("r2", JobStatus.RENDERING_VIDEO, minutes_stale=10)
mock_jm = _mock_jm(rendering=[_doc("r2", JobStatus.RENDERING_VIDEO)], jobs={"r2": job})
resp, _ = _run(client, mock_jm)
assert resp.json()["reparked_render_count"] == 0
mock_jm.transition_to_state.assert_not_called()
+15
View File
@@ -662,6 +662,21 @@ class TestSummaryEndpoint:
'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_summary_projection_includes_made_for_you(self):
"""Verify SUMMARY_FIELD_PATHS includes made_for_you (and customer_email).
The dashboard needs made_for_you in the summary payload so it can keep
made-for-you orders (which sit at awaiting_audio_selection) visible as
cards instead of filtering them out with self-service guided-flow jobs.
"""
from backend.services.firestore_service import FirestoreService
paths = FirestoreService.SUMMARY_FIELD_PATHS
assert 'made_for_you' in paths, (
"'made_for_you' must be in summary projection so the dashboard can "
"surface made-for-you orders awaiting audio selection"
)
assert 'customer_email' in paths
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
@@ -2049,3 +2049,86 @@ class TestStageOriginalAudio:
# Must not raise
orch._stage_original_audio_for_upload()
assert any("Original audio" in w for w in orch.result.distribution_warnings)
class TestOriginalVocalsGuideEmit:
"""The write-path emit of the padded original-vocals guide at finalize."""
def _orch(self, brand="NOMAD-1500", video_720p=None, job_manager=None):
config = OrchestratorConfig(
job_id="job-1", artist="A", title="B",
title_video_path="/t.mov", karaoke_video_path="/k.mov",
instrumental_audio_path="/a.flac",
)
orch = VideoWorkerOrchestrator(config, job_manager=job_manager, storage=MagicMock())
orch.result.brand_code = brand
orch.result.final_video_720p = video_720p
return orch
@pytest.mark.asyncio
async def test_emit_skips_non_nomad(self, tmp_path):
v = tmp_path / "v.mp4"; v.write_bytes(b"x")
orch = self._orch(brand="VOCALSTAR-1", video_720p=str(v))
assert await orch._emit_original_vocals_guide("VOCALSTAR-1") is None
orch.storage.download_file.assert_not_called()
@pytest.mark.asyncio
async def test_emit_none_when_no_720p(self):
orch = self._orch(brand="NOMAD-1500", video_720p=None)
assert await orch._emit_original_vocals_guide("NOMAD-1500") is None
@pytest.mark.asyncio
async def test_emit_builds_guide_for_nomad(self, tmp_path):
v = tmp_path / "v.mp4"; v.write_bytes(b"video")
orch = self._orch(brand="NOMAD-1500", video_720p=str(v), job_manager=None)
with patch("backend.services.original_vocals_guide.build_original_vocals_guide",
return_value="/tmp/guide.flac") as mb, \
patch("backend.services.original_vocals_guide.probe_duration", return_value=200.0):
out = await orch._emit_original_vocals_guide("NOMAD-1500")
assert out == "/tmp/guide.flac"
# The mixed-vocals stem is pulled from the job's GCS stems path.
assert orch.storage.download_file.call_args[0][0] == "jobs/job-1/stems/vocals_clean.flac"
# Built with the resolved intro (5s fallback, no job_manager) capped to master dur.
assert mb.call_args[0][1] == 5.0
assert mb.call_args.kwargs.get("master_duration") == 200.0
@pytest.mark.asyncio
async def test_emit_none_when_stem_download_fails(self, tmp_path):
v = tmp_path / "v.mp4"; v.write_bytes(b"video")
orch = self._orch(brand="NOMAD-1500", video_720p=str(v))
orch.storage.download_file.side_effect = RuntimeError("gone")
assert await orch._emit_original_vocals_guide("NOMAD-1500") is None
@pytest.mark.asyncio
async def test_resolve_intro_seconds_defaults_to_5_without_job_manager(self):
orch = self._orch(job_manager=None)
assert await orch._resolve_intro_seconds() == 5.0
@pytest.mark.asyncio
async def test_resolve_intro_seconds_preserves_explicit_zero(self):
# A style with no title card (video_duration=0) must NOT collapse to the 5s
# default — that would push the guide's vocals 5s late.
orch = self._orch(job_manager=MagicMock())
orch.job_manager.get_job.return_value = MagicMock()
fake_style = MagicMock()
fake_style.get_intro_format.return_value = {"video_duration": 0}
async def fake_load(*a, **k):
return fake_style
with patch("backend.workers.style_helper.load_style_config", side_effect=fake_load):
assert await orch._resolve_intro_seconds() == 0.0
@pytest.mark.asyncio
async def test_resolve_intro_seconds_honors_long_intro_style(self):
# A long-intro style (e.g. 8s) must be read, not assumed to be 5s.
orch = self._orch(job_manager=MagicMock())
orch.job_manager.get_job.return_value = MagicMock()
fake_style = MagicMock()
fake_style.get_intro_format.return_value = {"video_duration": 8}
async def fake_load(*a, **k):
return fake_style
with patch("backend.workers.style_helper.load_style_config", side_effect=fake_load):
assert await orch._resolve_intro_seconds() == 8.0
+337
View File
@@ -0,0 +1,337 @@
"""
Regression tests for the admin-reset / render race (job 7f457087).
Scenario: an operator hits the admin "Review" reset button while a render is
still in flight. The render finishes a moment later and attempts its normal
terminal transition (rendering_video -> instrumental_selected), which is now
illegal because the job was reset back to review. Previously this raised
InvalidStateTransitionError, was caught by the worker's generic handler, and
flipped a perfectly-good reset to `failed` with the confusing message:
Video render failed: Invalid state transition for job 7f457087:
in_review -> instrumental_selected
These tests lock in the hardened behaviour:
* A superseded render (status reset OR generation bumped) is discarded
quietly — it must NOT call fail_job and must NOT write stale outputs.
* An InvalidStateTransitionError at the terminal step is treated as
supersession (graceful bail), never a job failure.
* A normal, un-superseded render still transitions to INSTRUMENTAL_SELECTED.
"""
from unittest.mock import MagicMock, patch, AsyncMock
import pytest
from backend.models.job import JobStatus
from backend.exceptions import InvalidStateTransitionError
from backend.workers.supersede import capture_generation, check_superseded
# ---------------------------------------------------------------------------
# supersede helper unit tests
# ---------------------------------------------------------------------------
def _job(generation=0, status=JobStatus.RENDERING_VIDEO):
job = MagicMock()
job.state_data = {"worker_generation": generation}
job.status = status
return job
def test_capture_generation_defaults_to_zero():
job = MagicMock()
job.state_data = {}
assert capture_generation(job) == 0
job.state_data = None
assert capture_generation(job) == 0
def test_check_superseded_none_when_current():
jm = MagicMock()
jm.get_job.return_value = _job(generation=3, status=JobStatus.RENDERING_VIDEO)
assert check_superseded(jm, "j", 3, {JobStatus.RENDERING_VIDEO}) is None
def test_check_superseded_detects_generation_bump():
jm = MagicMock()
jm.get_job.return_value = _job(generation=4, status=JobStatus.RENDERING_VIDEO)
reason = check_superseded(jm, "j", 3, {JobStatus.RENDERING_VIDEO})
assert reason and "generation" in reason
def test_check_superseded_detects_status_reset():
jm = MagicMock()
# Status strings are how Job.status deserialises (use_enum_values=True)
jm.get_job.return_value = _job(generation=3, status="awaiting_review")
reason = check_superseded(jm, "j", 3, {JobStatus.RENDERING_VIDEO})
assert reason and "status" in reason
def test_check_superseded_when_job_deleted():
jm = MagicMock()
jm.get_job.return_value = None
assert check_superseded(jm, "j", 0, {JobStatus.RENDERING_VIDEO})
# ---------------------------------------------------------------------------
# JobManager.bump_worker_generation
# ---------------------------------------------------------------------------
def test_bump_worker_generation_uses_atomic_increment():
from backend.services.job_manager import JobManager
jm = JobManager.__new__(JobManager) # bypass __init__/Firestore connect
jm.firestore = MagicMock()
# Post-increment read reflects Increment(1) applied to a job at generation 5.
bumped_job = MagicMock()
bumped_job.state_data = {"worker_generation": 6}
jm.get_job = MagicMock(return_value=bumped_job)
# Patch the Increment symbol the production code imports so this assertion is
# robust even when another test has replaced the firestore_v1 module with a
# mock (real-vs-mock class identity would otherwise flake in the full suite).
with patch("google.cloud.firestore_v1.Increment") as mock_incr:
mock_incr.return_value = "INCREMENT(1)"
result = jm.bump_worker_generation("job-x")
# The returned value is informational (logging only) — workers never consume
# it as a token; they compare their captured generation against the current
# one. Correctness therefore only needs the fence to CHANGE, not to hand back
# a unique per-dispatch token, so concurrent bumps sharing a read are benign.
assert result == 6
mock_incr.assert_called_once_with(1) # atomic +1, not a read-modify-write
args, _ = jm.firestore.update_job.call_args
payload = args[1]
assert payload["state_data.worker_generation"] == "INCREMENT(1)"
def test_bump_worker_generation_is_best_effort():
"""A failed bump must never raise — the status fence still protects us."""
from backend.services.job_manager import JobManager
jm = JobManager.__new__(JobManager)
jm.firestore = MagicMock()
jm.firestore.update_job.side_effect = RuntimeError("firestore down")
jm.get_job = MagicMock()
assert jm.bump_worker_generation("job-x") is None
# ---------------------------------------------------------------------------
# render worker (GCE path) supersession behaviour
# ---------------------------------------------------------------------------
def _render_job(generation=1):
job = MagicMock()
job.artist = "John Maus"
job.title = "The Fear"
job.input_media_gcs_path = "jobs/test/audio.flac"
job.style_assets = {}
job.style_params_gcs_path = None
job.subtitle_offset_ms = 0
job.prep_only = False
job.state_data = {"worker_generation": generation, "is_duet": False}
job.file_urls = {}
job.status = JobStatus.RENDERING_VIDEO
return job
def _gce_result():
return {
"output_files": ["gs://test-bucket/jobs/test/videos/with_vocals.mkv"],
"metadata": {},
}
async def _run_gce_render(job_start, job_after, transition_side_effect=None):
"""Drive process_render_video down the GCE path with controlled get_job snapshots."""
from backend.workers import render_video_worker as rvw
jm = MagicMock()
seq = [job_start]
def _get_job(_job_id):
return seq.pop(0) if seq else job_after
jm.get_job.side_effect = _get_job
if transition_side_effect is not None:
jm.transition_to_state.side_effect = transition_side_effect
else:
jm.transition_to_state.return_value = True
encoding_service = MagicMock()
encoding_service.is_enabled = True
encoding_service.render_video_on_gce = AsyncMock(return_value=_gce_result())
storage = MagicMock()
storage.file_exists.return_value = False
worker_service = MagicMock()
worker_service.trigger_video_worker = AsyncMock(return_value=True)
with patch.object(rvw, "JobManager", return_value=jm), \
patch.object(rvw, "StorageService", return_value=storage), \
patch.object(rvw, "get_settings"), \
patch.object(rvw, "create_job_logger", return_value=MagicMock()), \
patch.object(rvw, "setup_job_logging", return_value=MagicMock()), \
patch.object(rvw, "validate_worker_can_run", return_value=None), \
patch.object(rvw, "get_encoding_service", return_value=encoding_service), \
patch("backend.services.worker_service.get_worker_service", return_value=worker_service):
result = await rvw.process_render_video("7f457087")
return result, jm
@pytest.mark.asyncio
async def test_render_superseded_by_status_reset_does_not_fail_job():
"""Admin reset moved the job to awaiting_review mid-render → discard, don't fail."""
job_start = _render_job(generation=1)
job_after = _render_job(generation=1)
job_after.status = "awaiting_review" # reset out from under the render
result, jm = await _run_gce_render(job_start, job_after)
assert result is False
jm.fail_job.assert_not_called()
# No stale outputs written and no terminal INSTRUMENTAL_SELECTED transition
jm.update_file_url.assert_not_called()
instrumental_transitions = [
c for c in jm.transition_to_state.call_args_list
if c.kwargs.get("new_status") == JobStatus.INSTRUMENTAL_SELECTED
]
assert not instrumental_transitions
@pytest.mark.asyncio
async def test_render_superseded_by_generation_bump_does_not_fail_job():
"""A newer render was triggered (generation bumped) → discard the stale run."""
job_start = _render_job(generation=1)
job_after = _render_job(generation=2) # newer run took over
result, jm = await _run_gce_render(job_start, job_after)
assert result is False
jm.fail_job.assert_not_called()
jm.update_file_url.assert_not_called()
@pytest.mark.asyncio
async def test_invalid_terminal_transition_is_graceful_when_superseded():
"""
The reset lands during the terminal transition itself: transition_to_state
raises InvalidStateTransitionError AND a re-read confirms supersession (the
reset moved the job to awaiting_review). The worker must bail gracefully,
exactly reproducing and fixing the 7f457087 incident.
"""
job_start = _render_job(generation=1)
job_after = _render_job(generation=1)
job_after.status = "awaiting_review" # reset confirmed on re-read in the handler
invalid = InvalidStateTransitionError(
"Invalid state transition for job 7f457087: in_review -> instrumental_selected",
job_id="7f457087",
from_status="in_review",
to_status="instrumental_selected",
valid_transitions=["review_complete", "awaiting_review", "failed"],
)
# 1st transition (RENDERING_VIDEO) ok, 2nd (INSTRUMENTAL_SELECTED) raises
result, jm = await _run_gce_render(
job_start, job_after, transition_side_effect=[True, invalid]
)
assert result is False
jm.fail_job.assert_not_called()
@pytest.mark.asyncio
async def test_invalid_transition_when_not_superseded_still_fails():
"""
An InvalidStateTransitionError that is NOT explained by supersession is a real
workflow defect — it must still fail the job (loudly) rather than be silently
swallowed and leave the job stuck. Guards against over-broad error suppression.
"""
job_start = _render_job(generation=1)
job_after = _render_job(generation=1) # same gen + still rendering_video => NOT superseded
invalid = InvalidStateTransitionError(
"Invalid state transition for job x: rendering_video -> instrumental_selected",
job_id="x",
)
result, jm = await _run_gce_render(
job_start, job_after, transition_side_effect=[True, invalid]
)
assert result is False
jm.fail_job.assert_called_once()
@pytest.mark.asyncio
async def test_progress_callback_skips_update_when_superseded():
"""A stale render's progress ticks must not drag a reset job's progress bar."""
from backend.workers import render_video_worker as rvw
job_start = _render_job(generation=1)
superseded = _render_job(generation=2) # reset bumped the fence mid-render
jm = MagicMock()
calls = {"n": 0}
def _get_job(_job_id):
calls["n"] += 1
return job_start if calls["n"] == 1 else superseded
jm.get_job.side_effect = _get_job
jm.transition_to_state.return_value = True
async def _render(_job_id, _config, progress_callback=None):
progress_callback(50) # encoder emits a tick on the now-stale job
return _gce_result()
encoding_service = MagicMock()
encoding_service.is_enabled = True
encoding_service.render_video_on_gce = AsyncMock(side_effect=_render)
storage = MagicMock()
storage.file_exists.return_value = False
with patch.object(rvw, "JobManager", return_value=jm), \
patch.object(rvw, "StorageService", return_value=storage), \
patch.object(rvw, "get_settings"), \
patch.object(rvw, "create_job_logger", return_value=MagicMock()), \
patch.object(rvw, "setup_job_logging", return_value=MagicMock()), \
patch.object(rvw, "validate_worker_can_run", return_value=None), \
patch.object(rvw, "get_encoding_service", return_value=encoding_service):
result = await rvw.process_render_video("7f457087")
assert result is False # bails after render (superseded)
jm.fail_job.assert_not_called()
# No progress write happened during the superseded tick
progress_writes = [
c for c in jm.update_job.call_args_list
if len(c.args) > 1 and isinstance(c.args[1], dict) and "progress" in c.args[1]
]
assert not progress_writes, "Superseded render must not stamp progress onto the job"
@pytest.mark.asyncio
async def test_normal_render_still_completes():
"""Un-superseded render must still write outputs and transition to INSTRUMENTAL_SELECTED."""
job_start = _render_job(generation=1)
job_after = _render_job(generation=1) # same gen, still rendering_video
result, jm = await _run_gce_render(job_start, job_after)
assert result is True
jm.fail_job.assert_not_called()
instrumental_transitions = [
c for c in jm.transition_to_state.call_args_list
if c.kwargs.get("new_status") == JobStatus.INSTRUMENTAL_SELECTED
]
assert instrumental_transitions, "Normal render must reach INSTRUMENTAL_SELECTED"
# with_vocals output recorded
assert any(
c.args[1:3] == ("videos", "with_vocals")
for c in jm.update_file_url.call_args_list
)
+49 -5
View File
@@ -80,6 +80,15 @@ DOWNLOAD_ALREADY_DONE_STATUSES = frozenset({
JobStatus.CANCELLED,
})
# How long to wait for a flacfetch download before giving up. This MUST stay
# strictly below the Cloud Run task `timeout` for audio-download-job (see
# infrastructure/modules/cloud_run.py::create_audio_download_job). If they are
# equal, Cloud Run SIGKILLs the task before this timeout can fire, so the
# worker never records retry-pending or fails gracefully — leaving an in-flight
# auto-retry that races manual retries (job 1cd29294). The headroom below the
# task timeout covers the final GCS upload + state transition.
DOWNLOAD_WAIT_TIMEOUT_SECONDS = 1080 # task timeout is 1200s
def _current_task_attempt() -> int:
"""Read CLOUD_RUN_TASK_ATTEMPT env var injected by Cloud Run Jobs.
@@ -227,6 +236,22 @@ async def process_audio_download(job_id: str) -> bool:
storage_service=storage_service,
)
# Concurrency guard: a second download run may have completed while we
# were downloading — e.g. a manual /retry racing this task's Cloud Run
# auto-retry. Re-read status now (it was read once at entry, before a
# potentially minutes-long download). If another run already advanced
# the job, treat this as an idempotent success: don't re-write the input
# path, don't re-transition (that would be an invalid
# downloading -> downloading), and don't re-trigger downstream workers.
# The winning run owns all of that.
latest = job_manager.get_job(job_id)
if latest and latest.status in DOWNLOAD_ALREADY_DONE_STATUSES:
logger.info(
f"[job:{job_id}] Another run already advanced the job "
f"(status={latest.status}); skipping duplicate transition/triggers"
)
return True
# Update job with GCS path
job_manager.update_job(job_id, {
'input_media_gcs_path': audio_gcs_path,
@@ -241,13 +266,32 @@ async def process_audio_download(job_id: str) -> bool:
# previous error so the UI stops showing a resolved failure.
_clear_retry_pending_and_error(job_manager, job_id)
# Transition from DOWNLOADING_AUDIO to DOWNLOADING
job_manager.transition_to_state(
# Transition from DOWNLOADING_AUDIO (or FAILED, on recovery) to
# DOWNLOADING. Use raise_on_invalid=False so a tight race that slipped
# past the guard above (another run advancing the job between our
# re-read and here) does NOT raise into the generic except and fail_job
# a job another run already succeeded on.
transitioned = job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.DOWNLOADING,
progress=15,
message="Audio downloaded, starting processing"
message="Audio downloaded, starting processing",
raise_on_invalid=False,
)
if not transitioned:
latest = job_manager.get_job(job_id)
if latest and latest.status in DOWNLOAD_ALREADY_DONE_STATUSES:
logger.info(
f"[job:{job_id}] Concurrent run advanced job during transition "
f"(status={latest.status}); treating as idempotent success"
)
return True
# Genuinely unexpected state (not a concurrency case) — surface it
# through the normal failure path so retry-pending is recorded.
raise DownloadError(
f"Could not transition to DOWNLOADING "
f"(status={latest.status if latest else 'missing'})"
)
# Check if audio editing was requested — enter blocking state instead of processing
job = job_manager.get_job(job_id)
@@ -423,7 +467,7 @@ async def _download_torrent(
final_status = await flacfetch_client.wait_for_download(
download_id,
timeout=600,
timeout=DOWNLOAD_WAIT_TIMEOUT_SECONDS,
)
filepath = final_status.get("gcs_path") or final_status.get("output_path")
@@ -461,7 +505,7 @@ async def _download_spotify(
final_status = await flacfetch_client.wait_for_download(
download_id,
timeout=600,
timeout=DOWNLOAD_WAIT_TIMEOUT_SECONDS,
)
filepath = final_status.get("gcs_path") or final_status.get("output_path")
+120
View File
@@ -35,9 +35,11 @@ from typing import Optional, Dict, Any
from dataclasses import dataclass
from backend.models.job import JobStatus
from backend.exceptions import InvalidStateTransitionError
from backend.services.job_manager import JobManager
from backend.services.storage_service import StorageService
from backend.services.job_health_service import validate_worker_can_run
from backend.workers.supersede import capture_generation, check_superseded
from backend.config import get_settings
from backend.workers.registry import worker_registry
from backend.workers.worker_logging import create_job_logger, setup_job_logging, job_logging_context
@@ -57,6 +59,10 @@ RENDER_WORKER_SHUTDOWN_CODE = "WORKER_SHUTDOWN"
# Import from lyrics_transcriber (submodule)
from karaoke_gen.lyrics_transcriber.output.generator import OutputGenerator
from karaoke_gen.lyrics_transcriber.output.countdown_processor import CountdownProcessor
from karaoke_gen.lyrics_transcriber.output.timing_validation import (
LyricsTimingError,
validate_segment_timing,
)
from karaoke_gen.lyrics_transcriber.types import CorrectionResult
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
from karaoke_gen.lyrics_transcriber.core.config import OutputConfig
@@ -119,6 +125,12 @@ async def process_render_video(job_id: str) -> bool:
job_log.error(f"Job {job_id} not found in Firestore!")
return False
# Capture the supersession fence at start. If an admin reset (or a newer
# render trigger) advances the generation while we render, our result is
# stale and must be discarded instead of overwriting fresh outputs or
# failing the job. See backend/workers/supersede.py.
captured_generation = capture_generation(job)
# Validate job status is appropriate for render video worker
# This helps catch bugs where the worker is triggered incorrectly
status_error = validate_worker_can_run("render_video_worker", job)
@@ -195,6 +207,16 @@ async def process_render_video(job_id: str) -> bool:
# gets logged via the error monitor, and (2) flood the
# timeline with redundant "transitioned" events for
# every tick.
#
# Supersession guard: if the job was reset/cancelled or a
# newer render took over while this (now stale) render is
# still emitting ticks, don't stamp our progress onto the
# job — that would drag a reset job's progress bar back to
# ~75-82% while it sits in awaiting_review.
if check_superseded(
job_manager, job_id, captured_generation, {JobStatus.RENDERING_VIDEO}
):
return
scaled = 75 + int(progress * 0.07) # Map 0-100 to 75-82
job_manager.update_job(job_id, {
'progress': scaled,
@@ -212,6 +234,30 @@ async def process_render_video(job_id: str) -> bool:
job_log.info(f"GCE render_video complete in {render_duration:.1f}s")
logger.info(f"[job:{job_id}] GCE render_video complete in {render_duration:.1f}s")
# Supersession fence: if the job was reset/cancelled or a newer
# render was triggered while we rendered, discard this stale
# result rather than recording its file_urls / transitioning
# (which would fail on an invalid terminal transition below).
#
# Residual (accepted): the GCE render already wrote the with_vocals
# object under the shared jobs/{job_id}/ prefix before this check, so
# a stale run can leave stale bytes there. A newer generation always
# re-renders and overwrites the same object, so the worst case is a
# transient stale object — never a failed job or a bad downstream
# trigger (those are blocked here + by the InvalidStateTransition
# guard). Fully closing the GCS window needs generation-scoped output
# prefixes + a conditional promote on the encoder side (follow-up).
superseded = check_superseded(
job_manager, job_id, captured_generation, {JobStatus.RENDERING_VIDEO}
)
if superseded:
job_log.warning(f"Render superseded, discarding stale GCE result: {superseded}")
logger.info(
f"[job:{job_id}] WORKER_END worker=render-video status=superseded "
f"reason={superseded}"
)
return False
# Parse response and update Firestore
output_files = result.get("output_files", [])
metadata = result.get("metadata", {})
@@ -362,6 +408,19 @@ async def process_render_video(job_id: str) -> bool:
job_log.info(f"Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
logger.info(f"Job {job_id}: Loaded CorrectionResult with {len(correction_result.corrected_segments)} segments")
# 4b. Reject untimed lyrics BEFORE any expensive work or encoder
# dispatch. Custom/replaced lyrics that were never tap-synced carry
# None start/end times and otherwise crash the encoder with a cryptic
# "'<' not supported between instances of 'NoneType' and 'float'".
# Failing here gives the user an actionable message and never sends a
# broken job to the GCE encoder (which runs its own pinned wheel).
try:
validate_segment_timing(correction_result.corrected_segments)
except LyricsTimingError as timing_err:
job_log.error(f"Render rejected — lyrics not synchronized: {timing_err}")
logger.error(f"Job {job_id}: Render rejected — lyrics not synchronized: {timing_err}")
raise ValueError(str(timing_err)) from timing_err
# 5. Download audio file
audio_path = os.path.join(temp_dir, "audio.flac")
audio_gcs_path = job.input_media_gcs_path
@@ -462,6 +521,31 @@ async def process_render_video(job_id: str) -> bool:
title=job.title
)
# Supersession fence: bail before overwriting outputs if
# the job was reset/cancelled or a newer render started
# while we rendered (mirrors the GCE path above).
#
# Same accepted residual as the GCE path: earlier writes in
# this path (lyrics_metadata countdown padding, GCS objects
# under the shared jobs/{job_id}/ prefix) can still land on a
# newer generation in the narrow window before this check. A
# newer render re-renders and overwrites them, and the
# InvalidStateTransition guard blocks any bad downstream
# trigger, so the worst case is transient stale bytes/metadata.
# Fully closing it needs generation-scoped output paths +
# conditional promote (deferred follow-up). NB: prod renders
# via the GCE path; this local path is dev/fallback only.
superseded = check_superseded(
job_manager, job_id, captured_generation, {JobStatus.RENDERING_VIDEO}
)
if superseded:
job_log.warning(f"Render superseded, discarding stale local result: {superseded}")
logger.info(
f"[job:{job_id}] WORKER_END worker=render-video status=superseded "
f"reason={superseded}"
)
return False
# 9. Upload video to GCS
if outputs.video and os.path.exists(outputs.video):
video_size = os.path.getsize(outputs.video)
@@ -567,6 +651,42 @@ async def process_render_video(job_id: str) -> bool:
)
_park_job_for_capacity_retry(job_manager, job_id, e)
return False
except InvalidStateTransitionError as e:
# Safety net for the reset race: if our terminal transition became illegal
# because the job was reset/cancelled out from under us mid-render (e.g.
# admin "Review" reset while rendering_video -> the transition to
# instrumental_selected is no longer valid), the operator moved the job
# deliberately. Discard our stale result quietly instead of clobbering
# their reset with a spurious "failed" (the original 7f457087 incident).
#
# But an InvalidStateTransitionError does NOT by itself prove supersession
# — it also fires for genuine workflow defects (a bad initial transition,
# a state-machine bug). CONFIRM supersession before swallowing the error;
# otherwise fall through to the real failure path so a non-superseded job
# surfaces instead of silently stalling.
duration = time.time() - start_time
supersede_reason = check_superseded(
job_manager, job_id, captured_generation, {JobStatus.RENDERING_VIDEO}
)
if supersede_reason:
job_log.warning(
f"Render superseded mid-transition, discarding stale result: "
f"{supersede_reason} ({e})"
)
logger.info(
f"[job:{job_id}] WORKER_END worker=render-video status=superseded "
f"duration={duration:.1f}s reason={supersede_reason}"
)
return False
# Not superseded: this is a real defect, not the reset race. Fail loudly.
error_text = str(e) or repr(e)
job_log.error(f"Video render failed (unexpected invalid transition): {error_text}")
logger.error(
f"[job:{job_id}] WORKER_END worker=render-video status=error "
f"duration={duration:.1f}s error={error_text}"
)
job_manager.fail_job(job_id, f"Video render failed: {error_text}")
return False
except Exception as e:
duration = time.time() - start_time
# Use repr() so empty-string exceptions still produce a useful message;
+89
View File
@@ -0,0 +1,89 @@
"""
Worker supersession fencing.
A long-running worker (render-video, video) can be "superseded" mid-flight when
an operator resets the job (admin "Review"/"Audio"/"Reprocess" buttons), a user
cancels it, or a newer run of the same stage is triggered. When that happens the
worker's result is stale and must be DISCARDED — not written back and, above all,
not used to fail a job the operator deliberately moved.
Two independent nets detect supersession:
1. Status fence (Layer A) — the job is no longer in a status this worker owns.
Catches admin resets that move the job backwards (e.g. rendering_video ->
awaiting_review) even when no new worker has been triggered yet.
2. Generation fence (Layer B) — ``state_data.worker_generation`` is bumped every
time a render/video worker is triggered. A worker captures the generation at
start; if it later differs, a newer run has taken over. This closes the race
where a stale run finishes just after a new one started and would otherwise
overwrite the newer run's outputs.
Together these guarantee that no sequence of admin resets / re-submissions can
push a job into an invalid state or clobber a fresher render.
"""
from typing import Iterable, Optional
from backend.models.job import JobStatus
def capture_generation(job) -> int:
"""Read the worker-generation fence off a job snapshot (0 if unset)."""
state_data = getattr(job, "state_data", None) or {}
try:
return int(state_data.get("worker_generation", 0) or 0)
except (TypeError, ValueError):
return 0
def _normalize_status(status) -> Optional[JobStatus]:
"""Job.status is deserialised with use_enum_values=True (a plain str)."""
if isinstance(status, JobStatus):
return status
try:
return JobStatus(status)
except (ValueError, TypeError):
return None
def check_superseded(
job_manager,
job_id: str,
captured_generation: int,
expected_statuses: Iterable[JobStatus],
) -> Optional[str]:
"""
Re-read the job and decide whether this worker has been superseded.
Args:
job_manager: JobManager instance (re-reads fresh from Firestore).
job_id: Job being processed.
captured_generation: Value from :func:`capture_generation` at worker start.
expected_statuses: Statuses this worker legitimately owns right now.
Returns:
A human-readable reason string if superseded, else ``None``.
"""
job = job_manager.get_job(job_id)
if job is None:
return "job no longer exists"
current_generation = capture_generation(job)
if current_generation != captured_generation:
return (
f"worker generation changed "
f"({captured_generation} -> {current_generation}) — a newer run took over"
)
status = _normalize_status(job.status)
expected = set(expected_statuses)
if status not in expected:
status_value = status.value if status else repr(job.status)
expected_values = sorted(s.value for s in expected)
return (
f"job status is {status_value}, no longer one of {expected_values} "
f"(reset or cancelled out from under this worker)"
)
return None
+26 -1
View File
@@ -32,6 +32,7 @@ from typing import Optional, Dict, Any
from pathlib import Path
from backend.models.job import JobStatus
from backend.exceptions import InvalidStateTransitionError
from backend.services.job_manager import JobManager
from backend.services.storage_service import StorageService
from backend.services.job_health_service import validate_worker_can_run
@@ -423,6 +424,18 @@ async def generate_video_orchestrated(job_id: str) -> bool:
job_manager.update_state_data(job_id, 'video_progress', {'stage': 'complete'})
return True
except InvalidStateTransitionError as e:
# The job was reset/cancelled out from under us mid-encode (e.g. admin
# reset while generating_video/encoding). Discard our stale result quietly
# rather than failing a job the operator deliberately moved. See
# backend/workers/supersede.py and render_video_worker for the same guard.
duration = time.time() - start_time
logger.info(
f"[job:{job_id}] WORKER_END worker=video orchestrator=true status=superseded "
f"duration={duration:.1f}s reason={e}"
)
return False
except Exception as e:
duration = time.time() - start_time
logger.error(f"[job:{job_id}] WORKER_END worker=video orchestrator=true status=error duration={duration:.1f}s error={e}")
@@ -957,6 +970,17 @@ async def generate_video_legacy(job_id: str) -> bool:
job_manager.update_state_data(job_id, 'video_progress', {'stage': 'complete'})
return True
except InvalidStateTransitionError as e:
# Job reset/cancelled out from under us mid-encode — discard the stale
# result quietly instead of failing the operator's reset (see the
# orchestrated path and render_video_worker for the same guard).
duration = time.time() - start_time
logger.info(
f"[job:{job_id}] WORKER_END worker=video status=superseded "
f"duration={duration:.1f}s reason={e}"
)
return False
except Exception as e:
duration = time.time() - start_time
logger.error(f"[job:{job_id}] WORKER_END worker=video status=error duration={duration:.1f}s error={e}")
@@ -966,7 +990,7 @@ async def generate_video_legacy(job_id: str) -> bool:
error_details={"stage": "video_generation", "error": str(e)}
)
return False
finally:
# Restore original working directory
os.chdir(original_cwd)
@@ -1123,6 +1147,7 @@ async def _handle_native_distribution(
brand_code=upload_brand_code,
base_name=base_name,
output_files=output_files,
warnings=result.setdefault('distribution_warnings', []),
)
result['gdrive_files'] = uploaded
@@ -871,11 +871,19 @@ class VideoWorkerOrchestrator:
'final_karaoke_cdg_zip': self.result.final_karaoke_cdg_zip,
}
# Emit the padded original-vocals guide for public NOMAD releases so kjbox can
# layer it under the master at the "Original Vocals" slider. Best-effort: a
# failure just omits the guide (the upload layer pushes it if present).
guide_path = await self._emit_original_vocals_guide(brand_code)
if guide_path:
output_files['original_vocals_guide'] = guide_path
uploaded = gdrive.upload_to_public_share(
root_folder_id=self.config.gdrive_folder_id,
brand_code=brand_code,
base_name=base_name,
output_files=output_files,
warnings=self.result.distribution_warnings,
)
self.result.gdrive_files = uploaded
@@ -886,6 +894,78 @@ class VideoWorkerOrchestrator:
self.result.distribution_warnings.append(f"Google Drive upload failed: {e}")
# Don't fail the pipeline - GDrive is optional
async def _emit_original_vocals_guide(self, brand_code) -> Optional[str]:
"""Build the padded original-vocals guide (silence[intro] + mixed_vocals, capped to
the master's duration) for a public NOMAD release, and return its local path.
The mixed-vocals stem is a byproduct of the karaoke separation (uploaded to
``jobs/{job_id}/stems/vocals_clean.flac``) and the intro offset is the job's own
style ``intro_video_duration`` — so no correlation/review is needed. Best-effort:
returns ``None`` (and never raises) for non-NOMAD brands, a missing stem, or any
build failure — the guide simply won't be distributed.
"""
try:
from backend.services.nomad_master_mirror import is_nomad_public_brand
if not is_nomad_public_brand(brand_code):
return None
master_720p = self.result.final_video_720p
if not master_720p or not os.path.exists(master_720p):
return None
if not self.storage:
return None
import tempfile
from backend.services.original_vocals_guide import (
build_original_vocals_guide,
probe_duration,
)
work_dir = tempfile.mkdtemp(prefix="vocals_guide_")
stem_gcs = f"jobs/{self.config.job_id}/stems/vocals_clean.flac"
local_stem = os.path.join(work_dir, "vocals_clean.flac")
try:
self.storage.download_file(stem_gcs, local_stem)
except Exception as e: # noqa: BLE001
self.job_log.warning(
f"Original-vocals guide: mixed-vocals stem unavailable ({stem_gcs}): {e}"
)
return None
intro_seconds = await self._resolve_intro_seconds()
master_duration = probe_duration(master_720p)
dest = os.path.join(work_dir, "original_vocals_guide.flac")
guide = build_original_vocals_guide(
local_stem, intro_seconds, dest, master_duration=master_duration
)
if guide:
self.job_log.info(
f"Built original-vocals guide for {brand_code} (intro={intro_seconds}s)"
)
return guide
except Exception as e: # noqa: BLE001 - never fatal to the pipeline
self.job_log.warning(f"Original-vocals guide emit skipped: {e}")
return None
async def _resolve_intro_seconds(self) -> float:
"""The master's silent title-card length = the job's style intro ``video_duration``
(default 5s). Read the *actual* value — long-intro styles exist. Falls back to 5s
(``get_intro_format`` raises when no theme is loaded — that's the fallback path)."""
try:
from backend.workers.style_helper import load_style_config
import tempfile
job = self.job_manager.get_job(self.config.job_id) if self.job_manager else None
if job is None:
return 5.0
style = await load_style_config(job, self.storage, tempfile.mkdtemp(prefix="style_"))
# Preserve an intentional 0 (a style with no title card); only None/absent
# falls back to the 5s default. A truthiness check would misalign the guide.
intro = style.get_intro_format().get("video_duration", 5)
return float(intro) if intro is not None else 5.0
except Exception as e: # noqa: BLE001
self.job_log.warning(f"Original-vocals guide: intro-duration lookup fell back to 5s: {e}")
return 5.0
async def _run_notifications(self):
"""Run the notifications stage (Discord)."""
self.job_log.info("Starting notifications stage")
+10 -1
View File
@@ -2,6 +2,13 @@
Base URL: `https://api.nomadkaraoke.com` (production) or `http://localhost:8000` (local)
> **Edge:** production traffic must go through `https://api.nomadkaraoke.com`
> (proxied by Cloudflare — WAF + rate limiting). The Cloud Run origin is
> **origin-locked**: requests hitting the raw `*.run.app` URL directly are
> rejected with `403` unless they carry the Cloudflare-injected `X-Edge-Auth`
> header (`/` and `/api/health*` are exempt for probes). See
> [ARCHITECTURE.md § Edge Security](ARCHITECTURE.md#edge-security-cloudflare).
## Authentication
All endpoints except `/health` and `/api/themes` require authentication.
@@ -630,7 +637,9 @@ best-effort — storage failures degrade to a normal uncached run.
`op` is `replace` | `delete` | `insert_after` (for `insert_after`, `word_ids`
holds the anchor word). Errors: `422` when no reference lyrics are available,
`400` for invalid settings, `502` when the model call fails or returns
`400` for invalid settings, `429` when the model provider is temporarily
rate-limited (transient — retryable; the service already retries with backoff
before surfacing this), `502` when the model call otherwise fails or returns
malformed output. Design/eval background:
`docs/archive/2026-06-10-lyrics-auto-correction-reeval-plan.md`.
+40 -1
View File
@@ -11,9 +11,17 @@
│ HTTPS
▼
┌─────────────────────────────────────────────────────────────────┐
│ Cloudflare edge (api.nomadkaraoke.com proxied — orange-cloud) │
│ WAF (exploit-path block) + rate limit + injects X-Edge-Auth │
│ header. See § Edge Security (Cloudflare). │
└───────────────────────────┬─────────────────────────────────────┘
│ HTTPS (SSL "full")
▼
┌─────────────────────────────────────────────────────────────────┐
│ Backend API (Cloud Run) │
│ FastAPI + Python 3.12 │
│ https://api.nomadkaraoke.com │
│ https://api.nomadkaraoke.com (origin lock: rejects direct- │
│ to-origin requests lacking X-Edge-Auth, health/root exempt) │
│ │
│ Workers: │
│ • Audio Worker - Stem separation via Cloud Run GPU (L4) │
@@ -61,6 +69,37 @@ Discord-alerting pipeline. `ChunkLoadError` after deploy triggers an automatic
hard reload; the `CrashReport` card also checks `/version.json` and shows an
"Update now" CTA when the running bundle is stale.
## Edge Security (Cloudflare)
`api.nomadkaraoke.com` is proxied through Cloudflare (orange-cloud) — the same
zone that already fronts the marketing site, `gen`, `decide`, and the tenant
portals. Cut over 2026-07-20 after a vuln-scanner hammered the previously
directly-exposed Cloud Run origin. Managed as IaC in
`infrastructure/modules/edge_security.py` (`pulumi_cloudflare`).
**Request path:** client → Cloudflare edge → Cloud Run. At the edge:
- **WAF** (`http_request_firewall_custom`) blocks exploit/secret-exposure paths
(`/.env`, `/.git/`, `/.ssh/`, `wp-config`, `/etc/passwd`, …) — uses the
`contains` operator (regex `matches` needs a Business plan; zone is Free).
- **Rate limiting** (`http_ratelimit`) — per-IP flood control (Free-plan limits:
`period=10s`, characteristics must include `cf.colo.id`). Excludes
`/api/internal/*` (scheduler/Cloud-Tasks cron).
- **Origin lock** — a Transform Rule injects a secret `X-Edge-Auth` header
(`http_request_late_transform`); the backend's `EdgeAuthMiddleware`
(`backend/middleware/edge_auth.py`, `EDGE_AUTH_MODE=enforce`) rejects public
requests lacking it, so hitting the raw `*.run.app` origin directly is blocked
(health/root exempt for Cloud Run probes). Internal callers reach the backend
via `api.nomadkaraoke.com` (Cloud Tasks use `CLOUD_RUN_SERVICE_URL`), so they
traverse the edge and carry the header.
**SSL:** zone TLS mode is **"full"** (not strict). The Cloud Run domain-mapping
managed cert cannot provision behind Cloudflare (ACME challenge not visible), but
"full" mode doesn't validate the origin cert, so the edge works and is
**renewal-safe** — no run.app Origin Rule or load balancer needed. **Never switch
the zone to "full (strict)".** Full rationale + cutover runbook:
`docs/archive/2026-07-20-edge-security-hardening-plan.md` and
`docs/archive/2026-07-20-edge-security-cutover-runbook.md`.
## Processing Pipeline
```text
+16 -2
View File
@@ -216,7 +216,7 @@ re-deploy).
## Image families
Three GCE image families are maintained by
Four GCE image families are maintained by
[`.github/workflows/build-runner-images.yml`](../.github/workflows/build-runner-images.yml):
| Family | Base | Bakes | Built on |
@@ -224,6 +224,20 @@ Three GCE image families are maintained by
| `gha-runner-general` | Debian 12 | Docker, gcloud, runner v2.332, Python 3.13 (pyenv), Node 20, Java 21, FFmpeg, Poetry | n2-standard-8, 50GB pd-balanced |
| `gha-runner-build` | Debian 12 | Same as general + pre-pulled `karaoke-backend-base`/`:latest` + `fake-gcs-server` | n2-standard-8, 50GB pd-balanced |
| `gha-runner-gpu` | Debian 12 | NVIDIA driver + CUDA 12.4, Python 3.13 (compiled), FFmpeg+libsamplerate, audio-separator models (~14GB at `/opt/audio-separator-models`) | n1-standard-4 + T4, 200GB pd-balanced |
| `gha-runner-gpu-windows` | Windows Server 2022 | NVIDIA **GRID** driver (WDDM — required for DirectML; datacenter driver = TCC = no DirectX), Python 3.12, Git, FFmpeg, Poetry, runner (win-x64), DirectML test models at `C:\audio-separator-models` | n1-standard-4 + T4, 100GB pd-balanced |
The Windows variant is provisioned by
[`runner-image-provision.ps1`](../infrastructure/scripts/runner-image-provision.ps1)
delivered via the `windows-startup-script-ps1` metadata key (Windows ignores
`startup-script`). It exists for python-audio-separator's `windows-directml`
integration tests (RoFormer-on-Windows, issue #292 there).
**Label routing**: every runner advertises `self-hosted, <os>, x64, gcp`.
Families additionally advertise `large-disk` (general/build), `docker-build`
(build), or `gpu` (GPU families). The dispatcher resolves families with
precedence windows → gpu → build → general, so jobs MUST include an OS label
in `runs-on` (`[self-hosted, linux, gpu]` / `[self-hosted, windows, gpu]`) —
GitHub schedules onto any runner whose labels are a superset of the job's.
Each image is tagged `gha-runner-<variant>-<YYYYMMDD-HHMMSS>` and joined to the
matching image family. The dispatcher always selects from the family, so the
@@ -235,7 +249,7 @@ Build cadence: monthly cron (`0 2 1 * *` UTC) + `workflow_dispatch`. Manual:
```bash
gh workflow run build-runner-images.yml -f variants=general,build
gh workflow run build-runner-images.yml -f variants=gpu
gh workflow run build-runner-images.yml # all three
gh workflow run build-runner-images.yml # all variants
```
Pulumi does **not** manage images — they're produced by the GHA workflow. The
+160
View File
@@ -6,6 +6,61 @@ Key insights for future AI agents working on this codebase.
---
## Cloudflare edge in front of Cloud Run — the SSL "dragon" (Jul 2026)
Putting `api.nomadkaraoke.com` behind Cloudflare (WAF/rate-limit/origin-lock)
surfaced several non-obvious gotchas. See `infrastructure/modules/edge_security.py`
and `docs/archive/2026-07-20-edge-security-*.md`.
- **Cloud Run domain-mapping managed certs cannot provision behind Cloudflare.**
Even with a correct grey-cloud CNAME → `ghs.googlehosted.com` (right DNS,
propagated, no CAA), Google's ACME challenge is "not visible through the public
internet" and the cert stays `pending` forever. Recreating the mapping doesn't
help. **This does not matter** because the zone SSL mode is **"full" (not
strict)**: Cloudflare encrypts to the origin but doesn't validate its cert, so
the edge works regardless and is **renewal-safe** (a never-provisioning /
never-renewing cert can't cause a 525 when the cert isn't checked). **Rule:
keep the zone on "full", never "full (strict)".** The much-feared run.app
SNI-override Origin Rule and a GCP load balancer are both unnecessary — and the
Origin Rule is blocked anyway by the zone's singleton `http_request_origin`
entrypoint (already holds a flacfetch prod rule).
- **A proxied (orange) record blocks cert issuance** (DNS points at Cloudflare,
not `ghs`) — so if you ever DO need the managed cert, create grey → provision →
flip orange. For the prod cutover this was moot: `api`'s cert already existed
and "full" mode tolerates it, so the cutover was just the grey→orange flip.
- **Cloudflare Free-plan WAF/rate-limit constraints (fail at apply time):** the
regex `matches` operator needs Business+ (use `contains`); rate-limit `period`
must be `10`s and `characteristics` MUST include `cf.colo.id` (per-colo
counting); managed OWASP ruleset is Pro+ only.
- **Origin lock without breaking internal callers:** all internal traffic (Cloud
Tasks via `CLOUD_RUN_SERVICE_URL`, schedulers, frontend) reaches the backend
through `api.nomadkaraoke.com`, so it traverses Cloudflare and carries the
injected `X-Edge-Auth` header. Validated by running the prod E2E in `warn` mode
first and confirming **zero** missing-header warnings before flipping to
`enforce`. Health/root paths are exempt (Cloud Run probes hit the origin
directly).
- **Applying from a worktree:** the prod Pulumi stack shows benign cross-worktree
Cloud Function source-archive drift (last applied from a different worktree) —
apply edge changes with `pulumi up --target <urn>` to avoid touching it. CI
does NOT auto-run `pulumi up` (apply locally before merge).
## Magic-link auth vs. email link-scanners (Jul 2026)
- **Never auto-consume a single-use token on page render.** `/auth/verify` used to
call `verifyMagicLink(token)` from a `useEffect` on mount (no user gesture) against
the state-mutating `GET /api/users/auth/verify`. Any agent that renders the page and
runs its JS — Gmail/Safe-Browsing scanners, corporate security proxies — burns the
token and creates a throwaway session, so the real user then sees "This link has
already been used." Diagnosed for one user whose links were consumed within ~60s by
Google LLC IPs (`2607:f8b0…`), his own click losing a sub-second race in Cloud Run logs.
- **Fix pattern:** gate verification behind an explicit "Complete Sign-In" click
(`frontend/app/[locale]/auth/verify/page.tsx`). Scanners render but don't click, so
the token survives. Switching GET→POST alone does NOT help — a JS-executing scanner
runs the fetch regardless of method; the user-gesture gate is the robust mitigation.
- **Still latent:** the admin one-click login path (`/app?admin_token=…`,
`frontend/app/[locale]/app/page.tsx`) auto-verifies the same way. Admin-only/low-volume,
so not yet gated — apply the same pattern if it ever bites.
## Bulk Mode (Jun 2026)
- **Auto-pick "tier 1" rule is duplicated** between `frontend/lib/audio-search-utils.ts`
@@ -1351,3 +1406,108 @@ can recover via the review UI's "Search All Providers" control with
`force_sources=["spotify"]` (registered at
`/api/review/{job_id}/search-lyrics`); no code change to the filter is
warranted.
## CJK Lyrics: Line-Splitting Must Use Display Width, Not Character Count (Jul 2026)
**Symptom:** A Japanese karaoke video (job `4dcca2d6`) rendered with lyric
lines overlapping and running off both screen edges.
**Root cause:** `SegmentResizer` gated/split lines on raw character count
(`len(text) <= max_line_length`, budget calibrated for Latin at 4K). East-Asian
*Wide/Fullwidth* glyphs render ~2.5× a Latin character, and CJK has no
inter-word spaces, so a Japanese line well under the *character* budget was ~2×
too wide for the frame. The karaoke ASS sets **no `WrapStyle`**, so libass
smart-wraps (style 0) a too-wide line onto a second physical row — which lands
on the next slot's fixed `y = first_pos + i*line_height` position and overlaps it.
**Fix:** Measure an **East-Asian display width** (`unicodedata.east_asian_width`
W/F → `WIDE_RATIO=2.7` units, else 1). For pure ASCII/Latin `display_width == len`,
so Latin/European output is byte-for-byte unchanged. Only the oversize *gate* uses
display width; wide-script segments are then split by **word-token packing**
(`_pack_words_into_lines`), which is boundary-safe (never cuts inside a multi-char
CJK token like `立ち向かう`) and counts the inter-token space the renderer emits.
**Gotchas for next time:**
- libass renders at ~0.70× the nominal ASS `Fontsize` — calibrate widths against
that effective size (`lyrics_line.ASS_FONT_SCALE`), not the nominal 250px.
- The renderer emits a space after **every** word token (`lyrics_line.py`
`transformed_text + " "`), which both inflates CJK width ~25% and is why CJK
text looks oddly spaced-out. Dropping inter-CJK spaces is a separate improvement.
- A wordless oversized segment must be **preserved**, not split — the word-matching
splitters map zero words and would return `[]`, silently dropping lyrics.
- The CJK font is a **system fallback** (Noto Sans CJK); the configured karaoke
font (Montserrat/Avenir) has no CJK glyphs. See `video_generator._find_cjk_font`.
## Long-Running Workers Must Be Fenced Against Supersession (Aug 2026)
**Symptom:** An operator reset a `rendering_video` job via the admin "Review"
button, then the job flipped itself to `failed` seconds later with *"Invalid
state transition … in_review -> instrumental_selected"* (job `7f457087`). The
reset was fine; the job died on its own.
**Root cause:** Admin reset hard-writes the status backwards but does **not**
stop the render worker already running on the encoder. When that render
finished it ran its normal terminal transition (`rendering_video ->
instrumental_selected`), now illegal, and the worker's generic `except
Exception` handler called `fail_job()` — clobbering the operator's reset. A
classic stale-worker / lost-update race: whoever finishes last wins, and the
loser is a perfectly good reset.
**Fix (v0.192.4):** Fence long-running render/video workers against
supersession with two independent nets (`backend/workers/supersede.py`):
1. **Status fence** — re-read the job before writing outputs / transitioning;
if it's no longer in the status this worker owns, discard the result.
2. **Generation fence** — `state_data.worker_generation`, atomically
`Increment`ed by every admin reset *and* every render/video trigger. A worker
captures it at start; if it later differs, a newer run took over.
Plus a targeted `except InvalidStateTransitionError` **before** the generic
handler in both workers: a terminal transition that became illegal is treated
as supersession (log + `return False`), never `fail_job()`.
**Principles for next time:**
- A worker must **never** `fail_job()` because its *own* success transition
became illegal — that only happens when something deliberately moved the job.
- Bump the fence at the **trigger choke point** (`trigger_render_video_worker` /
`trigger_video_worker`), so every run gets a unique generation without having
to hunt down every caller. Cloud Tasks/Run retries re-invoke the worker (not
the trigger), so they keep the same generation — correct, it's the same run.
- Check the fence **before writing outputs**, not just before the terminal
transition — otherwise a stale render can overwrite a newer render's video.
- Test-isolation gotcha: assert an atomic bump via
`patch("google.cloud.firestore_v1.Increment")` + `assert_called_once_with(1)`,
not `isinstance(..., Increment)` — another test in the suite replaces the
firestore module with a mock, so real-vs-mock class identity flakes.
## Server-Created Jobs Must Fit the Dashboard's UI Assumptions (Aug 2026)
**Symptom:** A paid "Made for you" Stripe order auto-created its job perfectly
(webhook → `_handle_made_for_you_order`, job `b092648c` at
`awaiting_audio_selection` with 10 audio sources found, admin notified) — yet
the operator saw *nothing* on the dashboard and re-created the job by hand,
producing a duplicate.
**Root cause:** Two UI assumptions that only hold for *self-service* jobs:
1. The dashboard filtered out **all** `awaiting_audio_selection` jobs, because
for a self-service user those are mid-wizard and owned by the guided-flow
component. Made-for-you jobs are created **server-side** by the Stripe
webhook, so they sit at that same status with **no active wizard session** —
and got silently dropped.
2. The admin notification email's "Open Job" button linked to bare `/app/`,
i.e. the exact page that filters the job out.
**Fix (v0.192.5):** `shouldShowJobOnDashboard()` keeps `made_for_you` jobs
visible at `awaiting_audio_selection` (hiding only self-service ones); added
`made_for_you`/`customer_email` to `SUMMARY_FIELD_PATHS` so the summary payload
carries the flag; the email now deep-links to
`/app/?admin_token=…&status=awaiting_audio_selection` (dashboard honors a
`status` URL param).
**Principles for next time:**
- A UI filter written for one creation path (interactive wizard) will silently
swallow items from another path (server/webhook). When adding a server-created
job that reuses an interactive status, audit every place that status is
special-cased in the frontend.
- A notification's action link must point at a view that actually **renders the
item** — verify the deep-link, don't assume "/app shows everything".
- Any field a frontend filter branches on must be in `SUMMARY_FIELD_PATHS`, or
it arrives `undefined` and the branch silently takes the wrong path.
+3
View File
@@ -43,6 +43,7 @@
| **i18n / Multilingual (frontend)** | Working (next-intl, en/es/de, 1062 strings, [locale] routing) |
| **Referral system** | Working (referral links with configurable discounts, 20% cash kickback via Stripe Connect, auto-payout at $20) |
| **Error monitor** | New (Cloud Run Job every 15 min — log collection, normalization, LLM dedup/grouping, Discord alerts, auto-resolution, daily digest) |
| **Edge security (Cloudflare)** | Working (api.nomadkaraoke.com proxied — WAF + rate limit + origin lock enforced; 2026-07-20) |
## Known Issues
@@ -54,6 +55,8 @@
## Recent Changes
- **Cloudflare Edge Security for the Backend API** (2026-07-20): `api.nomadkaraoke.com` is now proxied through Cloudflare (WAF + rate limiting + origin lock), after a vuln-scanner hammered the previously directly-exposed Cloud Run origin. WAF blocks exploit/secret-exposure paths (`contains` operator — regex needs a Business plan); per-IP rate limiting excludes `/api/internal/*`; a Transform Rule injects a secret `X-Edge-Auth` header that the backend's `EdgeAuthMiddleware` (`EDGE_AUTH_MODE=enforce`) requires, blocking direct-to-`*.run.app` bypass (health/root exempt). Key finding: the Cloud Run managed cert can't provision behind Cloudflare, but zone SSL mode "full" (not strict) doesn't validate the origin cert, so it works and is renewal-safe — **never switch the zone to "full (strict)".** Managed as IaC in `infrastructure/modules/edge_security.py`. Also retuned the "High Error Rate" alert to 5xx-only (scanner 404s no longer page). See [ARCHITECTURE.md § Edge Security](ARCHITECTURE.md#edge-security-cloudflare), [LESSONS-LEARNED.md](LESSONS-LEARNED.md#cloudflare-edge-in-front-of-cloud-run--the-ssl-dragon-jul-2026), and [archive/2026-07-20-edge-security-cutover-runbook.md](archive/2026-07-20-edge-security-cutover-runbook.md).
- **AI Auto-Correct Suggestions** (2026-06-11): Opt-in AI correction suggestions in the lyrics review UI — the third attempt at lyrics auto-correction, redesigned around the failures that led to disabling it in PR #321 (Jan 2026). One whole-song LLM call (default Gemini 3.1 Pro via Vertex, `AUTO_CORRECT_MODEL` env) compares the working transcription against reference lyrics and returns word-id-keyed suggestions; nothing is applied until the reviewer accepts each one (or accept-all) in a dedicated panel with per-row undo. New `POST /api/review/{job_id}/auto-correct` endpoint + `backend/services/auto_correct/`; frontend `useAutoCorrect` hook, `AutoCorrectModal` (knobs: adlib removal, insertions, confidence filter), `AutoCorrectPanel`. Accept/reject decisions land in the EditLog (`ai_suggestion_*` ops) to measure real accept rates. 5-model offline eval over 30 real jobs with human ground truth picked the default (Fable 5 ≈ Gemini 3.1 Pro ≫ GPT-5.2, which made lyrics worse). See [archive/2026-06-10-lyrics-auto-correction-reeval-plan.md](archive/2026-06-10-lyrics-auto-correction-reeval-plan.md).
- **Syllable-Aware Custom Lyrics** (2026-05-02): Enhanced the Custom Lyrics LLM mode with syllable-count validation and a per-line repair loop. Backend computes per-line target/candidate syllable counts via the existing `SyllablesMatchHandler` engine and re-prompts Gemini up to 3 times until lines fit budget (Δ ≤ 2 default, configurable via Verbatim/Loose/Balanced/Tight/Strict strictness). New `GenerationSettings` (`allow_reword`, `allow_omit`, `fixed_line_count`, `strictness`) exposed in the modal as a collapsible settings panel. New `CustomLyricsPreview` component shows per-line syllable annotations (target / actual / Δ) with severity badges and stop-reason banners. Variable-line-count mode (when `fixed_line_count=false`) re-times segments proportionally. Eval harness with disk-backed Gemini cache, per-line + per-fixture + corpus scorers, and 4 fixtures (1 from production, 3 handcrafted public-domain). v1-ships criteria validation (Year 5 ≥75% pass@2, macro corpus ≥70% pass@2) deferred to post-merge. See [archive/2026-05-02-custom-lyrics-syllable-aware-design.md](archive/2026-05-02-custom-lyrics-syllable-aware-design.md) and [archive/2026-05-02-custom-lyrics-syllable-aware-plan.md](archive/2026-05-02-custom-lyrics-syllable-aware-plan.md).
+39 -3
View File
@@ -8,7 +8,9 @@ Operational runbooks for known production issues.
**Cause:** Before v0.130.0, audio downloads ran as FastAPI BackgroundTasks. Cloud Run would terminate "idle" instances mid-download. Since v0.130.0, downloads use a Cloud Run Job (`audio-download-job`) and a Cloud Scheduler recovery job runs every 5 minutes to fail stuck downloads automatically.
**Auto-recovery:** The `recover-stuck-downloads` scheduler detects jobs stuck in `downloading_audio` for >10 minutes and fails them. Use the admin retry button to re-attempt.
**Auto-recovery:** The `recover-stuck-downloads` scheduler (`/api/internal/recover-stuck-jobs`, every 5 min) detects jobs stuck in `downloading_audio` for >10 minutes and, since v0.192.3:
- **Torrent sources (RED/OPS)** → parks the job in `download_pending_retry` and keeps re-attempting the download for up to **24 hours** (handles rare tracks with few/intermittent seeders and transient tracker outages), then fails permanently with a clear message. No manual action needed. See `download_pending_retry` below.
- **Other sources (YouTube/Spotify/URL)** → fails the job (deterministic); use the admin retry button to re-attempt.
**Manual recovery:**
@@ -195,9 +197,41 @@ gcloud compute instances describe encoding-worker-a \
---
## Job stuck at `rendering_video` (orphaned render)
**Symptoms:** Job frozen at `rendering_video` (step 7/10) for a long time with **no error** and **no Retry button** (it's a processing state, not `failed`).
**Cause:** The render worker started (VM up, rendering underway) then died mid-render — Cloud Run instance recycle / SIGKILL / OOM / lost GCE VM — without unregistering. `updated_at` stops advancing. Before v0.192.3 nothing recovered this: the capacity-retry cron only looks at `render_pending_capacity`, `recover-stuck-jobs` only looked at `downloading_audio`, and the render Cloud Task has finite attempts.
**Auto-recovery (v0.192.3+):** `recover-stuck-jobs` (every 5 min) now flags a job in `rendering_video` with no progress for **>45 min** (`rendering_video_stuck`) and re-parks it into `render_pending_capacity`, so the existing `retry-pending-render-jobs` cron resets it to `review_complete` and re-renders (same 24h ceiling). No manual action needed.
**Manual unstick (if needed):** don't re-trigger the render worker while status is `rendering_video` (it starts mid-state and fails with "Invalid state transition"). Instead let it fail (or re-park it), then use the admin **Retry** which resumes cleanly from `review_complete`. If a ghost `render_progress.stage='running'` blocks re-trigger, clear it first (`update({'state_data.render_progress': {'stage': 'pending'}})`).
---
## Job flips to `failed` right after an admin reset (reset/render race)
**Symptoms:** An operator hit an admin **Reset** button (e.g. "Review") on a job that was `rendering_video`, and moments later the job went to `failed` with a message like *"Video render failed: Invalid state transition for job …: in_review -> instrumental_selected"*. The reset itself looked fine, but the job died on its own.
**Cause (fixed in v0.192.4):** The reset moved the job backwards while the render worker was still running on the encoder. When that render finished it attempted its normal terminal transition (`rendering_video -> instrumental_selected`), which was now illegal, and the worker's generic error handler flipped the job to `failed` — clobbering the operator's reset. First seen on job `7f457087`.
**Auto-handling (v0.192.4+):** Long-running render/video workers are now fenced against supersession — a reset or a newer trigger causes the in-flight worker to **discard its stale result quietly** instead of failing the job. Two nets: a **status fence** (job no longer in the status the worker owns) and a **generation fence** (`state_data.worker_generation`, bumped by every reset and every render/video trigger). An `InvalidStateTransitionError` at the terminal step is treated as supersession, not failure. So resetting a rendering job is now safe at any timing — no manual action needed.
**If you still see a `failed` job from an older occurrence:** use the admin **Retry** endpoint. For a job that has corrections + screens but no committed `instrumental_selection`, it returns cleanly to `awaiting_review` so the review (and instrumental choice) can be re-submitted.
---
## Job in `download_pending_retry`
**Symptoms:** Job status is `download_pending_retry` (introduced v0.192.3), step 3/10, message *"Still finding a good source for this track — … We'll keep trying automatically for up to 24 hours; no action needed."*
**Background:** A **torrent** (RED/OPS) download stalled (few/no seeders or a brief tracker outage). Rather than dead-end the job at `failed` after ~1h, `recover-stuck-jobs` parks it here and re-triggers the download on later ticks for up to **24h**, then fails permanently with a "too rare to source right now" message. This is expected, self-healing behaviour — a seedless release simply may never complete. `state_data.download_retry` holds `{first_seen_at, attempt_count}`. To source it a different way, retry with an alternate release/source.
---
## Job stuck in `render_pending_capacity`
**Symptoms:** Job status is `render_pending_capacity` (introduced 2026-05-05). User-facing message says *"Encoding capacity is temporarily unavailable. Your job will retry automatically — no action needed."*
**Symptoms:** Job status is `render_pending_capacity` (introduced 2026-05-05). User-facing message says *"Encoding capacity is temporarily unavailable. Your job will retry automatically — no action needed."* (As of v0.192.3 a mid-render stall can also land here — see "orphaned render" above.)
**Background — what this state means:** GCE returned `ZONE_RESOURCE_POOL_EXHAUSTED` or transient `503 SERVICE_UNAVAILABLE` from `compute.instances.start` on every encoding-worker VM (primary in `us-central1-c`, plus capacity fallbacks in `-a` and `-b`). The render worker parks the job in `RENDER_PENDING_CAPACITY` instead of failing it; Cloud Scheduler retries it every 5 min via `/api/internal/retry-pending-render-jobs`. Hard timeout is 24 hours (then transitions to `failed` with a clear permanent-failure message).
@@ -230,7 +264,9 @@ done
**Configuration knobs:** `MAX_PER_TICK = 1` and `MAX_WAIT_SECONDS = 24*3600` constants in `backend/api/routes/internal.py::retry_pending_render_jobs`.
**Not an incident:** a *primary* warmup hitting `503 SERVICE_UNAVAILABLE` / capacity exhaustion is self-healing — the encoding flow's `ensure_any_running()` falls back to an alternate-zone worker and the job completes. As of 0.174.12 the `/internal/encoding-worker/warmup` endpoint logs this at **WARNING** (`"Primary encoding worker warmup failed (...); encoding will fall back..."`), specifically so it stays below the error monitor's `severity>=ERROR` filter and does **not** page Discord. Only a genuine, unexpected warmup failure (non-`EncodingWorkerStartError`) logs at ERROR. If you see the WARNING in logs with a job that still completed, no action is needed.
**Not an incident:** a *primary* warmup hitting `503 SERVICE_UNAVAILABLE` / capacity exhaustion is self-healing — the encoding flow's `ensure_any_running()` falls back to an alternate-zone worker and the job completes. As of 0.174.12 the `/internal/encoding-worker/warmup/{job_id}` endpoint logs this at **WARNING** (`"Primary encoding worker warmup failed (...); encoding will fall back..."`), specifically so it stays below the error monitor's `severity>=ERROR` filter and does **not** page Discord. Only a genuine, unexpected warmup failure (non-`EncodingWorkerStartError`) logs at ERROR. If you see the WARNING in logs with a job that still completed, no action is needed.
**403 on `/internal/encoding-worker/warmup` or `/heartbeat`:** as of 0.188.9 these endpoints are `{job_id}`-scoped and gated on `require_review_auth` (not `require_admin`). The lyrics-review page calls them on load / while editing so the encoding VM is warm by the time the reviewer previews a render. If you see 403s in the browser console, the caller lacks review access to that job — before 0.188.9 they required admin, so **every non-admin customer 403'd and the JIT pre-warm never fired** (renders paid the full cold-boot latency).
---
@@ -0,0 +1,81 @@
# Prod Error Triage & Fix — 2026-07-01
Batch of Discord error alerts, grouped, root-caused, and fixed.
## Group A (PRIMARY — job-breaking, today): render/preview crash on untimed lyrics
### Symptoms (all job `231806a4`, "Nelly Furtado - Maneater")
- `Failed to generate outputs: unsupported format string passed to NoneType.__format__` (×4)
- `Job 231806a4: Failed to generate preview video: unsupported format string passed to NoneType.__format__` (×2)
- `Video render failed: Encoding job 231806a4 failed: '<' not supported between instances of 'NoneType' and 'float'` (×3, retried 3× then job failed)
### Root cause
The saved corrections JSON (`gs://.../jobs/231806a4/lyrics/corrections_updated.json`) had
**all 50 segments and all 364 words with `start_time`/`end_time` = `null`.**
The lyrics were Danish custom parody lyrics ("Vor's veninde er blevet gift") replacing the
original Maneater transcription. Segment IDs (`segment-N-<epoch>`) trace to the **LyricsSynchronizer's
"Edit Lyrics" sub-modal** (`LyricsSynchronizer.tsx:334 handleSaveEditedLyrics`), which creates
segments/words with `start_time: null, end_time: null` — an *expected intermediate state* that the
user must resolve by tap-syncing. The user saved + triggered preview/render **without synchronizing**,
so every timing was null.
The pipeline then crashes cryptically instead of rejecting cleanly. Both paths funnel through
`OutputGenerator.generate_outputs → SegmentResizer.resize_segments → ASS generation`, which has
**many** None-unsafe timing operations:
- `segment_resizer.py:540/550` — `f"time={segment.start_time:.2f}..."` → format crash (preview, newer Cloud Run wheel dies here first, at a *debug log line*).
- `segment_resizer.py:149` — `segment.end_time >= seg_start` (segment-level None not handled; only word-level is).
- `ass/lyrics_line.py:70/97` — `segment.start_time - previous_end_time >= threshold`.
- `ass/lyrics_screen.py:245/250` — `min/max(... .start_time/.end_time ...)`.
- `ass/section_detector.py:36` — `segments[0].start_time >= gap_threshold`.
- `_is_in_instrumental_section` — `segment.start_time < inst_end` → **exact `'<' NoneType vs float`** the GCE encoder hits (encoder runs its own pinned wheel and gets deeper before crashing).
Per-site None-guarding is whack-a-mole. The correct fix is a **validation gate** at the shared choke
points that rejects untimed lyrics with a clear, actionable message — untimed custom/replaced lyrics
*cannot* produce a correct karaoke video (auto-distribution would be meaningless against different
vocals), so blocking-with-guidance is the right product behavior.
### Fix
1. **Shared validator** `karaoke_gen/lyrics_transcriber/output/timing_validation.py` — new
`validate_segment_timing(segments) -> None` raising `LyricsTimingError` (with count + first
offending line) when any segment/word has `None` start/end. Called at the top of
`OutputGenerator.generate_outputs()`. Covers preview (Cloud Run) + local render + encoder (once its
wheel updates).
2. **Backend render gate** — call the validator in `render_video_worker.py` right after the
`correction_result` is loaded (~line 363), *before* any render/encoder dispatch. This stops the
encoder from ever being sent an untimed job **now**, without waiting for an encoder-wheel redeploy.
Fail the job with a clear user-facing message.
3. **Preview endpoint** `review.py generate_preview_video` — map `LyricsTimingError` to a clean
422 with a "synchronize your lyrics first" message (instead of the current cryptic 500).
4. **Defense-in-depth** — make `_log_input_segments`/`_log_output_segments` None-safe (a debug log
must never crash a job); make `_sanitize_segment_timings` tolerate None segment timing.
5. **Frontend guard (prevention/UX)** — in the review UI, block "Generate preview" and
"Complete/Submit" when untimed words exist, with a message pointing the user to synchronize.
## Group B (cheap robustness win): GDrive brand_code cleanup incomplete
- `Error cleaning up Google Drive for job 94ee69f3: GDrive brand_code search incomplete: 2/3 subfolder(s) failed`
- Underlying per-subfolder errors: `[SSL: UNEXPECTED_EOF_WHILE_READING]`, `[Errno 32] Broken pipe`
— transient Drive API connection drops.
- `gdrive_service.py:462` correctly refuses to declare "clean" on partial results (prevents brand-code
recycling) — behavior is right, but transient drops shouldn't reach that raise.
### Fix
Wrap the per-subfolder `files().list().execute()` (`gdrive_service.py:438`) in a small
retry-with-backoff for transient connection errors, so single SSL/broken-pipe blips self-heal.
## Group C (transient — document only, no code change)
- **`request_audit_error` + "Exception in ASGI application"** (same event): Firestore
`The referenced transaction has expired or is no longer valid` on
`/api/admin/rate-limits/blocklists/allowlisted-domains` (`email_validation_service.py:754`).
Count 1, admin-only, transient (likely a cold/paused instance mid-transaction). Admin can retry.
Not worth added complexity.
- **`Default STARTUP TCP probe failed ... DEADLINE_EXCEEDED`**: single slow cold start at 12:07:30;
**retry succeeded** at 12:10. Pure Cloud Run infra noise, no code issue.
## Testing
- Unit: `validate_segment_timing` raises on None segment/word timing, passes on valid; `_log_input_segments`
no longer crashes on None; gdrive retry recovers from transient then succeeds / raises after exhaustion.
- Frontend: Jest test that preview/complete is blocked when untimed words present.
- Regression fixture built from the real 231806a4 corrections shape (all-null timings).
@@ -0,0 +1,194 @@
# Nomad master fast-sync to kjbox — diagnosis + plan (2026-07-02)
## Symptom
New Nomad releases made on karaoke-gen are expected to appear on kjbox at
`/opt/nomad/downloads/NOMAD-720p/` "within minutes". In reality the box is stuck
at **NOMAD-1497** while Google Drive already has **NOMAD-1500** (made today).
## Root cause (evidence-backed) — NOT a broken component
The sync is a **3-hop pipeline**. Two hops are continuous; the middle hop is **daily**:
| Hop | Mechanism | Cadence | State 2026-07-02 15:00 ET |
|-----|-----------|---------|---------------------------|
| 1. gen → **Google Drive** `MP4-720p/` | `gdrive_service.upload_to_public_share()` at finalize | immediate | ✅ has NOMAD-1500 |
| 2. Drive → **GCS** `gs://nomadkaraoke-divebar-files/files/Nomad Karaoke/MP4-720p/` | `divebar-sync` VM via `divebar-sync-vm-daily` scheduler | **once/day @ 03:00 ET** | ❌ stuck at 1497 |
| 3. GCS → **kjbox** `NOMAD-720p/` | `nomad-master-sync.timer` (`sync_masters.py`) | every 5 min | ✅ mirrors GCS (1497) |
Evidence:
- GCS masters folder latest object = `NOMAD-1497` (1496 objects) — read via `claude-readonly` SA.
- `divebar-sync` VM `lastStartTimestamp = 2026-07-02T03:00 ET`, now `TERMINATED` (self-terminates after rsync). It captured Drive up to 1497; 1498–1500 were made later today.
- kjbox timer healthy: fires every 5 min, `{changed:False, copied:0, error:None}` = correctly in sync with a stale GCS. Its clean result is **correct**, not a bug.
- karaoke-gen has **no** code that writes to the GCS divebar bucket (`grep` of `backend/` for `nomadkaraoke-divebar-files` / `MP4-720p` GCS → only Drive uploads). GCS is populated *exclusively* by the daily VM.
**Conclusion:** the "within minutes" guarantee only ever covered hop 3. Hop 2 is a
~24h bottleneck that was never built for freshness. Fresh releases are delayed up to ~1 day.
(Red herring ruled out: `master_sync_source` absent from device `config.json` — the sync
works, so `load_config()` supplies it from `config.py` defaults. Not the issue.)
## Options
- **A. Direct gen→GCS push at finalize (RECOMMENDED).** When gen uploads the 720p master
to Drive, also upload it to the same GCS object the daily VM would produce. Existing kjbox
5-min timer then delivers within minutes. Idempotent with the daily VM (same object name+size
→ rsync skips). No kjbox change. gen-side code + 1 IAM grant.
- B. Trigger the sync VM per release. Reuses machinery but boots an e2-medium VM each time
(~1–2 min + full-tree rsync); heavy, can thrash on bursts.
- C. Run the daily VM hourly. Trivial cron change but delay up to ~1h (not "minutes") and pays
VM boot ×24/day.
## Recommended design — Option A
### Where
`backend/workers/video_worker_orchestrator.py::_upload_to_gdrive()` (line ~874) and the sibling
call in `backend/workers/video_worker.py` (~1121). Both call
`gdrive.upload_to_public_share(root_folder_id=..., brand_code=..., base_name=..., output_files=...)`.
Cleanest: add the GCS push **inside `upload_to_public_share()`** (single place, both callers
covered) OR a small helper invoked right after it. Prefer inside, guarded, non-fatal.
### GCS object path (must match the daily VM exactly for idempotency)
`gs://nomadkaraoke-divebar-files/files/Nomad Karaoke/MP4-720p/{brand_code} - {safe_base_name}.mp4`
- Matches observed names, e.g. `.../MP4-720p/NOMAD-0001 - This Is Me Smiling - Prettier.mp4`.
- `filename_base = f"{brand_code} - {sanitize_filename(base_name)}"` — already computed in the method.
### Gating (correctness)
- Only push when `brand_prefix == "NOMAD"` (i.e. brand_code `NOMAD-####`).
**Exclude `NOMADNP`** (private tracks) — they must not enter the public masters mirror.
- Only the 720p artifact (that's all kjbox mirrors). Skip 4K/CDG.
### Config
- `DIVEBAR_FILES_BUCKET` env (default `nomadkaraoke-divebar-files`).
- `NOMAD_MASTER_GCS_PREFIX` (default `files/Nomad Karaoke/MP4-720p`).
- Feature flag `NOMAD_MASTER_FAST_SYNC_ENABLED` (default true) for easy kill-switch.
### Reliability
- Wrap in try/except; on failure append a `distribution_warnings` entry and continue
(exactly like the existing Drive/Dropbox uploads — never fail the pipeline). The daily VM
remains the backfill safety net, so a missed fast-push self-heals within 24h.
- Reuse `google.cloud.storage` (already a gen dep). Upload via `blob.upload_from_filename`.
### Delete / replace symmetry (REQUIRED — Andrew's #1)
The whole existing mirror chain is **additive / never-delete**, so deletes & renames already
orphan files today:
- `divebar_file_sync.py` (VM) only ever downloads Drive→GCS; it never deletes a GCS object. A file
gone from Drive is marked `missing:drive_404` in BigQuery *only if it was still pending*; anything
already in GCS is never revisited → stale forever.
- kjbox `sync_masters.py` is explicitly additive ("never deletes local files").
So Drive deletes/renames leave orphans in **both** GCS and kjbox-local right now. Option A doesn't
introduce this, but it propagates new files faster and gives gen the clean hook to fix it for Nomad
masters.
gen already deletes Drive outputs at these events — mirror each with a GCS delete of the deterministic
master object `files/Nomad Karaoke/MP4-720p/{brand_code} - {name}.mp4`:
- Job delete: `services/job_manager.py:354`, `api/routes/jobs.py:396`
- Re-finalize / re-process (delete old outputs before re-upload): `api/routes/jobs.py:2270`
- Admin delete: `api/routes/admin.py:1700`
- Visibility change public→private: `services/visibility_change_service.py:267`
Rename/edit case: if artist/title changes, the object NAME changes. gen must delete the **old** object
name (reconstruct from the job's previously-stored output filename / `gdrive_files` metadata) and write
the new one — otherwise the rename orphans the old GCS object (the daily VM won't clean it either).
**Delete policy (RESOLVED by Andrew 2026-07-02):**
- **Community uploads: keep-forever in GCS — do NOT delete.** Deliberate: preserves valid karaoke
video data even if a user removes it from their Drive. (This is why the general mirror is additive.)
- **Nomad Karaoke masters: deletes ARE allowed** — we control the source, and the goal is that the
*latest edited version* is what ends up on kjbox. So Nomad deletes/renames SHOULD propagate all the
way to kjbox-local (an orphaned old-named file would keep playing the stale cut).
- ⇒ Delete symmetry is **Nomad-brand only** (same gate as the push). Never delete community objects.
**Recommended mechanism for kjbox-local propagation:** make the NOMAD-720p mirror a *true mirror* of
its GCS source — change `sync_masters.py`'s rsync to `--delete-unmatched-destination-objects` (scoped
to the Nomad masters folder we fully control, NOT the general additive community policy). Then gen just
deletes/replaces the GCS object and kjbox auto-reconciles (deletes old, pulls new) on its next 5-min
tick — no separate gen→kjbox delete channel needed. This is the kjbox half of the change.
- ⚠️ **SAFETY GUARD (critical):** `--delete-unmatched` + an empty/failed source listing = wipe the
whole local mirror. Guard: refuse to run the delete-mode rsync if the GCS source lists 0 objects
(or drops below a sanity threshold vs. current local count); on any listing/auth error, fall back to
additive-only. Never let a transient auth failure (like today's expired token) delete 1500 files.
### IAM (infra — needs `pulumi up` before merge)
Add binding: `backend_service_account` → `roles/storage.objectCreator` (create-only is enough;
use `objectAdmin` if we later want overwrite/idempotent re-put) on bucket
`nomadkaraoke-divebar-files`. Put it in `infrastructure/modules/iam/worker_sas.py`
(`grant_backend_compute_permissions`) or alongside the divebar bucket definition. ~5 lines.
- `grant_backend_compute_permissions` today grants only encoding-worker VM lifecycle — no bucket write.
### Testing
- Unit: mock `storage.Client`; assert (a) Nomad 720p → `upload_from_filename` called with the exact
`files/Nomad Karaoke/MP4-720p/{filename_base}.mp4` blob name; (b) NOMADNP → NOT pushed;
(c) non-Nomad brand → NOT pushed; (d) GCS failure → warning appended, pipeline continues.
- Idempotency note: gen writes the identical object name the VM would → next daily rsync no-ops.
- Prod E2E (post-deploy, once): finalize a throwaway NOMAD test job, assert object appears in GCS
within seconds and on kjbox `NOMAD-720p/` within ~5 min.
## Immediate gap (1498–1500 not yet in GCS)
Independent of the durable fix. To backfill now (needs admin gcloud; readonly SA can't):
```bash
gcloud scheduler jobs run divebar-sync-vm-daily --location=us-central1 --project=nomadkaraoke
```
This starts the `divebar-sync` VM immediately → mirrors today's Drive releases to GCS → kjbox
picks them up within 5 min. Otherwise they flow automatically at tonight's 03:00 ET run.
## Phase 4 — Refresh-catalog sequential fix (infra: `divebar_lookup` CF)
Confirmed root cause of the failed manual test (2026-07-02): `_refresh()` (main.py:443) fires all 3
scheduler jobs via `client.run_job()` in a loop with **no wait**. The sync VM (`divebar-sync-vm-daily`)
only copies files already in the BigQuery index, but it launches ~concurrently with the index rebuild
(`divebar-mirror-daily`) and finishes (~3 min) before the index adds the new rows → just-published
files get indexed (searchable) but miss the GCS sync pass. The **nightly path avoids this by time gaps**
(mirror 02:00 → sync 03:00 → xref 06:00 ET); the button collapses those gaps.
Dependency truth: **sync VM depends on the index; xref depends on the index (catalog rows), NOT on the
GCS file sync.** So correct order = run index → (on completion) run sync-VM **and** xref.
**Recommended fix — chain-on-completion (robust, non-blocking, also hardens nightly):**
- `_refresh()` triggers ONLY `divebar-mirror-daily` (the index) and returns immediately (button stays snappy).
- The index builder (`divebar_mirror`), at the end of a successful run, triggers `divebar-sync-vm-daily`
and `divebar-xref-rebuild-daily`.
- Nightly can then be simplified to a single index trigger (the chain follows), or left as-is (the extra
staggered triggers become harmless no-ops / redundant). Keep nightly schedulers for now; just add the
chain so BOTH paths sequence correctly.
- Alternative (simpler, worse UX) considered & rejected: make `_refresh()` block — synchronously await
the index (poll `MAX(synced_at)` in `divebar_catalog`) then fire sync+xref. Rejected: blocks the button
for minutes and risks the CF timeout.
## Implementation notes locked in (from code reads)
- **gen GCS client**: `StorageService` is hardwired to `settings.gcs_bucket_name` (gen's default bucket),
so it can't target the divebar bucket. Add a dedicated `backend/services/nomad_master_mirror.py`
(own `storage.Client`, `bucket=settings.divebar_files_bucket`) with `push_720p(local, filename)` and
`delete_720p(filename)` — isolated, mockable, non-fatal. Config: `DIVEBAR_FILES_BUCKET`
(`nomadkaraoke-divebar-files`), `NOMAD_MASTER_GCS_PREFIX` (`files/Nomad Karaoke/MP4-720p`),
`NOMAD_MASTER_FAST_SYNC_ENABLED` (kill switch).
- **Push call site**: inside `gdrive_service.upload_to_public_share()` right after the 720p Drive upload
(single place, covers both worker callers), guarded + non-fatal.
- **Brand gate**: `brand_code` prefix before first `-` == `"NOMAD"` exactly (so `NOMADNP-####` private is
excluded). NB: in the BigQuery index `brand_code` is literally just `"NOMAD"` and the release number
lives only in the filename — but gen's job-side `brand_code` here IS the full `NOMAD-####`.
- **Object name**: `{NOMAD_MASTER_GCS_PREFIX}/{brand_code} - {sanitize_filename(base_name)}.mp4` — matches
the daily VM's output exactly → idempotent.
## Rollout
1. `pulumi up` locally for the IAM grant (verify no unrelated drift).
2. Code + unit tests; `make test`.
3. `/test-review` → `/docs-review` → `/coderabbit` → version bump → `/pr`.
4. Merge → deploy → prod E2E with a NOMAD test job.
## Decision log
1. Approach: **A — direct gen→GCS push (CONFIRMED by Andrew).**
2. Scope: **Nomad-brand only (CONFIRMED)** — push AND delete are Nomad-gated; community objects are
never touched (keep-forever policy). Generalizing to all brands is out of scope.
3. Delete policy: **CONFIRMED** — Nomad deletes/renames propagate to GCS *and* kjbox-local (latest
edit wins on the box); community = keep-forever. See "Delete/replace symmetry".
4. Current-gap backfill (1498–1500): Andrew triggered it via the kjbox "Refresh catalog" button
2026-07-02 ~15:xx ET to verify the existing pipeline end-to-end (no code change).
## This is a two-repo change (kjbox + gen)
- **gen**: direct GCS push on Nomad finalize; delete/replace GCS object on Nomad job delete + rename;
+1 Pulumi IAM grant (backend SA → objectAdmin on divebar bucket, need overwrite+delete not just create).
- **kjbox**: `sync_masters.py` → true-mirror rsync (`--delete-unmatched-destination-objects`) with the
empty-source safety guard, so GCS deletes/renames reconcile onto the box.
## Still open
- Exact IAM role: `objectAdmin` (needs delete+overwrite for the delete/replace path) vs narrower.
- kjbox true-mirror safety-guard threshold (refuse delete if source count 0 / << local count).
@@ -0,0 +1,87 @@
# Tenant Portal E2E — Rewrite as a Faithful Frontend Journey Test
**Date:** 2026-07-04
**Status:** Design approved, pending spec review → implementation plan
**Author:** Andrew Beveridge + Claude
**Scope:** karaoke-gen (`frontend/e2e/production/`, `.github/workflows/e2e-tenant-daily.yml`, tenant setup scripts)
## Problem
The daily tenant E2E (`scripts/e2e/tenant_e2e.py`, run by `e2e-tenant-daily.yml`) is a **Python script that drives the whole flow via direct backend API calls** — submit, `uploads-complete`, `complete-review`, poll — bypassing the frontend entirely. It was built this way in June 2026 (PR #828) to prove the tenant pipeline worked, not to represent the user experience.
Two consequences:
1. **It is not a representative test.** It never exercises the tenant portal UI a real operator uses, so it cannot catch UX regressions and gives false confidence.
2. **It intermittently fails with stuck-render orphans.** Because it never loads the lyrics-review page, it never fires `POST /api/internal/encoding-worker/warmup/{job_id}` (+ `/heartbeat`) that the real review UI fires on load (`LyricsAnalyzer.tsx`). The encoding-worker VM (terminated at idle) is therefore cold when the render starts; the render worker enters its GCE-connection retry loop, and if the backend Cloud Run instance is recycled mid-retry the job orphans in `rendering_video` with no recovery. Confirmed root cause for runs #31 (vocalstar) and #32 (singa) — see the render-orphan analysis in this session's notes.
The consumer daily test (`happy-path-real-user.spec.ts`, "piri – dog") is the model done right: a real Playwright journey through the frontend that naturally fires the warmup.
## Goal
Replace the API-driven tenant script with a **Playwright frontend-journey test** that drives the tenant portal UI exactly as a real tenant operator would — which makes it representative **and** fires the warmup that prevents the orphan.
## Non-Goals (explicitly out of scope — separate follow-up)
- Deeper render-pipeline reliability hardening for real users: server-side warmup guarantee, pinning the encoding-worker URL for a render's lifetime (the undone 2026-06-15 follow-up), and a backstop recovery scheduler for jobs stuck in `rendering_video`. These protect real users from the rarer orphan and will be tracked as their own effort. This spec relies on the frontend warmup (which real tenant users already fire) to keep the happy path green.
## Design
### Approach
Replace `scripts/e2e/tenant_e2e.py` with a single parametrized Playwright spec that mirrors `happy-path-real-user.spec.ts`, run per-tenant via the existing matrix.
### 1. File layout & workflow
- **New:** `frontend/e2e/production/tenant-happy-path.spec.ts` — parametrized by `TENANT_ID` (`vocalstar` | `singa`) and `TENANT_PORTAL_URL` env vars. Structured like the consumer happy-path test.
- **Reuse helpers:** `email-testing.ts` (magic link via testmail), `auth.ts` — including `clickCompleteSignInGate()` (added earlier this session for the #870 gate), `test-cleanup.ts`.
- **Delete:** `scripts/e2e/tenant_e2e.py`.
- **Rework** `.github/workflows/e2e-tenant-daily.yml`: swap the `python scripts/e2e/tenant_e2e.py` step for `npx playwright test tenant-happy-path.spec.ts --config=playwright.production.config.ts`. Keep the `vocalstar`/`singa` matrix + `max-parallel: 1`. Add the Node/Playwright/testmail setup the consumer daily job already uses (`TESTMAIL_API_KEY`, `TESTMAIL_NAMESPACE`, `E2E_ADMIN_TOKEN`); keep WIF auth only if still needed for cleanup/GCS. Pass `TENANT_ID`/`TENANT_PORTAL_URL` per matrix entry.
### 2. The journey — entirely through the tenant portal UI
On `https://{tenant}.nomadkaraoke.com`:
1. **Sign in** via the real magic-link flow: open AuthDialog → request link to a testmail inbox → poll testmail → navigate the magic link → **Complete Sign-In gate** (`clickCompleteSignInGate`) → land in `/app`. The issued token carries `tenant_id` (verified in June).
2. **Submit track** via the tenant's simplified form: fill unique Artist/Title, upload real mixed + instrumental audio (`#tenant-mixed-audio`, `#tenant-instrumental-audio`), click *Submit Track* → assert *Track Submitted* + capture `[data-testid="created-job-id"]`.
3. **Wait for transcription** by polling the tenant portal job list UI until the *Review Lyrics* link/affordance appears.
4. **Open the review UI and approve** — the crux. Loading the review page fires `warmup` + `heartbeat`, keeping the encoder alive. Proceed through the review → instrumental step and complete it (the UI calls `completeReview(..., 'custom', ...)`; tenant instrumental is pre-supplied → `'custom'`, matching June bug-fix #7).
5. **Wait for render** by polling the UI to completion.
6. **Verify tenant distribution** (same guarantees the old script asserted, read after the UI-driven flow): Dropbox link present; **no** YouTube URL; downloads present (4K/720p/with-vocals + CDG + TXT via `job.file_urls`); job `is_private`; locked theme.
7. **Cleanup** the job (reuse `test-cleanup.ts` / admin delete).
### 3. Auth — allowlist a dedicated E2E email domain
Tenant magic-link login is gated by `tenant_config.auth.allowed_email_domains` (`users.py:287`). Current live values:
- vocalstar: `vocal-star.com`, `vocalstarmusic.com`
- singa: `singa.com`, `nomadkaraoke.com`
CI can only read **testmail.app** inboxes, which are on neither allowlist. Per the design decision, add a **dedicated E2E domain** to both tenants' `allowed_email_domains` so the test logs in exactly like a real operator.
**Domain choice (to finalize in the plan):**
- **Preferred (dedicated, owned):** a domain we control that testmail can receive for — e.g. `e2e.nomadkaraoke.com` via testmail's custom-domain feature (requires an MX record + testmail plan support). Truly dedicated; does not widen the portal to a shared public domain.
- **Fallback (simple):** `inbox.testmail.app`. Zero setup, but shared — anyone with a testmail account could register on the B2B portal. Low real risk (tenant jobs forced `is_private`, no payment on signup), but a wider surface than the owned-domain option.
Apply the change in **both** `scripts/setup-{vocalstar,singa}-tenant.py` **and** the live GCS `tenants/{id}/config.json` (the setup scripts are the source of truth; the live config must be updated to take effect).
### 4. Coverage & test data
- **Both tenants** (`vocalstar`, `singa`) via the matrix, sequential (`max-parallel: 1`) — the shared single encoder can't do two concurrent renders.
- **Real audio pair** (existing `gs://…/e2e-tests/shared/{e2e-mixed,e2e-instrumental}.mp3`, or bundled test assets). **Unique Artist/Title per run** (encoder caches by base name — repeated identical titles collide).
## Open items to resolve during planning/implementation
1. **E2E domain**: confirm dedicated-owned (`e2e.nomadkaraoke.com` via testmail custom domain — check plan/DNS) vs. fallback `inbox.testmail.app`.
2. **Review-approve selectors**: the exact tenant review/instrumental UI affordances that drive `completeReview('custom')` — nail down against the real UI during implementation.
3. **WIF vs testmail workflow setup**: confirm what the reworked workflow still needs from GCP auth (cleanup/GCS) vs. the consumer test's testmail/admin-token setup.
4. **Credits**: none needed — tenant portals do not require credits (separate financial agreement / manual invoicing per tenant). No credit-granting step in the test.
## Testing / verification
- Iterate the spec locally against prod for one tenant first (whichever the finalized E2E domain supports), driving the real portal via Playwright, before wiring the workflow.
- Confirm the warmup fires (review-page load → `warmup`/`heartbeat` 200s) and the render completes without orphaning.
- Then enable the reworked workflow and confirm a clean scheduled/dispatched run for both tenants.
## Risks
- Testmail custom-domain feasibility (for the dedicated-owned option) is unconfirmed — may fall back to `inbox.testmail.app`.
- The underlying render-orphan can still theoretically occur if the encoder is stopped mid-render despite warmup (the deeper reliability follow-up covers this); the frontend warmup makes it unlikely but not impossible. Retain a sane render timeout and clear failure output.
@@ -0,0 +1,503 @@
# Tenant Portal Frontend E2E — Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Replace the API-bypassing `scripts/e2e/tenant_e2e.py` with a Playwright frontend-journey test that drives the tenant portal UI end-to-end, so the daily tenant E2E is representative of the real operator experience and fires the encoding-worker warmup that prevents stuck-render orphans.
**Architecture:** A single parametrized Playwright spec (`tenant-happy-path.spec.ts`), run per-tenant via the existing `e2e-tenant-daily.yml` matrix, that mirrors the consumer `happy-path-real-user.spec.ts`: magic-link login on the tenant subdomain → submit track via the tenant form → wait for transcription → open the review UI (fires `warmup`/`heartbeat`) → approve → wait for render → assert tenant distribution → cleanup.
**Tech Stack:** Playwright (`@playwright/test`), TypeScript, testmail.app (E2E email), GitHub Actions matrix, FastAPI backend (tenant config in GCS).
## Global Constraints
- **Verification model:** These are production E2E tests. A task's "test cycle" is *running the spec (or the built-up portion of it) against production* and observing the segment pass — not unit tests. Use `cd frontend && ./node_modules/.bin/playwright test tenant-happy-path.spec.ts --config=playwright.production.config.ts --project=chromium --reporter=list` with the required env vars set.
- **Required env vars for local runs:** `TESTMAIL_API_KEY`, `TESTMAIL_NAMESPACE`, `E2E_ADMIN_TOKEN` (admin token, `gcloud secrets versions access latest --secret=admin-tokens --project=nomadkaraoke | cut -d, -f1`), `TENANT_ID` (`vocalstar`|`singa`), `TENANT_PORTAL_URL` (`https://{tenant}.nomadkaraoke.com`).
- **testmail address domain is `inbox.testmail.app`** — hardcoded in `frontend/e2e/helpers/email-testing.ts:133`. The tenant allowlist decision (Task 1) is bound to this: allowlisting `inbox.testmail.app` is the minimal path; a truly-owned dedicated domain would additionally require testmail custom-domain support + a helper change (out of scope for this plan — see Task 1 note).
- **Encoder is a single shared worker** — tenants must run sequentially (`max-parallel: 1`), and every run must use a **unique Artist/Title** (encoder caches by base name; repeated titles collide).
- **Tenant distribution invariants** (assert these): Dropbox link present, **no** YouTube URL, downloads from `job.file_urls` present (finals: `lossy_4k_mp4`, `lossy_720p_mp4`, `with_vocals_mp4`; packages: `cdg_zip`, `txt_zip`), job `is_private`, locked theme.
- **No credits needed** — tenant portals do not require credits (manual invoicing per tenant). Do not add a credit-granting step.
- **Reuse existing helpers** — `createEmailHelper`/`isEmailTestingAvailable` (`email-testing.ts`), `clickCompleteSignInGate` (`auth.ts`), cleanup via admin `DELETE /api/admin/jobs/{id}` (`test-cleanup.ts` pattern). Do not reinvent them.
- **Commit style:** end commit messages with `Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>`. Bump `pyproject.toml` version once (Task 7).
## File Structure
- **Create:** `frontend/e2e/production/tenant-happy-path.spec.ts` — the parametrized tenant journey spec. One responsibility: drive one tenant's full portal journey and assert distribution.
- **Modify:** `scripts/setup-vocalstar-tenant.py`, `scripts/setup-singa-tenant.py` — add the E2E domain to `allowed_email_domains`.
- **Create:** `scripts/e2e/update_tenant_allowlist.py` — small idempotent script to apply the `allowed_email_domains` change to the **live** GCS `tenants/{id}/config.json` (setup scripts are source-of-truth; live config must also be updated).
- **Modify:** `.github/workflows/e2e-tenant-daily.yml` — run the Playwright spec per matrix tenant; add Node/Playwright/testmail setup; keep matrix + `max-parallel: 1`.
- **Delete:** `scripts/e2e/tenant_e2e.py`.
- **Modify:** `pyproject.toml` — version bump (Task 7).
---
### Task 1: Allowlist the E2E email domain on both tenants
**Files:**
- Modify: `scripts/setup-vocalstar-tenant.py` (the `allowed_email_domains` list)
- Modify: `scripts/setup-singa-tenant.py` (the `allowed_email_domains` list)
- Create: `scripts/e2e/update_tenant_allowlist.py`
**Note (decision):** Uses `inbox.testmail.app`. The spec's "dedicated owned domain" preference (`e2e.nomadkaraoke.com`) needs testmail custom-domain support + a change to the hardcoded domain in `email-testing.ts`; that is deferred. If the shared-domain surface is later deemed unacceptable, swap the constant here and in the helper. Risk is low: tenant jobs are forced `is_private`, no payment on signup.
**Interfaces:**
- Produces: both tenants' live config `auth.allowed_email_domains` contains `inbox.testmail.app`, so `POST /api/users/auth/magic-link` with a testmail address + `X-Tenant-ID: {tenant}` returns 200 (not domain-rejected).
- [ ] **Step 1: Add the domain to the setup scripts**
In `scripts/setup-vocalstar-tenant.py`, change:
```python
"allowed_email_domains": ["vocal-star.com", "vocalstarmusic.com"],
```
to:
```python
"allowed_email_domains": ["vocal-star.com", "vocalstarmusic.com", "inbox.testmail.app"],
```
In `scripts/setup-singa-tenant.py`, change:
```python
"allowed_email_domains": ["singa.com", "nomadkaraoke.com"],
```
to:
```python
"allowed_email_domains": ["singa.com", "nomadkaraoke.com", "inbox.testmail.app"],
```
- [ ] **Step 2: Write the live-config updater script**
Create `scripts/e2e/update_tenant_allowlist.py`:
```python
#!/usr/bin/env python3
"""Idempotently add inbox.testmail.app to a tenant's allowed_email_domains in
the live GCS config (tenants/{id}/config.json). Setup scripts are the source
of truth, but the live config must be updated to take effect.
Usage: python scripts/e2e/update_tenant_allowlist.py vocalstar singa
"""
import json
import sys
from google.cloud import storage
BUCKET = "karaoke-gen-storage-nomadkaraoke"
E2E_DOMAIN = "inbox.testmail.app"
def update(tenant_id: str) -> None:
client = storage.Client(project="nomadkaraoke")
blob = client.bucket(BUCKET).blob(f"tenants/{tenant_id}/config.json")
cfg = json.loads(blob.download_as_text())
auth = cfg.setdefault("auth", {})
domains = auth.setdefault("allowed_email_domains", [])
if E2E_DOMAIN in domains:
print(f"{tenant_id}: already allowlisted ({domains})")
return
domains.append(E2E_DOMAIN)
blob.upload_from_string(json.dumps(cfg, indent=2), content_type="application/json")
print(f"{tenant_id}: added {E2E_DOMAIN} -> {domains}")
if __name__ == "__main__":
for t in sys.argv[1:] or ["vocalstar", "singa"]:
update(t)
```
- [ ] **Step 3: Apply to live config**
Run: `cd <worktree> && python scripts/e2e/update_tenant_allowlist.py vocalstar singa`
Expected: prints `vocalstar: added inbox.testmail.app -> [...]` and same for singa. (Uses ADC — the read-only SA can read; if it lacks write, run with an admin-capable credential / break-glass per project convention. If write is blocked, STOP and notify.)
- [ ] **Step 4: Verify magic-link is accepted for a testmail address on the tenant portal**
Run:
```bash
curl -s -X POST "https://api.nomadkaraoke.com/api/users/auth/magic-link" \
-H "Content-Type: application/json" -H "X-Tenant-ID: vocalstar" \
-d '{"email": "'"$TESTMAIL_NAMESPACE"'.probe@inbox.testmail.app"}'
```
Expected: HTTP 200 / `{"status": ...}` (NOT a domain-rejection error). Repeat with `X-Tenant-ID: singa`.
- [ ] **Step 5: Commit**
```bash
git add scripts/setup-vocalstar-tenant.py scripts/setup-singa-tenant.py scripts/e2e/update_tenant_allowlist.py
git commit -m "feat(e2e): allowlist testmail domain for tenant magic-link login"
```
---
### Task 2: Scaffold the spec + magic-link login segment
**Files:**
- Create: `frontend/e2e/production/tenant-happy-path.spec.ts`
**Interfaces:**
- Consumes: `createEmailHelper`, `isEmailTestingAvailable` from `../helpers/email-testing`; `clickCompleteSignInGate` from `../helpers/auth`.
- Produces: an authenticated tenant session in `page` (localStorage `karaoke_access_token` set, token carries `tenant_id`), reached entirely via the portal UI.
- [ ] **Step 1: Create the spec with env parametrization + login segment**
```typescript
import { test, expect, Page } from '@playwright/test';
import { createEmailHelper, isEmailTestingAvailable, EmailHelper } from '../helpers/email-testing';
import { clickCompleteSignInGate } from '../helpers/auth';
const TENANT_ID = process.env.TENANT_ID || 'vocalstar';
const PORTAL_URL = process.env.TENANT_PORTAL_URL || `https://${TENANT_ID}.nomadkaraoke.com`;
const API_URL = 'https://api.nomadkaraoke.com';
const ADMIN_TOKEN = process.env.E2E_ADMIN_TOKEN || process.env.KARAOKE_ADMIN_TOKEN || '';
const T = { action: 30_000, transcription: 900_000, render: 1_800_000, full: 3_000_000 };
test.describe(`Tenant Portal Happy Path — ${TENANT_ID}`, () => {
test.describe.configure({ retries: 0 });
let emailHelper: EmailHelper | null = null;
let createdJobId: string | null = null;
test.beforeAll(async () => {
if (isEmailTestingAvailable()) emailHelper = await createEmailHelper();
});
test.afterAll(async () => {
if (createdJobId && ADMIN_TOKEN) {
await fetch(`${API_URL}/api/admin/jobs/${createdJobId}`, {
method: 'DELETE', headers: { 'X-Admin-Token': ADMIN_TOKEN },
}).catch(() => {});
}
});
test(`Full tenant journey: login -> submit -> review -> render -> distribution`, async ({ page, context }) => {
test.skip(!emailHelper, 'Email testing not configured (TESTMAIL_API_KEY/NAMESPACE)');
test.setTimeout(T.full);
// ---- Sign in via magic link on the tenant portal ----
const inbox = await emailHelper!.createInbox();
await page.goto(`${PORTAL_URL}/app`, { waitUntil: 'domcontentloaded', timeout: T.action });
const signInButton = page.getByRole('button', { name: /sign (in|up)/i }).first();
await expect(signInButton).toBeVisible({ timeout: T.action });
await signInButton.click();
const authDialog = page.getByRole('dialog');
await expect(authDialog).toBeVisible({ timeout: T.action });
await authDialog.getByPlaceholder('you@example.com').fill(inbox.emailAddress);
await page.getByRole('button', { name: /send sign-in link/i }).click();
await expect(page.getByText(/check your email/i)).toBeVisible({ timeout: 15_000 });
const email = await emailHelper!.waitForEmail(inbox.id, 60_000);
const magicLink = emailHelper!.extractMagicLink(email);
if (!magicLink) throw new Error('Could not extract magic link from tenant sign-in email');
await page.goto(magicLink);
await clickCompleteSignInGate(page);
await page.waitForURL(/\/app/, { timeout: T.action });
const token = await page.evaluate(() => localStorage.getItem('karaoke_access_token'));
expect(token, 'authenticated token present after magic-link login').toBeTruthy();
console.log(`[${TENANT_ID}] Signed in via magic-link UI`);
});
});
```
- [ ] **Step 2: Run the login segment against prod (singa first — the allowlist from Task 1 is live)**
Run: `cd frontend && ./node_modules/.bin/playwright test tenant-happy-path.spec.ts --config=playwright.production.config.ts --project=chromium --reporter=list`
(with `TENANT_ID=singa TENANT_PORTAL_URL=https://singa.nomadkaraoke.com` + testmail/admin env).
Expected: reaches `/app`, logs `Signed in via magic-link UI`, token present. (The test will continue past login only once later tasks add steps; for now it ends after the login assertion.)
- [ ] **Step 3: Confirm the token carries the tenant_id**
Add a temporary log of the decoded token payload or verify via `GET /api/users/me` with the token that the session is tenant-scoped. Expected: `tenant_id == singa`. Remove the temporary log before commit.
- [ ] **Step 4: Commit**
```bash
git add frontend/e2e/production/tenant-happy-path.spec.ts
git commit -m "feat(e2e): tenant-happy-path spec scaffold + magic-link login segment"
```
---
### Task 3: Submit-track segment
**Files:**
- Modify: `frontend/e2e/production/tenant-happy-path.spec.ts`
**Interfaces:**
- Consumes: authenticated `page` from Task 2.
- Produces: `createdJobId` set to the submitted job's short id; job is transcribing.
**Test audio:** download the shared E2E pair to temp files at test start:
`gs://karaoke-gen-storage-nomadkaraoke/e2e-tests/shared/e2e-mixed.mp3` and `.../e2e-instrumental.mp3`. Fetch via the public/authorized GCS path or a signed URL helper; if not directly fetchable in CI, stage them as repo test assets under `frontend/e2e/fixtures/`. Confirm the fetch path during this task's run.
- [ ] **Step 1: Add the submit segment after login**
Insert before the closing of the test body:
```typescript
// ---- Submit a track via the tenant form ----
const uniqueTitle = `E2E ${TENANT_ID} ${new Date().toISOString().replace(/[:.]/g, '-')}`;
await page.getByLabel('Artist').fill('Nomad E2E');
await page.getByLabel('Title').fill(uniqueTitle);
await page.locator('#tenant-mixed-audio').setInputFiles(mixedAudioPath);
await page.locator('#tenant-instrumental-audio').setInputFiles(instrumentalAudioPath);
await page.getByRole('button', { name: /submit track/i }).click();
await expect(page.getByText(/track submitted/i)).toBeVisible({ timeout: 120_000 });
const jobIdText = await page.locator('[data-testid="created-job-id"]').textContent();
createdJobId = jobIdText?.replace(/^ID:\s*/i, '').trim() || null;
expect(createdJobId, 'created job id captured from tenant submit').toBeTruthy();
console.log(`[${TENANT_ID}] Submitted job ${createdJobId}: ${uniqueTitle}`);
```
Add the audio-staging code in `beforeAll` (or top of test) producing `mixedAudioPath` / `instrumentalAudioPath` (temp files). Use a unique title per run (constraint).
- [ ] **Step 2: Run login+submit against prod (singa)**
Run: same command as Task 2 Step 2.
Expected: `Track Submitted` appears, `createdJobId` logged. The `afterAll` cleanup deletes the job.
- [ ] **Step 3: Commit**
```bash
git add frontend/e2e/production/tenant-happy-path.spec.ts
git commit -m "feat(e2e): tenant submit-track segment via portal form"
```
---
### Task 4: Wait-for-transcription + open-review (warmup) + approve segment
**Files:**
- Modify: `frontend/e2e/production/tenant-happy-path.spec.ts`
**Interfaces:**
- Consumes: `createdJobId`, authenticated `page`.
- Produces: job past review (status left `awaiting_review`), review-page load having fired `warmup`+`heartbeat`.
**Pattern to follow:** `happy-path-real-user.spec.ts` Steps 7–8 (poll job card for a `Review Lyrics` link → open review page in a new tab → the page fires `warmupEncodingWorker(jobId)` on load → proceed to completion). The exact tenant review→approve affordance that calls `completeReview(..., 'custom')` must be confirmed against the live tenant review UI during this task's run (this is the legitimate E2E test cycle). Opening the review page is the essential warmup-firing action.
- [ ] **Step 1: Add poll-for-review-readiness**
```typescript
// ---- Wait until the job is ready for review (poll the portal UI) ----
const jobCard = page.locator(`text=${createdJobId}`).locator('xpath=ancestor::*[self::div][1]');
let reviewLink = null;
const deadline = Date.now() + T.transcription;
while (Date.now() < deadline) {
await page.reload({ waitUntil: 'domcontentloaded' });
const link = page.getByRole('link', { name: /review lyrics/i }).first();
if (await link.isVisible().catch(() => false)) { reviewLink = link; break; }
await page.waitForTimeout(15_000);
}
expect(reviewLink, 'Review Lyrics link appeared before transcription timeout').not.toBeNull();
```
- [ ] **Step 2: Open the review page (fires warmup) and capture the warmup request**
```typescript
const reviewHref = await reviewLink!.getAttribute('href');
const reviewUrl = reviewHref!.startsWith('http') ? reviewHref! : `${PORTAL_URL}${reviewHref}`;
const reviewPage = await context.newPage();
// Assert the warmup fires on review-page load (the whole point of the UI journey)
const warmupReq = reviewPage.waitForRequest(
(r) => r.url().includes('/api/internal/encoding-worker/warmup/'),
{ timeout: 60_000 },
);
await reviewPage.goto(reviewUrl, { waitUntil: 'domcontentloaded' });
await warmupReq;
console.log(`[${TENANT_ID}] Review page fired encoding-worker warmup`);
```
- [ ] **Step 3: Complete the review through the UI**
Follow the happy-path Step 7–8 flow adapted for the tenant (pre-supplied instrumental → `'custom'`). Confirm the exact finalize affordance against the live tenant review UI while running this task; encode the confirmed selectors here. The completion triggers `completeReview(jobId, ..., 'custom', ...)` and moves the job into the render pipeline.
- [ ] **Step 4: Run login→submit→review-approve against prod (singa)**
Run: same command.
Expected: logs the warmup firing, review completes, job leaves `awaiting_review` (verify via a `GET /api/jobs/{id}` status check with the session token or admin token).
- [ ] **Step 5: Commit**
```bash
git add frontend/e2e/production/tenant-happy-path.spec.ts
git commit -m "feat(e2e): tenant review-open (warmup) + approve segment"
```
---
### Task 5: Wait-for-render + distribution assertions
**Files:**
- Modify: `frontend/e2e/production/tenant-happy-path.spec.ts`
**Interfaces:**
- Consumes: `createdJobId`, session token.
- Produces: full green journey for one tenant (singa).
- [ ] **Step 1: Poll to render completion, then assert tenant distribution**
```typescript
// ---- Wait for render to complete, then assert tenant distribution ----
const token2 = await page.evaluate(() => localStorage.getItem('karaoke_access_token'));
const getJob = async () => {
const r = await fetch(`${API_URL}/api/jobs/${createdJobId}`, {
headers: { Authorization: `Bearer ${token2}` },
});
if (!r.ok) throw new Error(`GET job ${createdJobId}: ${r.status}`);
return r.json();
};
const renderDeadline = Date.now() + T.render;
let job: any = null;
while (Date.now() < renderDeadline) {
job = await getJob();
if (job.status === 'complete') break;
if (job.status === 'failed' || job.status === 'error') {
throw new Error(`Render failed: status=${job.status} ${JSON.stringify(job.state_data?.error || '')}`);
}
await new Promise((res) => setTimeout(res, 15_000));
}
expect(job?.status, 'job reached complete before render timeout').toBe('complete');
const fileUrls = job.file_urls || {};
const finals = Object.keys(fileUrls.finals || {});
const packages = Object.keys(fileUrls.packages || {});
expect(job.dropbox_url || job.state_data?.dropbox_url, 'Dropbox link present').toBeTruthy();
expect(job.youtube_url || null, 'no YouTube upload for tenant').toBeFalsy();
for (const f of ['lossy_4k_mp4', 'lossy_720p_mp4', 'with_vocals_mp4']) expect(finals).toContain(f);
for (const p of ['cdg_zip', 'txt_zip']) expect(packages).toContain(p);
expect(job.is_private, 'tenant job is private').toBeTruthy();
console.log(`[${TENANT_ID}] PASSED — complete, Dropbox present, no YouTube, downloads available`);
```
(Confirm the exact field names — `dropbox_url` vs `state_data.dropbox_url`, `is_private` location — against a real completed job's `GET /api/jobs/{id}` payload during this run; the old `tenant_e2e.py` read `file_urls` finals/packages, `dropbox_link`, `youtube_url`.)
- [ ] **Step 2: Run the FULL journey against prod (singa) end-to-end**
Run: same command, allow up to ~30–40 min.
Expected: `[singa] PASSED …`. This is the first full green frontend journey.
- [ ] **Step 3: Commit**
```bash
git add frontend/e2e/production/tenant-happy-path.spec.ts
git commit -m "feat(e2e): tenant render-wait + distribution assertions (full journey green)"
```
---
### Task 6: Confirm vocalstar + robust cleanup
**Files:**
- Modify: `frontend/e2e/production/tenant-happy-path.spec.ts` (only if selector/field differences surface)
- [ ] **Step 1: Run the full journey for vocalstar**
Run: same command with `TENANT_ID=vocalstar TENANT_PORTAL_URL=https://vocalstar.nomadkaraoke.com`.
Expected: `[vocalstar] PASSED …`. Fix any tenant-specific selector/field differences inline (both tenants use the same portal app, so differences should be minimal).
- [ ] **Step 2: Verify cleanup deletes the job for both tenants**
Confirm `afterAll` deleted each test job (`GET /api/jobs/{id}` → 404, or check admin). No orphaned E2E jobs left.
- [ ] **Step 3: Commit (if any changes)**
```bash
git add frontend/e2e/production/tenant-happy-path.spec.ts
git commit -m "fix(e2e): tenant-happy-path passes for both vocalstar and singa"
```
---
### Task 7: Rework the workflow + delete the old script + version bump
**Files:**
- Modify: `.github/workflows/e2e-tenant-daily.yml`
- Delete: `scripts/e2e/tenant_e2e.py`
- Modify: `pyproject.toml`
- [ ] **Step 1: Replace the run step in the workflow**
Replace the Python "Run tenant E2E" step with the Playwright run, keeping the `matrix` (`vocalstar`, `singa`) and `max-parallel: 1`. Add the Node/Playwright/testmail setup that the consumer daily job (`e2e-daily.yml`) already uses. Concretely, the job's steps become:
```yaml
- name: Checkout code
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with: { node-version: '20', cache: 'npm', cache-dependency-path: frontend/package-lock.json }
- name: Install dependencies
working-directory: frontend
run: npm ci --legacy-peer-deps
- name: Install Playwright browsers
working-directory: frontend
run: npx playwright install --with-deps chromium
- name: Ensure testmail.app domain is allowlisted (rate-limit)
run: |
curl -sf -X POST "https://api.nomadkaraoke.com/api/admin/rate-limits/blocklists/allowlisted-domains" \
-H "X-Admin-Token: ${{ secrets.E2E_ADMIN_TOKEN }}" -H "Content-Type: application/json" \
-d '{"domain": "inbox.testmail.app"}' || echo "Warning: allowlist may already exist"
- name: Run tenant E2E (frontend journey)
id: run_test
working-directory: frontend
env:
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
TESTMAIL_NAMESPACE: ${{ secrets.TESTMAIL_NAMESPACE }}
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
TENANT_ID: ${{ matrix.tenant }}
TENANT_PORTAL_URL: https://${{ matrix.tenant }}.nomadkaraoke.com
run: |
npx playwright test tenant-happy-path.spec.ts \
--config=playwright.production.config.ts --project=chromium \
--reporter=list --timeout=2400000 2>&1 | tee e2e-output.log
echo "exit_code=${PIPESTATUS[0]}" >> "$GITHUB_OUTPUT"
continue-on-error: true
```
Keep the existing "Upload logs", "Discord notification (failure)", "Fail the job", and `notify-email` steps; point the log upload at `frontend/e2e-output.log` and `frontend/test-results/`. Drop the GCP WIF auth + `pip install` steps unless still needed (they were for the Python script's Secret Manager/GCS access — the Playwright test uses `E2E_ADMIN_TOKEN` directly; remove if unused).
- [ ] **Step 2: Delete the old Python script**
```bash
git rm scripts/e2e/tenant_e2e.py
```
- [ ] **Step 3: Bump version**
In `pyproject.toml`, bump the patch version (e.g. `0.190.3` → `0.190.4`).
- [ ] **Step 4: Commit**
```bash
git add .github/workflows/e2e-tenant-daily.yml pyproject.toml
git commit -m "ci(e2e): run tenant daily via Playwright frontend journey; drop API script"
```
---
### Task 8: Final end-to-end verification via the workflow
- [ ] **Step 1: Dispatch the reworked workflow against the branch, off-peak if possible**
Run: `gh workflow run e2e-tenant-daily.yml --repo nomadkaraoke/karaoke-gen --ref <branch>`
(Only the default branch may be dispatchable; if so, this runs after merge. Prefer a low-traffic window given the shared encoder.)
- [ ] **Step 2: Watch both matrix jobs to green**
Confirm `Tenant E2E: vocalstar` and `Tenant E2E: singa` both succeed, and the logs show the warmup firing + render completing (no `rendering_video` orphan). If a job stalls at `rendering_video`, capture logs — that would indicate the warmup did not prevent the orphan and the separate reliability follow-up is needed.
- [ ] **Step 3: Confirm no leftover E2E jobs**
Check admin/job list for orphaned `Nomad E2E` jobs; none should remain.
---
## Self-Review
**Spec coverage:**
- Representative frontend journey (login→submit→review→render→verify) → Tasks 2–6. ✓
- Delete `tenant_e2e.py` / rework workflow → Task 7. ✓
- Allowlist dedicated E2E domain on both tenants (scripts + live config) → Task 1. ✓
- Both tenants, sequential, unique title, real audio → Tasks 3, 6, Global Constraints. ✓
- Distribution invariants → Task 5 + Global Constraints. ✓
- No credits step → Global Constraints. ✓
- Warmup-fires assertion (the crux) → Task 4 Step 2. ✓
- Non-goal (reliability hardening) → explicitly excluded; Task 8 Step 2 flags if warmup proves insufficient. ✓
**Placeholder scan:** Two spots require live-UI confirmation (Task 4 Step 3 review-approve affordance; Task 5 Step 1 exact job field names). These are inherent to E2E authoring against a live UI, not deferred implementation — each names the exact mechanism, the reference (`happy-path` Steps 7–8; old `tenant_e2e.py` fields), and the run in which to confirm. Acceptable; not fixable ahead of a live run without guessing selectors.
**Type/name consistency:** `createdJobId`, `emailHelper`, `PORTAL_URL`, `TENANT_ID`, `reviewUrl`, `getJob()` used consistently across tasks. Helper names (`createEmailHelper`, `waitForEmail`, `extractMagicLink`, `clickCompleteSignInGate`) match the real exports verified in the source.
@@ -0,0 +1,50 @@
# Plan: Original-Vocals guide write-path
**Created:** 2026-07-09
**Branch:** feat/sess-20260709-0013-vocals-writepath
**Spec:** `docs/superpowers/specs/2026-07-09-original-vocals-writepath-design.md`
**Status:** In progress (autonomous)
## Verified code map (server render flow)
| Fact | Location |
|--|--|
| `mixed_vocals` stem uploaded to GCS | `backend/workers/audio_worker.py:510` → `jobs/{job_id}/stems/vocals_clean.flac` |
| Finalize/upload hook (has brand_code, base_name, local 720p) | `backend/workers/video_worker_orchestrator.py:852 _upload_to_gdrive` |
| 720p master (local at finalize) | `self.result.final_video_720p` (orch:870) |
| Existing 720p GCS push seam | `backend/services/gdrive_service.py:315-336` (`_fast_sync_nomad_master` → `NomadMasterMirror.push_720p`) |
| Intro seconds from style | `karaoke_gen/style_loader.py:688 get_video_durations(style_params)` → intro (default 5) |
| Style load | `backend/workers/style_helper.py StyleHelper(job, storage, temp_dir).load()` (orch has `self.storage`, `self.job_manager`) |
| GCS helpers | `backend/services/storage_service.py` (`download_file`, `delete`) |
| Brand-recycle / master cleanup seam | `backend/services/nomad_master_mirror.py cleanup_nomad_masters()` |
| Settings | `backend/config.py` (`divebar_files_bucket`, `nomad_master_gcs_prefix`, `nomad_master_fast_sync_enabled`, `gcs_bucket_name`) |
## Implementation steps (karaoke-gen)
1. [ ] `backend/config.py`: add `nomad_vocals_guide_gcs_prefix` (default `"files/Nomad Karaoke/vocals-padded"`).
2. [ ] `backend/services/original_vocals_guide.py` (NEW, pure + testable):
`build_original_vocals_guide(mixed_vocals_path, intro_seconds, master_duration, dest_path, ffmpeg_path="ffmpeg") -> str | None`
— ffmpeg `-i vocals -af "adelay={ms}:all=1" -t {master_duration} -c:a flac -f flac {dest}.part` → atomic replace. Returns dest or None (missing input / ffmpeg fail → None, never raises).
3. [ ] `backend/services/nomad_master_mirror.py`: add `push_vocals_guide(local_path, filename)` + `delete_vocals_guides_by_brand(brand_code)` (siblings of the 720p methods, keyed on `nomad_vocals_guide_gcs_prefix`). Extend `cleanup_nomad_masters` (or add sibling call) to also delete guides.
4. [ ] `video_worker_orchestrator.py _upload_to_gdrive`: before building `output_files`, call new `await self._emit_original_vocals_guide(brand_code, safe_base_name)` which (only for `is_nomad_public_brand`): loads job+style→intro secs, downloads `vocals_clean.flac`, ffprobes 720p→master_dur, builds guide named `{brand} - {base}.flac`, returns path. Register as `output_files["original_vocals_guide"]`. Best-effort; failures → `self.result.distribution_warnings`.
5. [ ] `gdrive_service.py _upload_public_share_files`: after the 720p fast-sync block, push `output_files["original_vocals_guide"]` via a new `_fast_sync_vocals_guide(brand_code, path, filename)` (gated `is_nomad_public_brand` + `nomad_master_fast_sync_enabled`, best-effort, warning on failure).
6. [ ] Tests: `test_original_vocals_guide.py` (builder: offset/cap/`-f flac`/None paths), extend `test_nomad_master_mirror.py` (push/delete vocals prefix + gating), wiring test (guide registered + pushed + warned).
7. [ ] Version bump `pyproject.toml`.
## Implementation steps (kjbox — separate worktree, PR only)
8. [ ] `kj-controller/config.py`: add `vocals_sync_enabled` (False), `vocals_sync_source` (`gs://nomadkaraoke-divebar-files/files/Nomad Karaoke/vocals-padded/`), `vocals_sync_dest` (""→`{download_folder}/NOMAD-vocals-padded`), `vocals_sync_delete_removed` (False).
9. [ ] `kj-controller/scripts/sync_masters.py main()`: after master `run_sync`, build a vocals config view (map `vocals_sync_*`→`master_sync_*` keys, `delete_removed=False`, no rescan poke) and call `run_sync` again when `vocals_sync_enabled`. `run_sync` unchanged.
10. [ ] Tests: extend `test_sync_masters.py` — both syncs run, vocals additive-only, isolation on vocals failure.
## Testing
- karaoke-gen: `make test` (or targeted pytest for new files) — unit for builder (synthetic tone+silence), mirror (mocked storage), wiring.
- kjbox: `cd kj-controller && pytest tests/unit/test_sync_masters.py`.
## Release
- karaoke-gen: full ship to `main` (inert change).
- kjbox: PR only; **not merged/deployed** (live device — Andrew's maintenance window).
## Rollback
- karaoke-gen: revert PR; `nomad_master_fast_sync_enabled=false` also disables guide push.
- kjbox: `vocals_sync_enabled=false` default → inert; not deployed.
@@ -0,0 +1,238 @@
# Edge Security — Cutover Runbook
Companion to `2026-07-20-edge-security-hardening-plan.md`. Step-by-step ops
sequence to put `api.nomadkaraoke.com` behind the Cloudflare edge with **near-zero
downtime**. Every prod-affecting action is a single, instantly-reversible flip.
**Who runs what:** all `pulumi`, `gcloud`, and Cloudflare-token steps are run by
**Andrew** (agent has read-only ADC). The code (Pulumi module, middleware, alert,
CI env) is already in this branch.
---
## Legend
- 🟢 non-disruptive (no prod impact)
- 🔴 prod-affecting (but instantly reversible)
- ✅ verification gate — do not proceed until green
---
## Prereqs (one-time) 🟢
1. **Cloudflare token** — the `.envrc` `CLOUDFLARE_API_TOKEN` (`nomadkaraoke-claude`)
now has the required zone scopes (**verified 2026-07-20**: DNS record
create+delete OK, rulesets list OK, zone settings editable). Point Pulumi at it:
```bash
cd infrastructure
pulumi config set --secret cloudflare:apiToken "$CLOUDFLARE_API_TOKEN"
# zone id (807f07f458f9cd38251f3b7948d55172) is baked in as the default;
# only set these if overriding:
# pulumi config set edge:cloudflareZoneId <zone-id>
# pulumi config set edge:cloudflareAccountId <account-id>
pulumi config set edge:rolloutStage staging # default anyway
# Zone is on the FREE plan → managed OWASP ruleset stays OFF (Pro+ only).
# Leave edge:managedWafEnabled unset; set true only after upgrading to Pro.
```
> (Optional least-privilege: mint a dedicated token scoped to nomadkaraoke.com
> with DNS:Edit, Zone WAF:Edit, Zone Settings:Edit, Transform Rules:Edit,
> Zone:Read, and use that instead of the broad account token.)
> **Re-check any token before enabling** (should print `success: True`):
> ```bash
> curl -s -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
> "https://api.cloudflare.com/client/v4/zones/807f07f458f9cd38251f3b7948d55172/dns_records?per_page=1" \
> | python3 -c "import sys,json;print('success:',json.load(sys.stdin)['success'])"
> ```
2. **Create the secret container + other additive infra first** (edge module is
still OFF — `edge:enabled` defaults to false, so NO Cloudflare calls happen):
```bash
cd infrastructure && pulumi preview # expect ONLY additions (incl. edge-origin-secret); no Cloudflare
pulumi up
```
✅ No Cloudflare resources, no staging mapping, prod `api` untouched.
3. **Origin secret** — generate once, store in BOTH Secret Manager (backend reads
it) and Pulumi config (Cloudflare injects it). Must be identical.
```bash
SECRET=$(openssl rand -hex 32)
printf '%s' "$SECRET" | gcloud secrets versions add edge-origin-secret \
--data-file=- --project=nomadkaraoke # container created in step 2
pulumi config set --secret edge:originSecret "$SECRET"
unset SECRET
```
> ⚠️ The CI deploy references `edge-origin-secret:latest` — a backend deploy
> will fail until this version exists. Add it **before** this branch merges.
4. **Activate + apply the edge module (staging scope)** — creates the staging
Cloud Run mapping + staging DNS + WAF/rate-limit/header-transform/zone-settings,
all scoped to `api-edge-test.nomadkaraoke.com` only. The live prod `api` record
is NOT managed at this stage (the module only manages it once rolloutStage=prod),
so there is nothing to import yet and zero risk to prod DNS:
```bash
pulumi config set --secret cloudflare:apiToken "$CLOUDFLARE_API_TOKEN"
pulumi config set edge:enabled true # rolloutStage defaults to "staging"
pulumi preview # expect: NEW staging resources only; prod `api` record NOT in the plan
pulumi up # (use --target on the edge URNs if the stack has unrelated drift)
```
> The staging `api-edge-test` record is created **grey-cloud (proxied=False)**
> on purpose — see step 6 (the SSL dragon). It gets flipped to orange after the
> cert issues.
> Zone `security_level` (already "medium") is set via `cloudflare.ZoneSetting`
> — it adopts the current value (no-op). If preview errors that it "exists",
> import it: `pulumi import cloudflare:index/zoneSetting:ZoneSetting zone-security-level 807f07f458f9cd38251f3b7948d55172/security_level`.
>
> **Free-plan gotchas already handled in code (learned 2026-07-20 apply):**
> WAF uses the `contains` operator not regex `matches` (regex = Business+);
> rate-limit `period` must be 10s and `characteristics` MUST include
> `cf.colo.id`. Managed OWASP ruleset stays off (Pro+).
---
## Phase A — Ship code dormant 🟢
5. Merge this branch (or deploy backend) with `EDGE_AUTH_MODE=off`. The
middleware is a no-op; the alert retune and staging infra are live.
✅ Prod behaves exactly as before: `curl -sI https://api.nomadkaraoke.com/`
still shows `server: Google Frontend` (no cf-ray).
---
## Phase B — Validate everything on staging 🟢 ✅ DONE (2026-07-20)
> **RESULT: staging validation PASSED.** With the zone on SSL "full" mode, the
> managed cert does NOT need to provision — flip straight to orange and it works.
> (The cert stays "pending" behind Cloudflare forever; "full" mode ignores it.
> See plan §4.) Recorded here for the eventual prod cutover.
6. Flip the staging record to **orange-cloud** — no cert wait needed in "full"
mode:
```bash
pulumi config set edge:proxyStaging true
pulumi up --target 'urn:...:DnsRecord::api-edge-test-dns'
```
Keep zone SSL/TLS mode = **Full** (NOT strict — strict would 525 since the
managed cert can't validate behind CF).
7. Verification suite against **staging** (`HOST=api-edge-test.nomadkaraoke.com`) —
**actual results 2026-07-20 in `[ ]`**:
```bash
HOST=api-edge-test.nomadkaraoke.com
curl -sI https://$HOST/ | grep -iE 'server|cf-ray' # [200, server: cloudflare, cf-ray ✅]
for p in '.env' 'home/root/.ssh/id_rsa' 'wp-config.php' 'etc/passwd'; do
echo -n "$p -> "; curl -s -o /dev/null -w '%{http_code}\n' "https://$HOST/$p"; done # [all 403 ✅]
curl -s -o /dev/null -w 'health %{http_code}\n' https://$HOST/api/health # [200 ✅]
```
✅ cf-ray present, exploit paths 403, health 200, **no 525** — edge fully works.
8. **If SSL errors appear**, step down the ladder (edit `edge_security.py` /
zone SSL mode) and re-test:
- `Full (strict)` → `Full` (skip strict cert validation), or
- add a Cloudflare **Origin Rule** overriding origin host + SNI to
`karaoke-backend-ipzqd2k4yq-uc.a.run.app` (always-valid `*.run.app` cert).
9. **Origin-lock check** — deploy backend with `EDGE_AUTH_MODE=enforce` (test
env / temporary override), then hit a **non-exempt** path directly on the
origin. Exempt paths are only `/`, `/api/health`, `/api/health/*` (probes) —
testing those would return 200 and prove nothing, so use a real endpoint:
```bash
RUNAPP=karaoke-backend-ipzqd2k4yq-uc.a.run.app
curl -s -o /dev/null -w '%{http_code}\n' https://$RUNAPP/api/jobs # expect 403 (direct, non-exempt)
curl -s -o /dev/null -w '%{http_code}\n' https://$RUNAPP/api/health # expect 200 (exempt probe path)
curl -s -o /dev/null -w '%{http_code}\n' https://api-edge-test.nomadkaraoke.com/api/jobs # expect NOT 403 (via edge → has header)
```
✅ Non-exempt path blocked direct-to-origin (403); same path via the edge is
allowed; health/root stay 200 direct (exempt for probes).
10. **Soak** staging proxied for a few days; watch for delayed cert/525 issues
and any WAF false positives (Cloudflare Firewall Events / Security dashboard).
---
## Phase C — (Pro only) enable + block the managed WAF ruleset 🟢
11. **Skip on the Free plan** — the managed OWASP ruleset is Pro+ and is gated
off (`edge:managedWafEnabled` default false). If/when the zone is upgraded to
Pro: `pulumi config set edge:managedWafEnabled true`, `pulumi up` (deploys it
in **log** mode), review Firewall Events for false positives, then change
`_managed_action = "log"` → `"block"` in `edge_security.py` and `pulumi up`.
---
## Phase D — Prod cutover (two isolated steps)
Pick a low-traffic window. `gen.nomadkaraoke.com` depends on this API. The prod
edge rules and the DNS proxy flip are now **separate** switches
(`edge:rolloutStage=prod` vs `edge:proxyProdApi=true`) so we provision + verify
the rules while the API is still DNS-only, then flip the proxy on its own.
12. **Provision prod edge rules (still DNS-only)** 🟢 — extends the WAF /
rate-limit / header-transform rules to the prod host AND brings the prod
`api` record under management (still proxied=False). Because the record
already exists in Cloudflare, IMPORT it first so Pulumi adopts it instead of
creating a duplicate:
```bash
cd infrastructure
pulumi config set edge:rolloutStage prod
# Import the existing prod `api` CNAME (only now does the module manage it):
pulumi import cloudflare:index/dnsRecord:DnsRecord api-dns \
807f07f458f9cd38251f3b7948d55172/6c31cba0080ff334a85cfff6c2927219
pulumi preview # expect: edge rules add api.nomadkaraoke.com; api DnsRecord = NO diff (proxied=False, ttl=1)
pulumi up
```
✅ `api` still resolves direct to `ghs` (no cf-ray); prod WAF/header rules now
exist; the `api` record is managed with proxied=False. Nothing user-facing changed.
13. Set backend `EDGE_AUTH_MODE=warn` in prod and redeploy (observe, don't
block). This is inert until step 14 makes CF inject the header, but staging
it now means the very first proxied requests are only warned, not blocked.
14. **Flip the prod DNS proxy** 🔴 (the single reversible change):
```bash
pulumi config set edge:proxyProdApi true
pulumi preview # expect: ONLY the api DnsRecord proxied False->True; no other diffs
pulumi up
```
15. Verify against **prod** (`HOST=api.nomadkaraoke.com`) — same suite as step 7,
plus a real product smoke test (load `gen.nomadkaraoke.com`, start a job,
confirm signed-URL upload to GCS still works — uploads bypass CF so must be
unaffected). Watch backend logs for `edge-auth` warn lines from any legit
caller missing the header (incl. tenants) before enforcing.
✅ cf-ray present, exploit paths 403, product works end-to-end, no warn spam.
16. Once stable (minutes-hours) and warn logs are clean, set
`EDGE_AUTH_MODE=enforce` in prod + redeploy.
✅ `curl -s -o /dev/null -w '%{http_code}\n' https://karaoke-backend-ipzqd2k4yq-uc.a.run.app/api/jobs` → 403.
### 🔴 Rollback (any time within Phase D)
```bash
cd infrastructure
pulumi config set edge:proxyProdApi false # prod api record → proxied=False (rules stay provisioned)
pulumi up # reverts within one DNS TTL
```
And/or set `EDGE_AUTH_MODE=off` + redeploy backend. Uploads (signed-URL→GCS) are
never affected either way.
---
## Phase E — Cleanup 🟢
17. After prod is stable for ~1 week, remove the staging scaffold: delete
`create_staging_domain_mapping()` + the staging DnsRecord from
`edge_security.py` (and drop `STAGING_API_HOST` from the rule host lists),
`pulumi up`. Keep everything else.
---
## Notes / gotchas captured
- **Uploads bypass the API** (signed-URL direct-to-GCS) → Cloudflare's 100MB
proxy cap is a non-issue.
- **Schedulers** hit the public host `api.nomadkaraoke.com/api/internal/*` → they
traverse CF and get the header automatically; they're **excluded from rate
limiting** but **not** from the origin-lock (they're expected to carry the
header). Their OIDC auth is unchanged.
- **Tenant subdomains** (`singa`, `vocalstar`) — live but idle. They're Cloudflare
Pages frontends that call `api.nomadkaraoke.com` with an `X-Tenant-ID` header
(their own `/api/*` 404s at Cloudflare — no backend passthrough). So they get
the `X-Edge-Auth` header via the proxied `api` host like everyone else and are
NOT expected to break. `warn` mode (steps 13/15) is the safety net — if any
tenant request shows up in the missing-header logs, fix before `enforce`.
Downtime tolerable per Andrew.
- The error-rate alert is a **rate** (req/s), not a true %. Now scoped to 5xx so
client/bot 404s never page.
@@ -0,0 +1,260 @@
# Edge Security Hardening — Cloudflare WAF for `api.nomadkaraoke.com`
**Date:** 2026-07-20
**Branch:** `feat/sess-20260720-1407-edge-security-hardening`
**Trigger:** Prod alert "Karaoke Backend - High Error Rate" fired 2026-07-20 17:43 UTC (0.167 vs 0.1 threshold).
**Prime directive:** *No extended downtime on the product.* `gen.nomadkaraoke.com`
(frontend) depends on `api.nomadkaraoke.com`. Validate every unknown on a
throwaway staging hostname first; the only prod-affecting action is a single,
instantly-reversible DNS proxy flip.
---
## 1. Incident recap & root cause
A single IP (`195.178.110.105`) ran an automated vulnerability scan against
`api.nomadkaraoke.com` — 323 requests/24h, ~1 every 2s — probing secret-exposure
paths (`/.env`, `/etc/passwd`, `/home/*/.ssh/id_rsa`, `wp-config.php`,
`.aws/credentials`, `/proc/self/environ`, …). **Every request returned 404** —
nothing exposed, no functional impact.
It tripped the alert only because on a low-traffic backend, 312/348 requests that
hour were bot 404s (~90%), and the alert counts **all non-2xx** with **no minimum
request-count floor**.
**Why we were reachable — the real gap:**
| Surface | Edge today |
|---|---|
| `nomadkaraoke.com`, `www`, `decide`, `gen` (frontend) | ✅ Proxied through Cloudflare (orange-cloud Pages) |
| **`api.nomadkaraoke.com`** (karaoke-backend) | ❌ **DNS-only** CNAME → `ghs.googlehosted.com`; Cloud Run **ingress=`all`**; no WAF, no rate limit |
Confirmed live: `curl -sI https://api.nomadkaraoke.com/` → `server: Google
Frontend`, no `cf-ray`. `infrastructure/__main__.py:665-673` even exports the
intended DNS record with `"proxied": False`. The API origin is our one
internet-facing surface with zero edge protection, served via a Cloud Run
**domain mapping** (not a Load Balancer) — which is why Cloud Armor can't attach
without re-architecting.
## 2. Decisions (confirmed with Andrew)
- **Architecture:** Cloudflare edge (orange-cloud the API + Cloudflare WAF).
- **Management:** Pulumi IaC (`pulumi_cloudflare`), version-controlled.
- **Scope:** Full — block + WAF/rate-limiting + origin lockdown + alert tuning.
- **Constraint:** ≤1h total downtime, ideally ~zero; test all unknowns off-prod.
## 3. Confirmed facts (from investigation)
- **Backend = FastAPI** (`backend/main.py:147`); existing middleware chain
(`AuditLoggingMiddleware`, `TenantMiddleware`) — clean insertion point.
- **Tenant subdomains — investigated 2026-07-20.** `singa.nomadkaraoke.com` and
`vocalstar.nomadkaraoke.com` are **live but idle**. They are **Cloudflare Pages
frontends** (already proxied; `/api/*` on them 404s at Cloudflare — no backend
passthrough). All their API traffic goes to `api.nomadkaraoke.com` with an
**`X-Tenant-ID` header** (`frontend/lib/tenant.ts`, `lib/api.ts` →
`API_BASE_URL=api.nomadkaraoke.com`), incl. tenant logo assets. So once `api`
is proxied they get the `X-Edge-Auth` header like everyone else — **edge-auth
should NOT break them.** `TenantMiddleware`'s Host-based detection path is
dormant (the backend never receives Host=`*.nomadkaraoke.com` tenant hosts).
Idle + downtime-tolerant per Andrew; `warn` mode catches any missed path.
- **Schedulers call the public host** `https://api.nomadkaraoke.com/api/internal/*`
(`__main__.py:347-445`) via OIDC. Once proxied they traverse Cloudflare and get
the injected secret header automatically — **but must be excluded from rate
limits** (cron bursts) and their OIDC auth is unchanged.
- **Uploads bypass the API** — signed-URL direct-to-GCS
(`karaoke_gen/utils/remote_cli.py:440`, "bypass Cloud Run's 32MB request body
limit"). So Cloudflare's 100MB proxy cap is a **non-issue**; the API is a
control plane (small JSON, async jobs via Cloud Tasks).
- **Only one domain mapping today** (`api.nomadkaraoke.com → karaoke-backend`,
Ready) → we can add a **second staging mapping to the same service** for
end-to-end edge testing without touching prod.
- **Cloudflare token — RESOLVED 2026-07-20.** The `.envrc` `CLOUDFLARE_API_TOKEN`
is the account token `nomadkaraoke-claude` (account `a7dd2a2b…`). It was
originally missing zone DNS/WAF/settings access (DNS records + rulesets +
settings all 403); Andrew added the scopes. **Re-verified:** DNS record
create+delete succeeds, rulesets list 200, zone settings readable/editable. So
`cloudflare:apiToken` can reuse this token. (It's a broad account-admin token;
a dedicated least-privilege zone-scoped token would be nicer but isn't required.)
- **Zone plan = Free** (verified). The **Cloudflare Managed (OWASP) ruleset is
Pro+ only**, so it's **gated off by default** (`edge:managedWafEnabled`,
default false) — deploying it on Free errors. Free DOES support everything
else we use: custom firewall rules (≤5), one rate-limit rule, Transform Rules
(header inject), Bot Fight Mode, Security Level — enough for the path-scanning
threat. Pro (~$20/mo) later unlocks OWASP CRS.
- **Zone id:** `807f07f458f9cd38251f3b7948d55172` (baked in as the default in
`config.py`; overridable via `edge:cloudflareZoneId`).
- **Activation gate:** the whole module is a no-op until `edge:enabled=true`
(default false), so merging it can't make `pulumi up` attempt Cloudflare calls
with the wrong token.
## 4. The dragon: Cloud Run domain mapping × Cloudflare proxy (TLS) — RESOLVED
**Investigated + resolved live on staging 2026-07-20.** The theory:
- A Cloud Run domain mapping provisions a Google-managed cert via ACME, which
needs the host to resolve directly to `ghs` — a proxied (orange) record blocks
issuance; and renewal (~90d) could fail behind the proxy → delayed 525/526.
**What we actually found (staging `api-edge-test.nomadkaraoke.com`):**
- Fresh managed-cert provisioning genuinely **does not work** behind Cloudflare
even grey-cloud — the ACME challenge is never "visible" (confirmed correct DNS,
propagation, no CAA; recreating the mapping didn't help). So the managed cert
stays "pending" indefinitely.
- **BUT the zone SSL mode is "full" (not strict)** — and in "full" mode Cloudflare
encrypts to the origin **without validating the origin cert**. So through the
proxy, the managed cert's status is **irrelevant**: `ghs` serves the request
over TLS that "full" mode accepts, and Cloud Run routes via the domain mapping.
- **Result: the proxied edge works end-to-end** — `GET /` → 200 + `cf-ray` + real
backend JSON; exploit paths → 403 (WAF); `/api/health` → 200.
**Conclusion — no ladder, no run.app Origin Rule, no LB needed.** "Full" mode is
inherently renewal-safe (a never-provisioning / never-renewing managed cert can't
525 when the cert isn't validated). The only rule: **keep the zone on "full"; do
NOT switch to "full (strict)"** unless the managed cert is actually valid (it
can't be, behind CF). The run.app-SNI-override (Origin Rule) was implemented and
then removed — it's blocked anyway by the zone's singleton `http_request_origin`
entrypoint (already used by a flacfetch prod rule) and adds no benefit over "full".
**Prod cutover is therefore simple:** the prod `api` domain mapping already has a
(historically-provisioned) cert, and "full" mode tolerates it regardless — so the
cutover is just the DNS proxy flip; no cert wait, no 525 risk.
## 5. Phased plan (zero-downtime by construction)
### Phase 0 — Immediate mitigation (ship now, independent)
No dependency on the rest; stops paging + blocks the active scanner.
- **0a. Alert retune** (`monitoring.py`, §Phase E) — merge/apply first so scanner
404s stop paging regardless of the WAF timeline.
- **0b. Temporary block** — Cloudflare IP Access Rule / WAF custom rule for
`195.178.110.105` + exploit-path signature (dashboard now, codified in Phase D).
### Phase A — Pulumi Cloudflare bootstrap (no prod effect)
- Add `pulumi-cloudflare` to `infrastructure/requirements.txt`.
- Token as **Pulumi config secret**: `pulumi config set --secret cloudflare:apiToken <token>`.
- Add `CLOUDFLARE_ZONE_ID`, `CLOUDFLARE_ACCOUNT_ID` to `config.py`.
- New module `infrastructure/modules/edge_security.py` (all CF resources; nothing
proxied yet). `pulumi preview` must show only *additive* resources.
### Phase B — Staging validation (the core de-risking; no prod effect)
Prove the entire edge stack on a throwaway host pointing at the **same** service.
1. Add **staging domain mapping** `api-edge-test.nomadkaraoke.com → karaoke-backend`.
2. Add staging **DNS record** grey-cloud (`proxied=False`) → `ghs.googlehosted.com`;
**wait for the Cloud Run managed cert to provision** (proves ACME path).
3. Flip staging DNS to **orange-cloud** with **Full (strict)**; run the
verification suite (§6) against `api-edge-test`:
- `cf-ray` present, 200 on `/`, real endpoints work.
- Exploit paths return **403 from Cloudflare** (not 404 from origin).
- Rate-limit rule trips under a burst; `/api/internal/*` excluded.
- Origin-secret-header: requests via CF pass; direct-to-`*.run.app` gets 403
once middleware is in enforce mode.
- No TLS errors; if 525/handshake issues → step down the SSL ladder (§4) and
re-test until green.
4. **Soak:** leave staging proxied a few days; watch for delayed cert/525 issues.
5. Tear down staging mapping/record after cutover (documented).
### Phase C — Backend origin-lockdown middleware (deploy dormant)
- New `backend/middleware/edge_auth.py` (`BaseHTTPMiddleware`), added after CORS.
- Modes via env: `EDGE_AUTH_MODE=off|warn|enforce` (default `off`), secret from
`EDGE_ORIGIN_SECRET` (Secret Manager). In `warn` it logs missing/invalid header
but allows; in `enforce` it 403s. **Exempt** Cloud Run health/startup probes and
keep it a no-op when `off`, so deploying it changes nothing until we flip modes.
- Unit tests for off/warn/enforce + exempt paths + tenant-host requests.
- Deploy to prod in `off`/`warn` — zero behavior change — before any DNS flip.
### Phase D — WAF / rate-limit / bot rules (staging-scoped, then global)
`cloudflare.Ruleset` resources, initially matched to the **staging host only**,
promoted to zone-wide after staging passes:
1. **Custom firewall** (`http_request_firewall_custom`): block exploit paths
(`\.(env|git|aws)|/\.ssh/|wp-(config|login|admin)|/etc/|/proc/|configuration\.php|\.(mysql|bash)_history`).
2. **Rate limiting** (`http_ratelimit`): >~60 req/min per IP → block; exclude
`/api/internal/*` and known tenant hosts.
3. **Managed ruleset** (`http_request_firewall_managed`): Cloudflare core managed
rules in **log** mode → review → `block`.
4. **Bot Fight Mode** + zone Security Level ≥ Medium.
### Phase E — Alert retune (`infrastructure/modules/monitoring.py`, ~72-105)
Current: counts all non-2xx, `threshold=0.1`, no volume floor.
- Scope to **`response_code_class="5xx"`** (real server errors), or exclude 4xx.
- Add a **minimum-volume gate** (e.g. AND a condition on absolute 5xx count > N/5m)
so a few requests can't trip the ratio.
- Update/add regression test if alert tests exist.
### Phase F — Prod cutover (two isolated steps; instant rollback)
Preconditions: Phases B–E green; middleware live in `warn` in prod. The prod
edge rules and the DNS proxy flip are **separate** switches so we never change
both at once (per CodeRabbit review):
1. **Provision prod rules, still DNS-only** (non-disruptive): `edge:rolloutStage=prod`
+ `pulumi up`. Prod WAF/rate-limit/header rules now exist; `api` still resolves
direct to `ghs` (unchanged).
2. **Flip the DNS proxy** (the only prod-affecting change): `edge:proxyProdApi=true`
+ `pulumi up` — this changes ONLY the `api` record to proxied.
3. Run the §6 verification suite against `api.nomadkaraoke.com`; watch `edge-auth`
warn logs for legit callers missing the header.
4. Rollback if needed → **`edge:proxyProdApi=false` + `pulumi up`** reverts within
one TTL (`ttl=1`/auto), leaving the edge rules provisioned. Upload flow
(signed-URL→GCS) is unaffected throughout.
5. Once stable + warn logs clean, flip middleware to `enforce`; remove the
temporary Phase-0b block (now covered by the codified rules).
## 6. Verification suite (run against staging, then prod)
```bash
HOST=api-edge-test.nomadkaraoke.com # then api.nomadkaraoke.com at cutover
RUNAPP=karaoke-backend-ipzqd2k4yq-uc.a.run.app
# Proxied by Cloudflare (expect server: cloudflare + cf-ray)
curl -sI https://$HOST/ | grep -iE 'server|cf-ray'
# Exploit paths blocked at edge (expect 403 from Cloudflare, not 404)
for p in '.env' 'home/root/.ssh/id_rsa' 'wp-config.php' 'etc/passwd'; do
echo -n "$p -> "; curl -s -o /dev/null -w '%{http_code}\n' "https://$HOST/$p"; done
# Legit control-plane still works (expect 200)
curl -s -o /dev/null -w '%{http_code}\n' https://$HOST/api/health
# Rate limit trips under burst (expect some 429/403 after threshold)
for i in $(seq 1 120); do curl -s -o /dev/null -w '%{http_code} ' https://$HOST/api/health; done; echo
# Origin bypass rejected once middleware enforced (expect 403)
curl -sI https://$RUNAPP/ | head -1
# No long (>100s) synchronous endpoints behind proxy — review slow-request logs
```
## 7. Files to change
1. `infrastructure/requirements.txt` — add `pulumi-cloudflare`.
2. `infrastructure/config.py` — CF zone/account ids, token secret ref.
3. `infrastructure/modules/edge_security.py` — **new**: staging+prod DnsRecord,
Rulesets (custom/rate-limit/managed), Transform Rule (secret header), staging
domain mapping, zone settings.
4. `infrastructure/__main__.py` — wire module; replace `proxied:False` export
(~665-673); staging mapping export.
5. `infrastructure/modules/monitoring.py` — retune error-rate alert (~72-105).
6. `backend/middleware/edge_auth.py` — **new** middleware + register in
`backend/main.py` after CORS; env-driven modes.
7. `backend/config` / deploy env — `EDGE_AUTH_MODE`, `EDGE_ORIGIN_SECRET`.
8. Tests: `tests/.../test_edge_auth_middleware.py`; monitoring test if present.
9. Docs: `infrastructure/README.md` + this runbook.
## 8. Rollback summary (per phase)
- A/C/D/E deploy dormant or additive → revert = normal `pulumi up` / redeploy.
- **B** staging is throwaway → delete mapping+record, zero prod impact.
- **F** cutover → `proxied=False` + `pulumi up` (≤ one TTL). Middleware → set
`EDGE_AUTH_MODE=off`.
## 9. Open questions
Resolved:
- ✅ **Zone id** = `807f07f458f9cd38251f3b7948d55172` (baked in).
- ✅ **Plan tier** = Free → managed WAF ruleset gated off (Pro+ only); rest works.
- ✅ **Token** — the `.envrc` `CLOUDFLARE_API_TOKEN` now has DNS/WAF/settings
scopes (verified via live create+delete). Reuse it for `cloudflare:apiToken`.
- ✅ **Existing `api` DNS record** (id `6c31cba0080ff334a85cfff6c2927219`,
proxied=False, ttl=1) — must be `pulumi import`ed, not created (runbook step 4a).
- ✅ **Tenant subdomains** (`singa`, `vocalstar`) — live but idle Pages frontends
that call the proxied `api` host with `X-Tenant-ID`; not broken by edge-auth
(see §3). Downtime-tolerant per Andrew.
Still open:
- Confirm **no synchronous endpoint** routinely runs >100s under proxy (checked
during staging soak via slow-request logs).
- Do we also want to protect other direct GCP origins (audio-separator,
flacfetch) as a follow-up — same exposure class.
@@ -0,0 +1,136 @@
# Original-Vocals Guide write-path — Design Spec
**Status:** Approved (autonomous session 2026-07-09; brainstormed with Andrew before handoff)
**Repos:** karaoke-gen (emit + push + cleanup) · kjbox (device pull)
**Related:** kjbox `docs/ORIGINAL-VOCALS.md`, `docs/archive/2026-07-06-original-vocals-guide-design.md`; workspace `docs/archive/2026-07-09-karaoke-gen-vocals-writepath-handoff.md`
## Goal
Make the "Original Vocals" sing-along guide **self-maintaining**. When karaoke-gen
finalises a new public NOMAD master, it automatically emits an aligned original-vocals
guide and pushes it to GCS; the kjbox device pulls it into `NOMAD-vocals-padded/`, so the
feature "just works" for new tracks with no re-run of the kjbox retro-fit pipeline.
## Key insight (why this is simpler than the retro-fit)
At render time karaoke-gen **already knows everything** the retro-fit had to *measure*:
- The **isolated vocals stem** is a byproduct of making the karaoke instrumental
(`karaoke_gen/audio_processor.py` separation → `mixed_vocals`).
- The **exact intro offset** is the job's own style value — the master is
`[silent title-card intro] + song + [tail]`, and the intro length is
`intro_video_duration` from the job's resolved style (default 5s, but read the
*actual* value, never hardcode 5).
So the guide is simply `silence[intro] + mixed_vocals`, capped to the master's duration.
**No correlation, no human review, no `align_offsets`/`align_decisions`, no "exclude"** —
the vocals ARE the true original and the alignment is known, so every new public NOMAD
render gets a valid guide for free. This is byte-compatible with what the retro-fit
`pad_vocals.sh` produced (`adelay` + flac), but built for free instead of measured.
## Decisions
| # | Decision | Choice | Rationale |
|--|--|--|--|
| Scope | One spec, both repos | ✅ | Agree the GCS prefix/naming contract once. |
| Vocals stem | `mixed_vocals` (lead + backing) | ✅ | Always produced (Stage 1); matches retro-fit "main vocal, backing left in"; fullest sing-along reference. |
| Emit shape | Padded (`silence[intro]+vocals`), not raw | ✅ | Zero device compute; offset is known at render. |
| Offset | Job's actual `intro_video_duration` | ✅ | Not hardcoded 5s — long-intro styles exist. |
| Length | Cap to 720p master duration (`-t`) | ✅ | Defensive: guide can never bleed past the master. |
| GCS layout | New sibling prefix `files/Nomad Karaoke/vocals-padded/` | ✅ | Parallel to masters `MP4-720p/`; device maps it to `NOMAD-vocals-padded/`. |
| Device pull | Extend existing 5-min timer to `run_sync` twice | ✅ | `run_sync` unchanged (never raises → can't touch masters mirror); no new systemd unit on the live box. |
| Sync mode | **Additive-only** (`vocals_sync_delete_removed=False`) | ✅ | The device already holds 1,459 retro-fit guides absent from the (initially near-empty) GCS prefix; a reconcile would try to delete them. Additive-only removes that risk entirely. |
| Privates | Gate on `is_nomad_public_brand` | ✅ | Skip `NOMADNP`. |
| Cleanup | Delete GCS guide on brand recycle | ✅ | Parallel to `cleanup_nomad_masters`. |
### Known limitation (documented, out of scope)
With additive-only sync, a **recycled** public NOMAD brand code (re-rendered as a
different song) leaves its **old** guide on the device. The play-time resolver globs
`NOMAD-#### - *` and takes `sorted()[0]`, so it could serve the stale vocal under the new
song. Public-NOMAD brand recycling is rare, so this is accepted for now. Future fix:
one-off backfill of the 1,459 existing device guides → the GCS prefix, then flip the
vocals sync to reconcile-enabled so deletes propagate cleanly. Until then, GCS-side
cleanup (`delete_vocals_guides_by_brand`) keeps GCS correct but won't auto-remove a stale
device copy.
## Architecture / data flow
```
karaoke-gen finalize (server flow, backend/services/gdrive_service.py)
has: mixed_vocals stem + job intro_video_duration + freshly built 720p master
├─ build_original_vocals_guide(): ffmpeg -af "adelay={intro_ms}:all=1" -t {master_dur}
│ -c:a flac -f flac → "{brand} - {base_name}.flac" (atomic .part rename)
│ registered as output_files["original_vocals_guide"]
└─ _upload_public_share_files():
push_720p() → gs://…/MP4-720p/{brand} - name.mp4 (existing)
push_vocals_guide() → gs://…/vocals-padded/{brand} - name.flac (NEW, best-effort)
kjbox device (existing 5-min timer: kj-controller/scripts/sync_masters.py :: main())
├─ run_sync(master config) → NOMAD-720p/ (existing, unchanged)
└─ run_sync(vocals config) → NOMAD-vocals-padded/ (NEW, additive-only, no /rescan poke)
play time (unchanged): routes.py::_resolve_vocals_guide() globs "NOMAD-#### - *"
in NOMAD-vocals-padded/ → "Original Vocals" slider works
```
## Components & interfaces
### karaoke-gen
**`build_original_vocals_guide(mixed_vocals_path, intro_seconds, master_duration, dest_path, ffmpeg=...) -> str | None`**
(new helper; lives next to the audio/finalize code that has the separation result + style)
- ffmpeg: `-i mixed_vocals -af "adelay={intro_seconds*1000}:all=1" -t {master_duration} -c:a flac -f flac {dest}.part`, then atomic `os.replace` to `{dest}`.
- `-f flac` is mandatory (the `.part` extension would otherwise confuse the muxer — carried-over gotcha).
- Returns dest path on success, `None` on any failure (best-effort; never raises to the pipeline). Missing inputs → `None`.
- Emits `{brand_code} - {safe_base_name}.flac` (mirrors master naming so the device's brand-prefix glob resolves it).
**`NomadMasterMirror.push_vocals_guide(local_path, filename) -> bool`** (sibling of `push_720p`)
- Uploads to `gs://{divebar_files_bucket}/{nomad_vocals_guide_gcs_prefix}/{filename}`.
- New setting `nomad_vocals_guide_gcs_prefix` (default `"files/Nomad Karaoke/vocals-padded"`).
- Best-effort; returns success.
**`NomadMasterMirror.delete_vocals_guides_by_brand(brand_code) -> int`** (sibling of `delete_masters_by_brand`)
- Deletes `{vocals_prefix}/{brand_code} - *` (requires full `NOMAD-####`, refuses bare/non-Nomad — same guardrail as the master delete).
**Wiring:**
- `_fast_sync_nomad_master`-adjacent (or a new `_fast_sync_vocals_guide`) in `gdrive_service.py` calls `push_vocals_guide` right after the 720p push, gated by `nomad_master_fast_sync_enabled` + `is_nomad_public_brand`, surfacing failure as a distribution warning.
- `cleanup_nomad_masters(brand_code)` gains a sibling call (or is extended) to also delete guides, so every brand-recycle / job-delete path that already cleans masters cleans guides too.
### kjbox
**`sync_masters.py :: main()`** — after the existing master `run_sync`, call `run_sync` again with a vocals config view:
- `source = config["vocals_sync_source"]` (default `gs://nomadkaraoke-divebar-files/files/Nomad Karaoke/vocals-padded/`)
- `dest = config["vocals_sync_dest"]` or derived `{download_folder}/NOMAD-vocals-padded`
- `vocals_sync_enabled` (default False until the device is configured), `vocals_sync_delete_removed=False` (additive-only), and skip the `/rescan` poke (guides are glob-resolved at play time, never indexed).
- `run_sync` itself is **unchanged**; the vocals invocation passes a config dict with the `master_sync_*` keys populated from the `vocals_sync_*` values (thin adapter in `main()`), so the isolation/never-raise contract is preserved verbatim.
- New config keys added to `config.py` defaults.
## Error handling & safety
- **Never fatal.** Emit + push are best-effort; the Drive upload and render already succeeded. A guide failure = a `distribution_warnings` entry (admin alert), nothing more. The nightly Drive→GCS VM remains the masters backfill net (guides are new-renders-only; no VM path yet, acceptable).
- **Masters mirror untouched.** kjbox `run_sync` is not modified; a vocals-sync error returns an error dict and cannot break the masters sync in the same `main()` run.
- **Additive-only** protects the existing device guides (see Decisions).
- **Gating** on `is_nomad_public_brand` keeps `NOMADNP` privates out of the public GCS mirror.
## Testing strategy
**karaoke-gen (pytest):**
- Unit `build_original_vocals_guide`: synthetic tone+silence input → assert output offset (leading silence ≈ intro), duration capped to master, flac muxed via `-f flac`; missing input → `None`; ffmpeg failure → `None` (no raise).
- Unit `push_vocals_guide` / `delete_vocals_guides_by_brand`: mocked `storage.Client` — correct blob prefix, brand gating, best-effort return, bare-brand refusal. Mirror the existing `nomad_master_mirror` tests.
- Unit wiring: guide push is gated + surfaced as a warning like the master push; non-Nomad / disabled → no-op.
**kjbox (pytest, `test_sync_masters.py`):**
- `main()` invokes `run_sync` for both master and vocals configs.
- Vocals invocation is additive-only (`delete_removed=False`) and skips `/rescan`.
- A vocals `run_sync` failure does not fail the masters sync (isolation).
## Rollback
- karaoke-gen: revert the PR; the new GCS prefix simply stops being written. Nothing consumes it, so no user-facing effect either way. `nomad_master_fast_sync_enabled=false` also disables the guide push (shared gate).
- kjbox: `vocals_sync_enabled=false` (default) makes the device change inert; not merged/deployed autonomously — left for a maintenance window.
## Release plan
- **karaoke-gen:** full ship to `main` (main-based; Cloud Run deploys on merge). Change is inert until kjbox lands, so safe.
- **kjbox:** implement + test + PR only. **Not merged/deployed** in this session — live production device; merge+deploy is Andrew's call during a maintenance window (kjbox `CLAUDE.md`).
+1
View File
@@ -23,3 +23,4 @@ messages/.en-snapshot.json
# Generated at build time by scripts/write-version.mjs
public/version.json
e2e/fixtures/*.mp3
+17 -1
View File
@@ -2,7 +2,7 @@
* Unit tests for job-status.ts utility functions
*/
import { getJobStep, formatStepIndicator, isBlockingStatus, isNotifiableBlockingStatus, getJobProgressPercent, sortJobsByDate, isAutoRetryPending, JobStep, STATUS_CONFIG } from '../lib/job-status';
import { getJobStep, formatStepIndicator, isBlockingStatus, isNotifiableBlockingStatus, getJobProgressPercent, sortJobsByDate, isAutoRetryPending, shouldShowJobOnDashboard, JobStep, STATUS_CONFIG } from '../lib/job-status';
import type { Job } from '../lib/api';
// Helper to create a minimal Job object for testing
@@ -597,3 +597,19 @@ describe('isAutoRetryPending', () => {
expect(isAutoRetryPending({ state_data: { cloud_run_retry_pending: {} } })).toBe(false);
});
});
describe('shouldShowJobOnDashboard', () => {
it('shows normal (non-audio-selection) jobs', () => {
expect(shouldShowJobOnDashboard({ status: 'complete' })).toBe(true);
expect(shouldShowJobOnDashboard({ status: 'awaiting_review' })).toBe(true);
});
it('hides self-service jobs still in the guided-flow at awaiting_audio_selection', () => {
expect(shouldShowJobOnDashboard({ status: 'awaiting_audio_selection' })).toBe(false);
expect(shouldShowJobOnDashboard({ status: 'awaiting_audio_selection', made_for_you: false })).toBe(false);
});
it('keeps made-for-you orders visible even at awaiting_audio_selection', () => {
expect(shouldShowJobOnDashboard({ status: 'awaiting_audio_selection', made_for_you: true })).toBe(true);
});
});
+100 -2
View File
@@ -2,7 +2,7 @@
* @jest-environment jsdom
*/
import React from 'react'
import { render, screen, waitFor, fireEvent } from '@testing-library/react'
import { render, screen, waitFor, fireEvent, act } from '@testing-library/react'
import { NextIntlClientProvider } from 'next-intl'
import messages from '@/messages/en.json'
@@ -37,10 +37,13 @@ jest.mock('@/lib/auth', () => {
// Referral helper is incidental.
jest.mock('@/lib/referral', () => ({ setReferralCode: jest.fn() }))
// API client — only the resend method matters here.
// API client. getMagicLinkStatus decides the initial UI (gate vs. dead-link);
// resendMagicLinkFromToken drives the recovery flow.
const resendMock = jest.fn()
const getStatusMock = jest.fn()
jest.mock('@/lib/api', () => ({
api: {
getMagicLinkStatus: (token: string) => getStatusMock(token),
resendMagicLinkFromToken: (token: string) => resendMock(token),
},
}))
@@ -56,16 +59,105 @@ function wrap(ui: React.ReactElement) {
)
}
/**
* The verify page gates verification behind an explicit click so that
* automated email link-scanners (which render the page but never click)
* cannot burn the single-use token before the real user acts.
* Every flow that needs a verification result must click through this gate.
*/
async function clickConfirmToVerify() {
const confirmButton = await screen.findByRole('button', { name: /Complete Sign-?In/i })
// Wrap in act + await so the async verify() state updates flush inside act.
await act(async () => {
fireEvent.click(confirmButton)
})
}
describe('VerifyMagicLinkPage — scanner-safety gate (valid link)', () => {
beforeEach(() => {
pushMock.mockClear()
resendMock.mockReset()
verifyMagicLinkMock.mockClear()
getStatusMock.mockReset()
getStatusMock.mockResolvedValue({ status: 'valid' })
})
it('does NOT verify the token on mount (link-scanners must not burn it)', async () => {
render(wrap(<VerifyMagicLinkPage />))
// The confirm prompt is shown for a valid link...
expect(
await screen.findByRole('button', { name: /Complete Sign-?In/i }),
).toBeInTheDocument()
// ...the status check is read-only, and no verification happened.
expect(getStatusMock).toHaveBeenCalledWith(tokenParam)
expect(verifyMagicLinkMock).not.toHaveBeenCalled()
})
it('verifies with the token only after the user clicks Complete Sign-In', async () => {
render(wrap(<VerifyMagicLinkPage />))
await clickConfirmToVerify()
await waitFor(() =>
expect(verifyMagicLinkMock).toHaveBeenCalledWith(tokenParam),
)
})
})
describe('VerifyMagicLinkPage — already-used / expired link', () => {
beforeEach(() => {
pushMock.mockClear()
resendMock.mockReset()
verifyMagicLinkMock.mockClear()
getStatusMock.mockReset()
})
it('shows the failure UI upfront (no gate, no verify) when the link is already used', async () => {
getStatusMock.mockResolvedValue({ status: 'used' })
render(wrap(<VerifyMagicLinkPage />))
// Failure UI + one-click resend appear without the user clicking anything.
expect(await screen.findByText('Sign-in failed')).toBeInTheDocument()
expect(
screen.getByRole('button', { name: /Email me a new link/i }),
).toBeInTheDocument()
// No "Complete Sign-In" gate, and the token was never sent to verify.
expect(
screen.queryByRole('button', { name: /Complete Sign-?In/i }),
).not.toBeInTheDocument()
expect(verifyMagicLinkMock).not.toHaveBeenCalled()
})
it('falls back to the gate if the status check itself errors (never block a valid user)', async () => {
getStatusMock.mockRejectedValue(new Error('status endpoint down'))
render(wrap(<VerifyMagicLinkPage />))
expect(
await screen.findByRole('button', { name: /Complete Sign-?In/i }),
).toBeInTheDocument()
expect(verifyMagicLinkMock).not.toHaveBeenCalled()
})
})
describe('VerifyMagicLinkPage — resend recovery flow', () => {
beforeEach(() => {
pushMock.mockClear()
resendMock.mockReset()
verifyMagicLinkMock.mockClear()
getStatusMock.mockReset()
getStatusMock.mockResolvedValue({ status: 'valid' })
})
it('shows "Email me a new link" button after verification fails', async () => {
render(wrap(<VerifyMagicLinkPage />))
await clickConfirmToVerify()
await waitFor(() => {
expect(screen.getByText('Sign-in failed')).toBeInTheDocument()
})
@@ -84,6 +176,8 @@ describe('VerifyMagicLinkPage — resend recovery flow', () => {
render(wrap(<VerifyMagicLinkPage />))
await clickConfirmToVerify()
const button = await screen.findByRole('button', { name: /Email me a new link/i })
fireEvent.click(button)
@@ -102,6 +196,8 @@ describe('VerifyMagicLinkPage — resend recovery flow', () => {
render(wrap(<VerifyMagicLinkPage />))
await clickConfirmToVerify()
fireEvent.click(await screen.findByRole('button', { name: /Email me a new link/i }))
expect(
@@ -114,6 +210,8 @@ describe('VerifyMagicLinkPage — resend recovery flow', () => {
render(wrap(<VerifyMagicLinkPage />))
await clickConfirmToVerify()
fireEvent.click(await screen.findByRole('button', { name: /Email me a new link/i }))
await waitFor(() => {
+41 -1
View File
@@ -1,7 +1,47 @@
/**
* @jest-environment jsdom
*/
import { isStale, hardReload, __resetForTest, __setBuildShaForTest } from '@/lib/version-check'
import {
isStale,
hardReload,
isChunkLoadError,
__resetForTest,
__setBuildShaForTest,
} from '@/lib/version-check'
describe('version-check.isChunkLoadError', () => {
it('matches webpack ChunkLoadError by name', () => {
const e = new Error('boom')
e.name = 'ChunkLoadError'
expect(isChunkLoadError(e)).toBe(true)
})
it('matches webpack "Loading chunk <id> failed" message', () => {
expect(isChunkLoadError(new Error('Loading chunk 429 failed'))).toBe(true)
})
it.each([
// Turbopack (Next.js 16 default) — a plain Error, no ChunkLoadError name.
'Failed to load chunk /_next/static/chunks/e66613528f386db8.js from module 64893',
'Failed to load chunk /_next/static/chunks/abc.js as a runtime dependency of chunk 12',
'Failed to load chunk /_next/static/chunks/abc.js from an HMR update',
])('matches Turbopack chunk-load message: %s', (msg) => {
expect(isChunkLoadError(new Error(msg))).toBe(true)
})
it('matches native ESM dynamic-import failures', () => {
expect(
isChunkLoadError(new Error('Failed to fetch dynamically imported module: https://x/y.js')),
).toBe(true)
expect(isChunkLoadError(new Error('Importing a module script failed.'))).toBe(true)
})
it('ignores unrelated errors and falsy input', () => {
expect(isChunkLoadError(new Error('Cannot read properties of undefined'))).toBe(false)
expect(isChunkLoadError(null)).toBe(false)
expect(isChunkLoadError(undefined)).toBe(false)
})
})
describe('version-check.isStale', () => {
const fetchMock = jest.fn()
+18 -3
View File
@@ -18,7 +18,7 @@ import {
} from "@/components/ui/select"
import { Music2, RefreshCw, Loader2, Search, Gift, X, Shield, ShieldOff } from "lucide-react"
import { useTranslations } from "next-intl"
import { sortJobsByDate } from "@/lib/job-status"
import { sortJobsByDate, shouldShowJobOnDashboard } from "@/lib/job-status"
import { WarmingUpLoader } from "@/components/WarmingUpLoader"
import { JobCard } from "@/components/job"
import { GuidedJobFlow } from "@/components/job/GuidedJobFlow"
@@ -88,9 +88,10 @@ function AppPageContent() {
// Check if user is admin (for exclude_test parameter)
const isAdmin = user?.role === "admin" || user?.email?.endsWith("@nomadkaraoke.com")
// Filter out in-progress search jobs (managed by the guided flow, not standalone cards)
// Hide self-service jobs still in the guided-flow wizard, but keep made-for-you orders
// visible even at awaiting_audio_selection (see shouldShowJobOnDashboard).
const jobs = useMemo(
() => allJobs.filter(job => job.status !== 'awaiting_audio_selection'),
() => allJobs.filter(shouldShowJobOnDashboard),
[allJobs]
)
@@ -100,6 +101,20 @@ function AppPageContent() {
return () => clearTimeout(timer)
}, [searchInput])
// Honor a `status` URL param (e.g. made-for-you admin email deep-links to
// /app/?admin_token=...&status=awaiting_audio_selection). Applied on mount before
// the admin_token handler strips the query string, so the actionable queue is shown.
useEffect(() => {
const statusParam = searchParams.get("status")
if (statusParam) {
setStatusFilter(statusParam)
if (typeof window !== "undefined") {
localStorage.setItem("nomad-karaoke-status-filter", statusParam)
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
// Memoize loadJobs for use with visibility refresh
const loadJobs = useCallback(async () => {
if (!getAccessToken()) {
+82 -9
View File
@@ -10,27 +10,40 @@ import { setReferralCode } from "@/lib/referral"
import { api } from "@/lib/api"
import { useTranslations } from "next-intl"
type VerifyState = "verifying" | "preparing" | "credits_granted" | "credits_denied" | "credits_pending" | "success" | "error"
type VerifyState = "checking" | "confirm" | "verifying" | "preparing" | "credits_granted" | "credits_denied" | "credits_pending" | "success" | "error"
type ResendState = "idle" | "sending" | "sent" | "no_token" | "failed"
function VerifyMagicLinkContent() {
const t = useTranslations('auth')
const router = useRouter()
const searchParams = useSearchParams()
const [state, setState] = useState<VerifyState>("verifying")
// Start in "checking": a read-only status probe runs on mount to decide the
// initial UI. A VALID link shows the "Complete Sign-In" gate — an explicit
// click is required before we spend the single-use token, so automated email
// link-scanners (Gmail/Safe-Browsing, corporate security proxies) that render
// this page and run its JS can't burn the token (they don't click). A DEAD
// link (already used / expired) shows the failure UI upfront, so the user
// isn't offered a button that will only fail when clicked.
const [state, setState] = useState<VerifyState>("checking")
const [errorMessage, setErrorMessage] = useState("")
const [creditsGranted, setCreditsGranted] = useState(0)
const [creditStatus, setCreditStatus] = useState<string>("not_applicable")
const [originalToken, setOriginalToken] = useState<string | null>(null)
const [resendState, setResendState] = useState<ResendState>("idle")
const [resendMaskedEmail, setResendMaskedEmail] = useState<string | null>(null)
const hasSetup = useRef(false)
const hasVerified = useRef(false)
const { verifyMagicLink, user, error } = useAuth()
// Mount-time setup — deliberately does NOT verify (consume) the token. It
// stores the referral code, remembers the token, and runs a READ-ONLY status
// probe to pick the initial UI. The status check does not mutate the token,
// so a scanner rendering this page can't burn a valid link; consumption still
// happens only when the user clicks "Complete Sign-In".
useEffect(() => {
if (hasVerified.current) return
hasVerified.current = true
if (hasSetup.current) return
hasSetup.current = true
const token = searchParams.get("token")
@@ -46,10 +59,36 @@ function VerifyMagicLinkContent() {
return
}
// Remember the original token so the failure UI can offer a one-click
// resend without forcing the user to re-enter their email.
// Remember the original token so both the confirm action and the failure
// UI's one-click resend can use it without re-entering an email.
setOriginalToken(token)
// Read-only probe: show the gate for a valid link, or the failure UI upfront
// for an already-used/expired one. If the probe itself fails, fall back to
// the gate so a transient error never blocks a user with a valid link.
api.getMagicLinkStatus(token)
.then(({ status }) => {
if (status === "valid") {
setState("confirm")
} else {
setState("error")
setErrorMessage(t('linkExpiredOrUsed'))
}
})
.catch(() => setState("confirm"))
}, [searchParams, t])
const handleConfirm = async () => {
// Guard against double-clicks / re-entrancy — the token is single-use.
if (hasVerified.current) return
const token = originalToken ?? searchParams.get("token")
if (!token) {
setState("error")
setErrorMessage(t('noVerificationToken'))
return
}
hasVerified.current = true
const verify = async () => {
// Show "preparing your account" while the backend runs AI evaluation
setState("preparing")
@@ -96,8 +135,8 @@ function VerifyMagicLinkContent() {
}
}
verify()
}, [searchParams, verifyMagicLink, router, t])
await verify()
}
const goToApp = () => router.push("/app")
const goToBuy = () => router.push("/app?buy=true")
@@ -120,7 +159,41 @@ function VerifyMagicLinkContent() {
return (
<div className="max-w-md w-full bg-card border border-border rounded-xl p-8 text-center">
{/* Verifying token */}
{/* Checking link status (read-only probe, does not consume the token) */}
{state === "checking" && (
<>
<Loader2 className="w-12 h-12 text-primary animate-spin mx-auto mb-4" />
<h1 className="text-xl font-semibold text-foreground mb-2">
{t('pleaseWait')}
</h1>
<p className="text-muted-foreground">
{t('verifyingWait')}
</p>
</>
)}
{/* Confirm gate — an explicit click is required before we spend the
single-use token, so automated email link-scanners that render this
page (but never click) can't burn the link before the real user. */}
{state === "confirm" && (
<>
<Mail className="w-12 h-12 text-primary mx-auto mb-4" />
<h1 className="text-xl font-semibold text-foreground mb-2">
{t('confirmTitle')}
</h1>
<p className="text-muted-foreground mb-6">
{t('confirmBody')}
</p>
<Button
onClick={handleConfirm}
className="w-full bg-primary hover:bg-primary/90"
>
{t('confirmButton')}
</Button>
</>
)}
{/* Verifying token (transient, after the user confirms) */}
{state === "verifying" && (
<>
<Loader2 className="w-12 h-12 text-primary animate-spin mx-auto mb-4" />
@@ -495,6 +495,9 @@ export function AudioEditor({ job }: AudioEditorProps) {
const seekTo = useCallback((time: number) => {
const audio = audioRef.current
if (!audio) return
// Math.min/max propagate NaN, so a non-finite input still throws on the
// currentTime assignment — reject it before clamping.
if (!Number.isFinite(time)) return
audio.currentTime = Math.max(0, Math.min(time, audio.duration || currentDuration))
setCurrentTime(audio.currentTime)
}, [currentDuration])
@@ -134,6 +134,9 @@ export default function AudioPlayer({ audioUrl, onTimeUpdate }: AudioPlayerProps
const handleSeek = (value: number[]) => {
if (!audioRef.current || !isReadyRef.current) return
const time = value[0]
// Non-finite (NaN/Infinity) throws "The provided double value is
// non-finite" when assigned to currentTime — guard the sink.
if (!Number.isFinite(time)) return
audioRef.current.currentTime = time
setCurrentTime(time)
}
@@ -146,6 +149,9 @@ export default function AudioPlayer({ audioUrl, onTimeUpdate }: AudioPlayerProps
const seekAndPlay = useCallback((time: number) => {
if (!audioRef.current || !isReadyRef.current) return
// A non-finite target (e.g. a click that resolved to NaN/Infinity) throws
// on assignment to currentTime; drop it rather than crash the review UI.
if (!Number.isFinite(time)) return
audioRef.current.currentTime = time
setCurrentTime(time)
@@ -44,6 +44,7 @@ import {
deleteWord,
} from '@/lib/lyrics-review/utils/segmentOperations'
import { generateStorageKey } from '@/lib/lyrics-review/utils/localStorage'
import { countUntimedWords } from '@/lib/lyrics-review/utils/timingCompleteness'
import { createLocalSessionStore, type LocalSessionStore } from '@/lib/lyrics-review/utils/localSessionStore'
import {
setupKeyboardHandlers,
@@ -386,22 +387,25 @@ export default function LyricsAnalyzer({
setSessionRestoreOpen(true)
}, [sessionClient])
// Warm up encoding worker VM when lyrics review page loads
// Warm up encoding worker VM when lyrics review page loads.
// Only in cloud mode (jobId present) — the endpoint is review-auth scoped to
// the job, and there's no cloud encoding VM to warm in local mode.
useEffect(() => {
if (!isReadOnly) {
warmupEncodingWorker()
if (!isReadOnly && jobId) {
warmupEncodingWorker(jobId)
}
}, []) // eslint-disable-line react-hooks/exhaustive-deps
// Debounced heartbeat — keeps VM alive during active editing
const lastHeartbeat = useRef(0)
const sendHeartbeat = useCallback(() => {
if (!jobId) return
const now = Date.now()
if (now - lastHeartbeat.current > 60_000) {
lastHeartbeat.current = now
heartbeatEncodingWorker()
heartbeatEncodingWorker(jobId)
}
}, [])
}, [jobId])
// Heartbeat the encoding worker as the reviewer works. Crash recovery /
// restore now flows entirely through review sessions (server in cloud mode,
@@ -989,6 +993,18 @@ export default function LyricsAnalyzer({
const handleSubmitToServer = useCallback(async () => {
if (!apiClient) return
// Block submission of lyrics that still have no timing (e.g. custom lyrics
// pasted into the synchronizer but never tap-synced). These otherwise reach
// the render pipeline and fail the job with a cryptic NoneType error; catch
// it here with an actionable message so the user can synchronize first.
const untimed = countUntimedWords(data.corrected_segments)
if (untimed > 0) {
toast.error(
`${untimed} lyric word(s) have no timing yet. Open the synchronizer and tap each line to the beat before generating the video.`
)
return
}
setIsSubmitting(true)
try {
const dataToSubmit =
@@ -1054,6 +1070,9 @@ export default function LyricsAnalyzer({
if (typeof window !== 'undefined' && window.seekAndPlayAudio) {
const adjustedStartTime =
timingOffsetMs !== 0 ? startTime + timingOffsetMs / 1000 : startTime
// A caller can resolve to a non-finite time (e.g. an untimed segment or
// a zero-width timeline click); don't forward it to the media element.
if (!Number.isFinite(adjustedStartTime)) return
window.seekAndPlayAudio(adjustedStartTime)
}
},
@@ -213,9 +213,13 @@ export default function TimelineEditor({
const handleTimelineClick = (e: React.MouseEvent) => {
const rect = containerRef.current?.getBoundingClientRect()
if (!rect || !onPlaySegment) return
// A not-yet-laid-out container has zero width, making the ratio non-finite;
// bail so we never hand a NaN/Infinity time to the audio element.
if (rect.width <= 0) return
const x = e.clientX - rect.left
const clickedPosition = (x / rect.width) * (endTime - startTime) + startTime
if (!Number.isFinite(clickedPosition)) return
onPlaySegment(clickedPosition)
}
@@ -75,6 +75,30 @@ describe('AudioPlayer readiness gating', () => {
expect(created[0].currentTime).toBe(12)
})
it('ignores non-finite seek targets instead of crashing the media element', () => {
renderPlayer()
fireOnAudio('canplaythrough')
expect(window.isAudioReady).toBe(true)
// NaN / Infinity would throw "The provided double value is non-finite"
// in a real browser. The guard must no-op: never seek, never play.
act(() => {
window.seekAndPlayAudio?.(Number.NaN)
})
act(() => {
window.seekAndPlayAudio?.(Number.POSITIVE_INFINITY)
})
expect(created[0].play).not.toHaveBeenCalled()
expect(Number.isFinite(created[0].currentTime)).toBe(true)
// A finite target still works.
act(() => {
window.seekAndPlayAudio?.(7)
})
expect(created[0].currentTime).toBe(7)
expect(created[0].play).toHaveBeenCalledTimes(1)
})
it('reveals playback controls and publishes ready once canplaythrough fires', () => {
const onReady = jest.fn()
window.addEventListener(AUDIO_READY_EVENT, onReady)
+46
View File
@@ -5,6 +5,52 @@
import { Page, APIRequestContext } from '@playwright/test';
import { STORAGE_KEYS, URLS, TIMEOUTS } from './constants';
/**
* Click through the "Complete Sign-In" gate on the magic-link verify page.
*
* As of #870 (fix(auth): gate magic-link verify behind explicit click), the
* `/auth/verify` page no longer auto-consumes the single-use token on mount.
* Instead it runs a read-only status probe and, for a valid link, shows a
* "Complete Sign-In" confirm gate. The token is only spent when this button
* is clicked — this protects the link from email scanners / security proxies
* that render the page (and run its JS) but never click.
*
* E2E tests navigate directly to the magic link, so they must click this gate
* themselves. Call this AFTER `page.goto(magicLink)` and BEFORE waiting for
* the post-sign-in states (success / credit interstitial).
*
* If the verify page shows the failure UI instead of the gate (e.g. the link
* was genuinely already used or expired), this throws with the on-page detail
* so the failure is diagnosable rather than a bare 30s timeout.
*/
export async function clickCompleteSignInGate(page: Page): Promise<void> {
const confirmButton = page.getByRole('button', { name: /complete sign-?in/i });
const failureHeading = page.getByText(/sign-in failed/i);
const outcome = await Promise.race([
confirmButton
.waitFor({ state: 'visible', timeout: 30000 })
.then(() => 'gate' as const),
failureHeading
.waitFor({ state: 'visible', timeout: 30000 })
.then(() => 'failure' as const),
]);
if (outcome === 'failure') {
const detail = await page
.locator('.text-muted-foreground')
.first()
.textContent()
.catch(() => null);
throw new Error(
`Magic-link verify page showed the failure UI instead of the "Complete Sign-In" gate` +
` (link already used / expired?): ${detail?.trim() ?? 'no detail'}`
);
}
await confirmButton.click();
}
/**
* Set the auth token in localStorage before page navigation.
* Must be called BEFORE navigating to the page.
@@ -2,7 +2,7 @@
import { test, expect } from '@playwright/test';
import { createEmailHelper, isEmailTestingAvailable } from '../helpers/email-testing';
import { completeStripeCheckout } from '../helpers/stripe-checkout';
import { getPageAuthToken } from '../helpers/auth';
import { getPageAuthToken, clickCompleteSignInGate } from '../helpers/auth';
import { URLS, TIMEOUTS } from '../helpers/constants';
import * as fs from 'fs';
import * as path from 'path';
@@ -83,6 +83,11 @@ test.describe('Real Credit Purchase Flow', () => {
// Navigate to magic link
await page.goto(magicLink);
// Click the "Complete Sign-In" gate (verify page no longer auto-consumes
// the token on mount — see #870). This spends the single-use token.
await clickCompleteSignInGate(page);
console.log(' Clicked "Complete Sign-In" gate');
// Handle verification result (new user interstitial or direct success)
const verifyResult = await Promise.race([
page.getByText(/successfully signed in/i).waitFor({ state: 'visible', timeout: 30000 }).then(() => 'success'),
@@ -1,5 +1,6 @@
import { test, expect, Page, APIRequestContext } from '@playwright/test';
import { createEmailHelper, isEmailTestingAvailable } from '../helpers/email-testing';
import { clickCompleteSignInGate } from '../helpers/auth';
/**
* Production E2E Test - Full User Journey
@@ -235,6 +236,10 @@ test.describe('Production E2E - Full User Journey', () => {
}
await page.goto(magicLinkUrl);
// Click the "Complete Sign-In" gate (verify page no longer auto-consumes
// the token on mount — see #870). This spends the single-use token.
await clickCompleteSignInGate(page);
// Wait for successful verification and redirect
await expect(
page.getByText(/successfully signed in/i)
@@ -1,5 +1,6 @@
import { test, expect, Page, BrowserContext } from '@playwright/test';
import { createEmailHelper, isEmailTestingAvailable } from '../helpers/email-testing';
import { clickCompleteSignInGate } from '../helpers/auth';
/**
* E2E Happy Path Test - Real User Journey with Full UI Interactions
@@ -335,6 +336,11 @@ test.describe('E2E Happy Path - Real User with Full UI Interactions', () => {
await page.goto(magicLinkUrl);
console.log(' Navigated to magic link verification page');
// Click the "Complete Sign-In" gate (verify page no longer auto-consumes
// the token on mount — see #870). This spends the single-use token.
await clickCompleteSignInGate(page);
console.log(' Clicked "Complete Sign-In" gate');
// Wait for verification to complete — new users see a credit interstitial
// (credits_granted, credits_denied, or credits_pending), returning users
// see "Successfully signed in!". Handle all cases.
@@ -0,0 +1,280 @@
import { test, expect } from '@playwright/test';
import * as path from 'path';
import * as fs from 'fs';
import { createEmailHelper, isEmailTestingAvailable, EmailHelper } from '../helpers/email-testing';
import { clickCompleteSignInGate } from '../helpers/auth';
// Real test audio (mixed + instrumental), gitignored under e2e/fixtures.
// Populate with scripts/e2e/fetch_test_audio.sh (CI + local).
const MIXED_AUDIO = path.resolve(__dirname, '../fixtures/e2e-mixed.mp3');
const INSTRUMENTAL_AUDIO = path.resolve(__dirname, '../fixtures/e2e-instrumental.mp3');
/**
* Tenant Portal Happy Path — Production E2E (frontend journey)
*
* Drives the full tenant operator journey through the tenant portal UI, exactly
* as a real operator would, so it is representative of the user experience AND
* fires the encoding-worker warmup (on review-page load) that keeps the encoder
* alive for the render. Replaces the API-driven scripts/e2e/tenant_e2e.py.
*
* Parametrized per tenant via env:
* TENANT_ID vocalstar | singa (default: vocalstar)
* TENANT_PORTAL_URL https://{tenant}.nomadkaraoke.com
*
* Requires: TESTMAIL_API_KEY, TESTMAIL_NAMESPACE, E2E_ADMIN_TOKEN.
* The tenant must allowlist inbox.testmail.app in auth.allowed_email_domains.
*/
const TENANT_ID = process.env.TENANT_ID || 'vocalstar';
const PORTAL_URL = process.env.TENANT_PORTAL_URL || `https://${TENANT_ID}.nomadkaraoke.com`;
const API_URL = 'https://api.nomadkaraoke.com';
const ADMIN_TOKEN = process.env.E2E_ADMIN_TOKEN || process.env.KARAOKE_ADMIN_TOKEN || '';
const T = {
action: 30_000,
transcription: 900_000, // 15 min to reach review
render: 1_800_000, // 30 min to complete render
full: 3_000_000, // 50 min whole-test budget
};
test.describe(`Tenant Portal Happy Path — ${TENANT_ID}`, () => {
test.describe.configure({ retries: 0 });
let emailHelper: EmailHelper | null = null;
let createdJobId: string | null = null;
test.beforeAll(async () => {
if (isEmailTestingAvailable()) emailHelper = await createEmailHelper();
});
test.afterAll(async () => {
if (createdJobId && ADMIN_TOKEN) {
// DELETE /api/jobs/{id} uses require_auth + ownership; admins bypass.
await fetch(`${API_URL}/api/jobs/${createdJobId}`, {
method: 'DELETE',
headers: { Authorization: `Bearer ${ADMIN_TOKEN}` },
}).catch(() => {});
console.log(`[${TENANT_ID}] Cleaned up job ${createdJobId}`);
}
});
test('Full tenant journey: login -> submit -> review -> render -> distribution', async ({ page }) => {
test.skip(!emailHelper, 'Email testing not configured (TESTMAIL_API_KEY/NAMESPACE)');
test.skip(
!fs.existsSync(MIXED_AUDIO) || !fs.existsSync(INSTRUMENTAL_AUDIO),
'Test audio missing — run scripts/e2e/fetch_test_audio.sh',
);
test.setTimeout(T.full);
// The shared prod config sets a global `x-playwright-test` header on every
// request (playwright.production.config.ts). On the cross-origin PUT to the
// GCS signed URL that header makes the browser's CORS preflight request an
// extra header the bucket's CORS policy (Content-Type only) doesn't allow,
// so the upload fails — a test-harness artifact, not a product bug (verified
// the same PUT succeeds in a real browser). Strip it only for GCS uploads.
await page.route('https://storage.googleapis.com/**', async (route) => {
const headers = { ...route.request().headers() };
delete headers['x-playwright-test'];
await route.continue({ headers });
});
// =====================================================================
// Sign in via the tenant portal magic-link UI
// =====================================================================
const inbox = await emailHelper!.createInbox();
console.log(`[${TENANT_ID}] Test inbox: ${inbox.emailAddress}`);
await page.goto(`${PORTAL_URL}/app`, { waitUntil: 'domcontentloaded', timeout: T.action });
// Tenant landing shows a single "Sign In" button that opens the auth dialog.
const signInTrigger = page.getByRole('button', { name: /sign in/i }).first();
await expect(signInTrigger).toBeVisible({ timeout: T.action });
await signInTrigger.click();
const authDialog = page.getByRole('dialog');
await expect(authDialog).toBeVisible({ timeout: T.action });
await authDialog.getByPlaceholder('you@example.com').fill(inbox.emailAddress);
const sendLinkButton = authDialog.getByRole('button', { name: /send sign-in link/i });
await expect(sendLinkButton).toBeEnabled({ timeout: T.action });
await sendLinkButton.click();
await expect(page.getByText(/check your email/i)).toBeVisible({ timeout: 15_000 });
console.log(`[${TENANT_ID}] Magic-link email requested`);
const email = await emailHelper!.waitForEmail(inbox.id, 60_000);
const magicLink = emailHelper!.extractMagicLink(email);
if (!magicLink) {
console.log(' Email body preview:', (email.body || '').substring(0, 500));
throw new Error('Could not extract magic link from tenant sign-in email');
}
console.log(`[${TENANT_ID}] Magic link received`);
await page.goto(magicLink);
// Verify page gates behind an explicit "Complete Sign-In" click (see #870).
await clickCompleteSignInGate(page);
// New users (incl. first tenant login) see a credit interstitial; returning
// users see "Successfully signed in!". Handle both, then land on /app.
const verifyResult = await Promise.race([
page.getByText(/successfully signed in/i).waitFor({ state: 'visible', timeout: T.action }).then(() => 'success'),
page.getByText(/welcome to nomad karaoke/i).waitFor({ state: 'visible', timeout: T.action }).then(() => 'credits_interstitial'),
page.getByText(/sign-in failed/i).waitFor({ state: 'visible', timeout: T.action }).then(() => 'error'),
]);
if (verifyResult === 'error') {
const detail = await page.locator('.text-muted-foreground').first().textContent().catch(() => null);
throw new Error(`Tenant magic-link verification failed: ${detail ?? 'unknown'}`);
}
if (verifyResult === 'credits_interstitial') {
const startButton = page.getByRole('button', { name: /start creating|go to dashboard|explore the app/i });
await expect(startButton).toBeVisible({ timeout: T.action });
await startButton.click();
}
await page.waitForURL(/\/app/, { timeout: T.action });
const token = await page.evaluate(() => localStorage.getItem('karaoke_access_token'));
expect(token, 'authenticated token present after magic-link login').toBeTruthy();
console.log(`[${TENANT_ID}] Signed in via magic-link UI (${verifyResult})`);
// =====================================================================
// Submit a track through the tenant portal form
// =====================================================================
const uniqueTitle = `E2E ${TENANT_ID} ${new Date().toISOString().replace(/[:.]/g, '-')}`;
await page.getByLabel('Artist').fill('Nomad E2E');
await page.getByLabel('Title').fill(uniqueTitle);
await page.locator('#tenant-mixed-audio').setInputFiles(MIXED_AUDIO);
await page.locator('#tenant-instrumental-audio').setInputFiles(INSTRUMENTAL_AUDIO);
await page.getByRole('button', { name: /submit track/i }).click();
await expect(page.getByText(/track submitted/i)).toBeVisible({ timeout: 120_000 });
const jobIdText = await page.locator('[data-testid="created-job-id"]').textContent();
createdJobId = (jobIdText || '').replace(/^ID:\s*/i, '').trim() || null;
expect(createdJobId, 'created job id captured from tenant submit').toBeTruthy();
console.log(`[${TENANT_ID}] Submitted job ${createdJobId}: ${uniqueTitle}`);
// =====================================================================
// Wait for transcription, then open the review UI (fires warmup)
// =====================================================================
await page.goto(`${PORTAL_URL}/app`, { waitUntil: 'domcontentloaded' });
let reviewLink = null;
const reviewDeadline = Date.now() + T.transcription;
while (Date.now() < reviewDeadline) {
const link = page.getByRole('link', { name: /review lyrics/i }).first();
// waitFor (not instant isVisible) so the client-side job-list fetch has
// time to render each iteration; reload + retry if not ready yet.
try {
await link.waitFor({ state: 'visible', timeout: 15_000 });
reviewLink = link;
break;
} catch {
await page.reload({ waitUntil: 'domcontentloaded' });
}
}
expect(reviewLink, 'Review Lyrics link appeared before transcription timeout').not.toBeNull();
console.log(`[${TENANT_ID}] Job ready for review`);
const reviewHref = await reviewLink!.getAttribute('href');
const reviewUrl = reviewHref!.startsWith('http') ? reviewHref! : `${PORTAL_URL}${reviewHref}`;
// The review page must fire the encoding-worker warmup on load — this is
// what keeps the encoder alive for the render (and what the old API-driven
// test skipped, causing stuck-render orphans).
const warmupReq = page.waitForRequest(
(r) => r.url().includes('/api/internal/encoding-worker/warmup/'),
{ timeout: 60_000 },
);
await page.goto(reviewUrl, { waitUntil: 'domcontentloaded' });
await warmupReq;
console.log(`[${TENANT_ID}] Review page fired encoding-worker warmup`);
// =====================================================================
// Approve the review through the UI (Preview -> Instrumental -> Confirm)
// =====================================================================
// Preview Video (bottom of the review page) — generates a preview using the
// now-warm encoder, then opens a modal with a "Proceed to Instrumental" CTA.
await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
const previewBtn = page.getByRole('button', { name: /preview video/i });
await expect(previewBtn).toBeVisible({ timeout: T.action });
await previewBtn.click();
const modal = page.getByRole('dialog');
await expect(modal).toBeVisible({ timeout: T.action });
// Preview generation can take a bit; don't fail the journey if it's slow.
await page.getByText(/generating preview video/i)
.waitFor({ state: 'hidden', timeout: 180_000 })
.catch(() => {});
const proceedBtn = page.getByRole('button', { name: /proceed to instrumental/i });
await expect(proceedBtn).toBeVisible({ timeout: T.action });
await proceedBtn.click();
const sessionToken = await page.evaluate(() => localStorage.getItem('karaoke_access_token'));
const getJob = async () => {
const r = await fetch(`${API_URL}/api/jobs/${createdJobId}`, {
headers: { Authorization: `Bearer ${sessionToken}` },
});
if (!r.ok) throw new Error(`GET job ${createdJobId}: ${r.status}`);
return r.json();
};
// For a pre-supplied (tenant) instrumental there is nothing to pick, so
// "Proceed to Instrumental Review" completes the review directly and the
// instrumental route redirects to /app. For a selectable instrumental an
// InstrumentalSelector (#submit-btn) renders instead. Handle both.
const submitBtn = page.locator('#submit-btn');
let hasInstrumentalStep = false;
try {
// waitFor actually blocks up to the timeout (isVisible would not); if the
// selector never appears the review already completed on "Proceed".
await submitBtn.waitFor({ state: 'visible', timeout: 15_000 });
hasInstrumentalStep = true;
} catch { /* pre-supplied tenant instrumental: review completed directly */ }
if (hasInstrumentalStep) {
const opt = page.locator('.selection-option').first();
if (await opt.isVisible().catch(() => false)) await opt.click();
await submitBtn.click();
console.log(`[${TENANT_ID}] Instrumental confirmed`);
}
// Confirm the review actually advanced (left awaiting_review) before waiting
// on the render — otherwise a silent no-op would masquerade as a render hang.
let left = false;
for (let i = 0; i < 8; i++) {
const s = (await getJob()).status;
if (s !== 'awaiting_review' && s !== 'in_review' && s !== 'reviewing') { left = true; break; }
await new Promise((res) => setTimeout(res, 5_000));
}
expect(left, 'review completed (job left awaiting_review)').toBeTruthy();
console.log(`[${TENANT_ID}] Review approved -> render started`);
// =====================================================================
// Wait for the render to complete, then assert tenant distribution
// =====================================================================
let job: any = null;
const renderDeadline = Date.now() + T.render;
while (Date.now() < renderDeadline) {
job = await getJob();
if (job.status === 'complete') break;
if (job.status === 'failed' || job.status === 'error') {
throw new Error(`Render failed: status=${job.status} ${JSON.stringify(job.state_data?.error || '')}`);
}
await new Promise((res) => setTimeout(res, 15_000));
}
expect(job?.status, 'job reached complete before render timeout').toBe('complete');
console.log(`[${TENANT_ID}] Render complete`);
// Tenant distribution invariants (field paths per the proven tenant flow:
// dropbox_link + youtube_url live in state_data; downloads in file_urls).
const sd = job.state_data || {};
const fileUrls = job.file_urls || {};
const finals = Object.keys(fileUrls.finals || {});
const packages = Object.keys(fileUrls.packages || {});
expect(sd.dropbox_link || job.dropbox_link, 'Dropbox link present').toBeTruthy();
expect(sd.youtube_url || job.youtube_url || null, 'no YouTube upload for tenant').toBeFalsy();
for (const f of ['lossy_4k_mp4', 'lossy_720p_mp4', 'with_vocals_mp4']) expect(finals).toContain(f);
for (const p of ['cdg_zip', 'txt_zip']) expect(packages).toContain(p);
expect(job.is_private, 'tenant job is private').toBeTruthy();
console.log(`[${TENANT_ID}] PASSED — complete, Dropbox present, no YouTube, downloads available`);
});
});
@@ -0,0 +1,70 @@
/**
* @jest-environment jsdom
*/
import { isBenignError, reportClientError, __resetForTest } from '@/lib/crash-reporter'
describe('isBenignError', () => {
it('treats ResizeObserver loop notices as benign (both phrasings)', () => {
expect(
isBenignError(new Error('ResizeObserver loop completed with undelivered notifications.'))
).toBe(true)
expect(isBenignError(new Error('ResizeObserver loop limit exceeded'))).toBe(true)
// window.onerror sometimes hands us the bare string.
expect(isBenignError('ResizeObserver loop completed with undelivered notifications.')).toBe(
true
)
})
it('still treats media AbortError as benign', () => {
const abort = new Error('The play() request was interrupted')
abort.name = 'AbortError'
expect(isBenignError(abort)).toBe(true)
})
it('does not suppress real errors', () => {
expect(isBenignError(new Error('Cannot read properties of undefined'))).toBe(false)
expect(
isBenignError(new TypeError("Failed to set the 'currentTime' property"))
).toBe(false)
})
})
describe('reportClientError', () => {
// jsdom has no global fetch to spyOn, so assign directly — but save and
// restore the original so the mock never leaks into other suites.
let fetchSpy: jest.Mock
let originalFetch: typeof global.fetch
beforeEach(() => {
__resetForTest()
originalFetch = global.fetch
fetchSpy = jest.fn().mockResolvedValue({ ok: true } as Response)
global.fetch = fetchSpy as unknown as typeof fetch
})
afterEach(() => {
global.fetch = originalFetch
jest.restoreAllMocks()
})
const ctx = {
href: 'https://gen.nomadkaraoke.com/en/app/jobs/',
userAgent: 'test',
}
it('never POSTs a benign ResizeObserver error to the monitor', async () => {
await reportClientError({
error: new Error('ResizeObserver loop completed with undelivered notifications.'),
source: 'window.onerror',
context: ctx,
})
expect(fetchSpy).not.toHaveBeenCalled()
})
it('POSTs a genuine error', async () => {
await reportClientError({
error: new Error('boom'),
source: 'window.onerror',
context: ctx,
})
expect(fetchSpy).toHaveBeenCalledTimes(1)
})
})
+26 -4
View File
@@ -145,6 +145,7 @@ export interface Job {
brand_prefix?: string;
// Customer order fields
customer_email?: string;
made_for_you?: boolean;
// Request tracking metadata
request_metadata?: Record<string, any>;
}
@@ -1542,6 +1543,19 @@ export const api = {
/**
* Verify a magic link token and get a session
*/
/**
* Read-only status check for a magic link — does NOT consume the token.
* Used by the verify page on load to show the correct UI upfront (the
* "Complete Sign-In" gate for a valid link, or an already-used/expired
* message for a dead one) without making the user click only to then fail.
*/
async getMagicLinkStatus(token: string): Promise<{ status: 'valid' | 'used' | 'expired' | 'invalid' }> {
const response = await fetch(`${API_BASE_URL}/api/users/auth/link-status?token=${encodeURIComponent(token)}`, {
method: 'GET',
})
return handleResponse(response)
},
async verifyMagicLink(token: string, referralCode?: string | null): Promise<VerifyMagicLinkResponse> {
const headers: HeadersInit = {};
if (referralCode) {
@@ -3507,10 +3521,16 @@ export const lyricsReviewApi = {
/**
* Signal the backend to start the encoding worker VM.
* Fire-and-forget — doesn't wait for the VM to boot.
*
* Scoped to the job being reviewed: the endpoint authorizes via the same
* review access as the rest of the lyrics-review page (require_review_auth),
* so getAuthHeaders() supplies the reviewer's token. Passing an admin-only
* token was the previous behaviour and 403'd for every non-admin customer.
*/
export async function warmupEncodingWorker(): Promise<void> {
export async function warmupEncodingWorker(jobId: string): Promise<void> {
if (!jobId) return
try {
await fetch(`${API_BASE_URL}/api/internal/encoding-worker/warmup`, {
await fetch(`${API_BASE_URL}/api/internal/encoding-worker/warmup/${encodeURIComponent(jobId)}`, {
method: 'POST',
headers: getAuthHeaders(),
})
@@ -3521,10 +3541,12 @@ export async function warmupEncodingWorker(): Promise<void> {
/**
* Send heartbeat to keep encoding worker alive during active session.
* Scoped to the job being reviewed (see warmupEncodingWorker).
*/
export async function heartbeatEncodingWorker(): Promise<void> {
export async function heartbeatEncodingWorker(jobId: string): Promise<void> {
if (!jobId) return
try {
await fetch(`${API_BASE_URL}/api/internal/encoding-worker/heartbeat`, {
await fetch(`${API_BASE_URL}/api/internal/encoding-worker/heartbeat/${encodeURIComponent(jobId)}`, {
method: 'POST',
headers: getAuthHeaders(),
})
+19 -7
View File
@@ -92,17 +92,29 @@ function signatureFor(message: string, stack: string | null, source: string): st
/**
* Benign errors that are routinely produced by the browser during normal use
* and carry no diagnostic value. The most common is a rejected
* `HTMLMediaElement.play()` promise (DOMException "AbortError") that fires when
* playback is interrupted by a pause / src change / unmount — e.g. clicking play
* on the lyrics-review audio while it is still loading. These must never reach
* the error monitor.
* and carry no diagnostic value. These must never reach the error monitor:
*
* - A rejected `HTMLMediaElement.play()` promise (DOMException "AbortError")
* that fires when playback is interrupted by a pause / src change / unmount —
* e.g. clicking play on the lyrics-review audio while it is still loading.
* - The "ResizeObserver loop …" notice: a spec-defined signal that an observer
* callback nudged layout and the browser deferred the next batch a frame. It
* is not a crash — Chrome hides it from its own console — and every page using
* ResizeObserver (TimelineCanvas, FlyerPreview, the VNC toolbar, …) emits it.
*/
function isBenignError(e: unknown): boolean {
const BENIGN_MESSAGE_PATTERNS = [
// Both the current ("completed with undelivered notifications") and legacy
// ("loop limit exceeded") Chromium phrasings.
/resizeobserver loop/i,
]
export function isBenignError(e: unknown): boolean {
if (e instanceof DOMException && e.name === 'AbortError') return true
// Some browsers surface the same media abort as a plain Error.
if (e instanceof Error && e.name === 'AbortError') return true
return false
const message =
e instanceof Error ? e.message : typeof e === 'string' ? e : ''
return BENIGN_MESSAGE_PATTERNS.some((re) => re.test(message))
}
/**
+20
View File
@@ -62,6 +62,9 @@ export const STATUS_CONFIG: Record<
// Step 3: Download
downloading_audio: { step: 3, label: "downloadingAudio", isBlocking: false, color: "text-blue-400" },
// Transient torrent-download issue (rare track / few seeders / tracker blip);
// auto-retried for up to 24h by the recover-stuck cron. Not blocking — no user action.
download_pending_retry: { step: 3, label: "findingAudioSources", isBlocking: false, color: "text-amber-400" },
downloading: { step: 3, label: "downloading", isBlocking: false, color: "text-blue-400" },
// Step 3.5: Audio Editing (optional, BLOCKING)
@@ -91,6 +94,9 @@ export const STATUS_CONFIG: Record<
// Step 7: Video Rendering
review_complete: { step: 7, label: "startingRender", isBlocking: false, color: "text-teal-400" },
rendering_video: { step: 7, label: "renderingVideo", isBlocking: false, color: "text-indigo-400" },
// Parked waiting for GCE encoding capacity (or re-parked after a mid-render
// stall); auto-retried by the scheduler. Not blocking — no user action.
render_pending_capacity: { step: 7, label: "waitingForCapacity", isBlocking: false, color: "text-amber-400" },
// Step 8: Instrumental Selection (BLOCKING - requires user action)
awaiting_instrumental_selection: { step: 8, label: "selectInstrumental", isBlocking: true, color: "text-amber-400" },
@@ -316,3 +322,17 @@ export function sortJobsByDate(jobs: Job[]): Job[] {
});
}
/**
* Whether a job should render as a standalone card on the main dashboard.
*
* Self-service jobs at `awaiting_audio_selection` are driven by the guided-flow
* wizard in the same browser session and must NOT appear as standalone cards
* (the wizard owns them). Made-for-you orders also sit at that status, but they
* are created server-side by the Stripe webhook with no active guided-flow
* session — so they'd otherwise be invisible to an admin. Keep those visible so
* their built-in "Open Audio Selection" action is reachable from the dashboard.
*/
export function shouldShowJobOnDashboard(job: Pick<Job, 'status' | 'made_for_you'>): boolean {
return job.status !== 'awaiting_audio_selection' || Boolean(job.made_for_you);
}
@@ -3,6 +3,7 @@ import {
mergeSegment,
addSegmentBefore,
deleteSegment,
deleteWord,
} from '../utils/segmentOperations'
import type { CorrectionData } from '../types'
@@ -98,3 +99,64 @@ describe('segmentOperations — singer inheritance', () => {
expect(result.corrected_segments[0].singer).toBe(2)
})
})
describe('deleteWord — segment timing recompute', () => {
const threeWordSegment = () => baseData([{
id: 's1', text: 'hello world foo', start_time: 0, end_time: 3,
words: [
{ id: 'w1', text: 'hello', start_time: 0, end_time: 1 },
{ id: 'w2', text: 'world', start_time: 1, end_time: 2 },
{ id: 'w3', text: 'foo', start_time: 2, end_time: 3 },
],
}])
it('deleting the first word tightens segment start_time to the next word', () => {
const result = deleteWord(threeWordSegment(), 'w1')
const seg = result.corrected_segments[0]
expect(seg.words.map((w: any) => w.id)).toEqual(['w2', 'w3'])
expect(seg.start_time).toBe(1) // was 0 (w1's start); now w2's start
expect(seg.end_time).toBe(3)
expect(seg.text).toBe('world foo')
})
it('deleting the last word tightens segment end_time to the previous word', () => {
const result = deleteWord(threeWordSegment(), 'w3')
const seg = result.corrected_segments[0]
expect(seg.words.map((w: any) => w.id)).toEqual(['w1', 'w2'])
expect(seg.start_time).toBe(0)
expect(seg.end_time).toBe(2) // was 3 (w3's end); now w2's end
expect(seg.text).toBe('hello world')
})
it('deleting a middle word leaves segment bounds unchanged', () => {
const result = deleteWord(threeWordSegment(), 'w2')
const seg = result.corrected_segments[0]
expect(seg.start_time).toBe(0)
expect(seg.end_time).toBe(3)
})
it('deleting a word when all remaining words are untimed nulls the segment bounds', () => {
const data = baseData([{
id: 's1', text: 'hello world', start_time: 0, end_time: 1,
words: [
{ id: 'w1', text: 'hello', start_time: 0, end_time: 1 },
{ id: 'w2', text: 'world', start_time: null, end_time: null },
],
}])
const result = deleteWord(data, 'w1')
const seg = result.corrected_segments[0]
expect(seg.start_time).toBeNull()
expect(seg.end_time).toBeNull()
})
it('deleting the only word removes the whole segment', () => {
const data = baseData([
{ id: 's1', text: 'hello', start_time: 0, end_time: 1,
words: [{ id: 'w1', text: 'hello', start_time: 0, end_time: 1 }] },
{ id: 's2', text: 'world', start_time: 1, end_time: 2,
words: [{ id: 'w2', text: 'world', start_time: 1, end_time: 2 }] },
])
const result = deleteWord(data, 'w1')
expect(result.corrected_segments.map((s: any) => s.id)).toEqual(['s2'])
})
})
@@ -0,0 +1,62 @@
import { countUntimedWords, hasUntimedLyrics } from '../timingCompleteness'
import type { LyricsSegment } from '@/lib/lyrics-review/types'
function timedSegment(id = 's'): LyricsSegment {
return {
id,
text: 'Hello world',
start_time: 0,
end_time: 1,
words: [
{ id: `${id}-w0`, text: 'Hello', start_time: 0, end_time: 0.5 },
{ id: `${id}-w1`, text: 'world', start_time: 0.5, end_time: 1 },
],
}
}
function untimedSegment(id = 'segment-0-1782928225732'): LyricsSegment {
return {
id,
text: "Vor's veninde er blevet gift",
start_time: null,
end_time: null,
words: [
{ id: `${id}-w0`, text: "Vor's", start_time: null, end_time: null },
{ id: `${id}-w1`, text: 'veninde', start_time: null, end_time: null },
],
}
}
describe('countUntimedWords', () => {
it('returns 0 for fully-timed lyrics', () => {
expect(countUntimedWords([timedSegment('a'), timedSegment('b')])).toBe(0)
expect(hasUntimedLyrics([timedSegment('a')])).toBe(false)
})
it('counts every untimed word (regression: job 231806a4 all-null)', () => {
const segs = [untimedSegment('0'), untimedSegment('1')]
expect(countUntimedWords(segs)).toBe(4)
expect(hasUntimedLyrics(segs)).toBe(true)
})
it('counts a single untimed word among timed ones', () => {
const seg = timedSegment('a')
seg.words[1].start_time = null
expect(countUntimedWords([seg])).toBe(1)
})
it('flags timed words whose segment bounds are null', () => {
const seg = timedSegment('a')
seg.start_time = null
expect(countUntimedWords([seg])).toBe(2)
})
it('skips word-less segments', () => {
const seg: LyricsSegment = { id: 's', text: '', start_time: null, end_time: null, words: [] }
expect(countUntimedWords([seg])).toBe(0)
})
it('handles empty input', () => {
expect(countUntimedWords([])).toBe(0)
})
})
@@ -363,11 +363,23 @@ export function deleteWord(data: CorrectionData, wordId: string): CorrectionData
const updatedWords = segment.words.filter((_, index) => index !== wordIndex)
if (updatedWords.length > 0) {
// Update the segment with the word removed
// Recompute the segment's boundary times from the remaining words so the
// segment no longer spans a deleted first/last word. This mirrors the
// Edit-segment modal's updateSegment behaviour (EditModal.tsx), keeping the
// Ctrl+click "delete word" path consistent with it.
const validStartTimes = updatedWords
.map((w) => w.start_time)
.filter((t): t is number => t !== null)
const validEndTimes = updatedWords
.map((w) => w.end_time)
.filter((t): t is number => t !== null)
const updatedSegment = {
...segment,
words: updatedWords,
text: updatedWords.map((w) => w.text).join(' '),
start_time: validStartTimes.length > 0 ? Math.min(...validStartTimes) : null,
end_time: validEndTimes.length > 0 ? Math.max(...validEndTimes) : null,
}
// Update the data
@@ -0,0 +1,37 @@
import type { LyricsSegment } from '@/lib/lyrics-review/types'
/**
* Count words that lack timing (start_time or end_time == null) across all
* segments. Untimed lyrics are a legitimate *intermediate* state in the
* synchronizer (paste lyrics → tap-sync), but they must be resolved before the
* video is generated: the render pipeline (segment resizing, ASS generation, the
* GCE encoder) does arithmetic on timing values and crashes on null.
*
* Mirrors the backend gate `validate_segment_timing`
* (karaoke_gen/lyrics_transcriber/output/timing_validation.py) so the UI can
* warn the user *before* they submit rather than surfacing a server error.
*
* A segment with no words is skipped (nothing to time).
*/
export function countUntimedWords(segments: LyricsSegment[]): number {
let count = 0
for (const segment of segments) {
const words = segment.words ?? []
if (words.length === 0) continue
const segmentUntimed = segment.start_time === null || segment.end_time === null
for (const word of words) {
if (word.start_time === null || word.end_time === null) {
count += 1
} else if (segmentUntimed) {
// A timed word inside a segment with null bounds still can't render.
count += 1
}
}
}
return count
}
/** True if any segment/word lacks timing. */
export function hasUntimedLyrics(segments: LyricsSegment[]): boolean {
return countUntimedWords(segments) > 0
}
+10 -2
View File
@@ -112,8 +112,15 @@ export function hardReload(latestSha?: string): boolean {
/**
* Returns true if `err` looks like a chunk-load error from a post-deploy
* mismatch. Next.js surfaces these as `ChunkLoadError` or messages mentioning
* "Loading chunk" / "dynamically imported module".
* mismatch. Bundlers surface these differently:
*
* - webpack: `ChunkLoadError` / "Loading chunk <id> failed"
* - native ESM: "Failed to fetch dynamically imported module" /
* "Importing a module script failed"
* - Turbopack (Next.js 16 default): a plain `Error` whose message is
* "Failed to load chunk <path> from module <n>" (also "… as a runtime
* dependency of chunk <id>" / "… from an HMR update"). These carry NO
* `ChunkLoadError` name, so they must be matched by message.
*/
export function isChunkLoadError(err: unknown): boolean {
if (!err) return false
@@ -123,6 +130,7 @@ export function isChunkLoadError(err: unknown): boolean {
return (
/ChunkLoadError/i.test(msg) ||
/Loading chunk [\w-]+ failed/i.test(msg) ||
/Failed to load chunk/i.test(msg) ||
/Failed to fetch dynamically imported module/i.test(msg) ||
/Importing a module script failed/i.test(msg)
)
Loaded 100 of 170 files, more files were not shown because too many files have changed in this diff. Show more