Compare commits

...
154 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 4.8 df93eb9f82 feat(status): opaque System Status modal + live encoding-worker instance type (#920)
## Summary

Two fixes to the **System Status** modal (opened from the version
footer):

### 1. Modal was transparent
The modal set `backgroundColor: var(--card-bg)` — but `--card-bg` is
**defined nowhere** in the codebase (the real vars are `--card` /
`--card-border`). An undefined CSS variable makes the property invalid,
so the modal fell back to `transparent` and the job list showed through
it (see the reported screenshot).

Fixed by using defined opaque surfaces:
- Dialog shell → `var(--bg)` (`#0f0f0f` dark / `#f8fafc` light)
- Service cards → `var(--card)` (`#1a1a1a` dark / `#ffffff` light)

This was the only usage of the phantom `var(--card-bg)` anywhere in the
frontend.

### 2. Show the currently-live encoding worker
Given the recent c4d stockout / multi-instance-family fallback work,
admins couldn't see **which** worker was actually serving or its
instance type. The live worker is the `active_override` VM when a
capacity fallback has routed off the primary, else the c4d blue-green
primary.

- **Backend** (`/health/system-status`): the admin-only encoder
`admin_details` now carries `active_vm`, `active_zone`,
`active_machine_type`, and `on_fallback`. The instance type is derived
via the existing `infer_machine_type` helper (primary →
`c4d-highcpu-32`; fallbacks decoded from the VM-name family token, e.g.
`…-fallback-n2c` → `n2-highcpu-32`).
- **Frontend**: a new `LiveWorkerSection` on the Encoder card shows the
instance type prominently, the serving `VM · zone`, and an amber
**"Fallback"** badge + notice when running off the primary due to a
stockout. The existing Blue-Green expander is unchanged.

## Changes
- `backend/api/routes/health.py` — compute live-worker fields (admin
only)
- `frontend/components/system-status-modal.tsx` — opaque vars +
`LiveWorkerSection`
- `frontend/lib/api.ts` — `ServiceStatus.admin_details` new fields
- `frontend/messages/*` — 3 new `status` keys translated to all 32
locales

## Testing
- `make test` — full suite green (backend 1741+3878+103, frontend 1115
tests / 86 suites)
- Added a capacity-fallback path test to
`test_system_status_endpoint.py`
- Added `frontend/__tests__/system-status-modal.test.tsx` (primary,
fallback badge/notice, non-admin omission)
- CodeRabbit reviewed locally; addressed 3 minor translation-grammar
findings (ja/sk/ro)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-20 22:47:16 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 3e666c28bb fix(e2e,submit): tolerate Stripe layout A/B + retry tenant upload-complete (#919)
## Problem

Two independent daily-E2E failures fired alerts:

- **E2E Daily #138/#139 (Credit Purchase)** — timed out 30s at
`stripe-checkout.ts` waiting for a top-frame `Pay` button.
- **Tenant E2E #80 (`vocalstar`; `singa` passed)** — timed out 120s
waiting for "Track Submitted".

## Root causes (both investigated to ground truth)

**1. Stripe Checkout layout flipped again (test-only).**
Stripe has now oscillated its hosted Checkout layout **three times**,
strongly implying A/B testing / staged rollout:
- Apr (#715): multi-method accordion of **radios**, card fields in
iframes, Pay in top frame
- Aug 17 (#916): **single-method**, direct textbox inputs, no chooser
- Now: multi-method **Payment Element** where the chooser is **buttons**
and the whole element — chooser, card fields **and the Pay button** — is
inside a **nested iframe**

`page.getByRole(...)` only searches the top frame, so the Pay button
(now nested) was invisible → 30s timeout. The real checkout rendered
correctly throughout (right product, referral 70% off, $3.00 total).

**2. Tenant submit: network blip on the final completion call (real,
transient).**
For `vocalstar` the submit **created the job + deducted a credit**, both
files reached GCS (verified in the bucket), but the final
`completeJobUpload()` `fetch` failed at the network layer — it never
reached the server (zero backend logs) — and threw a non-`ApiError`,
surfacing the generic "Something went wrong" while stranding the
paid-for job at "Setting up". `singa` passed the identical flow seconds
earlier.

## Changes (v0.196.2)

- **`frontend/e2e/helpers/stripe-checkout.ts`** — rewritten to be
**layout-agnostic**: searches **every frame** (top + nested iframes) for
the Pay button, the Card chooser (radio **or** button), card fields
(direct **or** iframe), ZIP and save-info toggle. Prominent doc-comment
cataloguing the three observed variants with a "do not narrow to one
layout" warning.
- **`frontend/lib/api.ts`** — `completeJobUpload` now retries
**network-level** failures (3 attempts, backoff). HTTP errors are never
retried (deterministic). Self-heals the exact failure observed.
- **`frontend/components/job/TenantJobFlow.tsx`** — logs the real error;
shows a network-specific message (`submitNetworkError`, translated to
all 33 locales).
- Tests: 3 new `completeJobUpload` retry tests; tenant error-mapping
tests updated. All pass; tsc/eslint clean on changed files.

## Verification

- Dispatched `e2e-daily.yml` on this branch (test code from branch,
driving **production**):
- **Stage 1: Credit Purchase — ✅ success** (real ~$3 charge through the
new nested-iframe Stripe layout — directly exercises the helper fix)
  - Stage 2: Happy Path — validating (orthogonal to these changes)
- Run:
https://github.com/nomadkaraoke/karaoke-gen/actions/runs/32394417473
- Local CodeRabbit review completed; one legit finding fixed (Hebrew
register), one false positive skipped (`ApiError` is exported at
`api.ts:3982`; the new `toBeInstanceOf(ApiError)` test passes).

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-20 13:18:04 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 03464145b5 fix(monitoring): replace flaky instance-count-absence alert with /api/health uptime check (#918)
## Summary
- The **"Karaoke Backend - Service Unavailable"** alert fired a false
page at 2026-08-19 03:15 UTC. Root cause: it alerted on *absence* of the
`run.googleapis.com/container/instance_count` metric, which is a sampled
series that legitimately blinks out for a `min-instances=1`, low-traffic
service. Logs confirmed the same instance was serving the scheduled
recover-stuck-jobs / retry-render crons with HTTP 200 the whole time —
zero errors, no instance replacement.
- Replaces the metric-absence condition with a real **Cloud Monitoring
uptime check** against `https://api.nomadkaraoke.com/api/health`
(through the Cloudflare edge, the same path real users take; body must
contain `"healthy"`).
- Pages only when the check **fails from more than one checker
location**, so a single flaky checker can't page us but a genuine
hard-down fires in ~1–2 min.

## Changes
- `infrastructure/modules/monitoring.py`:
- New `UptimeCheckConfig` `backend-health-uptime-check` (HTTPS GET
`/api/health`, 60s period, content matcher `"healthy"`).
- `service-unavailable-alert` condition changed from
`condition_absent(instance_count)` → `condition_threshold` on
`monitoring.googleapis.com/uptime_check/check_passed`
(`REDUCE_COUNT_FALSE` grouped by host, fire when `>1` failing checker
location).
  - Updated the alert documentation accordingly.

## Deployment status
- **Already applied to the `prod` stack** via targeted `pulumi up` (`+1
created` uptime check, `~1 updated` policy). Verified live: uptime check
passing 100% from all checker locations (`fraction_true=1.0`,
`COUNT_FALSE=0`) — confirms Cloudflare does not block Google's checkers.
This PR reconciles `main` with the deployed state; CI's pulumi apply is
a no-op.

## Testing
- [x] `pulumi preview` / `pulumi up` on prod stack (targeted; unrelated
runner-manager drift left untouched)
- [x] Uptime check verified passing from all checker locations
post-deploy
- [x] Alert policy condition + docs verified on the deployed policy
- N/A `make test` — infra-only Pulumi change, not covered by app test
suites

## Review
- [x] Local CodeRabbit review completed (1 major finding: "count checker
locations, not regions" — addressed by making the condition name + docs
accurately say "checker location")
- [x] Final CodeRabbit pass: no new findings

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-19 10:45:16 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 cd4c88ca3e fix(visibility): make public→private atomic; fix redistribute crash (NOMAD-1537 gap) (#917)
## Summary

Investigated a `⚠️ GDrive Validation: missing NOMAD-1537` alert. Root
cause was **not** a brand-code allocation race — it was a
**public→private visibility change** on job `25d076e5` (`Alma Nocturna –
Mejor Cállate`) that:

1. deleted the public YouTube/Dropbox/GDrive outputs and recycled
`NOMAD-1537`, **then**
2. crashed the private redistribution on an illegal `complete →
packaging` state transition (`redistribute_video` drove the normal
orchestrator progress path on an already-`complete` job).

So the flow was **delete-first with no rollback**: public files gone,
private archive never created. The gap self-closed when an unrelated
public job (`Luvcat – Spider`) reused the recycled number. The customer
track was fine (GCS-backed downloads intact + correctly private), but
every public→private conversion was silently failing its private-side
archive, and each leaked a `NOMADNP` code.

## Changes

- **A — fix the crash:** `OrchestratorConfig.redistribute_mode`;
`_update_progress` updates progress only and skips status transitions
when redistributing a `complete` job. `redistribute_video` sets it.
- **B — distribute-then-delete:** `change_to_private` captures the
public refs, redistributes to the private destination first, and only on
success deletes the public outputs + recycles the public number. On
redistribution failure it reverts to public — nothing deleted (YouTube
deletion is irreversible, so it must be last).
- **C — no leaked codes:** a redistribution that fails after allocating
a `NOMADNP` code recycles it.
- **Hardening (from local CodeRabbit review):** `redistribute_video`
verifies the archive actually materialized (brand code + Dropbox upload)
before reporting success — the orchestrator swallows those failures as
warnings; the public number is recycled only when every public deletion
succeeded; revert-to-public happens only pre-deletion.

**Validator intentionally unchanged.** Going-private is a rare,
legitimate cause of a transient gap that the next public track refills;
the owner wants to keep receiving that warning.

## Testing

- New/updated unit tests: distribute-then-delete ordering, real rollback
(no public deletion + revert on failure), `redistribute_mode` skips
status transition, public/private brand-code recycle, recycle-gating on
incomplete cleanup.
- Green: `test_change_visibility.py`,
`test_video_worker_orchestrator.py`, `test_brand_code_service.py`,
`test_private_tracks.py`, `test_cleanup_distribution.py`,
`test_admin_delete_outputs.py` (326 tests).

## Follow-up (post-merge, operational)

- Recover job `25d076e5`: re-run `redistribute_video('25d076e5')` (GCS
finals intact) to create its NonPublished archive + `NOMADNP` code.
- Recycle the leaked `NOMADNP-0214`.

Full analysis + plan:
`docs/archive/2026-08-18-visibility-change-recycle-dataloss-plan.md`.

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-18 12:15:01 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 e78ba02e62 fix(e2e): handle Stripe Checkout single-payment-method layout (#916)
## Problem

The daily E2E test (`e2e-daily.yml` → **Stage 1: Credit Purchase**)
started failing, firing the "🚨 Payment flow is broken" alert (run #135).
All 3 attempts timed out at the same line:

```
TimeoutError: locator.check: Timeout 10000ms exceeded.
> 67 |   await cardRadio.check({ force: true, timeout: 10_000 });
```

## Root cause — test-only, prod is healthy

Stripe changed its **hosted Checkout** layout. It now serves a
**single-payment-method (Card-only)** page where the card fields render
directly — there is **no `radio` named "Card"** to select. The helper
unconditionally waited on that radio, which no longer exists, so it hung
for 10s × 3.

The failure snapshot shows the real customer checkout rendering
**correctly**: right product ("1 Karaoke Credit"), referral discount
applied ("Referral 70% off"), correct total ($3.00), and working card
inputs. The alert message is the workflow's generic worst-case text, not
an observed payment break. **No product/app code changed or needed to
change** — this is purely test-automation drift.

(On the hosted `checkout.stripe.com` page the card inputs are
same-origin **direct textboxes**, not cross-origin iframes.)

## Fix

`frontend/e2e/helpers/stripe-checkout.ts` — make
`completeStripeCheckout` resilient to **both** layouts:

- Only click the "Card" radio when one is actually present.
- If card fields are already visible (single-method layout), skip radio
selection entirely.
- Fill fields via direct locators (stable-field-name / id / placeholder
/ accessible name), keeping the existing iframe fallback for the legacy
accordion layout.
- Broaden cardholder-name and ZIP locators to match the new accessible
names.

## Verification

Dispatched `e2e-daily.yml` on this branch (test code from branch,
driving **production**). The changed helper is exercised on the real
Stripe page:

- **Stage 1: Credit Purchase — ✅ success** (real ~$3 charge; full flow:
checkout → submit → success page → credits allocated)
- **Stage 2: Happy Path — ✅ success**
- Run:
https://github.com/nomadkaraoke/karaoke-gen/actions/runs/32037148447

Test-helper-only change; no shipped code affected, so no
`pyproject.toml` version bump.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-17 12:23:22 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 c9c019aaf7 perf(encoding): faster, smaller, portable "With Vocals" mp4 (yuv420p + veryfast + AAC) (#915)
## Summary
- The **"(With Vocals).mp4"** sing-along deliverable was the *single
longest finalization stage* (~59s on a 32-vCPU worker).
`convert_mov_to_mp4` encoded it accidentally-badly: no `-pix_fmt`
(inherited the renderer's `High 4:4:4`/`yuv444p` — the only 4:4:4 file
in the set, poorly supported by browsers/TVs/phones), default `medium`
preset (slow), and `-c:a copy` → **FLAC-in-mp4** (non-standard) despite
the documented spec ("4k H264/**AAC**").
- Verified the file is a **pure leaf** — nothing downstream reads its
video or audio. Every later output (Karaoke.mp4, Lossless/Lossy/720p,
MKV) derives from the *source* `with_vocals` file + the *instrumental*
audio; YouTube uploads the lossless MKV. So the encode is chosen purely
for the deliverable.

## Change
`convert_mov_to_mp4` (software/CPU path — what runs on prod workers):
```
-c:v libx264 -pix_fmt yuv420p -preset veryfast -c:a aac -ar 48000 -b:a 320k -movflags +faststart
```
Applied to both implementations, kept in sync:
- `LocalEncodingService.convert_mov_to_mp4` (cloud worker — prod). Its
`MP4_FLAGS` has no pix_fmt, so `-pix_fmt yuv420p` is explicit on both
GPU and CPU commands.
- `KaraokeFinalise.convert_mov_to_mp4` (local CLI). Already emitted AAC
and already forces yuv420p via its `mp4_flags`; adds the `-preset
veryfast` speed win + `-b:a 320k`.

## Measured result (real 138s 4K source: Arctic Monkeys – Riot Van)
| Metric | Before (prod) | After |
|---|---|---|
| Encode time | 56 s | **29 s** (~2×) |
| File size | 22 MB | **14 MB** (~36% smaller) |
| Video | h264 High 4:4:4 / yuv444p | **h264 High / yuv420p** |
| Audio | FLAC-in-mp4 (~639 kbps) | **AAC-LC 48 kHz / 320 kbps** |

This is the longest finalization stage, so ~halving it cuts **~20-25%
off total finalization wall-time**. The file also gets **smaller** (AAC
320k ≪ FLAC ~639k, 4:2:0 < 4:4:4) — no size/CPU tradeoff; every axis
improves, plus universal playback + spec alignment. Verified end-to-end
by running the exact shipped command on the source and re-probing the
output.

## Testing
- [x] `backend/tests/test_local_encoding_service.py` +
`tests/unit/test_karaoke_finalise/test_ffmpeg_commands.py` updated to
assert the new flags (pix_fmt/preset/AAC/320k + regression guard: no
`-c:a copy`)
- [x] 236 passed / 8 skipped across encoding + karaoke_finalise suites
- [x] End-to-end: exact command on real source → 29s, 14MB, yuv420p, AAC
320k

## Review
- [x] Local CodeRabbit review completed (2 cycles); findings addressed
(forced yuv420p on NVENC path; removed duplicate pix_fmt on CLI path).
Pre-existing skipped-NVENC-test fixture gap noted, out of scope.

## Non-goals
User-uploaded (finalise-only) non-H.264 videos still re-encode correctly
(codec-agnostic). Whether a "reference" file needs to be 4K at all is a
separate product decision.

@coderabbitai ignore

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

---------

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

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

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

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

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

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

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

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

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-16 15:14:04 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 a1a92d197c docs: reflect multi-instance-type encode pool + finalization-CPU handoff (#913)
## Summary
Brings all **live** repo docs in line with the v0.195.0 encode-worker
mechanism (shipped in #911/#912) and adds a handoff for the next
investigation. Docs-only, no version bump.

## What changed
- **ARCHITECTURE.md** — rewrote the "Encoding Worker" section: c4d
blue-green primary pair **+ ranked 6-family fallback pool**
(c4d/c4/n4d/c2d/n2d/n2, 10 VMs), the shared
`encoding_worker_preference.ordered_candidates` driving **both** runtime
and deploy selection, fastest-first + 15-min `capacity_state` cooldown,
`is_primary` override routing, and the self-sufficient CPU-torch
dep-baked image. Updated the topology diagram + intro.
- **TROUBLESHOOTING.md** — capacity runbook now lists all 6 families / 8
fallbacks + cooldown; the capacity-probe loop covers the 4 new VMs;
deploy green-selection points at the ranked pool; the "No module named"
section notes the dep-bake largely eliminated it (plus the
create-time-stockout caveat).
- **DEVELOPMENT.md** + **CLAUDE.md** — fixed "two VMs" framing;
CLAUDE.md ssh example uses a real VM name (there is no VM literally
named `encoding-worker`).
- **GCP-COST-OPTIMIZATION.md** — corrected the stale "c4d running 24/7,
~\$700/mo" current-state (now an on-demand pool with idle-shutdown — the
listed opportunities are largely shipped).
- **LESSONS-LEARNED.md** — marked the Aug-2026 2-family diversification
lesson as **superseded** by the v0.195.0 pool (history preserved,
redirects to current).
- **NEW**
`docs/archive/2026-08-16-finalization-cpu-efficiency-handoff.md` —
grounded handoff to investigate whether prod finalization is
CPU-underutilized (`ffmpeg_threads:8` on 32-vCPU workers), with repro
steps, constraints (heavy-lane serialization / RAM), and the benchmark
baselines.

Left untouched: `docs/archive/**` and `docs/superpowers/**` (historical
snapshots), and dated changelog entries in `docs/README.md`.

## Testing
Docs-only — verified internal anchor link (DEVELOPMENT → ARCHITECTURE
section) resolves. No code/tests affected.

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

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

* **Documentation**
* Updated architecture and development guidance for blue-green encoding
workers, fallback capacity, active VM selection, and on-demand startup.
* Refined troubleshooting instructions for capacity-aware deployment, VM
promotion, health checks, restarts, and dependency recovery.
* Updated cost-optimization guidance to document auto-shutdown,
scale-to-zero behavior, and on-demand capacity.
* Marked instance-type diversification as shipped and documented rollout
outcomes.
* Added a handoff for investigating CPU utilization during video
finalization.
  * Clarified outdated guidance in the lessons learned documentation.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-16 14:14:46 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 824e4f9e6b fix(packer): verify baked deps via canary imports (unbreak encoding-worker image build) (#912)
## Summary
The v0.195.0 dep-bake (#911) broke the **Build Encoding Worker Image**
workflow: the build-time verify step imported
`backend.services.gce_encoding.main`, which constructs GCP clients at
import and needs `GOOGLE_CLOUD_PROJECT` + auth that only exist at
runtime. Packer failed with *"Project was not passed and could not be
determined from the environment"* — even though the full dep tree (torch
2.13.0+cpu, tenacity, langchain, …) installed cleanly.

No prod impact: the failed build left the `encoding-worker` image family
unchanged, so VMs kept using the prior image + the runtime
`ensure_latest_wheel` backstop.

## Fix
Verify the dependency **tree** via heavy transitive library imports
(`tenacity` + the langchain chain +
`transformers`/`librosa`/`onnxruntime`) — the exact modules whose
absence broke fresh fallback VMs — instead of the app module. Proves
install completeness without app-level GCP-init fragility. Keeps the
CPU-only torch assertion (`torch.version.cuda is None`).

## Testing
- [x] `bash -n provision.sh`
- [x] Confirmed all canary libs present in the failed build's install
log
- [ ] Re-run of Build Encoding Worker Image (auto-triggers on merge)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-15 21:20:40 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 c7959ea2d5 feat(encoding): mature multi-instance-type pool with availability-aware selection (#911)
## Summary
- Replaces "c4d primary + single n2 fallback family" with a **ranked
pool of 6 x86_64 / 32-vCPU / ≥32 GB highcpu types** across 4 silicon
lineages (c4d, c4, n4d, c2d, n2d, n2), selected **fastest-first** but
**availability-aware** — a type that stocks out is demoted for a 15-min
cooldown then re-probed. c4d stays the top pick whenever it can start; a
render no longer stalls even if 2+ types are fully stocked out in
us-central1.
- One **pure preference module**
(`encoding_worker_preference.ordered_candidates`) is now the single
source of truth for candidate ranking, driving **both** runtime
selection and deploy green selection so they can't drift.
- Keeps the per-VM start/stop model (MIG deferred with documented
triggers; no reservation). Full plan + rollout in
`docs/archive/2026-08-15-encoding-instance-type-diversity-plan.md`.

## Changes
- **New** `backend/services/encoding_worker_preference.py` — speed-rank
+ Firestore `capacity_state` cooldown; stdlib-only so `deploy_promote`
imports it (with a shadow-proof by-path fallback).
- **Runtime** (`encoding_service`, `encoding_worker_manager`): builder
ranks primary + fallbacks; manager records/clears per-(type,zone)
stockout; override routing now keys off an explicit `is_primary` flag
instead of list position.
- **Deploy** (`deploy_promote`, `ci.yml`): green selection uses the
shared ranker + threads `capacity_state`.
- **IaC** (`config.py`, tests): `FALLBACKS` broadened to 6 types
(additive-only) with family-correct disk types (Titanium c4/c4d/n4/n4d =
hyperdisk-balanced; c2d/n2/n2d = pd-balanced); secret schema gains
optional `machine_type`.
- **Packer** (`provision.sh`, `startup.sh`): bake full dep tree with
**CPU-only torch** so fresh type VMs boot self-sufficient; build-time
import verify.
- **New** `benchmark_types.py` to measure per-type encode wall-time and
refine the seeded `SPEED_RANK`.

## Testing
- [x] Full backend unit suite: **3871 passed, 36 skipped** (emulator
tests need external services)
- [x] New/updated tests: preference module (16), capacity_state +
`is_primary` manager tests, builder-ordering + non-list-JSON service
tests, deploy ranking tests, infra disk-capability + pool-breadth
invariants
- [ ] Operator rollout (needs write creds): `pulumi up` (verify +8
create, 0 replace) → rebuild image (dep-bake) → grow fallback secret
with `machine_type` → run `benchmark_types.py`

## Review
- [x] Local CodeRabbit review completed (4 major findings fixed; cycle 2
clean)
- [x] Review feedback addressed

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-15 20:52:56 -04:00
Andrew Beveridge ☄️ 9a752ab3eb fix(deploy): capacity-aware encoding-worker deploy (reach serving fallback in c4d stockout) (#910)
## Problem

Follow-up to #908/#909. The CI encoding-worker deploy is a blue-green
over the **c4d primary/secondary** VMs. us-central1 is in a persistent
**c4d Spot stockout**, so both are down and all traffic runs on an n2
fallback recorded as `active_override_vm`. The deploy can't start the
c4d secondary → rolls back → **never refreshes the serving fallback**,
so worker-side `main.py` changes (the #908/#909 fixes) never reach prod
until a manual restart. Evidence: the config doc's `primary_version` was
stuck at `0.192.9`, and I had to hand-start the n2f fallback to get
0.194.0 live.

## Fix — validate on a fresh green, then promote it (zero-downtime,
stockout-proof)

Decision logic is a pure, unit-tested module
(`infrastructure/encoding-worker/deploy_promote.py`) since the branching
can't be exercised in CI:
- **`select_green_candidates`** — try the c4d `secondary` first, else a
fresh n2 fallback (n2 before c4d), **excluding the current override** so
it keeps serving while we validate a *different* fresh worker.
- **`promote_plan`** — for a c4d green, the classic primary/secondary
swap **and clear any stale override**; for a fallback green, set it as
`active_override`. Returns the exact Firestore update + which retired
VM(s) to drain/stop (**never the just-promoted green**).

Workflow (`.github/workflows/ci.yml`):
- "Select & start green target" (capacity-aware, `continue-on-error`,
emits `green_ok`), health + real-encode-test on the green IP, then
"Promote green to serving" (apply plan + drained stop of retired VMs,
non-RUNNING skipped, one shared 20-min drain budget).
- Rollback uses `always()` so `deploy_in_progress` is always cleared;
only stops a green we started fresh, and **recovers the serving
override** (starts it back up) if a last-resort in-place restart left it
down.

## Testing
- `backend/tests/test_deploy_promote.py` — 10 cases: candidate ordering
(secondary-first, n2-before-c4d, override excluded), both promote
branches, and never-drain-the-green guard.
- `actionlint` clean on the new steps; YAML validated.
- Two full local CodeRabbit cycles; all 7 findings addressed (self-drain
guard, stuck `deploy_in_progress`, None-IP guard, drain time-bound,
override recovery).

## Deploy note
This PR's own merge is the first live run of the new logic (deploy runs
on every push to main). Expected: it selects an n2 fallback as green
(c4d won't start), validates it, sets `active_override` to the fresh
one, and drains the old override. Will be watched closely.

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

* **New Features**
* Improved encoding-worker deployments with capacity-aware green worker
selection and fallback support.
* Added safer blue-green promotion, health validation, job draining, and
rollback handling.
* Prevented active jobs from being interrupted during worker
replacement.

* **Bug Fixes**
* Added recovery for capacity shortages, including validated in-place
restarts as a last resort.
* Automatically clears stale deployment overrides and deployment locks.

* **Documentation**
* Updated troubleshooting guidance for worker restarts and
capacity-related recovery.

* **Tests**
* Added coverage for worker selection, promotion, fallback handling, and
draining behavior.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

@coderabbitai ignore
2026-08-15 18:09:51 -04:00
Andrew Beveridge ☄️ 329a0944c8 fix(encoding): race-free ensure_latest_wheel + skip redundant installs (#909)
## Problem

Follow-up to #908. During the OOM-fix verification, a fresh n2 fallback
booted and three renders hit it at once; one (`374dec26`) failed with
`karaoke-gen wheel/dependencies not ready on this worker after retries;
job should be retried on a healthy worker`.

**Root cause:** `ensure_latest_wheel()` runs on the **light** executor
(>1 thread) at the start of every job — the heavy-lane serialization
(`ENCODING_HEAVY_CONCURRENCY=1`) does **not** cover it. So concurrent
jobs on a fresh boot raced on the shared `/tmp/karaoke_gen-<v>.whl` path
(`gsutil cp` clobbered mid-copy) and the venv (two `pip install`s at
once). It also re-downloaded + re-installed the wheel on **every** job
even when the installed version already matched.

## Fix (`backend/services/gce_encoding/main.py`)
- **Process-wide lock** (`threading.Lock`) around the whole
check/download/install/verify so only one caller does the work; the rest
wait.
- **"Already current" fast path:** compare the installed `karaoke-gen`
version to the latest GCS wheel; if they match (the common case —
`startup.sh` installs it at boot), skip download/install entirely. A
per-process verified-version cache makes repeat calls a no-op. Only the
*first* job after a new wheel actually installs.

Net effect: on a fresh boot, the first job installs (under the lock) and
the rest take the fast path — no clobbering, no redundant installs, no
spurious "wheel not ready" failures.

## Testing
- New tests: fast path (already-verified / installed-matches → zero
`cp`/`pip`), full install when the version differs, and **3 concurrent
callers install exactly once** (`cp==1`, `pip==1`).
- Existing wheel-verification tests get an autouse cache reset so the
new module global can't leak between tests.
- Encoding suite: 163 passed.
- Local CodeRabbit review completed; feedback addressed.

## Deploy note
Same as #908: the worker picks this up on a fresh boot / service restart
(it ships in the wheel). No infra changes.

@coderabbitai ignore
2026-08-15 16:42:24 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 51dbf1cbfd fix(encoding): serialize heavy encodes (OOM-proof) + auto-resubmit lost renders (#908)
## Problem

Three Arctic Monkeys renders (`a3f340a2`, `374dec26`, `590630c0`) failed
within ~2 min on 2026-08-15 with `lost contact with worker after 5
consecutive poll failures: Encoding job … not found`.

**Root cause (confirmed from live forensics):** Both 60 GB c4d primary
encoding workers were down (Spot stockout), so all render traffic
funneled onto the single 32 GB `n2-highcpu-32` fallback. The worker ran
`ThreadPoolExecutor(max_workers=4)`, so the batch put **3 concurrent 4K
ffmpeg encodes** (~30 GB) on it → **kernel OOM-killer fired** →
`encoding-worker` service restarted → in-memory `jobs` registry wiped →
every poll `404`'d → all three failed. ffmpeg already saturates all
cores for one job, so the parallelism bought **no throughput**, only
multiplied peak RAM.

## Fix

**Worker — serialize the heavy lane**
(`backend/services/gce_encoding/main.py`)
- Split the single pool into `heavy_executor`
(`max_workers=ENCODING_HEAVY_CONCURRENCY`, default **1**, clamped to
`[1,4]`) for renders/encodes and `light_executor` (previews + wheel
installs). One heavy ffmpeg at a time = OOM-proof on any machine type;
extras queue as `pending`.
- `/status` now exposes `queue_position` (+ `restart_failure_code`);
jobs tagged by `kind`.

**Client + workers — auto-resubmit a lost job**
- `wait_for_completion` raises the typed `EncodingJobLostError` on a
**404-after-the-job-was-seen** (a pinned poll can only 404 if the worker
lost it) or a terminal failure carrying `restart_failure_code`. 404 is
now a typed `EncodingJobNotFoundError` (no message parsing).
- Time spent `pending` counts against a generous `queue_timeout`, not
the per-run `timeout`.
- `run_with_lost_job_resubmit` resubmits a lost job as
`<id>_retry_<hex8>` (bounded, `ENCODING_RESUBMIT_MAX=2`), wired into
`render_video_worker`, `video_worker`, and `video_worker_orchestrator`
(incl. the stale-cache path). Idempotent by deterministic output paths
(overwrite, no dupes).
- `GCEEncodingBackend.encode` re-raises the lost error instead of
flattening it to `success=False`, so the resubmit actually fires.

## Testing
- New tests: worker lane serialization + `queue_position`;
concurrency-clamp matrix; client lost-job detection (404-after-seen,
restart code, pending-not-timeout); resubmit wrapper (fresh id, bounded,
non-retry of other errors); backend re-raise; preview queue-timeout cap.
- Full backend suite: **3766 passed, 139 skipped**.
- Local CodeRabbit review completed; feedback addressed (typed 404,
bounded env parsing, preview queue cap, idempotency doc).

## Deploy note
`main.py` ships in the wheel, but the running uvicorn process only picks
up worker-side changes on a **service restart** — the CI deploy /
blue-green swap handles this. Post-deploy verification: re-render the 3
failed jobs **concurrently** (the exact OOM trigger) and confirm no OOM
(`journalctl -k`), `NRestarts` doesn't increase, and all three complete.

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-15 15:26:25 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 3f4b7550ab feat(portrait): 9:16 karaoke video output (GCS + Dropbox) (#890)
## Summary

Adds a **portrait 1080×1920 karaoke video** as an additional output of
every finalised job — for phone viewing / social sharing — distributed
to **GCS + the Dropbox brand-code folder only** (never Google Drive or
YouTube). Default-on, gated by `PORTRAIT_RENDER_ENABLED`, and fully
**non-fatal**.

It is a genuine **re-render** at portrait resolution with re-wrapped
lyrics — *not* a transform of the finished landscape video. The design
experiments proved transforms are unusable: letterboxing leaves the
lyrics tiny (~32% of the frame); centre-cropping slices the start/end
off **every** line. See the comparison in
`docs/archive/2026-06-14-portrait-video-experiments/comparison.png`.

## What's included

**New `karaoke_gen/portrait/` module** (reuses the existing
`SubtitlesGenerator` engine + the job's corrected-lyrics data, so
word-by-word timing is identical to the landscape video):
- `wrap.py` — orphan-merging balanced wrapper (no stranded "No," lines),
timing-preserving
- `background.py` — branded portrait background (wordmark/header +
song/artist + footer) + "thank you" end card
- `renderer.py` — portrait ASS + title/end cards + single-pass ffmpeg
assembly (title + lyrics body + end)

**Backend integration** (minimal, low-risk):
- `gce_encoding/main.py::render_portrait_into_outputs` — renders on the
GCE encoder inside `run_encoding`, using the un-padded instrumental +
un-countdown-processed segments (inherently in sync). Writes into
`output_dir`, so it rides the existing `finals/` GCS upload + Dropbox
folder upload.
- `EncodingOutput.portrait_mp4_path` + filename classification +
orchestrator download-allowlist mapping + admin files-manifest entry.
YouTube/Drive use their own allowlists, so the portrait is naturally
excluded from them.

## Testing

- 17 new tests in `tests/unit/portrait/` (balanced wrapping,
background/layout, guard + non-fatal wiring, and a real end-to-end
ffmpeg render on a synthetic fixture).
- Existing GCE/encoding/orchestration/lyrics-output suites green (116
tests total across touched areas).
- **Verified end-to-end on real prod job piri – dog (`052b94ab`)** via
the backend integration function: produced a valid, on-brand 1080×1920
portrait with live word-highlighting, correct title/end cards, correct
duration.

## Safety / rollout

- Additive + `PORTRAIT_RENDER_ENABLED` (default on) + wrapped in
try/except: a portrait failure logs and returns `None` — it never fails
the job or blocks landscape outputs/distribution.
- Subprocess timeouts on ffprobe/ffmpeg so a stalled render can't hang
the worker.
- ~15–30s + ~10 MB per job.

Design: `docs/archive/2026-06-14-portrait-video-design.md` · Plan:
`docs/archive/2026-07-13-portrait-video-plan.md`

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

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-14 21:01:08 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 1b6833b182 fix(jobs): show job/log timestamps in the viewer's local timezone (#907)
## Problem

Job dates on the dashboard displayed the raw UTC wall-clock instead of
the viewer's local time. e.g. a job submitted at ~4:10 PM local (viewer
at UTC-2) showed as `8/14/2026, 6:10:25 PM`.

## Root cause

`created_at` (and timeline/log timestamps) were built from naive
`datetime.utcnow()` and serialized via `model_dump(mode='json')` /
`.isoformat()`, producing ISO strings with **no timezone offset**
(`"2026-08-14T18:10:25.123456"`). Firestore stored them as plain strings
and returned them verbatim. The frontend's `new Date(str)` parses an
offset-less ISO date-time as **local** time, so the UTC value was shown
unconverted — off by the viewer's UTC offset.

## Fix

**Frontend (fixes all existing + new data, no migration):**
- New `parseServerDate()` util in `frontend/lib/utils.ts` — treats
offset-less ISO date-times as UTC (appends `Z`); passes through strings
that already carry `Z`/`±HH:MM`, plus `Date`/epoch inputs.
- Applied at every customer-facing server-timestamp display: `JobCard`
created-at, `JobLogs` timestamps, referral payout dates, and
referral-discount expiry (`BuyCreditsDialog` + dashboard).
- 8 unit tests covering
naive/`Z`/`+00:00`/non-UTC-offset/date-only/epoch/`Date` cases.

**Backend (makes stored timestamps unambiguous going forward):**
- `create_job` and timeline events now use `datetime.now(timezone.utc)`,
so serialized ISO strings carry a `+00:00` offset. Arithmetic consumers
(`job_health_service`) already guard for both naive and aware datetimes.

## Testing
- Backend: 210 targeted tests pass (job_manager / firestore / timeline /
job_health / countdown).
- Frontend: full suite 1108 tests pass (85 suites), including the new
util tests.

## Notes
- `/admin/*` pages (English-only, internal) still use `new Date()`
directly; they benefit from the backend change for new jobs but were
left otherwise untouched as out of scope.
- CodeRabbit local review was rate-limited (free OSS quota), so this PR
intentionally omits `@coderabbitai ignore` to let the bot review.

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-14 17:40:11 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 84b0683cba fix(audio-search): recover parked jobs — edit + re-search + own-audio fallback (#906)
## Problem

In Bulk Mode (and single jobs), the "Choose audio" dialog was a **hard
dead-end**. When a search returned nothing usable — 0 results, a
transient flacfetch failure, or an auto-picked source that's unusable —
the bulk worker parks the job in `AWAITING_AUDIO_SELECTION` with
**empty** cached results. The dialog then showed "No audio sources
found" with **no retry, no way to edit the title, and no manual
source**, so the user was trapped.

Real-world trigger (batch `4af58968a64a`): two Arctic Monkeys tracks
parked with 0 results (one a transient miss on a common track, one an
over-long title), and three more stuck downloading the **same dead RED
torrent** — all with no path forward.

## What this does

Adds a full recovery path to the shared `AudioSearchDialog` (used by
bulk **and** single jobs):

- **Edit + Search again** — always-available editable artist/title with
a re-search button. Edits apply to the job's search terms *and* display
metadata.
- **Provide your own audio** — paste a YouTube/yt-dlp URL, or upload a
file.
- **Graceful empty state** — a 400 (no cached results) renders as the
empty state with the refine bar, not a red error; real network/5xx
errors still surface.

### Backend (`audio_search.py`) — all guarded to
`AWAITING_AUDIO_SELECTION`, tenant-gated, no new job, no double-charge
(final duration billing reconciles post-download)
- `POST /{job_id}/research` — retry / edit-and-re-search. Empty results
are a normal `200`.
- `POST /{job_id}/provide-url` — YouTube URLs go through the **async**
audio-download worker; generic yt-dlp URLs download inline, bounded by a
timeout (never strands a job).
- `POST /{job_id}/attach-upload-url` + `/attach-upload-complete` —
signed-URL upload of the user's own file (extension allow-list +
traversal-safe; the complete step pins the exact uploaded object).
- Factored the triplicated result serialization into
`_build_result_response`.

## Testing
- 20 backend endpoint tests + 5 frontend dialog tests (all green);
broader audio/jobs sweeps pass.
- i18n: 15 new `audioSearch` keys across all 33 locales.

## Review
Local CodeRabbit review completed (2 cycles, all 6 findings addressed,
final pass 0 findings).

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-14 02:50:53 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 c5bca2240a fix(encoding): self-heal missing wheel deps on fresh workers (No module named 'tenacity') (#905)
## Problem

Renders failed with `OutputGenerator not available: No module named
'tenacity'. The karaoke-gen wheel must be installed. Check that
ensure_latest_wheel() succeeded.` (job `233b9536`, Luke Bell –
Sometimes; all 4 retries failed identically).

**Root cause (confirmed live in prod):** A freshly-provisioned
encoding-worker VM — specifically the `n2-highcpu-32` fallback added in
#903 — boots with only a handful of packages baked into the Packer image
and installs the wheel with `--no-deps`. The full karaoke-gen dependency
tree (torch, langchain, tenacity, …) is installed **lazily at the first
job** by `ensure_latest_wheel()`. Two bugs made that fragile:

1. `ensure_latest_wheel()` ran `gsutil cp
gs://…/wheels/karaoke_gen-*.whl /tmp/` — copying the **entire `wheels/`
dir (338 wheels ≈ 6.4 GiB)** every job with a 60 s timeout. On a fresh
VM that times out → "no wheel found" → no deps installed.
2. The actual dep install (torch + CUDA, multi-GB) can't finish in the
old 300 s timeout. A partial/failed install left the venv
importable-but-incomplete, and **`ensure_latest_wheel()`'s return value
was ignored**, so the render proceeded and died on the first missing
import.

The SSH repair on the stuck VM showed the venv was nearly bare (install
pulled the whole tree, ~3.5 min).

## Fix

`backend/services/gce_encoding/main.py`:
- **Download only the single latest wheel** (`gsutil ls` → version-sort
→ `gsutil cp` one file, ~2 s) instead of copying the whole 6.4 GiB
directory.
- **Retry the install** (3× at 900 s) and **verify the render/encode
import chain** in a subprocess (`verify_wheel_imports()`) before
returning `True` — a clean `pip` exit is no longer trusted, since pip
can exit 0 while a dependency is still missing.
- **Callers fail fast** with a clear, retryable error when the
environment isn't ready, instead of proceeding into a confusing
`ImportError`.
- Run `ensure_latest_wheel()` in the **thread-pool executor** so its
blocking, multi-minute installs don't stall the async event loop
(health/status endpoints stay responsive).
- Fix misleading "deps pre-installed" comments in `startup.sh` /
`provision.sh`; add a `TROUBLESHOOTING.md` runbook (manual VM repair +
safe re-render path).

The fix propagates to fresh workers automatically via the wheel
installed at boot.

## Testing

- New `TestEnsureLatestWheelVerification` + `TestVerifyWheelImports` (13
tests) cover: single-wheel download, **pip-ok-but-imports-broken** (the
core regression), retry-after-partial-install, install timeout recovery,
and no-wheel / download-fail. `test_gce_encoding_worker.py`: 40 passed;
encoding-related suite: 111 passed.
- **Verified in prod:** repaired the stuck
`encoding-worker-fallback-n2c` venv (`sudo pip install` latest wheel →
imports OK, health OK), then re-rendered job `233b9536` via
`awaiting_review` → review `/complete`. Render ran on the repaired
worker past the old ~72 s failure point and the job reached **`complete`
(100%)**.
- CodeRabbit reviewed locally (2 cycles): event-loop-blocking + docs
findings fixed; no new findings.

## Known limitation (not addressed here)

CodeRabbit flagged that per-job `pip install --upgrade` mutates a
**shared venv**, which could disrupt a concurrent job. This is
pre-existing behavior (the GCE worker is single-tenant per render by
design) and would require job isolation / install serialization — out of
scope for this hotfix.

## Durable follow-up

Bake the full dependency tree into the Packer image (and/or pin CPU-only
torch) so fresh workers are self-sufficient and don't pay a multi-GB
first-job install. Larger infra change (image rebuild + Pulumi).

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-13 16:26:46 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 807145a6f9 fix(ci): bump Windows GHA runner 2.334.0 → 2.336.0 (missed in #902) (#904)
## Follow-up to #902
#902 bumped the runner pin to `2.336.0` in the Linux provision + startup
scripts but **missed the Windows image bake** —
`infrastructure/scripts/runner-image-provision.ps1` still pinned
deprecated `v2.334.0` (my grep only covered `.sh/.py/.yml`).

Symptom: the `gpu-windows` image rebuild failed downloading
`actions-runner-win-x64-2.334.0.zip`, and even on success would bake a
deprecated runner (→ Windows GPU runners self-terminate, same failure
mode as #902).

## Fix
One-line bump in `runner-image-provision.ps1` to match (`2.336.0`). Then
rebuild the `gha-runner-gpu-windows` image (dispatched from this
branch).

Infra-only, image-build-consumed script (no Pulumi graph impact — same
as #902). The Linux `gpu` image already rebuilt successfully on 2.336.0.

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

## Summary by CodeRabbit

* **Chores**
* Updated the Windows build runner environment to use a newer runner
version.
  * No other provisioning behavior changed.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-12 17:31:33 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 f5d3bdf426 fix(ci): bump GHA runner 2.334.0 → 2.336.0 (deprecated, wedging all self-hosted CI) (#902)
## Incident
All self-hosted CI jobs (`Backend - Unit Tests`, `Backend - Emulator
Integration Tests`, and any `build`/`gpu` jobs) have been **wedged in
`queued`** — ephemeral runner VMs boot, then self-terminate within ~1-2
min without ever picking up a job.

## Root cause (confirmed via live serial console)
GitHub **deprecated `actions/runner` v2.334.0**. Our ephemeral runners
register with JIT config (`run.sh --jitconfig`), which runs with
`disableUpdate` — so they **cannot self-update**. Serial console of a
dispatched runner VM:

```
√ Connected to GitHub
Current runner version: '2.334.0'
2026-08-12 ...Z: Listening for Jobs
An error occurred: Runner version v2.334.0 is deprecated and cannot receive messages.
Runner listener exit with terminated error, stop the service, no retry needed.
Exiting runner...
Shutdown scheduled for ...
```

The VM's `trap 'shutdown -h +1' EXIT` then terminates it, the
orphan-reaper deletes it, and the queued job is stranded. (The
immediate-TERMINATED reaping made this masquerade as Spot
preemption/capacity — it is not.)

This is a recurrence of the known runner-deprecation failure mode; the
provision script even documents it.

## Fix
Bump the pin `2.334.0 → 2.336.0` (current latest) in:
- `infrastructure/scripts/runner-image-provision.sh` (image bake — the
one the ephemeral `run.sh` actually uses)
- `infrastructure/compute/startup_scripts/github_runner.sh`,
`github_runner_gpu.sh` (baked startup scripts, kept consistent)

## Rollout
The **`Build GHA Runner Images`** workflow must rebuild the
`gha-runner-*` images so the ephemeral dispatcher (which selects the
newest non-deprecated image in each family) picks up the new binary.
I've dispatched a build for `general,build` from this branch. **`gpu` +
`gpu-windows` still need rebuilding too** (follow-up) to unblock GPU CI.

## Testing
Infra-only change; validated by the image build + a green self-hosted CI
run once new images are live.

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

## Summary by CodeRabbit

* **Chores**
  * Updated the GitHub Actions runner to version 2.336.0.
* Applied the update across standard, GPU, and provisioned runner
environments.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-12 15:00:21 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 5291d6ca78 fix: quiet visibility-change 404 noise + clarify re-render UX (#901)
## Summary

A **private→public visibility change** on a completed job re-runs the
render pipeline. This tripped three error-monitor alerts and confused
users. All fixed here (backend noise + frontend UX), plus the
encoding-capacity transparency the delay exposed.

Traced from prod alerts on job `25d076e5` (user clicked "Make Public";
the finals were deleted for re-render, and the encoding-worker capacity
was exhausted → 503s for ~26 min → looked "stuck").

## Backend — kill the false-alarm noise
- `visibility_change_service`: best-effort intermediate-artifact deletes
now pass `ignore_missing=True` (no more spurious `Error deleting file
…404` ERRORs).
- `storage_service.download_file`: re-raises `NotFound` at `warning`,
not `error`.
- `jobs` download route: missing object → **HTTP 404** (localized
detail), not 500. Temp file is now cleaned up when download fails before
streaming starts (no leak).

## Frontend — fix the UX confusion
- **JobCard banner** while `visibility_change_in_progress` (and not
complete): explains the re-render + republish takes ~15–30 min, so a
completed track no longer silently reverts to a generic processing
state.
- **OutputLinks** hides stale links during a change: GCS finals only
during the private→public re-render (status leaves `complete`);
YouTube/Dropbox in both directions. The fast public→private path keeps
its finals.
- **Encoding-capacity transparency**: the `render_pending_capacity`
status + its persistent `state_data` breadcrumb drive a `(waiting for
encoding server availability)` note next to progress; reworded
`jobStatus.waitingForCapacity`.
- New i18n strings translated to all 33 locales (frontend + backend).

## Testing
- Backend: `test_change_visibility`, `test_storage_service`,
`test_routes_jobs` (added: intermediate deletes use `ignore_missing`;
`download_file` re-raises `NotFound`).
- Frontend: `job-status` helper tests (capacity/visibility, incl.
lingering-breadcrumb guard) + `OutputLinks` (both transition
directions).
- Full frontend jest suite green (1094 tests).

## Reviewed locally with CodeRabbit
2 major + 1 minor findings addressed (temp-file leak, direction-aware
download gating, localized 404).

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-12 12:32:31 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 ec99164a05 feat(infra): diversify encoding-worker fallbacks with n2-highcpu-32 (capacity resilience) (#903)
## Problem

A **region-wide `c4d-highcpu-32` capacity stockout**
(`ZONE_RESOURCE_POOL_EXHAUSTED` across `us-central1-a`, `-b`, and `-c`
simultaneously, 2026-08-12) took out **every** encoding-worker lane at
once, because the primary blue-green pair *and* both capacity fallbacks
are all the same machine family.

Consequences observed in prod:
- **Lyrics-review preview** (`POST /api/review/{id}/preview-video`) fell
back to slow local Cloud-Run encoding (~130–160 s), which **exceeds
Cloudflare's ~100 s edge timeout** → users got a **524 / "NetworkError
when attempting to fetch resource"** even though the backend actually
returned 200.
- **Final renders** parked in `RENDER_PENDING_CAPACITY` and could only
complete once c4d capacity returned (24 h auto-retry window).

Prior work (May 2026) diversified fallbacks across **zones** but not
**machine family** — and a stockout is per *(machine family × region)*,
so every zone of a family can go at once.

## Fix (Option B)

Add **`n2-highcpu-32`** capacity fallbacks
(`encoding-worker-fallback-n2c` in `us-central1-c`, `-n2f` in
`us-central1-f`) — an independent, much deeper capacity pool a c4d
stockout cannot exhaust.

**Runtime is unchanged** — `ensure_any_running` already iterates
arbitrary `{vm,zone,ip}` candidates, `start_vm(zone=)` is zone-generic,
and the idle-shutdown function is secret-driven. This is purely IaC + a
secret version:

- `infrastructure/config.py` — `EncodingWorkerConfig.FALLBACKS` now
carries per-VM `machine_type` + `disk_type` (n2 uses `pd-balanced`; it
doesn't support hyperdisk-balanced). Existing `a`/`b` entries kept
**byte-identical** so `pulumi up` does not replace the live c4d VMs.
- `infrastructure/compute/encoding_worker_vm.py` — build fallback
IPs/VMs from `FALLBACKS`.
- Tests: config invariants + n2 idle-shutdown regression (**29 pass**).
- Docs: `LESSONS-LEARNED`, `TROUBLESHOOTING`, plan doc.

## Rollout status (already applied locally)

- ✅ `pulumi up` (targeted) applied to `prod`: created 2 n2 IPs + 2 n2
VMs (stopped). Verified additive — the existing c4d VMs were **not**
touched. (A pre-existing unrelated `runner-manager` drift from another
worktree was deliberately **not** applied.)
- ✅ `encoding-worker-fallback-vms` secret updated to v2 with the two n2
entries (picked up by Cloud Run / `video-encoding-job` / idle function
at next instance start).
- ✅ Smoke-tested: n2 VM boots the encoding-worker image and serves
`/health`.

## Testing

- `pytest infrastructure/test_encoding_worker_config.py
infrastructure/functions/encoding_worker_idle/test_idle_shutdown.py` →
29 passed.
- `pulumi preview` → `+4 to create`, no replacement of existing
encoding-worker resources.

## Follow-up (separate)

Preview is synchronous and can outlive the ~100 s edge timeout → opaque
524. Durable fix is making preview async/polling (like render), or
fail-fast to local when all VM starts stock out. Tracked in the plan
doc.

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

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-12 12:07:53 -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
Andrew Beveridge ☄️andClaude Opus 4.8 eb711b32a8 fix(divebar): folder-brand-aware index parser + symmetric xref normalization (#857)
## Summary
- Rewrites the Divebar Drive→BigQuery **filename parser** to be
folder-brand-aware, fixing mis-split artists and brand-polluted titles
that prevented mirror files from surfacing in kjbox.
- Fixes a **normalization asymmetry** in the KN↔Divebar xref join (KN
side was only `LOWER(TRIM())` vs the db's fully-normalized columns) and
removes a buggy `brand_match` branch that produced wrong-song links.
- Switches both divebar Cloud Function modules to `pulumi.FileArchive`
so `pulumi up` actually redeploys changed code.

## Changes
- `divebar_mirror/filename_parser.py` — folder-brand-aware rewrite:
strip the brand token wherever it sits (disc-id prefix/suffix,
`(CODE)`/`CODE -` prefix, `[Brand]`/`(Brand)`/` - Brand` suffix, generic
karaoke tags), each strip gated on a folder-brand match so real song
text (`(Live)`, `(G)I-DLE`, bands like `UB40`/`311`/`ACDC`) survives.
Curated folder→KN-code map fills `brand_code`. En-dash separator +
leading-dash cleanup.
- `divebar_lookup/main.py` — new `_norm_sql(col)` routes **both** join
sides through one identical BigQuery expression replicating
`normalize_for_search`; `brand_match` branch removed (it matched
brand+artist with no title → Cartesian wrong-song links; 107,485/107,485
pairs were title mismatches in live data).
- `modules/divebar_mirror.py` + `modules/divebar_lookup.py` —
`FileArchive` + `BucketObject` with `generation` pinning (matches
`runner_manager`), so code changes redeploy.
- New `tests/unit/test_divebar_filename_parser.py` (48 cases) + 3
`_norm_sql` guard tests; version bump 0.188.3→0.188.4.

## Impact (validated read-only over all 50,046 live rows)
- null `brand_code`: 18,437 (37%) → **1,619 (3%)**
- Divebar files cross-referenced to a KN song: production **23,318** →
**33,449** on current data (+10,131 from the symmetry fix alone),
lifting toward ~38k after the parser re-index.

## Testing
- [x] 64 divebar unit tests pass locally (parser 48, index_builder 5,
divebar_lookup 11)
- [x] Offline validation harness over all 50k live rows (read-only
BigQuery); `_norm_sql` confirmed to reproduce `normalize_for_search`
exactly
- [ ] CI full suite

## Deploy / re-index (post-merge)
`pulumi up` redeploys both functions; then trigger scheduler
`divebar-mirror-daily` (re-parse → MERGE, preserves `gcs_path`) **then**
`divebar-xref-rebuild-daily`. Order matters. (`kn_data_sync` still uses
a static source object — future-edit redeploy trap, out of scope here.)

## Review
- [x] CodeRabbit CLI review completed locally (1 finding → fixed:
brand_match removal; cycle 2 clean)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-28 14:16:35 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 ef65adedc7 feat: richer DRM-URL guidance + validate at 'Use this URL' (follow-up to #855) (#856)
## Summary

Follow-up to #855 (the Apple Music DRM-URL fix). Two improvements to how
we guide users who paste an undownloadable streaming link:

### 1. More downloader options + Google-search fallback
The DRM rejection now offers richer guidance:
- **Apple Music** → https://am-dl.pages.dev, https://aplmate.com
- **Spotify** → https://spotdown.org, https://spotmate.online
- **Everything else** (Tidal, Amazon Music, Deezer, Pandora) → a Google
search link for "`<platform> downloader`"

`_DRM_DOWNLOADER_SUGGESTIONS` now maps platform → list of URLs, and a
new `_drm_unsupported_detail()` helper picks `drmUrlUnsupportedWithLink`
(known tools) vs the new `drmUrlUnsupportedSearch` (web-search
fallback). `LinkifiedText` already renders multiple URLs as clickable
links, so no frontend change was needed for the message itself.

### 2. Validate at "Use this URL", not just final submit
Previously the guided flow collected the URL early but only surfaced the
DRM rejection at **final submit** — after the user walked the entire
flow. Now the "Use this URL" button calls a lightweight **`POST
/api/jobs/validate-url`** endpoint (reuses `_unsupported_url_platform` +
`_drm_unsupported_detail` — single source of truth, no duplicated
list/links/i18n), shows the guidance immediately with a "Checking…"
spinner, and blocks advancing. Fails open on network error since the
final submit still validates server-side.

## Review notes (CodeRabbit, local)
- Generalized Amazon Music host matching; `urlparse().hostname` for
robustness; locale-neutral comma join (not English "or").
- **Kept** the third-party downloader links by design — explicit product
decision (the third-party/link-rot risk is acknowledged;
`_DRM_DOWNLOADER_SUGGESTIONS` makes updates one-line).
- Disabled the URL input during validation to avoid a stale-result race.
- Skipped a suggested 400-handler in `validateJobUrl`: the endpoint
returns **200** with `{supported:false}`, not 400.

## Testing
- Backend: `TestUnsupportedDrmUrl`, `TestValidateJobUrlEndpoint` (+
existing) — `test_file_upload.py` 151 passed.
- Frontend: new `AudioSourceStep` interaction test (Apple Music URL
blocked at "Use this URL" with a clickable downloader link, no advance)
+ `LinkifiedText` tests — 32 passed; full job/ui suites green.

Details: `docs/archive/2026-06-27-apple-music-url-download-errors.md`

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

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-27 22:39:48 +00:00
Andrew Beveridge ☄️andClaude Opus 4.8 a213ec4d5d fix: reject DRM streaming URLs upfront + fix retry routing for failed URL downloads (#855)
## Summary

Investigated four simultaneous "New Error Pattern" alerts (Apple Music
`Unsupported URL` on `karaoke-backend`, plus `Failed to download audio
file` on `audio-separation-job` and `lyrics-transcription-job`). All
four were **one incident**: a user tried to make a karaoke track from an
Apple Music link (job `7f36304a`), submitted it twice, and clicked
**Retry** once. That exposed two real bugs, both fixed here.

### Bug A — DRM streaming URLs accepted, then fail deep with a cryptic
error
`_validate_url` had an allowlist but fell through to `return True` for
everything ("let yt-dlp try"). Apple Music / Spotify / Tidal / Amazon
Music / Deezer / Pandora are DRM-protected and can never download, so a
job got created and died at the download stage with an HTTP 500 +
"Unsupported URL".

**Fix:** new `_unsupported_url_platform()` helper + the
`create-from-url` endpoint now returns a friendly **400**
(`audioSearch.drmUrlUnsupported`, all 33 locales) before a job is
created. YouTube Music (`music.youtube.com`) is deliberately **not**
blocked — it's downloadable. Amazon Music matched generically
(`music.amazon.*`) to cover all country domains.

### Bug B — retrying a URL job that failed *before download* fires the
wrong workers
The retry "restart from beginning" branch was gated on
`job.input_media_gcs_path or job.url`. A URL job whose download never
succeeded still has `job.url` set but **no** audio in GCS, so Retry
jumped straight to the audio/lyrics workers → "Failed to download audio
file" → Cloud Run retried them (the ×6/×6 alert counts) → wasted GPU.
Latent for any URL-download failure, not just Apple Music.

**Fix:** the branch is now gated on `job.input_media_gcs_path` only. URL
jobs without downloaded audio fall through to the existing clean
**"resubmit"** 400 instead of firing doomed workers — matching the
endpoint's documented intent.

## Timeline (job `7f36304a`)

| Time (UTC) | Event |
|---|---|
| 20:23:02 | Job created from Apple Music URL |
| 20:23:07 | flacfetch → `Unsupported URL` → job failed, HTTP 500 |
| 20:23:31 | User clicks Retry → fires audio + lyrics workers (no audio
in GCS) |
| 20:24–20:28 | Workers fail repeatedly via Cloud Run retries → ×6/×6 |

## Testing

- `TestUnsupportedDrmUrl` — detection across all DRM platforms (+
subdomains, + Amazon country domains); YouTube/YouTube
Music/Vimeo/SoundCloud/generic/None not flagged.
- `TestRetryUrlJobWithoutDownload` — URL job without audio → 400
resubmit + **no** workers scheduled; URL job with audio in GCS →
restarts + workers scheduled.
- Full `test_file_upload.py` + `test_routes_jobs.py`: 217 passed (no
regressions).

Details: `docs/archive/2026-06-27-apple-music-url-download-errors.md`

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

@coderabbitai ignore

---

### Follow-up (same PR): actionable suggestion + clickable links

Rather than just "paste a YouTube link", the DRM rejection now suggests
**downloading the audio with a third-party tool, then uploading the
file**. For platforms with a verified downloader
(`_DRM_DOWNLOADER_SUGGESTIONS`) it links to it — **Apple Music →
https://am-dl.pages.dev** (`drmUrlUnsupportedWithLink`). URLs in
submit-error messages are now clickable via a new `LinkifiedText`
component (guided flow + URL-tab error). `LinkifiedText` has unit tests;
all backend tests still pass (218).

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-27 17:34:33 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 b5e3f39d83 fix(bulk): detect community versions for overlong song titles (#854)
## Problem

In Bulk Mode (By album), ABBA's **"I Do, I Do, I Do, I Do, I Do"**
showed **no community versions** even though two exist on KaraokeNerds
(Nomad Karaoke + RUE ABBA Karaoke). Tracks with no detected community
version are **ticked by default**, so the user would have generated a
**duplicate of an existing community karaoke video**.

## Root cause

Not the commas, and not our title-matching — it's a limit in
**karaokenerds.com's own search**: it silently returns **zero results
once a query exceeds ~10 whitespace-separated terms** (verified against
the live site: 10 terms match, 11 return nothing, regardless of word
order).

`check_community_versions` searches `"{artist} {title}"`. For this track
that's 11 terms → 0 results → falsely reported as "no community
version".

| Query | Terms | Live result |
|---|---|---|
| `ABBA I Do I Do I Do I Do` | 9 | ✅ 2 songs |
| `I Do I Do I Do I Do I Do` (title alone) | 10 | ✅ 2 songs |
| `ABBA I Do, I Do, I Do, I Do, I Do` (what bulk sends) | 11 | ❌ 0 songs
|

## Fix

In `backend/services/karaokenerds_service.py`:
- Extracted `_search_songs(query)` and `_extract_community_songs(songs)`
helpers.
- When the combined `"{artist} {title}"` query **exceeds
`MAX_RELIABLE_QUERY_TERMS` (10)** *and* returns nothing, retry with
**title-only** (the highest-signal term), then keep only results whose
artist matches via `normalize_for_match` (reused from
`match_judge.classifier`) — guarding against same-titled songs by other
artists.
- **Gated on query length**, so short songs and genuine no-community
songs incur **zero extra requests** (KaraokeNerds rate-limiting matters
in bulk).

Verified through the real code path: the ABBA track now returns
`has_community: True` with both brands; short songs are unchanged.

**Known residual limit:** a title that *alone* exceeds 10 words still
chokes — inherent to KaraokeNerds' search, not handled here.

## Tests

4 regression tests (mock `_search_songs`): overlong→title-only fallback,
wrong-artist false-positive guard, short-query-no-fallback,
non-empty-skips-fallback. 48 passed across `test_karaokenerds_service`,
`test_bulk_album_lookup`, `test_bulk_search_worker`, `test_bulk_submit`,
`test_catalog_routes`, `test_match_judge_routes`. CodeRabbit: 0
findings.

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 12:44:57 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 2ff5e4b49f feat(bulk): collapse editions to tracklist variants + clickable community versions (#852)
## Summary
Improves Bulk Mode's "By album" UX in two ways (live-MusicBrainz, no
mirror dependency):

**1. Edition selection → tracklist variants (A+C).** The release
dropdown was ~17 rows of the same album pressed in different countries.
Since the selection only feeds a list of track *names*, we now collapse
a release-group's editions into a few distinct **tracklist variants**
(Option 1: grouped by track count — zero extra MB calls, dodges the
egress rate-limiter) and show a single confident default — *"Using
Original · 1976 · 10 tracks"* — with a **Change** disclosure (hidden
entirely when there's one variant). **Track numbers** are now rendered.
Representative pressing is locale-biased (`next-intl` locale → country
preference), wiring the hook the future mirror upgrade will lean on.

**2. Community versions → vertical, clickable.** The wide inline
`Community version: A, B, C` is replaced by a vertical list, each row a
**clickable YouTube link** so the user can preview a version and decide
whether to remake it. We simply stopped discarding the `youtube_url` the
scraper already captured. Shared by album and text modes.

## Changes
- **Backend** — `musicbrainz_service.build_variants()` +
`country_prefs_for_locale()`; `karaokenerds_service` batch returns
`versions:[{brand,url}]` (back-compat `brands` kept); `bulk.py`
models/routes gain `variants`, `selected_variant_mbid`, per-track
`versions`, and a `locale` param.
- **Frontend** — new `CommunityVersions` component (replaces
`AvailabilityBadge`); `BulkAlbumMode` C-pattern picker + track numbers;
types updated.
- **i18n** — 6 new `bulk` keys translated to all 32 locales.
- **Docs** — `API.md` bulk endpoints updated.

## Testing
- Backend: new unit tests for variant grouping, locale prefs, versions
dedup, and route plumbing; full bulk/MB/KN/catalog suites green (62
passing across touched + regression files).
- Frontend: `community-versions.test.tsx` (link href/target/rel,
fallback, hidden states); `tsc` clean on all touched files.
- Post-deploy: API-level prod verification of
`/api/bulk/album/tracklist` (variants + versions present).

## Notes
- The larger mirror-backed upgrade (exact tracklist-signature grouping +
popularity ranking) is captured in
`docs/archive/2026-06-18-musicbrainz-mirror-and-album-ux-handoff.md`;
this PR is the cheap live-MB version.
- Design:
`docs/archive/2026-06-22-bulk-edition-collapse-and-community-versions-design.md`.

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

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 18:44:02 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 3b5fd07ba0 docs: archive PyPI 10GB storage-limit fix retrospective (#853)
## Summary

Archives a detailed retrospective of the 2026-06-22 PyPI 10 GB
storage-limit fix (shipped in #851), so future sessions can refer back
if it recurs.

Covers:
- **Symptom & diagnosis** — `poetry publish` 400ing at the 10 GB cap;
measured 10.711 GB / 444 releases
- **Root cause** — i18n's 33-locale static export bundled in wheel+sdist
since v0.172.1 (Apr 2026)
- **The two-part fix** — one-time web-UI deletion of 42 fat releases
(~4.35 GB freed) + wheel-only publish (104→54 MB/release)
- **How to bulk-delete PyPI releases** (no API; the
CSRF/`confirm_delete_version` web-UI technique) and the
Fastly-cached-JSON verification gotcha
- **Why `exclude` can't trim the sdist** while `out/` is git-tracked
- **Recurrence runbook**

Docs-only — no version bump.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 22:34:49 +00:00
Andrew Beveridge ☄️andClaude Opus 4.8 bfa375639b ci: publish wheel-only to PyPI (fix 10 GB storage cap) (#851)
## Problem

Every `poetry publish` on merge to `main` was failing with:

```
HTTP Error 400: Project size too large. Limit project 'karaoke-gen' total size 10 GB.
```

The PyPI project had grown to **10.711 GB across 444 releases**, over
the 10 GB cap.

## Root cause

Since the i18n initiative (**v0.172.1, 2026-04-23**), `next build`
pre-renders the app into **33 locale directories** (~112 MB
uncompressed), and both the wheel **and** the sdist bundle this static
export. Per-release cost jumped from ~18 MB to ~104 MB (53.7 MB wheel +
50.2 MB sdist). 57 fat releases = >5.8 GB of the 10.7 GB total.

## Fix (this PR): publish wheel-only

The sdist is dead weight — we ship a universal `py3-none-any` wheel, pip
always installs from it, and nothing builds karaoke-gen from source (the
GCE encoding worker pulls the wheel from GCS, not PyPI).

- `poetry build --format wheel` in both the package-test and
package-publish jobs (no sdist built)
- drop `dist/*.tar.gz` from the GitHub release attachments
- bump `0.187.4 → 0.187.5`

**Per-release PyPI cost: 104 MB → 54 MB.** The wheel is unchanged — it
still bundles the frontend the CLI local-review server reads at runtime
(verified: built wheel contains all 3575 `out/` entries + entry points).

## Companion one-time cleanup (already done, not in this diff)

Deleted **42 old fat releases** (`0.172.1`–`0.182.2`, ~4.35 GB) via the
PyPI web UI, keeping the 15 most recent fat releases
(`0.183.0`–`0.187.2`) and all 387 small historical releases
(`≤0.171.x`). Project is now **~6.36 GB** (3.64 GB headroom). Nothing
internal pins old PyPI versions, so blast radius was zero.

## Testing

- `poetry build --format wheel` → `dist/` contains only the 53.7 MB
wheel (no tar.gz), wheel has all `out/` assets + 3 console entry points.
- `ci.yml` validated (parses, no remaining sdist/tar.gz dependencies).
- No application code changed; full suite runs in CI on this PR.
- The merge itself is the live verification that `poetry publish`
succeeds (publishes 0.187.5 wheel-only).

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-22 18:16:19 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 ec41ad5e5e feat: colorize word pills when a song has no reference lyrics (#850)
## Summary
- When a song has **no reference lyrics**, nothing classifies words as
anchor/gap/corrected, so every word pill rendered uncoloured — losing
the colour-scanning the review UI is built around (see attached
screenshot: every line plain grey).
- Adds a lowest-precedence **gap-orange** fallback for plain word pills,
gated on "no reference lyrics" (the same
`Object.keys(reference_lyrics).length === 0` signal `GuidancePanel` uses
for its "No reference lyrics found" panel).
- Works in **both Simple and Advanced** modes — threaded through the
single `wordPositions` render path both modes share.

## Changes
- `lib/lyrics-review/types.ts` — new `fallbackGapColor?: boolean` on
`WordProps`.
- `components/lyrics-review/shared/Word.tsx` — appends the fallback to
the end of the colour chain, so any real classification colour
(playing/AI/anchor/user-edited/corrected/gap) still wins.
- `components/lyrics-review/shared/HighlightedText.tsx` — new
`noReferenceFallback` prop, passed down as `fallbackGapColor` to both
`WordComponent` render paths.
- `components/lyrics-review/TranscriptionView.tsx` — computes
`hasReferenceLyrics` and passes
`noReferenceFallback={!hasReferenceLyrics}`.
- `components/lyrics-review/shared/__tests__/Word.test.tsx` — new
focused test (5 cases) verifying the orange appears only with the
fallback flag and never overrides a real classification colour.
- No new user-facing strings → no i18n changes.

## Testing
- [x] Frontend unit suite: 79 suites / 1049 tests pass (incl. new
`Word.test.tsx`)
- [x] Typecheck clean on all touched files
- [x] CodeRabbit CLI review: 0 findings

## Review
- [x] Local CodeRabbit review completed
- [x] No issues to address

@coderabbitai ignore

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

https://claude.ai/code/session_01E8pq3aMDRkcPdrsmd1PqHH

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-19 11:31:03 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 354f60b59d fix(lyrics-review): pad long-word duration pill in Simple mode (#849)
## Summary

Adds a little breathing room between a word and its long-word duration
pill in the Simple-mode lyrics review, so the amber `🕐 3.3s` badge isn't
squashed up against the word text.

## The bug

The duration badge uses `ml-auto` to hug the right edge in
Advanced/Timeline mode. But `ml-auto` only consumes free space — in
Simple mode the pill is content-sized, so `ml-auto` resolved to `0` and
the badge sat flush against the word. The badge's own `pl-1`/`px-1` only
pad *inside* the amber border, not between the word and the pill.

## The fix

Add `gap-1` (4px) to the outer flex container, applied only to long-word
pills (`hasDurationBadge`):

```diff
- hasDurationBadge ? 'inline-flex items-center' : 'inline-block',
+ hasDurationBadge ? 'inline-flex items-center gap-1' : 'inline-block',
```

- Plain words (no badge) are untouched — they use `inline-block`.
- Timeline/Advanced mode unaffected: `ml-auto` still hugs the badge to
the right edge; the gap is just a minimum.

## Before / After

Before: `now🕐3.3s` (badge flush against "now")
After: `now 🕐3.3s` (4px gap)

## Testing

- All 142 lyrics-review unit tests pass (17 suites).
- No snapshots reference this component, so the class change breaks
nothing.
- CodeRabbit: 0 findings.

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 19:44:48 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 d5edaab7d2 feat(bulk): compact Single/Bulk toggle in card header (#848)
Moves the Single/Bulk switch from a full-width two-button tab (which
wasted vertical space for the ~majority who never bulk-submit) into a
subtle segmented control in the top-right of the Create Karaoke Video
card header. Content switches via state. Frontend-only.

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

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 18:07:55 +00:00
Andrew Beveridge ☄️andClaude Opus 4.8 7d21260438 fix(bulk): diagnose + harden MusicBrainz lookups failing in prod (#847)
Album-mode MusicBrainz lookups return 502 from Cloud Run (they work
locally + in unit tests). Prod logs show an empty exception message, so
this PR:

- Adds `%r` + `exc_info=True` to the 3 MB route handlers to capture the
real exception type + traceback in prod.
- Adds retry-with-backoff (3×) to `musicbrainz_service._get` for MB 503s
(rate-limiting) and transient transport/timeout errors — the most common
cloud-egress failure mode.

Text mode + the credit gate are already verified working in prod; album
lookup degrades gracefully to a 502 + frontend fallback. Once deployed,
the logs will reveal the true cause and we can apply the targeted fix
(e.g. route MB through flacfetch if it's a hard IP block).

Tests: 2 new retry unit tests (503→retry→success; exhaust→raise). Full
MB suite green.

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

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 17:14:16 +00:00
Andrew Beveridge ☄️andClaude Opus 4.8 4f411c4306 feat(lyrics-review): auto-apply corrections + timeline-in-text Advanced view (#846)
## Summary

Reworks the lyrics review UX now that AI auto-corrections are reliable,
and replaces the separate Timeline view with timing intelligence baked
into the lyrics themselves.

### Auto-correct display
- **Auto-apply on load** (= the old "Accept all") as the review
**baseline** — not an undoable edit — so no save/restore prompt appears
unless you make a genuine manual edit.
- Corrected words render **purple** with a grey struck-through "original
transcription" bubble above; words whose timing was **estimated** (a
word split into several, or inserted) get an **amber dashed underline**,
while clean 1:1 replacements stay solid.
- The standing suggestions row is gone — the toolbar button reads
**"Auto-corrected · N"** and opens a details panel on demand (per-item
**undo**, **Re-run**, **Revert all auto-corrections**).
- Guidance panel: purple/amber legend + a "play each corrected line and
re-check timing" tip. Tooltips say "auto-corrected by our system" (no
"AI").

### Timeline rework (replaces the Timeline view)
- Single **Simple / Advanced** toggle replaces both the Text/Timeline
toggle and the old Simple/Advanced badge; `DurationTimelineView`
deleted.
- Inline **>2s long-word** (badge inside the pill, right-aligned) and
**>2s inter-word gap** warnings, in both modes.
- **Advanced** mode stretches each word pill by its duration (flex) so a
segment fills the full width as a readable timeline; gap spacers are
**click-to-play** (hover shows a play icon).

### Session restore unification
- Removed the ad-hoc `window.confirm` localStorage path. The same
`SessionRestoreDialog` is now used everywhere — server-backed in cloud
mode, and a new **localStorage session store** when running karaoke-gen
locally.

### Other
- `crash-reporter`: never POST client errors from a localhost origin
(was tripping the prod error monitor during local dev).
- New `Word` provenance fields + apply-time stamping.

## Testing
- Frontend unit suite: **1034/1034 pass** (new tests for apply-time
stamping, the local session store, and the localhost-skip guard).
- `tsc --noEmit`: no new errors; ESLint: 0 errors.
- All **33 locales** translated and verified complete (1415 keys each).
- Iterated and verified live in a local frontend against the prod
backend across several real jobs (auto-apply, purple/bubbles/markers,
Advanced timeline, gap-click-to-play, clean fresh-load with no restore
prompt).
- Reviewed with CodeRabbit; findings addressed.

Design doc: `docs/archive/2026-06-18-autocorrect-applied-ux-design.md`

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 13:05:41 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 feca70674b feat: Bulk Mode — submit up to 100 karaoke jobs at once (album or text) (#845)
## Bulk Mode — submit up to 100 karaoke jobs at once

Adds a **Bulk Mode** tab to the job-submission flow so users can make
karaoke versions of a whole album (or a typed list) in one go.

### Two ways in
- **By album** — MusicBrainz artist → album → tracklist.
Live/remix/bonus tracks and songs that already have a community version
on KaraokeNerds start **unticked** (re-tick anything). Auto-picks the
canonical edition, with an edition switcher.
- **By text** — up to 100 artist/title rows, each with a
community-version availability badge.

### Auto + review-queue model
Batch settings (auto-pick lossless / public-private / skip audio edit /
skip customization) drive auto-completion. The server runs each audio
search and **auto-selects only a confident lossless ("tier 1") match**;
everything else is parked in the existing `AWAITING_AUDIO_SELECTION`
state and surfaced as a review queue (reusing the existing
`AudioSearchDialog`). A popular full-FLAC album with all toggles on =
zero further prompts; the tab can be closed (searches run as a Cloud Run
Job).

### Credits
Gated upfront: requires `credits >= number_of_songs` (1/song minimum)
before any job is created; admins bypass. Duration deltas for long
tracks are charged per-song during processing as today.

### Backend
- `POST /api/bulk/submit`, `GET /api/bulk/{batch_id}`, `GET
/api/bulk/album/{artists,albums,tracklist}`, `POST
/api/bulk/availability`
- `bulk_search_worker` Cloud Run Job (`infrastructure/`:
`bulk-search-job`) — search → tier-1 auto-select (with duration-delta
charge) or park; per-job crash isolation; idempotent on retry
(charge_pending guard prevents double-charge)
- New `musicbrainz_service` (release lookup + extras detection); reuses
existing `karaokenerds_service` scraper (batch helper) for availability
— **no karaoke-decide change** (it has the `is_community` flag matching
"community-created"; see design doc)
- `pick_auto_selection` ports the frontend tier-1 confidence rule to the
backend (parity test)

### Frontend
- `components/job/bulk/*` (album/text modes, batch settings, submit bar,
batch progress + review queue); api client + types; 33-locale i18n

### Testing
- 40 new backend tests (foundations, MusicBrainz, lookup routes, submit
credit gate, search worker auto/park + credit math, progress) + frontend
Jest for the default-selection and credit-gate helpers
- Safe production E2E smoke
(`frontend/e2e/production/bulk-mode.spec.ts`) — read-only lookups + gate
rejection, does not spawn real jobs
- Full backend suite green (3588 passed); frontend typechecks clean (no
new errors)

### Deploy notes
- **Requires `pulumi up`** to create the `bulk-search-job` Cloud Run Job
before submit works in prod.
- Design + plan: `docs/archive/2026-06-18-bulk-mode-design.md`,
`-plan.md`

Docs: `docs/API.md` § Bulk Mode, `docs/LESSONS-LEARNED.md`.

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

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 16:18:02 +00:00
Andrew Beveridge ☄️andClaude Opus 4.8 715c796bfb fix(dr): correct backup freshness monitor limit + scheduler deadline (weekly-S3 Firestore regressions) (#844)
## Summary

Fixes two DR-backup alerting regressions introduced by PR #823 (Jun-14
cost reduction), which switched the Firestore S3 upload from **nightly →
weekly (Sundays)** to cut cross-cloud egress. Both surfaced as Discord
alerts on 2026-06-17/18; backups themselves were never actually broken.

### 1. False "🚨 DR backup is stale" alert (fires every Tue–Sat)
The off-platform freshness monitor (`dr-backup-freshness.yml`) checks
the **S3** copy of `firestore/` against a **36h** limit — set back when
Firestore uploaded to S3 nightly. Since #823, Firestore ships to S3 only
weekly (like BigQuery, which correctly uses 192h), so the S3 copy is
>36h old from Tuesday onward **by design**.

Monitor run history confirms: 06-14 Sun ✅ → 06-15 Mon ✅ (~34h) → 06-16
Tue ❌ → 06-17 Wed ❌, repeating weekly.

**Fix:** Firestore limit `36h → 192h` (≈8 days), matching its actual
weekly off-site cadence. The nightly GCS-staging export (1-day local
restore point) is unaffected.

### 2. Spurious "Path already exists" FAILED backup report
Cloud Scheduler had no `attempt_deadline` (default **180s**), but the
Firestore export runs for minutes. Scheduler timed out the HTTP call and
retried (`retry_count=2`) while the original invocation kept running to
success; the retry then collided on the already-created
`firestore/<date>/` export path → `400 Path already exists`.

**Fix:** set `attempt_deadline="1800s"` (Cloud Scheduler max) and align
the Cloud **Function** `timeout_seconds` 3600 → 1800, so the function
can't outrun the scheduler's wait and reopen the same collision window
(per CodeRabbit).

Also refreshes `docs/DISASTER-RECOVERY.md`: Firestore off-site RPO is 7
days (S3) / 24h local (GCS), and the freshness-monitor section now
documents the per-prefix S3 cadence so this can't regress again.

## Changes
- `.github/workflows/dr-backup-freshness.yml` — Firestore freshness
limit 36h → 192h + explanatory comment
- `infrastructure/modules/backup.py` — scheduler
`attempt_deadline="1800s"`; function `timeout_seconds` 3600 → 1800
- `docs/DISASTER-RECOVERY.md` — RPO table + freshness-monitor cadence
docs

## Testing
- Backup function unit tests: 13 passed (no function code changed)
- YAML + embedded-Python + Pulumi module all validate/compile
- CodeRabbit: 0 findings (1 major fixed: function/scheduler timeout
mismatch)
- **`pulumi up` applied to prod** (clean diff: 2 updated, 265
unchanged). Verified live: scheduler `attemptDeadline=1800s`, function
`timeoutSeconds=1800`. Merging keeps IaC in sync (CI re-applies as
no-op).

Infra/CI + docs only; no application code (no version bump).

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 02:33:44 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 23ebee4657 fix(backfill): correct date filter, private-track path, and folder guard (#843)
## Summary
Follow-up to #842. Operational correctness fixes to
`backend/scripts/backfill_original_audio.py`, found while running the
original-audio backfill against production (**344 jobs restored, 0
errors**). As merged, the script silently did nothing and would have
mis-routed private tracks.

## Changes
- **Date filter:** `created_at` is stored as an ISO **string** in
Firestore, so the server-side `created_after`/`created_before` datetime
filters matched nothing ("Considering 0 jobs"). Now fetches completed
jobs (ordered desc) and filters the date window in Python; default fetch
limit raised to 5000 to bound the lookback.
- **Private-track path:** uses `get_effective_distribution_for_job()`
for the Dropbox path, so private (`NOMADNP`) tracks resolve to the
**NonPublished** path instead of the job's stored public `dropbox_path`
(was skipping 130+ private tracks as "folder missing").
- **Folder guard:** only uploads into a track folder that **already
exists** (new `skip-folder-missing`), so drifted brand/artist/title
naming can't create an orphan folder with a lone FLAC.
- **Env filter:** filters environment in Python (avoids needing a
3-field composite Firestore index); `--env` now defaults to none (test
jobs skip naturally — no brand/Dropbox folder).
- **Resilience:** per-job planning errors are counted, not fatal.

## Testing
- [x] 8 planner unit tests pass (`test_backfill_original_audio.py`),
incl. new `skip-folder-missing` case
- [x] Proven end-to-end in production: 344 original-audio files restored
to the correct public/private Dropbox folders, idempotent re-run
confirmed (already-present skipped, transient errors retried clean)

## Review
- [x] Validated by actually executing against prod; script-only change,
no runtime/service impact

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 20:47:36 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 113197293b fix: restore missing (Title/End).mov + original audio in Dropbox folders (#842)
## Summary
- Organised Dropbox track folders stopped containing the 5-second screen
videos (`(Title).mov`/`(End).mov`) and the original input audio
(`(flacfetch).flac` / `(uploaded).mp3`). Root cause:
`_upload_to_dropbox` uploads the whole `output_dir`, and the
monolith→distributed-GCE migration quietly narrowed what lands there.
- Restores both file types for new jobs, adds an audio-only backfill for
past jobs, and adds a daily-E2E guard so this regression class is caught
automatically.
- Bundles a CLI fix for an ffmpeg interactive-prompt hang in
`--finalise-only` (found while regenerating the missing files locally).

## Changes
**Screen `.mov`s (forward):** GCE encoder copies its generated
`title/end.mov` into `outputs/` with canonical names → plumbed via
`EncodingOutput.title_mov_path`/`end_mov_path`, the `GCEEncodingBackend`
filename mapping, and `_download_gce_encoded_files` back into
`output_dir`.

**Original audio (forward):** new `backend/services/original_audio.py`
(source tag `(uploaded)`/`(flacfetch)`/`(YouTube)` + GCS path +
filename); orchestrator `_stage_original_audio_for_upload()` fetches it
into `output_dir` before folder uploads (non-fatal, only when a folder
upload will occur).

**Backfill (audio only):** `backend/scripts/backfill_original_audio.py`
— dry-run by default, `--live` to upload, skips when audio is gone from
GCS or already present. `.mov` can't be backfilled (needs re-encode).
Adds `DropboxService.file_exists` (re-raises non-not-found `ApiError`).

**Daily E2E guard:** `audio_download_worker` records original audio in
`file_urls['input']['audio']`; `_upload_results` registers
`title_mov`/`end_mov` under `file_urls['finals']`;
`happy-path-real-user.spec.ts` STEP 10.5 asserts the admin files
manifest contains `finals/title_mov`, `finals/end_mov`, `input/audio`,
`finals/lossless_4k_mp4`.

**CLI ffmpeg-hang fix:** `karaoke_finalise` only added `-y` in
non-interactive mode, so a pre-existing output made ffmpeg block on an
invisible `Overwrite? [y/N]` prompt until the 600s timeout (silently
aborting at step 2/6). `-y` is now unconditional +
`stdin=subprocess.DEVNULL` on all ffmpeg `subprocess.run` calls.

## Testing
- [x] 38 new/updated unit tests; all affected suites green
(`encoding_interface`, `video_worker_orchestrator`,
`gce_encoding_worker`, `original_audio`, `backfill_original_audio`,
`dropbox_service`, `upload_results_screen_movs`,
`audio_download_worker`, full `karaoke_finalise` suite)
- [x] Full backend suite: +38 passing vs main, 0 new failures (12
pre-existing `asyncio.get_event_loop()` ordering failures on main,
unrelated)
- [x] Output-file completeness now verified by the daily GHA E2E (STEP
10.5)

## Review
- [x] Local CodeRabbit review completed (scoped to this branch) — 1
major finding fixed (`file_exists` masking non-not-found errors),
re-review clean (0 findings)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 17:11:24 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 b6dcf6602d feat: match-judge improvements — parallel tidy + hard gate, two-way toggle, weak-tier AI verify, preview perf (#841)
## Summary

Four follow-ups to the artist/title **match judge** (shipped in
v0.184.1), per
`docs/archive/2026-06-16-match-judge-improvements-prompt.md`:

### 1. Race fix — parallel tidy + hard gate
The judge previously ran only *after* the audio search resolved, leaving
a window where a user could select audio with un-tidied metadata (or
have a late verdict clobber their pick).
- Split into a **`fast`** catalog-only pass (fired on mount, parallel
with the audio search) and a **`full`** pass (with the tier, may use
AI). New `stage` field + `needs_ai` marker on
`/api/catalog/match-judge`.
- **Hard-gate** all audio-selection buttons until the judge settles,
with a subtle "Checking song details…" indicator. A 12s safety timeout
guarantees release. Impossible to reach Step 3 with un-tidied metadata
in the normal flow.

### 2. Two-way tidy/correction toggle
The notice now switches **both directions** — canonical ⇄ what-you-typed
— instead of a one-way undo. The current value is always clear.

### 3. Title-screen preview performance
`TitleCardPreview` + `KaraokeBackgroundPreview` rendered a 3840×2160
(4K) canvas and loaded a 2.7 MB 4K PNG for a small thumbnail.
- Render at preview resolution (960×540, dpr-aware) via a scale
transform.
- Low-res background assets (~540 KB) for the preview; 4K stays for the
real render path.
- Preload backgrounds at Step 2; show a loading spinner.

### 4. Catalog-match trust — verify weak matches with AI
A confident catalog match could land on a junk/misspelled Spotify entry
(prod: `Queen / Bohemian Rapsody` → wrongly "already canonical"). Now,
when audio results are weak (tier 3), the AI judge verifies the catalog
match and can override. Extra cost (~$0.0003/call) only on weak-result
cases.

## Testing
- **Backend:** new unit tests for `fast`/`full` staging, `needs_ai`,
weak-tier AI override + keep-catalog-on-unconfident/failure/disabled;
route tests for `stage` forwarding. Full suite green (3510 passed).
- **Frontend:** Jest coverage for fast-on-mount, gate disable→enable,
12s timeout release, full-pass-only-when-needed, two-way toggle;
`TitleCardPreview` preview-resolution canvas + low-res bg + spinner.
Full unit suite green (1024 passed).
- `make test` green; `tsc` introduces zero net-new errors; ESLint clean.

## i18n
6 new keys (`matchUsingTyped`, `matchUseTidied`, `matchUseCorrection`,
`matchChecking`, `titleCardPreview.loading`,
`karaokeBackgroundPreview.loading`) translated to all 32 locales.

## Notes
Preserves all "constraints from history": no Step-1 autocomplete,
cosmetic never restarts the audio search, deferred job creation, public
brand rule, audio-before-customize ordering.

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

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 02:15:43 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 a0b94f95a2 fix(encoding): pin in-flight render polls to the submission worker (#840)
## Problem

A blue-green encoding-worker deploy that swaps the Firestore primary
pointer (`active_url`) **mid-render** caused in-flight status polls to
migrate from the worker actually encoding the job to the just-swapped
new primary, which returns 404 `Encoding job <ID> not found`. After 5
consecutive poll failures the render was failed — even though the
original worker finished the encode fine.

**Incident 2026-06-16, job `d3af33ae`** (error-monitor alert). Confirmed
from logs + Firestore:
- 04:31:39 render submitted to worker-a; encoding begins
- 04:33:46.985 deploy swaps `primary_vm` worker-a → worker-b
(`last_swap_at`)
- 04:33:53–04:34:33 polls hit worker-b (never had the job) → 404 ×5 →
render failed
- worker-a was alive and finished the encode the whole time; user
retried 12 min later and it succeeded

The 4 poll failures happened **before** worker-a was stopped (04:34:33),
proving the orphaning is at the **poll layer** — the 2026-06-15 drain
fix (which keeps the old VM alive) can't catch it.

## Fix

Pin in-flight polls to the worker that accepted the job — the poll
follows the job, not the floating primary pointer.

- `_request_with_retry(..., allow_failover=True)` — gates the
fallback-VM warmup + URL re-resolution (default `True` keeps capacity
fallback unchanged).
- `get_job_status(job_id, worker_url=None)` — pinned polls target the
given worker with `allow_failover=False` (never re-route / never spin up
a fallback VM — a fresh VM can't have the in-flight job).
- `wait_for_completion(..., worker_url=None)` — threads the pinned URL
into every poll.
- `render_video_on_gce` / `encode_videos` / `encode_preview_video` —
capture the worker URL **after** submit (reflects a capacity-fallback
re-route, precedes any later swap) and pin the wait to it.

URL re-resolution stays correct for capacity fallback (dead primary,
fresh submission); it's only suppressed for in-flight polls.

## Tests

New `TestWorkerUrlPinning` in `test_encoding_service.py`, including an
**end-to-end swap regression** where `active_url` has swapped to a
404'ing worker and the render still completes by polling the submission
worker (fails before the fix, passes after). Plus pinned-vs-active
resolution, failover suppression, and poll threading.

`391 passed` across encoding / render-worker / review suites. No
regressions.

## Docs / version
- `docs/LESSONS-LEARNED.md` + `docs/TROUBLESHOOTING.md` (runbook note) +
plan doc in `docs/archive/`
- version `0.184.1 → 0.184.2`

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 01:53:23 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 654e331dd4 docs: match-judge improvements prompt doc (next session) (#839)
Prompt doc for a fresh session to implement 4 match-judge follow-ups
(decisions already captured from Andrew):

1. **Race** — tidy in parallel with audio search + hard-gate 'Use This
Audio' until both search & judge resolve.
2. **Reversible 'keep what I typed'** — two-way toggle showing both
values.
3. **Title-screen preview perf** — render at display res, low-res bg,
preload at step 2, spinner.
4. **Catalog trust** — when audio results are weak (tier 3), run the AI
even if the catalog 'matched' (fixes junk Spotify entries
short-circuiting the judge).

Docs-only, no version bump.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 04:27:19 +00:00
Andrew Beveridge ☄️andClaude Opus 4.8 4a550c34cd fix(match-judge): raise AI timeout to fix Vertex 504 DEADLINE_EXCEEDED (#838)
Bumps the match-judge AI timeout from 3s to 12s.

Prod verification of #836 confirmed the endpoint works (cosmetic tidy +
catalog canonical correct, graceful fallback, no crashes), but the AI
judge layer was failing with **504 DEADLINE_EXCEEDED** —
`gemini-3.5-flash` could not finish generation within the 3s deadline.
The model id is valid; the timeout was just too tight.

Fix: `MATCH_JUDGE_TIMEOUT_MS` default 3000 -> 12000ms. Still bounded and
off the critical path (the call degrades to a `none` verdict on
timeout); for comparison the auto_correct service uses 120s.

Verified locally: backend match-judge tests still green. Will re-verify
the AI path live after deploy.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 23:07:21 +00:00
Andrew Beveridge ☄️andClaude Opus 4.8 ffa9558db5 feat: artist/title match-judge — auto-tidy formatting, replace 'database' panel (#836)
## Summary

Reworks the **artist/title matching, suggestions & auto-correction** on
Step 2 of the Create Karaoke Video flow. The confusing green **"Song
found in our database"** panel is gone; formatting is now tidied
intelligently and (mostly) invisibly.

Driven by a new backend **match judge**: a deterministic normalizer +
the karaoke-decide catalog run first, and a light Vertex Gemini model
(`gemini-3.5-flash`) is consulted **only** when those aren't confident.

### Behaviour (Step 2)
- **Cosmetic** fix (casing/punctuation/diacritics, same song) → applied
**silently**, with a quiet *"Tidied to X · keep what I typed"* line.
**Never** re-runs the audio search.
- **Confident content** fix (e.g. `Yesteray → Yesterday`) → applied with
a *"Corrected to X · Undo"* line, and re-runs the audio search **only
when the original results were weak** (tier 3).
- **Ambiguous** → ask-first *"Did you mean…?"* prompt before changing
anything.
- **None** → no change.

Resilient by design: the judge never blocks job creation — on
timeout/error it returns `none`. Kill switch:
`MATCH_JUDGE_ENABLED=false` (deterministic + catalog still run).

## Why
The catalog panel existed only to nudge official formatting (quality bar
for published tracks), but read like "we already have this karaoke
video." User feedback flagged it as confusing. This preserves the
formatting-hygiene benefit while removing the friction/confusion. Design
+ history review in
`docs/archive/2026-06-15-artist-title-matching-rework-plan.md`.

## Preserved (hard-won lessons honoured)
- No Step-1 autocomplete; suggestions stay on Step 2.
- Cosmetic correction never restarts the audio search (existing
`onArtistTitleCorrection` no-restart path reused).
- Deferred job-creation / search-session pattern untouched.
- `stringSimilarity`/`findFuzzyMatches` kept as pure utils (existing
tests green).
- No changes to step structure, visibility/customize ordering, or the
public-style brand rule.

## Changes
- **Backend**: `backend/services/match_judge/` (classifier → AI judge →
orchestration), `POST /api/catalog/match-judge`, config
(`MATCH_JUDGE_ENABLED`/`MATCH_JUDGE_MODEL`/`MATCH_JUDGE_TIMEOUT_MS`).
- **Frontend**: `api.matchJudge`, Step 2 rewired, green panel removed,
new `MatchNotice` component; 5 `jobFlow` i18n keys across all 33
locales.
- **Docs**: API.md endpoint section + design/plan doc. Version →
0.183.0.

## Testing
- Full suite green: backend (unit + integration + emulator, coverage
gate passed) + **1008 frontend tests** + e2e.
- New: 20 backend tests (classifier, AI mapping, orchestration,
endpoint) + updated `AudioSourceStep` tests (cosmetic tidy, ambiguous
ask, none, failure-silent) + preserved fuzzy-matching tests.
- CodeRabbit: 1 finding fixed (Literal types), 1 false positive.

## Follow-ups (separate PRs)
- Title-screen preview perf (4K canvas/bg → low-res + preload +
spinner).

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 18:02:23 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 2002b5eddf ci(tenant-e2e): move daily run to ~8pm US Eastern (#837)
## Summary
- Moves the tenant-portal daily E2E from **07:37 UTC** (~3:37am ET) to
**00:07 UTC** (~8pm US Eastern — 8:07pm EDT / 7:07pm EST), so the soak
runs land in the evening when they can be watched / manually tested
alongside.
- Cron is fixed-UTC, so the local time shifts 1h across DST (noted in
the comment). Minute kept off the :00 mark.

CI-config only (one-line cron change).

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 21:49:35 +00:00
Andrew Beveridge ☄️andClaude Opus 4.8 814ac50aca fix(encoder): fail-safe the active-jobs guards so a busy VM isn't stopped mid-render (#835)
## Summary
- The GCE encoder VMs have two stop paths that guard against killing a
busy worker by checking `/health`'s `active_jobs` — but **both fail
OPEN**, treating an unreachable/slow `/health` as "0 active jobs" and
stopping the VM anyway.
- Under load a busy encoder runs a 4K ffmpeg on all 32 cores and shares
uvicorn with the encode, so `/health` can miss its window *while the VM
is hard at work*. Combined with blue/green deploy churn (every merge
cycles the VMs) + the 5-min idle check, this stopped VMs **mid-render**,
orphaning the in-memory job → backend polls got 404 → "lost contact with
worker ... not found".
- **Incident 2026-06-15:** 12 occurrences, all self-inflicted by rapid
PR merges (#831–#834) during the tenant E2E retries; **0 in the prior
48h**. Not tenant-specific; affects consumer renders too in the same
deploy/idle-during-render window.

## Changes
- **`infrastructure/functions/encoding_worker_idle/main.py`** —
`check_active_jobs()` now returns `None` (not `0`) on any failure, with
3 retries. The idle loop keeps a VM alive for the cycle when the count
is unconfirmed or the VM has no reachable IP; it only stops on a
**confirmed** `active_jobs == 0`. A genuinely idle VM answers `/health`
fast and is still reclaimed next run.
- **`.github/workflows/ci.yml`** ("Drain and stop old primary") — new
`probe_active_jobs` helper distinguishes a real integer from
`"unknown"`; the drain loop only stops on a definitive `0`, or after a
bounded **20-min** timeout (was 10) so a render finishes comfortably
while a wedged worker still can't block the deploy forever. Dropped an
unused `API_KEY` fetch.
- **`docs/LESSONS-LEARNED.md`** — "Is It Busy?" guards must fail safe,
not fail open.

## Testing
- [x] Idle-shutdown unit tests pass (24, incl. new fail-safe cases +
direct `check_active_jobs` contract tests)
- [x] Bash `probe_active_jobs` classification unit-checked (curl-fail /
missing-field / garbage → `unknown`; only real int → number)
- [x] `ci.yml` YAML + actionlint clean (no new findings in the changed
step)
- [x] CodeRabbit CLI review: 0 findings
- No backend/frontend wheel code changed → no version bump (avoids an
unnecessary encoder redeploy)

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

## Deploy note
The idle Cloud Function deploys via Pulumi (`infrastructure/`); the
`ci.yml` change takes effect on the next workflow run. Per repo
convention, run `pulumi up` locally before merging.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 17:03:04 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 21e8a05c61 test(tenant): retry daily E2E once on transient encoder failure (#834)
@coderabbitai ignore

The shared GCE encoder intermittently drops a job mid-encode ("lost
contact with worker ... not found") — a pre-existing,
**non-tenant-specific** transient (it hit the daily E2E twice but not
the manual runs; both tenants complete when the encoder cooperates). The
daily health check now detects that specific error and retries the whole
job once, so it doesn't false-alarm on encoder flakiness. Other failures
still fail immediately. Test-script only.

Separately worth a look (out of scope here): the encoder "lost contact /
job not found" reliability affects consumer renders too.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 10:28:58 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 460f18d47d fix(ci): run tenant E2E matrix sequentially (#833)
@coderabbitai ignore

The daily tenant E2E ran both tenants concurrently and overwhelmed the
single shared GCE encoder ("Encoding job lost contact with worker... not
found"). Both tenants pass individually (verified). Serialize the matrix
(`max-parallel: 1`) so the daily run doesn't self-inflict encoder
contention. CI-config only.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 09:58:49 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 defaf85230 fix(ci): tenant E2E workflow — drop invalid matrix-context job 'if' (#832)
@coderabbitai ignore

The daily tenant E2E workflow used the `matrix` context in a job-level
`if`, which GitHub Actions rejects ("Unrecognized named-value:
'matrix'") — so the workflow (incl. the scheduled run) failed to parse.
Removed the per-tenant dispatch filter; the workflow always runs both
tenants (the intended daily behavior). `workflow_dispatch` takes no
inputs.

CI/workflow-config only.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 09:47:37 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 1218337346 test(tenant): daily E2E asserts portal downloads via file_urls (#831)
@coderabbitai ignore

The daily tenant E2E asserted on `job.download_urls` (backed by
`output_files`, which the orchestrator pipeline never populates), so it
failed even on fully-successful jobs. The `OutputLinks` UI reads
`job.file_urls` (finals/packages) — assert that instead.

Confirmed in prod: **both vocalstar and singa pass the full E2E** — job
completes, Dropbox link present, no YouTube, and all downloads available
(4K / 720p / with-vocals MP4 + CDG + TXT). Doc updated with the final
outcome.

Test/docs only — no production code change.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 09:44:40 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 6fe01f2d6f fix(tenant): stage instrumental under the name the GCE encoder globs for (#830)
@coderabbitai ignore

Third and decisive iteration on the GCE encode of existing-instrumental
(tenant) jobs.

#828/#829 staged the instrumental but under names the **running**
encoder doesn't look for. The live encoder VM (`encoding-worker-b`)
boots the **2026-01-23 image**, whose `custom` instrumental branch globs
only for `*custom_instrumental*.{flac,mp3}` / `*Instrumental Custom*` —
**not** `*existing_instrumental*` / `*Instrumental User*` (those
patterns were added 2026-03-04, after the image). Tenant jobs run with
`instrumental_selection='custom'`, so they hit that branch and failed
"No instrumental audio found".

**Fix:** in the orchestrator's `_run_encoding`, server-side copy the
supplied instrumental from `uploads/{job}/audio/existing_instrumental.*`
→ `jobs/{job}/custom_instrumental.<ext>` — a name the encoder's `custom`
branch finds — sourced from the authoritative GCS object (no local-temp
dependency). Image-agnostic and verified against the old image's actual
glob patterns.

> The encoder VM is also 5 months stale (boots a
pre-existing-instrumental image). Recreating the `encoding-worker` VMs
from the image family's newest image is a worthwhile separate Pulumi
pass, but this fix unblocks tenant jobs on the current VM.

Validated by re-running the full prod E2E to completion after deploy.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 08:37:16 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 66dcfd7d19 fix(tenant): stage instrumental in the orchestrator encode path (#829)
@coderabbitai ignore

Follow-up to #828. That PR staged the instrumental in `_encode_via_gce`
(legacy `video_worker.py`), but production jobs run the **orchestrator**
pipeline (`video_worker_orchestrator.py`), whose `_run_encoding` builds
its own `EncodingInput` and never made the user-supplied instrumental
available under `jobs/{job_id}/`. Tenant jobs still failed at the GCE
encoder with "No instrumental audio found" (confirmed — the "Staged
existing instrumental" log never appeared).

**Fix:** in the orchestrator's `_run_encoding`, when using the GCE
backend, upload the local instrumental (existing/custom — identified by
the `(Instrumental User)` / `(Instrumental Custom)` filename) into
`jobs/{job_id}/` so the encoder's recursive `find_file` locates it.
Consumer `clean`/`backing` jobs are untouched (their stems already live
under `jobs/{job_id}/`).

Also: the daily E2E uses a tenant-specific title so the two matrix
tenants don't share a `base_name` (the GCE encoder caches by base_name).

Validated by re-running the full prod E2E to completion after deploy.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 07:44:17 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 40c7960854 fix(tenant): stage instrumental for the GCE encoder + daily tenant E2E (#828)
@coderabbitai ignore

## Final render blocker (bug #8)

With #824/#825/#826/#827, tenant jobs now render the karaoke video — but
the GCE encoder failed with **"No instrumental audio found"**.

**Root cause:** the user-supplied instrumental lives under
`uploads/{job}/audio/`, but the encoder only pulls input from
`jobs/{job}/` (`input_gcs_path`) and locates the instrumental via
`find_file("*existing_instrumental*", "*Instrumental User*")`. On top of
that, the running encoder VM (`encoding-worker-b`) boots a **2026-01-23
image** that predates the encoder's own `existing_instrumental`
config-download path (added 2026-03-04), so it could never fetch it from
`uploads/` either.

**Fix (image-agnostic — no risky shared-VM recreation, no consumer
impact):** `_encode_via_gce` server-side copies the instrumental into
`jobs/{job_id}/existing_instrumental.<ext>` before submitting. The
encoder downloads `jobs/{job}/` and its **recursive** `find_file` then
locates it on any image version. Added `StorageService.copy_blob` + unit
test.

> Note: the stale encoder VM image is a separate infra item — the
`encoding-worker` VMs should be recreated from the image family's newest
image (which has 3 months of encoder fixes). Tracked for a Pulumi pass;
not required for this fix.

## Daily tenant E2E (second ask)
- `scripts/e2e/tenant_e2e.py` — full per-tenant prod health check:
submit → approve review → render → assert (completes, Dropbox link
present, no YouTube, downloads available) → clean up job + uploads.
- `.github/workflows/e2e-tenant-daily.yml` — daily matrix (vocalstar,
singa), WIF auth, Discord + email on failure.
- `docs/archive/2026-06-15-tenant-portals-e2e.md` — the full story (8
bugs, all fixed).

## Testing
- `copy_blob` unit test; storage suite green (20).
- Full tenant E2E re-run to completion after deploy.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 06:49:46 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 d6bd2f1787 fix(tenant): complete the render for jobs that supply their own instrumental (#827)
@coderabbitai ignore

## Two final render blockers (found by the Vocal Star E2E)

With attribution (#824), the audio slot (#825), and transcription
padding (#826) fixed, the first real tenant job advanced through
transcription → screens → review → render, surfacing the last two
never-exercised issues:

### 1. Render prerequisites — "No instrumental selected"
existing-instrumental jobs (every tenant submission) have no
instrumental-selection UI step, so `instrumental_selection` was never
written to state_data. The video orchestrator then defaults to `'clean'`
(a separated stem that was never produced for these jobs), and
`_validate_prerequisites` rejects the job, leaving it stuck retrying.

**Fix:** `complete-review` now defaults `instrumental_selection` to
`'custom'` (use the provided instrumental) when
`existing_instrumental_gcs_path` is set. An explicit request value still
wins. The render path already supports `'custom'`.

### 2. Theme asset paths (reproducibility)
The tenant setup scripts wrote full `gs://bucket/themes/.../assets/X`
URLs, but `theme_service._build_style_assets_mapping` only resolves bare
basenames (the consumer convention). With `gs://` URLs, `style_assets`
came back empty → assets never downloaded → encoder failed with "Video
background image not found". Scripts now emit basenames, and add the
newly-required `extra_text_text_transform` field the strict theme
validator expects.

(The two live GCS themes — vocalstar, singa — were corrected out-of-band
to match.)

## Testing
- New regression tests: complete-review defaults to `custom` for
existing-instrumental jobs; explicit selection still wins.
- Review suites green (102). Full E2E re-run to completion after deploy.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 05:34:20 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 c94a5b8754 fix(audioshake): remux user audio with leading null padding before transcription (#826)
@coderabbitai ignore

## Problem (found by the real Vocal Star E2E)

After #824/#825, the first real Vocal Star job reached transcription but
**AudioShake rejected the asset**: `400 ... "Error fetching or
processing asset"`.

Root cause: the supplied MP3 — and **Vocal Star's entire bulk batch** —
begins with ~731 leading `0x00` bytes before the first ID3/MPEG frame.
`ffmpeg`/`ffprobe` tolerate it (the audio decodes fine), but
AudioShake's asset processing does not.

Consumer jobs never hit this because their audio is re-encoded into
clean stems by the separator before transcription. Tenant /
existing-instrumental jobs upload the user's **raw** file straight to
AudioShake.

## Fix
`AudioUploadOptimizer.prepare_for_upload` now detects leading null
padding on padding-prone compressed formats (`.mp3/.aac/.mp4a` — **not**
container formats like `.mp4/.mov`, which legitimately start with a null
box-size prefix) and **losslessly remuxes** (`ffmpeg -c copy`, no
re-encode) before upload.

## Verified against the real AudioShake API
- padded file → `create_task` **400** ("Error fetching or processing
asset")
- remuxed file (same upload path) → `create_task` **200** ✓

Regression tests added (detection + routing + container-format safety).

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 04:12:22 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 829ff02bdb fix(tenant): transcribe the mixed audio, not the supplied instrumental (#825)
@coderabbitai ignore

## Problem (found by the first real tenant E2E)

After #824 made tenant jobs attribute correctly, the first real Vocal
Star job **failed at transcription**: `Lyrics transcription failed: 400
... audioshake.ai/tasks`. Firestore showed `input_media_gcs_path`
pointing at `existing_instrumental.mp3` — transcription was running on
the **instrumental**, not the vocals.

**Root cause:** in the `existing_instrumental` flow (every tenant
submission), the mixed audio and the instrumental are uploaded into the
**same** `uploads/{job_id}/audio/` directory:
- mixed → `audio/<filename>`
- instrumental → `audio/existing_instrumental.*`

On `uploads-complete`, resolving the `'audio'` slot listed the whole
`audio/` dir and took `files[0]` — which sorts to
`existing_instrumental.mp3` (`e` < most letters). So the instrumental
became the transcription input.

This was a **latent bug never hit in prod** because no
existing-instrumental job had ever run end-to-end (0 tenant jobs ever,
per #824).

## Fix
Extract `_select_mixed_audio_files()` to exclude the
existing-instrumental file when selecting the `'audio'` (mixed,
with-vocals) input. Regression tests added (incl. real filenames).

## Testing
- New regression tests + `test_file_upload.py`/`test_upload_api.py`
green (156).
- Re-running the real Vocal Star E2E to completion after this deploys.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 03:22:53 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 fea6ebec1a fix(tenant): make white-label B2B portals attribute jobs to the tenant (Vocal Star + Singa) (#824)
@coderabbitai ignore

## Problem

The white-label tenant portals (`vocalstar.nomadkaraoke.com`,
`singa.nomadkaraoke.com`) looked "done" but **had never worked
end-to-end**: 0 of the last 484 production jobs carried a `tenant_id`.
No tenant job had ever run.

**Root cause:** the frontend API client never sent the `X-Tenant-ID`
header. Tenant portals call the shared `api.nomadkaraoke.com`, whose
Host isn't the tenant subdomain, and the `?tenant=` query param is
disabled in prod — so the backend could never detect the tenant. Every
tenant sign-in and job submission silently fell back to consumer
behavior (default theme, no tenant Dropbox, etc.). The
`getTenantHeaders()` helper existed and was unit-tested, but was never
wired into requests.

## Changes

**Frontend** (`lib/api.ts`, `lib/tenant.ts`)
- Attach `X-Tenant-ID` on all authenticated requests **and** the
magic-link request, sourced from `window.__TENANT_CONFIG__`
(edge-injected by the Cloudflare function; mirrored from the tenant
store for dev/preview). Consumer build resolves no tenant → no header →
**behavior unchanged**.

**Backend** (`_apply_tenant_overrides` in `file_upload.py`)
- Make tenant config **authoritative** over global distribution
defaults. Prod sets `DEFAULT_DROPBOX_PATH` / `DEFAULT_GDRIVE_FOLDER_ID`
/ `DEFAULT_BRAND_PREFIX` globally; these seed `dist`, and the old "fill
only when unset" overlay let them leak — so every tenant job would have
landed in the **shared consumer Dropbox folder** and uploaded to the
**global Google Drive**. Now Dropbox/GDrive routing is gated by the
tenant feature flags and cleared when disabled.

**Tenant configs** (GCS + setup scripts, Vocal Star + Singa)
- Disable Google Drive (`gdrive_upload=false`, `gdrive_folder_id=null`),
keep YouTube off, enable Dropbox to each tenant's own folder. B2B =
locked theme, no YouTube/GDrive, Dropbox + portal download only.

## Why it's consumer-safe
- Frontend: header only attached when a tenant is resolved (never on
`gen.nomadkaraoke.com`).
- Backend: `_apply_tenant_overrides` early-returns when `tenant_config
is None` (all consumer jobs).

## Testing
- New: frontend header-attachment tests (tenant build vs consumer);
backend authoritative-override + feature-flag-gating regression guards
(incl. the global-default-leak case).
- Full suites green: **3466 backend**, **1013 frontend**.
- Verified live tenant configs via API after update.

Manual prod E2E (real track through each portal) + a daily per-tenant
E2E workflow follow in a second PR, once this deploys and is verified in
prod.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 02:40:08 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 fd331a643f infra: GCP cost reductions (artifact cleanup, NAT egress, weekly backup) (#823)
Part of the June 2026 cost-reduction effort
(`docs/archive/2026-06-14-gcp-cost-reduction-plan.md`). Targets the
post-credit-expiry (2026-09-19) bill.

## Changes
- **Item 4 — Artifact Registry cleanup** (~$6/mo + caps growth): keep 10
most-recent versions + delete untagged digests >7d, on all 3 repos
(karaoke-repo, karaoke-backend-gpu, audio-separator; 92 GiB, previously
no policy). In-place update.
- **Item 5 — NAT egress** (~$26/mo): ephemeral GHA runners now always
get an external IP, so egress bypasses the Cloud NAT data-processing
charge (runners were the NAT's only user; us-central1 IN_USE_ADDRESSES
quota is 69, usage 1).
- **Item 6 — backup cadence** (~$15/mo): Firestore export stays nightly
to GCS (1-day local restore point) but uploads to S3 only on Sundays
(1-week off-site RPO) — Firestore is the bulk of the cross-cloud egress.
Staging keeps only the latest export so the weekly upload ships exactly
one.
- **Item 1 — encoding disks** (~$35/mo): pinned the 4 worker hyperdisks
to the free baseline (3000 IOPS / 140 MB/s) **live via `gcloud`**, not
IaC — setting it in IaC forces a capacity-risky VM replacement. A code
comment documents this.

## Deploy status
- `pulumi up` (artifact policies + runner function): **applied** locally
(prod, update 751).
- Backup function source: shipped via
`functions/backup_to_aws/deploy.sh` (pulumi doesn't manage the source
zip).
- Encoding disks: tuned live via gcloud.

## Tests
- `backup_to_aws`: 13 pass (added firestore-cleanup + s3-exclude
coverage).
- `runner_manager/ephemeral`: 32 pass (updated external-IP assertion).

Item 7 (fallback disks on-demand) intentionally deferred — reliability
tradeoff not worth ~$20/mo. See plan doc.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-14 17:11:18 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 39fb93653f fix(auto-correct): switch active model from Fable 5 to Opus 4.8 (#822)
## Summary

Claude **Fable 5** (`claude-fable-5`) is no longer available on the
Anthropic API. Verified live against `api.anthropic.com`:

```
404 not_found_error: "Claude Fable 5 is not available. Please use Opus 4.8.
Learn more: https://www.anthropic.com/news/fable-mythos-access"
```

`claude-opus-4-8` responds normally and is the API's own prescribed
replacement. Opus 4.8 was also ≈ Gemini 3.1 Pro in our 30-job offline
eval, so switching to it preserves the two-model compare quality.

## Changes

- **`.github/workflows/ci.yml`** (load-bearing):
`AUTO_CORRECT_MODEL=claude-opus-4-8` and
`AUTO_CORRECT_COMPARE_MODELS=claude-opus-4-8;gemini-3.1-pro-preview`.
Compare mode now runs **Opus 4.8 + Gemini 3.1 Pro** instead of Fable +
Gemini.
- **`scripts/measure_autocorrect_cost.py`**: default models + docstring
example → Opus, so the cost tool measures what prod runs.
- **`docs/API.md`**: example auto-correct response reflects Opus.
- **`pyproject.toml`**: `0.182.1` → `0.182.2`.

## Re-enable path

Fable is **disabled, not deleted** — its pricing entry in `pricing.py`
and all Fable unit tests are intentionally left intact. If access
returns, flip it back by reverting the two env-var values in `ci.yml`.

## Testing

- Auto-correct suite: 73 passed (`backend/tests/services/auto_correct/`
+ `test_proactive_auto_correct.py`).
- Live API probe confirmed Fable 404s and Opus 4.8 works.
- CodeRabbit (uncommitted): 0 findings.

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-13 10:27:58 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 dfdbf60dc5 docs(monitoring): document email-channel verification gap (Pulumi vs Console) (#785)
## Summary

Followup to PR #783. The PR claimed Cloud Monitoring would deliver a
verification email to `andrew@beveridge.uk` automatically after `pulumi
up`. It didn't — the channel sat in `UNVERIFIED` state silently, exactly
as if no channel had been created.

The actual GCP behaviour: the auto-send only fires when a channel is
created through the **Cloud Console**. Channels created through the
**API/Pulumi** require an explicit call to the `:sendVerificationCode`
REST endpoint to trigger the email.

I discovered this when running `getVerificationCode` against the channel
and getting `"Cannot generate a verification code from an unverified
channel."` despite `enabled: true`. The right endpoint is
`sendVerificationCode` (no admin-flow restrictions), which returned `{}`
(success) and the email arrived shortly after.

## Change

Rewrite the "Gotcha" callout in `infrastructure/monitoring/README.md` to
explain this, with a copy-paste-ready curl invocation for triggering the
email after any future `pulumi up` that adds a new email channel.

No code change.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-12 16:03:05 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 9f25ae4c4c feat(divebar): on-demand pipeline refresh trigger (refresh action) (#821)
## Why

A track made via gen.nomadkaraoke.com is uploaded to the Nomad Google
Drive immediately, but the Divebar/GCS community mirror only ingests it
on the nightly schedule (mirror index 2 AM, GCS file sync 3 AM, xref
rebuild 6 AM ET). Until then, kjbox's link flow can't find a mirror copy
and falls back to a YouTube download.

This adds an **on-demand "refresh now"** path so a freshly-published
track can be pulled into the catalog within minutes.

## What

New `refresh` action on the **public `divebar-lookup`** Cloud Function:

- Force-runs the three existing scheduler jobs in pipeline order —
`divebar-mirror-daily` (Drive→BigQuery index, makes the track appear) →
`divebar-sync-vm-daily` (Drive→GCS, fast URL) →
`divebar-xref-rebuild-daily` — via `CloudSchedulerClient.run_job`.
Reuses each job's own OIDC identity/target.
- **Least privilege:** the function SA gets a custom
`divebarSchedulerRunner` role (`cloudscheduler.jobs.run` + `.get`) only
— no new function-invoke or compute perms.
- **Token-gated:** the endpoint is public, so the action requires a
shared bearer token (constant-time compare). The token is read from the
`divebar-refresh-token` Secret Manager secret **at runtime** (not
injected as a secret env var) so the function deploys cleanly before the
secret has a version — it just returns a uniform `403` until one is
added, and picks up rotations without a redeploy. Fails closed.

Consumed by kjbox's new "Refresh catalog" button (kjbox#107).

## Tests

`infrastructure/functions/divebar_lookup/test_main.py` — 8 tests: token
gate (wrong/empty/unconfigured), all-jobs-triggered-in-order,
partial-failure tolerance, dispatch 200/403. All green.

## Deploy status — ✅ applied to prod

Applied locally (provider pinned to prod's 9.22.0 so the apply contained
only these 5 resources — no unrelated provider-upgrade churn): `4
created, 1 updated, 262 unchanged`. Function source rebuilt from the new
zip. Secret version set. Verified live: no/wrong token → 403; valid
token → 200 triggering all three jobs.

**Remaining (kjbox#107):** put the same token in the kjbox device
`config.json` as `divebar_refresh_token`, then deploy kjbox.

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-12 00:53:41 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 cf79da79ab fix: honor "use official formatting" correction on search-created jobs (#820)
## Problem

When a user searches for a song, selects **"Use the official
formatting"** (e.g. picks `Hard-Fi — Hard to Beat` over their typed
`hard-fi - hard to beat`), and creates the job, the job was still named
with their raw lowercase query. The official-formatting selection was
silently discarded.

## Root cause

`create_job_from_search` (`backend/api/routes/jobs.py`) derived the
display name from the **original search query stored in the session**,
not from the corrected `artist`/`title` the frontend sends in the
request body:

```python
session_artist = session.get('artist', body.artist)   # always the raw query
effective_display_artist = body.display_artist or session_artist  # body.artist never used
```

Since the session always has an `artist` key, `body.artist` was only
ever an unreachable fallback. The frontend's "Use official formatting"
click correctly updates its state and sends the corrected values — they
were just ignored server-side.

## Fix

Prefer `body.artist`/`body.title` (the wizard's current,
possibly-corrected values) over the stored query, with an explicit
display override still winning above all. Whitespace-only body values
are stripped and fall back to the stored query so a stray `" "` can't
become the job name. The original query is preserved for
`audio_search_artist`/`audio_search_title` matching metadata.

## Tests

- New regression test: corrected artist/title wins over the session
query (fails on old code: `'hard-fi' == 'Hard-Fi'`).
- New test: whitespace-only body artist/title falls back to the stored
query.
- `test_standalone_search.py`: **33 passed**; broader job
route/api/regression suites: **123 passed**.
- Existing `test_display_overrides_applied_when_provided` still passes
(override precedence intact).

Version bumped `0.181.0 → 0.181.1`.

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-11 22:44:09 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 eccf77a626 fix(audio-editor): always show Trim/Fade buttons, disable off-edge (#819)
## Summary
- The Trim Start/End and Fade In/Out buttons in the input audio editor
were **conditionally rendered** — only visible when the selection
touched the very start or end of the track. A mid-track selection showed
only Cut/Mute/Clear, so users couldn't discover the Fade actions at all.
- Reported on a 9:11 track with a 3:02–3:55 selection: the Fade buttons
(shipped in #813) appeared to be "missing in prod" when they were
actually just hidden by the edge-gating.
- Now all four edge-actions **always render** when a selection exists
but are `disabled` off-edge, with a tooltip hint explaining how to
enable them.

## Changes
- `AudioEditor.tsx`: derive `atStartEdge`/`atEndEdge` (1s tolerance,
matching the server-side `afade` anchoring in
`audio_edit_service.fade_region`); render Trim Start, Fade In, Trim End,
Fade Out always, `disabled` off-edge with context-aware `title`
tooltips.
- 6 new i18n keys (`trimStart/EndSelection`, `trim*/fade*DisabledHint`)
added to `en.json` and translated to all 33 locales.
- New jest test asserting a mid-track selection renders the four buttons
disabled.
- Version bump `0.181.0 → 0.182.0`.

## Testing
- [x] `AudioEditor.test.tsx` — 26/26 pass (incl. new disabled-state
test)
- [x] i18n completeness — 33/33 locales at 100%
- [x] No new `tsc` errors in changed files

## Review
- [x] CodeRabbit CLI review completed locally
- [x] In-scope findings addressed (only i18n loanword nits, consistent
with existing convention)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-11 22:04:44 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 a7bb338703 feat(auto-correct): enable proactive pre-generation (runs on API service) (#818)
## Summary

Enables the proactive pre-generation that PR #816 intended but couldn't
deploy (the lyrics-job `--update-secrets` crashed on Cloud Run secret
aliases). Per the chosen approach, the work now runs **on the API
service** — which already has a working `ANTHROPIC_API_KEY` +
`AUTO_CORRECT_COMPARE_MODELS` — instead of the lyrics job, sidestepping
the secret-alias problem entirely.

## How it works

1. Lyrics worker finishes transcription → after `mark_lyrics_complete`,
fires `WorkerService.trigger_auto_correct(job_id)` — a direct, awaited
HTTP call (no Cloud Tasks / new queue). Best-effort: never blocks or
fails the job.
2. New internal endpoint `POST /api/internal/workers/auto-correct`
(admin auth) runs `process_proactive_auto_correct(job_id)` synchronously
on the service: loads `corrections.json`, runs the multi-model
`suggest()` with default settings (cache-aligned with the UI), caches
it. Gated by `AUTO_CORRECT_PROACTIVE_ENABLED`, 180s timeout, swallows
all errors.
3. `ci.yml`: `AUTO_CORRECT_PROACTIVE_ENABLED=true` added to the
**service** env (deploys cleanly — the broken lyrics-job secret path is
gone).

Result: when a reviewer opens the lyrics UI, the auto-run-on-load
request is an instant cache hit.

## Testing
- Backend: **3462 passing** (emulator excluded), incl. rewritten
`test_proactive_auto_correct.py` covering the service worker (flag
gating, no-references skip, happy path multi-model, error-swallow) and
the lyrics-worker trigger (fires / swallows errors).
- CodeRabbit: trace-context propagation + defensive endpoint guard
applied.

## Notes
- Failure modes unchanged & graceful: flaky AI / out of credits /
timeout → endpoint returns a status, job proceeds; UI falls back to
on-demand generation.
- Version bumped 0.180.0 → 0.181.0.

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-11 19:42:08 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 32dfd9fbdc fix(ci): revert lyrics-transcription-job to image-only deploy (#817)
## Why

PR #816's deploy **failed** at the "Update Cloud Run Jobs" step:

```
ERROR: gcloud crashed (ValueError): Invalid secret path 'projects/nomadkaraoke/secrets/audioshake-api-key' in annotation
```

The `--update-secrets ANTHROPIC_API_KEY=…` I added to
`lyrics-transcription-job` made gcloud re-validate the job's *existing*
secrets, which are stored via Cloud Run **secret aliases**
(`secret-alias-N`) in a format `--update-secrets` rejects. That crash
stranded **lyrics + audio jobs on the previous image** (the API service
deployed fine and is healthy; the video-encoding-job updated fine).

## Fix

Revert the lyrics-job step to **image-only** (proven to work — same form
the video/audio job steps use). This makes deploys succeed and brings
lyrics + audio jobs onto the current image, so prod is consistent again.

Proactive auto-correct ships dormant: the worker's
`_run_proactive_auto_correct()` is gated by
`AUTO_CORRECT_PROACTIVE_ENABLED`, which is unset, so it returns early
(no-op, zero risk). Wiring that env + the Anthropic secret onto the job
via an alias-safe method is a tracked follow-up.

## Testing
- No code change; CI-only. The reverted step matches the working
video-encoding-job step exactly.

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-11 18:48:38 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 364e4ebd5f feat(auto-correct): proactive multi-model suggestions + cost logging + de-AI-ified review UI (#816)
## Summary

Makes AI lyrics auto-correction run **automatically on every job**
(multi-model), so suggestions are cached and ready the moment the
reviewer opens the lyrics UI — plus token/cost instrumentation and a UI
cleanup that removes all "AI"/"model" wording.

Measured cost first (`scripts/measure_autocorrect_cost.py`):
**~$0.13/track** multi-model on normal songs — cheap enough to run
proactively.

## Changes

**Cost instrumentation**
- Capture per-model `usage` from Anthropic + Gemini; log greppable
`auto-correct usage` / `auto-correct cost … total_est_cost_usd=…` lines
from `suggest()`.
- `backend/services/auto_correct/pricing.py` (Anthropic rates
authoritative; Gemini estimated) + `scripts/measure_autocorrect_cost.py`
offline harness.

**Proactive generation (every job)**
- `lyrics_worker._run_proactive_auto_correct()` runs the multi-model
path after `mark_lyrics_complete` (downstream already triggered →
non-blocking), gated by `AUTO_CORRECT_PROACTIVE_ENABLED`, bounded by a
180s timeout, and **swallows every error** — it never blocks or fails
the karaoke job (flaky AI / out of credits / timeout all degrade
gracefully).
- Cache-key aligned with the UI request, so the review page's on-load
call is an instant cache hit (no double spend).
- `ci.yml`: wires `AUTO_CORRECT_*` env + the `anthropic-api-key` secret
onto `lyrics-transcription-job` (same SA as the API service — no IAM
change).

**Review UI**
- Always multi-model (removed the model-selection toggle); button
renamed **"Auto-correct"**; stripped model/consensus/cached attribution
badges; reworded strings to drop "AI"/"model" (translated to all 32
locales).
- Auto-runs once on review load so suggestions are ready without a
click; the button stays for the paste-references-later flow.

## Testing
- Backend: **3460 passed** (`backend/tests/`, emulator excluded) — incl.
new `test_pricing.py` + `test_proactive_auto_correct.py` (gating,
graceful failure, cache alignment).
- Frontend: **1006 jest tests pass**; type-clean; 33-locale key parity
verified.

## Notes / follow-ups
- Proactive activates on the **next deploy** (the lyrics-job env/secret
apply via this PR's ci.yml on merge).
- Left "AI" wording in two *separate* features untouched (different
subsystems): `lyricsReview.agenticMetrics` and
`lyricsReview.modals.correctionAnnotation` — flagged for a separate
decision.
- The production E2E spec's click-to-open flow may want a tweak now that
suggestions auto-run on load.

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-11 18:22:51 -04:00
Andrew Beveridge ☄️andClaude Fable 5 0dd5d404e5 feat: cache AI auto-correct suggestions per job (free re-runs on unmodified lyrics) (#815)
@coderabbitai ignore

Per Andrew: clicking AI Suggest twice on the same unmodified lyrics
shouldn't spend AI tokens twice.

Suggestions are now cached per job in GCS
(`jobs/{job_id}/lyrics/auto_correct_cache/{hash}.json`), keyed on the
exact input — word ids + texts, reference lyrics texts, settings knobs,
and the resolved model list. A repeat run on byte-identical input
returns the previous suggestions instantly with `cached: true` (teal
"cached" badge in the panel) and incurs no LLM cost. Any edit to the
lyrics, references, or settings produces a new key and a fresh run; word
ids in the key guarantee cached suggestions always reference words that
still exist.

Cache reads/writes are strictly best-effort — any storage failure
degrades to a normal uncached run (tested). 7 new backend tests (hit
skips model call, miss writes cache, key stability/sensitivity, payload
round-trip, corrupt entry = miss, storage failure never breaks the
request).

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

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 18:03:44 +00:00
Andrew Beveridge ☄️andClaude Fable 5 5bf8de3730 fix: AI suggestions list overflows panel instead of scrolling (#814)
@coderabbitai ignore

The suggestions list in the auto-correct panel rendered past the panel
border over the content below (screenshot from Andrew on job b9adb5b4
with 39 suggestions). Root cause: the repo's `ScrollArea` Radix root has
no `overflow-hidden`, so `max-h-64` on it never clips the viewport.
Replaced with a plain `max-h-64 overflow-y-auto` div — native scroll,
guaranteed containment.

Test-impact: none (tsc clean, auto-correct suites pass; pure
CSS/structure change).

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

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 17:32:22 +00:00
Andrew Beveridge ☄️andClaude Opus 4.8 a0e61d9e21 feat(audio-editor): add Fade In / Fade Out buttons for selected region (#813)
## Summary

Adds **Fade In** and **Fade Out** action buttons to the audio editor
toolbar so users can ramp the volume of a selected region gracefully
instead of an abrupt hard cut.

**Primary use case:** after trimming a long intro off a song, the track
otherwise begins at full volume at the trim point. Selecting the first
few seconds and clicking **Fade In** makes it come in gracefully.
Likewise **Fade Out** for a trimmed outro.

## UX

The buttons are **edge-gated**, mirroring the existing `Trim Start` /
`Trim End` behaviour:
- **Fade In** appears when the selection starts near the beginning
(`start < 1s`)
- **Fade Out** appears when the selection ends near the end (`end >
duration - 1s`)

This matches the real workflow and `afade`'s semantics (fades only make
sense at clip edges — a mid-clip fade-in would silence everything before
it). Mid-track fades are noted as out-of-scope future work.

## Changes

**Backend** (`audio_edit_service.py`, `review.py`)
- New `fade_region()` using FFmpeg's `afade` filter (lossless FLAC,
duration-preserving).
- **Anchoring + bounds enforced server-side** (not just in the UI): a
fade-in is forced to begin at the clip start and a fade-out to finish at
the clip end, with a 1s tolerance matching the UI gating, so a
non-anchored API request can never silently mute the rest of the track.
- `fade_in` / `fade_out` dispatch in `apply_edit` + added to route
`valid_operations`.

**Frontend** (`AudioEditor.tsx`)
- `handleFadeIn` / `handleFadeOut` + edge-gated toolbar buttons
(`TrendingUp` / `TrendingDown` icons).
- i18n strings added and translated to all 33 locales.

## Testing

- **Backend unit** (`test_audio_edit_service.py`): fade in/out ffmpeg
args, invalid direction, inverted region, **unanchored start/end
rejection**, end-beyond-duration rejection, `apply_edit` dispatch for
both ops.
- **Backend route** (`test_audio_edit_routes.py`): `fade_in` /
`fade_out` accepted (parametrized).
- **Frontend** (`AudioEditor.test.tsx`): Fade In/Out buttons render for
start/end-anchored selections and call `applyAudioEdit` with the right
operation + params.
- Full suites green: 60 backend audio-edit + 45 review-route + 25
frontend AudioEditor tests pass. Lint clean on changed files.

Plan doc: `docs/archive/2026-06-11-audio-editor-fade-buttons-plan.md`

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

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-11 13:25:28 -04:00
Andrew Beveridge ☄️andClaude Fable 5 f5169bfaa1 test: harden auto-correct production E2E (session dialog + cold start) (#812)
@coderabbitai ignore

Test-only follow-up to #811. The production E2E for AI auto-correct
failed against a job that had a saved review session: the Saved Review
Sessions dialog aria-hides the rest of the app, so role-based locators
couldn't find the (visible) AI Suggest button. The spec now closes that
dialog without restoring, and allows 90s for the first review-page load
after a fresh deploy (cold Cloud Run + uncached correction payload).
Verified passing against live prod (19.5s).

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

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 07:52:41 +00:00
Andrew Beveridge ☄️andClaude Fable 5 e4aad66a06 feat: Fable 5 default + multi-model compare for AI auto-correct (v0.178.0) (#811)
@coderabbitai ignore

## Summary

Follow-up to #809, per Andrew's direction: switch the auto-correct
default to the eval's best model, and add an opt-in **multi-model
compare mode** that queries several models in parallel, dedupes
identical suggestions with consensus counts, and lets the reviewer pick
between conflicting variants.

## Changes

**Fable 5 as production default**
- New Anthropic provider path in `AutoCorrectService` (structured
outputs + adaptive thinking — the exact configuration the 30-job eval
used). Eval rationale: strict precision 0.62 vs 0.56, strict recall 0.51
vs 0.46, 27s vs 35s median latency vs Gemini 3.1 Pro.
- `anthropic-api-key` secret: container added to Pulumi
(`infrastructure/modules/secrets.py`, **already applied** — preview was
exactly +1 create after pinning pulumi-gcp to 9.22.0 to avoid
provider-upgrade VM replaces), value added and verified against the live
API.
- Cloud Run deploy: `AUTO_CORRECT_MODEL=claude-fable-5`,
`AUTO_CORRECT_COMPARE_MODELS=claude-fable-5;gemini-3.1-pro-preview`,
`ANTHROPIC_API_KEY` secret mapping.
- No silent provider fallback: missing key → clear 502.
- `anthropic >=0.109` added as a direct dependency (lock updated).

**Multi-model compare mode**
- `compare_models` setting → all configured models queried in parallel;
identical suggestions deduped with `consensus`/`total_models` + `models`
attribution; overlapping disagreements share a `conflict_group`.
- UI: "Compare multiple AI models" toggle in the run modal; consensus
badges ("2/2 models") and variant badges in the panel; accepting one
variant of a conflict group auto-rejects its siblings; accept-all picks
the highest-consensus winner per group.
- Partial model failure (call error or malformed output) degrades to a
response warning; only all-fail returns 502.
- EditLog decisions now record models/consensus/conflict_group —
per-model accept-rate data accrues in prod.

**Cross-provider bug fixed**: google-genai mutates `response_schema`
dicts in place (injects `property_ordering`), which the Anthropic API
rejects — found via real-call smoke test of compare mode; schemas now
deep-copied per call, with a regression test.

## Testing

- 55 backend auto-correct tests (incl. 10 new multi-model
merge/conflict/degradation tests + schema-pollution regression) and
frontend conflict-util tests; full suite green (3,426 backend unit + 103
emulator + 1,004 frontend)
- Real-call smoke tests: single-model Fable (glory→chlorine, 0.98, 5.6s)
and compare mode (Fable + Gemini parallel, merged to one 2/2-consensus
suggestion, 5.8s)
- Secret value verified end-to-end against the Anthropic API
- CodeRabbit CLI: 12 findings — 5 fixed, 5 skipped with reasons, 2 in
files from another merged PR

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 06:52:14 +00:00
Andrew Beveridge ☄️andClaude Fable 5 6f8503a113 feat: opt-in AI auto-correct suggestions in lyrics review UI (v0.177.0) (#809)
@coderabbitai ignore

## Summary

Third take on lyrics auto-correction, redesigned around the failures
that led to disabling it in #321 (Jan 2026): **one whole-song LLM call**
instead of per-gap calls, **user-triggered from the review UI** instead
of blocking the pipeline, and a **pending-suggestion layer with
per-change accept/reject/undo** instead of silent application. Fully
opt-in — zero change to the default review journey.

## Changes

**Backend**
- `POST /api/review/{job_id}/auto-correct` — stateless; client posts its
current working segments + reference lyrics, gets back word-id-keyed
suggestions (`replace` / `delete` / `insert_after`) with reason,
category, confidence
- `backend/services/auto_correct/` — prompts (kept in sync with the
offline eval harness), settings knobs (adlib removal, insertions,
min-confidence), Vertex Gemini call with 120s timeout, strict
server-side validation of model output
- `AUTO_CORRECT_MODEL` env (default `gemini-3.1-pro-preview`); 422 when
no reference sources exist

**Frontend**
- "AI Suggest" button in the review header → settings modal →
suggestions panel: per-row accept/reject/undo, accept-all/reject-all,
click-to-scroll-and-flash, stale detection when targeted words were
edited since generation
- `useAutoCorrect` hook + pure `autoCorrectApply` utils (id-based
apply/revert, safe against concurrent edits)
- EditLog ops `ai_suggestion_run/accept/reject/undo` — real accept-rate
data accrues from day one
- i18n strings translated to all 33 locales

**Model choice** backed by an offline eval over 30 real production jobs
scored against actual human review edits (design doc:
`docs/archive/2026-06-10-lyrics-auto-correction-reeval-plan.md`): Fable
5 ≈ Gemini 3.1 Pro at the top; GPT-5.2 actively worsened lyrics (would
have repeated the 2025 failure). Gemini chosen for v1 (already on
Vertex, no new secret); switching models is one env var.

## Testing

- 42 backend unit/route tests (`backend/tests/services/auto_correct/`,
`backend/tests/api/test_review_auto_correct.py`)
- 15 frontend unit tests (`autoCorrectApply.test.ts`)
- Production E2E spec
(`frontend/e2e/production/auto-correct-suggestions.spec.ts`) — runs one
real suggestion cycle and dismisses without mutating review state
- Full `make test` green (unit + backend + emulator + frontend)
- CodeRabbit CLI review: 7 findings, 6 fixed, 1 skipped with reason

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 05:44:51 +00:00
Andrew Beveridge ☄️andClaude Opus 4.8 2b7d6bb5f0 fix(lyrics-review): validate & sanitize word timings during review (prevent overlap at source) (#810)
## Summary
Prevents the invalid-word-timing class that caused job `17f7c313`'s
overlapping rendered lyrics (`start=0`, `end=-0.005`) from being
**created or persisted** during lyrics review. The render-time net
(v0.176.2, #804) stays as the last resort; this fixes the source.

Root cause: `useManualSync` ("tap-to-time") assigned `start=0` when the
audio playhead sat at 0 and cascaded `end = 0 - 0.005`. Verified against
this job's data — not AudioShake; not in the edit log (manual-sync
timing edits aren't logged there).

## One shared invariant, four enforcement points
Each word stays within its segment's `[start, end]`; `end ≥ start`;
repaired words are placed at the previous word's end. All four
implementations now produce identical results:
1. **Frontend sanitizer**
`frontend/lib/lyrics-review/sanitizeWordTimings.ts` — pure function +
change report.
2. **Manual-sync clamp** `frontend/hooks/useManualSync.ts` — tap times
clamped to the segment window; `end_time` inversion-guarded (without
capping — holding a note still extends the segment); toast on clamp.
3. **Modal** `frontend/components/lyrics-review/modals/EditModal.tsx` —
sanitize-on-open + `role="status"` banner; Reset/Un-Correct also
sanitize (fixes the buggy 0/null editing surface).
4. **Backend safety net** `backend/services/timing_sanitizer.py` +
`submit_corrections` — clamps + logs before persisting
`corrections_updated.json`.

"Segment follows words" (the modal already derives bounds from word
min/max) means dragging a word earlier/later extends the segment — so
clamping is operation-specific and never traps the user.

## Changes
- 3 new sanitizers (FE lib, FE hook helper, BE service) + modal wiring +
route safety net.
- New unit tests anchored on the `17f7c313` fixture across all layers
(FE Jest + BE pytest).
- 2 new i18n strings, auto-translated to all 33 locales.
- Version `0.176.2 → 0.176.3`. Design + plan in
`docs/archive/2026-06-10-review-timing-validation-{design,plan}.md`.

## Testing
- [x] Backend unit (sanitizer + request-level submit test): 14 passed
- [x] Frontend lyrics-review/hooks/lib: 301 passed
- [x] Two-stage subagent review (spec + quality) per task; final
whole-impl review; CodeRabbit (1 doc fix; i18n nitpicks skipped)

## Review
- [x] Local CodeRabbit review completed

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-11 01:15:45 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 1b7b106c21 fix(lyrics): sanitize invalid word timings to prevent overlapping screens (#804)
## Summary
- Fixes overlapping rendered lyrics on job `17f7c313` ("Atmosphere -
Scalp") — two full screens of lyrics displayed on the same 4 vertical
slots for 7-12s.
- **Distinct root cause** from the earlier libass-wrap overlap (PR
#794), which is why it recurred. This one is a genuine same-Y /
same-time overlap caused by invalid word timestamps.

## Root cause
The transcription left the 4 leading words of a segment ("A whiskey and
a") with invalid timestamps (`start=0.0`, `end=-0.005`) while the
segment itself correctly started at 15.18s.
`SegmentResizer._create_segment_from_words` derives a split line's
`start_time` from `words[0].start_time`, so the split line `"A whiskey
and a beer,"` inherited `start_time=0.0`. A `LyricsScreen` sorts by
`min(line.segment.start_time)`, so the screen jumped ahead of the INTRO
section screen; the INTRO then wiped the active-line bookkeeping and the
next screen faded in (post-instrumental) over the still-displayed
previous screen.

## Changes
- Add `SegmentResizer._sanitize_segment_timings`, run at the top of
`resize_segments` (covers all output paths via `generator.py`).
- Clamps **only invalid** word timings into the segment's `[start, end]`
window and keeps them non-decreasing; valid words are left untouched so
the karaoke highlight sweep is preserved.
- New regression tests in
`tests/unit/lyrics_transcriber/output/test_segment_resizer_timing.py`.
- Bump version `0.176.1` → `0.176.2`.

## Testing
- [x] New timing regression tests + prior line-length regression tests
pass
- [x] Full `lyrics_transcriber` unit suite: 110 passed
- [x] End-to-end against job `17f7c313`: **4 same-Y overlaps before → 0
after**

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

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-09 19:24:43 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 bce87a37fb feat(ui): advertise multi-site URL support on create-from-URL input (#803)
## Summary

Phase 3 of the flacfetch-sole-downloader work. Now that **all** URLs
route through flacfetch and any yt-dlp-supported site works (Facebook,
SoundCloud, TikTok, Vimeo, …), tell users so on the create-from-URL
input.

## Changes (`frontend/components/job/steps/AudioSourceStep.tsx`)

- Broaden the button label **"YouTube URL" → "Paste a link"**.
- Add a hint under the URL field: *"Works with YouTube, Facebook,
SoundCloud, TikTok, Vimeo and hundreds of other sites."* with a link to
the yt-dlp [supported-sites
list](https://github.com/yt-dlp/yt-dlp/blob/master/supportedsites.md).
- Wire the URL section to i18n (`useTranslations('jobFlow')`) —
previously hardcoded — and add 4 new `jobFlow` keys (`pasteUrlButton`,
`useThisUrl`, `urlSupportedSitesHint`, `urlSupportedSitesLink`).
- Translated to **all 33 locales** via `translate.py` (key parity
verified; CI i18n validation will confirm).

## Testing

- i18n key parity verified across all 33 locale files (0 missing).
- Existing `AudioSourceStep.test.tsx` uses the global `next-intl` mock
that returns real en.json strings, and asserts none of the changed
literals — unaffected.
- Frontend `next build`/jest/E2E run in CI (node_modules isn't installed
in this worktree).

Depends on the already-shipped backend change (#802) that makes
non-YouTube URLs actually work.

Plan:
`nomadkaraoke/docs/archive/2026-06-08-flacfetch-sole-downloader-plan.md`

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 15:51:02 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 11b3d30618 feat(downloads): route all URLs through flacfetch; remove Cloud Run yt-dlp (#802)
## Summary

Phase 2 of making **flacfetch the sole audio downloader** — no yt-dlp
ever runs on Cloud Run. Fixes the original Facebook-URL job failure and
removes a class of legacy silent-fallback behaviour.

**Root cause of the reported bug** (job `34e60208`,
`facebook.com/share/v/...`): non-YouTube URLs were downloaded by local
yt-dlp *inside the Cloud Run container*, which succeeded but then died
in `convert_to_wav` (ffmpeg given both `-y` and `-n`), surfacing as a
generic `Failed to download audio file`. Rather than patch the flags,
this removes the path entirely.

## Changes

- **`youtube_download_service.py`** — `download()` now handles **any**
yt-dlp-supported URL: YouTube via the existing video-id path; everything
else (Facebook, SoundCloud, TikTok, Vimeo, …) via flacfetch's generic
`URL` source (`download_by_id(source_name="URL", download_url=url)`).
**Deleted `_download_local`** (local yt-dlp fallback); with no flacfetch
configured it now **hard-fails with a clear error** instead of silently
falling back.
- **`file_upload.create_job_from_url`** — downloads audio up front via
the service for **all** URLs (not just YouTube), then
`start_job_processing`. Removed the non-YouTube branch that triggered
the GPU worker to download locally, and the now-dead
`_trigger_audio_worker_only`. (Keeps GPU idle until audio is in GCS.)
- **`audio_worker.py`** — deleted `download_from_url` (the buggy local
path) and `download_audio`'s URL-download fallback + the dead
`_trigger_lyrics_worker_after_url_download`. The worker now only
consumes a pre-downloaded GCS file; a URL job arriving without one fails
clearly.
- **Docs** — added
`docs/archive/2026-06-08-fallback-logic-audit-prompt.md` (a prompt for a
future session to audit all legacy "fallback" logic).

Net **−331 lines**.

## Testing

- Updated/replaced tests for the removed fallbacks; added tests for
generic-URL routing (`source_name="URL"`) and the no-flacfetch
hard-fail. Affected suites green (410 passed across the touched files);
full backend collection clean.
- Depends on **flacfetch ≥ 0.21.0** (generic `URL` source) — already
shipped & deployed (flacfetch #28), and verified end-to-end: the
original Facebook URL downloads through flacfetch to GCS.

Requires no infra change. Plan:
`nomadkaraoke/docs/archive/2026-06-08-flacfetch-sole-downloader-plan.md`.

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 15:15:13 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 a319bf206a feat(lyrics-review): show song artist + title in header (#801)
## Summary

The Lyrics Transcription Review header showed only the static title
"Lyrics Transcription Review". The Instrumental Review header already
displays the song (artist + title). This adds the same song display to
the lyrics review header so reviewers can see which song they're working
on at a glance.

## Changes

- `frontend/app/[locale]/app/jobs/[[...slug]]/client.tsx`: render
`artist - title` (from the existing `job` prop) next to the header
title, mirroring the Instrumental Review pattern
(`InstrumentalSelector.tsx`). Uses `[job.artist,
job.title].filter(Boolean).join(" - ")` so it degrades cleanly when a
field is missing, with `truncate` to protect the layout.
- `pyproject.toml`: version bump 0.175.1 → 0.175.2.

## Testing

- ESLint clean on the changed file.
- `tsc` reports no new errors (the 39 pre-existing errors are all in
unrelated files).
- No new user-facing strings — only renders existing `job` data — so no
i18n/translation changes (won't trip CI's locale-completeness check).
- CodeRabbit reviewed locally (1 minor finding, fixed: cleaner
artist/title join).

## Notes

Display-only, low-risk change. No existing test covers either review
header's artist/title display (the instrumental review precedent has
none either); a meaningful test would require mocking the full lyrics
data-loading lifecycle, so none was added.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 12:31:31 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 c1837c1086 fix(lyrics-review): gate audio playback until loaded + silence benign AbortError noise (#800)
## Summary
- Production error monitor flagged `AbortError: The fetching process for
the media resource was aborted...` from the lyrics-review page. Root
cause: the audio player started fetching a large file on mount but left
playback controls live before the media could play, so early clicks /
spacebar did nothing **and** the rejected `play()` promise was reported
as error noise.
- Fixes both the noise and the janky UX: playback is now gated until the
audio is fully ready, with a clear loading spinner + buffer progress
bar.

## Changes
- **AudioPlayer** is now the single source of truth for readiness:
tracks `canplaythrough` (+ fully-buffered fallback), publishes
`window.isAudioReady` and a `karaoke:audio-ready` event, and **guards
the `seekAndPlayAudio` / `toggleAudioPlayback` globals** so spacebar,
segment buttons, and the edit modal no-op until ready.
- While loading, shows a spinner + `<Progress>` bar ("Loading
audio..."); on failure shows an inline error.
- New `useAudioReady()` hook visually disables the segment play buttons
(`TranscriptionView`) and the edit-modal play button with an "Audio is
still loading..." tooltip.
- Added `.catch(() => {})` to the three bare `play()` calls and filter
benign `AbortError` in `crash-reporter` so this class of noise never
reaches the error monitor again.
- 3 new i18n strings, translated to all 33 locales (ASCII `...` to match
existing loading strings).

## Testing
- [x] Frontend unit suite green: **916 tests / 65 suites** (added
`AudioPlayer` readiness+gating, `useAudioReady`, `crash-reporter`
benign-abort cases)
- [x] Lint clean; typecheck clean on all touched files
- [ ] Manual: throttled-network check of spinner → controls transition
(recommended post-deploy)

## Review
- [x] CodeRabbit CLI review completed locally (1 finding fixed: ASCII
ellipsis; 1 pre-existing tl.json translation gap noted, out of scope)
- [x] Issues addressed

Plan doc: `docs/archive/2026-06-07-lyrics-review-audio-loading-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-06-08 10:45:58 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 7cf42c8983 feat(pricing): duration-based credit pricing + long-duration input handling (#799)
@coderabbitai ignore

## Summary

Implements **duration-based credit pricing** for karaoke jobs, replacing
the flat 1-credit/job model. Credits now scale with input audio length
(`ceil(min/10)`, hard-block >60 min), with cost confirmed before heavy
processing and reconciled against the actual measured audio. Closes out
the planned fix from the 2026-06-04 long-duration mashup incident.

- Design:
`docs/archive/2026-06-04-long-duration-input-handling-design.md`
- Plan: `docs/archive/2026-06-04-long-duration-input-handling-plan.md`

## Pricing model

`credits = max(1, ceil(minutes / 10))` — 1 credit ≤10 min, 2 ≤20 min … 6
≤60 min. Inputs over 60 min are blocked. Single source of truth in
`backend/services/pricing.py`, mirrored in `frontend/lib/pricing.ts`.

## How it works

- **`state_data.credits_charged`** is the authoritative running total.
`create_job` charges the base (URL = full N via `acknowledged_credits`;
search/upload = 1); top-ups deduct only the **delta**
(`count_as_job_creation=False`).
- **Reconciliation engine** (`duration_reconciliation.py`) runs at the
single convergence point before separation+transcription in all three
processing paths (download / post-edit / `start_job_processing`),
exactly once each. It measures the audio actually sent to AudioShake
(post-edit if trimmed):
  - actual < estimate → auto-refund the difference
- actual > estimate → pause at new **`AWAITING_DURATION_CONFIRM`**
state, user re-confirms (inline Buy Credits)
  - actual > 60 min → refund everything + cancel
- **`POST /api/jobs/{id}/confirm-duration`** (+ `POST
/api/jobs/estimate`) reuse the review-stage pause/resume.
- **Notifications**: in-browser + push, 15-min idle email, 24h reminder,
**48h auto-cancel + full refund** — via the existing idle-reminder /
stale-job machinery.
- **Admin / made-for-you jobs bypass charging entirely**
(`payment_bypassed` → reconcile short-circuits).

## Endpoints

| Method | Path | Purpose |
|---|---|---|
| `POST` | `/api/jobs/estimate` | URL duration probe →
`{duration_seconds, credits, blocked, source}` |
| `POST` | `/api/jobs/{id}/confirm-duration` | confirm cost / resume
(402 insufficient, 409 mismatch) |
| `POST` | `/api/jobs` | URL create gains optional `duration_seconds`,
`acknowledged_credits` |
| `POST` | `/api/audio-search/{id}/select` | gains optional
`acknowledged_credits` |

## Frontend

`DurationCostConfirm` modal (Radix Dialog) surfaced via a "Confirm Cost"
action on `awaiting_duration_confirm` jobs (`useDurationConfirm` hook),
per-result cost chips on audio search, `pricing` i18n namespace in all
33 locales.

## Testing

- Backend: **3358 passing** (incl. boundary tables, money-math
conservation, reconcile up/down/over-limit, confirm 402/409, idempotency
guards, stale-expiry refund, an end-to-end integration test). Frontend:
**960 passing**. i18n completeness clean.
- Reviewed locally: per-task spec + quality review, a holistic
cross-cutting review, `/test-review`, and two CodeRabbit fix cycles.

## Notable bugs caught & fixed during review

- **Multi-credit under-refund**: `_refund_credit_for_job` refunded a
flat 1 — now refunds `credits_charged` (user-cancel of a long job).
- **Admin-bypass trap**: admin jobs would pause at the confirm gate and
be charged real credits — now short-circuited.
- Over-limit double-refund (suppress `cancel_job`'s built-in 1-credit
refund); over-limit email used the wrong "48h" message;
double-confirm/double-select idempotency guards.
- Hit the summary-projection gotcha (added fields to both projection
lists + regression test).

## Known residuals / follow-ups (non-blocking)

- **URL pre-flight cost-confirm is inert** until flacfetch's
`/check-youtube` returns a `duration` key — currently falls back to a
1-credit hold + post-download reconcile (functionally correct). Separate
flacfetch change.
- Duration-confirm email **bodies** are English (URLs are
locale-prefixed; backend i18n covers en/es/de) — `# TODO(i18n)` left.
- Concurrent confirm/select **double-charge TOCTOU** is an accepted
low-probability residual (atomic claim would need a Firestore
transaction); the status-transition guard handles the realistic
double-click case.

## Deploy note

Reuses the existing Cloud Tasks idle-reminder queue and the hourly
stale-review Cloud Scheduler (status-list / action-type expansions only)
— no new infra expected, but worth confirming `pulumi up` is a no-op on
deploy.

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-07 18:39:06 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 e806616408 fix: idempotent session revoke, error-pattern script crash, mobile header overlap (#798)
## Summary
Three independent fixes bundled together:

1. **`revoke_session` idempotency** — stops the recurring `Error
revoking session` prod error on `karaoke-backend`. Firestore
`document.update()` raises `NotFound` (404) when a session doc is
already gone (logged out / expired / cleaned up); logout against an
already-absent session now succeeds instead of erroring.
2. **`query-error-patterns.py` crash** — `last_seen`/`first_seen` are
stored as ISO-8601 strings in Firestore, but the sort key and `--hours`
filter did `float(value)`, raising `ValueError` and breaking the
`--json` path that `/prod-investigate` relies on. Added a `_to_epoch()`
helper handling datetime objects, ISO strings, and numeric epochs.
3. **Mobile header overlap** — `AppHeader` was `position: fixed` and
each consumer cleared it with a hardcoded top padding. On narrow
viewports the header wraps to 3 rows (149px on a 412px Pixel), exceeding
the 112px offset, hiding the "Create Karaoke Video" heading and the top
of the form behind it (worse across locales with longer button labels).
Switched `AppHeader` to `position: sticky` (matching the already-working
jobs-page header) so content always clears it at any height, and removed
the now-redundant magic-number offsets.

## Changes
- `backend/services/user_service.py` — catch
`google_exceptions.NotFound` in `revoke_session`, return `True`
- `backend/tests/test_revoke_session.py` — new unit tests (existing /
missing / unexpected-error paths)
- `scripts/query-error-patterns.py` — `_to_epoch()` helper for sort +
`--hours` filter
- `frontend/components/app-header.tsx` — `fixed` → `sticky`
- `frontend/app/[locale]/app/page.tsx`,
`frontend/app/[locale]/app/referrals/page.tsx` — drop hardcoded top
padding
- `pyproject.toml` — bump to 0.174.17

## Testing
- [x] Backend tests pass locally (47 passed incl. 3 new `revoke_session`
tests)
- [x] `query-error-patterns.py --json` and `--hours` verified against
live Firestore
- [x] Mobile header fix verified in Playwright at 412px (Pixel) and
1280px — overlap eliminated (title moves from 12px behind the header to
a clear gap below it)
- [x] CodeRabbit CLI review: 0 findings

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

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-05 23:24:21 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 87f36687bf fix(storage): treat missing GCS object as no-op on best-effort deletes (#797)
## Summary

Recurring production error-monitor alerts — five sibling patterns of the
form
`Error deleting file <path>: 404 DELETE ... No such object` (one each
for
`.mov`, `.mp4`, `.png`, `.jpg`, `.mkv`) — were traced to routine **admin
actions**, not a real failure.

The admin **Restart Job** (`admin.py`) and **Regenerate Screens**
(`admin.py`) endpoints
speculatively delete a *hardcoded template* of every possible output
path
(`screens/title.mov`, `screens/title.png`, `output/final_4k.mp4`,
`output/with_vocals.mkv`, …)
before re-running a job. Any given job only produces a **subset** of
those (e.g. a static
title screen has no `title.mov`; a 720p-only render has no
`final_4k.mp4`), so the absent
variants return 404.

`StorageService.delete_file()` logged those 404s at **ERROR severity
before re-raising** —
even though the callers already wrapped each call in `try/except: pass`
with a
`# File may not exist` comment. The ERROR log line is what the error
monitor ingested,
generating noise tied to every admin restart/regen.

Confirmed against the most recent occurrence: job `8e9df2c1` shows
"Admin … triggered screen regeneration" at 16:58, and the `.mov` 404 was
last logged at 17:01.

## Changes

- `StorageService.delete_file(blob_path, ignore_missing=False)`: when
`ignore_missing=True`,
a `NotFound` (404) is treated as a successful no-op — logged at `debug`,
returns `False`
(vs `True` when an object was actually deleted). Default behaviour is
**unchanged**: a
  genuine unexpected 404 still logs `ERROR` and raises.
- Wired `ignore_missing=True` into the three best-effort callers:
- admin **Restart Job** output/screen cleanup (now only reports paths
actually deleted)
  - admin **Regenerate Screens** cleanup
  - `JobManager.delete_job()` output-file cleanup
- Added unit tests: returns `True` on real delete, raises on 404 by
default, returns `False`
  (no raise) on 404 when `ignore_missing=True`.

## Testing

- `test_storage_service.py`: 19 passed (incl. 3 new)
- `test_job_manager.py` + `test_credit_enforcement.py`: 69 passed
- All admin/restart/regen suites: 218 passed, 6 skipped (emulator-only)
- CodeRabbit (uncommitted): 0 findings

## Impact

Cosmetic / operational — deletions already succeeded and jobs regen
fine; this removes the
recurring false-positive ERROR logs at the source. No behaviour change
for genuine errors.

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

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-05 13:35:08 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 676e31056e fix(review): serve preview video via signed GCS URL redirect (Cloud Run 32 MiB limit) (#796)
## Summary
The preview-video endpoint failed for long songs because the 360p
preview exceeds Cloud Run's 32 MiB response-body limit. Surfaced while
testing the recovered job `9a12cf0f` (a 32-minute mashup whose preview
is **32.4 MiB**): the modal showed *"No video with supported format and
MIME type found."*

## Root cause
`get_preview_video` downloaded the mp4 and streamed it **through Cloud
Run** via `FileResponse`. For short songs previews are a few MB, but
this preview was >32 MiB, so Cloud Run truncated the response — uvicorn
logged `206` while the client received a `500` (confirmed in LB logs).
The browser got a broken body and couldn't decode it.

## Fix
Return a **302 redirect to a signed GCS URL** (matching the existing
audio-review endpoint at `review.py:372`), so the browser fetches the
mp4 directly from GCS with byte-range support intact — Cloud Run's body
limit never applies. Also removes the now-unused
`FileResponse`/`BackgroundTask` imports.

## Testing
- [x] Backend suite: **3186 passed, 36 skipped**
- [x] New tests: `TestGetPreviewVideoRedirect` (302 → signed URL, never
proxies; 404 when missing)
- [x] Verified the deployed mp4 for `9a12cf0f` is valid (h264/aac,
480x270) — the file was always fine; only the delivery path was broken.

## Review
- [x] CodeRabbit CLI review completed locally (0 findings)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 19:55:31 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 f683af6c84 fix(lyrics): cap Firestore corrections payload + scale transcription timeout by duration (#795)
## Summary
Both production error patterns alerted on 2026-06-04 traced to a
**single oversized input** — job `9a12cf0f`, a 32-minute mashup (422
segments, 3,742 words). Two fixes, plus a follow-up design doc for the
real solution (duration-based credit pricing).

## Changes
- **Firestore doc-size (`backend/api/routes/jobs.py`):**
`submit_corrections` now persists only a lightweight summary
(`state_data.corrected_lyrics = {corrected_segment_count: N}`) instead
of the multi-MB segment arrays
(`corrected_segments`/`original_segments`/`resized_segments`, ~600KB
each) that exceeded Firestore's 1MB limit. The prior `reference_lyrics`
strip missed the real bulk. Full corrections still go to GCS
(`corrections_updated.json`), which the render worker reads. The
`complete_review` 0-segment guard reads the summary and is
backward-compatible with the legacy full-dict shape.
- **Transcription timeout (`backend/workers/lyrics_worker.py`,
`backend/config.py`):** new `compute_transcription_timeout()` scales the
outer safety-net timeout by ffprobe-measured audio duration —
`clamp(floor 1200, duration × 1.0, cap 1700)` — instead of a fixed 1200s
that flapped long tracks to `failed`.
- **Infra (`infrastructure/modules/cloud_run.py`):**
lyrics-transcription-job task timeout `1800s → 3000s` + env
`TRANSCRIPTION_TIMEOUT_CAP_SECONDS=2700` so long mashups get real
headroom. **Requires `pulumi up`.**
- **Docs:** prompt/design doc for the follow-up duration-based credit
pricing + warn/block feature
(`docs/archive/2026-06-04-long-duration-input-handling-prompt.md`); two
LESSONS-LEARNED entries.
- **Tests:** new coverage for the summary contract, guard
backward-compat, and timeout boundaries; updated obsolete
`reference_lyrics`-stripping tests; modernized 4 flaky
`asyncio.get_event_loop()` tests.

## Testing
- [x] Backend suite: **3184 passed, 36 skipped** (`pytest
backend/tests`, excluding emulator/integration)
- [x] Targeted new tests green (doc-size summary, guard, timeout
scaling)

## Review
- [x] CodeRabbit CLI review completed locally (0 findings)
- [x] Issues addressed

> Note: these are targeted fixes for the symptoms. The structural fix is
the duration-pricing feature in the linked design doc.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 19:06:45 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 70bbabc661 fix(lyrics): prevent over-long lines overlapping the slot below in rendered video (#794)
## Summary
- Fixes overlapping lyric lines in rendered karaoke videos (preview and
final 4K).
- Root cause: `SegmentResizer` could emit a line longer than
`max_line_length`, which **libass word-wraps onto a second physical row
at render time**, colliding with the lyric line in the slot below (two
lines drawn on top of each other).
- This lives in the shared `lyrics_transcriber` package, so it fixes the
overlap for **all jobs**, not just the one reported.

## Root cause
In `_create_segments_from_lines`, word objects are re-assigned to the
splitter's lines via fragile substring matching. A `;` break was
positioned *before* the semicolon, so the line ended with `around` while
the word token was `around;`; the match failed and every remaining word
fell into an **unbounded catch-all** that joined them into one over-long
line. Space-dash-space (` - `) breaks orphaned the dash the same way.

## Changes
- `;` break now splits **after** the semicolon, keeping it attached to
its word token (also reads better).
- The catch-all now **greedily packs leftover words into ≤
`max_line_length` lines** instead of one unbounded segment — a length
guarantee that holds regardless of which punctuation desyncs
word-to-line matching.
- Added regression tests (`test_segment_resizer_line_length.py`):
semicolon case, dash case, single-long-word edge case, word-order
preservation.

## Testing
- [x] New regression tests pass; full backend unit suite green (the only
failures are pre-existing `audio-separator`-not-installed env errors,
unrelated to this change).
- [x] Verified against job `5c631108` + all 22 saved review sessions:
over-length output lines → **0**, no word loss/reorder.
- [x] Re-rendered the 4K overlap moment locally — confirmed the
collision is gone.

## Review
- [x] Local CodeRabbit CLI review completed; 1 minor finding 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-06-04 18:33:08 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 fe8430d990 fix(admin): allow regen-screens from in_review state + surface errors via toast (#793)
## Summary
- Fixes a 400 when regenerating title/end screens for a job the user has
opened in the review UI (`in_review` state).
- Fixes the root cause behind "click Regenerate Screens → modal just
closes, no error": `<Toaster />` was never mounted, so **all** `toast()`
calls (success and error) silently no-op'd.

## Changes
- **Backend:** add `in_review` to `REGENERATE_SCREENS_ALLOWED_STATES` in
`backend/api/routes/admin.py`. The sibling `/restart` endpoint already
allows `in_review`; this restores parity. Updated `docs/API.md`.
- **Frontend:** mount the shadcn `<Toaster />` (same `@/hooks/use-toast`
store) in the root `app/layout.tsx` so admin toasts render app-wide.
- **Frontend:** give the regen-screens handlers specific, human-readable
failure titles/messages (admin dashboard + compact `AdminJobActions`
toolbar).
- Version bump `0.174.12` → `0.174.13`.

## Testing
- [x] Backend: `tests/unit/test_regenerate_screens.py` — allow-list
membership, `in_review` → 200, invalid state → 400, missing job → 404 (4
pass).
- [x] Frontend: `AdminJobActions.test.tsx` — error-toast path now
covered (5 pass).
- [x] CodeRabbit CLI review: 0 findings.
- [x] Typecheck: no new errors from these changes (pre-existing errors
unrelated).

## Review
- [x] CodeRabbit CLI review completed locally
- [x] Issues 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-06-03 12:31:19 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 eb1cc7b94f fix(encoding,ci): silence self-healing warmup 503 alert + robust E2E result check (#790)
## Summary
Two unrelated production alert-noise fixes, prompted by two false-alarm
Discord alerts on 2026-05-24:

- **Encoding worker 503 → WARNING.** A primary-VM warmup hitting `503
SERVICE_UNAVAILABLE` (or capacity exhaustion) is self-healing — the
encoding flow's `ensure_any_running()` falls back to an alternate-zone
worker and the job completes (verified live on job `a40f3024`). It no
longer logs at ERROR, so it stays below the error monitor's
`severity>=ERROR` filter and stops paging Discord for a non-incident.
- **E2E daily test result check.** Both stages now derive pass/fail from
Playwright's real exit code instead of grepping the log for `"failed"`.
The old check matched the word "failed" inside a benign retry warning
(`goto attempt 1/3 failed`) and reported failure on a run where the job
completed and Playwright printed `1 passed`.

## Changes
- `backend/api/routes/encoding_worker.py` — catch
`EncodingWorkerStartError` in `/warmup` and log at WARNING with a clear
fallback message; genuine unexpected errors still log at ERROR.
- `.github/workflows/e2e-daily.yml` — capture `${PIPESTATUS[0]}` (the
pipe to `tee` was masking Playwright's exit code as 0) and gate the
result on it, for both Stage 1 and Stage 2.
- `backend/tests/test_encoding_worker_routes.py` — 3 regression tests:
503 start failure → WARNING, capacity error → WARNING, unexpected error
→ still ERROR.
- `docs/TROUBLESHOOTING.md` — note that a WARNING-level warmup 503 is
benign/self-healing.
- `pyproject.toml` — bump 0.174.11 → 0.174.12.

## Testing
- [x] `pytest backend/tests/test_encoding_worker_routes.py
backend/tests/test_encoding_worker_manager.py` — 46 passed
- [x] YAML validated
- [x] CodeRabbit CLI review — 0 findings

## Review
- [x] Local CodeRabbit review completed
- [x] Issues addressed

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-24 17:17:06 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 ce21560803 fix(runner-images): bump actions/runner 2.332.0 → 2.334.0 (deprecated, broke ephemeral CI) (#791)
## Summary
GitHub deprecated **actions/runner v2.332.0** and now returns **HTTP
403** on the broker poll (`"Runner version v2.332.0 is deprecated and
cannot receive messages"`). Ephemeral/JIT runners run with
`disableUpdate`, so they **cannot self-update** — each dispatched VM
registered, got rejected, exited, and self-halted, leaving CI jobs
**queued indefinitely** plus zombie `offline` runner registrations.

Nothing in our code changed; this is GitHub-side deprecation enforcement
that hit after the May 17 image build. Root-caused from a failed VM's
`_diag/Runner_*.log`.

## Changes
- Bump `RUNNER_VERSION` `2.332.0 → 2.334.0` (current latest) in:
- `infrastructure/scripts/runner-image-provision.sh` (ephemeral image —
the one that matters)
- `infrastructure/compute/startup_scripts/github_runner.sh` +
`github_runner_gpu.sh` (legacy)
- `infrastructure/compute/startup_scripts/__init__.py` (docstring
example)
- Document the failure mode + runbook in
`docs/EPHEMERAL-GHA-RUNNERS.md`.

## Why this broke CI
Dispatch + VM boot worked fine, so it looked like the jobs were just
"stuck queued." Ruled out (with evidence): label match, runner-group
access, Cloud NAT egress, manager env config, dirty runner dir,
fresh-image regression, JIT mint. The `_diag` log showed the 403.

## Follow-up (not in this PR)
- Rebuild cadence (`0 2 1 * *`, monthly) is too slow vs. GitHub's
deprecation pace — resolve "latest" at build time and/or alert on
deprecation 403s.
- Two secondary bugs found: #789's serial-capture can't read self-halted
(stopped) VMs; zombie offline JIT registrations make `cleanup_orphans`
treat dead VMs as "registered" until the 120-min cap.

## Testing
- [x] No remaining `2.332.0` refs in repo
- [x] CodeRabbit CLI review — 0 findings
- [ ] **Takes effect only after `build-runner-images.yml` rebuild**
(runs on GitHub-hosted runners, not blocked)

## Review
- [x] Local CodeRabbit review completed

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-24 16:38:43 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 748d5aefab obs(runner-manager): capture serial console before deleting unregistered VMs (#789)
## Summary

Ephemeral GPU runner VMs register with GitHub roughly **1 in 3** times.
Observed today on python-audio-separator PR #288: 3 GPU VMs dispatched,
1 ran \`core-models\`, 2 booted but never registered and were silently
deleted after 40 min.

We can't fix the underlying registration bug because we have **zero
visibility** into what's happening on the failed VMs:
- STARTUP_SCRIPT's stderr (including \`./run.sh --jitconfig\` output)
goes to the serial console only
- No Ops Agent is installed on the runner image, so journald doesn't
ship anywhere
- The script's \`EXIT\` trap shuts the VM down on any failure
- Boot disks are auto-delete → forensics impossible

This PR adds the missing observability so we can root-cause the real
bug.

## Changes

- New \`_log_serial_tail(zone, name)\` helper: fetches the last 50 KiB
of serial console output via \`instances.getSerialPortOutput()\` and
prints it. The manager's stdout already flows to Cloud Logging, so the
output becomes queryable.
- \`cleanup_orphans()\` calls \`_log_serial_tail\` **only** for the
\"unregistered past grace\" delete path (the genuinely-mysterious case).
Hung-after-registration deletes are skipped because that output is
mostly job stderr, which is already in GHA logs.
- Best-effort: a fetch error logs a warning and lets the delete proceed.
- 50 KiB cap prevents pathological logging volume if many VMs fail
simultaneously.

## Testing

- [x] All 32 unit tests pass (\`pytest
infrastructure/functions/runner_manager/test_ephemeral.py\`)
- [x] 2 new tests cover \`_log_serial_tail\` directly (truncation +
swallowing fetch errors)
- [x] 3 existing \`cleanup_orphans\` tests updated to assert serial
capture is called on registration-failure path and NOT on hung-VM path

## Review

- [x] Local CodeRabbit review pending — will run before merging
- [x] No behavioural change in the happy path (registered VMs that
successfully run jobs)

## After Merge

**Manual \`pulumi up\` required** to deploy the updated Cloud Function
(per CLAUDE.md: claude-readonly ADC blocks Pulumi's
storage.objects.create). Then wait for the next GPU integration test run
to fail → query \`gcloud logging read 'serial console for gha-gpu-'\` to
see the actual failure reason → open follow-up PR with the real fix.

## Related

- Triggered by python-audio-separator PR #288 stuck on GPU integration
tests
- Builds on memory: \`project_ephemeral_runner_phase4.md\` (PRs
#781-#783 fixed kernel-skew + Secure Boot, but registration-failure
flakiness remained)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 18:57:29 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 771b2965c9 fix(monitoring): autoClose minimum is 30min — raise from 600s to 1800s (#788)
## Summary

Follow-up to #787. GCP Monitoring rejects \`autoClose\` values below 30
minutes — \`pulumi up\` for #787 failed with:

\`\`\`
Error 400: Field alertStrategy.autoClose had an invalid value of
"seconds: 600":
the autoclose duration should be at least 30 minutes
\`\`\`

PR #787 didn't apply atomically, so prod alert policy is still on the
old values (threshold=7200, autoClose=3600s). This PR sets autoClose to
the GCP minimum (1800s = 30min). Combined with #787's threshold bump to
9000s, the noise alert from this morning will be killed once \`pulumi
up\` lands.

## Changes

- \`auto_close\`: \`600s\` → \`1800s\` (GCP minimum)
- Added comment explaining the floor so the next agent doesn't try to
lower it

## Test plan

- [x] \`ast.parse\` clean
- [ ] \`pulumi preview\` shows in-place update to
\`runner-dispatcher-long-lived-vm-alert\` only
- [ ] \`pulumi up\` succeeds (no GCP 400)
- [ ] Cloud Console shows policy with threshold=9000, autoClose=1800s

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 14:01:42 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 689edce365 fix(monitoring): raise long-lived VM alert threshold to 2h30m (kill false positives) (#787)
## Summary

Last night's alert (`VM Alive > 2h` firing at 06:40 UTC, recovering at
~07:41 UTC) was a false positive. The cleanup pass worked correctly —
the alert policy is too tight.

## Root cause

Orphan-cleanup deletes VMs at `MAX_VM_LIFETIME_MINUTES=120` on a 15-min
scheduler tick. Worst-case lifetime = **135min**. The alert threshold
was set to exactly **120min (7200s)** with `ALIGN_MAX` over a 5-min
window and a 300s duration — so the 5-min window containing the last
pre-delete sample reports `max > 7200` for ~5min after the VM is already
gone, and `autoClose=3600s` dragged recovery out for ~1h.

### Evidence (instance `6379757481209834386` =
`gha-general-1b8a7c29c8e2`)

| Time (UTC) | Event |
|---|---|
| 04:28:53 | VM created (workflow_job.queued webhook) |
| 06:28:53 | uptime crossed 7200s (exact 2h) |
| 06:30:03 | scheduler tick fires orphan cleanup |
| 06:30:04 | function logs `gha-general-1b8a7c29c8e2: age=121.3min >
max, deleting` |
| 06:31:24 | delete operation completes (`last=True`) — **VM gone** |
| 06:40:27 | **alert fires** (9 min after VM was deleted) |
| ~07:41 | alert auto-closes |

The alert hadn't fired before because notification channels were unwired
across all policies until PR #783 merged ~12 min before this VM was born
— this was the first cleanup cycle observed via email, not the first
false positive.

## Changes

- `threshold_value`: `7200` → `9000` (150 min = worst-case 135 min + 15
min buffer)
- `auto_close`: `3600s` → `600s` (faster recovery if it ever does
legitimately fire)
- `display_name` + docs updated to `VM Alive > 2h30m`

Real cleanup-broken cases (VMs stuck at 3h+) still trigger.

## Operator action required

Per memory `feedback_claude_readonly_adc`: claude-readonly ADC can't
push Pulumi state, so this needs a manual `pulumi up --target` after
merge:

\`\`\`bash
pulumi up --target
'urn:pulumi:prod::karaoke-gen-infrastructure::gcp:monitoring/alertPolicy:AlertPolicy::runner-dispatcher-long-lived-vm-alert'
\`\`\`

Expected diff: in-place update — `displayName`,
`conditions[0].displayName`,
`conditions[0].conditionThreshold.thresholdValue` (7200 → 9000),
`alertStrategy.autoClose` (3600s → 600s), `documentation.content`.

## Test plan

- [x] `ast.parse` clean for `monitoring.py`
- [x] No tests reference the alert policy displayName/threshold (`grep
-rn "long_lived\|VM Alive" infrastructure/` only hits this file)
- [ ] `pulumi preview` shows an in-place update to
`runner-dispatcher-long-lived-vm-alert` only — no creates/deletes
- [ ] After `pulumi up`, verify policy in Cloud Console shows
threshold=9000 and autoClose=600s

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 13:56:03 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 123a15cc78 docs: correct i18n notes in CLAUDE.md to match current frontend layout (#786)
## Summary
- Fix stale path in CLAUDE.md i18n section: `frontend/src/app/[locale]/`
→ `frontend/app/[locale]/`
- Clarify that non-locale routes like
`frontend/app/app/jobs/[[...slug]]/page.tsx` are `<LocaleRedirect />`
shims, not English-only surfaces
- Note that review UIs (`/review`, `/instrumental`, `/audio-edit`) are
fully multilingual via `components/lyrics-review`,
`instrumental-review`, `audio-editor` using `useTranslations`
- Narrow the English-only claim to `/admin/*` only

## Testing
- Docs-only change; no code paths affected
- Verified the new paths exist on disk and `LocaleRedirect` is used in
the referenced shim files

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 15:03:02 +00:00
Andrew Beveridge ☄️andClaude Opus 4.7 63e36b007c fix(monitoring): wire email notification channel to all alert policies (#783)
## Summary

Followup #3 from
`docs/archive/2026-05-17-ephemeral-runner-followups-handoff.md`. Root
cause of the 2026-05-17 cutover going undetected for ~14h: the `GHA
Runner Dispatcher - Create Failures` alert had a correct log-based
metric and a correct condition — but **no notification channels were
attached to any alert policy project-wide**, so the three create-failure
events fired into the void.

Verified before this PR:

\`\`\`
$ gcloud alpha monitoring channels list --project=nomadkaraoke
(empty)
\`\`\`

## Changes

- New `create_notification_channels()` in
`infrastructure/modules/monitoring.py`: creates one email channel
(`alerts-email`, delivering to `andrew@beveridge.uk`).
- Both `create_alert_policies` and
`create_ephemeral_runner_observability` now accept a `channels` dict and
thread it into every `gcp.monitoring.AlertPolicy` via
`notification_channels=...`.
- `__main__.py` calls `create_notification_channels()` first and passes
the result through.
- `infrastructure/monitoring/README.md` rewrites the "Notification
Channels" section to point at the IaC and includes a paste-ready snippet
for adding Discord (via Discord's Slack-compatible `<webhook_url>/slack`
endpoint) as a follow-up.

Policies that now get notifications:
- `error_rate`, `queue_backlog`, `memory`, `service_unavailable`
(Karaoke Backend)
- `dispatch_failure_alert`, `long_lived_vm_alert` (GHA Runner
Dispatcher)

## Operator action required

After merge + `pulumi up`, Cloud Monitoring sends a one-time
confirmation email to `andrew@beveridge.uk`. The channel stays in
PENDING state until the link is clicked.

Verify with:

\`\`\`bash
gcloud alpha monitoring channels list --project=nomadkaraoke \\
  --format='table(displayName,type,verificationStatus,enabled)'
\`\`\`

Looking for `verificationStatus=VERIFIED`.

## Test plan

- [x] `ast.parse` clean for `monitoring.py` and `__main__.py`
- [x] Confirmed all 6 alert policies have
`notification_channels=notification_channels` attached (`grep -c
notification_channels infrastructure/modules/monitoring.py` → 11,
expected)
- [ ] `pulumi preview` shows: 1 new `NotificationChannel`, 6 in-place
`AlertPolicy` updates. No destructive ops.
- [ ] Run `pulumi up`. Verify email arrives. Click verification link.
- [ ] Force a test alert (e.g. temporarily lower a threshold) and
confirm email delivery, then revert.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 00:28:29 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 b4e7a83067 refactor(runner-manager): drop legacy fixed-pool dispatcher code (~370 lines) (#782)
## Summary

Followup #2 from
`docs/archive/2026-05-17-ephemeral-runner-followups-handoff.md`. Phase 4
(PR #780, 2026-05-18) deleted the 7 long-lived runner VMs; the
dispatcher has been running `RUNNER_MODE=ephemeral` exclusively since
then. The legacy start/stop code paths are now dead weight.

### Removed

- `infrastructure/functions/runner_manager/main.py` (~370 lines):
- `start_runners`, `_start_single_runner`, `_stop_single_runner`,
`check_and_stop_idle_runners`, `get_runner_instances`,
`update_instance_metadata`, `get_instance_metadata`,
`_get_instance_age_hours`, `check_github_for_pending_jobs`
- `RUNNER_MODE`, `RUNNER_NAMES`, `GPU_RUNNER_NAMES`,
`IDLE_TIMEOUT_HOURS` module constants + the `if RUNNER_MODE ==
'ephemeral'` branching
- The `completed`-action metadata refresh (ephemeral runners self-clean)
- `infrastructure/modules/runner_manager.py`:
  - `RUNNER_MODE` Pulumi config + validation
  - `RUNNER_NAMES` / `GPU_RUNNER_NAMES` env vars passed to the function
- `runner_names` / `gpu_runner_names` params on `create_cloud_function`
and `create_runner_manager_resources`
  - `IDLE_TIMEOUT_HOURS` env var
- `Pulumi.prod.yaml`: `karaoke-gen-infrastructure:runnerMode: ephemeral`
- `config.py`: `RunnerManagerConfig.IDLE_TIMEOUT_HOURS`
- The 35-test legacy `test_runner_manager.py` (all dead code)

### Kept

- `runner-manager-idle-check` Cloud Scheduler job and its
`?action=check_idle` query parameter — both names are now load-bearing
for backward-compat (renaming would force a Pulumi recreate without
behavioural benefit). The function routes every scheduler tick to orphan
cleanup; the resource description is updated to reflect that.

`test_ephemeral.py::TestSchedulerAuthGate` simplified: removed
`RUNNER_MODE` / `RUNNER_NAMES` env-var fixtures and rewrote
`test_scheduler_with_bearer_token_dispatches_orphan_cleanup` to verify
the tick now routes to `ephemeral.cleanup_orphans`.

## Test plan

- [x] All 26 tests in `test_ephemeral.py` pass
- [x] `python -c 'import ast; ...'` clean for every touched module
- [ ] `pulumi preview` shows: Function source bundle replace + Function
env-var diff (loses `RUNNER_MODE`, `RUNNER_NAMES`, `GPU_RUNNER_NAMES`,
`IDLE_TIMEOUT_HOURS`), Pulumi config `runnerMode` removed — no
behavioural change in prod (dispatcher is already ephemeral-only)
- [ ] After merge + `pulumi up`, watch `gcloud logging read
'resource.type=\"cloud_run_revision\" AND
resource.labels.service_name=\"github-runner-manager\" AND
textPayload:\"Dispatched ephemeral runner\"' --freshness=30m` to confirm
dispatch still works
- [ ] Watch `textPayload:\"orphan cleanup\"` to confirm the scheduler
tick still drives cleanup

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 00:28:26 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 34c36088c1 fix(runner-images): GPU NVIDIA load + Secure Boot off; runbook updated (#781)
## Summary

Followup #1 + #4 from
`docs/archive/2026-05-17-ephemeral-runner-followups-handoff.md`. Fixes
the GPU-image cutover bug that blocked python-audio-separator
integration tests, and brings the operator runbook in line with what
actually shipped.

### Root cause (validated with two GPU smoke VMs against the broken
image)

Two compounding bugs:

1. **Kernel skew**: `apt-get install cuda-drivers` pulls a newer kernel
image via the `linux-image-cloud-amd64` meta-package, but DKMS only
builds nvidia.ko against the build-VM's currently-running kernel. Fresh
ephemeral VMs boot the newer kernel (GRUB default) and find no nvidia
module for `uname -r` — `nvidia-persistenced` fails with "Failed to
query NVIDIA devices". Confirmed on `gha-runner-gpu-20260517-183755`:
image baked nvidia for `6.1.0-47`, fresh VMs boot `6.1.0-48`.
2. **Secure Boot lockdown**: `enable_secure_boot=True` puts the kernel
in `lockdown=integrity` mode and rejects unsigned modules with "Key was
rejected by service". Legacy GPU runners had no
`shielded_instance_config` (SB off by default) and weren't affected.

### Fixes

- `infrastructure/scripts/runner-image-provision.sh`: bake
`gha-gpu-modprobe.service` (GPU variant only). Runs before
`nvidia-persistenced.service` and the GCE startup script. Idempotent —
no-op when nvidia is loaded; otherwise installs matching
`linux-headers-$(uname -r)`, runs `dkms autoinstall`, and modprobes
nvidia / nvidia_uvm / nvidia_drm.
- `infrastructure/functions/runner_manager/ephemeral.py`:
`enable_secure_boot=not family.has_gpu`. Keeps Secure Boot on for
general/build.
- `docs/EPHEMERAL-GHA-RUNNERS.md`: rewrite STATUS to reflect the actual
cutover history (3 bug-fix iterations in PR #776, Phase 4 already done
in PR #780), remove the now-stale Phase-4 followups walkthrough, add 7
new lessons-learned entries.

### Verification

- Manual fix sequence on a no-SB smoke VM produced working `nvidia-smi`
(Tesla T4, driver 595.71.05, CUDA 13.2) as root and as the `runner`
user.
- An SB-on smoke VM failed with "Key was rejected by service" at
modprobe even after `dkms autoinstall`, confirming the second fix.
- Image rebuild (run
[26012660753](https://github.com/nomadkaraoke/karaoke-gen/actions/runs/26012660753))
is in flight on this branch.

End-to-end verification will be a follow-up PR in
`python-audio-separator` once the new image is `READY` and a smoke VM
from it auto-loads nvidia.

## Test plan

- [x] All 30 tests in `test_ephemeral.py` pass (4 new in
`TestSecureBootPerFamily`)
- [x] Bash syntax check on `runner-image-provision.sh`
- [ ] Smoke-test new image: fresh GPU VM with
`--no-shielded-secure-boot` from `gha-runner-gpu` family, `nvidia-smi`
works at boot
- [ ] PR in `python-audio-separator` triggers all 3 GPU integration
jobs, all green

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 00:27:45 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 86aa4923b5 chore(infra): remove sendgrid-api-key from Pulumi secrets (#784)
## Summary

Follow-up cleanup to PR #779 (SendGrid → Postmark migration). The GCP
\`sendgrid-api-key\` Secret + all its versions have been deleted via
\`pulumi up --target\`; this PR removes the corresponding entry from
\`secret_names\` so Pulumi code matches state.

Also deleted: \`SENDGRID_API_KEY\` GitHub Actions secret (both org-level
and karaoke-gen repo-level).

## Pulumi already applied
\`pulumi up --target gcp:secretmanager/secret:Secret::sendgrid-api-key\`
already run; resource is gone from Pulumi state and \`gcloud secrets
describe sendgrid-api-key\` returns NOT_FOUND.

@coderabbitai ignore

## Test plan
- [ ] CI green
- [ ] No revisions reference \`sendgrid-api-key\` (already verified —
\`SENDGRID_API_KEY\` not mounted on \`karaoke-backend-00788-xk2\`)

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 00:27:03 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 a45798bb4d fix: remove SendGrid leftovers; consolidate on Postmark (#779)
## Summary
- Fixes the failing e2e-daily notification job ([run
#25983930960](https://github.com/nomadkaraoke/karaoke-gen/actions/runs/25983930960/job/76378786060))
which still used \`smtp.sendgrid.net\` — SendGrid was cancelled ~3 weeks
ago
- Drops the \`sendgrid\` Python dep, removes \`SendGridEmailProvider\`,
simplifies provider selection in \`email_service.py\`
- Removes \`SENDGRID_API_KEY\` env bindings from Pulumi
(gdrive-validator Cloud Function + video Cloud Run Job) and from
ci.yml's Cloud Run \`--set-secrets\`
- \`sendgrid-api-key\` Secret resource intentionally kept in
\`infrastructure/modules/secrets.py\` with a "delete manually" marker so
an unrelated \`pulumi up\` doesn't destroy the live secret + versions
- Version bumped 0.174.10 → 0.174.11

## Pulumi applied
\`pulumi up --target\` already run locally with the two affected
resources (video-encoding-job + gdrive-validator-function). PR #776's
runner-manager state intentionally untouched.

@coderabbitai ignore

## Test plan
- [x] Full backend test suite (3178 tests) passes locally
- [x] CodeRabbit local review: no findings
- [x] Pulumi up applied locally (clean)
- [ ] CI green on this PR
- [ ] After merge: e2e-daily.yml notification job should pass on next
scheduled run
- [ ] Verify gdrive-validator function still emails on next post-job
trigger

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 23:40:23 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 75134249ff chore(infra): Phase 4 — remove 7 legacy github-runner VMs (~$238/mo saving) (#780)
## Summary

- Concludes the ephemeral GHA runner migration. The dispatcher Cloud
Function (`github-runner-manager`, `RUNNER_MODE=ephemeral`) has been
creating fresh single-use VMs via JIT registration since PR #776 — the
legacy long-lived `github-runner-{1,2,3}`, `github-build-runner`, and
`github-gpu-runner-{1,2,3}` VMs and their always-billed 200GB pd-ssd
boot disks are no longer needed.
- Removed the `create_github_runners(...)`, `create_build_runner(...)`,
`create_gpu_runners(...)` calls from `infrastructure/__main__.py` plus
their three `pulumi.export` lines. Kept the Cloud NAT (ephemeral VMs
still need it for outbound) and the runner manager itself.
- **Already applied in production** — 7 VMs deleted, 7 boot disks
auto-deleted, Pulumi state refreshed. CI re-running this branch will be
a Pulumi no-op for the runner resources.

## Cost saving

**$238/mo** (7 × 200GB pd-ssd at $0.17/GB/mo). Ephemeral VM boot disks
(pd-balanced, ~30 min/job, ~30 jobs/mo typical) cost a few $/mo.

## How the apply was done

Pulumi `up --target` doesn't process deletes for resources removed from
the program, and `destroy --target` insisted on tearing down the
dispatcher function too via implicit dependents. The cleanest scoped
path was:

1. `gcloud compute instances delete` for the 7 VMs (boot disks
auto-deleted via `auto_delete=True`).
2. `pulumi refresh --target ...` for each instance URN to sync state.

This avoided disturbing the in-flight `sendgrid→postmark` Pulumi drift
from PR #779 (which is the same agent's other PR — both applied targeted
Pulumi locally before merge).

## Verification

```
$ gcloud compute instances list --filter="name~'github-(runner|gpu|build)'" --project=nomadkaraoke
(empty)
$ gcloud compute disks list --filter="name~'github-(runner|gpu|build)'" --project=nomadkaraoke
(empty)
$ curl -s https://api.nomadkaraoke.com/api/health/detailed | jq .version
"0.174.11"   # the PR #776 deploy ran on an ephemeral build runner end-to-end
```

## Follow-ups (separate PRs)

- **GPU image broken** — NVIDIA kernel module fails to load on fresh
ephemeral VM boots (`nvidia-persistenced` fails, `/dev/nvidia*` absent).
Needs a systemd boot-time DKMS rebuild service. GPU CI is broken until
then; last `python-audio-separator` integration run was 2026-04-20, so
not blocking active work.
- **Dead code cleanup** — `start_runners` /
`check_and_stop_idle_runners` / `RUNNER_MODE` branching in
`infrastructure/functions/runner_manager/main.py` is now unreachable.
- **Alert notification channels** — the `GHA Runner Dispatcher - Create
Failures` policy fired during today's cutover bug but went nowhere
because no notification channels are attached project-wide. Worth wiring
up Discord/email.

## Test plan

- [x] `pytest test_ephemeral.py` — 26 passed (no logic changed in
dispatcher)
- [x] `pulumi preview` shows the runner resources are out of state (in
sync with reality)
- [x] Prod is healthy on the version that deployed via the ephemeral
build runner

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 23:06:21 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 424b908d71 fix(runner-dispatcher): omit TERMINATE for e2 families (unblocks ephemeral cutover) (#776)
## Summary

Fixes three cutover bugs that left the ephemeral runner dispatcher
silently broken since 2026-05-17T04:56Z:

1. **`on_host_maintenance="TERMINATE"` set unconditionally** — e2
machine types reject TERMINATE unless preemptible, so 100% of
general/build VM creates failed. Fix: only set TERMINATE on GPU (n1)
families where it's required because attached GPUs can't live-migrate. 3
regression tests added in `test_ephemeral.py`.
2. **GPU `disk_size_gb=150` but image is 200GB** — GCE rejects boot
disks smaller than the source image. Fix: raise GPU disk to 200GB.
3. **Runner user has no passwordless sudo** — workflow steps like `sudo
apt-get install -y google-cloud-cli-firestore-emulator`
(backend-emulator-tests) and `sudo apt-get install -y ffmpeg`
(package-*, GPU integration tests) failed with "a terminal is required
to read the password". The legacy GHA runner VMs had NOPASSWD sudo. Fix:
add `/etc/sudoers.d/runner` in the image provision script.

Fixes 1 + 2 are dispatcher code (already applied via `pulumi up --target
...:runner-manager-source ...:runner-manager-function` from this
branch). Fix 3 requires a new image build (triggered:
build-runner-images.yml on this branch).

## Why the trivial file touches

`backend/main.py` and `karaoke_gen/__init__.py` carry one-line comments
to flip the `backend` and `package` `dorny/paths-filter` outputs so this
PR exercises **all five PR-triggered self-hosted jobs** end-to-end on
ephemeral runners. Verification PR (paired):
nomadkaraoke/python-audio-separator#286.

## Test plan

- [x] `pytest test_ephemeral.py` — 26 passed locally (3 new scheduling
tests)
- [x] Pulumi applied locally (both iterations, function update verified)
- [x] First ephemeral general VM create succeeded (4 RUNNING; previously
100% failure)
- [ ] Image rebuild completes for general+build+gpu with new sudo
provision
- [ ] PR CI passes with all 5 self-hosted jobs running on the new image
- [ ] python-audio-separator#286 GPU integration tests pass on the new
GPU image
- [ ] After merge: `deploy-backend` succeeds on ephemeral build runner;
prod /api/health/detailed reports new version
- [ ] Phase 4 decommission of 7 legacy VMs+disks (separate PR, ~$220/mo
saving)

## Context

- `karaoke-gen/docs/EPHEMERAL-GHA-RUNNERS.md`
- `docs/archive/2026-05-16-ephemeral-gha-runners-plan.md` (workspace)
- Memory: `project_cost_sprint_may2026.md`

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 22:42:01 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 241ad41096 docs: GCP cost reduction sprint recap (2026-05-16/17) (#775)
## Summary

Comprehensive record of the cost-reduction sprint executed across
2026-05-16/17 covering all repos and the workspace-level billing
investigation.

Captures:
- Baseline ($840/30d gross spend, $4.7k of GFS credits at risk of
expiring unused before 2026-09-19)
- 7 cost-driver findings — secret-version sprawl on 3 OAuth secrets,
7×200GB pd-ssd boot disks on idle runner VMs, divebar-sync `set -e`
regression that broke auto-shutdown, phantom Network Intelligence Center
charges, deploy-backend's real surface, the flacfetch SSH/guest-agent
dependency, and the ADC guardrail incident
- All shipped changes across `karaoke-gen` (#764) and `flacfetch` (#26,
#27) plus the parallel ephemeral-GHA-runner work (#765-#774, runbook in
`docs/EPHEMERAL-GHA-RUNNERS.md`)
- ~$305/mo projected saving once Phase 4 lands 2026-05-24
- 7 lessons learned for future sessions

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

@coderabbitai ignore

## Test plan

- [x] Markdown renders
- [x] All referenced PR numbers / file paths verified
- [x] Cross-references to existing docs (`EPHEMERAL-GHA-RUNNERS.md`,
`2026-05-16-ephemeral-gha-runners-plan.md`, March 2026 cost-reduction
docs) confirmed

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 01:12:54 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 bdc37b3b70 chore(infra): record runnerMode=ephemeral in Pulumi.prod.yaml (#774)
Syncs in-git stack config with deployed state post-cutover. No
behavioural change.

@coderabbitai ignore

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 01:02:31 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 c728b781ac docs(runner): cutover status + 1-week soak followup + lessons learned (#773)
## Summary
Updates the EPHEMERAL-GHA-RUNNERS runbook with three sections so the
operator can refer back to it during the 1-week soak and know exactly
what to do at the end:

1. **STATUS — 2026-05-17** — cutover went live at 04:56Z, current image
names, self-serve status command, serial-console tail command.
2. **Followups (1 week from cutover — 2026-05-24)** — exact verification
commands, Phase 4 decommission steps (the destructive bit that unlocks
~\$220/mo), rollback path.
3. **Iteration-cost lessons learned** — 8 hard-won gotchas from this
session covering serial-console visibility, IAP unreliability, gh-watch
rate limits, Python-from-source fragility, apt-daily race, disk-name
autoselect, Pulumi function-source generation pin, smoke-as-runner-user.

Docs-only change, no version bump.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 01:00:26 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 dd2189548d fix(runner-images): pacify apt-daily race on fresh Debian VMs (#772)
## Summary
The build-variant rebuild died at the GHA runner's
\`installdependencies.sh\` with an apt lock conflict:
\`\`\`
E: Could not get lock /var/lib/apt/lists/lock. It is held by process N
(apt-get)
'apt-get' failed with exit code '0'
Can't install dotnet core dependencies.
\`\`\`
Same code path as general (which won the race and succeeded). Just
timing relative to Debian's background \`apt-daily.service\`.

## Fix
Stop + disable + mask \`apt-daily.{service,timer}\` and
\`apt-daily-upgrade.{service,timer}\` early in the script, then wait up
to 2 min for any in-flight apt-get to release its lock. After that all
subsequent \`apt-get\` calls (including the runner's bundled installer)
have exclusive access.

## Test plan
- [x] bash -n clean
- [ ] Rebuild build variant: \`gh workflow run build-runner-images.yml
-f variants=build\`. The general rebuild from the previous run already
succeeded; only build needs retry.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-17 00:30:51 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 2399248c06 fix(runner-images): use pyenv for GPU variant too; drop hand-rolled Python build (#771)
## Summary
After 3 unsuccessful iterations trying to compile Python 3.13 from
source on the GPU image-build VM, switch to pyenv (which has worked
end-to-end for general/build all along).

## Failure history
| Iteration | Approach | Symptom |
|---|---|---|
| PR #765 (orig) | 3.13.0 + \`--with-ensurepip=install\` | Install-time
ensurepip crash (FileNotFoundError on _WHEEL_PKG_DIR) |
| PR #768 | 3.13.0 + \`--with-ensurepip=no\` + get-pip.py | get-pip.py
crashed on freshly-built python3.13 |
| PR #770 | 3.13.2 + \`--with-ensurepip=install\` w/o
\`--enable-optimizations\` | \`_socket\` C extension broken;
\`SystemError: error return without exception set\` from any urllib
import |

## Decision
Stop tilting at the hand-rolled-build windmill. pyenv-installed Python
3.13.0 has worked successfully for both general and build variants in
the latest runs (READY in ~5 min). The original "pyenv unreliable on
Debian 12 with CUDA installed" comment was speculation about *runtime*
conflicts — image-build VMs install CUDA but no CI job runs against CUDA
on the build VM itself, so the speculated conflict can't materialize.

Unify all three variants on pyenv. Bonus cleanup: install Poetry to
/opt/poetry on every variant (not just GPU) so the runner user can reach
it.

## Test plan
- [x] bash -n clean
- [ ] Re-trigger only the gpu variant: \`gh workflow run
build-runner-images.yml -f variants=gpu\` (general+build images already
exist and READY from the previous run).

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 23:36:29 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 659ba1ef7b fix(runner-images): image-create disk name + GPU python 3.13.2 (#770)
## Summary
Two follow-up fixes after PR #769's visibility update made it possible
to see exactly what was failing.

## What broke
1. **general/build PROVISIONED successfully** (READY marker written at
01:04 and 01:02), then the workflow's \`Create image\` step died with:
   \`\`\`
ERROR: (gcloud.compute.images.create) Invalid value for
[--source-disk-zone]:
You cannot specify [--source-disk-zone] unless you are specifying
[--source-disk].
   \`\`\`
The disk-name extraction format string returned empty. I'm using
auto-named boot disks (same as VM name), so just use \`\$VM\` directly.

2. **GPU got further than before** — phase: python 3.13 — but
\`get-pip.py | python3.13\` exited non-zero at line 197. PR #768's
workaround for the 3.13.0 install-time ensurepip bug introduced a new
failure on the bootstrap. Switch to **3.13.2** which fixes the
underlying bug, restore \`--with-ensurepip=install\`, drop the
bootstrap. Also drop \`--enable-optimizations\` (PGO runs full test
suite, can produce half-broken binaries on transient test failures).

## Plus
Wait step's failure-context dump now captures **40 lines BEFORE** the
FAILED marker (not just 5 after) so the actual error output is in the
GHA log.

## Test plan
- [x] bash + yaml syntax clean
- [ ] Re-trigger build after merge. Expected outcome: all 3 variants
build successfully end-to-end and produce images in the
\`gha-runner-{general,build,gpu}\` families.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 21:20:00 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 ce270052ff fix(runner-images): stream provisioner log to GCE serial console (eliminate SSH dependency) (#769)
## Problem
Three previous iterations of the image-build workflow failed silently.
Every diagnostic channel depended on \`gcloud compute ssh
--tunnel-through-iap\` and IAP tunneling was unreliable enough that:
- The wait step both false-positived ("Image ready" at 4 min on a 25-min
provisioner) AND false-timed-out (no output for 75 min)
- Manual SSH for debugging was equally broken — \`Connection closed by
UNKNOWN port 65535\` repeatedly

Net effect: 25–60 minute iteration loops with no actual visibility into
the provisioner's state.

## Fix
Eliminate SSH from the diagnostic path entirely:

1. **Provisioner streams to /dev/ttyS0** (GCE serial console). Readable
via \`gcloud compute instances get-serial-port-output --port=1\` with
zero SSH/IAP dependency.
2. **ERR trap + phase checkpoints.** Any non-zero exit prints \`###
runner-image-provision FAILED rc=N line=L cmd=...\` to the console. A
\`ck()\` helper marks each major phase (apt base, docker, python,
node+java, ffmpeg, poetry+gcloud, runner user, runner binary, build
pre-pull, gpu models, tool cache, cleanup, READY).
3. **Workflow wait step polls serial console.** Looks for
\`runner-image: READY:\` for success and \`runner-image-provision
FAILED\` for fast-fail. Also streams new console lines into the GHA log
on every poll so the operator sees live progress.

## Test plan
- [x] \`bash -n\` + yaml lint clean
- [ ] Re-trigger \`build-runner-images.yml\` after merge. When a variant
dies, we'll see exactly which phase failed.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 20:56:45 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 163fa95db8 fix(runner-images): bypass Python 3.13.0 install-time ensurepip crash (#768)
## Summary
Third hotfix in the runner-image series. The GPU build VM dies ~18 min
in with a Python 3.13.0 install-time crash when ensurepip runs as part
of \`make install\`.

## Root cause
\`./configure --with-ensurepip=install\` causes the Makefile to run
\`./python -E -m ensurepip --root=/\` during install, which crashes on a
missing \`_WHEEL_PKG_DIR\` path:

\`\`\`
FileNotFoundError: [Errno 2] No such file or directory
  File ".../pathlib/_local.py", line 670, in resolve
    return self.with_segments(os.path.realpath(self, strict=strict))
\`\`\`

The general/build variants use pyenv, which handles ensurepip
differently and isn't affected.

## Fix
\`--with-ensurepip=no\` + bootstrap pip from \`get-pip.py\` after \`make
install\`. Same end state, no install-time crash.

## Test plan
- [x] \`bash -n\` clean
- [ ] Re-trigger gpu build after merge

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 20:45:21 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 7f46bbc0af fix(runner-images): trust file content not IAP-tunnel ssh exit codes (#767)
## Summary
Hotfix for the build-runner-images workflow, observed failing on the
first real run after PR #766's variant-resolution fix.

## Root cause
Two related defects in the **Wait for provisioning to complete** step:

1. **False-positive readiness.** The general-image job detected `test -f
/opt/runner-image-ready` at attempt 8 (~4 min in) on a provisioner that
takes 25+ min. \`gcloud compute ssh --command='test -f ...'\` returned
exit 0 even though the remote test had nothing to test against. Most
likely an IAP-tunnel race where the SSH session closes before the remote
command completes, and the local exit code defaults to 0.

2. **Diagnostic SSH allowed to fail the step.** After "marker detected,"
a second SSH was run to `cat` the file. That one hit a real IAP error
(`destination read failed`) and `set -e` killed the step. So even if the
first marker check were trustworthy, this second hop would still flake
the build out.

## Fix
- Use `cat` instead of `test -f` for readiness check; require the output
to start with a 4-digit year (the provisioner writes an ISO-8601
timestamp). Empty stdout from a flaky SSH = "not ready, retry."
- Drop the second SSH — fold its diagnostic value into the cat above.
- Belt-and-suspenders `2>&1 || true` on the timeout-path diagnostic.

## Test plan
- [x] YAML lint clean
- [ ] Re-trigger \`build-runner-images.yml\` after merge

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 18:46:10 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 f270a88739 fix(runner-images): silent-fail when VARIANT is unresolved (#766)
## Summary
Hotfix for PR #765. The image-build workflow triggered after merge but
all three build VMs sat idle — the provisioner script's variant check
ran *before* the log redirect and silently exited when no positional arg
was passed.

## Root cause
When run as a GCE metadata startup-script (the production path), the
provisioner gets no argument. The fallback was
\`\$RUNNER_IMAGE_VARIANT\` which the workflow never set. Result: \`exit
2\` before \`exec > >(tee /var/log/...)\` — no log, no marker, no
diagnostic. The GHA workflow polled for \`/opt/runner-image-ready\` for
the full 75-minute timeout.

## Fix
1. Move the tee redirect to be the first action — every failure path now
leaves a trace in \`/var/log/runner-image-provision.log\`.
2. Resolve VARIANT from a third source: GCE instance metadata key
\`image-variant\` (which \`build-runner-images.yml\` already sets when
creating the VM). Priority: \`\$1\` → \`\$RUNNER_IMAGE_VARIANT\` →
metadata.

## Test plan
- [x] \`bash -n\` clean
- [ ] Re-trigger \`build-runner-images.yml\` after merge — expect
\`general\`/\`build\` to complete in ~25 min, \`gpu\` in ~60 min
- [ ] Smoke-test each image (script staged at
\`/tmp/smoke-test-runner-images.sh\`)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 18:27:44 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 bf5c9abdd7 feat(runners): ephemeral GHA runner dispatcher behind RUNNER_MODE flag (#765)
## Summary
- Implements Phases 1, 2, and 5 of the ephemeral GHA runner plan
([`docs/archive/2026-05-16-ephemeral-gha-runners-plan.md`](docs/archive/2026-05-16-ephemeral-gha-runners-plan.md)
at the workspace root). Target saving when fully cut over: **~\$220/mo**
(eliminates 7×200GB always-billed pd-ssd boot disks).
- **Default behaviour unchanged** — code lands with
`RUNNER_MODE=legacy`. Flipping to `ephemeral` is a Pulumi config +
targeted update, reversible in ~2 minutes.
- Operator runbook for the cutover at
[`docs/EPHEMERAL-GHA-RUNNERS.md`](docs/EPHEMERAL-GHA-RUNNERS.md)
including verification steps, rollback, and known gotchas.

## What's in this PR

**Phase 1 — image build infrastructure**
- `infrastructure/scripts/runner-image-provision.sh` — unified
provisioner with `general` / `build` / `gpu` variants (extracts the
existing `github_runner.sh` and `github_runner_gpu.sh` logic so it runs
at image-build time, not per-VM boot).
- `.github/workflows/build-runner-images.yml` — monthly cron + manual
trigger. Builds via temporary GCE VMs, snapshots to GCE image families
`gha-runner-{general,build,gpu}`, deprecates all but the newest 3 per
family.

**Phase 2 — dispatcher rewrite (behind a flag)**
- `infrastructure/functions/runner_manager/ephemeral.py` — picks image
family from job labels, mints a GitHub JIT runner config,
`compute.instances.insert` with auto-delete boot disk, falls back to
`us-east4-c` on `ZONE_RESOURCE_POOL_EXHAUSTED`. Orphan-cleanup deletes
VMs whose runner registration is gone or whose uptime exceeded 2h, and
de-registers zombie runners.
- `infrastructure/functions/runner_manager/main.py` — routes on
`RUNNER_MODE`. Legacy path untouched.
- `infrastructure/modules/runner_manager.py` — exposes `RUNNER_MODE` via
Pulumi config (`karaoke-gen-infrastructure:runnerMode`).
- 20 new unit tests in `test_ephemeral.py` (label resolution, JIT mint,
zone fallback, orphan reconciliation, zombie cleanup).

**Phase 5 — observability**
- 2 log-based metrics (`runner_dispatcher/create_failures`,
`runner_dispatcher/orphan_kills`).
- 2 alert policies: any create failure in 10 min; any ephemeral VM
uptime > 2h (orphan cleanup escape).

## Not in this PR (handed off)
- Triggering the image-build workflow for the first time (needs branch
merged first).
- `pulumi up` — `GOOGLE_APPLICATION_CREDENTIALS` points at
`claude-readonly@` per the workspace's operational guardrail; couldn't
apply from this session. Targeted apply commands are in the runbook.
Note that this repo's CI doesn't auto-apply Pulumi (see comment in
`ci.yml`).
- Phase 3 cutover (`pulumi config set runnerMode ephemeral` + test PR +
1-week soak).
- Phase 4 destructive decommission of the 7 legacy VMs (requires soak
first).

## Test plan
- [ ] `cd infrastructure/functions/runner_manager && pytest -v` — 20/20
new tests pass; 25/26 legacy tests pass (1 pre-existing failure
documented in the runbook).
- [ ] `cd infrastructure && pulumi preview --diff` — expect 4 resource
changes from this PR + 5 creates (log metrics + alerts).
- [ ] `pulumi up --target ...:runner-manager-source --target
...:runner-manager-function --target ...:runner-dispatcher-failures
--target ...:runner-dispatcher-orphan-kills --target
...:runner-dispatcher-failures-alert --target
...:runner-dispatcher-long-lived-vm-alert` — applies dispatcher +
monitoring.
- [ ] `gh workflow run build-runner-images.yml -f variants=general` —
produces first image, ~25 min.
- [ ] Smoke test launching a one-off VM from
`image-family=gha-runner-general` (runbook step).
- [ ] Repeat image build for `build` and `gpu` variants.
- [ ] Phase 3 cutover when ready (see runbook).

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 17:19:09 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 53be57fe60 fix: trim baseline GCP cost (secret retention + divebar shutdown) (#764)
## Summary

Two cost-reduction fixes bundled together:

1. **Secret version retention**
(`backend/services/credential_manager.py`): `dropbox-oauth-credentials`
had accumulated 1191 enabled versions costing ~$65/mo in replica
storage. Each refresh calls `add_secret_version` but never destroys the
prior version. Same pattern for the YouTube/GDrive secrets refreshed via
`_update_google_credentials`. Add a small
`_destroy_old_secret_versions(keep=5)` helper called after every
`add_secret_version` in this module. Errors swallowed so a prune failure
cannot break credential refresh.

2. **Divebar-sync auto-shutdown**
(`infrastructure/compute/startup_scripts/divebar_sync.sh`): VM was
running 24/7 for 45 days since 2026-03-31 — burning ~$15/mo of idle
compute. Root cause: the sync Python process crashed with a memory
error, and `set -euo pipefail` aborted the script before `shutdown -h
now` could execute. Switched to a `trap` on EXIT so shutdown runs no
matter how the script terminates. The scheduler `divebar-sync-vm-daily`
is currently **paused** — resume it after CI deploys this fix.

Estimated total savings: ~$80/mo.

The historical version backlog has already been manually cleaned:
`dropbox-oauth-credentials`, `youtube-cookies`, `spotify-oauth-token`
are all at 5 versions. This PR prevents regrowth.

@coderabbitai ignore

## Test plan

- [x] Unit tests added for `_destroy_old_secret_versions`
(destroy-beyond-keep, swallow-list-errors,
swallow-per-version-destroy-errors, no-op-when-below-keep)
- [x] Full `test_credential_manager.py` passes (31 tests)
- [x] Full backend suite passes (3187 passed, 36 skipped)
- [ ] After deploy: verify the three secrets stay at ~5 versions over
the next refresh cycle
- [ ] After deploy: resume `divebar-sync-vm-daily` scheduler and confirm
next run auto-shuts-down VM

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 16:43:21 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 e41d6a6860 Show bot-block message instead of misleading age-restriction (#763)
## Summary

Companion to flacfetch [PR
#25](https://github.com/nomadkaraoke/flacfetch/pull/25) (merged,
deployed). When flacfetch returns the new `is_bot_blocked: true` flag,
surface a clear user message explaining YouTube's bot challenge is
temporary — instead of falling through to the misleading "This YouTube
video is age-restricted" response.

## Test plan

- [x] Backend tests for affected paths: 211 pass
- [x] flacfetch 0.20.0 (with the new field) is already running on the
prod VM — verified end-to-end that `is_bot_blocked: true` is returned
for bot-challenged videos.
- [ ] CI green

## Notes

- Forward-compatible: if `is_bot_blocked` is absent (older flacfetch),
`availability.get()` returns falsy and the existing fallthrough kicks
in.
- The four pre-existing elif branches (geo / private / removed / age)
are also hardcoded English. Migrating them all to the backend `t()`
helper would be scope creep; this PR matches the existing pattern.

@coderabbitai ignore

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 16:15:06 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 64301db5d2 fix(audio-download): make worker idempotent, surface auto-retry to user (#762)
## Summary

Fixes the race condition behind job `8a9c74ff` where a single user Retry
click caused the `audio-download-job` Cloud Run Job to run 3 times,
producing a visible "Audio download failed: Invalid state transition for
job ...: downloading -> JobStatus.DOWNLOADING" error AND
double-triggering downstream L4 GPU separation + lyrics transcription
jobs.

Root cause: the user clicked Retry inside the ~75s window between Cloud
Run's failed task and its automatic task-attempt retry. Two parallel
executions raced on job state.

## Changes

**Backend**
- `audio_download_worker.py`:
- `DOWNLOAD_ALREADY_DONE_STATUSES` idempotency guard — return success
early when status is already past `DOWNLOADING_AUDIO`, instead of
re-downloading and crashing on a redundant state transition.
- `_mark_retry_pending_if_attempts_remain` writes
`state_data.cloud_run_retry_pending = { expires_at }` when
`CLOUD_RUN_TASK_ATTEMPT < CLOUD_RUN_MAX_RETRIES` (2). Final attempt
explicitly clears any stale marker.
- `_clear_retry_pending_and_error` clears the marker and `error_message`
on successful download so the dashboard stops showing a resolved
transient failure.
- `jobs.py` `/retry` endpoint returns **409** when
`cloud_run_retry_pending` is active, preventing duplicate parallel
executions.
- `job_manager.py` error-message rendering fix: f-strings now use
`.value` consistently so we don't get the misleading `downloading ->
JobStatus.DOWNLOADING` artifact.
- `cloud_run_retry_pending` added to `SUMMARY_FIELD_PATHS` and the
dashboard prune allowlist.

**Frontend**
- `isAutoRetryPending(job)` helper in `lib/job-status.ts`.
- `JobActions`: when auto-retry is pending, hide the manual Retry button
and show "Retrying automatically…" with a spinner. Falls back to Retry
once the window expires.
- `JobCard`: don't render the `error_message` banner on completed jobs
(covers legacy data where a transient failure left a stale error
string).
- New i18n keys auto-translated to all 33 locales.

**Docs**
- `LESSONS-LEARNED.md`: Cloud Run Job retry race pattern + idempotency
defenses.

## Testing

- [x] Backend unit tests pass: 3183 passed, 36 skipped (10 new tests for
this work)
- [x] Frontend Jest tests pass: 110 passed in affected suites (8 new
tests)
- [x] TDD throughout — failing test before each implementation change

Tests added cover:
- Worker idempotency across 8 post-download statuses (`DOWNLOADING`,
`AWAITING_AUDIO_EDIT`, `TRANSCRIBING`, ... `COMPLETE`)
- Retry-pending marker: written on non-final attempt, cleared on final
attempt, cleared on success
- `_is_auto_retry_pending` helper edge cases (missing / past / future /
malformed)
- Frontend: indicator shows during window, falls back to Retry after
expiry, JobCard hides stale error on complete

## Review

- [x] Local code review completed (CodeRabbit CLI auth issue →
`feature-dev:code-reviewer` agent fallback)
- [x] Should-fix finding addressed: stale marker after final attempt
blocked manual retry for ~3 min (commit `d87cd86`)
- [ ] Optional finding deferred: frontend doesn't auto-re-render at
exact expiry time (dashboard polls, self-heals)

## Infrastructure

No Pulumi changes. `audio-download-job` `max_retries=2` retained —
automatic recovery from transient Spotify timeouts still works, and the
new idempotency guard makes retries safe.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-16 15:02:36 -04:00
Andrew Beveridge ☄️ 37a6f12631 fix(idle-shutdown): check multi-zone fallback VMs (#758)
## Summary

The encoding-worker idle-shutdown Cloud Function only iterated
\`[primary_vm, secondary_vm]\` in the default zone — capacity-fallback
VMs in alternate zones (\`-a\`/\`-b\`) were never checked, so a fallback
started during a capacity event stayed RUNNING indefinitely after the
event resolved.

Observed 2026-05-07: \`encoding-worker-fallback-a\` in \`us-central1-a\`
ran for 13+ hours idle (~\$15 cost) before manual intervention.

## Changes

- **\`infrastructure/functions/encoding_worker_idle/main.py\`**:
- Read \`ENCODING_WORKER_FALLBACK_VMS\` env (same secret the backend
uses for capacity failover) and iterate fallbacks alongside
primary/secondary.
- Threaded \`zone\` through \`get_vm_status\` / \`get_vm_ip\` /
\`stop_vm\` so cross-zone shutdowns work.
- Keep-alive-on-recent-activity now follows \`active_override_vm\` (the
currently-routed VM during a capacity event), not always the primary.
Otherwise an active capacity-fallback would get killed while serving
real traffic.
- **\`infrastructure/modules/encoding_worker_manager.py\`** (Pulumi):
- Wire the \`encoding-worker-fallback-vms\` secret into the function via
\`secret_environment_variables\`.
- New \`gcp.secretmanager.SecretIamMember\` binding so the function's SA
can read that secret.
- **\`infrastructure/functions/encoding_worker_idle/deploy.sh\`** (new):
uploads source zip and triggers function rebuild. Was missing for this
function (other functions all have one); matches the pattern from
\`backup_to_aws/deploy.sh\` etc.
-
**\`infrastructure/functions/encoding_worker_idle/test_idle_shutdown.py\`**:
9 new tests:
  - Idle fallback gets stopped (in its own zone)
- Active-override fallback kept alive on recent activity (primary stops
instead)
  - Fallback with active jobs not stopped
  - Graceful behavior when env var missing or malformed JSON
  - 4 unit tests on the \`_parse_fallback_vms\` helper
  - All 18 tests pass.

## Already applied to prod

I ran \`pulumi up\` and \`deploy.sh\` from this branch to apply the fix.
CI's pulumi-up will be a no-op on merge.

**End-to-end verification:**
1. Started \`encoding-worker-fallback-a\` manually (RUNNING)
2. Triggered \`encoding-worker-idle-check\` scheduler
3. fallback-a went to STOPPING within ~20s ✅

Before fix: fallback-a would have stayed RUNNING (old code never checked
fallbacks).
After fix: fallback gets stopped on the next 5-min idle sweep.

## Test plan

- [x] 18 unit tests pass locally (9 existing + 9 new)
- [x] \`pulumi preview\`: 1 created (secret IAM), 1 updated (function
with secret env var), 263 unchanged
- [x] \`pulumi up\` applied successfully
- [x] \`deploy.sh\` deployed new function code
- [x] Manually verified: fallback-a started → triggered idle-check →
stopped

@coderabbitai ignore
2026-05-07 11:33:13 -04:00
Andrew Beveridge ☄️ db42594740 feat(encoding-worker): persist job state to Firestore (hardening 2/3) (#757)
## Summary

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

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

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

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

## Changes

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

## ⚠ Deploy note

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

## Test plan

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

@coderabbitai ignore
2026-05-06 22:46:00 -04:00
Andrew Beveridge ☄️ 9b903d95d3 feat(encoding): per-URL submission throttle (hardening 3/3) (#756)
## Summary

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

The encoding worker has a 4-thread \`ThreadPoolExecutor\`. Submitting 7
renders simultaneously to fallback-a (May 6 incident) caused
\`Connection reset by peer\` mid-encode on the 5th-7th jobs.

> Rebased to target \`main\` directly (was originally stacked on item 2
#757). Item 3 is independent of item 2 — landing this first is fine.
Item 2 (#757) requires \`pulumi up\` for IAM and can land separately.

## Changes

- **\`backend/services/encoding_service.py\`**:
- New \`_submission_slot(url, job_id)\` async context manager: per-URL
\`asyncio.Semaphore\` capped at 3 concurrent ops (configurable via
\`ENCODING_SUBMISSION_CONCURRENCY\` env var).
  - Lazy semaphore creation — bind to the right event loop on first use.
- \`encode_videos\` and \`render_video_on_gce\` now hold the slot for
the entire submit + wait_for_completion cycle.
- **\`pyproject.toml\`**: 0.174.4 → 0.174.5

## Design notes

- **Per-Cloud-Run-instance, not global.** With \`max-instances=20\` each
contributing 3, a worker VM can still see 60 concurrent in the absolute
worst case. But the storm pattern from May 6 was localized — one Cloud
Run instance retrying 7 jobs against fallback-a in parallel. The local
cap kills that pattern.
- **Per-URL, not global per service.** Primary (\`-c\`) and fallback
(\`-a\`, \`-b\`) get separate semaphores so multi-zone fallback isn't
serialized.
- **Slot held through wait.** The worker is genuinely busy with that
job's encode until the poll says complete/failed. Releasing earlier just
lets us submit work the worker can't run.
- **Cached responses release immediately.** \`status: \"cached\"\`
returns from the wrapped block before \`wait_for_completion\` so cached
re-submissions don't unnecessarily serialize.

## Test plan

- [x] 7 new tests in \`test_encoding_service_throttle.py\` (passed
locally)
- [x] All 45 \`test_encoding_service*\` tests pass
- [ ] Prod verification: monitor next time multi-zone fallback engages —
concurrent-jobs-per-VM should now be ≤3 from each Cloud Run instance, no
more \`Connection reset by peer\` log entries.

@coderabbitai ignore
2026-05-06 22:33:29 -04:00
Andrew Beveridge ☄️ 439742a175 feat(render): park in-flight render jobs on Cloud Run shutdown (hardening 1/3) (#754)
## Summary

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

When Cloud Run autoscales an instance down (or rolls a deployment)
mid-render, the BackgroundTask was killed without writing failure state.
The job sat at \`rendering_video\` indefinitely until an operator
manually retried.

## Changes

- **`render_video_worker.py`**: registers/unregisters with
\`worker_registry\` (try/finally on the outer scope so it fires even on
unexpected exceptions). New \`park_active_render_jobs_for_shutdown()\`
helper transitions any in-flight render jobs to
\`RENDER_PENDING_CAPACITY\` (last_code: \`WORKER_SHUTDOWN\`) before
exit. Race-safe: skips jobs that have moved past \`RENDERING_VIDEO\`
between the registry snapshot and the per-job park.
- **`main.py`**: lifespan shutdown waits 480s (down from 600s) then runs
the park pass — 120s headroom for Firestore writes before SIGKILL. Cloud
Run gen2 default termination grace is 600s.
- **`docs/TROUBLESHOOTING.md`**: updated the \"Job stuck in
\`rendering_video\`\" runbook to describe the new self-recovery
behaviour.
- **`docs/archive/2026-05-06-capacity-resilience-session.md`**: marked
item 1 as shipped.
- **`pyproject.toml`**: 0.174.3 → 0.174.4

The auto-retry scheduler (\`/api/internal/retry-pending-render-jobs\`,
every 5 min via Cloud Scheduler) picks up parked jobs.

## Test plan

- [x] 6 new tests in \`test_render_video_worker_shutdown.py\`:
  - register on success, unregister on exception
- park transitions in-flight job to \`RENDER_PENDING_CAPACITY\` with
\`WORKER_SHUTDOWN\` code
  - race-safe skip when job moved past \`RENDERING_VIDEO\`
  - no-op when no render workers active
  - continues past per-job failures
- [x] Existing capacity-error tests
(\`test_render_video_worker_capacity.py\`) still pass —
register/unregister doesn't break the parking behaviour for actual
capacity errors.
- [ ] Prod verification: deploy → trigger a render → force a Cloud Run
revision rollover mid-render → confirm job lands in
\`render_pending_capacity\` and gets retried within 5 min. (Hard to
artificially induce SIGTERM without a real load event; will monitor next
time autoscaler scales down naturally.)

@coderabbitai ignore
2026-05-06 21:57:08 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 1d7cefbf82 docs(render): runbook + lessons for capacity-resilience work (#753)
## Summary

Documentation pass after shipping PRs #748-#752. Without these, the next
operator or agent hitting a similar render failure has to re-derive
everything from code + git history.

### What's added

1. **`docs/TROUBLESHOOTING.md`** — three new sections matching the
failure modes the system can now surface:
- *"Job stuck in `render_pending_capacity`"* — the new parked-for-retry
state, how to check attempt count, how to poke the scheduler manually
- *"Video render failed: TimeoutError()"* — regression guard; explains
the empty-error history and the markers to look for in logs
- *"Job stuck in `rendering_video` for hours"* — the Cloud
Run-killed-mid-render case (separate hardening opportunity), with manual
recovery procedure

2. **`docs/LESSONS-LEARNED.md`** — *"Encoding Worker Capacity Resilience
(May 2026)"* — the seven traps we hit in order of discovery, the
architectural summary post-fix, and the key file map. Future work starts
here.

3. **`docs/archive/2026-05-06-capacity-resilience-session.md`** — full
session arc capturing the trigger, each PR's motivation, the recovery
flow today, and known unfixed hardening items so they don't get lost.

### What's not in this PR

- The original 3-phase plan
(`docs/archive/2026-05-05-encoding-worker-capacity-resilience-plan.md`)
stays as a historical record of what was planned before #750-#752
surfaced
- Workspace-level memory
(`~/.claude/projects/-Users-andrew-Projects-nomadkaraoke/memory/`)
updated separately — outside this repo

## Test plan

- [x] No code changes — pure docs
- [x] Markdown renders correctly (links to existing files use proper
paths)
- [ ] Future-self test: a fresh agent with no session context should be
able to diagnose a `render_pending_capacity` job using only
TROUBLESHOOTING.md

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 20:57:38 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 952302f8f3 fix(render): re-resolve encoding worker URL between retry attempts (#752)
## Summary

Bug observed on job `fae3eadc` 2026-05-06: multi-zone fallback
successfully routed to fallback-a in us-central1-a — set
`active_override` in Firestore, invalidated the URL cache — but
`_request_with_retry` had already captured the original (primary, dead)
URL **before** the retry loop started, and used it for all 8 retry
attempts. Every attempt timed out, the retry loop re-raised
`TimeoutError()` (not a typed start error), and the render worker's
`except EncodingWorkerStartError` didn't catch it → job hard-failed
instead of being parked for auto-retry.

Without this fix, the scheduler's auto-retry can't actually recover a
job once the URL gets stuck on a dead VM, even though all the multi-zone
plumbing engages correctly.

## Fix

`_request_with_retry` now accepts an optional `path` parameter (e.g.
`/render-video`) and re-resolves the full URL via `_get_worker_url() +
path` on retry attempts **after** the warmup has fired. Updated all four
call sites: `submit_encoding_job`, `get_job_status`,
`submit_preview_encoding_job`, `submit_render_video_job`.

The `_health` callsite uses `aiohttp.ClientSession` directly without
`_request_with_retry`, so no change needed there.

## Trace from the affected job

```
21:15:39 Trying candidate 1/3: VM encoding-worker-b in us-central1-c (status TERMINATED)
21:15:41 Candidate encoding-worker-b in us-central1-c start failed (503), trying next candidate
21:15:41 Set active_override to encoding-worker-fallback-a in us-central1-a (capacity fallback)
21:15:41 [job:fae3eadc] Encoding worker unreachable — VM encoding-worker-fallback-a already running/starting
21:15:41 [job:fae3eadc] GCE worker connection failed (attempt 1/8): TimeoutError. Retrying in 5.0s...
21:16:17 [job:fae3eadc] GCE worker connection failed (attempt 2/8): TimeoutError. Retrying in 10.0s...
... (all 8 attempts to dead primary URL — should have hit fallback-a from attempt 2 onwards)
21:20:48 [job:fae3eadc] WORKER_END worker=render-video status=error duration=341.6s error=TimeoutError()
21:20:49 Job fae3eadc failed: Video render failed: TimeoutError()
```

After this fix, attempt 2 onwards will resolve to
`http://34.55.231.54:8080/render-video` (fallback-a) instead of the dead
primary, and the request will succeed.

## Test plan

- [x] New regression test
`test_url_reresolves_after_warmup_so_fallback_takes_effect` — first
attempt to dead URL fails, warmup updates override, second attempt
re-resolves to live URL and succeeds. Asserts both URLs were actually
requested (in order)
- [x] All 84 capacity-related tests pass locally
- [ ] After merge: monitor for any new \"TimeoutError after warmup\"
patterns — should disappear

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 18:05:09 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 b321f56568 fix(render): zone-aware readiness wait + index-free retry + fallback env on encoding job (#751)
## Summary

Three issues observed after #750 deployed and the parked jobs were
re-triggered. All blocking real renders.

### 1. `wait_for_worker_ready` looks in the wrong zone

Multi-zone fallback successfully started a VM in `us-central1-a`, but
`wait_for_worker_ready` then polled `get_vm_status` against the
manager's default zone (`us-central1-c`), got 404 (\"instance not
found\"), gave up, and the next HTTP retry hit a still-booting VM and
timed out.

```
[job:6b0bf198] Encoding worker unreachable — started VM encoding-worker-fallback-a as fallback
[job:6b0bf198] Cold-start readiness wait failed (non-fatal): NotFound: 404 ... zones/us-central1-c/instances/encoding-worker-fallback-a
[job:6b0bf198] GCE worker connection failed (attempt 1/8): TimeoutError. Retrying in 5.0s...
```

Fix: thread the candidate's `zone` through `wait_for_worker_ready` so
the VM-status poll targets the right zone. Also include zone in
`ensure_primary_running`'s return for consistency.

### 2. /retry-pending-render-jobs returns 500 (Firestore composite
index)

```
status = StatusCode.FAILED_PRECONDITION
details = "The query requires an index. ..."
```

The Cloud Scheduler-driven endpoint's query (`status == X` + `order_by
updated_at`) needs a composite index that doesn't exist. Fix: drop the
server-side `order_by`, stream by status alone (small result set), sort
in Python by `first_seen_at`. No index ceremony, matches the existing
`recover-stuck-jobs` pattern.

### 3. video-encoding-job Cloud Run Job missing
`ENCODING_WORKER_FALLBACK_VMS`

The final encoding stage runs in a Cloud Run Job (separate from the main
service). Its IaC was missing the `ENCODING_WORKER_FALLBACK_VMS` env
var, so when it hit `503 SERVICE_UNAVAILABLE` starting the primary VM in
`us-central1-c`, it couldn't fall through to alt-zone fallbacks and the
job died.

Observed for `549cdf90`, `6b0bf198`: render succeeded via fallback, then
encoding stage failed at progress 0 with:
```
Video generation failed: Encoding failed: VM encoding-worker-b start failed in us-central1-c: 503 — SERVICE UNAVAILABLE
```

Fix: add the `ENCODING_WORKER_FALLBACK_VMS` secret-mount to the Cloud
Run Job in IaC.

## Test plan

- [x] Unit: `_patch_endpoint_dependencies` no longer mocks `order_by`
chain (matches new query)
- [x] Unit: `wait_for_worker_ready` accepts `zone` parameter and threads
to `get_vm_status`
- [x] All 83 capacity-related tests pass locally
- [x] `pulumi up` applied locally — Cloud Run Job updated with new env
var (1 resource updated)
- [ ] After merge: confirm parked jobs unstick (the auto-retry endpoint
should now actually work, and the Cloud Run Job should fall through to
fallback-a/b instead of dying on 503)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 14:35:52 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 dd827c1501 fix(render): broaden multi-zone fallback, force HTTP metadata, fix retry screens-key (#750)
## Summary

Follow-up fixes after PR #748/#749 didn't fully cover failure modes
observed when the parked jobs were re-triggered. All four bugs surfaced
via Discord error alerts at 13:02 ET on 2026-05-06.

### 1. Multi-zone fallback only triggered on capacity errors

The original code only fell through to the next zone on
`EncodingWorkerCapacityError` (`ZONE_RESOURCE_POOL_EXHAUSTED`). When GCE
returned `503 SERVICE_UNAVAILABLE` from `compute.instances.start` — also
a transient backend stress signal — the typed exception was the parent
`EncodingWorkerStartError` and the loop raised immediately, skipping
fallbacks.

Fixed by broadening the catch in `ensure_any_running`,
`_warmup_encoding_worker_fallback`, `_request_with_retry`, and the
render worker's catch to handle the parent class. Capacity errors are
still preferred when raising from `ensure_any_running` (more actionable
for the user-facing message).

### 2. SSL CERTIFICATE_VERIFY_FAILED on metadata server

The new fallback VMs (us-central1-a/b) failed with:
```
SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate'))
```
…on `https://metadata.google.internal:443/...`. Root cause: google-auth
≥2.40 uses mTLS-over-HTTPS to the metadata server when
`/run/google-mds-mtls/` certs exist on the VM, which is the case on
newer GCE images. The mTLS handshake fails on these freshly-provisioned
VMs, the worker can't refresh its SA token, and every GCS read/write
fails.

Fix: set `GCE_METADATA_MTLS_MODE=none` in the encoding worker's systemd
environment file (written by `infrastructure/encoding-worker/startup.sh`
on every boot). This forces HTTP-on-port-80 metadata access, which is
reliable everywhere.

### 3. /retry endpoint screens-existence check used wrong key

```python
elif file_urls.get('screens', {}).get('title'):
```
The actual `file_urls.screens` structure has `title_jpg` and `title_png`
(format-specific) keys — there is no bare `title` key. All retried jobs
with completed reviews got bounced back to `AWAITING_REVIEW`, forcing
users to re-submit lyrics review work that was already done.

Fixed via new `_has_title_screen()` helper that accepts either
bare-title or format-suffixed keys.

### 4. Progress callback's same-state transition spam

```python
def progress_callback(progress: int):
    job_manager.transition_to_state(new_status=RENDERING_VIDEO, ...)
```
…called while the job is already `rendering_video`. The state machine
rejects same-state transitions, generating `Invalid state transition:
rendering_video -> JobStatus.RENDERING_VIDEO` errors that hit the error
monitor on every progress tick.

Fixed by calling `update_job()` directly with the new progress +
timestamp — same effect, no fake transitions, less timeline noise.

## Test plan

- [x] Unit: `ensure_any_running` falls through on generic
`EncodingWorkerStartError` (e.g. 503), prefers capacity error when both
occur, raises last-seen error when all candidates fail with non-capacity
errors
- [x] Unit: render worker parks job for retry on
`EncodingWorkerStartError`, not just capacity
- [x] Unit: `_has_title_screen` recognizes `title_jpg` / `title_png`
(existing tests still pass)
- [x] All 83 capacity-related tests pass locally
- [ ] After merge: confirm the new env var lands in encoding worker via
CI deploy → next render kicks an encoding worker boot which downloads
the new startup.sh → SA auth works → renders complete
- [ ] After merge: confirm 5 parked jobs unstick (their next scheduler
tick should succeed since multi-zone fallback now actually engages)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 13:33:33 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 4d489c18f7 fix(iac): switch encoding-worker fallback us-central1-f → -b (capacity) (#749)
## Summary

Two related fixes wrapped into one PR:

### 1. Switch fallback zone us-central1-f → -b

The fallback VMs from #748 originally targeted `us-central1-a` and
`us-central1-f`. `pulumi up` provisioned the -a VM cleanly but **failed
in -f** with `ZONE_RESOURCE_POOL_EXHAUSTED` on multiple retries — the
same capacity exhaustion the fallback is meant to mitigate. -b has
consistent capacity for the `c4d-highcpu-32` family.

### 2. Mount ENCODING_WORKER_FALLBACK_VMS in Cloud Run

Phase 3 of #748 needs an env var on the `karaoke-backend` Cloud Run
service to enable multi-zone failover. The value is JSON which contains
commas, so gcloud's comma-delimited `--set-env-vars` flag won't work.
Stored as a Secret Manager secret instead and wired through
`--set-secrets`.

## Already applied (out-of-band)

| Resource | Action | Result |
|---|---|---|
| `encoding-worker-fallback-b` (VM, us-central1-b) | created via pulumi
up | TERMINATED, IP `35.193.127.24` |
| `encoding-worker-fallback-ip-b` | created via pulumi up | static IP |
| `encoding-worker-fallback-ip-f` | deleted via pulumi up | orphan from
earlier failed up |
| `encoding-worker-fallback-vms` (secret) | created via REST API +
Pulumi-imported | version 1 holds the JSON config |
| `karaoke-backend` Cloud Run service | PATCHed | revision `00765-jcc`
mounts the secret as env var, 100% traffic |

This commit syncs the IaC source + CI workflow to match deployed reality
so future `pulumi up` and CI deploys are no-ops / durable respectively.

## Current encoding-worker topology

```
encoding-worker-a            us-central1-c   34.57.78.246    (TERMINATED, primary blue)
encoding-worker-b            us-central1-c   34.10.189.118   (TERMINATED, primary green)
encoding-worker-fallback-a   us-central1-a   34.55.231.54    (TERMINATED, capacity fallback)
encoding-worker-fallback-b   us-central1-b   35.193.127.24   (TERMINATED, capacity fallback)
```

Multi-zone failover is **live in prod right now** via the patched Cloud
Run revision; merging this PR makes it durable across future CI deploys.

## Test plan

- [x] `pulumi preview` shows clean diff (only reflects deployed reality)
- [x] `pulumi up` succeeded; fallback VMs verified `TERMINATED` in -a
and -b
- [x] Secret Manager: `encoding-worker-fallback-vms/versions/latest`
returns the expected JSON
- [x] Cloud Run: revision 00765-jcc has `ENCODING_WORKER_FALLBACK_VMS`
mounted from the secret
- [ ] After merge: confirm CI's `pulumi up` is a no-op (Pulumi state
already imported)
- [ ] After merge: confirm CI deploy retains the env var (it will, since
it's now in `--set-secrets`)
- [ ] First real capacity event in -c will validate end-to-end fallback
(will know via logs / Discord alert when next outage hits)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 13:06:36 -04:00
Andrew Beveridge ☄️andClaude Opus 4.7 20fae2c579 Encoding worker capacity resilience: real errors, auto-retry, multi-zone failover (#748)
## Summary

Investigation of two failed jobs (`fbc651be`, `bee150fd`) revealed both
failed at the GCE encoding-worker render stage with empty error messages
(`Video render failed: `). Root cause: the GCP `compute.instances.start`
API was returning `ZONE_RESOURCE_POOL_EXHAUSTED` (us-central1-c out of
`c4d-highcpu-32` capacity), but the application's fire-and-forget call
swallowed the error. Users saw 7-minute timeouts with no useful message,
and there was no mechanism to retry once capacity returned.

This PR delivers all three phases of the capacity-resilience plan
([docs/archive/2026-05-05-encoding-worker-capacity-resilience-plan.md](docs/archive/2026-05-05-encoding-worker-capacity-resilience-plan.md)):

### Phase 1 — Surface real errors (commit `56e5968e`)
- New `EncodingWorkerCapacityError` / `EncodingWorkerStartError` typed
exceptions
- `EncodingWorkerManager.start_vm` now waits for the operation result
and raises the right typed error on `ZONE_RESOURCE_POOL_EXHAUSTED` /
`STOCKOUT` / `QUOTA_EXCEEDED`
- Capacity errors propagate through the warmup-fallback path; the HTTP
retry loop bails out fast (instead of hammering an unreachable VM for 7
min)
- Render worker catches capacity errors and parks the job in new state
`RENDER_PENDING_CAPACITY` with a user-friendly message: *"Encoding
capacity is temporarily unavailable. Your job will retry automatically —
no action needed. Most jobs recover within 5–30 minutes."*
- Repeat capacity hits accumulate `attempt_count` while preserving
`first_seen_at`
- `repr()` fallback in the generic exception handler so empty-string
errors no longer produce blank `Video render failed: ` messages

### Phase 2 — Auto-retry scheduler (commit `9d6d2161`)
- New endpoint `POST /api/internal/retry-pending-render-jobs`
(admin-auth)
- Cloud Scheduler fires it every 5 min — picks the oldest
`RENDER_PENDING_CAPACITY` job, clears its error state, re-triggers the
render worker
- 24h hard deadline: jobs older than that fail permanently with a clear
"retry manually or contact support" message
- Processes 1 job per tick (the GCE worker is single-tenant per render)

### Phase 3 — Multi-zone failover (commit `6d6b1376`)
- IaC: new fallback VMs `encoding-worker-fallback-a` (us-central1-a) and
`encoding-worker-fallback-f` (us-central1-f). All four zones support
`c4d-highcpu-32`. Provisioned stopped — ~$10/mo idle each
- New `EncodingWorkerManager.ensure_any_running(candidates)` iterates
VMs in order, catching capacity errors per-zone, falling through to the
next; returns the active VM info
- New `active_override_*` fields on the Firestore config doc track the
active fallback URL; `EncodingWorkerConfig.active_url` returns the
override if set, else primary; `EncodingService._get_worker_url`
consults `active_url` so in-flight requests after fallback hit the right
VM
- Gated by env var `ENCODING_WORKER_FALLBACK_VMS` (JSON list) — empty
default = single-zone behavior unchanged

## Operational rollout

Phases 1 & 2 ship as code only — no manual steps. Phase 3 needs:

1. `pulumi up` from `infrastructure/` — provisions the 2 fallback VMs
(stopped)
2. Capture Pulumi-output IPs (`encoding_worker_fallback_a_ip`,
`encoding_worker_fallback_f_ip`)
3. Set env var on `karaoke-backend` Cloud Run:
   ```

ENCODING_WORKER_FALLBACK_VMS=[{"vm":"encoding-worker-fallback-a","zone":"us-central1-a","ip":"<ip-a>"},{"vm":"encoding-worker-fallback-f","zone":"us-central1-f","ip":"<ip-f>"}]
   ```
4. Until step 3 is done the application uses single-zone behavior;
fallback VMs are inert

Plan doc:
[docs/archive/2026-05-05-encoding-worker-capacity-resilience-plan.md](docs/archive/2026-05-05-encoding-worker-capacity-resilience-plan.md)

## Test plan

- [x] Unit: `EncodingWorkerManager.start_vm` raises
`EncodingWorkerCapacityError` for `ZONE_RESOURCE_POOL_EXHAUSTED`,
generic `EncodingWorkerStartError` for other codes, surfaces `result()`
failures
- [x] Unit: `_warmup_encoding_worker_fallback` propagates capacity
errors, swallows generic warmup failures
- [x] Unit: `_request_with_retry` aborts immediately on capacity error
from warmup (no 7-min retry loop)
- [x] Unit: render worker transitions to `RENDER_PENDING_CAPACITY` on
capacity error, NOT `FAILED`; preserves `first_seen_at`; increments
`attempt_count`
- [x] Unit: render worker non-capacity exceptions still fail with a
useful message (no more blank `Video render failed: `)
- [x] Unit: `/api/internal/retry-pending-render-jobs` retries 1 job per
tick (oldest first), times out 24h+ jobs, no-op on empty queue, clears
error state before retry
- [x] Unit: `ensure_any_running` happy path, falls through on capacity
error, raises when all candidates exhausted, clears stale override on
primary success
- [x] Unit: `EncodingWorkerConfig.active_url` returns override if set,
else primary
- [x] Full backend suite passes (3114 tests; 5 pre-existing failures in
`test_internal_api.py` are unrelated and present on `main`)
- [ ] Manual prod test: trigger a render during a confirmed capacity
outage, observe job parks in `RENDER_PENDING_CAPACITY`, scheduler picks
it up next tick, completes when capacity returns

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 11:43:39 -04:00
Andrew Beveridge ☄️ 02ae657b5e fix(lyrics-review): evict oldest songs on localStorage quota error (#747)
## Summary
- The lyrics-analyzer auto-save (`LyricsAnalyzer.tsx:339`) writes the
full `CorrectionData` to localStorage on every history step, keyed by
song hash under a single `lyrics_analyzer_data` object. Across many
sessions this accumulates — for ~500-word songs each entry is ~500KB-1MB
once metadata is included. On **Firefox Android** (~5MB origin quota)
the next `setItem` throws `QuotaExceededError`, which propagates through
React's commit phase and prevents the lyrics review page from rendering
at all.
- Real symptom: a customer hit `QuotaExceededError: The quota has been
exceeded` on `/app/jobs/#/{id}/review` on Firefox Android, with the
recursive `uf → uc → uf` stack typical of a setter that throws inside a
commit-phase effect.
- Fix: `saveData`/`loadSavedData`/`clearSavedData` now wrap `setItem` in
quota-aware retry. On quota error, evict the **oldest** stored song
(per-entry `savedAt` timestamp) and try again. If even the current entry
can't fit alone, drop the save silently — the server-side
`review_sessions` snapshot is the durable backup; localStorage is just
crash-recovery convenience and shouldn't break the UI. Older
bare-`CorrectionData` entries are still read (`unwrap` accepts both).
`readStore` also survives a corrupted blob via try/catch + `removeItem`.

## Test plan
- [x] New unit suite `localStorage.test.ts` (5 cases): normal writes;
eviction on quota; quota exhausted with no other entries to evict (no
throw); non-quota errors still rethrown; legacy bare-format reads.
- [x] `npm run test:unit` — 894/894 pass.
- [ ] Manual verification on prod after deploy: open the failing job on
Firefox Android — page should render, and any pre-existing quota state
should self-heal as eviction kicks in on the next save.

@coderabbitai ignore

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-05-03 12:59:21 -04:00
520 changed files with 64613 additions and 4900 deletions

No files matched your search

+298
View File
@@ -0,0 +1,298 @@
name: Build GHA Runner Images
# 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 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).
# 5. Deprecate older images in the family, keeping the newest 3 ACTIVE.
on:
workflow_dispatch:
inputs:
variants:
description: 'Comma-separated variants to build (general,build,gpu,gpu-windows) or "all"'
required: false
default: 'all'
skip_prune:
description: 'Skip deprecation of old images (debugging)'
type: boolean
required: false
default: false
schedule:
# Monthly on the 1st at 02:00 UTC
- cron: '0 2 1 * *'
permissions:
contents: read
id-token: write
env:
GCP_PROJECT: nomadkaraoke
BUILD_REGION: us-central1
BUILD_ZONE: us-central1-a
BASE_IMAGE: projects/debian-cloud/global/images/family/debian-12
KEEP_IMAGES_PER_FAMILY: 3
jobs:
resolve-matrix:
name: Resolve variant matrix
runs-on: ubuntu-latest
outputs:
variants: ${{ steps.resolve.outputs.variants }}
steps:
- id: resolve
run: |
requested='${{ github.event.inputs.variants || 'all' }}'
if [[ "$requested" == "all" || -z "$requested" ]]; then
echo 'variants=["general","build","gpu","gpu-windows"]' >> "$GITHUB_OUTPUT"
else
json="$(echo "$requested" | tr ',' '\n' | jq -R . | jq -sc .)"
echo "variants=$json" >> "$GITHUB_OUTPUT"
fi
build:
name: Build ${{ matrix.variant }} image
needs: resolve-matrix
runs-on: ubuntu-latest
timeout-minutes: 90
strategy:
fail-fast: false
matrix:
variant: ${{ fromJSON(needs.resolve-matrix.outputs.variants) }}
steps:
- uses: actions/checkout@v4
- name: Authenticate to GCP
uses: google-github-actions/auth@v2
with:
workload_identity_provider: ${{ secrets.GCP_WORKLOAD_IDENTITY_PROVIDER }}
service_account: ${{ secrets.GCP_SERVICE_ACCOUNT }}
- name: Set up Cloud SDK
uses: google-github-actions/setup-gcloud@v2
with:
project_id: ${{ env.GCP_PROJECT }}
- name: Resolve build parameters
id: params
run: |
variant='${{ matrix.variant }}'
ts="$(date -u +%Y%m%d-%H%M%S)"
name="gha-runner-${variant}-${ts}"
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"
disk_size="50"
accel=""
;;
gpu)
# Build with a T4 attached so DKMS module is built and validated
# against the kernel that ships in the image.
machine="n1-standard-4"
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
;;
esac
{
echo "name=$name"
echo "family=$family"
echo "vm=$vm"
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
run: |
set -euo pipefail
gcloud compute instances create '${{ steps.params.outputs.vm }}' \
--project='${{ env.GCP_PROJECT }}' \
--zone='${{ env.BUILD_ZONE }}' \
--machine-type='${{ steps.params.outputs.machine }}' \
${{ 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='${{ steps.params.outputs.metadata_file }}' \
--labels=purpose=gha-runner-image-builder,variant='${{ matrix.variant }}' \
${{ steps.params.outputs.accel }}
- name: Wait for provisioning to complete
env:
VM: ${{ steps.params.outputs.vm }}
ZONE: ${{ env.BUILD_ZONE }}
PROJECT: ${{ env.GCP_PROJECT }}
run: |
set -uo pipefail
# Read the serial console — NOT SSH — to detect completion.
#
# The provisioner script tees its full output to /dev/ttyS0 (the GCE
# serial console). `gcloud compute instances get-serial-port-output`
# returns the full console buffer with zero SSH/IAP dependency. This
# makes the wait robust against the IAP tunnel issues that previously
# caused both false-positive readiness and false-negative timeouts.
#
# The script writes one of two distinctive marker lines:
# "### runner-image: READY: ..." — successful completion
# "### runner-image-provision FAILED ..." — fatal error (with line+rc)
#
# We also stream live progress to the GHA log so the operator can
# see what's happening without leaving the run page.
deadline=$(( $(date +%s) + 75 * 60 ))
last_size=0
attempt=0
while (( $(date +%s) < deadline )); do
attempt=$((attempt+1))
console=$(gcloud compute instances get-serial-port-output "$VM" \
--zone="$ZONE" --project="$PROJECT" --port=1 2>/dev/null || true)
cur_size=${#console}
# Stream new provisioner lines (filter syslog noise).
if (( cur_size > last_size )); then
echo "$console" | tail -c +$((last_size+1)) \
| grep -E "runner-image|### |Attempt " || true
last_size=$cur_size
fi
# Success marker
if echo "$console" | grep -qE 'runner-image: READY:'; then
echo
echo "### Image ready (attempt $attempt)"
echo "$console" | grep -E 'runner-image: READY:' | tail -1
exit 0
fi
# Failure marker
if echo "$console" | grep -qE 'runner-image-provision FAILED'; then
echo
echo "### Provisioner reported FAILURE — failure block + 40 lines of preceding context:" >&2
# -B 40: include 40 lines BEFORE the marker (where the actual
# error output of the failing command lives — python tracebacks,
# apt errors, curl messages, etc).
# -A 5: include the variant/line/cmd metadata lines after the marker.
echo "$console" | grep -B 40 -A 5 'runner-image-provision FAILED' \
| tail -80 >&2
exit 1
fi
sleep 30
done
echo
echo "### Timed out waiting for READY marker after 75 minutes" >&2
echo "### Last serial console output (tail):" >&2
gcloud compute instances get-serial-port-output "$VM" \
--zone="$ZONE" --project="$PROJECT" --port=1 2>/dev/null \
| grep -E "runner-image|### " | tail -50 >&2 || true
exit 1
- name: Stop build VM
env:
VM: ${{ steps.params.outputs.vm }}
ZONE: ${{ env.BUILD_ZONE }}
PROJECT: ${{ env.GCP_PROJECT }}
run: |
set -euo pipefail
gcloud compute instances stop "$VM" --zone="$ZONE" --project="$PROJECT" --quiet
# Belt-and-suspenders wait for TERMINATED.
for _ in $(seq 1 60); do
status=$(gcloud compute instances describe "$VM" --zone="$ZONE" --project="$PROJECT" --format='value(status)')
[[ "$status" == "TERMINATED" ]] && break
sleep 5
done
- name: Create image
env:
VM: ${{ steps.params.outputs.vm }}
ZONE: ${{ env.BUILD_ZONE }}
PROJECT: ${{ env.GCP_PROJECT }}
IMAGE: ${{ steps.params.outputs.name }}
FAMILY: ${{ steps.params.outputs.family }}
run: |
set -euo pipefail
# The "Create build VM" step doesn't pass --device-name or
# --boot-disk-name, so GCE auto-names the boot disk after the
# instance. We rely on that here instead of extracting the name
# via a format expression — the previous
# `disks[0].source.scope(disks).segment(1)` selector silently
# returned empty and gcloud rejected the call with
# "You cannot specify [--source-disk-zone] unless you are
# specifying [--source-disk]".
DISK="$VM"
echo "Creating image $IMAGE in family $FAMILY from disk $DISK in $ZONE..."
gcloud compute images create "$IMAGE" \
--project="$PROJECT" \
--source-disk="$DISK" \
--source-disk-zone="$ZONE" \
--family="$FAMILY" \
--description="GHA ephemeral runner image (${{ matrix.variant }}) built ${{ github.run_id }}" \
--labels=purpose=gha-ephemeral-runner,variant=${{ matrix.variant }},built-by=gha
echo "Created $IMAGE in family $FAMILY"
- name: Delete build VM
if: always()
env:
VM: ${{ steps.params.outputs.vm }}
ZONE: ${{ env.BUILD_ZONE }}
PROJECT: ${{ env.GCP_PROJECT }}
run: |
gcloud compute instances delete "$VM" --zone="$ZONE" --project="$PROJECT" --quiet || true
- name: Deprecate old images (keep newest ${{ env.KEEP_IMAGES_PER_FAMILY }})
if: ${{ github.event.inputs.skip_prune != 'true' }}
env:
PROJECT: ${{ env.GCP_PROJECT }}
FAMILY: ${{ steps.params.outputs.family }}
KEEP: ${{ env.KEEP_IMAGES_PER_FAMILY }}
run: |
set -euo pipefail
# List ACTIVE images in this family, newest first, skip the top $KEEP.
to_deprecate=$(gcloud compute images list \
--project="$PROJECT" \
--filter="family=$FAMILY AND status=READY AND -deprecated.state:*" \
--sort-by='~creationTimestamp' \
--format='value(name)' | tail -n +$((KEEP+1)))
if [[ -z "$to_deprecate" ]]; then
echo "Nothing to deprecate."
exit 0
fi
for img in $to_deprecate; do
echo "Deprecating $img"
gcloud compute images deprecate "$img" \
--project="$PROJECT" \
--state=DEPRECATED \
--replacement="projects/$PROJECT/global/images/family/$FAMILY"
done
+320 -89
View File
@@ -516,7 +516,10 @@ jobs:
virtualenvs-in-project: true
- name: Build package
run: poetry build
# Wheel-only: we ship a universal py3-none-any wheel. The sdist bundles
# the 33-locale Next.js static export (~50 MB) as dead weight and pushed
# the PyPI project over its 10 GB cap. pip always installs from the wheel.
run: poetry build --format wheel
- name: Test package installation
run: |
@@ -652,7 +655,17 @@ jobs:
java-version: "21"
- name: Install Firestore emulator
run: sudo apt-get install -y google-cloud-cli-firestore-emulator
run: |
# Ensure Google Cloud SDK apt source is present (ephemeral runner images
# may not ship it pre-installed). Idempotent.
if ! grep -rq "packages.cloud.google.com" /etc/apt/sources.list.d/ 2>/dev/null; then
echo "deb [signed-by=/usr/share/keyrings/cloud.google.gpg] https://packages.cloud.google.com/apt cloud-sdk main" | \
sudo tee /etc/apt/sources.list.d/google-cloud-sdk.list
curl -fsSL https://packages.cloud.google.com/apt/doc/apt-key.gpg | \
sudo gpg --dearmor --yes -o /usr/share/keyrings/cloud.google.gpg
fi
sudo apt-get update -y
sudo apt-get install -y google-cloud-cli-firestore-emulator
- name: Install dependencies
run: poetry install
@@ -821,7 +834,12 @@ jobs:
venv-package-${{ runner.os }}-py3.13-
- name: Build package
run: poetry build
# Wheel-only: we publish a universal py3-none-any wheel to PyPI. The
# sdist bundled the 33-locale Next.js static export (~50 MB/release) as
# dead weight and pushed the project over PyPI's 10 GB storage cap.
# pip always installs from the wheel; nothing builds karaoke-gen from
# source (the GCE encoding worker pulls the wheel from GCS).
run: poetry build --format wheel
- name: Upload build artifacts
uses: actions/upload-artifact@v4
@@ -915,7 +933,6 @@ jobs:
prerelease: false
files: |
dist/*.whl
dist/*.tar.gz
deploy-frontend:
name: "Deploy - Frontend (Cloudflare Pages)"
@@ -1171,10 +1188,15 @@ jobs:
data = doc.to_dict()
with open(os.environ["GITHUB_OUTPUT"], "a") as f:
for key in ["primary_vm", "primary_ip", "primary_version",
"secondary_vm", "secondary_ip"]:
"secondary_vm", "secondary_ip",
"active_override_vm", "active_override_ip", "active_override_zone"]:
f.write(f"{key}={data.get(key, '')}\n")
f.write(f"deploy_in_progress={str(data.get('deploy_in_progress', False)).lower()}\n")
print(f"Config: primary={data['primary_vm']}, secondary={data['secondary_vm']}")
# capacity_state is a map — emit as single-line JSON so the green
# selection step can demote recently-stocked-out machine types.
f.write(f"capacity_state={json.dumps(data.get('capacity_state') or {})}\n")
print(f"Config: primary={data.get('primary_vm')}, secondary={data.get('secondary_vm')}, "
f"active_override={data.get('active_override_vm')}")
PYEOF
- name: Wait for concurrent deploy
@@ -1209,29 +1231,159 @@ jobs:
print("Set deploy_in_progress=true")
PYEOF
- name: Start secondary VM
# Capacity-aware green (staging) target. us-central1 is often in a c4d Spot
# stockout, so the c4d secondary can't start and the serving worker is an n2
# fallback recorded as active_override. We validate the new wheel on a FRESH
# green — the c4d secondary if it starts, else a different n2 fallback (never
# the current override, so it keeps serving) — then promote the green. See
# infrastructure/encoding-worker/deploy_promote.py.
- name: Select & start green target
id: green
# Never hard-fail the whole backend deploy just because no encoding
# worker could be validated — emit green_ok=false and let the gated
# health/encode/promote steps skip while the Cloud Run deploy proceeds.
continue-on-error: true
run: |
SECONDARY_VM="${{ steps.config.outputs.secondary_vm }}"
echo "Starting secondary VM: $SECONDARY_VM"
gcloud compute instances start "$SECONDARY_VM" \
--zone=us-central1-c --project=nomadkaraoke || true
python3 << 'PYEOF'
import json, os, subprocess, sys, time
sys.path.insert(0, "infrastructure/encoding-worker")
import deploy_promote
for i in $(seq 1 12); do
STATUS=$(gcloud compute instances describe "$SECONDARY_VM" \
--zone=us-central1-c --project=nomadkaraoke \
--format='value(status)')
echo "VM status: $STATUS (attempt $i/12)"
if [ "$STATUS" = "RUNNING" ]; then
break
fi
sleep 10
done
try:
capacity_state = json.loads(os.environ.get("CAPACITY_STATE") or "{}")
except Exception:
capacity_state = {}
config = {
"primary_vm": os.environ.get("PRIMARY_VM") or None,
"primary_ip": os.environ.get("PRIMARY_IP") or None,
"secondary_vm": os.environ.get("SECONDARY_VM") or None,
"secondary_ip": os.environ.get("SECONDARY_IP") or None,
"secondary_zone": "us-central1-c",
"active_override_vm": os.environ.get("OVERRIDE_VM") or None,
"capacity_state": capacity_state,
}
raw = subprocess.run(
["gcloud", "secrets", "versions", "access", "latest",
"--secret=encoding-worker-fallback-vms", "--project=nomadkaraoke"],
capture_output=True, text=True)
try:
fallbacks = json.loads(raw.stdout) if raw.returncode == 0 and raw.stdout.strip() else []
except Exception as e:
print(f"::warning::Could not parse fallback VM secret: {e}")
fallbacks = []
candidates = deploy_promote.select_green_candidates(config, fallbacks)
print("Green candidates (in order):", [f"{c['vm']}({c['kind']})" for c in candidates])
def vm_status(vm, zone):
r = subprocess.run(
["gcloud", "compute", "instances", "describe", vm,
f"--zone={zone}", "--project=nomadkaraoke", "--format=value(status)"],
capture_output=True, text=True)
return r.stdout.strip()
green = None
started = [] # every VM we issued `start` to — so we can stop losers
for c in candidates:
vm, zone = c["vm"], c["zone"]
print(f"Trying green candidate: {vm} ({zone}, kind={c['kind']})")
subprocess.run(["gcloud", "compute", "instances", "start", vm,
f"--zone={zone}", "--project=nomadkaraoke"], check=False)
started.append((vm, zone))
for i in range(12):
st = vm_status(vm, zone)
print(f" {vm} status={st} ({i+1}/12)")
if st == "RUNNING":
green = c
break
time.sleep(10)
if green:
break
# Stop every candidate we started but did NOT select, so a slow-booting
# loser can't come up later unmanaged (and billed) after the deploy.
selected_vm = green["vm"] if green else None
for vm, zone in started:
if vm != selected_vm:
print(f"Stopping unselected candidate {vm} ({zone})")
subprocess.run(["gcloud", "compute", "instances", "stop", vm,
f"--zone={zone}", "--project=nomadkaraoke"], check=False)
started_fresh = "true"
inplace_failed = False
if green is None:
# Last resort: no separate green could start. Restart the current
# serving override in place (accepts a brief blip; auto-resubmit
# covers any in-flight render). If there's no override either, fail.
ov = os.environ.get("OVERRIDE_VM")
if ov:
zone = os.environ.get("OVERRIDE_ZONE") or "us-central1-f"
print(f"::warning::No separate green could start; restarting serving override {ov} in place")
subprocess.run(["gcloud", "compute", "instances", "stop", ov,
f"--zone={zone}", "--project=nomadkaraoke"], check=False)
for _ in range(18):
if vm_status(ov, zone) in ("TERMINATED", "STOPPED", ""):
break
time.sleep(5)
subprocess.run(["gcloud", "compute", "instances", "start", ov,
f"--zone={zone}", "--project=nomadkaraoke"], check=False)
final_status = ""
for _ in range(18):
final_status = vm_status(ov, zone)
if final_status == "RUNNING":
break
time.sleep(10)
# Record it either way so rollback can recover it (we stopped it,
# so if it didn't come back we must be able to start it again).
green = {"vm": ov, "ip": os.environ.get("OVERRIDE_IP"),
"zone": zone, "kind": "fallback"}
started_fresh = "false" # it's the serving worker — never stop on rollback
if final_status != "RUNNING":
inplace_failed = True
print(f"::error::In-place restart of {ov} did not reach RUNNING (status={final_status or 'unknown'})")
else:
print("::error::No green target could be started and no active override exists")
def _out(**kv):
with open(os.environ["GITHUB_OUTPUT"], "a") as f:
for k, v in kv.items():
f.write(f"{k}={v}\n")
# green_ok gates the downstream health/encode/promote steps. A missing
# green, a green with no IP, or an in-place restart that didn't come back
# RUNNING is "not ok" — the deploy skips the encoding-worker promote but
# does NOT fail; when a serving override is involved we still emit its
# vm/zone so the (always-run) rollback step can recover it.
if green is None:
_out(green_ok="false")
print("::warning::No green target selected; skipping encoding-worker promote")
elif not green.get("ip") or inplace_failed:
_out(green_ok="false", green_vm=green["vm"], green_zone=green["zone"],
green_started_fresh=started_fresh)
reason = "has no IP" if not green.get("ip") else "did not return to RUNNING"
print(f"::error::Green {green['vm']} {reason}; skipping promote")
else:
_out(green_ok="true", green_vm=green["vm"], green_ip=green["ip"],
green_zone=green["zone"], green_kind=green["kind"],
green_started_fresh=started_fresh)
print(f"Green: {green['vm']} ({green['zone']}, kind={green['kind']}, started_fresh={started_fresh})")
PYEOF
env:
PRIMARY_VM: ${{ steps.config.outputs.primary_vm }}
PRIMARY_IP: ${{ steps.config.outputs.primary_ip }}
SECONDARY_VM: ${{ steps.config.outputs.secondary_vm }}
SECONDARY_IP: ${{ steps.config.outputs.secondary_ip }}
OVERRIDE_VM: ${{ steps.config.outputs.active_override_vm }}
OVERRIDE_IP: ${{ steps.config.outputs.active_override_ip }}
OVERRIDE_ZONE: ${{ steps.config.outputs.active_override_zone }}
CAPACITY_STATE: ${{ steps.config.outputs.capacity_state }}
- name: Wait for service health
id: health
if: steps.green.outputs.green_ok == 'true'
continue-on-error: true
run: |
SECONDARY_IP="${{ steps.config.outputs.secondary_ip }}"
SECONDARY_IP="${{ steps.green.outputs.green_ip }}"
EXPECTED_VERSION="${{ steps.version_check.outputs.version }}"
HEALTH_URL="http://${SECONDARY_IP}:8080/health"
@@ -1260,7 +1412,7 @@ jobs:
id: encode-test
continue-on-error: true
run: |
SECONDARY_IP="${{ steps.config.outputs.secondary_ip }}"
SECONDARY_IP="${{ steps.green.outputs.green_ip }}"
API_KEY=$(gcloud secrets versions access latest \
--secret=encoding-worker-api-key --project=nomadkaraoke)
@@ -1324,13 +1476,35 @@ jobs:
exit 1
- name: Rollback on failure
if: steps.health.outputs.healthy != 'true' || steps.encode-test.outputs.passed != 'true'
# always() so the deploy_in_progress flag is ALWAYS cleared, even when the
# green step found no worker (its downstream steps skip, but the flag was
# already set). Skips only on a fully successful promote (passed == true).
if: always() && steps.encode-test.outputs.passed != 'true'
run: |
SECONDARY_VM="${{ steps.config.outputs.secondary_vm }}"
if [ -n "$SECONDARY_VM" ]; then
echo "Stopping secondary VM $SECONDARY_VM due to failed deploy"
gcloud compute instances stop "$SECONDARY_VM" \
--zone=us-central1-c --project=nomadkaraoke || true
GREEN_VM="${{ steps.green.outputs.green_vm }}"
GREEN_ZONE="${{ steps.green.outputs.green_zone }}"
STARTED_FRESH="${{ steps.green.outputs.green_started_fresh }}"
# Only stop a green we started fresh. If green is the serving override
# (last-resort in-place restart), leave it running — it's serving
# known-good code and stopping it would take production down.
if [ "$STARTED_FRESH" = "true" ] && [ -n "$GREEN_VM" ]; then
echo "Stopping fresh green $GREEN_VM ($GREEN_ZONE) due to failed deploy"
gcloud compute instances stop "$GREEN_VM" \
--zone="$GREEN_ZONE" --project=nomadkaraoke || true
elif [ -n "$GREEN_VM" ] && [ -n "$GREEN_ZONE" ]; then
# Serving override (last-resort in-place restart). We stopped it during
# the restart, so if it isn't RUNNING we must bring it back — otherwise
# production stays down after a failed deploy.
echo "Green is the serving worker; ensuring $GREEN_VM is RUNNING"
STATUS=$(gcloud compute instances describe "$GREEN_VM" \
--zone="$GREEN_ZONE" --project=nomadkaraoke --format='value(status)' 2>/dev/null || echo "")
if [ "$STATUS" != "RUNNING" ]; then
echo "::warning::Serving worker $GREEN_VM is '${STATUS:-unknown}'; starting it back up"
gcloud compute instances start "$GREEN_VM" \
--zone="$GREEN_ZONE" --project=nomadkaraoke || true
fi
else
echo "No green VM recorded; nothing to stop or recover"
fi
python3 -c "
@@ -1343,77 +1517,120 @@ jobs:
print('Cleared deploy_in_progress flag')
" || true
- name: Swap primary in Firestore
# Promote the validated green to serving. For a c4d secondary green this is
# the classic primary/secondary swap (and clears any stale override); for a
# fallback green it becomes the active_override. Then drain + stop whatever
# VM(s) the promote plan says are no longer serving. See deploy_promote.py.
- name: Promote green to serving
if: steps.encode-test.outputs.passed == 'true'
timeout-minutes: 25
env:
NEW_PRIMARY: ${{ steps.config.outputs.secondary_vm }}
NEW_PRIMARY_IP: ${{ steps.config.outputs.secondary_ip }}
GREEN_VM: ${{ steps.green.outputs.green_vm }}
GREEN_IP: ${{ steps.green.outputs.green_ip }}
GREEN_ZONE: ${{ steps.green.outputs.green_zone }}
GREEN_KIND: ${{ steps.green.outputs.green_kind }}
NEW_VERSION: ${{ steps.version_check.outputs.version }}
OLD_PRIMARY: ${{ steps.config.outputs.primary_vm }}
OLD_PRIMARY_IP: ${{ steps.config.outputs.primary_ip }}
OLD_VERSION: ${{ steps.config.outputs.primary_version }}
PRIMARY_VM: ${{ steps.config.outputs.primary_vm }}
PRIMARY_IP: ${{ steps.config.outputs.primary_ip }}
PRIMARY_VERSION: ${{ steps.config.outputs.primary_version }}
OVERRIDE_VM: ${{ steps.config.outputs.active_override_vm }}
OVERRIDE_IP: ${{ steps.config.outputs.active_override_ip }}
OVERRIDE_ZONE: ${{ steps.config.outputs.active_override_zone }}
run: |
echo "Swapping: $OLD_PRIMARY -> secondary, $NEW_PRIMARY -> primary"
python3 << 'PYEOF'
import os
import json, os, subprocess, sys, time, urllib.request
from datetime import datetime, timezone
sys.path.insert(0, "infrastructure/encoding-worker")
import deploy_promote
from google.cloud import firestore
db = firestore.Client(project="nomadkaraoke")
doc_ref = db.collection("config").document("encoding-worker")
green = {"vm": os.environ["GREEN_VM"], "ip": os.environ["GREEN_IP"],
"zone": os.environ["GREEN_ZONE"], "kind": os.environ["GREEN_KIND"]}
config = {
"primary_vm": os.environ.get("PRIMARY_VM") or None,
"primary_ip": os.environ.get("PRIMARY_IP") or None,
"primary_version": os.environ.get("PRIMARY_VERSION") or None,
"primary_zone": "us-central1-c",
"active_override_vm": os.environ.get("OVERRIDE_VM") or None,
"active_override_ip": os.environ.get("OVERRIDE_IP") or None,
"active_override_zone": os.environ.get("OVERRIDE_ZONE") or None,
}
now = datetime.now(timezone.utc).isoformat()
plan = deploy_promote.promote_plan(green, config, now=now, version=os.environ["NEW_VERSION"])
@firestore.transactional
def swap(transaction):
transaction.update(doc_ref, {
"primary_vm": os.environ["NEW_PRIMARY"],
"primary_ip": os.environ["NEW_PRIMARY_IP"],
"primary_version": os.environ["NEW_VERSION"],
"primary_deployed_at": now,
"secondary_vm": os.environ["OLD_PRIMARY"],
"secondary_ip": os.environ["OLD_PRIMARY_IP"],
"secondary_version": os.environ["OLD_VERSION"],
"secondary_deployed_at": now,
"last_swap_at": now,
"deploy_in_progress": False,
"deploy_in_progress_since": None,
})
db = firestore.Client(project="nomadkaraoke")
db.collection("config").document("encoding-worker").update(plan["firestore_updates"])
print("Applied config update:", json.dumps(plan["firestore_updates"], default=str))
print(f"Green {green['vm']} ({green['kind']}) is now serving")
transaction = db.transaction()
swap(transaction)
print(f"Swapped: {os.environ['NEW_PRIMARY']} is now primary")
def active_jobs(ip):
# /health is unauthenticated; None == "unknown / maybe busy".
if not ip:
return None
try:
with urllib.request.urlopen(f"http://{ip}:8080/health", timeout=5) as r:
return json.load(r).get("active_jobs")
except Exception:
return None
def vm_status(vm, zone):
r = subprocess.run(
["gcloud", "compute", "instances", "describe", vm,
f"--zone={zone}", "--project=nomadkaraoke", "--format=value(status)"],
capture_output=True, text=True)
return r.stdout.strip()
# Drain (bounded) then stop each VM the plan retired. A non-RUNNING target
# is already gone — stop it (idempotent) without waiting. For a RUNNING one
# we wait for a confirmed 0 active_jobs so we never stop mid-render (#908
# resubmit would cover a loss, but we still avoid it). The drain budget is
# SHARED across all targets (one 20-min deadline, not per-target) so a slow
# or unreachable target can't stretch the step to N×20 min; the step also
# has a hard timeout-minutes. New renders already route to the promoted green.
deadline = time.monotonic() + 1200
for tgt in plan["drain_and_stop"]:
vm, ip, zone = tgt["vm"], tgt.get("ip"), tgt.get("zone")
if not vm or not zone:
print(f"::warning::Skipping drain/stop with incomplete target: {tgt}")
continue
status = vm_status(vm, zone)
if status != "RUNNING" or not ip:
why = f"status={status or 'unknown'}" if status != "RUNNING" else "no IP to probe"
print(f"{vm} ({why}); stopping without drain")
subprocess.run(["gcloud", "compute", "instances", "stop", vm,
f"--zone={zone}", "--project=nomadkaraoke"], check=False)
continue
print(f"Draining {vm} ({zone}) before stop...")
n = active_jobs(ip)
while n != 0 and time.monotonic() < deadline:
time.sleep(15)
n = active_jobs(ip)
print(f" {vm} active_jobs={n} ({int(deadline - time.monotonic())}s budget left)")
if n == 0:
print(f"Drain confirmed for {vm}; stopping")
else:
print(f"::warning::Drain budget exhausted for {vm} (last={n}); stopping anyway")
subprocess.run(["gcloud", "compute", "instances", "stop", vm,
f"--zone={zone}", "--project=nomadkaraoke"], check=False)
PYEOF
- name: Drain and stop old primary
if: steps.encode-test.outputs.passed == 'true'
# Safety net: the deploy_in_progress lock is set unconditionally earlier, and
# both Rollback (on failure) and Promote (on success) clear it — but if the
# Promote step itself errors or hits its timeout, neither runs. This always()
# step guarantees the lock is released so the next deploy doesn't stall 10 min
# in "Wait for concurrent deploy". Idempotent with the other clears.
- name: Clear encoding-worker deploy lock
if: always()
run: |
OLD_PRIMARY="${{ steps.config.outputs.primary_vm }}"
OLD_PRIMARY_IP="${{ steps.config.outputs.primary_ip }}"
API_KEY=$(gcloud secrets versions access latest \
--secret=encoding-worker-api-key --project=nomadkaraoke)
ACTIVE_JOBS=$(curl -sf --connect-timeout 3 --max-time 5 "http://${OLD_PRIMARY_IP}:8080/health" \
| jq -r '.active_jobs // 0' 2>/dev/null || echo "0")
if [ "$ACTIVE_JOBS" -gt 0 ]; then
echo "Old primary has $ACTIVE_JOBS active jobs, waiting for drain..."
DRAIN_TIMEOUT=600
ELAPSED=0
while [ $ELAPSED -lt $DRAIN_TIMEOUT ]; do
sleep 15
ELAPSED=$((ELAPSED + 15))
ACTIVE_JOBS=$(curl -sf --connect-timeout 3 --max-time 5 "http://${OLD_PRIMARY_IP}:8080/health" \
| jq -r '.active_jobs // 0' 2>/dev/null || echo "0")
echo "Active jobs: $ACTIVE_JOBS (${ELAPSED}s elapsed)"
if [ "$ACTIVE_JOBS" -eq 0 ]; then
break
fi
done
fi
echo "Stopping old primary: $OLD_PRIMARY"
gcloud compute instances stop "$OLD_PRIMARY" \
--zone=us-central1-c --project=nomadkaraoke || true
python3 -c "
from google.cloud import firestore
db = firestore.Client(project='nomadkaraoke')
db.collection('config').document('encoding-worker').update({
'deploy_in_progress': False,
'deploy_in_progress_since': None,
})
print('Ensured deploy_in_progress is cleared')
" || true
- name: Configure Docker for Artifact Registry
run: |
@@ -1622,7 +1839,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 }}"
@@ -1648,8 +1871,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,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
--set-secrets "AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,SENDGRID_API_KEY=sendgrid-api-key:latest,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,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: |
@@ -1666,6 +1889,14 @@ jobs:
--quiet
# Lyrics transcription job (CPU, us-central1)
# NOTE: image-only update. Adding --update-secrets here crashed gcloud
# ("Invalid secret path ... in annotation") because this job's existing
# secrets are stored via Cloud Run secret *aliases* that --update-secrets
# re-validates and rejects. Proactive auto-correct env/secret
# (AUTO_CORRECT_PROACTIVE_ENABLED + ANTHROPIC_API_KEY) must be wired by a
# method that handles the alias format (see proactive-autocorrect plan
# doc); until then the proactive flag stays unset and the worker's
# _run_proactive_auto_correct() returns early (no-op).
gcloud run jobs update lyrics-transcription-job \
--image "$IMAGE" \
--region us-central1 \
+7 -1
View File
@@ -54,8 +54,14 @@ jobs:
BUCKET = os.environ["BUCKET"]
# (label, prefix, max_age_hours)
# NOTE: Firestore and BigQuery export to GCS staging nightly but are
# only uploaded to S3 *weekly* (Sundays) to cut cross-cloud egress —
# see backup_to_aws/main.py (firestore_to_s3_today). This monitor only
# sees the S3 (off-site) copy, so their limits must allow a full week
# plus slack (192h ≈ 8 days), NOT the 36h nightly cadence. GCS job
# files and secrets DO upload to S3 nightly, so they stay at 36h.
TARGETS = [
("Firestore", "firestore/", 36),
("Firestore", "firestore/", 192),
("GCS job files", "gcs/job-files/", 36),
("Encrypted secrets", "secrets/", 36),
("BigQuery weekly", "bigquery/daily-refresh/", 192),
+19 -11
View File
@@ -83,6 +83,7 @@ jobs:
-d '{"domain": "inbox.testmail.app"}' || echo "Warning: allowlist may already exist"
- name: Run Credit Purchase Test
id: run_test
working-directory: frontend
env:
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
@@ -102,16 +103,18 @@ jobs:
--reporter=list \
--timeout=600000 \
2>&1 | tee test-output-payment.log
# Capture Playwright's real exit code, not tee's (0) — the
# authoritative pass/fail signal. See Stage 2 for rationale.
echo "exit_code=${PIPESTATUS[0]}" >> "$GITHUB_OUTPUT"
continue-on-error: true
- name: Check test result
id: test_result
working-directory: frontend
run: |
if grep -q "CREDIT PURCHASE TEST PASSED" test-output-payment.log; then
echo "result=success" >> $GITHUB_OUTPUT
if [ "${{ steps.run_test.outputs.exit_code }}" = "0" ]; then
echo "result=success" >> "$GITHUB_OUTPUT"
else
echo "result=failure" >> $GITHUB_OUTPUT
echo "result=failure" >> "$GITHUB_OUTPUT"
fi
- name: Extract session token
@@ -209,6 +212,7 @@ jobs:
echo "token=$TOKEN" >> $GITHUB_OUTPUT
- name: Run Happy Path Test
id: run_test
working-directory: frontend
env:
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
@@ -234,16 +238,20 @@ jobs:
--reporter=list \
--timeout=3600000 \
2>&1 | tee test-output-happy-path.log
# Capture Playwright's real exit code, not tee's (0). This is the
# authoritative pass/fail signal — grepping the log for "failed" is
# fragile because benign retry warnings (e.g. "goto attempt 1/3
# failed") contain that substring and produce false alarms.
echo "exit_code=${PIPESTATUS[0]}" >> "$GITHUB_OUTPUT"
continue-on-error: true
- name: Check test result
id: test_result
working-directory: frontend
run: |
if grep -q "passed" test-output-happy-path.log && ! grep -q "failed" test-output-happy-path.log; then
echo "result=success" >> $GITHUB_OUTPUT
if [ "${{ steps.run_test.outputs.exit_code }}" = "0" ]; then
echo "result=success" >> "$GITHUB_OUTPUT"
else
echo "result=failure" >> $GITHUB_OUTPUT
echo "result=failure" >> "$GITHUB_OUTPUT"
fi
- name: Upload test artifacts
@@ -317,10 +325,10 @@ jobs:
if: github.event_name == 'schedule'
uses: dawidd6/action-send-mail@v3
with:
server_address: smtp.sendgrid.net
server_address: smtp.postmarkapp.com
server_port: 587
username: apikey
password: ${{ secrets.SENDGRID_API_KEY }}
username: ${{ secrets.POSTMARK_SERVER_TOKEN }}
password: ${{ secrets.POSTMARK_SERVER_TOKEN }}
subject: "E2E Daily Test ${{ needs.e2e-happy-path.result == 'success' && 'PASSED' || 'FAILED' }} - Run #${{ github.run_number }}"
to: andrew@nomadkaraoke.com
from: "Karaoke Gen CI <noreply@nomadkaraoke.com>"
+132
View File
@@ -0,0 +1,132 @@
name: E2E Daily Test (Tenant Portals)
# Full production E2E per white-label tenant: submit a job with the tenant's own
# mixed + instrumental audio, approve the lyrics review, wait for the render, and assert
# the tenant distribution (locked theme, no YouTube, no Google Drive, Dropbox folder +
# downloadable outputs). Mirrors the consumer e2e-daily.yml. Each run cleans up its job.
on:
schedule:
# Daily at 00:07 UTC = ~8pm US Eastern (8:07pm EDT / 7:07pm EST). Cron is fixed
# UTC so the local time shifts 1h across DST. Off the :00 mark to avoid the
# top-of-hour scheduler herd.
- cron: '7 0 * * *'
workflow_dispatch: {}
permissions:
contents: read
id-token: write # for Workload Identity Federation
jobs:
e2e-tenant:
name: "Tenant E2E: ${{ matrix.tenant }}"
runs-on: ubuntu-latest
timeout-minutes: 60
strategy:
fail-fast: false
# Run tenants sequentially: the GCE encoder is a single shared worker, and two
# concurrent full renders overwhelm it ("lost contact with worker"). One at a time.
max-parallel: 1
matrix:
tenant: [vocalstar, singa]
steps:
- 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: Authenticate to GCP
uses: google-github-actions/auth@v2
with:
workload_identity_provider: ${{ secrets.GCP_WORKLOAD_IDENTITY_PROVIDER }}
service_account: ${{ secrets.GCP_SERVICE_ACCOUNT }}
- 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: 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: |
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
- name: Upload logs
if: always()
uses: actions/upload-artifact@v4
with:
name: e2e-tenant-${{ matrix.tenant }}-${{ github.run_number }}
path: |
frontend/e2e-output.log
frontend/test-results/
frontend/playwright-report/
retention-days: 14
- name: Discord notification (failure)
if: ${{ steps.run_test.outputs.exit_code != '0' }}
env:
DISCORD_WEBHOOK: ${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}
run: |
if [ -n "$DISCORD_WEBHOOK" ]; then
curl -s -H "Content-Type: application/json" \
-d "{\"embeds\": [{\"title\": \"❌ Tenant E2E FAILED — ${{ matrix.tenant }}\", \"description\": \"Run: #${{ github.run_number }}\", \"color\": 15158332}]}" \
"$DISCORD_WEBHOOK" || true
fi
- name: Fail the job if the test failed
if: ${{ steps.run_test.outputs.exit_code != '0' }}
run: exit 1
notify-email:
name: "Email summary"
runs-on: ubuntu-latest
needs: e2e-tenant
if: ${{ always() && github.event_name == 'schedule' }}
steps:
- name: Send email notification
uses: dawidd6/action-send-mail@v3
with:
server_address: smtp.postmarkapp.com
server_port: 587
username: ${{ secrets.POSTMARK_SERVER_TOKEN }}
password: ${{ secrets.POSTMARK_SERVER_TOKEN }}
subject: "Tenant E2E Daily ${{ needs.e2e-tenant.result == 'success' && 'PASSED' || 'FAILED' }} - Run #${{ github.run_number }}"
to: andrew@nomadkaraoke.com
from: "Karaoke Gen CI <noreply@nomadkaraoke.com>"
body: |
Tenant E2E Daily Test (Vocal Star + Singa)
Result: ${{ needs.e2e-tenant.result }}
Run: #${{ github.run_number }}
Details: https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}
+17 -6
View File
@@ -96,14 +96,20 @@ See `docs/TESTING.md` § "Ad-Hoc Production Debugging" for full details.
- Never modify GCP resources directly via console or `gcloud` CLI
- `gcloud` CLI for reading/debugging only (e.g., checking logs, SSH to VMs)
- Stop and notify user on auth issues
- **GCS ops on macOS: never use `gsutil -m`** — its fork-based multiprocessing segfaults
on macOS (crash-report popups + the parent process hangs forever). Use `gcloud storage`
instead (`gcloud storage cp/rm/rsync …`) — no fork, and faster. Plain `gsutil` (no `-m`)
is safe but slower. `~/.boto` pins `parallel_process_count=1` as a safety net; don't remove it.
### Internationalization (i18n)
- All user-facing strings live in `frontend/messages/{locale}.json` (33 locales), NOT in components
- Backend strings live in `backend/translations/{locale}.json` (currently 3 locales: en, es, de)
- Components use `useTranslations('namespace')` from next-intl
- Pages are under `frontend/src/app/[locale]/` — locale-aware routing
- Admin pages (under `/admin/`, `/app/`) use DefaultIntlProvider (English-only, excluded from i18n)
- Pages are under `frontend/app/[locale]/` — locale-aware routing (customer-facing: `/`, `/app/*`, `/order/*`, `/auth/*`, `/payment/*`, `/r/*`)
- Non-locale routes at those same paths (e.g. `frontend/app/app/jobs/[[...slug]]/page.tsx`) are `<LocaleRedirect />` shims that redirect into `[locale]` — they are NOT English-only surfaces
- The `/app/jobs/#/{id}/review`, `/instrumental`, and `/audio-edit` review UIs are fully multilingual (components under `components/lyrics-review/`, `components/instrumental-review/`, `components/audio-editor/` use `useTranslations` heavily)
- Only `/admin/*` is English-only — it has no `[locale]/admin` counterpart and inherits `DefaultIntlProvider` from the root layout
- Internal links use `Link` from `@/i18n/routing` (locale-aware)
- After adding/changing English strings: `python frontend/scripts/translate.py --messages-dir frontend/messages --target all`
- Translation uses Gemini 3.1 Pro via Vertex AI with GCS cache for efficiency
@@ -143,13 +149,18 @@ EOF
```
### GCE Encoding Worker
The worker is a c4d blue-green primary pair (`encoding-worker-a`/`-b`, us-central1-c)
plus 8 stopped fallback VMs across 6 machine families for stockout resilience
(`encoding-worker-fallback-{a,b,n2c,n2f,c4a,n4db,c2df,n2da}`). The currently-serving
VM is `active_override_vm` in `config/encoding-worker` if set, else `primary_vm`.
Use that VM name + its zone below (there is no VM literally named `encoding-worker`):
```bash
# Check health (includes wheel_version)
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
# Check health (includes wheel_version). Example uses the primary pair's VM.
gcloud compute ssh encoding-worker-a --zone=us-central1-c --project=nomadkaraoke \
--command="curl -s http://localhost:8080/health"
# Restart service (pick up new wheel after a deploy)
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
# Restart the service (pick up new worker-side code after a deploy)
gcloud compute ssh encoding-worker-a --zone=us-central1-c --project=nomadkaraoke \
--command="sudo systemctl restart encoding-worker"
```
+21 -6
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
@@ -2049,6 +2063,7 @@ REGENERATE_SCREENS_ALLOWED_STATES = {
"complete",
"failed",
"awaiting_review",
"in_review", # User opened the review UI but hasn't submitted yet
"awaiting_instrumental_selection",
"instrumental_selected",
"prep_complete",
@@ -2131,7 +2146,7 @@ async def regenerate_screens(
]
for path in screen_paths:
try:
storage.delete_file(path)
storage.delete_file(path, ignore_missing=True)
except Exception:
pass # File may not exist
screens_deleted = True
@@ -2286,16 +2301,16 @@ async def restart_job(
for screen_file in ["title.mov", "title.jpg", "title.png", "end.mov", "end.jpg", "end.png"]:
try:
path = f"jobs/{job_id}/screens/{screen_file}"
storage.delete_file(path)
deleted_paths.append(path)
if storage.delete_file(path, ignore_missing=True):
deleted_paths.append(path)
except Exception:
pass
# Delete final outputs
for output_file in ["final_4k.mp4", "final_720p.mp4", "with_vocals.mkv", "preview.mp4"]:
try:
path = f"jobs/{job_id}/output/{output_file}"
storage.delete_file(path)
deleted_paths.append(path)
if storage.delete_file(path, ignore_missing=True):
deleted_paths.append(path)
except Exception:
pass
+552 -97
View File
@@ -52,6 +52,8 @@ from backend.middleware.tenant import get_tenant_config_from_request
from backend.exceptions import InsufficientCreditsError
from backend.services.tracing import add_span_attribute
from backend.services.firestore_service import FirestoreService
from backend.services.user_service import get_user_service
from backend.services.pricing import duration_to_credits, is_blocked
from pathlib import Path
from backend.i18n import t, get_locale_from_request
@@ -228,6 +230,57 @@ class AudioSelectRequest(BaseModel):
is_private: Optional[bool] = Field(None, description="Override privacy flag (guided flow Step 3)")
display_artist: Optional[str] = Field(None, description="Override display artist name")
display_title: Optional[str] = Field(None, description="Override display title")
# Anti-mismatch guard: client may send the expected credit total it observed.
# If the server's computed target_total differs, we return 409 so the UI can refresh.
acknowledged_credits: Optional[int] = Field(None, description="Expected total credits after this selection (anti-mismatch guard)")
class ProvideUrlRequest(BaseModel):
"""Request to attach a YouTube/yt-dlp URL to an existing parked job."""
url: str = Field(..., description="Audio source URL (YouTube, SoundCloud, or other yt-dlp supported site)")
class AttachUploadUrlsRequest(BaseModel):
"""Request for a signed upload URL to attach a file to an existing parked job."""
filename: str = Field(..., description="Original filename with extension")
content_type: str = Field("application/octet-stream", description="MIME type of the file")
class AttachUploadUrlsResponse(BaseModel):
"""Signed URL to upload an audio file for an existing job."""
job_id: str
gcs_path: str
upload_url: str
class AttachUploadCompleteRequest(BaseModel):
"""Finalise an upload; gcs_path (from attach-upload-url) pins the exact file."""
gcs_path: Optional[str] = Field(None, description="The gcs_path returned by attach-upload-url")
class AttachResponse(BaseModel):
"""Response after attaching a URL/file source to a parked job."""
status: str
job_id: str
message: str
class ResearchRequest(BaseModel):
"""Request to re-run the audio search for an existing parked job.
Both fields are optional: when a caller edits the artist/title (e.g. to fix
a typo or shorten an over-long title that returned nothing), the corrected
values are used for the search AND applied to the job. When omitted, the
job's existing search terms are re-used (a plain retry of a failed search).
"""
artist: Optional[str] = Field(None, description="Corrected artist to search + apply (blank = keep existing)")
title: Optional[str] = Field(None, description="Corrected title to search + apply (blank = keep existing)")
@validator('artist', 'title')
def normalize_text_fields(cls, v):
if v is not None and isinstance(v, str):
return normalize_text(v)
return v
class AudioSelectResponse(BaseModel):
@@ -575,6 +628,55 @@ async def _download_audio_and_trigger_workers(
job_manager.fail_job(job_id, f"Audio download failed: {e}")
def _build_result_response(r: AudioSearchResult) -> AudioSearchResultResponse:
"""Serialize an AudioSearchResult into the rich API response shape.
raw_result may be a dict (remote flacfetch API) or a Release object
(local flacfetch); both expose the same enriched display fields.
Shared by the search, standalone-search, and re-search endpoints so the
result shape stays identical across all three.
"""
raw_dict: Dict[str, Any] = {}
if r.raw_result:
if isinstance(r.raw_result, dict):
raw_dict = r.raw_result
else:
try:
raw_dict = r.raw_result.to_dict()
except AttributeError:
pass # Not a Release object
return AudioSearchResultResponse(
index=r.index,
title=r.title,
artist=r.artist,
provider=r.provider,
url=r.url,
duration=r.duration,
quality=r.quality,
source_id=r.source_id,
seeders=raw_dict.get('seeders') or r.seeders,
target_file=raw_dict.get('target_file') or r.target_file,
year=raw_dict.get('year'),
label=raw_dict.get('label'),
edition_info=raw_dict.get('edition_info'),
release_type=raw_dict.get('release_type'),
channel=raw_dict.get('channel'),
view_count=raw_dict.get('view_count'),
size_bytes=raw_dict.get('size_bytes'),
target_file_size=raw_dict.get('target_file_size'),
track_pattern=raw_dict.get('track_pattern'),
match_score=raw_dict.get('match_score'),
formatted_size=raw_dict.get('formatted_size'),
formatted_duration=raw_dict.get('formatted_duration'),
formatted_views=raw_dict.get('formatted_views'),
is_lossless=raw_dict.get('is_lossless'),
quality_str=raw_dict.get('quality_str'),
# Remote API uses 'quality_data', local uses 'quality' for the dict
quality_data=raw_dict.get('quality_data') or raw_dict.get('quality'),
)
@router.post("/audio-search/search", response_model=AudioSearchResponse)
async def search_audio(
request: Request,
@@ -881,59 +983,8 @@ async def search_audio(
)
# Convert to response format with full Release data for rich display
result_responses = []
for r in search_results:
# Get full serialized data from raw_result if available
# raw_result can be either:
# - A dict (from remote flacfetch API)
# - A Release object (from local flacfetch)
raw_dict = {}
if r.raw_result:
if isinstance(r.raw_result, dict):
# Remote flacfetch API returns dicts directly
raw_dict = r.raw_result
else:
# Local flacfetch returns Release objects
try:
raw_dict = r.raw_result.to_dict()
except AttributeError:
pass # Not a Release object
result_responses.append(
AudioSearchResultResponse(
index=r.index,
title=r.title,
artist=r.artist,
provider=r.provider,
url=r.url,
duration=r.duration,
quality=r.quality,
source_id=r.source_id,
seeders=raw_dict.get('seeders') or r.seeders,
target_file=raw_dict.get('target_file') or r.target_file,
# Additional fields for rich display
year=raw_dict.get('year'),
label=raw_dict.get('label'),
edition_info=raw_dict.get('edition_info'),
release_type=raw_dict.get('release_type'),
channel=raw_dict.get('channel'),
view_count=raw_dict.get('view_count'),
size_bytes=raw_dict.get('size_bytes'),
target_file_size=raw_dict.get('target_file_size'),
track_pattern=raw_dict.get('track_pattern'),
match_score=raw_dict.get('match_score'),
# Pre-computed display fields
formatted_size=raw_dict.get('formatted_size'),
formatted_duration=raw_dict.get('formatted_duration'),
formatted_views=raw_dict.get('formatted_views'),
is_lossless=raw_dict.get('is_lossless'),
quality_str=raw_dict.get('quality_str'),
# Full quality object for Release.from_dict()
# Remote API uses 'quality_data', local uses 'quality' for the dict
quality_data=raw_dict.get('quality_data') or raw_dict.get('quality'),
)
)
result_responses = [_build_result_response(r) for r in search_results]
return AudioSearchResponse(
status="awaiting_selection",
job_id=job_id,
@@ -1007,50 +1058,10 @@ async def search_audio_standalone(
raise HTTPException(status_code=500, detail=f"Search failed: {e}")
# Build result response objects
result_responses: List[AudioSearchResultResponse] = []
results_dicts: List[Dict[str, Any]] = []
for r in search_results:
raw_dict: Dict[str, Any] = {}
if r.raw_result:
if isinstance(r.raw_result, dict):
raw_dict = r.raw_result
else:
try:
raw_dict = r.raw_result.to_dict()
except AttributeError:
pass
result_responses.append(
AudioSearchResultResponse(
index=r.index,
title=r.title,
artist=r.artist,
provider=r.provider,
url=r.url,
duration=r.duration,
quality=r.quality,
source_id=r.source_id,
seeders=raw_dict.get('seeders') or r.seeders,
target_file=raw_dict.get('target_file') or r.target_file,
year=raw_dict.get('year'),
label=raw_dict.get('label'),
edition_info=raw_dict.get('edition_info'),
release_type=raw_dict.get('release_type'),
channel=raw_dict.get('channel'),
view_count=raw_dict.get('view_count'),
size_bytes=raw_dict.get('size_bytes'),
target_file_size=raw_dict.get('target_file_size'),
track_pattern=raw_dict.get('track_pattern'),
match_score=raw_dict.get('match_score'),
formatted_size=raw_dict.get('formatted_size'),
formatted_duration=raw_dict.get('formatted_duration'),
formatted_views=raw_dict.get('formatted_views'),
is_lossless=raw_dict.get('is_lossless'),
quality_str=raw_dict.get('quality_str'),
quality_data=raw_dict.get('quality_data') or raw_dict.get('quality'),
)
)
results_dicts.append(r.to_dict())
result_responses: List[AudioSearchResultResponse] = [
_build_result_response(r) for r in search_results
]
results_dicts: List[Dict[str, Any]] = [r.to_dict() for r in search_results]
# Store session in Firestore (TTL: 7 days)
# Long TTL so users who leave a tab open mid-flow don't hit "Search expired".
@@ -1124,6 +1135,394 @@ async def get_audio_search_results(
}
@router.post("/audio-search/{job_id}/research", response_model=AudioSearchResponse)
async def research_audio(
job_id: str,
request: Request,
body: ResearchRequest,
auth_result: AuthResult = Depends(require_auth),
):
"""
Re-run the audio search for an existing job that is awaiting selection.
Handles the dead-end where a search returned nothing (or a transient
failure parked the job with no sources): the user can retry, or edit the
artist/title and search again. The job stays in AWAITING_AUDIO_SELECTION;
its cached results are replaced with the fresh ones (which may be empty —
that is a normal outcome, returned as a 200 with an empty list, not an
error, so the UI can offer the manual fallback).
Editing the artist/title also applies the correction to the job's display
artist/title (used for title screens, filenames, lyrics), so the whole
pipeline runs on the corrected metadata.
"""
locale = get_locale_from_request(request)
_require_audio_search_enabled(request, locale)
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail=t(locale, "audioSearch.jobNotFound", job_id=job_id))
if job.status != JobStatus.AWAITING_AUDIO_SELECTION:
raise HTTPException(
status_code=400,
detail=f"Job is not awaiting audio selection (status: {job.status})"
)
# Resolve the terms to search. A non-blank edited value overrides; otherwise
# fall back to the job's existing search terms (then its display fields).
edited_artist = (body.artist or "").strip()
edited_title = (body.title or "").strip()
artist = edited_artist or job.audio_search_artist or job.artist or ""
title = edited_title or job.audio_search_title or job.title or ""
if not artist or not title:
raise HTTPException(status_code=400, detail="Both artist and title are required to search")
# Apply the edit to the job before searching so a corrected typo/title flows
# through the rest of the pipeline (search terms + display metadata).
prev_artist = job.audio_search_artist or job.artist
prev_title = job.audio_search_title or job.title
if artist != prev_artist or title != prev_title:
job_manager.update_job(job_id, {
'audio_search_artist': artist,
'audio_search_title': title,
'artist': artist,
'title': title,
})
logger.info(f"[job:{job_id}] Re-search with edited terms: {artist} - {title}")
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.SEARCHING_AUDIO,
progress=5,
message=f"Searching for: {artist} - {title}",
raise_on_invalid=False,
)
audio_search_service = get_audio_search_service()
try:
search_results = await audio_search_service.search_async(artist, title)
except NoResultsError:
search_results = []
except AudioSearchError as e:
# Restore the awaiting state so the job isn't stranded, then surface the error.
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.AWAITING_AUDIO_SELECTION,
progress=10,
message="Search failed. Please try again or provide your own audio.",
raise_on_invalid=False,
)
raise HTTPException(status_code=502, detail=f"Search failed: {e}")
# Replace cached results (empty is fine — the UI offers the manual fallback).
results_dicts = [r.to_dict() for r in search_results]
remote_id = getattr(audio_search_service, "last_remote_search_id", None)
job_manager.update_job(job_id, {
'state_data.audio_search_results': results_dicts,
'state_data.audio_search_count': len(results_dicts),
# Overwrite (or clear) the stale remote_search_id from the prior search.
'state_data.remote_search_id': remote_id,
})
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.AWAITING_AUDIO_SELECTION,
progress=10,
message=(
f"Found {len(results_dicts)} audio sources. Waiting for selection."
if results_dicts else
"No audio sources found. Edit the details and search again, or provide your own audio."
),
raise_on_invalid=False,
)
return AudioSearchResponse(
status="awaiting_selection",
job_id=job_id,
message=f"Re-search complete: {len(results_dicts)} audio sources.",
results=[_build_result_response(r) for r in search_results],
results_count=len(results_dicts),
auto_download=False,
server_version=VERSION,
)
# Audio formats accepted by the manual file-upload fallback (case-insensitive).
_AUDIO_UPLOAD_EXTENSIONS = {".mp3", ".wav", ".flac", ".m4a", ".ogg"}
# Upper bound on an inline (non-YouTube) URL download so a hung yt-dlp fetch can
# never leave a parked job stuck in DOWNLOADING_AUDIO. Kept under typical proxy
# request timeouts; YouTube URLs bypass this via the async download worker.
URL_DOWNLOAD_TIMEOUT_SECONDS = 240
def _require_audio_search_enabled(request: Request, locale: str) -> None:
"""Apply the tenant `audio_search` feature gate (mirrors /search).
White-label portals that don't offer audio search must not be able to drive
the recovery endpoints (re-search / provide-url / upload) either.
"""
tenant_config = get_tenant_config_from_request(request)
if tenant_config and not tenant_config.features.audio_search:
raise HTTPException(status_code=403, detail=t(locale, "audioSearch.notEnabled"))
def _require_awaiting_selection(job_id: str, locale: str):
"""Load a job and assert it is parked awaiting audio selection.
Shared guard for the manual-fallback endpoints (URL / file upload). Returns
the job or raises 404 (missing) / 400 (wrong state).
Note: like the sibling /select endpoint (which Bulk Mode already relies on),
this does not enforce per-user job ownership — bulk jobs are owned by a
service account, so a per-user check here would lock the real submitter out
of recovering their own parked job. Ownership hardening, if desired, must be
applied uniformly across the whole audio-search surface, not just here.
"""
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail=t(locale, "audioSearch.jobNotFound", job_id=job_id))
if job.status != JobStatus.AWAITING_AUDIO_SELECTION:
raise HTTPException(
status_code=400,
detail=f"Job is not awaiting audio selection (status: {job.status})"
)
return job
@router.post("/audio-search/{job_id}/provide-url", response_model=AttachResponse)
async def provide_url_for_job(
job_id: str,
request: Request,
background_tasks: BackgroundTasks,
body: ProvideUrlRequest,
auth_result: AuthResult = Depends(require_auth),
):
"""
Attach a YouTube/yt-dlp URL to a parked job and start processing.
The manual escape hatch when audio search finds nothing usable: the user
pastes a source URL for a job already in AWAITING_AUDIO_SELECTION. The job
was already created and charged, so we do NOT create a new job or deduct
base credits — the post-download duration reconcile handles final billing.
YouTube URLs are handed to the async audio-download Cloud Run Job (survives
request/instance shutdown, no long-blocking request). Generic yt-dlp URLs are
downloaded inline (the worker has no generic path) but bounded by a timeout so
a slow/hung download can never strand the job in DOWNLOADING_AUDIO.
"""
locale = get_locale_from_request(request)
_require_audio_search_enabled(request, locale)
# Validation helpers live in file_upload; import lazily to avoid a heavy
# import at module load (and any import cycle).
from backend.api.routes.file_upload import (
_is_youtube_url,
_validate_url,
_unsupported_url_platform,
_drm_unsupported_detail,
)
job = _require_awaiting_selection(job_id, locale)
url = (body.url or "").strip()
# Reject DRM-protected streaming links (Apple Music, Spotify, Tidal, …) upfront.
unsupported_platform = _unsupported_url_platform(url)
if unsupported_platform:
raise HTTPException(status_code=400, detail=_drm_unsupported_detail(locale, unsupported_platform))
if not _validate_url(url):
raise HTTPException(
status_code=400,
detail="Invalid URL. Please provide a valid YouTube, Vimeo, SoundCloud, or other supported video URL."
)
youtube_service = get_youtube_download_service()
is_youtube = _is_youtube_url(url)
# For YouTube URLs, check availability early (geo/private/removed/bot/age).
if is_youtube:
availability = await youtube_service.check_availability(url)
if availability and not availability.get("available"):
if availability.get("is_geo_restricted"):
detail = ("This YouTube video is not available in our server's region. "
"Try using a different source for this song.")
elif availability.get("is_private"):
detail = "This YouTube video is private and cannot be downloaded."
elif availability.get("is_removed"):
detail = "This YouTube video has been removed and cannot be downloaded."
elif availability.get("is_bot_blocked"):
detail = ("We're temporarily unable to access YouTube to download this video. "
"Please try again in a few minutes, or search for this song from another source.")
elif availability.get("is_age_restricted"):
detail = "This YouTube video is age-restricted and cannot be downloaded."
else:
detail = f"This YouTube video is unavailable: {availability.get('error', 'unknown error')}"
raise HTTPException(status_code=400, detail=detail)
# Point the job at the URL source and enter the download state. The
# audio-download worker (and generic inline path below) read these fields
# when selected_audio_index is unset (which it is for a parked job).
job_manager.update_job(job_id, {
'audio_source_type': 'url',
'url': url,
'source_name': 'YouTube' if is_youtube else 'url',
'download_url': url,
})
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.DOWNLOADING_AUDIO,
progress=10,
message=f"Downloading from provided URL: {job.artist} - {job.title}",
raise_on_invalid=False,
)
def _requeue(msg: str) -> None:
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.AWAITING_AUDIO_SELECTION,
progress=10,
message=msg,
raise_on_invalid=False,
)
if is_youtube:
# Async: the Cloud Run download job downloads + reconciles + triggers
# workers itself, so the request returns immediately.
worker_service = get_worker_service()
triggered = await worker_service.trigger_audio_download_worker(job_id)
if not triggered:
_requeue("Couldn't start the download. Please try again.")
raise HTTPException(status_code=502, detail="Failed to trigger audio download worker")
return AttachResponse(status="success", job_id=job_id, message="URL accepted, download started")
# Generic yt-dlp URL: no async worker path exists, so download inline —
# bounded so a hung download can't strand the job in DOWNLOADING_AUDIO.
try:
audio_gcs_path = await asyncio.wait_for(
youtube_service.download(url=url, job_id=job_id, artist=job.artist, title=job.title),
timeout=URL_DOWNLOAD_TIMEOUT_SECONDS,
)
except asyncio.TimeoutError:
_requeue("That download took too long. Try another URL or search again.")
raise HTTPException(status_code=504, detail="Download timed out")
except YouTubeDownloadError as e:
_requeue("Download from that URL failed. Try another URL or search again.")
raise HTTPException(status_code=502, detail=f"Download failed: {e}")
job_manager.update_job(job_id, {
'input_media_gcs_path': audio_gcs_path,
'filename': os.path.basename(audio_gcs_path),
})
# start_job_processing transitions DOWNLOADING_AUDIO → DOWNLOADING, runs the
# duration reconcile (final billing), and triggers audio + lyrics workers.
background_tasks.add_task(
job_manager.start_job_processing, job_id, 15,
"Audio downloaded, starting processing",
)
return AttachResponse(status="success", job_id=job_id, message="URL accepted, download complete, processing started")
@router.post("/audio-search/{job_id}/attach-upload-url", response_model=AttachUploadUrlsResponse)
async def attach_upload_url(
job_id: str,
request: Request,
body: AttachUploadUrlsRequest,
auth_result: AuthResult = Depends(require_auth),
):
"""
Issue a signed GCS upload URL to attach an audio file to a parked job.
Step 1 of the manual file-upload fallback: the client PUTs the file to the
returned URL, then calls /attach-upload-complete. No job is created here.
"""
locale = get_locale_from_request(request)
_require_audio_search_enabled(request, locale)
_require_awaiting_selection(job_id, locale)
# Normalise Windows separators before basename so "..\\evil.exe" can't be
# stored verbatim, then validate the extension against the audio allow-list.
raw = (body.filename or "").strip().replace("\\", "/")
filename = os.path.basename(raw) or "audio"
ext = os.path.splitext(filename)[1].lower()
if ext not in _AUDIO_UPLOAD_EXTENSIONS:
raise HTTPException(
status_code=400,
detail="Unsupported audio format. Use MP3, WAV, FLAC, M4A, or OGG.",
)
gcs_path = f"uploads/{job_id}/audio/{filename}"
upload_url = storage_service.generate_signed_upload_url(
gcs_path, content_type=body.content_type or "application/octet-stream", expiration_minutes=60,
)
return AttachUploadUrlsResponse(job_id=job_id, gcs_path=gcs_path, upload_url=upload_url)
@router.post("/audio-search/{job_id}/attach-upload-complete", response_model=AttachResponse)
async def attach_upload_complete(
job_id: str,
request: Request,
background_tasks: BackgroundTasks,
body: AttachUploadCompleteRequest = AttachUploadCompleteRequest(),
auth_result: AuthResult = Depends(require_auth),
):
"""
Finalise a file upload attached to a parked job and start processing.
Step 2 of the manual file-upload fallback: verifies the uploaded audio landed
in GCS, points the job at it, and starts processing. Like the URL path, the
job was already created/charged, so no new job and no base-credit deduction.
"""
locale = get_locale_from_request(request)
_require_audio_search_enabled(request, locale)
from backend.api.routes.file_upload import _select_mixed_audio_files
job = _require_awaiting_selection(job_id, locale)
prefix = f"uploads/{job_id}/audio/"
files = storage_service.list_files(prefix)
audio_files = [f for f in files if not f.rstrip("/").endswith("/")]
if not audio_files:
raise HTTPException(status_code=400, detail="No uploaded audio file found. Upload the file first.")
# Prefer the exact object the client uploaded to (from attach-upload-url),
# validated to live under this job's prefix and to actually exist — never
# trust an arbitrary client path, and don't depend on list ordering.
requested = (body.gcs_path or "").strip()
if requested:
if not requested.startswith(prefix) or requested not in audio_files:
raise HTTPException(status_code=400, detail="Uploaded file not found for this job.")
audio_gcs_path = requested
else:
selected = _select_mixed_audio_files(audio_files)
audio_gcs_path = selected[0] if isinstance(selected, list) and selected else (selected or audio_files[0])
job_manager.update_job(job_id, {
'audio_source_type': 'upload',
'input_media_gcs_path': audio_gcs_path,
'filename': os.path.basename(audio_gcs_path),
})
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.DOWNLOADING_AUDIO,
progress=10,
message=f"File uploaded: {job.artist} - {job.title}",
raise_on_invalid=False,
)
background_tasks.add_task(
job_manager.start_job_processing, job_id, 15,
"File uploaded, starting processing",
)
return AttachResponse(status="success", job_id=job_id, message="Upload accepted, processing started")
@router.post("/audio-search/{job_id}/select", response_model=AudioSelectResponse)
async def select_audio_source(
job_id: str,
@@ -1174,6 +1573,62 @@ async def select_audio_source(
if not search_results:
raise HTTPException(status_code=400, detail="No search results cached for this job")
# -------------------------------------------------------------------------
# Duration-based pricing: charge the DELTA before triggering any download.
# -------------------------------------------------------------------------
# The selected result may carry a duration field (seconds as int).
selected_result = search_results[body.selection_index] if 0 <= body.selection_index < len(search_results) else {}
duration = selected_result.get('duration') # int seconds, or None
# Hard ceiling: reject inputs over 60 minutes immediately (before any state change).
if duration is not None and is_blocked(duration):
raise HTTPException(status_code=422, detail="Inputs over 60 minutes aren't supported")
# Idempotency guard: if a previous /select call already applied the delta charge,
# skip re-charging entirely. This makes double-click / rapid-retry safe.
# Residual race: two *truly simultaneous* requests can both read the flag as False
# and both charge before either writes it True. The atomic status transition in
# _validate_and_prepare_selection() causes the second request to fail with 400,
# so the window is tiny; any rare double-charge is recoverable via support refund.
select_charge_applied = bool((job.state_data or {}).get('select_charge_applied', False))
# Compute how many credits this job should total after selecting this result.
# If duration is unknown, keep target_total == credits_charged so owed = 0.
credits_charged = int((job.state_data or {}).get('credits_charged', 1))
target_total = duration_to_credits(duration) if duration is not None else credits_charged
owed = max(0, target_total - credits_charged)
# Anti-mismatch guard: if the client sent an expected total, verify it still matches.
if body.acknowledged_credits is not None and body.acknowledged_credits != target_total:
raise HTTPException(status_code=409, detail="Credit figure changed; please refresh")
# Deduct the owed delta (or just persist duration metadata if owed == 0).
user_email = job.user_email
if not select_charge_applied:
if owed > 0:
if not user_email:
raise HTTPException(status_code=500, detail="Job has no associated user email")
ok, _, _ = get_user_service().deduct_credits(
user_email,
job_id,
amount=owed,
reason="job_creation",
count_as_job_creation=False, # job was already counted at create_job()
)
if not ok:
raise HTTPException(status_code=402, detail="Insufficient credits")
# Persist updated credit total, duration estimate, and idempotency flag.
state_update: dict = {
"state_data.credits_charged": target_total,
"state_data.select_charge_applied": True,
}
if duration is not None:
state_update["state_data.duration_estimate_seconds"] = duration
state_update["state_data.duration_estimate_source"] = "search_metadata"
job_manager.update_job(job_id, state_update)
# -------------------------------------------------------------------------
# Validate selection and transition to DOWNLOADING_AUDIO (returns immediately)
selection_info = _validate_and_prepare_selection(
job_id=job_id,
+476
View File
@@ -0,0 +1,476 @@
"""Bulk Mode API routes.
Lets a user submit up to 100 karaoke jobs at once, by text (artist/title rows)
or by album (MusicBrainz release lookup). Album tracklists and text rows are
enriched with KaraokeNerds community-version availability so the user can skip
tracks that already exist.
Submission (POST /bulk/submit) and progress (GET /bulk/{batch_id}) live here too
(added in later phases).
"""
import logging
import uuid
from typing import Literal, Optional
from fastapi import APIRouter, Depends, HTTPException, Query, Request
from pydantic import BaseModel, Field
from backend.api.dependencies import require_auth
from backend.services.auth_service import AuthResult
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/bulk", tags=["bulk"])
MAX_BULK_SONGS = 100
# --- Models -----------------------------------------------------------------
class BulkArtist(BaseModel):
mbid: Optional[str] = None
name: str
disambiguation: str = ""
type: Optional[str] = None
country: Optional[str] = None
class BulkAlbum(BaseModel):
release_group_mbid: str
title: str
primary_type: Optional[str] = None
secondary_types: list[str] = []
first_release_date: str = ""
is_studio: bool = True
class BulkEdition(BaseModel):
release_mbid: str
title: Optional[str] = None
status: Optional[str] = None
date: str = ""
country: Optional[str] = None
track_count: int = 0
class BulkEditionVariant(BaseModel):
"""A distinct tracklist variant (country pressings collapsed by track count)."""
representative_release_mbid: str
label: Literal["Original", "Reissue"] = "Original"
track_count: int = 0
year: str = ""
pressing_count: int = 0
delta_vs_original: int = 0
class CommunityVersion(BaseModel):
"""An existing community karaoke version the user can preview on YouTube."""
brand: str
url: str
class BulkTrack(BaseModel):
position: Optional[int] = None
title: str
recording_mbid: Optional[str] = None
length_ms: Optional[int] = None
is_extra: bool = False
extra_reason: str = ""
# Availability (filled from KaraokeNerds); available=True => already exists
available: bool = False
brands: list[str] = []
versions: list[CommunityVersion] = []
class BulkTracklistResponse(BaseModel):
release_mbid: Optional[str] = None
canonical_release_mbid: Optional[str] = None
selected_variant_mbid: Optional[str] = None
title: Optional[str] = None
date: str = ""
tracks: list[BulkTrack] = []
editions: list[BulkEdition] = []
variants: list[BulkEditionVariant] = []
class AvailabilityItem(BaseModel):
artist: str = Field(..., min_length=1)
title: str = Field(..., min_length=1)
class AvailabilityRequest(BaseModel):
tracks: list[AvailabilityItem]
class AvailabilityResult(BaseModel):
artist: str
title: str
available: bool
brands: list[str] = []
brand_count: int = 0
versions: list[CommunityVersion] = []
class AvailabilityResponse(BaseModel):
results: list[AvailabilityResult]
# --- Album lookup routes ----------------------------------------------------
@router.get("/album/artists", response_model=list[BulkArtist])
async def album_artists(
request: Request,
q: str = Query(..., min_length=2, description="Artist name search"),
limit: int = Query(8, ge=1, le=25),
auth_result: AuthResult = Depends(require_auth),
):
"""Search MusicBrainz for artists (album-mode step 1)."""
from backend.services.musicbrainz_service import get_musicbrainz_service
try:
results = await get_musicbrainz_service().search_artists(q, limit=limit)
except Exception as e: # noqa: BLE001
logger.warning("MusicBrainz artist search failed: %r", e, exc_info=True)
raise HTTPException(status_code=502, detail="Artist lookup is temporarily unavailable")
return results
@router.get("/album/albums", response_model=list[BulkAlbum])
async def album_albums(
request: Request,
artist_mbid: str = Query(..., min_length=1),
auth_result: AuthResult = Depends(require_auth),
):
"""List an artist's albums (release-groups) for the album picker."""
from backend.services.musicbrainz_service import get_musicbrainz_service
try:
return await get_musicbrainz_service().get_albums(artist_mbid)
except Exception as e: # noqa: BLE001
logger.warning("MusicBrainz album list failed: %r", e, exc_info=True)
raise HTTPException(status_code=502, detail="Album lookup is temporarily unavailable")
@router.get("/album/tracklist", response_model=BulkTracklistResponse)
async def album_tracklist(
request: Request,
artist: str = Query(..., min_length=1, description="Artist name for availability checks"),
release_group_mbid: Optional[str] = Query(None),
release_mbid: Optional[str] = Query(None, description="Specific edition to load"),
locale: Optional[str] = Query(None, description="UI locale → biases representative-pressing choice"),
auth_result: AuthResult = Depends(require_auth),
):
"""Resolve an album's canonical tracklist (or a specific edition) and enrich
each track with KaraokeNerds community-version availability.
Response shape note: ``variants`` is only populated on the ``release_group_mbid``
path (the initial album load). When loading a specific edition via
``release_mbid`` it is intentionally ``[]`` — the client already holds the
variant list from the initial load and only needs the chosen edition's tracks.
"""
from backend.services.musicbrainz_service import (
get_musicbrainz_service,
country_prefs_for_locale,
)
from backend.services.karaokenerds_service import check_community_versions_batch
if not release_group_mbid and not release_mbid:
raise HTTPException(status_code=422, detail="release_group_mbid or release_mbid required")
mb = get_musicbrainz_service()
try:
if release_mbid:
# Loading a specific variant — variants already known to the client.
tracklist = await mb.get_release_tracklist(release_mbid)
tracklist.setdefault("editions", [])
tracklist.setdefault("canonical_release_mbid", release_mbid)
tracklist.setdefault("variants", [])
tracklist.setdefault("selected_variant_mbid", release_mbid)
else:
tracklist = await mb.get_album_tracklist(
release_group_mbid, preferred_countries=country_prefs_for_locale(locale)
)
except Exception as e: # noqa: BLE001
logger.warning("MusicBrainz tracklist failed: %r", e, exc_info=True)
raise HTTPException(status_code=502, detail="Tracklist lookup is temporarily unavailable")
tracks = tracklist.get("tracks", [])
# Availability enrichment — never fatal.
try:
avail = await check_community_versions_batch(
[{"artist": artist, "title": t["title"]} for t in tracks]
)
for t, a in zip(tracks, avail):
t["available"] = a["available"]
t["brands"] = a["brands"]
t["versions"] = a.get("versions", [])
except Exception as e: # noqa: BLE001
logger.warning("Availability enrichment failed (non-fatal): %s", e)
return BulkTracklistResponse(
release_mbid=tracklist.get("release_mbid"),
canonical_release_mbid=tracklist.get("canonical_release_mbid"),
selected_variant_mbid=tracklist.get("selected_variant_mbid"),
title=tracklist.get("title"),
date=tracklist.get("date", ""),
tracks=[BulkTrack(**t) for t in tracks],
editions=[BulkEdition(**e) for e in tracklist.get("editions", [])],
variants=[BulkEditionVariant(**v) for v in tracklist.get("variants", [])],
)
@router.post("/availability", response_model=AvailabilityResponse)
async def bulk_availability(
request: Request,
body: AvailabilityRequest,
auth_result: AuthResult = Depends(require_auth),
):
"""Batch KaraokeNerds availability check for text-mode rows."""
from backend.services.karaokenerds_service import check_community_versions_batch
if len(body.tracks) > MAX_BULK_SONGS:
raise HTTPException(status_code=422, detail=f"At most {MAX_BULK_SONGS} tracks per request")
results = await check_community_versions_batch(
[{"artist": t.artist, "title": t.title} for t in body.tracks]
)
return AvailabilityResponse(results=[AvailabilityResult(**r) for r in results])
# --- Submission -------------------------------------------------------------
class BulkSong(BaseModel):
artist: str = Field(..., min_length=1)
title: str = Field(..., min_length=1)
display_artist: Optional[str] = None
display_title: Optional[str] = None
class BulkSettings(BaseModel):
auto_select_if_lossless: bool = True
is_private: bool = False
skip_audio_edit: bool = True
skip_customization: bool = True
class BulkSubmitRequest(BaseModel):
songs: list[BulkSong]
settings: BulkSettings = Field(default_factory=BulkSettings)
class BulkSubmitResponse(BaseModel):
batch_id: str
job_ids: list[str]
total: int
@router.post("/submit", response_model=BulkSubmitResponse)
async def bulk_submit(
request: Request,
body: BulkSubmitRequest,
auth_result: AuthResult = Depends(require_auth),
):
"""Create one job per song, gate on credits upfront, and dispatch the batch
search worker. Jobs start parked (auto_download=False) and the worker either
auto-selects a confident lossless match or leaves them awaiting selection."""
from backend.config import get_settings
from backend.exceptions import InsufficientCreditsError
from backend.models.job import JobCreate
from backend.services.job_manager import JobManager
from backend.services.job_defaults_service import resolve_cdg_txt_defaults
from backend.services.theme_service import get_theme_service
from backend.services.worker_service import get_worker_service
n = len(body.songs)
if n == 0:
raise HTTPException(status_code=422, detail="At least one song is required")
if n > MAX_BULK_SONGS:
raise HTTPException(status_code=422, detail=f"At most {MAX_BULK_SONGS} songs per batch")
user_email = auth_result.user_email
is_admin = bool(auth_result.is_admin)
# Upfront credit gate (1 credit/song minimum). Admins bypass.
if not is_admin and user_email:
from backend.services.user_service import get_user_service
available = get_user_service().check_credits(user_email)
if available < n:
raise HTTPException(
status_code=402,
detail={
"error": "insufficient_credits",
"message": "You don't have enough credits for this batch.",
"credits_available": available,
"credits_required": n,
},
)
settings = get_settings()
theme_service = get_theme_service()
theme_id = theme_service.get_default_theme_id()
resolved_cdg, resolved_txt = resolve_cdg_txt_defaults(theme_id, None, None)
batch_id = uuid.uuid4().hex[:12]
bulk_settings = body.settings.model_dump()
job_manager = JobManager()
job_ids: list[str] = []
for song in body.songs:
display_artist = (song.display_artist or song.artist).strip()
display_title = (song.display_title or song.title).strip()
request_metadata = {
"created_from": "bulk",
"batch_id": batch_id,
"user_email": user_email,
}
job_create = JobCreate(
artist=display_artist,
title=display_title,
theme_id=theme_id,
enable_cdg=resolved_cdg,
enable_txt=resolved_txt,
user_email=user_email,
audio_search_artist=song.artist.strip(),
audio_search_title=song.title.strip(),
auto_download=False,
is_private=body.settings.is_private,
brand_prefix=settings.default_brand_prefix,
enable_youtube_upload=settings.default_enable_youtube_upload,
youtube_description=settings.default_youtube_description,
discord_webhook_url=settings.default_discord_webhook_url,
dropbox_path=settings.default_dropbox_path,
gdrive_folder_id=settings.default_gdrive_folder_id,
request_metadata=request_metadata,
)
try:
job = job_manager.create_job(job_create, is_admin=is_admin)
except InsufficientCreditsError:
# Ran out mid-batch (e.g. concurrent spend after the gate). Stop here;
# already-created jobs are valid and will proceed.
logger.warning("[batch:%s] ran out of credits after %d/%d jobs", batch_id, len(job_ids), n)
break
job_manager.update_job(
job.job_id,
{
"state_data.batch_id": batch_id,
"state_data.bulk_settings": bulk_settings,
"state_data.bulk_pending_search": True,
},
)
job_ids.append(job.job_id)
if not job_ids:
raise HTTPException(status_code=402, detail="No jobs could be created")
# Dispatch the batch search worker. Retry once on transient failure. If it
# still fails the jobs exist (and are charged) but won't process, so surface
# an explicit error with the batch_id — and tell the user NOT to resubmit
# (that would create+charge a second batch); the batch can be re-dispatched.
worker_service = get_worker_service()
triggered = await worker_service.trigger_bulk_search_worker(batch_id)
if not triggered:
triggered = await worker_service.trigger_bulk_search_worker(batch_id)
if not triggered:
logger.critical(
"[batch:%s] created %d jobs but FAILED to dispatch bulk-search worker",
batch_id, len(job_ids),
)
raise HTTPException(
status_code=503,
detail={
"error": "dispatch_failed",
"message": "Your batch was created but processing couldn't start. "
"Please don't resubmit — contact support with this batch ID and we'll start it.",
"batch_id": batch_id,
"job_ids": job_ids,
},
)
logger.info("[batch:%s] created %d jobs, dispatched bulk-search worker", batch_id, len(job_ids))
return BulkSubmitResponse(batch_id=batch_id, job_ids=job_ids, total=len(job_ids))
# --- Progress ---------------------------------------------------------------
class BulkJobStatus(BaseModel):
job_id: str
artist: str
title: str
status: str
auto_selected: bool = False
class BulkBatchResponse(BaseModel):
batch_id: str
total: int
counts: dict
jobs: list[BulkJobStatus]
# Status -> progress bucket for the batch summary.
_AWAITING = "awaiting_audio_selection"
_TERMINAL_OK = "complete"
_TERMINAL_FAIL = "failed"
_SEARCHING = {"pending", "searching_audio"}
def _bucket(status: str, pending_search: bool) -> str:
if pending_search or status in _SEARCHING:
return "searching"
if status == _AWAITING:
return "awaiting_selection"
if status == _TERMINAL_OK:
return "complete"
if status == _TERMINAL_FAIL:
return "failed"
return "processing"
@router.get("/{batch_id}", response_model=BulkBatchResponse)
async def bulk_batch(
request: Request,
batch_id: str,
auth_result: AuthResult = Depends(require_auth),
):
"""Progress summary for a batch: counts by bucket + per-job status."""
from backend.services.job_manager import JobManager
job_manager = JobManager()
jobs = job_manager.list_jobs_by_batch_id(batch_id)
if not bool(auth_result.is_admin):
email = (auth_result.user_email or "").lower()
jobs = [j for j in jobs if (j.user_email or "").lower() == email]
if not jobs:
raise HTTPException(status_code=404, detail="Batch not found")
counts = {"searching": 0, "awaiting_selection": 0, "processing": 0, "complete": 0, "failed": 0}
job_statuses: list[BulkJobStatus] = []
for j in jobs:
status = j.status.value if hasattr(j.status, "value") else str(j.status)
sd = j.state_data or {}
bucket = _bucket(status, bool(sd.get("bulk_pending_search")))
counts[bucket] += 1
job_statuses.append(
BulkJobStatus(
job_id=j.job_id,
artist=j.audio_search_artist or j.artist or "",
title=j.audio_search_title or j.title or "",
status=status,
auto_selected=bool(sd.get("bulk_auto_selected")),
)
)
return BulkBatchResponse(
batch_id=batch_id, total=len(jobs), counts=counts, jobs=job_statuses
)
+61 -1
View File
@@ -7,7 +7,7 @@ and checks karaokenerds.com for existing community karaoke versions.
import logging
import time
from typing import Optional
from typing import Literal, Optional
from fastapi import APIRouter, Depends, HTTPException, Query, Request
from pydantic import BaseModel, Field
@@ -103,6 +103,38 @@ class CommunityCheckResponse(BaseModel):
best_youtube_url: Optional[str] = None
class MatchJudgeRequest(BaseModel):
"""Request body for the artist/title match judge."""
artist: str = Field(..., min_length=1)
title: str = Field(..., min_length=1)
# The audio search's confidence tier (1=strong..3=weak), so the judge can
# tell whether weak results hint at a typo. Optional.
audio_confidence_tier: Optional[int] = Field(None, ge=1, le=3)
# "fast" = catalog-only pass (no AI, no tier needed) the client fires in
# parallel with the audio search; "full" = complete pipeline once the tier is
# known. Defaults to "full" so a single legacy call still works.
stage: Literal["fast", "full"] = "full"
class MatchJudgeAlternative(BaseModel):
artist: str
title: str
class MatchJudgeResponse(BaseModel):
"""Verdict on a typed artist/title — formatting + match acceptance."""
kind: str # "cosmetic" | "content" | "ambiguous" | "none"
confident: bool
canonical_artist: str
canonical_title: str
alternatives: list[MatchJudgeAlternative] = []
engine: str # "deterministic" | "catalog" | "ai"
reason: str = ""
# Set by a "fast" pass that couldn't decide — the client should follow up with
# a "full" call once the audio tier is known.
needs_ai: bool = False
# --- Routes ---
@@ -161,3 +193,31 @@ async def check_community_versions(
from backend.services.karaokenerds_service import check_community_versions
result = await check_community_versions(body.artist, body.title)
return result
@router.post("/match-judge", response_model=MatchJudgeResponse)
async def match_judge(
request: Request,
body: MatchJudgeRequest,
auth_result: AuthResult = Depends(require_auth),
):
"""
Judge a typed artist/title: decide official formatting + whether it matches a
real song. Deterministic + catalog layers run first; a light AI model fires
only when those aren't confident. Never blocks the submission flow — failures
degrade to a "none" verdict.
"""
locale = get_locale_from_request(request)
_check_rate_limit(auth_result.user_email or auth_result.token_id or "unknown", locale)
from backend.services.match_judge.service import judge_match
verdict = await judge_match(
body.artist, body.title,
audio_tier=body.audio_confidence_tier,
stage=body.stage,
)
logger.info(
"match-judge stage=%s kind=%s engine=%s confident=%s needs_ai=%s",
body.stage, verdict.kind, verdict.engine, verdict.confident, verdict.needs_ai,
)
return verdict.to_dict()
+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,
+40 -9
View File
@@ -2,14 +2,23 @@
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
logger = logging.getLogger(__name__)
@@ -35,28 +44,50 @@ 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"]:
logger.info(f"Started encoding worker VM: {result['vm_name']}")
return result
except EncodingWorkerStartError as e:
# The primary VM couldn't start (capacity exhaustion or a transient
# 503 SERVICE_UNAVAILABLE from the GCE backend). This is NOT fatal:
# the encoding flow's own warmup (ensure_any_running) falls back to
# the alternate-zone workers, so the job still completes. Log at
# WARNING so it doesn't trip the production error monitor and page us
# for self-healing capacity events.
logger.warning(
f"Primary encoding worker warmup failed ({e}); "
f"encoding will fall back to an alternate-zone worker"
)
return {"started": False, "error": str(e)}
except Exception as e:
logger.error(f"Failed to warm up encoding worker: {e}")
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"}
+220 -71
View File
@@ -10,12 +10,11 @@ Supports two upload flows:
- Client uploads files directly to GCS using signed URLs (no size limit)
- POST /api/jobs/{job_id}/uploads-complete - Validates uploads, triggers workers
"""
import asyncio
import json
import logging
import tempfile
import os
from fastapi import APIRouter, UploadFile, File, Form, HTTPException, BackgroundTasks, Request, Body, Depends
from fastapi import APIRouter, UploadFile, File, Form, HTTPException, BackgroundTasks, Request, Depends
from pathlib import Path
from typing import Optional, List, Dict, Any, Tuple
@@ -58,6 +57,19 @@ def _is_youtube_url(url: str) -> bool:
router = APIRouter(tags=["jobs"])
def _select_mixed_audio_files(files):
"""Filter a listing of ``uploads/{job_id}/audio/`` down to the mixed (with-vocals) audio.
When a job supplies its own instrumental (existing_instrumental flow, e.g. tenant
submissions), that file is uploaded into the SAME ``audio/`` directory as the mixed
audio (``existing_instrumental.*``). The ``audio/`` prefix therefore matches both, and
because ``existing_instrumental`` sorts before most filenames, ``files[0]`` would pick
the instrumental — so transcription would run on the backing track instead of the
vocals. Excluding it here ensures the mixed audio is selected as the transcription input.
"""
return [f for f in files if not Path(f).name.startswith('existing_instrumental')]
def _apply_tenant_overrides(
dist: EffectiveDistributionSettings,
tenant_config,
@@ -68,12 +80,20 @@ def _apply_tenant_overrides(
"""
Apply tenant-specific overrides to distribution settings and job options.
White-label tenant config is AUTHORITATIVE: it replaces (not just fills in) the
distribution settings, so tenant outputs never inherit the global consumer defaults
(DEFAULT_BRAND_PREFIX / DEFAULT_DROPBOX_PATH / DEFAULT_GDRIVE_FOLDER_ID) that
``get_effective_distribution_settings`` seeds into ``dist``. Without this, every
tenant job would land in the shared consumer Dropbox folder and upload to the global
Google Drive, regardless of the tenant's own config.
For tenant jobs:
- Overlays brand_prefix, dropbox_path, gdrive_folder_id from tenant defaults
(only when not already set in the request body / dist)
- Sets brand_prefix, dropbox_path, gdrive_folder_id authoritatively from tenant config
- Routes Dropbox / Google Drive only when the matching feature flag is enabled;
otherwise disables that channel entirely (no global-default leak)
- Forces is_private = True
- Applies locked_theme as effective theme
- Disables YouTube upload
- Disables YouTube upload (tenants never publish to YouTube)
Returns:
Tuple of (dist, effective_theme_id, is_private, enable_youtube_upload)
@@ -82,14 +102,12 @@ def _apply_tenant_overrides(
return dist, effective_theme_id, is_private, enable_youtube_upload
defaults = tenant_config.defaults
features = tenant_config.features
# Overlay tenant distribution defaults (request-level values take precedence)
if defaults.brand_prefix and not dist.brand_prefix:
dist.brand_prefix = defaults.brand_prefix
if defaults.dropbox_path and not dist.dropbox_path:
dist.dropbox_path = defaults.dropbox_path
if defaults.gdrive_folder_id and not dist.gdrive_folder_id:
dist.gdrive_folder_id = defaults.gdrive_folder_id
# Authoritative distribution routing (overrides any global defaults in `dist`).
dist.brand_prefix = defaults.brand_prefix
dist.dropbox_path = defaults.dropbox_path if features.dropbox_upload else None
dist.gdrive_folder_id = defaults.gdrive_folder_id if features.gdrive_upload else None
# Force private for all tenant jobs
is_private = True
@@ -338,16 +356,6 @@ ALLOWED_IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp'}
ALLOWED_FONT_EXTENSIONS = {'.ttf', '.otf', '.woff', '.woff2'}
async def _trigger_audio_worker_only(job_id: str) -> None:
"""
Trigger only the audio worker.
Used for URL jobs where audio needs to be downloaded first.
The audio worker will trigger the lyrics worker after download completes.
"""
await worker_service.trigger_audio_worker(job_id)
def _prepare_theme_for_job(
job_id: str,
theme_id: str,
@@ -1393,12 +1401,14 @@ async def mark_uploads_complete(
# List files with this prefix to find the actual uploaded file
files = storage_service.list_files(prefix)
if file_type == 'audio':
files = _select_mixed_audio_files(files)
if not files:
raise HTTPException(
status_code=400,
detail=f"File for '{file_type}' was not uploaded to GCS. Expected prefix: {prefix}"
)
# Use the first (and should be only) file found
gcs_path = files[0]
@@ -1571,11 +1581,140 @@ def _validate_url(url: Optional[str]) -> bool:
for supported in supported_domains:
if domain == supported or domain.endswith('.' + supported):
return True
# For other URLs, let yt-dlp try (it supports many more sites)
return True
# Streaming services whose catalogue is DRM-protected and therefore cannot be
# downloaded by yt-dlp / flacfetch. Submitting one of these only creates a job
# that fails deep in the download stage with a cryptic "Unsupported URL" error
# (and lets the user trigger a futile retry), so we reject them at submission
# time with a clear, actionable message. Maps host -> friendly platform name;
# matching is suffix-based, so e.g. "spotify.com" also covers open./play.
_UNSUPPORTED_DRM_HOSTS = {
'music.apple.com': 'Apple Music',
'itunes.apple.com': 'Apple Music',
'spotify.com': 'Spotify',
'tidal.com': 'Tidal',
'deezer.com': 'Deezer',
'pandora.com': 'Pandora',
}
# Third-party tools that can download audio from a DRM platform, which the user
# can then upload to us. Listed where we know of working options; platforms
# without an entry fall back to a web-search link for "<platform> downloader".
_DRM_DOWNLOADER_SUGGESTIONS = {
'Apple Music': ['https://am-dl.pages.dev', 'https://aplmate.com'],
'Spotify': ['https://spotdown.org', 'https://spotmate.online'],
}
def _drm_unsupported_detail(locale: str, platform: str) -> str:
"""
Build the user-facing 400 message for a rejected DRM streaming URL.
Platforms with known downloader tools get a "download from {tools}, then
upload" message linking each tool; everything else gets a "search the web
for a '<platform> downloader'" message linking a Google search. Either way
the goal is to guide the user to obtain the audio and upload it themselves.
"""
downloaders = _DRM_DOWNLOADER_SUGGESTIONS.get(platform)
if downloaders:
# Join with commas (locale-neutral) rather than an English "or"; the
# message wording frames them as options and LinkifiedText makes each
# URL clickable in the frontend.
return t(
locale, "audioSearch.drmUrlUnsupportedWithLink",
platform=platform, downloader=", ".join(downloaders),
)
from urllib.parse import quote_plus
search_url = "https://www.google.com/search?q=" + quote_plus(f"{platform} downloader")
return t(
locale, "audioSearch.drmUrlUnsupportedSearch",
platform=platform, searchUrl=search_url,
)
def _unsupported_url_platform(url: Optional[str]) -> Optional[str]:
"""
Return a friendly platform name if the URL belongs to a known DRM-protected
streaming service that cannot be downloaded, else None.
These links (Apple Music, Spotify, Tidal, Amazon Music, Deezer, Pandora) are
rejected at submission time instead of being allowed to create a job that
always fails deep in the download stage. Note: YouTube Music
(music.youtube.com) is downloadable and is deliberately NOT included.
"""
if not url or not isinstance(url, str):
return None
from urllib.parse import urlparse
try:
# .hostname is already lowercased and strips userinfo, port, and IPv6
# brackets, so it's safer than parsing .netloc by hand.
domain = (urlparse(url).hostname or "").lower()
except (ValueError, TypeError):
return None
if not domain:
return None
# Normalise leading www.
if domain.startswith('www.'):
domain = domain[4:]
for host, platform in _UNSUPPORTED_DRM_HOSTS.items():
if domain == host or domain.endswith('.' + host):
return platform
# Amazon Music spans many country domains (music.amazon.com, .co.uk, .co.jp,
# .fr, .de, ...), so match the music.amazon.* prefix generically.
if domain == 'music.amazon' or domain.startswith('music.amazon.'):
return 'Amazon Music'
return None
class ValidateUrlRequest(BaseModel):
"""Request to pre-validate a URL before submitting a job."""
url: str = Field(..., description="The URL the user intends to submit")
class ValidateUrlResponse(BaseModel):
"""Whether a URL can be used for a job, with a friendly reason if not."""
supported: bool
detail: Optional[str] = None
@router.post("/jobs/validate-url", response_model=ValidateUrlResponse)
async def validate_job_url(
request: Request,
body: ValidateUrlRequest,
auth_result: AuthResult = Depends(require_auth),
) -> ValidateUrlResponse:
"""
Lightweight pre-flight check for a job URL, used by the guided submission
flow so unsupported links are caught at the "Use this URL" step instead of
only at final submit. Mirrors the URL validation in create_job_from_url.
"""
locale = get_locale_from_request(request)
platform = _unsupported_url_platform(body.url)
if platform:
return ValidateUrlResponse(
supported=False, detail=_drm_unsupported_detail(locale, platform)
)
if not _validate_url(body.url):
return ValidateUrlResponse(
supported=False,
detail="Invalid URL. Please provide a valid YouTube, Vimeo, SoundCloud, or other supported video URL.",
)
return ValidateUrlResponse(supported=True)
@router.post("/jobs/create-from-url", response_model=CreateJobFromUrlResponse)
async def create_job_from_url(
request: Request,
@@ -1609,6 +1748,17 @@ async def create_job_from_url(
)
try:
# Reject DRM-protected streaming links upfront (Apple Music, Spotify,
# Tidal, etc.). These can never be downloaded, so creating a job would
# only fail deep in the pipeline with a cryptic error and tempt the user
# into a futile retry storm.
unsupported_platform = _unsupported_url_platform(body.url)
if unsupported_platform:
raise HTTPException(
status_code=400,
detail=_drm_unsupported_detail(locale, unsupported_platform),
)
# Validate URL
if not _validate_url(body.url):
raise HTTPException(
@@ -1635,6 +1785,13 @@ async def create_job_from_url(
detail = "This YouTube video is private and cannot be downloaded."
elif availability.get("is_removed"):
detail = "This YouTube video has been removed and cannot be downloaded."
elif availability.get("is_bot_blocked"):
detail = (
"We're temporarily unable to access YouTube to download this video — "
"YouTube is asking our server to verify it's not a bot. "
"Please try again in a few minutes, or use Audio Search to find this song "
"from another source."
)
elif availability.get("is_age_restricted"):
detail = "This YouTube video is age-restricted and cannot be downloaded."
else:
@@ -1777,55 +1934,47 @@ async def create_job_from_url(
if title:
logger.info(f" Title: {title}")
# For YouTube URLs, download audio NOW using YouTubeDownloadService
# This uses remote flacfetch (if configured) to avoid bot detection on Cloud Run
if _is_youtube_url(body.url):
logger.info(f"YouTube URL detected, downloading via YouTubeDownloadService")
try:
youtube_service = get_youtube_download_service()
audio_gcs_path = await youtube_service.download(
url=body.url,
job_id=job_id,
artist=artist,
title=title,
)
# Update job with the downloaded audio path
job_manager.update_job(job_id, {
'input_media_gcs_path': audio_gcs_path,
'filename': os.path.basename(audio_gcs_path),
})
logger.info(f"YouTube audio downloaded to GCS: {audio_gcs_path}")
# Use centralized start_job_processing which handles:
# 1. Validates job exists and has input_media_gcs_path
# 2. Transitions PENDING → DOWNLOADING (raises if invalid)
# 3. Triggers audio + lyrics workers in parallel
background_tasks.add_task(
job_manager.start_job_processing,
job_id,
10, # progress
"Audio downloaded, starting processing"
)
except YouTubeDownloadError as e:
logger.error(f"YouTube download failed: {e}")
job_manager.fail_job(job_id, f"YouTube download failed: {e}")
raise HTTPException(
status_code=500,
detail=t(locale, "audioSearch.youtubeDownloadError", error=str(e))
)
else:
# For non-YouTube URLs, transition to DOWNLOADING and trigger audio worker
# The audio worker will download the URL and trigger lyrics worker after
job_manager.transition_to_state(
# Download audio NOW via the flacfetch service for ALL URLs (YouTube and
# any other yt-dlp-supported site, e.g. Facebook/SoundCloud/TikTok).
# flacfetch is the sole downloader — no yt-dlp ever runs on Cloud Run.
# Downloading up front (before the GPU worker starts) also keeps the GPU
# idle until the audio is in GCS.
logger.info(f"Downloading audio from URL via flacfetch: {body.url}")
try:
download_service = get_youtube_download_service()
audio_gcs_path = await download_service.download(
url=body.url,
job_id=job_id,
new_status=JobStatus.DOWNLOADING,
progress=5,
message="Starting audio download from URL"
artist=artist,
title=title,
)
# Update job with the downloaded audio path
job_manager.update_job(job_id, {
'input_media_gcs_path': audio_gcs_path,
'filename': os.path.basename(audio_gcs_path),
})
logger.info(f"Audio downloaded to GCS: {audio_gcs_path}")
# Use centralized start_job_processing which handles:
# 1. Validates job exists and has input_media_gcs_path
# 2. Transitions PENDING → DOWNLOADING (raises if invalid)
# 3. Triggers audio + lyrics workers in parallel
background_tasks.add_task(
job_manager.start_job_processing,
job_id,
10, # progress
"Audio downloaded, starting processing"
)
except YouTubeDownloadError as e:
logger.error(f"URL download failed: {e}")
job_manager.fail_job(job_id, f"Download failed: {e}")
raise HTTPException(
status_code=500,
detail=t(locale, "audioSearch.youtubeDownloadError", error=str(e))
)
background_tasks.add_task(_trigger_audio_worker_only, job_id)
return CreateJobFromUrlResponse(
status="success",
+26
View File
@@ -15,6 +15,7 @@ from backend.services.flacfetch_client import get_flacfetch_client
from backend.services.email_service import get_email_service
from backend.services.stripe_service import get_stripe_service
from backend.services.encoding_service import get_encoding_service
from backend.services.encoding_worker_preference import infer_machine_type, PRIMARY_MACHINE_TYPE
from backend.services.spacy_preloader import get_preloaded_model, is_model_preloaded
from backend.services.nltk_preloader import get_preloaded_cmudict, is_cmudict_preloaded
from backend.services.langfuse_preloader import get_preloaded_langfuse_handler, is_langfuse_preloaded, is_langfuse_configured
@@ -443,6 +444,26 @@ async def system_status(
if manager:
try:
config = manager.get_config()
# Which VM is actually serving right now? When a capacity
# fallback is active (e.g. a c4d stockout routed us to an
# alternate family) the override points at the live VM;
# otherwise it's the blue-green primary. The primary pair is
# always c4d — fallbacks carry their family in the VM name
# (…-fallback-n2c, …-fallback-c4a), which infer_machine_type
# decodes when no explicit machine_type is stored on the config.
on_fallback = bool(config.active_override_vm)
active_vm = config.active_override_vm or config.primary_vm
default_zone = getattr(manager, "_zone", "us-central1-c")
active_zone = config.active_override_zone or default_zone
if on_fallback:
active_machine_type = infer_machine_type({"vm": active_vm})
else:
active_machine_type = (
getattr(config, "primary_machine_type", None)
or PRIMARY_MACHINE_TYPE
)
encoder_svc["admin_details"] = {
"primary_vm": config.primary_vm,
"primary_ip": config.primary_ip,
@@ -456,6 +477,11 @@ async def system_status(
"deploy_in_progress": config.deploy_in_progress,
"active_jobs": encoding_status.get("active_jobs", 0),
"queue_length": encoding_status.get("queue_length", 0),
# Currently-serving worker (fallback-aware)
"active_vm": active_vm,
"active_zone": active_zone,
"active_machine_type": active_machine_type,
"on_fallback": on_fallback,
}
except Exception as e:
logger.warning(f"Failed to get blue-green config: {e}")
+445 -35
View File
@@ -20,6 +20,7 @@ from fastapi import APIRouter, HTTPException, BackgroundTasks, Depends, Request
from pydantic import BaseModel
from backend.workers.audio_worker import process_audio_separation
from backend.workers.auto_correct_worker import process_proactive_auto_correct
from backend.workers.lyrics_worker import process_lyrics_transcription
from backend.workers.screens_worker import generate_screens
from backend.workers.video_worker import generate_video
@@ -227,6 +228,48 @@ async def trigger_lyrics_worker(
)
@router.post("/workers/auto-correct", response_model=WorkerResponse)
async def trigger_auto_correct_worker(
request: WorkerRequest,
http_request: Request,
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
):
"""Proactively pre-generate + cache AI auto-correct suggestions for a job.
Called by the lyrics worker once transcription + references are ready, so
the suggestions are cached before the reviewer opens the lyrics UI. Runs
HERE (the API service) because the service has the working Anthropic key /
compare-models config; the lyrics job does not.
Best-effort and runs synchronously within the request (the caller awaits
with its own timeout): the work never fails the karaoke job, and the
response just reports what happened. Gated by AUTO_CORRECT_PROACTIVE_ENABLED.
"""
job_id = request.job_id
# Extract trace context from incoming request (propagated via the trigger).
trace_context = extract_trace_context(dict(http_request.headers))
logger.info(f"[job:{job_id}] WORKER_TRIGGER worker=auto-correct")
add_span_attribute("job_id", job_id)
add_span_attribute("worker", "auto-correct")
# process_proactive_auto_correct already swallows its own errors; the extra
# guard keeps the endpoint itself best-effort no matter what.
try:
result = await process_proactive_auto_correct(job_id)
add_span_event("auto_correct_proactive", {"result": result.get("status", "unknown")})
return WorkerResponse(
status=result.get("status", "unknown"),
job_id=job_id,
message=f"Proactive auto-correct: {result.get('status', 'unknown')}",
)
except Exception as e: # noqa: BLE001 — best-effort, never fail the caller
logger.warning(f"[job:{job_id}] auto-correct endpoint error (non-fatal): {e}")
add_span_event("auto_correct_proactive", {"result": "error"})
return WorkerResponse(status="error", job_id=job_id, message=f"error: {e}")
@router.post("/workers/screens", response_model=WorkerResponse)
async def trigger_screens_worker(
request: WorkerRequest,
@@ -362,8 +405,9 @@ async def check_idle_reminder(
"""
Check if a job needs an idle reminder email.
This endpoint is called by a Cloud Tasks scheduled task 5 minutes after
a job enters AWAITING_REVIEW state.
This endpoint is called by a Cloud Tasks scheduled task after a job enters
a blocking state (AWAITING_REVIEW, AWAITING_AUDIO_EDIT, AWAITING_DURATION_CONFIRM,
or the legacy AWAITING_INSTRUMENTAL_SELECTION).
If the job is still in the blocking state and no reminder has been sent yet,
sends a reminder email to the user.
@@ -390,7 +434,11 @@ async def check_idle_reminder(
# Check if job is still in a blocking state
# Note: AWAITING_INSTRUMENTAL_SELECTION is LEGACY - kept for historical jobs only
blocking_states = [JobStatus.AWAITING_REVIEW, JobStatus.AWAITING_INSTRUMENTAL_SELECTION]
blocking_states = [
JobStatus.AWAITING_REVIEW,
JobStatus.AWAITING_INSTRUMENTAL_SELECTION,
JobStatus.AWAITING_DURATION_CONFIRM,
]
if job.status not in [s.value for s in blocking_states]:
logger.info(f"[job:{job_id}] Job no longer in blocking state ({job.status}), skipping reminder")
add_span_event("not_blocking", {"current_status": job.status})
@@ -424,23 +472,32 @@ async def check_idle_reminder(
# Determine action type
action_type = state_data.get('blocking_action_type')
if not action_type:
action_type = "lyrics" if job.status == JobStatus.AWAITING_REVIEW.value else "instrumental"
if job.status == JobStatus.AWAITING_REVIEW.value:
action_type = "lyrics"
elif job.status == JobStatus.AWAITING_DURATION_CONFIRM.value:
action_type = "duration_confirm"
else:
action_type = "instrumental"
# Send the reminder email
try:
notification_service = get_job_notification_service()
success = await notification_service.send_action_reminder_email(
job_id=job.job_id,
user_email=job.user_email,
action_type=action_type,
user_name=None, # Could fetch from user service if needed
artist=job.artist,
title=job.title,
audio_hash=job.audio_hash,
review_token=job.review_token,
instrumental_token=job.instrumental_token,
)
if action_type == "duration_confirm":
# Duration-confirm has its own dedicated reminder method
success = await notification_service.send_duration_confirm_reminder(job)
else:
success = await notification_service.send_action_reminder_email(
job_id=job.job_id,
user_email=job.user_email,
action_type=action_type,
user_name=None, # Could fetch from user service if needed
artist=job.artist,
title=job.title,
audio_hash=job.audio_hash,
review_token=job.review_token,
instrumental_token=job.instrumental_token,
)
if success:
# Mark reminder as sent (prevents duplicate sends)
@@ -576,64 +633,417 @@ async def trigger_gdrive_validation_endpoint(
return {"status": "error", "message": str(e)}
@router.post("/retry-pending-render-jobs")
async def retry_pending_render_jobs(
http_request: Request,
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
):
"""
Auto-retry jobs parked in RENDER_PENDING_CAPACITY.
Called every 5 minutes by Cloud Scheduler. When the GCE encoding worker
can't be started because the zone is exhausted, the render worker parks
the job in this state instead of failing it. This endpoint re-attempts
the render — when GCE has capacity, the start succeeds and the job
completes normally.
Strategy:
- Process up to MAX_PER_TICK jobs (the GCE worker is single-tenant per
render, so spinning up many in parallel just collides on the same VM)
- Pick the oldest first (longest waiter gets fairness)
- Time out jobs that have been waiting longer than MAX_WAIT_SECONDS;
transition them to FAILED with a clear permanent-failure message
- For each remaining job: clear error state, reset to REVIEW_COMPLETE,
kick off the render worker again
"""
from datetime import datetime, UTC, timedelta
from google.cloud.firestore_v1 import FieldFilter
from backend.services.worker_service import get_worker_service
from backend.models.job import JobStatus
# Long enough to ride out a sustained capacity outage but short enough
# that an op gets paged about it before the user sees a "still pending"
# job >24h old.
MAX_WAIT_SECONDS = 24 * 60 * 60 # 24h
MAX_PER_TICK = 1 # one render at a time on the GCE worker
extract_trace_context(dict(http_request.headers))
add_span_attribute("operation", "retry_pending_render_jobs")
logger.info("RETRY_PENDING_RENDER_JOBS starting")
job_manager = JobManager()
worker_service = get_worker_service()
jobs_ref = job_manager.firestore.db.collection("jobs")
# Filter by status only — sorting by updated_at server-side would require
# a composite Firestore index that we don't have. The pending-capacity
# population is small (handful of jobs at most), so streaming and
# sorting in Python is cheap and avoids the index ceremony.
pending_query = (
jobs_ref
.where(filter=FieldFilter("status", "==", JobStatus.RENDER_PENDING_CAPACITY.value))
.limit(50) # cap defensively in case the queue ever grows
)
now = datetime.now(UTC)
timed_out = []
retried = []
skipped = 0
# Materialize and sort by first_seen_at (oldest waiter first). Falls back
# to updated_at, then doc id, when meta is missing.
pending_docs = list(pending_query.stream())
def _sort_key(doc):
data = doc.to_dict() or {}
meta = (data.get("state_data") or {}).get("render_pending_capacity") or {}
first_seen = meta.get("first_seen_at") or ""
updated = data.get("updated_at")
# Firestore returns a datetime; isoformat sorts correctly within the same TZ.
updated_str = updated.isoformat() if hasattr(updated, "isoformat") else str(updated or "")
return (first_seen, updated_str, doc.id)
pending_docs.sort(key=_sort_key)
for doc in pending_docs:
job_data = doc.to_dict()
job_id = job_data.get("job_id", doc.id)
sd = job_data.get("state_data") or {}
pending_meta = sd.get("render_pending_capacity") or {}
first_seen = pending_meta.get("first_seen_at")
# Permanent-failure timeout
if first_seen:
try:
first_seen_dt = datetime.fromisoformat(first_seen)
age = now - first_seen_dt
except (ValueError, TypeError):
age = timedelta(0)
if age.total_seconds() > MAX_WAIT_SECONDS:
permanent_msg = (
"Encoding capacity remained unavailable after "
f"{int(age.total_seconds() // 3600)}h of automatic retries. "
"Please retry manually or contact support."
)
logger.error(
f"[job:{job_id}] Capacity wait exceeded {MAX_WAIT_SECONDS}s — failing permanently"
)
job_manager.fail_job(job_id, permanent_msg, error_details={
"stage": "render_video",
"permanent_capacity_timeout": True,
"first_seen_at": first_seen,
"attempts": pending_meta.get("attempt_count", 0),
})
timed_out.append(job_id)
continue
if len(retried) >= MAX_PER_TICK:
skipped += 1
continue
# Clear error state and reset render progress for idempotency.
# render_pending_capacity meta is preserved so the next failure (if any)
# increments the existing attempt counter.
job_manager.update_job(job_id, {
"error_message": None,
"error_details": None,
})
job_manager.update_state_data(job_id, "render_progress", {"stage": "pending"})
if not job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.REVIEW_COMPLETE,
progress=70,
message="Auto-retrying video render — encoding capacity check",
raise_on_invalid=False,
):
logger.warning(f"[job:{job_id}] Could not transition to REVIEW_COMPLETE for retry")
continue
try:
await worker_service.trigger_render_video_worker(job_id)
retried.append(job_id)
logger.info(f"[job:{job_id}] Auto-retry triggered")
except Exception as e:
logger.error(f"[job:{job_id}] Failed to trigger render worker: {e}")
# Job remains in REVIEW_COMPLETE — next tick will pick it up if it
# falls back to RENDER_PENDING_CAPACITY again.
add_span_event("retry_complete", {
"retried": len(retried),
"timed_out": len(timed_out),
"skipped": skipped,
})
logger.info(
f"RETRY_PENDING_RENDER_JOBS complete: retried={len(retried)} "
f"timed_out={len(timed_out)} skipped={skipped}"
)
return {
"status": "success",
"retried_jobs": retried,
"retried_count": len(retried),
"timed_out_jobs": timed_out,
"timed_out_count": len(timed_out),
"skipped_for_next_tick": skipped,
}
@router.post("/recover-stuck-jobs")
async def recover_stuck_jobs(
http_request: Request,
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)
+402 -23
View File
@@ -17,7 +17,8 @@ from pathlib import Path
from typing import List, Optional, Dict, Any
from fastapi import APIRouter, HTTPException, BackgroundTasks, Depends, Request, UploadFile, File
from datetime import datetime
from datetime import datetime, timezone
from google.cloud.exceptions import NotFound
from backend.utils.request_helpers import get_client_ip
from backend.models.job import Job, JobCreate, JobResponse, JobStatus
from backend.models.requests import (
@@ -44,7 +45,10 @@ from backend.utils.test_data import is_test_email
from backend.exceptions import InsufficientCreditsError
from backend.services.firestore_service import FirestoreService, log_to_job
from backend.models.requests import ChangeVisibilityRequest, ChangeVisibilityResponse
from pydantic import BaseModel, Field, validator
from backend.services.user_service import get_user_service
from backend.services.youtube_download_service import get_youtube_download_service
from backend.services.pricing import duration_to_credits, is_blocked
from pydantic import BaseModel, Field, HttpUrl, validator
logger = logging.getLogger(__name__)
@@ -120,6 +124,32 @@ async def create_job(
)
logger.info(f"Applying default theme: {effective_theme_id}")
# Duration-based pricing: derive credit cost from known audio duration.
# Reject inputs that are too long before any job is created.
duration_seconds = request.duration_seconds
if duration_seconds is not None and is_blocked(duration_seconds):
raise HTTPException(
status_code=422,
detail="Inputs over 60 minutes aren't supported"
)
credits = duration_to_credits(duration_seconds) if duration_seconds is not None else 1
# Anti-mismatch guard: if the client told us how many credits it expects,
# reject early if the server's computation disagrees (avoids surprise charges).
if request.acknowledged_credits is not None and request.acknowledged_credits != credits:
raise HTTPException(
status_code=409,
detail="Credit figure changed; please refresh"
)
# Build initial state_data with duration estimate for observability.
initial_state_data: Dict[str, Any] = {}
if duration_seconds is not None:
initial_state_data["duration_estimate_seconds"] = duration_seconds
initial_state_data["duration_estimate_source"] = "youtube_metadata"
else:
initial_state_data["duration_estimate_source"] = "unknown"
# Create job with all preferences
job_create = JobCreate(
url=str(request.url),
@@ -133,13 +163,18 @@ async def create_job(
webhook_url=request.webhook_url,
user_email=user_email,
is_private=request.is_private or False,
credits=credits,
)
job = job_manager.create_job(job_create, is_admin=auth_result.is_admin)
# Store client IP on job for anti-abuse correlation
# Persist duration estimate fields and creation_ip in a single Firestore write.
update_payload = {
f"state_data.{k}": v for k, v in initial_state_data.items()
}
creation_ip = get_client_ip(http_request)
if creation_ip:
FirestoreService().update_job(job.job_id, {"creation_ip": creation_ip})
update_payload["creation_ip"] = creation_ip
FirestoreService().update_job(job.job_id, update_payload)
# Trace attributes for observability
add_span_attribute("job_id", job.job_id)
@@ -160,7 +195,7 @@ async def create_job(
job_id=job.job_id,
message=t(locale, "jobs.created")
)
except InsufficientCreditsError:
except (InsufficientCreditsError, HTTPException):
raise
except Exception as e:
logger.error(f"Error creating job: {e}", exc_info=True)
@@ -362,6 +397,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:
@@ -536,11 +576,58 @@ _SUMMARY_STATE_DATA_KEYS = {
'audio_progress', 'lyrics_progress',
'audio_complete', 'lyrics_complete',
'backing_vocals_analysis', 'visibility_change_in_progress',
'render_pending_capacity',
'cloud_run_retry_pending',
'credits_charged',
'pending_additional_credits',
'duration_actual_seconds',
'duration_confirm_reason',
'batch_id',
'bulk_auto_selected',
}
_SUMMARY_FILE_URLS_KEYS = {'finals', 'videos', 'packages'}
_HIDE_COMPLETED_STATUSES = ['complete', 'prep_complete', 'cancelled']
def _is_auto_retry_pending(state_data: Optional[Dict[str, Any]]) -> bool:
"""Return True if a Cloud Run Job auto-retry is currently expected.
The audio-download worker records `state_data.cloud_run_retry_pending`
with an `expires_at` when it fails and another task attempt is coming.
The /retry endpoint uses this to refuse starting a parallel execution,
and the UI uses the projected field to show a "Retrying automatically..."
indicator instead of a Retry button.
"""
pending = (state_data or {}).get('cloud_run_retry_pending')
if not isinstance(pending, dict):
return False
expires_at_str = pending.get('expires_at')
if not expires_at_str:
return False
try:
expires_at = datetime.fromisoformat(str(expires_at_str).replace('Z', '+00:00'))
except (ValueError, AttributeError):
return False
if expires_at.tzinfo is None:
expires_at = expires_at.replace(tzinfo=timezone.utc)
return expires_at > datetime.now(timezone.utc)
def _has_title_screen(file_urls: Dict[str, Any]) -> bool:
"""Return True if a title screen image (jpg or png) was generated.
Used by the /retry endpoint to decide whether to resume from the render
stage or rewind further. The actual screen URLs live under format-specific
keys (`title_jpg`, `title_png`) rather than a bare `title` key, so a
naive `screens.get('title')` check produced false-negatives and forced
completed-review jobs back to AWAITING_REVIEW.
"""
screens = file_urls.get('screens') or {}
if not isinstance(screens, dict):
return False
return any(k == 'title' or k.startswith('title_') for k in screens)
def _prune_state_data(data: Dict[str, Any]) -> Dict[str, Any]:
"""Strip state_data down to dashboard-required keys."""
sd = data.get('state_data')
@@ -995,14 +1082,23 @@ async def submit_corrections(
)
try:
# Strip reference_lyrics from Firestore save to avoid exceeding 1MB document
# limit. reference_lyrics can be very large (e.g. Genius fetching non-lyrics
# content like screenplays). The full data is preserved in the GCS upload below.
corrections_for_firestore = {
k: v for k, v in submission.corrections.items()
if k != 'reference_lyrics'
# Persist ONLY a lightweight summary of the corrections to Firestore —
# never the full segment arrays. The complete corrections JSON
# (corrected_segments, original_segments, resized_segments, etc.) can be
# several MB for long songs (e.g. a 30+ minute mashup with hundreds of
# segments) and would blow past Firestore's 1MB per-document hard limit,
# failing the save with a 400. (An earlier fix stripped only
# reference_lyrics, but the segment arrays are the real bulk.) The full
# data is preserved in the GCS upload below (corrections_updated.json),
# which the render worker reads. The only in-Firestore consumer is the
# complete-review 0-segment guard, which just needs the segment count.
corrected_segments = submission.corrections.get('corrected_segments')
corrected_lyrics_summary = {
'corrected_segment_count': (
len(corrected_segments) if isinstance(corrected_segments, list) else 0
),
}
job_manager.update_state_data(job_id, 'corrected_lyrics', corrections_for_firestore)
job_manager.update_state_data(job_id, 'corrected_lyrics', corrected_lyrics_summary)
if submission.user_notes:
job_manager.update_state_data(job_id, 'review_notes', submission.user_notes)
@@ -1024,6 +1120,18 @@ async def submit_corrections(
from backend.services.storage_service import StorageService
storage = StorageService()
# Safety net: never persist word timings that fall outside their segment.
# Frontend should already prevent this; this guarantees clean stored data
# (the render worker reads corrections_updated.json verbatim).
from backend.services.timing_sanitizer import sanitize_corrections
sanitized, clamp_count = sanitize_corrections(submission.corrections)
if clamp_count:
logger.warning(
f"Job {job_id}: sanitized {clamp_count} out-of-bounds word timing(s) "
f"in submitted corrections before persisting"
)
submission.corrections = sanitized
corrections_gcs_path = f"jobs/{job_id}/lyrics/corrections_updated.json"
storage.upload_json(corrections_gcs_path, submission.corrections)
job_manager.update_file_url(job_id, 'lyrics', 'corrections_updated', corrections_gcs_path)
@@ -1358,10 +1466,15 @@ async def complete_review(
lyrics_metadata = state_data.get('lyrics_metadata')
if lyrics_metadata is not None:
segment_count = lyrics_metadata.get('segment_count', 0)
corrected_lyrics = state_data.get('corrected_lyrics', {})
corrected_segments = corrected_lyrics.get('corrected_segments', [])
corrected_lyrics = state_data.get('corrected_lyrics') or {}
# corrected_lyrics now stores a lightweight summary
# ({'corrected_segment_count': N}). Fall back to the legacy shape (full
# dict with a corrected_segments list) for jobs saved before that change.
corrected_segment_count = corrected_lyrics.get('corrected_segment_count')
if corrected_segment_count is None:
corrected_segment_count = len(corrected_lyrics.get('corrected_segments') or [])
if segment_count == 0 and len(corrected_segments) == 0:
if segment_count == 0 and corrected_segment_count == 0:
raise HTTPException(
status_code=400,
detail=t(locale, "jobs.noLyricsDetected")
@@ -1370,6 +1483,13 @@ async def complete_review(
try:
# Store instrumental selection if provided (combined review flow)
instrumental_selection = body.instrumental_selection if body else None
# Jobs that supplied their own instrumental (existing_instrumental flow, e.g. tenant
# submissions) have no instrumental-selection UI step. Default to 'custom' so the
# render uses the provided instrumental instead of a separated stem that was never
# produced (the orchestrator otherwise defaults to 'clean' and fails prerequisites).
if not instrumental_selection and getattr(job, 'existing_instrumental_gcs_path', None):
instrumental_selection = 'custom'
logger.info(f"Job {job_id}: Defaulting instrumental selection to 'custom' (existing instrumental provided)")
if instrumental_selection:
job_manager.update_state_data(job_id, 'instrumental_selection', instrumental_selection)
logger.info(f"Job {job_id}: Stored instrumental selection: {instrumental_selection}")
@@ -1527,6 +1647,17 @@ DOWNLOAD_FILENAME_SUFFIXES = {
}
def _cleanup_temp_file(path: Optional[str]) -> None:
"""Best-effort removal of a temp file created for a download that failed
before streaming started (so it never reaches the iterator's cleanup)."""
if not path:
return
try:
os.unlink(path)
except OSError:
pass
@router.get("/{job_id}/download/{category}/{file_key}")
async def download_file(
job_id: str,
@@ -1600,6 +1731,11 @@ async def download_file(
else:
filename = gcs_path.split('/')[-1] # Fallback to original
# Created below with delete=False; the streaming iterator's finally removes it
# on the happy path. If download/setup raises before streaming starts, the
# except handlers below unlink it so failed (e.g. 404) requests don't leak
# temp files and fill local disk.
tmp_path = None
try:
# Download to temp file and stream
storage = StorageService()
@@ -1635,7 +1771,16 @@ async def download_file(
'Content-Disposition': content_disposition
}
)
except NotFound:
# The recorded output is gone from GCS (e.g. a stale download link hit
# mid-reprocess after a visibility change / edit deleted the finals). This
# is "not found", not a server error — return 404 and log at warning so it
# doesn't trip the error-monitor.
_cleanup_temp_file(tmp_path)
logger.warning(f"Download requested for missing object {gcs_path}")
raise HTTPException(status_code=404, detail=t(locale, "jobs.fileNoLongerAvailable"))
except Exception as e:
_cleanup_temp_file(tmp_path)
logger.error(f"Error downloading {gcs_path}: {e}")
raise HTTPException(status_code=500, detail=f"Error downloading file: {e}")
@@ -1707,6 +1852,15 @@ async def retry_job(
detail=t(locale, "jobs.notCompleted", status=job.status)
)
# Refuse if a Cloud Run Job auto-retry is already coming for this job.
# Otherwise the manual retry races with the automatic one and produces
# duplicate downloads and downstream worker triggers (see job 8a9c74ff).
if _is_auto_retry_pending(job.state_data):
raise HTTPException(
status_code=409,
detail="An automatic retry is already in progress. Please wait a few minutes."
)
try:
# Determine retry point based on what's already complete
error_details = job.error_details or {}
@@ -1758,7 +1912,7 @@ async def retry_job(
# Review completion is proven by instrumental_selection in state_data
# (set only when user submits the review endpoint)
elif (file_urls.get('lyrics', {}).get('corrections') and
file_urls.get('screens', {}).get('title') and
_has_title_screen(file_urls) and
state_data.get('instrumental_selection')):
logger.info(f"Job {job_id}: Has corrections, screens, and completed review — retrying from render stage")
@@ -1795,7 +1949,7 @@ async def retry_job(
# If we have corrections and screens but review was NOT completed,
# return to awaiting_review so the user can review lyrics
elif (file_urls.get('lyrics', {}).get('corrections') and
file_urls.get('screens', {}).get('title')):
_has_title_screen(file_urls)):
logger.info(f"Job {job_id}: Has corrections and screens but review not completed — returning to review")
@@ -1859,9 +2013,18 @@ async def retry_job(
"retry_stage": "screens_generation"
}
# If we have input audio (uploaded or from URL), restart from beginning
elif job.input_media_gcs_path or job.url:
logger.info(f"Job {job_id}: Has input audio, restarting from beginning")
# If the input audio is already in GCS (an uploaded file, or a URL whose
# download succeeded), restart from beginning — the audio/lyrics workers
# re-fetch it from GCS.
#
# A URL job whose download never succeeded has only `job.url` and NO
# audio in GCS, so it must NOT take this branch: triggering the workers
# would just fail with "Failed to download audio file" and Cloud Run
# would retry them repeatedly (see job 7f36304a — an Apple Music link).
# Such jobs fall through to the "resubmit" refusal below, since there is
# no worker that re-downloads a generic URL.
elif job.input_media_gcs_path:
logger.info(f"Job {job_id}: Has input audio in GCS, restarting from beginning")
# Clear error state and any partial progress
job_manager.update_job(job_id, {
@@ -2150,6 +2313,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",
@@ -2320,11 +2491,21 @@ async def create_job_from_search(
from backend.services.job_defaults_service import resolve_cdg_txt_defaults
resolved_cdg, resolved_txt = resolve_cdg_txt_defaults(effective_theme_id, None, None)
# Determine display values
# Determine display values.
# The session stores the ORIGINAL search query (e.g. "hard-fi"). body.artist/
# body.title carry whatever is currently in the wizard's artist/title fields,
# which reflect a "Use official formatting" correction the user may have applied
# after searching. The displayed job name must honour that correction, so prefer
# the request body over the stored query. An explicit display override wins above all.
session_artist = session.get('artist', body.artist)
session_title = session.get('title', body.title)
effective_display_artist = body.display_artist or session_artist
effective_display_title = body.display_title or session_title
# body.artist/body.title are required but unvalidated for whitespace, so strip
# them and fall back to the stored query if blank (display_* is pre-stripped to
# None by its validator). This keeps a stray " " from becoming the job name.
body_artist = (body.artist or "").strip()
body_title = (body.title or "").strip()
effective_display_artist = body.display_artist or body_artist or session_artist
effective_display_title = body.display_title or body_title or session_title
tenant_id = session.get('tenant_id') or ""
@@ -2497,3 +2678,201 @@ async def change_visibility(
except Exception as e:
logger.error(f"Error changing visibility for job {job_id}: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=f"Failed to change visibility: {str(e)}")
# =============================================================================
# Duration Confirmation Endpoint
# =============================================================================
class ConfirmDurationRequest(BaseModel):
"""Request body for POST /jobs/{job_id}/confirm-duration."""
acknowledged_credits: int
# Keep a set of background tasks alive to prevent GC (mirrors complete_review pattern)
_duration_confirm_tasks: set = set()
@router.post("/{job_id}/confirm-duration")
async def confirm_duration(
job_id: str,
body: ConfirmDurationRequest,
http_request: Request,
auth_result: AuthResult = Depends(require_auth),
):
"""
Confirm duration-based credit charge and resume job processing.
Called when a job is paused in AWAITING_DURATION_CONFIRM state.
The only pause reason currently used is ``reconcile``: the actual measured
duration costs more than was already charged; ``state_data.pending_additional_credits``
holds the delta owed. This applies to URL, upload, and audio-search jobs alike.
The caller must pass ``acknowledged_credits`` equal to the total credit cost
the user has agreed to pay. If the figure has changed (race condition) a 409
is returned so the frontend can refresh and re-show the dialog.
"""
locale = get_locale_from_request(http_request)
# 1. Load job — 404 if not found or not owned by this user.
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
if not _check_job_ownership(job, auth_result):
# Return 404 (not 403) to avoid leaking job existence to non-owners.
raise HTTPException(status_code=404, detail=t(locale, "jobs.notFound"))
# 2. Status guard.
if job.status != JobStatus.AWAITING_DURATION_CONFIRM:
raise HTTPException(
status_code=409,
detail=f"Job is not awaiting duration confirmation (status: {job.status})",
)
# 3. Compute owed credits and expected total.
#
# - credits_charged: total already deducted from the user's account
# - pending_additional_credits: exactly how many MORE credits are owed to clear the pause
#
# The reconcile engine is responsible for computing and storing pending_additional_credits.
# confirm_duration never needs to call duration_to_credits.
state_data = job.state_data or {}
reason = state_data.get("duration_confirm_reason", "reconcile")
credits_charged = int(state_data.get("credits_charged", 0))
owed = int(state_data.get("pending_additional_credits", 0))
expected_total = credits_charged + owed
# 4. Acknowledged-credits mismatch guard (figure may have changed; client refreshes).
if body.acknowledged_credits != expected_total:
raise HTTPException(
status_code=409,
detail=(
f"acknowledged_credits ({body.acknowledged_credits}) does not match "
f"expected total ({expected_total}). Please refresh and confirm again."
),
)
# 5. Deduct credits if any are owed.
if owed > 0:
user_email = job.user_email
if not user_email:
raise HTTPException(status_code=500, detail="Job has no associated user email")
user_svc = get_user_service()
success, _remaining, _msg = user_svc.deduct_credits(
user_email,
job_id,
amount=owed,
reason="duration_confirm",
count_as_job_creation=False, # job was already counted at create_job()
)
if not success:
raise InsufficientCreditsError(
message=f"Insufficient credits to confirm processing ({owed} credit(s) required).",
credits_available=_remaining,
credits_required=owed,
)
# Update credits_charged in state_data to reflect the new total.
job_manager.update_job(
job_id,
{
"state_data.credits_charged": credits_charged + owed,
"state_data.duration_confirmed": True,
"state_data.pending_additional_credits": 0,
},
)
else:
# owed == 0: nothing to charge, just mark confirmed.
job_manager.update_job(
job_id,
{
"state_data.duration_confirmed": True,
"state_data.pending_additional_credits": 0,
},
)
# 6. Transition job OUT of AWAITING_DURATION_CONFIRM before triggering workers.
#
# This is the idempotency guard: if a duplicate confirm POST arrives (e.g. a
# double-click) the status guard at step 2 will now 409 immediately, preventing
# a second pair of worker launches. We transition to SEPARATING_STAGE1 —
# the normal next state for both the audio and lyrics parallel tracks — which is
# a valid transition from AWAITING_DURATION_CONFIRM per STATE_TRANSITIONS.
# The audio and lyrics workers update their own track states from here on, the
# same as the normal convergence path.
job_manager.transition_to_state(
job_id,
new_status=JobStatus.SEPARATING_STAGE1,
progress=20,
message="Cost confirmed, processing",
)
# 7. Resume processing: trigger both parallel workers in background.
# Use asyncio.create_task (mirrors complete_review in review.py) so the HTTP
# response returns immediately without waiting for Cloud Run job submission.
ws = get_worker_service()
async def _trigger_workers_after_confirm():
try:
await asyncio.gather(
ws.trigger_audio_worker(job_id),
ws.trigger_lyrics_worker(job_id),
)
except Exception as exc:
logger.error(f"Job {job_id}: Failed to trigger workers after duration confirm: {exc}")
task = asyncio.create_task(_trigger_workers_after_confirm())
_duration_confirm_tasks.add(task)
task.add_done_callback(_duration_confirm_tasks.discard)
logger.info(
f"Job {job_id}: duration confirmed (reason={reason}, owed={owed}); workers triggered"
)
# 8. Return the updated job.
updated_job = job_manager.get_job(job_id)
if updated_job is None:
# Should not happen, but be safe.
return {"job_id": job_id, "status": "confirmed"}
return updated_job
# ---------------------------------------------------------------------------
# POST /jobs/estimate — URL duration probe
# ---------------------------------------------------------------------------
class EstimateRequest(BaseModel):
url: HttpUrl
@router.post("/estimate")
async def estimate_duration(
body: EstimateRequest,
auth_result: AuthResult = Depends(require_auth),
):
"""
Probe a URL to estimate its duration and compute the credit cost,
WITHOUT creating a job or downloading any audio.
Returns duration_seconds (or None if unknown), source, credits, and
whether the duration exceeds the supported ceiling (blocked).
"""
info = await get_youtube_download_service().check_availability(str(body.url))
seconds = (info or {}).get("duration")
if seconds is None:
return {
"duration_seconds": None,
"source": "unknown",
"credits": 1,
"blocked": False,
}
return {
"duration_seconds": seconds,
"source": "youtube_metadata",
"credits": duration_to_credits(seconds),
"blocked": is_blocked(seconds),
}
+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}
+168 -28
View File
@@ -22,8 +22,7 @@ from pathlib import Path
from typing import Dict, Any, List, Optional, Set, Tuple
from fastapi import APIRouter, HTTPException, Request, Depends, Form, File, UploadFile
from fastapi.responses import FileResponse, RedirectResponse, StreamingResponse
from starlette.background import BackgroundTask
from fastapi.responses import RedirectResponse
from backend.models.job import JobStatus
from backend.models.review_session import ReviewSession, ReviewSessionSummary
@@ -37,6 +36,7 @@ from backend.api.dependencies import require_auth, require_review_auth
from backend.services.auth_service import UserType
from backend.config import get_settings
from backend.i18n import t, get_locale_from_request
from backend.services.duration_reconciliation import reconcile_and_maybe_pause
from pydantic import BaseModel as _PydBaseModel
from backend.services.custom_lyrics_service import (
@@ -44,6 +44,11 @@ from backend.services.custom_lyrics_service import (
CustomLyricsServiceError,
get_custom_lyrics_service,
)
from backend.services.auto_correct import (
AutoCorrectService,
AutoCorrectServiceError,
get_auto_correct_service,
)
class LineMetadataResponse(_PydBaseModel):
@@ -70,11 +75,49 @@ class CustomLyricsResponse(_PydBaseModel):
model: str
class AutoCorrectRequest(_PydBaseModel):
segments: list[dict] # client's current working corrected_segments
reference_lyrics: dict # client's reference sources (incl. user-added)
artist: Optional[str] = None
title: Optional[str] = None
settings: Optional[dict] = None # AutoCorrectSettings knobs
class AutoCorrectSuggestionResponse(_PydBaseModel):
id: str
op: str # "replace" | "delete" | "insert_after"
word_ids: list[str]
segment_ids: list[str]
original_text: str
new_text: str
reason: str
category: str
confidence: float
models: list[str]
consensus: int
total_models: int
conflict_group: Optional[str] = None
class AutoCorrectResponse(_PydBaseModel):
suggestions: list[AutoCorrectSuggestionResponse]
model: str
elapsed_seconds: float
settings_applied: dict
warnings: list[str]
cached: bool = False
def _get_custom_lyrics_service_dep() -> CustomLyricsService:
"""FastAPI dependency wrapper around the singleton accessor."""
return get_custom_lyrics_service()
def _get_auto_correct_service_dep() -> AutoCorrectService:
"""FastAPI dependency wrapper around the singleton accessor."""
return get_auto_correct_service()
async def _load_target_segments_for_custom_lyrics(
job_id: str,
target_lines: list[str],
@@ -142,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
@@ -636,6 +680,79 @@ async def generate_custom_lyrics(
)
@router.post("/{job_id}/auto-correct", response_model=AutoCorrectResponse)
async def auto_correct_suggestions(
job_id: str,
body: AutoCorrectRequest,
auth_info: Tuple[str, str] = Depends(require_review_auth),
service: AutoCorrectService = Depends(_get_auto_correct_service_dep),
) -> AutoCorrectResponse:
"""Generate AI auto-correction suggestions for the lyrics review UI.
Stateless and strictly opt-in: one whole-song LLM call comparing the
client's current working transcription against the reference lyrics.
Returns word-id-keyed suggestions; nothing is applied server-side —
the reviewer accepts or rejects each suggestion individually and
persistence happens via the existing corrections/complete paths.
"""
from backend.services.auto_correct.settings import settings_from_dict
try:
settings = settings_from_dict(body.settings or {})
except ValueError as exc:
raise HTTPException(status_code=400, detail=f"invalid settings: {exc}") from exc
with job_log_context(job_id), create_span("auto_correct_suggestions"):
add_span_attribute("job_id", job_id)
add_span_attribute("segment_count", len(body.segments))
logger.info(
"auto-correct requested job=%s segments=%d sources=%d",
job_id, len(body.segments), len(body.reference_lyrics),
)
try:
result = await asyncio.to_thread(
service.suggest,
job_id=job_id,
segments=body.segments,
reference_lyrics=body.reference_lyrics,
artist=body.artist,
title=body.title,
settings=settings,
)
except AutoCorrectServiceError as exc:
raise HTTPException(status_code=exc.status_code, detail=str(exc)) from exc
logger.info(
"auto-correct completed job=%s suggestions=%d model=%s elapsed=%.1fs",
job_id, len(result.suggestions), result.model, result.elapsed_seconds,
)
return AutoCorrectResponse(
suggestions=[
AutoCorrectSuggestionResponse(
id=s.id,
op=s.op,
word_ids=s.word_ids,
segment_ids=s.segment_ids,
original_text=s.original_text,
new_text=s.new_text,
reason=s.reason,
category=s.category,
confidence=s.confidence,
models=s.models,
consensus=s.consensus,
total_models=s.total_models,
conflict_group=s.conflict_group,
)
for s in result.suggestions
],
model=result.model,
elapsed_seconds=result.elapsed_seconds,
settings_applied=result.settings_applied.to_dict(),
warnings=result.warnings,
cached=result.cached,
)
@router.post("/{job_id}/handlers")
async def update_handlers(
job_id: str,
@@ -1110,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))
@@ -1125,9 +1249,19 @@ async def get_preview_video(
preview_hash: str,
auth_info: Tuple[str, str] = Depends(require_review_auth)
):
"""Stream the generated preview video."""
"""Serve the generated preview video via a signed GCS URL redirect.
We redirect to a signed URL rather than proxying the bytes through Cloud
Run because Cloud Run caps response bodies at 32 MiB. Long songs (e.g. a
30+ minute mashup) produce a 360p preview larger than that, which the proxy
path truncated mid-stream — the response started as 206 but the client
received a 500, so the browser reported "no supported format". The signed
URL lets the browser fetch the mp4 directly from GCS (with byte-range
support intact), bypassing the limit entirely. Mirrors the audio-review
endpoint above.
"""
storage = StorageService()
# Check in-memory cache first
preview_gcs_path = None
if job_id in _preview_videos and preview_hash in _preview_videos[job_id]:
@@ -1137,30 +1271,14 @@ async def get_preview_video(
preview_gcs_path = f"jobs/{job_id}/previews/{preview_hash}.mp4"
if not storage.file_exists(preview_gcs_path):
raise HTTPException(status_code=404, detail=t("en", "review.previewVideoNotFound"))
try:
# Download to temp file and stream
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as tmp:
tmp_path = tmp.name
storage.download_file(preview_gcs_path, tmp_path)
logger.info(f"Job {job_id}: Streaming preview video {preview_hash}")
return FileResponse(
tmp_path,
media_type="video/mp4",
filename=f"preview_{preview_hash}.mp4",
headers={
"Accept-Ranges": "bytes",
"Content-Disposition": "inline",
"Cache-Control": "no-cache",
},
background=BackgroundTask(os.unlink, tmp_path),
)
signed_url = storage.generate_signed_url(preview_gcs_path, expiration_minutes=120)
logger.info(f"Job {job_id}: Redirecting to signed URL for preview video {preview_hash}")
return RedirectResponse(url=signed_url, status_code=302)
except Exception as e:
logger.error(f"Job {job_id}: Error streaming preview video: {e}", exc_info=True)
logger.error(f"Job {job_id}: Error serving preview video: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=t("en", "review.previewVideoStreamError", error=str(e)))
@@ -1823,7 +1941,8 @@ async def apply_audio_edit(
"""
Apply an edit operation to the input audio.
Supported operations: trim_start, trim_end, cut, mute, join_start, join_end.
Supported operations: trim_start, trim_end, cut, mute, fade_in, fade_out,
join_start, join_end.
Returns updated waveform data and playback URL.
"""
import uuid
@@ -1837,7 +1956,7 @@ async def apply_audio_edit(
if not operation:
raise HTTPException(status_code=400, detail="Missing 'operation' field")
valid_operations = {"trim_start", "trim_end", "cut", "mute", "join_start", "join_end"}
valid_operations = {"trim_start", "trim_end", "cut", "mute", "fade_in", "fade_out", "join_start", "join_end"}
if operation not in valid_operations:
raise HTTPException(status_code=400, detail=f"Invalid operation: {operation}. Valid: {valid_operations}")
@@ -2182,6 +2301,27 @@ async def submit_audio_edit(
message="Audio edit complete, starting processing"
)
# Reconcile credit charge against the (possibly-edited) audio before triggering workers.
# reconcile_and_maybe_pause probes job.input_media_gcs_path — which was just updated above
# to point to the edited audio (jobs/{job_id}/input/edited.flac) if edits were applied.
if await reconcile_and_maybe_pause(job_id):
# Job paused (AWAITING_DURATION_CONFIRM) or cancelled — do not start processing.
# Reload to distinguish the two outcomes so the caller can surface the right message.
reloaded = job_manager.get_job(job_id)
if reloaded and reloaded.status in (JobStatus.CANCELLED, JobStatus.FAILED):
return {
"status": "cancelled",
"message": "Audio edit saved. Job was cancelled — audio exceeds the supported limit.",
"job_id": job_id,
"edits_applied": len(edit_stack),
}
return {
"status": "paused",
"message": "Audio edit saved. Additional credits are required to continue processing.",
"job_id": job_id,
"edits_applied": len(edit_stack),
}
# Trigger parallel workers in background so the HTTP response returns immediately.
# The worker triggers involve Cloud Run Job calls that can take 30+ seconds;
# waiting synchronously causes the browser request to time out.
+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,
+71
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")
@@ -61,6 +72,17 @@ class Settings(BaseSettings):
# use uncorrected transcription - human review will fix any issues.
agentic_correction_timeout_seconds: int = int(os.getenv("AGENTIC_CORRECTION_TIMEOUT_SECONDS", "180"))
# Lyrics transcription outer (safety-net) timeout, scaled by audio duration.
# Long inputs (e.g. 30+ minute mashups) legitimately take longer to transcribe,
# so the timeout = clamp(floor, duration * per_audio_second, cap). The cap must
# stay under the Cloud Run Job task timeout so we surface a clean RuntimeError
# before the platform hard-kills the task. The lyrics-transcription-job sets the
# task timeout to 3000s and overrides this cap to 2700s via env; the 1700s
# default here is the safe value if that env is ever unset (under an 1800s task).
transcription_timeout_floor_seconds: int = int(os.getenv("TRANSCRIPTION_TIMEOUT_FLOOR_SECONDS", "1200"))
transcription_timeout_cap_seconds: int = int(os.getenv("TRANSCRIPTION_TIMEOUT_CAP_SECONDS", "1700"))
transcription_timeout_per_audio_second: float = float(os.getenv("TRANSCRIPTION_TIMEOUT_PER_AUDIO_SECOND", "1.0"))
# AI Credit Evaluation (anti-abuse gating for free credits)
# When enabled, welcome and feedback credit grants are evaluated by Gemini
# before granting. Fail-open: if evaluation fails, credits are granted anyway.
@@ -77,6 +99,48 @@ class Settings(BaseSettings):
custom_lyrics_default_strictness: str = os.getenv("CUSTOM_LYRICS_DEFAULT_STRICTNESS", "balanced")
custom_lyrics_max_output_lines_multiplier: float = float(os.getenv("CUSTOM_LYRICS_MAX_OUTPUT_LINES_MULTIPLIER", "2.0"))
# AI auto-correct suggestions — opt-in, user-triggered from the lyrics
# review UI. Stateless: one whole-song LLM call returning word-level
# suggestions the reviewer accepts/rejects individually.
auto_correct_model: str = os.getenv("AUTO_CORRECT_MODEL", "gemini-3.1-pro-preview")
# Models used by the multi-model "compare" mode (semicolon-separated —
# Cloud Run --set-env-vars is comma-delimited). Empty = single-model only.
auto_correct_compare_models: str = os.getenv("AUTO_CORRECT_COMPARE_MODELS", "")
# Proactively generate (and cache) auto-correct suggestions in the lyrics
# worker once transcription + references are ready, so the review UI has
# them instantly. Best-effort: failures never block or fail the job. Only
# meaningful where ANTHROPIC_API_KEY + AUTO_CORRECT_COMPARE_MODELS are set
# (the lyrics-transcription-job, via ci.yml). Default off.
auto_correct_proactive_enabled: bool = os.getenv(
"AUTO_CORRECT_PROACTIVE_ENABLED", "false"
).lower() in ("true", "1", "yes")
# Match judge — artist/title formatting + match-acceptance for the job
# submission flow. Deterministic + catalog layers always run; the light AI
# layer (Vertex Gemini Flash) fires only when those aren't confident.
match_judge_enabled: bool = os.getenv("MATCH_JUDGE_ENABLED", "true").lower() in (
"true", "1", "yes",
)
match_judge_model: str = os.getenv("MATCH_JUDGE_MODEL", "gemini-3.5-flash")
# Bounds the AI call so a hung model never strands the submission UI. Kept
# generous because Vertex returns 504 DEADLINE_EXCEEDED if generation can't
# finish within this deadline (3s was too tight for gemini-3.5-flash); the
# 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)
@@ -97,6 +161,13 @@ class Settings(BaseSettings):
encoding_worker_url: Optional[str] = os.getenv("ENCODING_WORKER_URL") # e.g., http://136.119.50.148:8080
encoding_worker_api_key: Optional[str] = os.getenv("ENCODING_WORKER_API_KEY")
# Optional capacity-fallback VMs in alternate zones. JSON list of objects:
# '[{"vm":"encoding-worker-fallback-a","zone":"us-central1-a","ip":"34.x.x.x"}]'
# Empty by default. After `pulumi up` provisions the fallback VMs (Phase 3
# of the capacity-resilience plan), populate this var with their public
# IPs to enable multi-zone failover when us-central1-c is exhausted.
encoding_worker_fallback_vms: Optional[str] = os.getenv("ENCODING_WORKER_FALLBACK_VMS")
# GCE Preview Encoding (for faster preview video generation)
# When enabled, preview video encoding during lyrics review is offloaded to the GCE worker.
# This reduces preview generation time from 60+ seconds to ~15-20 seconds.
+35 -4
View File
@@ -1,5 +1,8 @@
"""
FastAPI application entry point for karaoke generation backend.
(Trivial comment touch to trigger backend CI on ephemeral runners after
the 2026-05-17 dispatcher e2 fix; safe to remove on next backend edit.)
"""
import logging
from contextlib import asynccontextmanager
@@ -7,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
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
@@ -15,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
@@ -103,18 +107,37 @@ async def lifespan(app: FastAPI):
yield
# Shutdown - wait for any active workers to complete before terminating
# This prevents Cloud Run from killing workers mid-processing
# This prevents Cloud Run from killing workers mid-processing.
#
# Cloud Run gen2 default termination grace period is 600s. We wait up to
# 480s, leaving ~120s for the cleanup pass below to write Firestore state
# before SIGKILL. Without that headroom, render jobs that miss the wait
# would sit in `rendering_video` forever waiting for an operator.
logger.info("Shutdown requested, checking for active workers...")
if worker_registry.has_active_workers():
active = worker_registry.get_active_workers()
logger.info(f"Active workers found: {active}")
logger.info("Waiting for workers to complete (timeout: 600s)...")
completed = await worker_registry.wait_for_completion(timeout=600) # 10 min max
logger.info("Waiting for workers to complete (timeout: 480s)...")
completed = await worker_registry.wait_for_completion(timeout=480)
if not completed:
logger.error(
"Shutdown timeout - some workers may not have completed cleanly. "
f"Remaining workers: {worker_registry.get_active_workers()}"
)
# Park any still-active render jobs so the auto-retry scheduler can
# recover them. Safe to call unconditionally — it's a no-op if nothing
# render-related is in flight.
try:
from backend.workers.render_video_worker import park_active_render_jobs_for_shutdown
parked = park_active_render_jobs_for_shutdown()
if parked:
logger.warning(
f"Parked {parked} in-flight render job(s) for auto-retry "
f"due to shutdown"
)
except Exception as exc:
logger.error(f"Render-job shutdown park failed: {exc!r}")
else:
logger.info("No active workers, proceeding with shutdown")
@@ -148,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")
@@ -165,6 +194,8 @@ 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"})
+44 -5
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
@@ -45,6 +46,9 @@ class JobStatus(str, Enum):
IN_AUDIO_EDIT = "in_audio_edit" # User is actively editing audio
AUDIO_EDIT_COMPLETE = "audio_edit_complete" # User submitted edited audio
# Optional: duration cost confirmation (BLOCKING) - confirm credits before heavy processing
AWAITING_DURATION_CONFIRM = "awaiting_duration_confirm" # ⚠️ WAITING FOR USER - confirm duration-based cost
# Stage 2a: Audio separation (parallel track 1)
SEPARATING_STAGE1 = "separating_stage1" # Clean instrumental separation (Modal API)
SEPARATING_STAGE2 = "separating_stage2" # Backing vocals separation (Modal API)
@@ -68,6 +72,7 @@ class JobStatus(str, Enum):
# Stage 5.5: Render video with corrected lyrics (post-review)
RENDERING_VIDEO = "rendering_video" # Using OutputGenerator to create with_vocals.mkv
RENDER_PENDING_CAPACITY = "render_pending_capacity" # Waiting for GCE encoding capacity (auto-retry)
# Stage 6: Instrumental already selected (during combined review)
# Note: AWAITING_INSTRUMENTAL_SELECTION kept for DB compatibility with historical jobs only
@@ -106,16 +111,27 @@ 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.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
JobStatus.DOWNLOADING: [JobStatus.SEPARATING_STAGE1, JobStatus.TRANSCRIBING, JobStatus.GENERATING_SCREENS, JobStatus.AWAITING_AUDIO_EDIT, JobStatus.FAILED],
JobStatus.DOWNLOADING: [JobStatus.SEPARATING_STAGE1, JobStatus.TRANSCRIBING, JobStatus.GENERATING_SCREENS, JobStatus.AWAITING_AUDIO_EDIT, JobStatus.AWAITING_DURATION_CONFIRM, JobStatus.FAILED],
# Optional audio edit phase (trim, cut, mute, join input audio before processing)
JobStatus.AWAITING_AUDIO_EDIT: [JobStatus.IN_AUDIO_EDIT, JobStatus.AUDIO_EDIT_COMPLETE, JobStatus.FAILED, JobStatus.CANCELLED],
JobStatus.IN_AUDIO_EDIT: [JobStatus.AWAITING_AUDIO_EDIT, JobStatus.AUDIO_EDIT_COMPLETE, JobStatus.FAILED, JobStatus.CANCELLED],
JobStatus.AUDIO_EDIT_COMPLETE: [JobStatus.SEPARATING_STAGE1, JobStatus.TRANSCRIBING, JobStatus.GENERATING_SCREENS, JobStatus.FAILED],
JobStatus.AUDIO_EDIT_COMPLETE: [JobStatus.SEPARATING_STAGE1, JobStatus.TRANSCRIBING, JobStatus.GENERATING_SCREENS, JobStatus.AWAITING_DURATION_CONFIRM, JobStatus.FAILED],
# Duration cost confirmation (BLOCKING) - user confirms before heavy processing begins
JobStatus.AWAITING_DURATION_CONFIRM: [
JobStatus.SEPARATING_STAGE1, JobStatus.TRANSCRIBING,
JobStatus.GENERATING_SCREENS, JobStatus.AWAITING_AUDIO_EDIT,
JobStatus.FAILED, JobStatus.CANCELLED,
],
# Audio separation flow
JobStatus.SEPARATING_STAGE1: [JobStatus.SEPARATING_STAGE2, JobStatus.FAILED],
@@ -135,10 +151,27 @@ STATE_TRANSITIONS = {
# AWAITING_REVIEW can go directly to REVIEW_COMPLETE (quick review) or to IN_REVIEW (editing)
JobStatus.AWAITING_REVIEW: [JobStatus.IN_REVIEW, JobStatus.REVIEW_COMPLETE, JobStatus.FAILED, JobStatus.CANCELLED],
JobStatus.IN_REVIEW: [JobStatus.REVIEW_COMPLETE, JobStatus.AWAITING_REVIEW, JobStatus.FAILED],
JobStatus.REVIEW_COMPLETE: [JobStatus.RENDERING_VIDEO, JobStatus.PREP_COMPLETE, JobStatus.FAILED], # PREP_COMPLETE for prep-only jobs
JobStatus.REVIEW_COMPLETE: [
JobStatus.RENDERING_VIDEO,
JobStatus.PREP_COMPLETE, # for prep-only jobs
JobStatus.RENDER_PENDING_CAPACITY, # GCE capacity exhausted before render started
JobStatus.FAILED,
],
# Video rendering (post-review) - instrumental was already selected during combined review
JobStatus.RENDERING_VIDEO: [JobStatus.INSTRUMENTAL_SELECTED, JobStatus.PREP_COMPLETE, JobStatus.FAILED],
# RENDER_PENDING_CAPACITY = parked when GCE encoding capacity is exhausted; auto-retried by scheduler.
JobStatus.RENDERING_VIDEO: [
JobStatus.INSTRUMENTAL_SELECTED,
JobStatus.PREP_COMPLETE,
JobStatus.RENDER_PENDING_CAPACITY,
JobStatus.FAILED,
],
JobStatus.RENDER_PENDING_CAPACITY: [
JobStatus.RENDERING_VIDEO, # auto-retry succeeded, picked up again
JobStatus.REVIEW_COMPLETE, # admin / scheduler resets to re-trigger render
JobStatus.FAILED, # exceeded max wait or operator gave up
JobStatus.CANCELLED, # user cancelled while waiting
],
# AWAITING_INSTRUMENTAL_SELECTION is LEGACY - kept for historical jobs in DB
# New jobs never enter this state; they go directly to INSTRUMENTAL_SELECTED after render
@@ -166,6 +199,7 @@ STATE_TRANSITIONS = {
JobStatus.REVIEW_COMPLETE, # Retry from render stage
JobStatus.LYRICS_COMPLETE, # Retry from screens generation
JobStatus.AWAITING_REVIEW, # Retry from combined review
JobStatus.RENDER_PENDING_CAPACITY, # Operator parks a stale-failed job for auto-retry
],
JobStatus.CANCELLED: [
JobStatus.DOWNLOADING, # Retry from beginning (if input audio exists)
@@ -577,6 +611,11 @@ class JobCreate(BaseModel):
# Private (non-published) track mode
is_private: bool = False # Private tracks: Dropbox only (Tracks-NonPublished/NOMADNP), no YouTube/GDrive
# Credit pricing: how many credits to charge for this job at creation time.
# Search and upload jobs pass the default (1) and may top up later.
# URL jobs with a known duration pass ceil(duration/600) credits.
credits: int = 1
# Request metadata (set by API endpoint from request headers)
request_metadata: Dict[str, Any] = Field(default_factory=dict)
"""
+4
View File
@@ -20,6 +20,10 @@ class URLSubmissionRequest(BaseModel):
user_email: Optional[str] = None
is_private: Optional[bool] = None # Private (non-published) track mode
# Duration-based pricing: supplied by the client from YouTube metadata
duration_seconds: Optional[float] = None # Known audio duration in seconds
acknowledged_credits: Optional[int] = None # Client's expected credit cost (anti-mismatch guard)
class UploadSubmissionRequest(BaseModel):
"""Request to submit a job from an uploaded file."""
+1
View File
@@ -0,0 +1 @@
"""Operational and maintenance scripts for the karaoke-gen backend."""
+199
View File
@@ -0,0 +1,199 @@
#!/usr/bin/env python3
"""Backfill original input audio into past jobs' Dropbox folders.
Restores files like ``<artist> - <title> (flacfetch).flac`` / ``(uploaded).mp3`` to
the organised Dropbox track folders for completed jobs that predate the pipeline fix
(the distributed pipeline stopped copying the source audio into the output folder).
Dry-run by default; pass ``--live`` to actually upload. NOTE: this cannot backfill the
screen ``.mov`` files — those require re-encoding the job.
Usage:
python -m backend.scripts.backfill_original_audio # dry-run, since 2026-03-01
python -m backend.scripts.backfill_original_audio --live # actually upload
python -m backend.scripts.backfill_original_audio --since 2026-02-01 --limit 50 -v
"""
import argparse
import logging
import os
import tempfile
from datetime import datetime, timezone
from backend.models.job import JobStatus
from backend.services.original_audio import (
original_audio_gcs_path,
original_audio_output_filename,
)
logger = logging.getLogger("backfill_original_audio")
# The regression window: screen/audio files stopped reaching Dropbox once the
# distributed pipeline took over (last known-good folder ~Feb; PR #647/#650 Mar 31).
DEFAULT_SINCE = "2026-03-01"
def plan_job_backfill(job, *, storage, dropbox):
"""Decide what to do for one job (existence checks only — no uploads).
Returns ``(action, detail)`` where action is one of:
- ``"skip-no-dropbox"`` — job was never uploaded to Dropbox
- ``"skip-no-audio-record"`` — no original-audio reference on the job
- ``"skip-audio-missing-gcs"`` — original audio no longer in GCS (detail=gcs_path)
- ``"skip-folder-missing"`` — the track's Dropbox folder doesn't exist (detail=folder)
- ``"skip-already-present"`` — file already in the Dropbox folder (detail=remote_path)
- ``"upload"`` — detail={gcs_path, remote_path, filename}
"""
from karaoke_gen.utils import sanitize_filename
from backend.services.job_defaults_service import get_effective_distribution_for_job
state = getattr(job, "state_data", None) or {}
brand_code = state.get("brand_code")
# Use the EFFECTIVE dropbox path — private (NOMADNP) tracks upload to the
# NonPublished path, not the job's stored (public) dropbox_path. This mirrors
# what the orchestrator does at distribution time.
dropbox_path = get_effective_distribution_for_job(job).dropbox_path
if not brand_code or not dropbox_path:
return ("skip-no-dropbox", None)
gcs_path = original_audio_gcs_path(job)
if not gcs_path:
return ("skip-no-audio-record", None)
if not storage.file_exists(gcs_path):
return ("skip-audio-missing-gcs", gcs_path)
safe_artist = sanitize_filename(job.artist) if job.artist else "Unknown"
safe_title = sanitize_filename(job.title) if job.title else "Unknown"
base_name = f"{safe_artist} - {safe_title}"
filename = original_audio_output_filename(job, base_name)
folder = f"{dropbox_path.rstrip('/')}/{brand_code} - {base_name}"
remote_path = f"{folder}/{filename}"
# Only backfill into a track folder that already exists — never create a new
# folder (guards against drifted brand/artist/title naming producing an orphan).
if not dropbox.file_exists(folder):
return ("skip-folder-missing", folder)
if dropbox.file_exists(remote_path):
return ("skip-already-present", remote_path)
return ("upload", {"gcs_path": gcs_path, "remote_path": remote_path, "filename": filename})
def _execute_upload(detail, *, storage, dropbox):
"""Download the original audio from GCS and upload it to the Dropbox folder."""
with tempfile.TemporaryDirectory() as td:
local = os.path.join(td, detail["filename"])
storage.download_file(detail["gcs_path"], local)
dropbox.upload_file(local, detail["remote_path"])
def run_backfill(*, since, until=None, limit, environment, live):
from backend.services.job_manager import JobManager
from backend.services.storage_service import StorageService
from backend.services.dropbox_service import get_dropbox_service
jm = JobManager()
storage = StorageService()
dropbox = get_dropbox_service()
if not dropbox.is_configured:
logger.error("Dropbox not configured; aborting.")
return
# NOTE: created_at is stored as an ISO string in Firestore, so server-side
# created_after/created_before datetime filters match nothing. We fetch the most
# recent completed jobs (ordered by created_at desc) and filter dates in Python.
# `limit` therefore bounds how far back we look — set it high enough to cover the
# window since `since`.
jobs = jm.list_jobs(status=JobStatus.COMPLETE, limit=limit)
def _created(j):
c = getattr(j, "created_at", None)
if c is None:
return None
return c.replace(tzinfo=None) if getattr(c, "tzinfo", None) else c
since_naive = since.replace(tzinfo=None)
until_naive = until.replace(tzinfo=None) if until else None
def _in_window(j):
c = _created(j)
if c is None:
return False
if c < since_naive:
return False
if until_naive and c >= until_naive:
return False
return True
jobs = [j for j in jobs if _in_window(j)]
if environment:
def _env(j):
rm = getattr(j, "request_metadata", None)
if rm is None:
return None
return rm.get("environment") if isinstance(rm, dict) else getattr(rm, "environment", None)
jobs = [j for j in jobs if _env(j) == environment]
logger.info(
"Considering %d completed jobs since %s (env=%s, fetch limit=%d)",
len(jobs), since.date(), environment or "all", limit,
)
tally = {}
for job in jobs:
try:
action, detail = plan_job_backfill(job, storage=storage, dropbox=dropbox)
except Exception as e:
# A transient GCS/Dropbox error while planning shouldn't abort the whole run.
logger.error(" planning failed for %s: %s", getattr(job, "job_id", "?"), e)
tally["error"] = tally.get("error", 0) + 1
continue
tally[action] = tally.get(action, 0) + 1
if action == "upload":
verb = "uploading" if live else "[DRY-RUN] would upload"
logger.info("%s: %s -> %s", verb, job.job_id, detail["remote_path"])
if live:
try:
_execute_upload(detail, storage=storage, dropbox=dropbox)
except Exception as e:
logger.error(" upload failed for %s: %s", job.job_id, e)
tally["upload"] -= 1
tally["error"] = tally.get("error", 0) + 1
else:
logger.debug("%s: %s (%s)", action, job.job_id, detail)
logger.info("=== Backfill summary (%s) ===", "LIVE" if live else "DRY-RUN")
for k in sorted(tally):
logger.info(" %-24s %d", k, tally[k])
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--since", default=DEFAULT_SINCE, help="Only jobs created on/after YYYY-MM-DD")
parser.add_argument("--until", default=None, help="Only jobs created before YYYY-MM-DD")
parser.add_argument("--limit", type=int, default=5000,
help="Max completed jobs to fetch (most-recent first). Bounds how far "
"back the date window can reach.")
parser.add_argument("--env", default=None, dest="environment",
help="Filter to a request environment (e.g. production). Default: all "
"(test jobs are skipped anyway — no brand code / Dropbox folder).")
parser.add_argument("--live", action="store_true", help="Actually upload (default: dry-run)")
parser.add_argument("-v", "--verbose", action="store_true")
args = parser.parse_args()
logging.basicConfig(
level=logging.DEBUG if args.verbose else logging.INFO,
format="%(message)s",
)
since = datetime.strptime(args.since, "%Y-%m-%d").replace(tzinfo=timezone.utc)
until = (
datetime.strptime(args.until, "%Y-%m-%d").replace(tzinfo=timezone.utc)
if args.until else None
)
run_backfill(since=since, until=until, limit=args.limit, environment=args.environment, live=args.live)
if __name__ == "__main__":
main()
+53
View File
@@ -106,6 +106,54 @@ class AudioEditService:
])
return self.get_metadata(output_path)
# Fades must be anchored to a clip edge — FFmpeg's afade silences audio outside
# the ramp, so a mid-clip fade would unexpectedly mute the rest of the track.
# The tolerance matches the editor UI's edge gating (start < 1s / end within 1s).
FADE_ANCHOR_TOLERANCE_SECONDS = 1.0
def fade_region(
self, input_path: str, start: float, end: float, direction: str, output_path: str
) -> AudioMetadata:
"""Apply a fade in or out anchored to a clip edge (preserves duration).
direction='in' ramps the volume from silence to full over [0, end];
direction='out' ramps from full to silence over [start, clip_end].
Anchoring is enforced server-side (not just in the UI) because FFmpeg's
afade filter silences audio outside the ramp window: a fade-in is forced
to begin at the clip start, and a fade-out to finish at the clip end, so a
non-anchored request can never silently mute the rest of the track.
"""
if direction not in ("in", "out"):
raise ValueError(f"Invalid fade direction: {direction}")
if start < 0 or end <= start:
raise ValueError(f"Invalid fade region: start={start}, end={end}")
total = self.get_metadata(input_path).duration_seconds
tol = self.FADE_ANCHOR_TOLERANCE_SECONDS
if end > total + tol:
raise ValueError(f"Fade region exceeds clip duration ({end} > {total})")
if direction == "in":
if start > tol:
raise ValueError(f"fade_in must be anchored to the clip start (got start={start})")
fade_start, fade_duration = 0.0, end
else:
if end < total - tol:
raise ValueError(f"fade_out must be anchored to the clip end (got end={end}, duration={total})")
fade_start, fade_duration = start, total - start
if fade_duration <= 0:
raise ValueError(f"Fade region must have positive duration (got {fade_duration})")
self._run_ffmpeg([
"-i", input_path,
"-af", f"afade=t={direction}:st={fade_start}:d={fade_duration}",
"-c:a", "flac",
output_path,
])
return self.get_metadata(output_path)
def join_audio(self, input_path: str, other_path: str, position: str, output_path: str) -> AudioMetadata:
"""Join two audio files. position: 'start' (prepend other) or 'end' (append other)."""
if position == "start":
@@ -156,6 +204,11 @@ class AudioEditService:
metadata = self.mute_region(
local_input, params["start_seconds"], params["end_seconds"], local_output
)
elif operation in ("fade_in", "fade_out"):
direction = "in" if operation == "fade_in" else "out"
metadata = self.fade_region(
local_input, params["start_seconds"], params["end_seconds"], direction, local_output
)
elif operation in ("join_start", "join_end"):
# Download the upload file
upload_gcs_path = params["upload_gcs_path"]
+147 -1
View File
@@ -18,7 +18,8 @@ downloads since Cloud Run doesn't support BitTorrent peer connections.
import asyncio
import logging
import os
from typing import List, Optional
import re
from typing import Any, Dict, List, Optional
import nest_asyncio
@@ -47,6 +48,151 @@ AudioSearchError = AudioFetcherError
AudioDownloadResult = AudioFetchResult
# ---------------------------------------------------------------------------
# Bulk Mode: tier-1 auto-selection.
#
# This is a faithful port of the frontend confidence-tier logic in
# frontend/lib/audio-search-utils.ts (categorizeResult / getBestResult /
# checkFilenameMismatch / getSearchConfidence). It operates on the dicts
# produced by AudioSearchResult.to_dict() (keys: is_lossless, quality_data,
# seeders, provider, release_type, target_file, title, index).
#
# MAINTENANCE SEAM: if the frontend tier rule changes, update both. The
# parity tests in backend/tests/test_bulk_foundations.py guard the behaviour.
# ---------------------------------------------------------------------------
_BEST_RESULT_PRIORITY = [
"BEST CHOICE",
"STUDIO ALBUMS",
"HI-RES 24-BIT",
"SINGLES",
"COMPILATIONS",
"SPOTIFY",
"YOUTUBE",
"OTHER",
]
def _categorize_result(result: Dict[str, Any]) -> str:
"""Port of categorizeResult() from audio-search-utils.ts."""
is_lossless = result.get("is_lossless") is True
quality_data = result.get("quality_data") or {}
is_24bit = quality_data.get("bit_depth") == 24
seeders = result.get("seeders") or 0
provider = (result.get("provider") or "").lower()
release_type = (result.get("release_type") or "").lower()
media = (quality_data.get("media") or "").lower()
if provider == "spotify":
return "SPOTIFY"
if provider == "youtube" or not is_lossless:
return "YOUTUBE"
# Vinyl rips checked before BEST CHOICE (surface noise -> poor for karaoke)
if is_lossless and media == "vinyl":
return "VINYL RIPS"
if is_lossless and seeders >= 50:
return "BEST CHOICE"
if is_lossless and is_24bit:
return "HI-RES 24-BIT"
if is_lossless and (
release_type == "live album" or release_type == "bootleg" or "live" in release_type
):
return "LIVE VERSIONS"
if is_lossless and release_type in ("compilation", "soundtrack", "anthology"):
return "COMPILATIONS"
if is_lossless and release_type in ("single", "ep"):
return "SINGLES"
if is_lossless and (release_type == "album" or not release_type):
return "STUDIO ALBUMS"
return "OTHER"
def _get_best_result(results: List[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
"""Port of getBestResult() — highest-priority category, skipping vinyl."""
if not results:
return None
best: Optional[Dict[str, Any]] = None
best_priority = float("inf")
for result in results:
category = _categorize_result(result)
if category == "VINYL RIPS":
continue
try:
priority = _BEST_RESULT_PRIORITY.index(category)
except ValueError:
priority = float("inf")
if priority < best_priority:
best = result
best_priority = priority
elif priority == best_priority and best is not None:
if (result.get("seeders") or 0) > (best.get("seeders") or 0):
best = result
return best if best is not None else results[0]
def _check_filename_mismatch(search_title: str, result: Dict[str, Any]) -> bool:
"""Port of checkFilenameMismatch() — True if the file is clearly another track."""
if len(search_title) < 3:
return False
target_file = result.get("target_file")
if target_file:
raw_filename = target_file.split("/")[-1] or target_file
without_ext = re.sub(r"\.[^.]+$", "", raw_filename)
filename = re.sub(r"^\d{1,3}\s*[-.\s]\s*", "", without_ext)
elif result.get("title"):
filename = result["title"]
else:
return False
def normalize(s: str) -> str:
s = s.lower()
s = re.sub(r"[_\-.]+", " ", s)
s = re.sub(r"[^a-z0-9\s]", "", s)
s = re.sub(r"\s+", " ", s)
return s.strip()
norm_title = normalize(search_title)
norm_file = normalize(filename)
if not norm_file or not norm_title:
return False
# Stricter than the frontend's substring check (intentional — for the bulk
# AUTO-select path we'd rather park an uncertain match than auto-pick the
# wrong track). A match requires every title word to appear as a whole word
# in the filename, so "One" no longer matches "Someone".
title_tokens = [t for t in norm_title.split() if t]
file_tokens = set(norm_file.split())
if not title_tokens:
return False
matches = all(tok in file_tokens for tok in title_tokens)
return not matches
def pick_auto_selection(results: List[Dict[str, Any]], search_title: str = "") -> Optional[int]:
"""Return the index to auto-select, or None if no confident lossless pick.
Tier-1 rule (mirrors getSearchConfidence): the best result must be in the
BEST CHOICE category (lossless, 50+ seeders, non-vinyl) AND its filename
must match ``search_title`` (the song the user searched for). Otherwise we
defer to human selection.
"""
if not results:
return None
# Require a usable title before auto-selecting: a blank/too-short title can't
# be verified against the filename, so defer to human selection.
if len((search_title or "").strip()) < 3:
return None
best = _get_best_result(results)
if best is None:
return None
if _categorize_result(best) != "BEST CHOICE":
return None
if _check_filename_mismatch(search_title, best):
return None
return best.get("index")
class AudioSearchService:
"""
Service for searching and downloading audio files.
+19
View File
@@ -0,0 +1,19 @@
"""AI auto-correction suggestions for the lyrics review UI.
Stateless suggestion generation: the client posts its current working
segments, the service returns word-level suggestions (replace / delete /
insert_after) referencing word ids. Nothing is applied server-side — the
reviewer accepts or rejects each suggestion in the UI.
"""
from backend.services.auto_correct.service import (
AutoCorrectService,
AutoCorrectServiceError,
get_auto_correct_service,
)
__all__ = [
"AutoCorrectService",
"AutoCorrectServiceError",
"get_auto_correct_service",
]
+94
View File
@@ -0,0 +1,94 @@
"""Token pricing for auto-correct model calls.
Used to turn the per-call token usage we capture from each provider into an
estimated USD cost, for both the production usage logs and the offline
measurement script (``scripts/measure_autocorrect_cost.py``).
Prices are USD per 1,000,000 tokens.
- **Anthropic** prices are authoritative (published Claude API pricing).
``output`` is the billed output rate, which already includes adaptive
*thinking* tokens — they are billed as output and are not separable from
the final answer in the Anthropic usage object.
- **Gemini** prices are a best-known ESTIMATE for the Vertex preview tier and
are clearly marked below. Verify against current Vertex pricing before
relying on the dollar figure. Gemini thinking tokens ARE separable
(``thoughts_token_count``) and are billed at the output rate, so we fold
them into the output total.
The raw token counts are always logged alongside the dollar figure, so the
cost here is a derived convenience — if a rate is stale, recompute from the
logged tokens rather than trusting the historical USD value.
"""
from __future__ import annotations
from typing import Optional, TypedDict
class TokenUsage(TypedDict):
"""Normalized, provider-agnostic usage for one model call.
``output_tokens`` is the total billed output (final answer + thinking).
``thinking_tokens`` is informational only (None when the provider does
not report it separately) — it is already counted inside ``output_tokens``.
"""
input_tokens: int
output_tokens: int
cache_read_tokens: int
thinking_tokens: Optional[int]
class _Rate(TypedDict):
input: float
output: float
cache_read: float
# USD per 1,000,000 tokens.
MODEL_PRICING: dict[str, _Rate] = {
# --- Anthropic (authoritative) ---
"claude-fable-5": {"input": 10.0, "output": 50.0, "cache_read": 1.0},
"claude-opus-4-8": {"input": 5.0, "output": 25.0, "cache_read": 0.5},
"claude-sonnet-4-6": {"input": 3.0, "output": 15.0, "cache_read": 0.3},
"claude-haiku-4-5": {"input": 1.0, "output": 5.0, "cache_read": 0.1},
# --- Gemini (ESTIMATE — Vertex 3.x Pro preview, <=200K-token context
# tier; confirm against current Google pricing before trusting USD) ---
"gemini-3.1-pro-preview": {"input": 2.0, "output": 12.0, "cache_read": 0.2},
}
def get_rate(model: str) -> Optional[_Rate]:
"""Return the rate card for ``model``, or None if we have no pricing.
Falls back to a prefix match on the model family (e.g. a dated
``claude-fable-5-2026...`` snapshot still resolves to ``claude-fable-5``)
so a minor model-id change doesn't silently drop cost tracking.
"""
if model in MODEL_PRICING:
return MODEL_PRICING[model]
for known, rate in MODEL_PRICING.items():
if model.startswith(known):
return rate
return None
def estimate_cost_usd(model: str, usage: Optional[TokenUsage]) -> Optional[float]:
"""Estimate the USD cost of one model call from its token usage.
Returns None when usage is unavailable or the model has no known pricing,
so callers can distinguish "free/zero" from "unknown".
"""
if not usage:
return None
rate = get_rate(model)
if rate is None:
return None
input_tokens = usage.get("input_tokens") or 0
output_tokens = usage.get("output_tokens") or 0
cache_read = usage.get("cache_read_tokens") or 0
return (
input_tokens * rate["input"]
+ output_tokens * rate["output"]
+ cache_read * rate["cache_read"]
) / 1_000_000.0
+145
View File
@@ -0,0 +1,145 @@
"""Prompt construction for AI auto-correction suggestions.
Kept in sync with the offline eval harness
(lyrics-alignment-eval-dataset/auto-correct-eval/harness.py) — changes here
should be re-scored against the 30-job ground-truth dataset.
"""
from __future__ import annotations
from backend.services.auto_correct.settings import AutoCorrectSettings
RESPONSE_SCHEMA = {
"type": "object",
"properties": {
"suggestions": {
"type": "array",
"items": {
"type": "object",
"properties": {
"op": {
"type": "string",
"enum": ["replace", "delete", "insert_after"],
},
"start_idx": {"type": "integer"},
"end_idx": {"type": "integer"},
"new_text": {"type": "string"},
"reason": {"type": "string"},
"category": {
"type": "string",
"enum": [
"mishearing",
"grammar",
"adlib_removal",
"repeated_chorus_fix",
"formatting",
"other",
],
},
"confidence": {"type": "number"},
},
"required": [
"op",
"start_idx",
"end_idx",
"new_text",
"reason",
"category",
"confidence",
],
},
}
},
"required": ["suggestions"],
}
_BASE_SYSTEM_PROMPT = """\
You are an expert lyrics transcription reviewer for a karaoke video company. \
You are given an automatic speech transcription of a song's vocals (already \
segmented into lines, each word tagged with a numeric index) plus lyrics for \
the same song from internet sources. Internet sources are usually (not always) \
closer to the true lyrics, but lack the transcription's timing and line layout.
Propose word-level corrections to the TRANSCRIPTION so its words match what is \
actually sung. A human reviewer who has listened to the song will accept or \
reject each suggestion individually, so precision matters far more than \
recall: only suggest a change when you are confident a careful human reviewer \
would make it. If reference sources disagree and you have no other evidence, \
make no suggestion.
Guidelines:
- Transcription errors are usually sound-alike mishearings: the wrong words \
sound similar to the true lyric (e.g. "glory" vs "chlorine", "ladder" vs \
"matter"). Prefer corrections that are phonetically plausible.
- The same mishearing often repeats in every chorus; correct every occurrence.
- Keep the transcription's line structure. NEVER suggest timing changes.
- Match the casing and punctuation style of the surrounding transcription.
- Do not censor or bowdlerise explicit lyrics.
- Do not rewrite lines wholesale unless the transcription is clearly garbled \
and a reference line is unambiguously what is sung at that point.
- new_text may contain multiple words, or differ in word count from the span \
it replaces.
"""
_ADLIB_ALLOWED = """\
- Parenthesised backing vocals / adlibs that the transcription contains but \
references omit may be real (references often drop them). Only suggest \
deleting them when they look like transcription hallucinations or the \
references make clear they are not sung lead lines; use category \
"adlib_removal" and lower confidence.
"""
_ADLIB_FORBIDDEN = """\
- NEVER suggest deleting backing vocals or adlibs solely because the \
references omit them; references often drop adlibs that are really sung.
"""
_INSERTIONS_FORBIDDEN = """\
- NEVER use the "insert_after" operation; only suggest "replace" and \
"delete" operations.
"""
_OUTPUT_SPEC = """\
Output JSON only, matching this shape exactly:
{"suggestions": [{"op": "replace"|"delete"|"insert_after",
"start_idx": <int>, "end_idx": <int>,
"new_text": "<replacement, empty for delete>",
"reason": "<short justification>",
"category": "mishearing"|"grammar"|"adlib_removal"|"repeated_chorus_fix"|"formatting"|"other",
"confidence": <0.0-1.0>}]}
start_idx and end_idx are inclusive word indices. For "insert_after", \
start_idx == end_idx == the index of the word the new text should follow. \
If nothing needs changing, return {"suggestions": []}.
"""
def build_system_prompt(settings: AutoCorrectSettings) -> str:
parts = [_BASE_SYSTEM_PROMPT]
parts.append(_ADLIB_ALLOWED if settings.suggest_adlib_removal else _ADLIB_FORBIDDEN)
if not settings.allow_insertions:
parts.append(_INSERTIONS_FORBIDDEN)
parts.append(_OUTPUT_SPEC)
return "\n".join(parts)
def build_user_prompt(
*,
segments: list[dict],
reference_lyrics: dict[str, dict],
artist: str | None,
title: str | None,
) -> str:
"""Render segments (with global word indices) + reference sources."""
lines = [f"ARTIST: {artist or 'unknown'}", f"TITLE: {title or 'unknown'}", "", "TRANSCRIPTION:"]
idx = 0
for li, seg in enumerate(segments):
toks = []
for w in seg.get("words") or []:
toks.append(f"{idx}:{w.get('text', '')}")
idx += 1
lines.append(f"[L{li:03d}] " + " ".join(toks))
for source, ref in (reference_lyrics or {}).items():
lines.append("")
lines.append(f"REFERENCE LYRICS ({source}):")
for seg in ref.get("segments") or []:
lines.append(seg.get("text", ""))
return "\n".join(lines)
+717
View File
@@ -0,0 +1,717 @@
"""Auto-correct suggestion service: one whole-song LLM call, validated output."""
from __future__ import annotations
import hashlib
import json
import logging
import os
import time
import uuid
from dataclasses import asdict, dataclass, field
from typing import Any, Optional
from google import genai
from google.genai import types
from backend.config import get_settings
from backend.services.auto_correct.pricing import TokenUsage, estimate_cost_usd
from backend.services.auto_correct.prompts import (
RESPONSE_SCHEMA,
build_system_prompt,
build_user_prompt,
)
from backend.services.auto_correct.settings import AutoCorrectSettings
logger = logging.getLogger(__name__)
VALID_OPS = {"replace", "delete", "insert_after"}
VALID_CATEGORIES = {
"mishearing",
"grammar",
"adlib_removal",
"repeated_chorus_fix",
"formatting",
"other",
}
class AutoCorrectServiceError(Exception):
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
class Suggestion:
id: str
op: str # replace | delete | insert_after
word_ids: list[str] # targeted words (replace/delete); [anchor] for insert_after
segment_ids: list[str] # segments containing the targeted words
original_text: str # current text of the targeted span ("" for insert_after)
new_text: str # replacement text ("" for delete)
reason: str
category: str
confidence: float
# Multi-model compare metadata. In single-model mode models has one
# entry and consensus == total_models == 1.
models: list[str] = field(default_factory=list)
consensus: int = 1
total_models: int = 1
# Set when other suggestions target overlapping words with a different
# outcome — the UI lets the reviewer pick at most one per group.
conflict_group: Optional[str] = None
@dataclass
class AutoCorrectResult:
suggestions: list[Suggestion]
model: str # comma-joined when compare mode queried several models
elapsed_seconds: float
settings_applied: AutoCorrectSettings
warnings: list[str] = field(default_factory=list)
# True when served from the per-job GCS cache (no LLM call was made).
cached: bool = False
class AutoCorrectService:
def __init__(self) -> None:
self.settings = get_settings()
def suggest(
self,
*,
job_id: str,
segments: list[dict],
reference_lyrics: dict[str, dict],
artist: Optional[str],
title: Optional[str],
settings: AutoCorrectSettings,
) -> AutoCorrectResult:
if not segments:
raise AutoCorrectServiceError("segments is empty")
if not reference_lyrics:
raise AutoCorrectServiceError(
"no reference lyrics available — auto-correction needs at least "
"one internet/reference source to compare against",
status_code=422,
)
# Flat word list mirrors the prompt's global indices.
flat: list[tuple[str, str, str]] = [] # (word_id, word_text, segment_id)
for seg in segments:
if not seg.get("id"):
raise AutoCorrectServiceError("all segments must have ids")
for w in seg.get("words") or []:
if not w.get("id"):
raise AutoCorrectServiceError("all words must have ids")
flat.append((w["id"], w.get("text", ""), seg["id"]))
system_prompt = build_system_prompt(settings)
user_prompt = build_user_prompt(
segments=segments,
reference_lyrics=reference_lyrics,
artist=artist,
title=title,
)
models = self._models_for(settings)
# Re-running on byte-identical input (lyrics, references, settings,
# models) returns the previous result instead of paying for another
# LLM call. Word ids are part of the key, so cached suggestions
# always reference words that still exist.
cache_path = self._cache_path(
job_id, models, settings, flat, reference_lyrics, artist, title
)
cached = self._cache_get(cache_path)
if cached is not None:
logger.info(
"auto-correct cache hit job=%s suggestions=%d", job_id,
len(cached.suggestions),
)
return cached
t0 = time.time()
per_model: dict[str, list[Suggestion]] = {}
# Token usage per successful model call (None when the provider's
# usage object couldn't be read). Drives the cost log below.
per_model_usage: dict[str, Optional[TokenUsage]] = {}
warnings: list[str] = []
if len(models) == 1:
raw, usage = self._call_model(
models[0], system_prompt, user_prompt, job_id=job_id
)
suggestions, vw = self._validate(raw, flat, settings)
per_model[models[0]] = suggestions
per_model_usage[models[0]] = usage
warnings.extend(vw)
else:
import concurrent.futures as cf
with cf.ThreadPoolExecutor(max_workers=len(models)) as ex:
futures = {
ex.submit(
self._call_model, m, system_prompt, user_prompt, job_id=job_id
): m
for m in models
}
for fut, m in futures.items():
try:
raw, usage = fut.result()
suggestions, vw = self._validate(raw, flat, settings)
except AutoCorrectServiceError as exc:
# One model failing (call OR malformed output) must not
# abort compare mode; the rest still return results.
warnings.append(f"model {m} failed: {exc}")
continue
per_model[m] = suggestions
per_model_usage[m] = usage
warnings.extend(f"[{m}] {w}" for w in vw)
if not per_model:
raise AutoCorrectServiceError(
"all AI models failed", status_code=502
)
merged = self._merge(per_model, flat)
elapsed = time.time() - t0
model_label = ", ".join(per_model.keys())
logger.info(
"auto-correct job=%s models=%s words=%d suggestions=%d dropped_warnings=%d elapsed=%.1fs",
job_id, model_label, len(flat), len(merged), len(warnings), elapsed,
)
self._log_usage(job_id, per_model_usage)
result = AutoCorrectResult(
suggestions=merged,
model=model_label,
elapsed_seconds=round(elapsed, 1),
settings_applied=settings,
warnings=warnings,
)
self._cache_put(cache_path, result)
return result
@staticmethod
def _log_usage(
job_id: str, per_model_usage: dict[str, Optional[TokenUsage]]
) -> None:
"""Emit greppable per-model and total cost lines for one suggest() call.
Token counts are ground truth; the USD figures are derived from
``pricing.MODEL_PRICING`` and use ESTIMATED Gemini rates (see that
module). Query in Cloud Logging via ``auto-correct usage`` /
``auto-correct cost``. Observability only — never raises.
"""
total_cost = 0.0
any_cost = False
for model, usage in per_model_usage.items():
cost = estimate_cost_usd(model, usage)
if cost is not None:
total_cost += cost
any_cost = True
if usage is None:
logger.info(
"auto-correct usage job=%s model=%s tokens=unavailable",
job_id, model,
)
continue
thinking = usage.get("thinking_tokens")
logger.info(
"auto-correct usage job=%s model=%s input_tokens=%d "
"output_tokens=%d thinking_tokens=%s cache_read_tokens=%d "
"est_cost_usd=%s",
job_id,
model,
usage.get("input_tokens", 0),
usage.get("output_tokens", 0),
"na" if thinking is None else thinking,
usage.get("cache_read_tokens", 0),
"unknown" if cost is None else f"{cost:.4f}",
)
logger.info(
"auto-correct cost job=%s models=%s total_est_cost_usd=%s",
job_id,
", ".join(per_model_usage.keys()),
f"{total_cost:.4f}" if any_cost else "unknown",
)
# ---- suggestion cache (GCS, best-effort) ----
def _get_storage(self):
if not hasattr(self, "_storage"):
from backend.services.storage_service import StorageService
self._storage = StorageService()
return self._storage
@staticmethod
def _cache_path(
job_id: str,
models: list[str],
settings: AutoCorrectSettings,
flat: list[tuple[str, str, str]],
reference_lyrics: dict[str, dict],
artist: Optional[str],
title: Optional[str],
) -> str:
payload = {
"v": 1,
"models": models,
"settings": settings.to_dict(),
"words": [[word_id, text] for word_id, text, _seg in flat],
"references": {
source: [seg.get("text", "") for seg in (ref.get("segments") or [])]
for source, ref in sorted((reference_lyrics or {}).items())
},
"artist": artist,
"title": title,
}
digest = hashlib.sha256(
json.dumps(payload, sort_keys=True, ensure_ascii=False).encode()
).hexdigest()[:24]
return f"jobs/{job_id}/lyrics/auto_correct_cache/{digest}.json"
def _cache_get(self, path: str) -> Optional[AutoCorrectResult]:
"""Best-effort: any storage/shape problem is a cache miss, never an error."""
try:
storage = self._get_storage()
if not storage.bucket.blob(path).exists():
return None
data = storage.download_json(path)
return AutoCorrectResult(
suggestions=[Suggestion(**s) for s in data["suggestions"]],
model=data["model"],
elapsed_seconds=0.0,
settings_applied=AutoCorrectSettings(**data["settings_applied"]),
warnings=list(data.get("warnings") or []),
cached=True,
)
except Exception:
logger.warning("auto-correct cache read failed for %s", path, exc_info=True)
return None
def _cache_put(self, path: str, result: AutoCorrectResult) -> None:
"""Best-effort: a failed cache write never fails the request."""
try:
self._get_storage().upload_json(
path,
{
"suggestions": [asdict(s) for s in result.suggestions],
"model": result.model,
"settings_applied": result.settings_applied.to_dict(),
"warnings": result.warnings,
"elapsed_seconds": result.elapsed_seconds,
},
)
except Exception:
logger.warning("auto-correct cache write failed for %s", path, exc_info=True)
def _models_for(self, settings: AutoCorrectSettings) -> list[str]:
if settings.compare_models:
configured = [
m.strip()
for m in self.settings.auto_correct_compare_models.replace(",", ";").split(";")
if m.strip()
]
# De-dupe while preserving order.
seen: set[str] = set()
models = [m for m in configured if not (m in seen or seen.add(m))]
if len(models) >= 2:
return models
logger.warning(
"compare_models requested but AUTO_CORRECT_COMPARE_MODELS has "
"%d usable entries; falling back to single model", len(models),
)
return [self.settings.auto_correct_model]
@staticmethod
def _merge(
per_model: dict[str, list[Suggestion]],
flat: list[tuple[str, str, str]],
) -> list[Suggestion]:
"""Deduplicate identical suggestions across models, tag consensus,
assign conflict groups to overlapping non-identical suggestions, and
sort by document position."""
total = len(per_model)
merged: dict[tuple, Suggestion] = {}
for model, suggestions in per_model.items():
for s in suggestions:
key = (s.op, tuple(s.word_ids), " ".join(s.new_text.lower().split()))
existing = merged.get(key)
if existing is None:
s.models = [model]
s.consensus = 1
s.total_models = total
merged[key] = s
else:
existing.models.append(model)
existing.consensus += 1
existing.confidence = max(existing.confidence, s.confidence)
result = list(merged.values())
# Conflict groups: suggestions sharing any target word but not merged
# above disagree about the same span — reviewer picks at most one.
# (insert_after anchors are excluded: inserting after a word does not
# conflict with editing that word.)
by_word: dict[str, list[int]] = {}
for i, s in enumerate(result):
if s.op == "insert_after":
continue
for wid in s.word_ids:
by_word.setdefault(wid, []).append(i)
parent = list(range(len(result)))
def find(x: int) -> int:
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for overlapping in by_word.values():
for other in overlapping[1:]:
parent[find(other)] = find(overlapping[0])
roots: dict[int, list[int]] = {}
for i in range(len(result)):
roots.setdefault(find(i), []).append(i)
for members in roots.values():
if len(members) < 2:
continue
group = str(uuid.uuid4())
for i in members:
result[i].conflict_group = group
position = {word_id: i for i, (word_id, _, _) in enumerate(flat)}
result.sort(key=lambda s: position.get(s.word_ids[0], 0) if s.word_ids else 0)
return result
# ---- internals ----
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.
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]:
"""Best-effort usage from an Anthropic response.
``output_tokens`` already includes adaptive thinking tokens (billed as
output); they are not separable here, so thinking_tokens is None.
Returns None on any shape problem — usage must never break the call.
"""
try:
u = response.usage
return TokenUsage(
input_tokens=int(getattr(u, "input_tokens", 0) or 0),
output_tokens=int(getattr(u, "output_tokens", 0) or 0),
cache_read_tokens=int(getattr(u, "cache_read_input_tokens", 0) or 0),
thinking_tokens=None,
)
except Exception:
logger.debug("auto-correct: could not read Anthropic usage", exc_info=True)
return None
@staticmethod
def _gemini_usage(response: Any) -> Optional[TokenUsage]:
"""Best-effort usage from a Gemini (Vertex) response.
Gemini reports thinking separately (``thoughts_token_count``); it is
billed at the output rate, so it's folded into output_tokens and also
reported separately for visibility. Returns None on any shape problem.
"""
try:
u = response.usage_metadata
prompt = int(getattr(u, "prompt_token_count", 0) or 0)
candidates = int(getattr(u, "candidates_token_count", 0) or 0)
thoughts = int(getattr(u, "thoughts_token_count", 0) or 0)
cached = int(getattr(u, "cached_content_token_count", 0) or 0)
return TokenUsage(
input_tokens=prompt,
output_tokens=candidates + thoughts,
cache_read_tokens=cached,
thinking_tokens=thoughts,
)
except Exception:
logger.debug("auto-correct: could not read Gemini usage", exc_info=True)
return None
def _call_anthropic(
self, model: str, system_prompt: str, user_prompt: str, *, job_id: str
) -> tuple[Any, Optional[TokenUsage]]:
import anthropic
if not os.environ.get("ANTHROPIC_API_KEY"):
# No silent fallback to another provider — surface the
# misconfiguration so it gets fixed, not masked.
logger.error(
"auto-correct model %s requires ANTHROPIC_API_KEY which is not set "
"(job=%s)", model, job_id,
)
raise AutoCorrectServiceError(
"AI model is not configured", status_code=502
)
# Structured outputs require additionalProperties: false on objects;
# the Vertex variant of the schema omits it, so inject here. Deep-copy
# because the google-genai SDK mutates schema dicts in place (it adds
# 'property_ordering', which the Anthropic API rejects).
import copy
base = copy.deepcopy(RESPONSE_SCHEMA)
for obj in (base, base["properties"]["suggestions"]["items"]):
obj.pop("property_ordering", None)
obj.pop("propertyOrdering", None)
obj["additionalProperties"] = False
strict_schema = base
client = anthropic.Anthropic(timeout=120.0)
try:
response = client.messages.create(
model=model,
max_tokens=16000,
system=system_prompt,
messages=[{"role": "user", "content": user_prompt}],
thinking={"type": "adaptive"},
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
) from exc
usage = self._anthropic_usage(response)
try:
text = next(b.text for b in response.content if b.type == "text")
return json.loads(text), usage
except (StopIteration, json.JSONDecodeError, TypeError) as exc:
logger.exception(
"auto-correct model returned non-JSON job=%s model=%s", job_id, model
)
raise AutoCorrectServiceError(
"AI returned non-JSON output", status_code=502
) from exc
def _call_gemini(
self, model: str, system_prompt: str, user_prompt: str, *, job_id: str
) -> tuple[Any, Optional[TokenUsage]]:
client = genai.Client(
vertexai=True,
project=self.settings.google_cloud_project,
location="global",
# Milliseconds; bounds the call so a hung model never strands the UI.
http_options=types.HttpOptions(timeout=120_000),
)
# Deep-copy: the google-genai SDK mutates the schema dict in place,
# which would poison the shared module-level constant for other
# providers running in the same process.
import copy
try:
response = client.models.generate_content(
model=model,
contents=[user_prompt],
config=types.GenerateContentConfig(
system_instruction=system_prompt,
response_mime_type="application/json",
response_schema=copy.deepcopy(RESPONSE_SCHEMA),
),
)
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
) from exc
usage = self._gemini_usage(response)
try:
return json.loads(response.text), usage
except (json.JSONDecodeError, TypeError) as exc:
logger.exception(
"auto-correct model returned non-JSON job=%s model=%s", job_id, model
)
raise AutoCorrectServiceError(
"AI returned non-JSON output", status_code=502
) from exc
def _validate(
self,
raw: Any,
flat: list[tuple[str, str, str]],
settings: AutoCorrectSettings,
) -> tuple[list[Suggestion], list[str]]:
if not isinstance(raw, dict) or not isinstance(raw.get("suggestions"), list):
raise AutoCorrectServiceError(
"AI response missing 'suggestions' list", status_code=502
)
n = len(flat)
out: list[Suggestion] = []
warnings: list[str] = []
for i, s in enumerate(raw["suggestions"]):
problem = self._check(s, n, settings)
if problem:
warnings.append(f"dropped suggestion {i}: {problem}")
continue
start, end = int(s["start_idx"]), int(s["end_idx"])
if s["op"] == "insert_after":
word_ids = [flat[start][0]]
segment_ids = [flat[start][2]]
original_text = ""
else:
span = flat[start : end + 1]
word_ids = [w[0] for w in span]
segment_ids = sorted({w[2] for w in span})
original_text = " ".join(w[1] for w in span)
out.append(
Suggestion(
id=str(uuid.uuid4()),
op=s["op"],
word_ids=word_ids,
segment_ids=segment_ids,
original_text=original_text,
new_text="" if s["op"] == "delete" else str(s["new_text"]).strip(),
reason=str(s.get("reason", "")),
category=s["category"] if s.get("category") in VALID_CATEGORIES else "other",
confidence=max(0.0, min(1.0, float(s["confidence"]))),
)
)
return out, warnings
@staticmethod
def _check(s: Any, n_words: int, settings: AutoCorrectSettings) -> Optional[str]:
if not isinstance(s, dict):
return "not an object"
op = s.get("op")
if op not in VALID_OPS:
return f"invalid op {op!r}"
try:
start, end = int(s["start_idx"]), int(s["end_idx"])
confidence = float(s["confidence"])
except (KeyError, TypeError, ValueError):
return "missing/invalid indices or confidence"
if not (0 <= start <= end < n_words):
return f"indices out of range ({start}..{end} of {n_words})"
if op == "insert_after" and not settings.allow_insertions:
return "insertions disabled by settings"
if op == "insert_after" and start != end:
return "insert_after requires start_idx == end_idx"
new_text = str(s.get("new_text", "")).strip()
if op in ("replace", "insert_after") and not new_text:
return f"{op} with empty new_text"
if op == "delete" and new_text:
return "delete with non-empty new_text"
if confidence < settings.min_confidence:
return f"confidence {confidence:.2f} below threshold"
if (
s.get("category") == "adlib_removal"
and not settings.suggest_adlib_removal
):
return "adlib removal disabled by settings"
return None
_service_instance: Optional[AutoCorrectService] = None
def get_auto_correct_service() -> AutoCorrectService:
global _service_instance
if _service_instance is None:
_service_instance = AutoCorrectService()
return _service_instance
+47
View File
@@ -0,0 +1,47 @@
"""User-facing knobs for AI auto-correction suggestions."""
from __future__ import annotations
from dataclasses import asdict, dataclass
@dataclass(frozen=True)
class AutoCorrectSettings:
"""Reviewer-tunable behaviour for a suggestion run.
suggest_adlib_removal: allow suggestions that delete transcribed
backing-vocal / adlib phrases absent from the references.
allow_insertions: allow suggestions that insert words the
transcription missed entirely.
min_confidence: drop suggestions below this confidence server-side
(the UI can filter further client-side).
compare_models: query every configured compare model in parallel,
deduplicate identical suggestions and report per-suggestion
model consensus (slower, costs one call per model).
"""
suggest_adlib_removal: bool = True
allow_insertions: bool = True
min_confidence: float = 0.0
compare_models: bool = False
def to_dict(self) -> dict:
return asdict(self)
def settings_from_dict(data: dict) -> AutoCorrectSettings:
known = {f for f in AutoCorrectSettings.__dataclass_fields__}
unknown = set(data) - known
if unknown:
raise ValueError(f"unknown settings: {sorted(unknown)}")
merged = {**AutoCorrectSettings().to_dict(), **data}
if not isinstance(merged["suggest_adlib_removal"], bool):
raise ValueError("suggest_adlib_removal must be a boolean")
if not isinstance(merged["allow_insertions"], bool):
raise ValueError("allow_insertions must be a boolean")
if not isinstance(merged["compare_models"], bool):
raise ValueError("compare_models must be a boolean")
mc = merged["min_confidence"]
if isinstance(mc, bool) or not isinstance(mc, (int, float)) or not 0.0 <= float(mc) <= 1.0:
raise ValueError("min_confidence must be a number between 0 and 1")
merged["min_confidence"] = float(mc)
return AutoCorrectSettings(**merged)
+33 -5
View File
@@ -22,6 +22,30 @@ from backend.config import get_settings
logger = logging.getLogger(__name__)
def _destroy_old_secret_versions(client, secret_path: str, keep: int = 5) -> None:
"""Destroy ENABLED secret versions beyond the newest `keep`.
OAuth credential secrets are rewritten on every refresh, which would
otherwise accumulate hundreds of versions and cost ~$0.06/version/month
in replica storage. Only the newest version is read (`versions/latest`),
so older versions are dead weight.
"""
try:
versions = list(client.list_secret_versions(request={"parent": secret_path}))
enabled = [
v for v in versions
if v.state == v.State.ENABLED # type: ignore[attr-defined]
]
enabled.sort(key=lambda v: v.create_time, reverse=True)
for v in enabled[keep:]:
try:
client.destroy_secret_version(request={"name": v.name})
except Exception as e:
logger.warning(f"Failed to destroy {v.name}: {e}")
except Exception as e:
logger.warning(f"Failed to prune old secret versions for {secret_path}: {e}")
class CredentialStatus(str, Enum):
"""Status of OAuth credentials."""
VALID = "valid"
@@ -329,7 +353,9 @@ class CredentialManager:
parent=secret_path,
payload={"data": json.dumps(updated_data).encode("utf-8")}
)
_destroy_old_secret_versions(client, secret_path, keep=5)
logger.info(f"Updated {secret_name} with refreshed token")
return True
@@ -421,19 +447,21 @@ class CredentialManager:
"""Update stored Dropbox credentials."""
try:
from google.cloud import secretmanager
client = secretmanager.SecretManagerServiceClient()
project_id = self.settings.google_cloud_project
secret_path = f"projects/{project_id}/secrets/{self.DROPBOX_SECRET}"
client.add_secret_version(
parent=secret_path,
payload={"data": json.dumps(creds).encode("utf-8")}
)
_destroy_old_secret_versions(client, secret_path, keep=5)
logger.info("Updated Dropbox credentials with refreshed token")
return True
except Exception as e:
logger.error(f"Failed to update Dropbox credentials: {e}")
return False
+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]:
+31
View File
@@ -151,6 +151,37 @@ class DropboxService:
logger.info(f"Next brand code for {brand_prefix}: {next_code} (max existing: {max_existing})")
return next_code
def file_exists(self, remote_path: str) -> bool:
"""
Check whether a file exists at the given Dropbox path.
Args:
remote_path: Dropbox path (must start with /)
Returns:
True if a file exists at the path, False otherwise.
"""
from dropbox.exceptions import ApiError
if not remote_path.startswith("/"):
remote_path = f"/{remote_path}"
try:
self.client.files_get_metadata(remote_path)
return True
except ApiError as e:
# Only a genuine "not found" means the file is absent. Re-raise other
# API errors (auth, network, rate limit) so callers don't mistake a
# transient failure for "missing" (e.g. the backfill uploading a dup).
err = e.error
if (
hasattr(err, "is_path")
and err.is_path()
and err.get_path().is_not_found()
):
return False
raise
def upload_file(self, local_path: str, remote_path: str) -> None:
"""
Upload a single file to Dropbox.
+153
View File
@@ -0,0 +1,153 @@
"""Reconcile a job's credit charge against the actual audio about to be processed.
Called at the convergence point immediately before the separation+transcription
workers are triggered (post-edit if an edit occurred). The probe callable returns
the duration in seconds of `job.input_media_gcs_path` (the to-be-processed audio).
"""
import asyncio
import json
import subprocess
from dataclasses import dataclass
from typing import Callable, Optional
import logging
from backend.services.pricing import duration_to_credits, is_blocked
from backend.models.job import JobStatus
logger = logging.getLogger(__name__)
@dataclass
class ReconcileResult:
action: str # "proceed" | "pause" | "cancel"
pending_additional_credits: int = 0
actual_seconds: Optional[float] = None
def reconcile_duration(
job_id: str,
job_manager,
user_service,
probe_duration: Callable[[object], Optional[float]],
email_service=None,
) -> ReconcileResult:
job = job_manager.get_job(job_id)
actual = probe_duration(job)
state = dict(job.state_data or {})
credits_charged = int(state.get("credits_charged", 1))
# Short-circuit for admin / payment-bypassed jobs: measure duration for
# observability but do NOT pause, charge, refund, or cancel regardless of
# how long the audio turns out to be.
if state.get("payment_bypassed"):
if actual is not None:
job_manager.update_job(job_id, {"state_data.duration_actual_seconds": actual})
logger.info("Job %s: payment_bypassed=True, skipping reconcile (actual=%s s)", job_id, actual)
return ReconcileResult(action="proceed", actual_seconds=actual)
if actual is None:
logger.warning("Job %s: duration probe returned None; proceeding without reconcile", job_id)
return ReconcileResult(action="proceed", actual_seconds=None)
job_manager.update_job(job_id, {"state_data.duration_actual_seconds": actual})
if is_blocked(actual):
if credits_charged > 0:
user_service.add_credits(job.user_email, amount=credits_charged,
reason="duration_over_limit_refund", job_id=job_id)
job_manager.update_job(job_id, {"credit_refunded": True}) # suppress cancel_job's built-in 1-credit refund (we already refunded the full charge)
job_manager.cancel_job(job_id, reason="Input audio exceeds the 60-minute limit")
if email_service:
email_service.send_duration_confirm_expired(
to_email=job.user_email,
artist=getattr(job, "artist", None),
title=getattr(job, "title", None),
credits_refunded=credits_charged,
reason="over_limit",
)
return ReconcileResult(action="cancel", actual_seconds=actual)
required = duration_to_credits(actual)
delta = required - credits_charged
if delta == 0:
return ReconcileResult(action="proceed", actual_seconds=actual)
if delta < 0:
user_service.add_credits(job.user_email, amount=abs(delta),
reason="duration_refund", job_id=job_id)
job_manager.update_job(job_id, {"state_data.credits_charged": required})
return ReconcileResult(action="proceed", actual_seconds=actual)
# delta > 0 : owe more credits — pause for explicit re-confirmation.
job_manager.update_job(job_id, {
"state_data.duration_confirm_reason": "reconcile",
"state_data.pending_additional_credits": delta,
})
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.AWAITING_DURATION_CONFIRM,
progress=16,
message=f"This turned out longer than estimated — {delta} more credit(s) needed",
)
return ReconcileResult(action="pause", pending_additional_credits=delta, actual_seconds=actual)
# --- Pipeline wiring (impure: uses singletons + ffprobe) ---
def _ffprobe_seconds(job, storage) -> Optional[float]:
"""Header-only ffprobe of job.input_media_gcs_path via a signed URL.
Mirrors the async _get_audio_duration_ffprobe_signed helper in
backend/api/routes/jobs.py, but as a sync function suitable for use
in run_in_executor.
"""
gcs_path = getattr(job, "input_media_gcs_path", None)
if not gcs_path:
return None
try:
signed_url = storage.generate_signed_url(gcs_path, expiration_minutes=5)
result = subprocess.run(
["ffprobe", "-v", "quiet", "-print_format", "json", "-show_format", signed_url],
capture_output=True, text=True, timeout=30,
)
if result.returncode != 0:
return None
return float(json.loads(result.stdout)["format"]["duration"])
except Exception as e:
logger.warning("Job %s: ffprobe duration failed: %s", getattr(job, "id", "?"), e)
return None
async def reconcile_and_maybe_pause(job_id: str) -> bool:
"""Resolve real singletons, probe duration, run reconcile_duration, return True if blocked.
Returns True when the job has been paused (AWAITING_DURATION_CONFIRM) or cancelled,
meaning the caller must NOT trigger downstream workers.
Returns False when the job should proceed normally.
Designed for the no-edit convergence point in audio_download_worker.py.
"""
# Import at function scope to avoid circular imports.
from backend.services.job_manager import JobManager
from backend.services.user_service import get_user_service
from backend.services.storage_service import StorageService
from backend.services.email_service import get_email_service
job_manager = JobManager()
user_service = get_user_service()
storage = StorageService()
# JobManager/StorageService have no singleton accessor; instantiate directly (matches audio_download_worker).
email_service = get_email_service()
result = await asyncio.get_running_loop().run_in_executor(
None,
lambda: reconcile_duration(
job_id,
job_manager,
user_service,
lambda job: _ffprobe_seconds(job, storage),
email_service,
),
)
return result.action in ("pause", "cancel")
+298 -119
View File
@@ -2,12 +2,10 @@
Email service for sending transactional emails.
Supports multiple providers:
- Postmark (production default — better Yahoo/AOL deliverability)
- SendGrid (legacy fallback, retained during cutover)
- Postmark (production)
- Console logging (for development/testing)
Provider selection: EMAIL_PROVIDER env var (postmark|sendgrid). Defaults to
postmark when both keys are present.
Provider selection: POSTMARK_SERVER_TOKEN env var enables Postmark.
"""
import html
import logging
@@ -121,91 +119,6 @@ class PreviewEmailProvider(EmailProvider):
return self.last_html
class SendGridEmailProvider(EmailProvider):
"""
SendGrid email provider for production.
Requires SENDGRID_API_KEY environment variable.
"""
def __init__(self, api_key: str, from_email: str, from_name: str = "Nomad Karaoke"):
self.api_key = api_key
self.from_email = from_email
self.from_name = from_name
def send_email(
self,
to_email: str,
subject: str,
html_content: str,
text_content: Optional[str] = None,
cc_emails: Optional[List[str]] = None,
bcc_emails: Optional[List[str]] = None,
from_email_override: Optional[str] = None,
) -> bool:
try:
# Import here to avoid requiring sendgrid in all environments
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail, Email, To, Content, Cc, Bcc
sg = SendGridAPIClient(api_key=self.api_key)
# Use override sender if provided (for multi-tenant)
sender_email = from_email_override or self.from_email
message = Mail(
from_email=Email(sender_email, self.from_name),
to_emails=To(to_email),
subject=subject,
html_content=Content("text/html", html_content)
)
# Add CC recipients if provided (deduplicated and normalized)
if cc_emails:
# Normalize emails (lowercase, strip whitespace) and deduplicate
seen = set()
unique_cc_emails = []
for cc_email in cc_emails:
normalized = cc_email.strip().lower()
if normalized and normalized not in seen:
seen.add(normalized)
unique_cc_emails.append(cc_email.strip())
for cc_email in unique_cc_emails:
message.add_cc(Cc(cc_email))
# Add BCC recipients if provided (deduplicated and normalized)
if bcc_emails:
seen = set()
unique_bcc_emails = []
for bcc_email in bcc_emails:
normalized = bcc_email.strip().lower()
if normalized and normalized not in seen:
seen.add(normalized)
unique_bcc_emails.append(bcc_email.strip())
for bcc_email in unique_bcc_emails:
message.add_bcc(Bcc(bcc_email))
if text_content:
message.add_content(Content("text/plain", text_content))
response = sg.send(message)
if response.status_code >= 200 and response.status_code < 300:
cc_info = f" (CC: {', '.join(cc_emails)})" if cc_emails else ""
bcc_info = f" (BCC: {', '.join(bcc_emails)})" if bcc_emails else ""
logger.info(f"Email sent to {to_email}{cc_info}{bcc_info} via SendGrid")
return True
else:
logger.error(f"SendGrid returned status {response.status_code}")
return False
except Exception:
logger.exception("Failed to send email via SendGrid")
return False
class PostmarkEmailProvider(EmailProvider):
"""
Postmark email provider for production.
@@ -315,48 +228,25 @@ class EmailService:
self.buy_url = os.getenv("BUY_URL", self.frontend_url)
def _get_provider(self) -> EmailProvider:
"""
Get the configured email provider.
"""Get the configured email provider.
Selection rules:
- EMAIL_PROVIDER=postmark → Postmark (requires POSTMARK_SERVER_TOKEN)
- EMAIL_PROVIDER=sendgrid → SendGrid (requires SENDGRID_API_KEY)
- Unset/auto → Postmark if its token is set, else SendGrid if its key is set, else console
Postmark is used when POSTMARK_SERVER_TOKEN is set; otherwise falls
back to console logging (dev/test).
"""
provider_name = (os.getenv("EMAIL_PROVIDER") or "").strip().lower()
postmark_token = os.getenv("POSTMARK_SERVER_TOKEN")
sendgrid_api_key = os.getenv("SENDGRID_API_KEY")
from_email = os.getenv("EMAIL_FROM", "gen@nomadkaraoke.com")
from_name = os.getenv("EMAIL_FROM_NAME", "Nomad Karaoke")
if provider_name == "postmark":
if not postmark_token:
logger.error("EMAIL_PROVIDER=postmark but POSTMARK_SERVER_TOKEN is not set; falling back to console")
return ConsoleEmailProvider()
if postmark_token:
logger.info("Using Postmark email provider")
return PostmarkEmailProvider(postmark_token, from_email, from_name)
if provider_name == "sendgrid":
if not sendgrid_api_key:
logger.error("EMAIL_PROVIDER=sendgrid but SENDGRID_API_KEY is not set; falling back to console")
return ConsoleEmailProvider()
logger.info("Using SendGrid email provider")
return SendGridEmailProvider(sendgrid_api_key, from_email, from_name)
# Auto-detect: prefer Postmark when both keys are present
if postmark_token:
logger.info("Using Postmark email provider (auto-detected)")
return PostmarkEmailProvider(postmark_token, from_email, from_name)
if sendgrid_api_key:
logger.info("Using SendGrid email provider (auto-detected)")
return SendGridEmailProvider(sendgrid_api_key, from_email, from_name)
logger.warning("No email provider configured, using console logging")
return ConsoleEmailProvider()
def is_configured(self) -> bool:
"""Check if a real email provider is configured (not just console logging)."""
return isinstance(self.provider, (SendGridEmailProvider, PostmarkEmailProvider))
return isinstance(self.provider, PostmarkEmailProvider)
def send_magic_link(
self,
@@ -1230,6 +1120,148 @@ class EmailService:
text_content=text_content,
)
def send_duration_confirm_reminder(
self,
to_email: str,
job_id: Optional[str] = None,
artist: Optional[str] = None,
title: Optional[str] = None,
pending_credits: Optional[int] = None,
duration_seconds: Optional[int] = None,
confirm_url: Optional[str] = None,
locale: str = "en",
) -> bool:
"""
Send a 15-minute idle reminder email for jobs awaiting duration confirmation.
Sent when a job has been in AWAITING_DURATION_CONFIRM for 15 minutes without
the user confirming the extra cost.
Args:
to_email: User's email address
job_id: Job ID (used to build the confirm URL if not provided)
artist: Artist name for subject line
title: Song title for subject line
pending_credits: Number of additional credits required
duration_seconds: Actual duration of the song in seconds
confirm_url: Direct URL to the confirmation page
locale: User's locale (future: translated; currently English)
Returns:
True if email was sent successfully
"""
if artist and title:
subject = f"Your karaoke job needs you to confirm the cost — {artist} - {title}"
else:
subject = "Your karaoke job needs you to confirm the cost"
extra_styles = """
.alert {
background-color: #fef3c7;
border: 1px solid #fcd34d;
border-radius: 8px;
padding: 16px;
margin: 20px 0;
text-align: center;
}
.confirm-btn {
display: inline-block;
background-color: #ff7acc;
color: #ffffff !important;
text-decoration: none;
padding: 12px 24px;
border-radius: 8px;
font-weight: bold;
margin: 16px 0;
}
.cost-box {
background-color: #f0f9ff;
border: 1px solid #93c5fd;
border-radius: 8px;
padding: 16px;
margin: 20px 0;
text-align: center;
}
"""
song_name = (
f" for <strong>{html.escape(artist)} — {html.escape(title)}</strong>"
if artist and title
else ""
)
song_name_text = f" for {artist} — {title}" if artist and title else ""
# Build cost detail line (best-effort — fields may be absent for older jobs)
if pending_credits is not None and duration_seconds is not None:
duration_mins = duration_seconds // 60
duration_secs = duration_seconds % 60
duration_str = f"{duration_mins}:{duration_secs:02d}"
cost_detail_html = (
f"<p>The song{song_name} turned out to be "
f"<strong>{duration_str}</strong> long and requires "
f"<strong>{pending_credits} additional credit"
f"{'s' if pending_credits != 1 else ''}</strong> to process.</p>"
)
cost_detail_text = (
f"The song{song_name_text} turned out to be {duration_str} long and "
f"requires {pending_credits} additional credit"
f"{'s' if pending_credits != 1 else ''} to process.\n"
)
elif pending_credits is not None:
cost_detail_html = (
f"<p>Processing{song_name} requires "
f"<strong>{pending_credits} additional credit"
f"{'s' if pending_credits != 1 else ''}</strong>.</p>"
)
cost_detail_text = (
f"Processing{song_name_text} requires {pending_credits} additional credit"
f"{'s' if pending_credits != 1 else ''}.\n"
)
else:
cost_detail_html = f"<p>Your karaoke job{song_name} requires a few extra credits to continue.</p>"
cost_detail_text = f"Your karaoke job{song_name_text} requires a few extra credits to continue.\n"
# TODO(i18n): translate subject/body once duration-confirm keys are added to
# backend/translations/{locale}.json. URL already uses the locale prefix.
locale_prefix = get_locale_prefix(locale)
url_to_use = confirm_url or (
f"{self.frontend_url}{locale_prefix}/app/jobs#/{job_id}/review"
if job_id
else f"{self.frontend_url}{locale_prefix}/app"
)
content = f"""
<div class="alert">
⏰ Your job is waiting for your confirmation
</div>
{cost_detail_html}
<p>Please visit your job to review the cost and confirm whether to continue processing.</p>
<p style="text-align: center;">
<a href="{html.escape(url_to_use)}" class="confirm-btn">Confirm cost &amp; continue</a>
</p>
<p>If you have any questions, just reply to this email — we're happy to help.</p>
"""
html_content = self._build_email_html(content, extra_styles, locale=locale)
text_content = (
f"Your karaoke job is waiting for your confirmation.\n\n"
f"{cost_detail_text}\n"
f"Please visit your job to confirm: {url_to_use}\n\n"
f"If you have any questions, just reply to this email — we're happy to help."
)
return self.provider.send_email(
to_email=to_email,
subject=subject,
html_content=html_content,
text_content=text_content,
)
def send_review_expired(
self,
to_email: str,
@@ -1323,6 +1355,148 @@ class EmailService:
text_content=text_content,
)
def send_duration_confirm_expired(
self,
to_email: str,
artist: Optional[str] = None,
title: Optional[str] = None,
credits_refunded: int = 0,
locale: str = "en",
reason: str = "timeout",
) -> bool:
"""
Send duration-confirm cancellation notification email.
Two cancellation reasons are supported via the ``reason`` parameter:
- ``"timeout"`` (default): job was auto-cancelled after 48 hours in
AWAITING_DURATION_CONFIRM because the user never confirmed the extra cost.
- ``"over_limit"`` : job was immediately cancelled because the audio
duration exceeds the supported 60-minute ceiling.
Args:
to_email: User's email address
artist: Artist name for subject line
title: Song title for subject line
credits_refunded: Number of credits that were refunded
locale: User locale (reserved for future i18n; currently English)
reason: "timeout" or "over_limit" — controls the cancellation message
Returns:
True if email was sent successfully
"""
if reason == "over_limit":
if artist and title:
subject = f"Your karaoke job was cancelled — audio exceeds 60 minutes ({artist} - {title})"
else:
subject = "Your karaoke job was cancelled — audio exceeds 60 minutes"
else:
if artist and title:
subject = f"Your karaoke job was cancelled — cost not confirmed in time ({artist} - {title})"
else:
subject = "Your karaoke job was cancelled — cost not confirmed in time"
extra_styles = """
.info-box {
background-color: #f0f9ff;
border: 1px solid #93c5fd;
border-radius: 8px;
padding: 16px;
margin: 20px 0;
text-align: center;
}
.credit-badge {
display: inline-block;
background-color: #22c55e;
color: #ffffff;
padding: 4px 12px;
border-radius: 12px;
font-weight: bold;
}
.create-btn {
display: inline-block;
background-color: #ff7acc;
color: #ffffff !important;
text-decoration: none;
padding: 12px 24px;
border-radius: 8px;
font-weight: bold;
margin: 16px 0;
}
"""
song_name = f" for <strong>{html.escape(artist)} - {html.escape(title)}</strong>" if artist and title else ""
song_name_text = f" for {artist} - {title}" if artist and title else ""
credits_word = "credit" if credits_refunded == 1 else "credits"
refund_notice_html = (
f"<p>We've refunded <span class=\"credit-badge\">{credits_refunded} {credits_word}</span> "
f"to your account.</p>"
if credits_refunded > 0
else "<p>Your account has been updated.</p>"
)
refund_notice_text = (
f"We've refunded {credits_refunded} {credits_word} to your account."
if credits_refunded > 0
else "Your account has been updated."
)
if reason == "over_limit":
cancel_reason_html = (
f"Your karaoke job{song_name} was automatically cancelled because the audio "
f"exceeds the supported 60-minute limit."
)
cancel_reason_text = (
f"Your karaoke job{song_name_text} was automatically cancelled because the "
f"audio exceeds the supported 60-minute limit."
)
else:
cancel_reason_html = (
f"Your karaoke job{song_name} was automatically cancelled because the extra cost "
f"was not confirmed within 48 hours."
)
cancel_reason_text = (
f"Your karaoke job{song_name_text} was automatically cancelled because the extra "
f"cost was not confirmed within 48 hours."
)
# TODO(i18n): translate subject/body once duration-confirm keys are added to
# backend/translations/{locale}.json. URL already uses the locale prefix.
locale_prefix = get_locale_prefix(locale)
app_url = f"{self.frontend_url}{locale_prefix}/app"
content = f"""
<div class="info-box">
{cancel_reason_html}
</div>
{refund_notice_html}
<p>You can start a new job at any time — your credits are ready to use.</p>
<p style="text-align: center;">
<a href="{html.escape(app_url)}" class="create-btn">Create a new job</a>
</p>
<p>If you have any questions, just reply to this email — we're happy to help.</p>
"""
html_content = self._build_email_html(content, extra_styles, locale=locale)
text_content = (
f"{cancel_reason_text}\n\n"
f"{refund_notice_text}\n\n"
f"You can start a new job at any time: {app_url}\n\n"
f"If you have any questions, just reply to this email — we're happy to help."
)
return self.provider.send_email(
to_email=to_email,
subject=subject,
html_content=html_content,
text_content=text_content,
)
def send_youtube_upload_complete(
self,
to_email: str,
@@ -1531,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">
+92
View File
@@ -0,0 +1,92 @@
"""Typed exceptions for encoding worker lifecycle failures.
These let callers distinguish between transient capacity issues (retry will
likely help) and unexpected start failures (something is actually broken).
"""
from typing import FrozenSet
CAPACITY_ERROR_CODES: FrozenSet[str] = frozenset({
"ZONE_RESOURCE_POOL_EXHAUSTED",
"ZONE_RESOURCE_POOL_EXHAUSTED_WITH_DETAILS",
"STOCKOUT",
"QUOTA_EXCEEDED",
})
class EncodingWorkerStartError(Exception):
"""Raised when an attempt to start an encoding worker VM fails.
Carries the GCE error code so callers can react to specific failure modes.
"""
def __init__(
self,
message: str,
*,
vm_name: str = "",
zone: str = "",
code: str = "",
) -> None:
super().__init__(message)
self.vm_name = vm_name
self.zone = zone
self.code = code
class EncodingWorkerCapacityError(EncodingWorkerStartError):
"""A capacity-related GCE failure (e.g. ZONE_RESOURCE_POOL_EXHAUSTED).
The zone temporarily cannot allocate the requested machine type. Callers
should treat this as recoverable — retrying after a wait, or trying an
alternate zone, is likely to succeed.
"""
# Marker the encoding worker writes into a job's status when it was interrupted
# by a worker-process restart (OOM, deploy, crash). Kept in sync with
# gce_encoding/persistence.py `_RESTART_FAIL_CODE`.
ENCODING_RESTART_FAILURE_CODE = "encoding_worker_restart"
class EncodingJobNotFoundError(RuntimeError):
"""The encoding worker returned HTTP 404 for a job status poll.
Subclasses RuntimeError so existing `except RuntimeError` handlers and
`"not found" in str(e)` checks keep working, while giving callers a precise
type to branch on (e.g. distinguishing a lost job from other RuntimeErrors)
without parsing the message text. Keep the message containing "not found".
"""
class EncodingJobLostError(Exception):
"""The encoding worker lost a job mid-run (restart wiped its in-memory state).
Distinct from a transient poll blip: the ffmpeg process and temp work dir
are gone, so the *same* job will never complete. The only recovery is to
resubmit the work as a fresh job. Deliberately NOT a subclass of
RuntimeError so it escapes the poll-failure tolerance in
`wait_for_completion` instead of being swallowed as a retryable blip.
"""
def __init__(self, message: str, *, job_id: str = "") -> None:
super().__init__(message)
self.job_id = job_id
def classify_gce_error(code: str, message: str, *, vm_name: str, zone: str) -> EncodingWorkerStartError:
"""Wrap a GCE error code/message in the appropriate typed exception."""
if code in CAPACITY_ERROR_CODES:
return EncodingWorkerCapacityError(
f"VM {vm_name} could not be started in {zone}: {code} — {message}",
vm_name=vm_name,
zone=zone,
code=code,
)
return EncodingWorkerStartError(
f"VM {vm_name} start failed in {zone}: {code or 'unknown error'} — {message or 'no message'}",
vm_name=vm_name,
zone=zone,
code=code,
)
+28
View File
@@ -14,6 +14,8 @@ from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Any
from backend.services.encoding_errors import EncodingJobLostError
logger = logging.getLogger(__name__)
@@ -65,6 +67,17 @@ class EncodingOutput:
lossless_mkv_path: Optional[str] = None # MKV with FLAC (for YouTube)
lossy_720p_mp4_path: Optional[str] = None # 720p web version
# Standalone 5-second screen videos generated from the title/end images.
# Kept so they land in the Dropbox folder (regression after #647/#650 moved
# screen generation to the encoder). Not used downstream.
title_mov_path: Optional[str] = None # "<artist> - <title> (Title).mov"
end_mov_path: Optional[str] = None # "<artist> - <title> (End).mov"
# Portrait (9:16) karaoke video for phone viewing / social sharing. Additive;
# distributed to GCS + Dropbox only (never Drive/YouTube). May be absent when the
# portrait render is disabled or fails (it is best-effort).
portrait_mp4_path: Optional[str] = None # "<artist> - <title> (Final Karaoke Portrait 1080x1920).mp4"
# All output files as a dict for convenience
output_files: Dict[str, str] = field(default_factory=dict)
@@ -381,10 +394,16 @@ class GCEEncodingBackend(EncodingBackend):
output_files["mp4_4k_lossless"] = path
elif "lossy 4k" in filename_lower:
output_files["mp4_4k_lossy"] = path
elif "portrait" in filename_lower:
output_files["portrait_mp4"] = path
elif "720p" in filename_lower:
output_files["mp4_720p"] = path
elif "with vocals" in filename_lower and filename.endswith(".mp4"):
output_files["with_vocals_mp4"] = path
elif filename_lower.endswith("(title).mov"):
output_files["title_mov"] = path
elif filename_lower.endswith("(end).mov"):
output_files["end_mov"] = path
self.logger.info(f"Converted output_files list to dict: {output_files}")
else:
output_files = raw_output_files if isinstance(raw_output_files, dict) else {}
@@ -396,11 +415,20 @@ class GCEEncodingBackend(EncodingBackend):
lossless_mkv_path=output_files.get("mkv_4k"),
lossy_720p_mp4_path=output_files.get("mp4_720p"),
with_vocals_mp4_path=output_files.get("with_vocals_mp4"),
title_mov_path=output_files.get("title_mov"),
end_mov_path=output_files.get("end_mov"),
portrait_mp4_path=output_files.get("portrait_mp4"),
output_files=output_files,
encoding_time_seconds=encoding_time,
encoding_backend=self.name
)
except EncodingJobLostError:
# The worker lost this job mid-run (OOM/deploy restart). This is
# recoverable by resubmitting a fresh job id, so let the orchestrator
# decide — do NOT flatten it into success=False (which would fail the
# whole render). See video_worker_orchestrator's resubmit wrapper.
raise
except Exception as e:
encoding_time = time.time() - start_time
self.logger.error(f"GCE encoding failed: {e}")
+502 -54
View File
@@ -17,15 +17,40 @@ Usage:
import asyncio
import logging
import os
import time
from typing import Optional, Dict, Any
import uuid
from contextlib import asynccontextmanager
from typing import Awaitable, Callable, Optional, Dict, Any, AsyncIterator
import aiohttp
from backend.config import get_settings
from backend.services.encoding_errors import (
ENCODING_RESTART_FAILURE_CODE,
EncodingJobLostError,
EncodingJobNotFoundError,
EncodingWorkerCapacityError,
EncodingWorkerStartError,
)
logger = logging.getLogger(__name__)
# Per-URL submission throttle. The encoding worker has a ThreadPoolExecutor
# of 4 workers (gce_encoding/main.py). Submitting more concurrent jobs than
# that to a single VM caused `Connection reset by peer` errors on the 5th+
# job during the May 6 fallback storm — 7 jobs simultaneously hammered
# fallback-a after the primary failed.
#
# Limit to 3 concurrent renders per URL per Cloud Run instance, leaving 1
# worker thread for status polls / preview / health checks. With multiple
# Cloud Run instances this is not a global cap (would require a distributed
# lock) but it caps each instance's contribution to the storm — empirically
# enough to prevent the failure mode.
_DEFAULT_SUBMISSION_CONCURRENCY = int(
os.environ.get("ENCODING_SUBMISSION_CONCURRENCY", "3")
)
# Retry configuration for handling transient failures (e.g., worker restarts during deployments).
#
# During a CI deployment, the encoding worker is restarted via systemctl. The restart
@@ -44,6 +69,94 @@ MAX_BACKOFF_SECONDS = 15.0
# long-running encoding job. Similar pattern to flacfetch status polling (PR #446).
MAX_CONSECUTIVE_POLL_FAILURES = 5
_DEFAULT_QUEUE_TIMEOUT_SECONDS = float(4 * 3600)
def _parse_queue_timeout() -> float:
"""How long a job may sit *queued* (status "pending") before we give up.
Parsed defensively: a malformed / non-finite / non-positive value must not
crash the module at import nor make pending jobs fail immediately — fall back
to the generous default. Separate from the per-run `timeout`, which only
starts once the job is actually "running".
"""
raw = os.environ.get("ENCODING_QUEUE_TIMEOUT")
if raw is None:
return _DEFAULT_QUEUE_TIMEOUT_SECONDS
try:
value = float(raw)
except (TypeError, ValueError):
logger.warning("Invalid ENCODING_QUEUE_TIMEOUT=%r; using default", raw)
return _DEFAULT_QUEUE_TIMEOUT_SECONDS
if not (value > 0) or value == float("inf"):
logger.warning("ENCODING_QUEUE_TIMEOUT=%r not a positive finite number; using default", raw)
return _DEFAULT_QUEUE_TIMEOUT_SECONDS
return value
def _parse_resubmit_max() -> int:
"""Bounded automatic resubmits when the worker loses a job mid-run.
Each resubmit is a fresh job id; see `run_with_lost_job_resubmit`. A bad
value falls back to 2; negatives clamp to 0 (no resubmits).
"""
raw = os.environ.get("ENCODING_RESUBMIT_MAX", "2")
try:
return max(0, int(raw))
except (TypeError, ValueError):
logger.warning("Invalid ENCODING_RESUBMIT_MAX=%r; using 2", raw)
return 2
QUEUE_TIMEOUT_SECONDS = _parse_queue_timeout()
ENCODING_RESUBMIT_MAX = _parse_resubmit_max()
async def run_with_lost_job_resubmit(
operation: Callable[[str], Awaitable[Any]],
base_job_id: str,
*,
log: logging.Logger = logger,
max_resubmits: int = ENCODING_RESUBMIT_MAX,
) -> Any:
"""Run a submit+wait `operation(job_id)`, resubmitting if the worker loses it.
The encoding worker keeps job state in memory; an OOM/deploy restart wipes it
and the in-flight ffmpeg, so the original job id can never complete. When
`wait_for_completion` detects that (via `EncodingJobLostError`), we resubmit
the same work under a fresh `<base>_retry_<hex8>` id (the worker treats a new
id as a brand-new job). Bounded by `max_resubmits`.
`operation` must be an async callable taking the job id to use and performing
the whole submit-and-wait, returning the encode result. It should raise
`EncodingJobLostError` (propagated from `wait_for_completion`) when the job is
lost; any other exception aborts immediately.
Idempotency: only the *worker-side* job id changes between attempts — output
GCS paths are keyed by the real job (fixed input/output prefixes), so a
resubmit re-encodes and *overwrites* the same objects rather than producing
duplicates. Downstream side effects (uploads, distribution) run in the
orchestrator only after a successful encode, so a resubmit before "complete"
cannot double them.
"""
attempt = 0
while True:
job_id = base_job_id if attempt == 0 else f"{base_job_id}_retry_{uuid.uuid4().hex[:8]}"
try:
return await operation(job_id)
except EncodingJobLostError as e:
attempt += 1
if attempt > max_resubmits:
log.error(
f"[job:{base_job_id}] Encoding worker lost the job {attempt} time(s); "
f"giving up after {max_resubmits} resubmit(s): {e}"
)
raise
log.warning(
f"[job:{base_job_id}] Encoding worker lost the job (restart/OOM); "
f"resubmitting as a fresh job (attempt {attempt + 1}/{max_resubmits + 1})"
)
def _format_exception(e: BaseException) -> str:
"""Render an exception with type info.
@@ -70,12 +183,24 @@ class EncodingService:
self._url_cached_at = 0
self._URL_CACHE_TTL = 30 # seconds
# Per-URL submission semaphores. Lazily created on first use so we
# don't bind to the wrong event loop at import time. Bound at
# _DEFAULT_SUBMISSION_CONCURRENCY to keep concurrent renders per
# worker VM under the worker's own ThreadPool capacity.
self._url_semaphores: Dict[str, asyncio.Semaphore] = {}
self._url_semaphores_lock: Optional[asyncio.Lock] = None
self._submission_concurrency = _DEFAULT_SUBMISSION_CONCURRENCY
def set_worker_manager(self, manager):
"""Set the worker manager for dynamic URL resolution from Firestore."""
self._worker_manager = manager
def _get_worker_url(self) -> str:
"""Get the current primary worker URL from Firestore (with TTL cache).
"""Get the current worker URL from Firestore (with TTL cache).
Returns config.active_url, which is normally the primary URL but
switches to the capacity-fallback override when a primary-zone
outage caused us to start a fallback VM in another zone.
Falls back to static URL from config if worker_manager is not set.
"""
@@ -85,7 +210,7 @@ class EncodingService:
if self._worker_manager:
config = self._worker_manager.get_config()
self._cached_url = config.primary_url
self._cached_url = config.active_url
self._url_cached_at = now
return self._cached_url
@@ -94,6 +219,135 @@ class EncodingService:
self._load_credentials()
return self._url
def _invalidate_cached_url(self) -> None:
"""Force the next _get_worker_url() to re-read from Firestore.
Called after the worker manager updates active_override (e.g. on
capacity fallback) so the in-flight request loop picks up the new URL.
"""
self._cached_url = None
self._url_cached_at = 0.0
@asynccontextmanager
async def _submission_slot(self, url: str, job_id: str) -> AsyncIterator[None]:
"""Bound the number of concurrent renders/encodes per worker URL.
The encoding worker has 4 thread-pool workers; submitting 7+ at once
causes `Connection reset by peer` mid-encode (observed during the
May 6 fallback storm). This semaphore caps each Cloud Run instance's
concurrent submissions per URL at `_submission_concurrency`,
leaving headroom for status polls and previews.
Captures the URL at entry — if the worker manager swaps active_url
mid-operation (capacity fallback) we keep the original slot. The
slot count for the new URL will be slightly understated until the
next submission, which is acceptable: the fallback path is rare,
and the goal is preventing the orchestrator-side thundering herd.
"""
# Lazily create the per-loop lock so we bind to the right event loop
if self._url_semaphores_lock is None:
self._url_semaphores_lock = asyncio.Lock()
async with self._url_semaphores_lock:
sem = self._url_semaphores.get(url)
if sem is None:
sem = asyncio.Semaphore(self._submission_concurrency)
self._url_semaphores[url] = sem
# Brief log only when we actually have to wait — keeps the happy
# path quiet but surfaces contention during a fallback storm.
if sem.locked():
logger.info(
f"[job:{job_id}] Waiting for encoding submission slot "
f"(url={url}, in_flight>={self._submission_concurrency})"
)
async with sem:
yield
def _build_worker_candidates(self) -> list:
"""Build the ranked candidate list for ensure_any_running.
Reads optional fallback VMs from settings (env var
ENCODING_WORKER_FALLBACK_VMS, JSON list of {vm, zone, ip, machine_type?}).
The primary + all fallbacks are ranked by the shared preference logic
(fastest-first, demoting recently-stocked-out types) so runtime selection
stays in lock-step with the deploy green selection. Returns an empty list
when no worker manager / no configured fallbacks — caller falls back to
the single-VM ensure_primary_running path.
"""
if not self._worker_manager:
return []
try:
config = self._worker_manager.get_config()
except Exception as e: # noqa: BLE001
logger.warning(f"Could not read worker config for candidates: {_format_exception(e)}")
return []
from backend.services.encoding_worker_manager import EncodingWorkerCandidate
from backend.services.encoding_worker_preference import (
PRIMARY_MACHINE_TYPE,
ordered_candidates,
)
# Build a dict pool (primary + fallbacks), each tagged with machine_type so
# the shared preference logic can rank them. The primary/secondary pair is
# always c4d; the config may override via primary_machine_type.
primary_mt = getattr(config, "primary_machine_type", None) or PRIMARY_MACHINE_TYPE
pool = [{
"vm": config.primary_vm,
"zone": self._worker_manager._zone,
"ip": config.primary_ip,
"machine_type": primary_mt,
"kind": "primary",
"is_primary": True,
}]
# Optional capacity-fallback VMs in alternate zones/families, configured via
# env var. Schema: '[{"vm":"encoding-worker-fallback-c4a","zone":"us-central1-a",
# "ip":"34.x.x.x","machine_type":"c4-highcpu-32"}, ...]'. machine_type is
# optional (inferred from the VM name for legacy entries). Empty by default;
# populated after `pulumi up` provisions the fallback VMs.
import json as _json
raw = self.settings.encoding_worker_fallback_vms
if raw:
try:
parsed = _json.loads(raw)
except (ValueError, TypeError) as e:
logger.warning(f"Invalid ENCODING_WORKER_FALLBACK_VMS JSON: {e}")
parsed = []
# A non-list root (null, dict, scalar) parses fine but would blow up
# `for item in parsed` and escape this method during connection
# recovery — degrade to no fallbacks instead.
if not isinstance(parsed, list):
logger.warning("ENCODING_WORKER_FALLBACK_VMS must be a JSON list; ignoring")
parsed = []
for item in parsed:
try:
pool.append({
"vm": item["vm"],
"zone": item["zone"],
"ip": item["ip"],
"machine_type": item.get("machine_type"),
"kind": "fallback",
})
except (KeyError, TypeError) as e:
logger.warning(f"Skipping malformed fallback candidate {item}: {e}")
continue
# Rank fastest-first, demoting types that recently stocked out. Keeps the
# primary (c4d) at the top whenever it has capacity.
ranked = ordered_candidates(pool, capacity_state=config.capacity_state)
return [
EncodingWorkerCandidate(
vm_name=c["vm"],
zone=c["zone"],
ip=c["ip"],
machine_type=c.get("machine_type"),
is_primary=c.get("is_primary", False),
)
for c in ranked
]
def _load_credentials(self):
"""Load encoding worker URL and API key from config/secrets."""
if self._initialized:
@@ -140,11 +394,36 @@ class EncodingService:
If the worker_manager is not set (e.g. dev mode with static URL), this
is a no-op.
Raises:
EncodingWorkerCapacityError: GCE could not allocate capacity (e.g.
ZONE_RESOURCE_POOL_EXHAUSTED). Caller should bail out of any
retry loop — no point hammering an HTTP endpoint that will
never come up — and surface the error to the job.
"""
if not self._worker_manager:
return
candidates = self._build_worker_candidates()
try:
result = self._worker_manager.ensure_primary_running()
if candidates and len(candidates) > 1:
# Multi-zone path: try primary, then fallbacks in alt zones.
result = self._worker_manager.ensure_any_running(candidates)
# If we fell back, the worker manager just persisted the
# active_override URL — invalidate our cache so the next
# request hits the right VM.
if result.get("fell_back"):
self._invalidate_cached_url()
else:
result = self._worker_manager.ensure_primary_running()
except EncodingWorkerStartError:
# Every candidate exhausted (or single-zone primary failed) — both
# capacity errors and other start failures (e.g. 503
# SERVICE_UNAVAILABLE from the GCE backend) are transient and the
# render worker should park the job for retry rather than hard-fail
# with a misleading "connection timeout" message. EncodingWorker
# CapacityError subclasses StartError, so this catches both.
raise
except Exception as e:
logger.warning(
f"[job:{job_id}] Encoding worker warmup fallback failed (non-fatal): "
@@ -160,6 +439,12 @@ class EncodingService:
await self._worker_manager.wait_for_worker_ready(
result["vm_name"],
f"{result['primary_url']}/health",
# Pass the candidate's zone — without this, multi-zone
# fallback successfully starts a VM in (e.g.) us-central1-a
# but readiness wait looks for it in the manager's default
# zone (us-central1-c), gets 404, gives up, and the next
# request hits a still-booting VM and times out.
zone=result.get("zone"),
)
logger.info(
f"[job:{job_id}] Cold-started VM {result['vm_name']} is now ready"
@@ -186,6 +471,8 @@ class EncodingService:
json_payload: Optional[Dict[str, Any]] = None,
timeout: float = 30.0,
job_id: str = "unknown",
path: Optional[str] = None,
allow_failover: bool = True,
) -> Dict[str, Any]:
"""
Make an HTTP request with retry logic for transient failures.
@@ -195,11 +482,25 @@ class EncodingService:
Args:
method: HTTP method (GET, POST)
url: Request URL
url: Initial request URL (used for the first attempt)
headers: Request headers
json_payload: JSON body for POST requests
timeout: Request timeout in seconds
job_id: Job ID for logging
path: Endpoint path (e.g. "/render-video"). When set, retry attempts
AFTER the warmup runs re-resolve the URL via _get_worker_url() +
path. This is what lets multi-zone fallback take effect mid-loop:
the warmup may set a new active_override (e.g. switching to a
fallback VM in another zone) and invalidate the URL cache; the
next retry then targets the freshly-routed URL instead of the
original primary which is dead.
allow_failover: When True (default), a connection error fires the
fallback-VM warmup and lets retries re-resolve the URL. Set False
for requests pinned to a specific worker (in-flight status polls):
a pinned poll must never re-route to active_url nor spin up a
fallback VM, because a different/fresh VM cannot have the job — it
would only return "not found" and orphan a render that is actually
succeeding on the pinned worker (incident 2026-06-16, job d3af33ae).
Returns:
Dict with keys:
@@ -214,8 +515,22 @@ class EncodingService:
"""
last_exception = None
backoff = INITIAL_BACKOFF_SECONDS
warmup_ran = False
for attempt in range(MAX_RETRIES + 1):
# Re-resolve URL on retries after the warmup has fired, so that any
# active_override change made by the warmup actually takes effect.
# Without this, all 8 retry attempts hammer the original (dead)
# URL even though the warmup successfully routed to a fallback VM.
if allow_failover and path and warmup_ran and self._worker_manager is not None:
resolved = f"{self._get_worker_url()}{path}"
if resolved != url:
logger.info(
f"[job:{job_id}] Re-resolved encoding URL after warmup: "
f"{url} -> {resolved}"
)
url = resolved
try:
async with aiohttp.ClientSession() as session:
if method.upper() == "POST":
@@ -239,8 +554,21 @@ class EncodingService:
}
except (aiohttp.ClientConnectorError, aiohttp.ServerDisconnectedError, asyncio.TimeoutError) as e:
last_exception = e
if attempt == 0:
await self._warmup_encoding_worker_fallback(job_id)
if allow_failover and attempt == 0:
try:
await self._warmup_encoding_worker_fallback(job_id)
warmup_ran = True
except EncodingWorkerStartError as start_err:
# No VM could be started — capacity exhaustion or
# transient backend errors (e.g. 503). Hammering the
# HTTP endpoint 7 more times won't help; surface the
# typed error so the render worker can park the job
# for auto-retry rather than fail hard.
logger.error(
f"[job:{job_id}] Encoding worker start failed, "
f"aborting retries: {start_err}"
)
raise start_err from e
if attempt < MAX_RETRIES:
logger.warning(
f"[job:{job_id}] GCE worker connection failed "
@@ -284,7 +612,8 @@ class EncodingService:
if not self.is_configured:
raise RuntimeError("Encoding service not configured")
url = f"{self._get_worker_url()}/encode"
path = "/encode"
url = f"{self._get_worker_url()}{path}"
headers = {"X-API-Key": self._api_key, "Content-Type": "application/json"}
payload = {
"job_id": job_id,
@@ -302,6 +631,7 @@ class EncodingService:
json_payload=payload,
timeout=30.0,
job_id=job_id,
path=path,
)
if resp["status"] == 401:
@@ -330,12 +660,23 @@ class EncodingService:
return resp["json"]
async def get_job_status(self, job_id: str) -> Dict[str, Any]:
async def get_job_status(
self, job_id: str, worker_url: Optional[str] = None
) -> Dict[str, Any]:
"""
Get the status of an encoding job.
Args:
job_id: Job identifier
worker_url: When set, pin the request to this worker base URL instead
of resolving the current active_url. In-flight polls must stay on
the worker that accepted the job: a blue-green deploy can swap the
active_url primary pointer mid-render, and an unpinned poll would
migrate to the new primary — which never received the job and 404s
"not found", orphaning a render that is succeeding on the original
worker (incident 2026-06-16, job d3af33ae). A pinned poll also
disables failover (allow_failover=False) so it never re-routes nor
starts a fallback VM.
Returns:
Job status including: status, progress, error, output_files
@@ -345,7 +686,11 @@ class EncodingService:
if not self.is_configured:
raise RuntimeError("Encoding service not configured")
url = f"{self._get_worker_url()}/status/{job_id}"
path = f"/status/{job_id}"
if worker_url:
url = f"{worker_url}{path}"
else:
url = f"{self._get_worker_url()}{path}"
headers = {"X-API-Key": self._api_key}
resp = await self._request_with_retry(
@@ -354,12 +699,16 @@ class EncodingService:
headers=headers,
timeout=30.0,
job_id=job_id,
# When pinned, never re-resolve or fail over — the job lives on this
# exact worker; do not pass `path` (which drives re-resolution).
path=None if worker_url else path,
allow_failover=not worker_url,
)
if resp["status"] == 401:
raise RuntimeError("Invalid API key for encoding worker")
if resp["status"] == 404:
raise RuntimeError(f"Encoding job {job_id} not found")
raise EncodingJobNotFoundError(f"Encoding job {job_id} not found")
if resp["status"] != 200:
raise RuntimeError(f"Failed to get job status: {resp['status']} - {resp['text']}")
@@ -371,6 +720,8 @@ class EncodingService:
poll_interval: float = 10.0,
timeout: float = 3600.0,
progress_callback=None,
worker_url: Optional[str] = None,
queue_timeout: float = QUEUE_TIMEOUT_SECONDS,
) -> Dict[str, Any]:
"""
Poll for encoding job completion with tolerance for transient failures.
@@ -385,6 +736,11 @@ class EncodingService:
poll_interval: Seconds between status checks
timeout: Maximum time to wait (default 1 hour)
progress_callback: Optional callback(progress: int) for progress updates
worker_url: Worker base URL the job was submitted to. When set, every
poll is pinned to this worker (see get_job_status) so a mid-render
blue-green primary swap can't migrate the poll to a worker that
never received the job. When None, polls resolve active_url (legacy
behaviour, e.g. direct callers/tests).
Returns:
Final job status with output files
@@ -398,18 +754,46 @@ class EncodingService:
start_time = asyncio.get_event_loop().time()
last_progress = 0
consecutive_failures = 0
# Set to True after the first successful poll. Once we've seen the job,
# a later 404 means the worker LOST it (restart wiped in-memory state),
# not that it never existed — that is unrecoverable for this job id, so
# we resubmit rather than burn the transient-blip tolerance.
job_seen = False
# Set once the job is actually "running". The per-run `timeout` only
# counts from here; time spent "pending" in the worker's serialized
# heavy queue counts against `queue_timeout` instead.
run_started_at: Optional[float] = None
while True:
elapsed = asyncio.get_event_loop().time() - start_time
if elapsed > timeout:
raise TimeoutError(f"Encoding job {job_id} timed out after {timeout}s")
now = asyncio.get_event_loop().time()
if run_started_at is not None:
if now - run_started_at > timeout:
raise TimeoutError(f"Encoding job {job_id} timed out after {timeout}s")
elif now - start_time > queue_timeout:
raise TimeoutError(
f"Encoding job {job_id} stuck in worker queue longer than {queue_timeout}s"
)
try:
status = await self.get_job_status(job_id)
status = await self.get_job_status(job_id, worker_url=worker_url)
# Reset failure counter on successful poll
consecutive_failures = 0
except (aiohttp.ClientConnectorError, aiohttp.ServerDisconnectedError,
asyncio.TimeoutError, RuntimeError) as e:
# A 404 *after* we've already seen the job = the worker lost it
# (OOM/deploy restart wiped its in-memory registry). Resubmitting
# the same id can never recover it, so surface a distinct signal
# immediately instead of polling 4 more times and mislabelling it
# "lost contact" (which callers treat as unrecoverable).
if job_seen and isinstance(e, EncodingJobNotFoundError):
logger.warning(
f"[job:{job_id}] Worker no longer has this job after previously "
f"reporting it — treating as lost (worker restart): {e}"
)
raise EncodingJobLostError(
f"Encoding job {job_id} was lost by the worker (restarted mid-run)",
job_id=job_id,
) from e
consecutive_failures += 1
if consecutive_failures >= MAX_CONSECUTIVE_POLL_FAILURES:
logger.error(
@@ -434,12 +818,19 @@ class EncodingService:
logger.error(f"[job:{job_id}] Unexpected status type: {type(status)}")
status = {}
job_seen = True
job_status = status.get("status", "unknown")
progress = status.get("progress", 0)
if run_started_at is None and (job_status == "running" or progress):
run_started_at = now
# Report progress
if progress != last_progress:
logger.info(f"[job:{job_id}] Encoding progress: {progress}%")
queue_position = status.get("queue_position")
if job_status == "pending" and queue_position:
logger.info(f"[job:{job_id}] Queued on worker (position {queue_position})")
else:
logger.info(f"[job:{job_id}] Encoding progress: {progress}%")
last_progress = progress
if progress_callback:
try:
@@ -448,11 +839,21 @@ class EncodingService:
logger.warning(f"Progress callback failed: {e}")
if job_status == "complete":
logger.info(f"[job:{job_id}] GCE encoding complete in {elapsed:.1f}s")
logger.info(f"[job:{job_id}] GCE encoding complete in {now - start_time:.1f}s")
return status
if job_status == "failed":
error = status.get("error", "Unknown error")
# A restart-marked failure is recoverable by resubmission, same
# as a mid-run vanish — surface the typed signal so callers retry.
if status.get("restart_failure_code") == ENCODING_RESTART_FAILURE_CODE:
logger.warning(
f"[job:{job_id}] Worker marked job failed after a restart — treating as lost: {error}"
)
raise EncodingJobLostError(
f"Encoding job {job_id} was lost by the worker (restarted mid-run)",
job_id=job_id,
)
raise RuntimeError(f"Encoding job {job_id} failed: {error}")
await asyncio.sleep(poll_interval)
@@ -468,7 +869,10 @@ class EncodingService:
"""
Submit encoding job and wait for completion.
This is a convenience method that combines submit + wait.
This is a convenience method that combines submit + wait. The
submission is bounded by a per-URL semaphore so concurrent renders
from the same Cloud Run instance can't overwhelm a single worker
VM (see `_submission_slot`).
Args:
job_id: Unique job identifier
@@ -482,23 +886,36 @@ class EncodingService:
"""
config = encoding_config or {"formats": ["mp4_4k", "mp4_720p"]}
# Submit the job
submit_result = await self.submit_encoding_job(job_id, input_gcs_path, output_gcs_path, config)
# Resolve URL up front so the semaphore is keyed by the actual
# target VM (matters when capacity fallback is active — see
# _submission_slot for the URL-change semantics).
target_url = self._get_worker_url()
# If cached, return immediately — encoding already done
submit_status = submit_result.get("status")
if submit_status == "cached":
logger.info(f"[job:{job_id}] Encoding already cached, returning immediately")
return {"status": "complete", "output_files": submit_result.get("output_files")}
async with self._submission_slot(target_url, job_id):
# Submit the job
submit_result = await self.submit_encoding_job(
job_id, input_gcs_path, output_gcs_path, config,
)
# If in_progress, another request is encoding it — just wait for that
if submit_status == "in_progress":
logger.info(f"[job:{job_id}] Encoding already in progress, joining poll")
# If cached, return immediately — encoding already done
submit_status = submit_result.get("status")
if submit_status == "cached":
logger.info(f"[job:{job_id}] Encoding already cached, returning immediately")
return {"status": "complete", "output_files": submit_result.get("output_files")}
# Wait for completion
return await self.wait_for_completion(
job_id, progress_callback=progress_callback
)
# If in_progress, another request is encoding it — just wait for that
if submit_status == "in_progress":
logger.info(f"[job:{job_id}] Encoding already in progress, joining poll")
# Pin polls to the worker the job landed on (see render_video_on_gce).
pinned_url = self._get_worker_url()
# Wait for completion (still holding the slot — the worker is
# actually doing CPU work for `job_id` until poll returns
# complete/failed).
return await self.wait_for_completion(
job_id, progress_callback=progress_callback, worker_url=pinned_url
)
async def submit_preview_encoding_job(
self,
@@ -533,7 +950,8 @@ class EncodingService:
if not self.is_configured:
raise RuntimeError("Encoding service not configured")
url = f"{self._get_worker_url()}/encode-preview"
path = "/encode-preview"
url = f"{self._get_worker_url()}{path}"
headers = {"X-API-Key": self._api_key, "Content-Type": "application/json"}
payload = {
"job_id": job_id,
@@ -556,6 +974,7 @@ class EncodingService:
json_payload=payload,
timeout=30.0,
job_id=job_id,
path=path,
)
if resp["status"] == 401:
@@ -620,11 +1039,19 @@ class EncodingService:
if submit_status == "in_progress":
logger.info(f"[job:{job_id}] Preview encoding already in progress, waiting")
# Wait for completion with shorter timeout
# Pin polls to the worker the job landed on (see render_video_on_gce).
pinned_url = self._get_worker_url()
# Wait for completion with a short timeout. Previews are interactive
# (a user is waiting in the review UI), so cap the *total* wait at the
# same short bound — don't let a queued preview sit for the long default
# queue_timeout before its per-run timeout even starts.
return await self.wait_for_completion(
job_id=job_id,
poll_interval=poll_interval,
timeout=timeout,
worker_url=pinned_url,
queue_timeout=timeout,
)
async def submit_render_video_job(
@@ -651,7 +1078,8 @@ class EncodingService:
if not self.is_configured:
raise RuntimeError("Encoding service not configured")
url = f"{self._get_worker_url()}/render-video"
path = "/render-video"
url = f"{self._get_worker_url()}{path}"
headers = {"X-API-Key": self._api_key, "Content-Type": "application/json"}
payload = {"job_id": job_id, **render_config}
@@ -664,6 +1092,7 @@ class EncodingService:
json_payload=payload,
timeout=30.0,
job_id=job_id,
path=path,
)
if resp["status"] == 401:
@@ -705,7 +1134,10 @@ class EncodingService:
"""
Submit render-video job and wait for completion.
This is a convenience method that combines submit + wait.
This is a convenience method that combines submit + wait. The
submission is bounded by a per-URL semaphore so concurrent renders
from the same Cloud Run instance can't overwhelm a single worker
VM (see `_submission_slot`).
Args:
job_id: Unique job identifier
@@ -715,27 +1147,43 @@ class EncodingService:
Returns:
Final job status with output files and metadata
"""
# Submit the job
submit_result = await self.submit_render_video_job(job_id, render_config)
# Resolve URL up front so the semaphore is keyed by the actual
# target VM. If capacity fallback later swaps active_url, the slot
# accounting is slightly off for that operation but the new
# submissions land on the right counter.
target_url = self._get_worker_url()
# If cached, return immediately — rendering already done
submit_status = submit_result.get("status")
if submit_status == "cached":
logger.info(f"[job:{job_id}] Render-video already cached, returning immediately")
return {
"status": "complete",
"output_files": submit_result.get("output_files"),
"metadata": submit_result.get("metadata"),
}
async with self._submission_slot(target_url, job_id):
# Submit the job
submit_result = await self.submit_render_video_job(job_id, render_config)
# If in_progress, another request is rendering it — just wait for that
if submit_status == "in_progress":
logger.info(f"[job:{job_id}] Render-video already in progress, joining poll")
# If cached, return immediately — rendering already done
submit_status = submit_result.get("status")
if submit_status == "cached":
logger.info(f"[job:{job_id}] Render-video already cached, returning immediately")
return {
"status": "complete",
"output_files": submit_result.get("output_files"),
"metadata": submit_result.get("metadata"),
}
# Wait for completion
return await self.wait_for_completion(
job_id, progress_callback=progress_callback
)
# If in_progress, another request is rendering it — just wait for that
if submit_status == "in_progress":
logger.info(f"[job:{job_id}] Render-video already in progress, joining poll")
# Pin status polls to the worker the job actually landed on. Resolving
# AFTER submit captures a capacity-fallback re-route (warmup invalidates
# the URL cache) while being BEFORE any later blue-green deploy swap —
# so the poll follows the job, not the floating active_url primary
# pointer (incident 2026-06-16, job d3af33ae).
pinned_url = self._get_worker_url()
# Wait for completion (still holding the slot — the worker is
# actively rendering for `job_id` until poll returns
# complete/failed).
return await self.wait_for_completion(
job_id, progress_callback=progress_callback, worker_url=pinned_url
)
async def health_check(self) -> Dict[str, Any]:
"""
+417 -19
View File
@@ -27,17 +27,57 @@ Usage:
import asyncio
import logging
from dataclasses import dataclass
import time
from dataclasses import dataclass, field
from datetime import datetime, UTC
from typing import Optional
from typing import Any, Optional
import aiohttp
from google.cloud import firestore
from backend.services.encoding_errors import (
EncodingWorkerCapacityError,
EncodingWorkerStartError,
classify_gce_error,
)
logger = logging.getLogger(__name__)
# How long to wait for a compute.instances.start operation to settle. The GCE
# operation itself is fast (1-2s) — we just need to know whether it succeeded
# 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
@@ -58,6 +98,19 @@ class EncodingWorkerConfig:
last_activity_at: Optional[str]
deploy_in_progress: bool
deploy_in_progress_since: Optional[str]
# Optional capacity-fallback override: when ensure_any_running falls back
# to a non-primary VM (e.g. due to ZONE_RESOURCE_POOL_EXHAUSTED), these
# fields point at the active fallback so requests target the right VM.
# Cleared when the primary becomes healthy again.
active_override_vm: Optional[str] = None
active_override_ip: Optional[str] = None
active_override_zone: Optional[str] = None
active_override_set_at: Optional[str] = None
# Availability-awareness state: {"<machine_type>@<zone>": last_stockout_iso}.
# Written when a candidate start hits a capacity/stockout error, read by the
# shared preference logic to demote recently-exhausted types. See
# backend/services/encoding_worker_preference.py.
capacity_state: dict = field(default_factory=dict)
@property
def primary_url(self) -> str:
@@ -67,6 +120,49 @@ class EncodingWorkerConfig:
def secondary_url(self) -> str:
return f"http://{self.secondary_ip}:{ENCODING_WORKER_PORT}"
@property
def active_url(self) -> str:
"""URL the encoding service should target right now.
Returns the capacity-fallback override if set, otherwise the primary
URL. The override mechanism lets us route around a zone that's
temporarily out of c4d-highcpu-32 capacity without rewriting the
blue-green primary/secondary tracking.
"""
if self.active_override_ip:
return f"http://{self.active_override_ip}:{ENCODING_WORKER_PORT}"
return self.primary_url
@dataclass
class EncodingWorkerCandidate:
"""A VM that ensure_any_running may try to start.
Carries everything needed to talk to the worker: VM name + zone (so the
GCE compute client targets the right zone) and external IP (so successful
starts can be persisted as the active URL override). ``machine_type`` (e.g.
"c4d-highcpu-32") lets the manager record/clear per-(type,zone) capacity
state so the shared preference logic can demote a stocked-out type.
"""
vm_name: str
zone: str
ip: str
machine_type: Optional[str] = None
# True iff this candidate is the blue-green PRIMARY VM. The override routing
# (set on fallback, clear on primary) keys off this flag, NOT list position —
# the preference logic may rank a fallback ahead of a stocked-out primary, so
# "first candidate" is no longer synonymous with "primary".
is_primary: bool = False
@property
def url(self) -> str:
return f"http://{self.ip}:{ENCODING_WORKER_PORT}"
def _cooldown_dict(self) -> dict:
"""Dict view for the shared preference helpers (cooldown_key)."""
return {"vm": self.vm_name, "zone": self.zone, "machine_type": self.machine_type}
class EncodingWorkerManager:
"""Manages blue-green encoding worker VMs via Firestore config and Compute API."""
@@ -107,6 +203,11 @@ class EncodingWorkerManager:
last_activity_at=data.get("last_activity_at"),
deploy_in_progress=data.get("deploy_in_progress", False),
deploy_in_progress_since=data.get("deploy_in_progress_since"),
active_override_vm=data.get("active_override_vm"),
active_override_ip=data.get("active_override_ip"),
active_override_zone=data.get("active_override_zone"),
active_override_set_at=data.get("active_override_set_at"),
capacity_state=data.get("capacity_state") or {},
)
def update_activity(self) -> None:
@@ -164,55 +265,81 @@ class EncodingWorkerManager:
# VM lifecycle operations (Task 2)
# ------------------------------------------------------------------
def get_vm_status(self, vm_name: str) -> str:
"""Get the current status of a GCE VM (e.g. RUNNING, TERMINATED, STAGING)."""
def get_vm_status(self, vm_name: str, zone: Optional[str] = None) -> str:
"""Get the current status of a GCE VM (e.g. RUNNING, TERMINATED, STAGING).
Pass `zone` for fallback VMs that live in alternate zones.
"""
instance = self._compute.get(
project=self._project_id,
zone=self._zone,
zone=zone or self._zone,
instance=vm_name,
)
return instance.status
def start_vm(self, vm_name: str) -> None:
def start_vm(self, vm_name: str, zone: Optional[str] = None) -> None:
"""Start a VM if it is not already running or starting.
Fire-and-forget: returns immediately. Caller should poll get_vm_status
if they need to wait for the VM to be fully RUNNING.
Waits for the start operation to complete and raises a typed error if
GCE rejects the request (e.g. ZONE_RESOURCE_POOL_EXHAUSTED). Caller
should still poll get_vm_status / wait_for_worker_ready before
dispatching work — operation success only means GCE accepted the start,
not that the VM has finished booting.
Args:
vm_name: VM to start.
zone: Override the manager's default zone. Required when starting
capacity-fallback VMs in alternate zones.
Raises:
EncodingWorkerCapacityError: zone is out of capacity for the
machine type. Retry from a different zone or after a wait.
EncodingWorkerStartError: any other start failure.
"""
status = self.get_vm_status(vm_name)
target_zone = zone or self._zone
status = self.get_vm_status(vm_name, zone=target_zone)
if status in ("RUNNING", "STAGING"):
logger.info("VM %s is already %s, skipping start", vm_name, status)
return
logger.info("Starting VM %s (current status: %s)", vm_name, status)
self._compute.start(
logger.info("Starting VM %s in zone %s (current status: %s)", vm_name, target_zone, status)
operation = self._compute.start(
project=self._project_id,
zone=self._zone,
zone=target_zone,
instance=vm_name,
)
self._wait_for_compute_operation(operation, vm_name=vm_name, zone=target_zone)
def stop_vm(self, vm_name: str) -> None:
def stop_vm(self, vm_name: str, zone: Optional[str] = None) -> None:
"""Stop a VM if it is not already stopped or stopping."""
status = self.get_vm_status(vm_name)
target_zone = zone or self._zone
status = self.get_vm_status(vm_name, zone=target_zone)
if status in ("TERMINATED", "STOPPING"):
logger.info("VM %s is already %s, skipping stop", vm_name, status)
return
logger.info("Stopping VM %s (current status: %s)", vm_name, status)
logger.info("Stopping VM %s in zone %s (current status: %s)", vm_name, target_zone, status)
self._compute.stop(
project=self._project_id,
zone=self._zone,
zone=target_zone,
instance=vm_name,
)
def ensure_primary_running(self) -> dict:
"""Ensure the primary encoding worker VM is running.
Reads config, starts primary VM if stopped, and updates activity timestamp.
Reads config, starts primary VM if stopped, and updates activity
timestamp. Waits for the start operation to settle so that capacity
errors surface immediately instead of being hidden behind a 120s
readiness wait.
Returns:
dict with keys:
- started (bool): True if VM was started, False if already running
- vm_name (str): Name of the primary VM
- primary_url (str): URL of the primary encoding worker
Raises:
EncodingWorkerCapacityError: zone is exhausted for the machine type.
EncodingWorkerStartError: any other start failure.
"""
config = self.get_config()
vm_name = config.primary_vm
@@ -222,11 +349,12 @@ class EncodingWorkerManager:
if status not in ("RUNNING", "STAGING"):
logger.info("Primary VM %s is %s, starting it", vm_name, status)
self._compute.start(
operation = self._compute.start(
project=self._project_id,
zone=self._zone,
instance=vm_name,
)
self._wait_for_compute_operation(operation, vm_name=vm_name, zone=self._zone)
started = True
else:
logger.info("Primary VM %s is already %s", vm_name, status)
@@ -236,9 +364,273 @@ class EncodingWorkerManager:
return {
"started": started,
"vm_name": vm_name,
"zone": self._zone,
"primary_url": config.primary_url,
}
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
capacity error (ZONE_RESOURCE_POOL_EXHAUSTED, etc.) on candidate N
triggers a try of candidate N+1. Other start failures abort the
whole call.
On fallback success (a non-first candidate started), persists the
fallback's URL as `active_override_*` in Firestore so subsequent
encoding requests target the right VM. The first candidate (the
primary) succeeding clears any stale override.
Args:
candidates: List of EncodingWorkerCandidate, ordered by preference.
Typically [primary, secondary, *fallbacks_in_alt_zones].
Returns:
dict {started, vm_name, zone, primary_url, fell_back}
fell_back is True iff the chosen VM is not the first candidate.
Raises:
EncodingWorkerCapacityError: all candidates rejected with
capacity errors.
EncodingWorkerStartError: any non-capacity start failure.
ValueError: empty candidate list.
"""
if not candidates:
raise ValueError("ensure_any_running requires at least one candidate")
# Track the last error so we can raise something representative if
# every candidate fails. Capacity errors are preferred (they're more
# actionable for the user-facing message) but generic start errors
# also trigger fallback — observed failure modes include 503
# SERVICE_UNAVAILABLE from the GCE backend, which behaves like
# 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
# When the caller marks a primary explicitly, route override off that flag;
# otherwise preserve the legacy "index 0 is the primary" behaviour.
has_explicit_primary = any(getattr(c, "is_primary", False) for c in candidates)
for index, candidate in enumerate(candidates):
try:
status = self.get_vm_status(candidate.vm_name, zone=candidate.zone)
started = False
if status not in ("RUNNING", "STAGING"):
logger.info(
"Trying candidate %d/%d: VM %s in %s (status %s)",
index + 1, len(candidates), candidate.vm_name,
candidate.zone, status,
)
self.start_vm(candidate.vm_name, zone=candidate.zone)
started = True
self.update_activity()
# A clean start means this type/zone has capacity again — clear
# any stale cooldown so the preference logic stops demoting it.
self._clear_stockout(candidate)
# "Fell back" = we did NOT land on the primary VM. Keyed off the
# explicit flag when present (ordering can rank a fallback ahead of
# a stocked-out primary, so it may not be index 0); otherwise the
# legacy position-based rule.
is_primary = candidate.is_primary if has_explicit_primary else (index == 0)
fell_back = not is_primary
if fell_back:
self._set_active_override(candidate)
else:
self._clear_active_override()
return {
"started": started,
"vm_name": candidate.vm_name,
"zone": candidate.zone,
"primary_url": candidate.url,
"fell_back": fell_back,
}
except EncodingWorkerCapacityError as cap_err:
logger.warning(
"Candidate %s in %s exhausted (%s), trying next candidate",
candidate.vm_name, candidate.zone, cap_err.code,
)
# Record the stockout so the shared preference logic demotes this
# (type,zone) for a cooldown window instead of re-probing it first.
self._record_stockout(candidate)
last_capacity_error = cap_err
last_start_error = cap_err
continue
except EncodingWorkerStartError as start_err:
# Other start failures (e.g. 503 SERVICE_UNAVAILABLE from the
# GCE backend) are also transient — try the next candidate
# rather than giving up. If all candidates fail with these
# generic errors and no candidate hit a capacity error, we
# surface the last generic error.
logger.warning(
"Candidate %s in %s start failed (%s), trying next candidate",
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. 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
def _record_stockout(self, candidate) -> None:
"""Mark a candidate's (machine_type, zone) as recently stocked out.
Merges a single key into the ``capacity_state`` map so concurrent starts
don't clobber each other's entries. Best-effort — a Firestore hiccup here
must never break the start path, so failures are logged and swallowed.
"""
from backend.services.encoding_worker_preference import cooldown_key
key = cooldown_key(candidate._cooldown_dict())
if not key:
return
try:
self._doc_ref().set(
{"capacity_state": {key: datetime.now(UTC).isoformat()}}, merge=True
)
logger.info("Recorded stockout for %s", key)
except Exception as e: # noqa: BLE001 — never fail the start path on telemetry
logger.warning("Could not record stockout for %s: %s", key, e)
def _clear_stockout(self, candidate) -> None:
"""Clear a candidate's (machine_type, zone) cooldown after a clean start.
Sets the key to None (parsed as "not stocked out") via a merge so other
keys are untouched. Best-effort, like _record_stockout.
"""
from backend.services.encoding_worker_preference import cooldown_key
key = cooldown_key(candidate._cooldown_dict())
if not key:
return
try:
self._doc_ref().set({"capacity_state": {key: None}}, merge=True)
except Exception as e: # noqa: BLE001
logger.warning("Could not clear stockout for %s: %s", key, e)
def _set_active_override(self, candidate) -> None:
"""Record a fallback VM as the active worker URL in Firestore."""
now = datetime.now(UTC).isoformat()
self._doc_ref().update({
"active_override_vm": candidate.vm_name,
"active_override_ip": candidate.ip,
"active_override_zone": candidate.zone,
"active_override_set_at": now,
})
logger.info(
"Set active_override to %s in %s (capacity fallback)",
candidate.vm_name, candidate.zone,
)
def _clear_active_override(self) -> None:
"""Clear active_override fields (primary is healthy again).
Idempotent: safe to call when no override is currently set.
"""
snapshot = self._doc_ref().get()
if not snapshot.exists:
return
data = snapshot.to_dict() or {}
if not data.get("active_override_vm"):
return # nothing to clear
self._doc_ref().update({
"active_override_vm": None,
"active_override_ip": None,
"active_override_zone": None,
"active_override_set_at": None,
})
logger.info("Cleared active_override (primary is healthy again)")
# ------------------------------------------------------------------
# Compute operation helpers
# ------------------------------------------------------------------
def _wait_for_compute_operation(
self,
operation: Any,
*,
vm_name: str,
zone: str,
timeout: float = START_OPERATION_TIMEOUT_SECONDS,
) -> None:
"""Block on a compute v1 ExtendedOperation; raise typed exceptions on error.
google.cloud.compute_v1 returns an ExtendedOperation. Calling .result()
blocks until done; successful operations return None, failures raise.
Some failure modes set .error_code/.error_message on the operation
without raising (depending on SDK version), so we check both paths.
"""
result_exc: Optional[BaseException] = None
try:
if hasattr(operation, "result"):
operation.result(timeout=timeout)
except Exception as e: # noqa: BLE001 — we re-raise as a typed error below
result_exc = e
code = (getattr(operation, "error_code", "") or "")
message = (getattr(operation, "error_message", "") or "")
if not code and result_exc is None:
return # Success.
if not code and result_exc is not None:
# Operation raised but did not set error_code (e.g. timeout, transport
# failure). Fall back to the raised exception text.
raise EncodingWorkerStartError(
f"VM {vm_name} start operation failed in {zone}: {result_exc}",
vm_name=vm_name,
zone=zone,
code="",
) from result_exc
# error_code populated — classify it.
raise classify_gce_error(code, message, vm_name=vm_name, zone=zone) from result_exc
# ------------------------------------------------------------------
# Task 3: cold-start readiness gate
# ------------------------------------------------------------------
@@ -248,6 +640,7 @@ class EncodingWorkerManager:
vm_name: str,
health_url: str,
*,
zone: Optional[str] = None,
vm_timeout: float = 120.0,
health_timeout: float = 180.0,
poll_interval: float = 5.0,
@@ -268,6 +661,11 @@ class EncodingWorkerManager:
vm_name: Name of the GCE VM to poll.
health_url: Full URL of the worker /health endpoint
(e.g. "http://10.0.0.1:8080/health").
zone: Override the manager's default zone. Required when waiting on
capacity-fallback VMs that live in alternate zones — without
this override the status poll hits the wrong zone and 404s
("instance not found"), the readiness wait gives up, and the
next request hits a VM that hasn't finished booting.
vm_timeout: Max seconds to wait for VM RUNNING.
health_timeout: Max seconds to wait for /health 200.
poll_interval: Seconds between polls in either phase.
@@ -281,7 +679,7 @@ class EncodingWorkerManager:
last_status = None
last_log = 0.0
while loop.time() < deadline:
last_status = self.get_vm_status(vm_name)
last_status = self.get_vm_status(vm_name, zone=zone)
if last_status == "RUNNING":
logger.info("VM %s reached RUNNING", vm_name)
break
@@ -0,0 +1,178 @@
"""Shared, pure preference logic for encoding-worker candidate ordering.
This is the SINGLE SOURCE OF TRUTH for how encode-worker VM candidates are ranked,
used by BOTH:
* runtime worker selection —
``backend/services/encoding_service._build_worker_candidates`` →
``encoding_worker_manager.ensure_any_running``
* deploy green (staging) selection —
``infrastructure/encoding-worker/deploy_promote.select_green_candidates``
Keeping the ordering in one place stops the two call-sites from drifting (they
previously used different ad-hoc heuristics: runtime = secret order, deploy =
"n2 before c4d").
Design:
* **Fastest-first base order.** Candidates sort by ``SPEED_RANK`` (lower =
faster), so the fastest available type (c4d) is always preferred when it can
start — the whole reason c4d was chosen. No behaviour change on a healthy day.
* **Availability-aware cooldown.** A type that recently failed to start with a
capacity/stockout error (recorded in Firestore ``capacity_state``) is
*demoted to the back* for ``COOLDOWN_SECONDS`` — long enough to stop paying
the ~2-min-per-attempt probe cost on a known-dead type, short enough to
re-probe and snap back to the faster type the moment capacity returns. It is
demoted, never dropped, so the pool always stays fully available.
This module is intentionally **dependency-free (stdlib only)** so that
``deploy_promote`` — which is loaded by path in CI with no backend package deps —
can import it without pulling the heavy backend tree.
"""
from __future__ import annotations
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional
# Lower rank = faster = preferred. Seeded from CPU architecture; refine with the
# measured medians from infrastructure/encoding-worker/benchmark_types.py.
# c4d AMD EPYC Turin (Zen5) — current primary, fastest
# c4 Intel Emerald Rapids — newest Intel perf tier
# n4d AMD (Titanium) — flexible/deep AMD
# c2d AMD Milan (Zen3) — mature, deep pool
# n2d AMD Rome/Milan — deep pool (32 GB floor)
# n2 Intel Cascade/Ice Lake — current fallback (32 GB floor)
SPEED_RANK: Dict[str, int] = {
"c4d-highcpu-32": 10,
"c4-highcpu-32": 20,
"n4d-highcpu-32": 30,
"c2d-highcpu-32": 50,
"n2d-highcpu-32": 60,
"n2-highcpu-32": 70,
}
# Rank for a candidate whose machine type is unknown and cannot be inferred:
# treat as slowest-but-usable so it sorts LAST without ever being dropped.
UNKNOWN_RANK = 1000
# How long a type that just stocked out is demoted before it is re-probed.
COOLDOWN_SECONDS = 900 # 15 minutes
# Machine type of the blue-green primary/secondary pair (encoding-worker-a/-b).
# They are always c4d; used when a candidate carries no explicit machine_type.
PRIMARY_MACHINE_TYPE = "c4d-highcpu-32"
# vm-name substring → machine type, for backward-compat inference when a fallback
# entry predates the machine_type field. Checked in order — longer / more-specific
# family tokens FIRST so "n2d" is not shadowed by "n2", nor "c4d" by "c4".
_NAME_TOKEN_TO_TYPE = (
("c4d", "c4d-highcpu-32"),
("n4d", "n4d-highcpu-32"),
("n2d", "n2d-highcpu-32"),
("c2d", "c2d-highcpu-32"),
("c4", "c4-highcpu-32"),
("n2", "n2-highcpu-32"),
)
def _candidate_name(candidate: Dict[str, Any]) -> str:
"""VM name from either dict shape ({"vm"} for deploy, {"vm_name"} for runtime)."""
return (candidate.get("vm") or candidate.get("vm_name") or "")
def infer_machine_type(candidate: Dict[str, Any]) -> Optional[str]:
"""Best-effort machine type: explicit ``machine_type`` field, else vm-name token.
Fallback secret entries created before the ``machine_type`` field carry only
vm/zone/ip; the VM-name family token (…-fallback-n2c, …-fallback-c4a) is the
only hint. Returns None when nothing matches (caller treats as UNKNOWN_RANK).
"""
explicit = candidate.get("machine_type")
if explicit:
return explicit
name = _candidate_name(candidate).lower()
for token, mtype in _NAME_TOKEN_TO_TYPE:
if token in name:
return mtype
return None
def _speed_rank(candidate: Dict[str, Any]) -> int:
return SPEED_RANK.get(infer_machine_type(candidate), UNKNOWN_RANK)
def cooldown_key(candidate: Dict[str, Any]) -> Optional[str]:
"""Firestore ``capacity_state`` key for a candidate: ``"<machine_type>@<zone>"``.
Zone-scoped because a stockout is per (machine family × zone). Returns None
when the machine type can't be determined (no cooldown tracking possible).
NOTE: keys deliberately avoid ``.`` so they are safe as Firestore map keys.
"""
mtype = infer_machine_type(candidate)
if not mtype:
return None
zone = candidate.get("zone")
return f"{mtype}@{zone}" if zone else mtype
def _parse_iso(value: Any) -> Optional[datetime]:
if not value:
return None
try:
dt = datetime.fromisoformat(value)
except (ValueError, TypeError):
return None
if dt.tzinfo is None: # tolerate naive timestamps — assume UTC
dt = dt.replace(tzinfo=timezone.utc)
return dt
def _recently_stocked_out(
candidate: Dict[str, Any],
capacity_state: Optional[Dict[str, Any]],
now: datetime,
cooldown_seconds: float,
) -> bool:
"""True if this candidate's (type@zone) — or its coarser type-only key — is in cooldown."""
if not capacity_state:
return False
key = cooldown_key(candidate)
if not key:
return False
ts = _parse_iso(capacity_state.get(key))
if ts is None:
# Fall back to a type-only signal (a coarser "this family is short").
mtype = infer_machine_type(candidate)
if mtype:
ts = _parse_iso(capacity_state.get(mtype))
if ts is None:
return False
return (now - ts).total_seconds() < cooldown_seconds
def ordered_candidates(
pool: List[Dict[str, Any]],
capacity_state: Optional[Dict[str, Any]] = None,
now: Optional[datetime] = None,
cooldown_seconds: float = COOLDOWN_SECONDS,
) -> List[Dict[str, Any]]:
"""Rank ``pool`` fastest-first, demoting recently-stocked-out types to the back.
Args:
pool: candidate dicts, each ``{vm|vm_name, zone, ip, machine_type?, kind?}``.
Objects are returned as-is (not copied), only reordered — so callers can
round-trip their own richer objects through a dict view.
capacity_state: Firestore map ``{"<type>@<zone>"|"<type>": last_stockout_iso}``.
Absent/empty ⇒ pure fastest-first order (today's behaviour).
now: current UTC time (injectable for tests); defaults to ``datetime.now(UTC)``.
cooldown_seconds: demotion window; defaults to ``COOLDOWN_SECONDS``.
The speed sort is STABLE, so equal-rank candidates keep their input order —
callers express a secondary preference (e.g. zone spread) purely via input
ordering. The hot/cold partition is likewise stable within each group.
"""
if now is None:
now = datetime.now(timezone.utc)
ranked = sorted(pool, key=_speed_rank) # stable: fastest first
hot = [c for c in ranked if not _recently_stocked_out(c, capacity_state, now, cooldown_seconds)]
cold = [c for c in ranked if _recently_stocked_out(c, capacity_state, now, cooldown_seconds)]
return hot + cold
@@ -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).
+30 -3
View File
@@ -3,7 +3,7 @@ Firestore database operations for job management.
"""
import logging
from typing import Optional, Dict, Any, List
from datetime import datetime
from datetime import datetime, timezone
from google.cloud import firestore
from google.cloud.firestore_v1 import FieldFilter
@@ -87,7 +87,9 @@ class FirestoreService:
# Create timeline event
timeline_event = TimelineEvent(
status=status.value,
timestamp=datetime.utcnow().isoformat(),
# Timezone-aware UTC so the serialized ISO string carries a
# "+00:00" offset (see job_manager.create_job for rationale).
timestamp=datetime.now(timezone.utc).isoformat(),
progress=progress,
message=message,
metadata=timeline_metadata,
@@ -177,17 +179,42 @@ class FirestoreService:
except Exception as e:
logger.error(f"Error listing jobs: {e}")
raise
def list_jobs_by_batch_id(self, batch_id: str, limit: int = 200) -> List[Job]:
"""List all jobs belonging to a Bulk Mode batch (state_data.batch_id == batch_id).
Single-field equality, so no composite index is required.
"""
try:
query = (
self.db.collection(self.collection)
.where(filter=FieldFilter('state_data.batch_id', '==', batch_id))
.limit(limit)
)
return [Job(**doc.to_dict()) for doc in query.stream()]
except Exception as e:
logger.error(f"Error listing jobs for batch {batch_id}: {e}")
raise
# Fields needed by the dashboard summary view
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',
'state_data.audio_progress', 'state_data.lyrics_progress',
'state_data.audio_complete', 'state_data.lyrics_complete',
'state_data.backing_vocals_analysis', 'state_data.visibility_change_in_progress',
'state_data.render_pending_capacity',
'state_data.cloud_run_retry_pending',
'state_data.credits_charged',
'state_data.pending_additional_credits',
'state_data.duration_actual_seconds',
'state_data.duration_confirm_reason',
'state_data.batch_id',
'state_data.bulk_auto_selected',
'file_urls.finals', 'file_urls.videos', 'file_urls.packages',
'processing_metadata',
]
+2 -1
View File
@@ -680,7 +680,8 @@ class FlacfetchClient:
Returns:
Dict with keys: available, video_id, title, error,
is_geo_restricted, is_age_restricted, is_private, is_removed
is_geo_restricted, is_age_restricted, is_private, is_removed,
is_bot_blocked
Raises:
FlacfetchServiceError: On request failure
+482 -52
View File
@@ -1,5 +1,4 @@
import asyncio
import glob as glob_module
import hashlib
import json
import logging
@@ -9,8 +8,10 @@ import shutil
import subprocess
import sys
import tempfile
import threading
import uuid
from concurrent.futures import ThreadPoolExecutor
from contextlib import asynccontextmanager
from pathlib import Path
from typing import Optional
@@ -19,10 +20,91 @@ from google.cloud import storage
from packaging.version import Version
from pydantic import BaseModel
from .persistence import JobStatePersister
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = FastAPI(title="Encoding Worker", version="1.0.0")
# Job tracking — process-local dict, mirrored to Firestore via `persister`
# so polls after a worker restart return the *last known* status instead of
# 404. Hot path stays in-memory; persistence is best-effort.
jobs: dict[str, dict] = {}
# Two execution lanes with very different memory profiles:
#
# heavy_executor — full renders (`run_render_video`) and final encodes
# (`run_encoding`). Each of these spawns an ffmpeg that already saturates
# every core, so running two in parallel gains no throughput but doubles
# peak RAM (a single 4K encode can use ~18 GB). Three concurrent encodes
# OOM-killed the 32 GB n2 fallback worker on 2026-08-15, which restarted
# the service and lost every in-flight job. Default to ONE heavy job at a
# time so the worker is OOM-proof on any machine type; the rest queue as
# `status="pending"` (surfaced via /health `queue_length` and /status
# `queue_position`). Override with ENCODING_HEAVY_CONCURRENCY only on
# boxes with headroom to spare.
#
# light_executor — wheel installs (`ensure_latest_wheel`) and interactive
# review previews (`run_preview_encoding`). These are small/fast and
# latency-sensitive, so they get their own lane and never wait behind a
# multi-minute encode.
def _heavy_concurrency() -> int:
"""Parse ENCODING_HEAVY_CONCURRENCY, clamped to a sane [1, 4] range.
A malformed/zero/negative value must never crash the worker at boot or
(via max_workers=0) wedge every encode — fall back to the OOM-safe default
of 1. The upper bound guards against an operator accidentally reintroducing
the concurrent-encode OOM on a small box.
"""
raw = os.environ.get("ENCODING_HEAVY_CONCURRENCY", "1")
try:
value = int(raw)
except (TypeError, ValueError):
logger.warning("Invalid ENCODING_HEAVY_CONCURRENCY=%r; defaulting to 1", raw)
return 1
if value < 1:
logger.warning("ENCODING_HEAVY_CONCURRENCY=%d < 1; clamping to 1", value)
return 1
if value > 4:
logger.warning("ENCODING_HEAVY_CONCURRENCY=%d > 4; clamping to 4", value)
return 4
return value
HEAVY_CONCURRENCY = _heavy_concurrency()
heavy_executor = ThreadPoolExecutor(max_workers=HEAVY_CONCURRENCY)
light_executor = ThreadPoolExecutor(max_workers=2)
# Persister is initialized lazily — see persistence.py — so import-time
# stays free of GCP creds. Tests can monkey-patch this attribute.
persister = JobStatePersister()
def _persist(job_id: str) -> None:
"""Mirror a job's current state to Firestore (best-effort, never raises)."""
state = jobs.get(job_id)
if state is not None:
persister.save(state)
@asynccontextmanager
async def lifespan(app: FastAPI):
# Startup: read back any in-progress jobs from Firestore. They were
# interrupted by the restart that brought us here — their work_dir is
# gone, so mark them failed with the restart code so polls return a
# clear failure instead of 404.
try:
marked = persister.mark_orphans_failed_on_startup(jobs)
if marked:
logger.warning(
"Marked %d orphaned encoding job(s) failed on startup", marked,
)
except Exception as exc:
logger.error("Encoding worker startup orphan-recovery failed: %r", exc)
yield
app = FastAPI(title="Encoding Worker", version="1.0.0", lifespan=lifespan)
# API key authentication
API_KEY = os.environ.get("ENCODING_API_KEY", "")
@@ -37,10 +119,6 @@ async def verify_api_key(x_api_key: str = Header(None)):
raise HTTPException(status_code=401, detail="Invalid API key")
return True
# Job tracking
jobs: dict[str, dict] = {}
executor = ThreadPoolExecutor(max_workers=4) # 4 parallel encoding jobs
# GCS client
storage_client = storage.Client()
@@ -85,6 +163,15 @@ class JobStatus(BaseModel):
error: Optional[str] = None
output_files: Optional[list[str]] = None
metadata: Optional[dict] = None
# Set when a job was interrupted by a worker-process restart (OOM, deploy,
# crash). Its work_dir is gone, so the client should resubmit rather than
# treat this as a permanent failure. See persistence.mark_orphans_failed_on_startup.
restart_failure_code: Optional[str] = None
# How many heavy jobs (renders/encodes) are ahead of this one in the
# serialized heavy lane (0 = running or next up). None for previews /
# terminal jobs. Lets the client wait through a deep queue without
# tripping the encode timeout.
queue_position: Optional[int] = None
def download_from_gcs(gcs_uri: str, local_path: Path):
@@ -213,6 +300,7 @@ def run_preview_encoding(job_id: str, work_dir: Path, request: "EncodePreviewReq
# Run FFmpeg encoding for preview video (480x270, fast settings)
jobs[job_id]["status"] = "running"
jobs[job_id]["progress"] = 10
_persist(job_id)
try:
# Download input files
@@ -309,6 +397,7 @@ def run_preview_encoding(job_id: str, work_dir: Path, request: "EncodePreviewReq
logger.error(f"Preview encoding failed: {e}")
jobs[job_id]["status"] = "failed"
jobs[job_id]["error"] = str(e)
_persist(job_id)
raise
@@ -324,6 +413,7 @@ def run_render_video(job_id: str, work_dir: Path, request: "RenderVideoRequest")
"""
jobs[job_id]["status"] = "running"
jobs[job_id]["progress"] = 5
_persist(job_id)
try:
# Import from installed karaoke-gen wheel
@@ -490,68 +580,222 @@ def run_render_video(job_id: str, work_dir: Path, request: "RenderVideoRequest")
logger.error(error_msg)
jobs[job_id]["status"] = "failed"
jobs[job_id]["error"] = error_msg
_persist(job_id)
raise RuntimeError(error_msg) from e
except Exception as e:
logger.error(f"[job:{job_id}] Render video failed: {e}")
jobs[job_id]["status"] = "failed"
jobs[job_id]["error"] = str(e)
_persist(job_id)
raise
# Wheel install/verification tuning.
#
# On a freshly-provisioned worker the Packer image only pre-installs a handful
# of packages (fastapi/uvicorn/gcs/...) and boot installs the wheel with
# --no-deps, so the FIRST job's install here has to resolve the entire
# karaoke-gen dependency tree (torch, langchain, tenacity, ...). That can take
# well over 5 minutes and, if it times out or partially completes, leaves the
# environment importable-but-broken (e.g. "No module named 'tenacity'"). We
# therefore retry, and — critically — verify the import chain actually works
# before declaring success, since pip can return 0 while a dependency is still
# missing.
WHEEL_INSTALL_TIMEOUT = int(os.environ.get("WHEEL_INSTALL_TIMEOUT", "900"))
WHEEL_INSTALL_ATTEMPTS = int(os.environ.get("WHEEL_INSTALL_ATTEMPTS", "3"))
# Serialize wheel checks. ensure_latest_wheel() runs on the light executor
# (>1 thread) and is invoked at the start of every job, so without a lock two
# concurrent jobs race on the same /tmp wheel path (`gsutil cp` clobbers the
# file mid-copy) and the same venv (`pip install` runs twice at once) —
# corrupting each other so one job fails with "wheel/dependencies not ready"
# (incident 2026-08-15, job 374dec26, three jobs hitting a fresh fallback boot).
# The lock makes the first caller do the work while the rest wait, then take the
# already-verified fast path below.
_wheel_lock = threading.Lock()
# Version we've already downloaded+installed+verified in THIS process. Lets a
# job skip the whole download/install/verify when the environment is already
# current — the common case, since startup.sh installs the wheel at boot and
# only the first job after a new deploy actually needs to install.
_verified_wheel_version: Optional[str] = None
def _installed_karaoke_gen_version() -> Optional[str]:
'''Return the karaoke-gen version currently importable in this venv, or None.'''
try:
from importlib.metadata import version as _get_version
return _get_version("karaoke-gen")
except Exception:
return None
# Modules exercised by the render (OutputGenerator) and encode
# (LocalEncodingService) code paths. Importing these confirms the whole
# dependency tree they pull in — including transitive deps like tenacity — is
# actually present, not just that `pip install` exited 0.
_WHEEL_IMPORT_CHECK = (
"import tenacity; "
"from karaoke_gen.lyrics_transcriber.output.generator import OutputGenerator; "
"from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations; "
"from backend.services.local_encoding_service import LocalEncodingService"
)
def verify_wheel_imports():
'''Verify the karaoke-gen render/encode import chain is fully importable.
Runs in a subprocess so a broken/partial install surfaces as a clean
boolean instead of crashing (or half-importing into) the worker process.
Returns True if every module imports, False otherwise.
'''
try:
check = subprocess.run(
[sys.executable, "-c", _WHEEL_IMPORT_CHECK],
capture_output=True, text=True, timeout=180,
)
except subprocess.TimeoutExpired:
logger.warning("Wheel import verification timed out")
return False
if check.returncode != 0:
# Tail of stderr carries the actionable ModuleNotFoundError.
logger.warning(f"Wheel import verification failed: {check.stderr.strip()[-500:]}")
return False
return True
def ensure_latest_wheel():
'''Download and install latest karaoke-gen wheel from GCS.
'''Ensure the latest karaoke-gen wheel is installed & verified (thread-safe).
Called at the start of each job to enable hot code updates without restart.
In-progress jobs continue with their version, new jobs get latest code.
Serialized via `_wheel_lock` so concurrent jobs can't race on the shared
/tmp wheel path or venv; the first caller installs/verifies while the rest
wait and then hit the already-verified fast path.
'''
with _wheel_lock:
return _ensure_latest_wheel_locked()
def _ensure_latest_wheel_locked():
'''Download, install, and verify the latest karaoke-gen wheel from GCS.
MUST be called holding `_wheel_lock`. In-progress jobs continue with their
version, new jobs get latest code.
Retries the install and verifies the full import chain before returning, so
a transient/partial dependency install can't leave the worker running jobs
against a broken environment. Returns True only when the wheel is installed
AND its render/encode imports succeed.
'''
global _verified_wheel_version
try:
logger.info("Checking for latest karaoke-gen wheel in GCS...")
# Download latest wheel
result = subprocess.run(
["gsutil", "cp", "gs://karaoke-gen-storage-nomadkaraoke/wheels/karaoke_gen-*.whl", "/tmp/"],
capture_output=True, text=True, timeout=60
)
# Find the downloaded wheel (get the latest by version sorting)
wheels = glob_module.glob("/tmp/karaoke_gen-*.whl")
# Filter out karaoke_gen-current.whl (not a valid PEP 427 wheel name)
wheels = [w for w in wheels if '-current' not in w]
if not wheels:
logger.warning("No wheel found in GCS, using fallback encoding logic")
return False
# Sort to get latest version (by semantic version, not alphabetically)
# Sort helper: extract version from a wheel name/URI like
# karaoke_gen-0.116.1-py3-none-any.whl
def extract_version(wheel_path):
"""Extract version from wheel filename like karaoke_gen-0.116.1-py3-none-any.whl"""
match = re.search(r'karaoke_gen-([0-9.]+)-', wheel_path)
if match:
return Version(match.group(1))
return Version("0.0.0") # Fallback for unparseable filenames
wheels.sort(key=extract_version, reverse=True)
wheel_path = wheels[0]
logger.info(f"Installing wheel: {wheel_path}")
# Install (or upgrade) the wheel
# Use 5-minute timeout - first install at job start may need to resolve dependencies
# Subsequent installs are faster since dependencies are cached
install_result = subprocess.run(
[sys.executable, "-m", "pip", "install", "--upgrade", "--quiet", wheel_path],
capture_output=True, text=True, timeout=300
# List wheel names only (fast), then copy just the single latest one.
# NOTE: `gsutil cp gs://.../karaoke_gen-*.whl /tmp/` would download the
# ENTIRE wheels/ directory (hundreds of wheels, multiple GiB) on every
# job and blow the timeout on fresh workers — the historical cause of
# "no wheel found" / partial installs. Listing + single copy is ~2s.
ls_result = subprocess.run(
["gsutil", "ls", "gs://karaoke-gen-storage-nomadkaraoke/wheels/karaoke_gen-*.whl"],
capture_output=True, text=True, timeout=60
)
# Filter out karaoke_gen-current.whl (not a valid PEP 427 wheel name)
wheel_uris = [
line.strip() for line in ls_result.stdout.splitlines()
if line.strip() and '-current' not in line
]
if install_result.returncode != 0:
logger.warning(f"Wheel installation failed: {install_result.stderr}")
if not wheel_uris:
logger.warning("No versioned wheel found in GCS, using fallback encoding logic")
return False
logger.info(f"Successfully installed wheel: {wheel_path}")
return True
wheel_uris.sort(key=extract_version)
latest_uri = wheel_uris[-1]
latest_version = str(extract_version(latest_uri))
wheel_path = os.path.join("/tmp", latest_uri.rsplit("/", 1)[-1])
# Fast path: if the environment is already at the latest version, skip
# the download/install entirely. This is the common case (startup.sh
# installs the wheel at boot) and — together with `_wheel_lock` — is what
# stops concurrent jobs from re-downloading/re-installing and racing.
if _verified_wheel_version == latest_version:
# Already validated in this process — nothing to do.
return True
installed_version = _installed_karaoke_gen_version()
if installed_version == latest_version:
# Right version is present but not yet verified in this process.
# Confirm the import chain (cheap) rather than reinstalling; only
# fall through to a full reinstall if a prior install was partial.
if verify_wheel_imports():
_verified_wheel_version = latest_version
logger.info(f"karaoke-gen {latest_version} already installed and verified; skipping wheel install")
return True
logger.warning(
f"karaoke-gen {latest_version} present but import chain incomplete; reinstalling"
)
cp_result = subprocess.run(
["gsutil", "cp", latest_uri, wheel_path],
capture_output=True, text=True, timeout=120
)
if cp_result.returncode != 0:
logger.warning(f"Failed to download wheel {latest_uri}: {cp_result.stderr.strip()[-500:]}")
return False
# Install (with deps), then verify the import chain is complete. Retry a
# failed or partial install: pip is resumable, so a second pass fills in
# dependencies a timed-out first pass left missing (e.g. tenacity).
for attempt in range(1, WHEEL_INSTALL_ATTEMPTS + 1):
logger.info(f"Installing wheel (attempt {attempt}/{WHEEL_INSTALL_ATTEMPTS}): {wheel_path}")
try:
install_result = subprocess.run(
[sys.executable, "-m", "pip", "install", "--upgrade", "--quiet", wheel_path],
capture_output=True, text=True, timeout=WHEEL_INSTALL_TIMEOUT
)
except subprocess.TimeoutExpired:
logger.warning(
f"Wheel install timed out after {WHEEL_INSTALL_TIMEOUT}s "
f"(attempt {attempt}/{WHEEL_INSTALL_ATTEMPTS})"
)
install_result = None
if install_result is not None and install_result.returncode != 0:
logger.warning(
f"Wheel installation failed (attempt {attempt}/{WHEEL_INSTALL_ATTEMPTS}): "
f"{install_result.stderr.strip()[-500:]}"
)
elif install_result is not None:
logger.info(f"pip install completed for wheel: {wheel_path}")
# A clean `pip install` exit is not sufficient — confirm the deps
# the render/encode paths need are actually importable before we let
# a job run against this environment.
if verify_wheel_imports():
_verified_wheel_version = latest_version
logger.info(f"Successfully installed and verified wheel: {wheel_path}")
return True
logger.warning(
f"Wheel environment incomplete after attempt {attempt}/{WHEEL_INSTALL_ATTEMPTS}; "
"dependencies are missing or failed to import"
)
logger.error(
f"Wheel not ready after {WHEEL_INSTALL_ATTEMPTS} attempts: import verification "
"still failing (environment is missing dependencies)"
)
return False
except subprocess.TimeoutExpired:
logger.warning("Wheel download/install timed out, using fallback")
logger.warning("Wheel download timed out, using fallback")
return False
except Exception as e:
logger.warning(f"Failed to ensure latest wheel: {e}")
@@ -604,6 +848,110 @@ def generate_mov_from_png(png_path: Path, mov_path: Path, duration: int = 5) ->
return mov_path
# Portrait (9:16) karaoke render is default-on; set PORTRAIT_RENDER_ENABLED=false to disable.
PORTRAIT_RENDER_ENABLED = os.environ.get("PORTRAIT_RENDER_ENABLED", "true").lower() == "true"
PORTRAIT_SUFFIX = "(Final Karaoke Portrait 1080x1920)"
def _resolve_portrait_font(styles: dict, work_dir: Path) -> Optional[str]:
"""Resolve a usable .ttf file for the portrait header (PIL needs a file path).
libass resolves the lyrics font via fontconfig (the theme font is registered by
the earlier render step on the same VM), but PIL needs an actual file. Ask
fontconfig for the theme font family's file; fall back to any bundled style font.
"""
family = (styles.get("karaoke", {}) or {}).get("font") or "Avenir Next Bold"
try:
res = subprocess.run(
["fc-match", "--format=%{file}", family],
capture_output=True, text=True, timeout=5,
)
if res.returncode == 0 and res.stdout and os.path.isfile(res.stdout.strip()):
return res.stdout.strip()
except (FileNotFoundError, subprocess.TimeoutExpired):
pass
for pattern in ("style/*.ttf", "style/*.otf", "*.ttf"):
hit = next(iter(work_dir.glob(pattern)), None)
if hit:
return str(hit)
return None
def render_portrait_into_outputs(
job_id: str, work_dir: Path, output_dir: Path, base_name: str,
artist: str, title: str, instrumental: Path, config: dict,
) -> Optional[str]:
"""Render the portrait (9:16) karaoke video into ``output_dir`` (best-effort).
Reuses the same corrected-lyrics data + theme as the landscape render. Uses the
un-padded instrumental and un-countdown-processed segments so the two stay in
sync without the countdown offset (the portrait title card provides lead-in).
This is additive and non-fatal: any failure logs and returns ``None`` so the
landscape outputs and distribution proceed unaffected.
"""
if not PORTRAIT_RENDER_ENABLED:
logger.info(f"[job:{job_id}] Portrait render disabled via PORTRAIT_RENDER_ENABLED")
return None
try:
from karaoke_gen.lyrics_transcriber.types import CorrectionResult
from karaoke_gen.portrait import render_portrait_video, PortraitBrandConfig
# Corrected lyrics: prefer the reviewed corrections_updated.json.
corrections_file = None
for candidate in ("lyrics/corrections_updated.json", "lyrics/corrections.json"):
p = work_dir / candidate
if p.is_file():
corrections_file = p
break
if corrections_file is None:
found = next(iter(work_dir.glob("**/corrections*.json")), None)
corrections_file = found
if corrections_file is None:
logger.warning(f"[job:{job_id}] Portrait skipped: no corrections JSON found")
return None
with open(corrections_file, "r", encoding="utf-8") as f:
correction_result = CorrectionResult.from_dict(json.load(f))
# Theme styles (optional — renderer fills defaults).
styles = {}
style_params = work_dir / "style" / "style_params.json"
if not style_params.is_file():
style_params = next(iter(work_dir.glob("**/style_params.json")), None)
if style_params and Path(style_params).is_file():
with open(style_params, "r", encoding="utf-8") as f:
styles = json.load(f)
font_path = _resolve_portrait_font(styles, work_dir)
brand = PortraitBrandConfig(
brand_text=config.get("portrait_brand_text", "NOMAD KARAOKE"),
footer_text=config.get("portrait_footer_text", "nomadkaraoke.com"),
font_path=font_path,
)
out_path = output_dir / f"{base_name} {PORTRAIT_SUFFIX}.mp4"
logger.info(f"[job:{job_id}] Rendering portrait karaoke video -> {out_path.name}")
render_portrait_video(
correction_result=correction_result,
instrumental_path=str(instrumental),
styles=styles,
artist=artist,
title=title,
output_path=str(out_path),
brand=brand,
font_path=font_path,
work_dir=str(work_dir / "portrait_tmp"),
logger=logger,
)
if out_path.is_file():
logger.info(f"[job:{job_id}] Portrait render complete ({out_path.stat().st_size} bytes)")
return str(out_path)
logger.warning(f"[job:{job_id}] Portrait render produced no file")
return None
except Exception as e:
logger.error(f"[job:{job_id}] Portrait render failed (non-fatal): {e}", exc_info=True)
return None
def run_encoding(job_id: str, work_dir: Path, config: dict):
'''Run encoding using LocalEncodingService (single source of truth).
@@ -617,6 +965,7 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
'''
jobs[job_id]["status"] = "running"
jobs[job_id]["progress"] = 10
_persist(job_id)
try:
# Import LocalEncodingService from installed wheel (required, no fallback)
@@ -786,6 +1135,27 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
jobs[job_id]["progress"] = 90
# Include the standalone 5-second screen videos in the uploaded outputs so they
# land in the Dropbox folder. They are generated above (or passed in) purely as
# concat inputs and used to live only in screens/; copy them into outputs/ with
# the canonical names. Regression fix: screen MOVs disappeared from Dropbox after
# #647/#650 moved screen generation to this encoder.
for screen_video, suffix in ((title_video, "Title"), (end_video, "End")):
if screen_video and Path(screen_video).is_file():
dest = output_dir / f"{base_name} ({suffix}).mov"
try:
shutil.copy2(screen_video, dest)
logger.info(f"Staged screen video for upload: {dest.name}")
except Exception as e:
logger.warning(f"Failed to stage {suffix} MOV into outputs: {e}")
# Portrait (9:16) karaoke render — additive, non-fatal. Written into output_dir
# so it rides the same GCS upload + Dropbox distribution as the other finals.
jobs[job_id]["progress"] = 92
render_portrait_into_outputs(
job_id, work_dir, output_dir, base_name, artist, title, instrumental, config,
)
# Collect output files
output_files = [str(f) for f in output_dir.glob("*") if f.is_file()]
jobs[job_id]["output_files"] = output_files
@@ -803,12 +1173,14 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
logger.error(error_msg)
jobs[job_id]["status"] = "failed"
jobs[job_id]["error"] = error_msg
_persist(job_id)
raise RuntimeError(error_msg) from e
except Exception as e:
logger.error(f"Encoding failed: {e}")
jobs[job_id]["status"] = "failed"
jobs[job_id]["error"] = str(e)
_persist(job_id)
raise
@@ -816,8 +1188,18 @@ async def process_job(job_id: str, request: EncodeRequest):
# Process an encoding job asynchronously
try:
# Download and install latest wheel at job start (allows hot updates without restart)
# This means in-progress jobs continue with their version, new jobs get latest code
ensure_latest_wheel()
# This means in-progress jobs continue with their version, new jobs get latest code.
# Fail fast (retryable) if the environment isn't ready rather than proceeding into a
# confusing "No module named ..." ImportError deep in encoding.
# ensure_latest_wheel() makes blocking subprocess calls (install can retry for many
# minutes) — run it in the thread pool so the async event loop keeps serving health
# checks and status polls.
loop = asyncio.get_event_loop()
if not await loop.run_in_executor(light_executor, ensure_latest_wheel):
raise RuntimeError(
"karaoke-gen wheel/dependencies not ready on this worker after retries; "
"job should be retried on a healthy worker"
)
with tempfile.TemporaryDirectory() as temp_dir:
work_dir = Path(temp_dir) / "work"
@@ -839,10 +1221,11 @@ async def process_job(job_id: str, request: EncodeRequest):
logger.info(f"Downloading existing instrumental: {gcs_uri} -> {dest}")
download_single_file_from_gcs(gcs_uri, dest)
# Run encoding in thread pool (CPU-bound)
# Run encoding in the heavy lane (CPU/RAM-bound; serialized to
# avoid OOM — see heavy_executor comment).
loop = asyncio.get_event_loop()
output_dir = await loop.run_in_executor(
executor,
heavy_executor,
run_encoding,
job_id,
work_dir,
@@ -871,12 +1254,14 @@ async def process_job(job_id: str, request: EncodeRequest):
jobs[job_id]["status"] = "complete"
jobs[job_id]["progress"] = 100
_persist(job_id)
logger.info(f"Job {job_id} complete")
except Exception as e:
logger.error(f"Job {job_id} failed: {e}")
jobs[job_id]["status"] = "failed"
jobs[job_id]["error"] = str(e)
_persist(job_id)
async def process_preview_job(job_id: str, request: EncodePreviewRequest):
@@ -886,11 +1271,11 @@ async def process_preview_job(job_id: str, request: EncodePreviewRequest):
work_dir = Path(temp_dir) / "work"
work_dir.mkdir()
# Run preview encoding in thread pool (CPU-bound)
# Note: run_preview_encoding handles download/upload internally
# Run preview encoding in the light lane so interactive review
# previews never queue behind a multi-minute full encode.
loop = asyncio.get_event_loop()
await loop.run_in_executor(
executor,
light_executor,
run_preview_encoding,
job_id,
work_dir,
@@ -899,28 +1284,40 @@ async def process_preview_job(job_id: str, request: EncodePreviewRequest):
jobs[job_id]["status"] = "complete"
jobs[job_id]["progress"] = 100
_persist(job_id)
logger.info(f"Preview job {job_id} complete")
except Exception as e:
logger.error(f"Preview job {job_id} failed: {e}")
jobs[job_id]["status"] = "failed"
jobs[job_id]["error"] = str(e)
_persist(job_id)
async def process_render_video_job(job_id: str, request: RenderVideoRequest):
# Process a render-video job asynchronously
try:
# Download and install latest wheel at job start (allows hot updates without restart)
ensure_latest_wheel()
# Download and install latest wheel at job start (allows hot updates without restart).
# Fail fast (retryable) if the environment isn't ready rather than proceeding into a
# confusing "No module named 'tenacity'" ImportError inside render_video.
# Run in the thread pool: ensure_latest_wheel() blocks on subprocess installs (which
# can retry for many minutes) and must not stall the async event loop.
loop = asyncio.get_event_loop()
if not await loop.run_in_executor(light_executor, ensure_latest_wheel):
raise RuntimeError(
"karaoke-gen wheel/dependencies not ready on this worker after retries; "
"job should be retried on a healthy worker"
)
with tempfile.TemporaryDirectory() as temp_dir:
work_dir = Path(temp_dir) / "work"
work_dir.mkdir()
# Run render-video in thread pool (CPU-bound)
# Run render-video in the heavy lane (CPU/RAM-bound; serialized to
# avoid OOM — see heavy_executor comment).
loop = asyncio.get_event_loop()
await loop.run_in_executor(
executor,
heavy_executor,
run_render_video,
job_id,
work_dir,
@@ -929,12 +1326,14 @@ async def process_render_video_job(job_id: str, request: RenderVideoRequest):
jobs[job_id]["status"] = "complete"
jobs[job_id]["progress"] = 100
_persist(job_id)
logger.info(f"Render video job {job_id} complete")
except Exception as e:
logger.error(f"Render video job {job_id} failed: {e}")
jobs[job_id]["status"] = "failed"
jobs[job_id]["error"] = str(e)
_persist(job_id)
@app.post("/encode-preview")
@@ -961,7 +1360,9 @@ async def submit_preview_encode_job(request: EncodePreviewRequest, background_ta
"progress": 0,
"error": None,
"output_files": None,
"kind": "preview", # light lane — never counted in the heavy queue
}
_persist(job_id)
background_tasks.add_task(process_preview_job, job_id, request)
@@ -992,7 +1393,9 @@ async def submit_render_video_job(request: RenderVideoRequest, background_tasks:
"error": None,
"output_files": None,
"metadata": None,
"kind": "render", # heavy lane
}
_persist(job_id)
background_tasks.add_task(process_render_video_job, job_id, request)
@@ -1023,19 +1426,46 @@ async def submit_encode_job(request: EncodeRequest, background_tasks: Background
"progress": 0,
"error": None,
"output_files": None,
"kind": "encode", # heavy lane
}
_persist(job_id)
background_tasks.add_task(process_job, job_id, request)
return {"status": "accepted", "job_id": job_id}
_HEAVY_KINDS = frozenset({"encode", "render"})
def _heavy_queue_position(job_id: str) -> Optional[int]:
"""Number of heavy jobs ahead of `job_id` in the serialized heavy lane.
0 means this job is running or next up; None means it isn't a queued heavy
job (a preview, a terminal job, or unknown-kind). Relies on `jobs` being
insertion-ordered (dict order) so "ahead" == submitted earlier and still
pending/running.
"""
job = jobs.get(job_id)
if job is None or job.get("kind") not in _HEAVY_KINDS:
return None
if job.get("status") not in ("pending", "running"):
return None
ahead = 0
for other_id, other in jobs.items():
if other_id == job_id:
break
if other.get("kind") in _HEAVY_KINDS and other.get("status") in ("pending", "running"):
ahead += 1
return ahead
@app.get("/status/{job_id}")
async def get_job_status(job_id: str, _auth: bool = Depends(verify_api_key)) -> JobStatus:
# Get the status of an encoding job
if job_id not in jobs:
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
return JobStatus(**jobs[job_id])
return JobStatus(**jobs[job_id], queue_position=_heavy_queue_position(job_id))
@app.get("/health")
@@ -0,0 +1,266 @@
"""Firestore persistence for the encoding worker's in-memory job state.
Why this exists
---------------
The encoding worker holds job state in a process-local `dict`. When the
systemd service restarts (deploy, crash, OOM, manual restart) the dict is
empty, so polls from the Cloud Run side return 404 and the orchestrator
either fails the user's job or triggers wasteful re-renders.
This module mirrors per-job state to Firestore so that:
1. Polls after a restart return the *last known* status (typically `failed`
with `code: encoding_worker_restart`), not 404 — orchestrator can react
intelligently instead of guessing.
2. On startup, the worker reads back any jobs it had in flight and marks
them failed with that restart code, so the in-memory dict and Firestore
stay in sync after a crash.
Scope
-----
Each row is keyed by `job_id` and tagged with `vm_name`. Loads are filtered
to the current VM — VMs don't see each other's jobs. (We never have two
VMs simultaneously holding the same `job_id` — Cloud Run only submits to
one VM at a time, and on restart that same VM is the only one that owned
the doc.)
A Firestore field-level TTL on `expires_at` cleans completed/failed rows
automatically after 7 days; we set it on every write.
Cost / latency
--------------
Writes are best-effort. A Firestore failure logs a warning but does NOT
fail the encoding job — persistence is observability/recovery, not
correctness. The hot path stays in-memory.
"""
from __future__ import annotations
import logging
import os
import socket
import threading
from datetime import datetime, timedelta, timezone
from typing import Any, Optional
logger = logging.getLogger(__name__)
_RESTART_FAIL_CODE = "encoding_worker_restart"
_TERMINAL_STATUSES = frozenset({"complete", "failed"})
_DEFAULT_TTL_DAYS = 7
_COLLECTION = "encoding_worker_jobs"
def _now_utc() -> datetime:
return datetime.now(timezone.utc)
def get_vm_name() -> str:
"""Return the VM's identifier.
Prefer the GCE instance name (set by infrastructure/encoding-worker/
startup.sh as `ENCODING_WORKER_VM_NAME`), falling back to the OS
hostname so this still works in tests/local dev.
"""
return (
os.environ.get("ENCODING_WORKER_VM_NAME")
or socket.gethostname()
or "unknown"
)
class JobStatePersister:
"""Mirror in-memory job state to Firestore.
Lazily initializes the Firestore client so import-time has zero cost
and tests/local-dev that don't have GCP creds don't blow up.
All operations are thread-safe — the encoding worker uses a
ThreadPoolExecutor and may call save() from multiple worker threads.
"""
def __init__(
self,
*,
vm_name: Optional[str] = None,
collection: str = _COLLECTION,
ttl_days: int = _DEFAULT_TTL_DAYS,
client: Any = None, # for tests
) -> None:
self.vm_name = vm_name or get_vm_name()
self.collection = collection
self.ttl_days = ttl_days
self._client = client
self._client_lock = threading.Lock()
self._enabled: Optional[bool] = None # None = not yet probed
def _get_client(self):
"""Return a Firestore client or None if creds are missing."""
if self._client is not None:
return self._client
with self._client_lock:
if self._client is not None:
return self._client
try:
from google.cloud import firestore # type: ignore
self._client = firestore.Client()
self._enabled = True
logger.info(
"JobStatePersister initialized (vm=%s, collection=%s)",
self.vm_name, self.collection,
)
except Exception as exc:
# Don't fail the worker if creds aren't available — just
# disable persistence and log loudly so it's discoverable.
self._enabled = False
logger.warning(
"JobStatePersister disabled (Firestore unavailable): %s",
exc,
)
return self._client
@property
def enabled(self) -> bool:
if self._enabled is None:
self._get_client()
return bool(self._enabled)
def save(self, job_state: dict) -> None:
"""Persist a single job's state.
Adds `vm_name`, `updated_at`, and `expires_at` (TTL) fields. Never
raises — Firestore failures are logged and swallowed because
encoding is the source of truth and persistence is best-effort.
On the first PermissionDenied (typically: IAM not yet applied for
the encoding worker SA), self-disables to avoid logging a warning
on every save call. Caller can re-enable by re-instantiating after
IAM lands.
"""
client = self._get_client()
if client is None:
return
job_id = job_state.get("job_id")
if not job_id:
logger.warning("JobStatePersister.save called without job_id; skipping")
return
try:
doc = {
**job_state,
"vm_name": self.vm_name,
"updated_at": _now_utc(),
"expires_at": _now_utc() + timedelta(days=self.ttl_days),
}
client.collection(self.collection).document(job_id).set(doc)
except Exception as exc:
# If this is a permanent auth failure (IAM not applied yet),
# log once and self-disable so we don't spam ERROR per save.
# Other transient errors are logged at WARNING per occurrence.
if self._looks_like_auth_error(exc):
if self._enabled is not False: # only log on transition
logger.warning(
"JobStatePersister disabling: Firestore auth failed "
"(likely IAM not yet applied to encoding-worker-sa: "
"needs roles/datastore.user). Subsequent saves will "
"be no-ops. Error: %r",
exc,
)
self._enabled = False
self._client = None
return
logger.warning(
"[job:%s] Failed to persist job state to Firestore: %r",
job_id, exc,
)
@staticmethod
def _looks_like_auth_error(exc: BaseException) -> bool:
"""Heuristic — google.api_core.exceptions.PermissionDenied or 403/401."""
type_name = type(exc).__name__
if type_name in ("PermissionDenied", "Unauthenticated", "Forbidden"):
return True
msg = str(exc).lower()
return any(s in msg for s in ("permission_denied", "permissiondenied",
"403", "401", "unauthenticated",
"missing or insufficient permissions"))
def load_active_jobs(self) -> dict[str, dict]:
"""Return any non-terminal jobs persisted for this VM.
Used at startup to recover state from before the restart. Terminal
jobs (complete/failed) are also persisted but not returned here —
their docs serve only post-restart status polls.
Self-disables on auth errors (same pattern as save).
"""
client = self._get_client()
if client is None:
return {}
try:
query = (
client.collection(self.collection)
.where("vm_name", "==", self.vm_name)
)
recovered: dict[str, dict] = {}
for doc_snapshot in query.stream():
data = doc_snapshot.to_dict() or {}
status = data.get("status")
if status in _TERMINAL_STATUSES:
continue
# Strip the persistence-only fields before handing back
for k in ("vm_name", "updated_at", "expires_at"):
data.pop(k, None)
recovered[doc_snapshot.id] = data
return recovered
except Exception as exc:
if self._looks_like_auth_error(exc):
if self._enabled is not False:
logger.warning(
"JobStatePersister disabling: Firestore auth failed "
"during load_active_jobs (likely IAM not applied). "
"Error: %r", exc,
)
self._enabled = False
self._client = None
return {}
logger.warning(
"JobStatePersister.load_active_jobs failed: %r", exc,
)
return {}
def mark_orphans_failed_on_startup(self, jobs: dict[str, dict]) -> int:
"""Mark any in-progress jobs as failed with the restart code.
Called at worker startup. Mutates `jobs` in place AND persists each
change so polls from the orchestrator see consistent state.
The work_dir for an interrupted job is gone (tmpfs / temp dir wiped
by systemd restart), so we cannot resume — the only safe thing is
to surface a clear failure so the caller can decide to retry.
Returns the number of jobs marked failed.
"""
active = self.load_active_jobs()
if not active:
return 0
marked = 0
for job_id, job_state in active.items():
job_state["status"] = "failed"
job_state["error"] = (
f"Encoding worker restarted mid-job (code: {_RESTART_FAIL_CODE}). "
"Worker process restart wiped in-memory state and the temp "
"work directory; resubmit to retry."
)
job_state["restart_failure_code"] = _RESTART_FAIL_CODE
jobs[job_id] = job_state
self.save(job_state)
marked += 1
logger.warning(
"[job:%s] Marked failed at startup due to encoding worker restart "
"(was status=%s, progress=%s)",
job_id,
job_state.get("_pre_restart_status", "unknown"),
job_state.get("progress"),
)
return marked
@@ -8,6 +8,10 @@ uvicorn>=0.27.0
# GCS client
google-cloud-storage>=2.14.0
# Firestore client - persists job state across systemd restarts so polls
# survive a worker restart instead of returning 404. See persistence.py.
google-cloud-firestore>=2.14.0
# Async utilities (optional, for future improvements)
aiofiles>=23.2.0
aiohttp>=3.9.0
+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
+118 -22
View File
@@ -10,13 +10,14 @@ This module handles the complete job lifecycle including:
"""
import logging
import uuid
from datetime import datetime
from datetime import datetime, timezone
from typing import Optional, Dict, Any, List
from backend.config import settings
from backend.exceptions import InvalidStateTransitionError, InsufficientCreditsError
from backend.models.job import Job, JobStatus, JobCreate, STATE_TRANSITIONS
from backend.models.worker_log import WorkerLogEntry
from backend.services.duration_reconciliation import reconcile_and_maybe_pause
from backend.services.firestore_service import FirestoreService
from backend.services.storage_service import StorageService
@@ -57,15 +58,16 @@ class JobManager:
ValueError: If theme_id is not provided (all jobs require a theme)
"""
# Check credits (skip for admins)
credits_to_charge = job_create.credits
if job_create.user_email and not is_admin:
from backend.services.user_service import get_user_service
user_service = get_user_service()
if not user_service.has_credits(job_create.user_email):
credits_available = user_service.check_credits(job_create.user_email)
credits_available = user_service.check_credits(job_create.user_email)
if credits_available < credits_to_charge:
raise InsufficientCreditsError(
message="You're out of credits. Buy more to continue creating karaoke videos.",
credits_available=credits_available,
credits_required=1,
credits_required=credits_to_charge,
)
# Enforce theme requirement - all jobs must have a theme
@@ -78,7 +80,10 @@ class JobManager:
job_id = str(uuid.uuid4())[:8]
now = datetime.utcnow()
# Timezone-aware UTC so the serialized ISO string carries a "+00:00"
# offset. A naive datetime.utcnow() serializes with no offset, and the
# frontend's Date() parser then mis-reads it as local time.
now = datetime.now(timezone.utc)
job = Job(
job_id=job_id,
status=JobStatus.PENDING, # New state machine starts with PENDING
@@ -126,17 +131,27 @@ class JobManager:
"is_admin": is_admin,
"created_from": job_create.request_metadata.get("created_from", "unknown"),
},
# Record how many credits were charged for this job (authoritative running total).
# When charging is bypassed (admin / no user_email), set credits_charged=0 and
# payment_bypassed=True so duration reconciliation short-circuits without pausing,
# charging, or refunding.
state_data=(
{"credits_charged": 0, "payment_bypassed": True}
if (is_admin or not job_create.user_email)
else {"credits_charged": credits_to_charge}
),
)
self.firestore.create_job(job)
logger.info(f"Created new job {job_id} with status PENDING")
# Deduct credit atomically (after job is persisted so we have job_id for transaction record)
# Deduct credits atomically (after job is persisted so we have job_id for transaction record)
if job_create.user_email and not is_admin:
from backend.services.user_service import get_user_service
user_service = get_user_service()
success, _remaining, deduct_msg = user_service.deduct_credit(
job_create.user_email, job_id, reason="job_creation"
success, _remaining, deduct_msg = user_service.deduct_credits(
job_create.user_email, job_id, amount=credits_to_charge, reason="job_creation",
count_as_job_creation=True,
)
if not success:
# Deduction failed (e.g., race condition) - delete the job and raise error
@@ -148,7 +163,7 @@ class JobManager:
raise InsufficientCreditsError(
message="Failed to deduct credit. Please try again.",
credits_available=0,
credits_required=1,
credits_required=credits_to_charge,
)
return job
@@ -177,6 +192,10 @@ class JobManager:
def update_job(self, job_id: str, updates: Dict[str, Any]) -> None:
"""Update job with arbitrary fields."""
self.firestore.update_job(job_id, updates)
def list_jobs_by_batch_id(self, batch_id: str, limit: int = 200) -> List[Job]:
"""List all jobs in a Bulk Mode batch (state_data.batch_id == batch_id)."""
return self.firestore.list_jobs_by_batch_id(batch_id, limit=limit)
def list_jobs(
self,
@@ -338,7 +357,9 @@ class JobManager:
if delete_files and job and job.output_files:
for gcs_path in job.output_files.values():
try:
self.storage.delete_file(gcs_path)
# ignore_missing: a job being deleted whose recorded file is
# already gone is not an error, just skip it quietly.
self.storage.delete_file(gcs_path, ignore_missing=True)
except Exception as e:
logger.error(f"Error deleting file {gcs_path}: {e}")
@@ -395,9 +416,16 @@ class JobManager:
valid_transitions = STATE_TRANSITIONS.get(current_status, [])
if new_status not in valid_transitions:
# Normalise both sides to their string values so the message reads
# 'downloading -> downloading' rather than the misleading
# 'downloading -> JobStatus.DOWNLOADING'. The asymmetry exists
# because Job.status is deserialised with use_enum_values=True
# (plain str) while new_status is typically an enum at call time.
from_value = current_status.value if hasattr(current_status, 'value') else str(current_status)
to_value = new_status.value if hasattr(new_status, 'value') else str(new_status)
error_msg = (
f"Invalid state transition for job {job_id}: "
f"{current_status} -> {new_status}. "
f"{from_value} -> {to_value}. "
f"Valid transitions: {[s.value for s in valid_transitions]}"
)
logger.error(error_msg)
@@ -406,8 +434,8 @@ class JobManager:
raise InvalidStateTransitionError(
message=error_msg,
job_id=job_id,
from_status=current_status,
to_status=new_status.value if hasattr(new_status, 'value') else str(new_status),
from_status=from_value,
to_status=to_value,
valid_transitions=[s.value for s in valid_transitions]
)
return False
@@ -539,13 +567,15 @@ class JobManager:
self._send_push_notification(job, "complete")
# Idle reminder scheduling for blocking states
elif new_status in [JobStatus.AWAITING_REVIEW, JobStatus.AWAITING_INSTRUMENTAL_SELECTION, JobStatus.AWAITING_AUDIO_EDIT]:
elif new_status in [JobStatus.AWAITING_REVIEW, JobStatus.AWAITING_INSTRUMENTAL_SELECTION, JobStatus.AWAITING_AUDIO_EDIT, JobStatus.AWAITING_DURATION_CONFIRM]:
self._schedule_idle_reminder(job, new_status)
# Send push notification for blocking states
if new_status == JobStatus.AWAITING_AUDIO_EDIT:
action_type = "audio_edit"
elif new_status == JobStatus.AWAITING_REVIEW:
action_type = "lyrics"
elif new_status == JobStatus.AWAITING_DURATION_CONFIRM:
action_type = "duration_confirm"
else:
action_type = "instrumental"
self._send_push_notification(job, action_type)
@@ -625,7 +655,9 @@ class JobManager:
Schedule an idle reminder for a blocking state.
Records the timestamp when the blocking state was entered and
schedules a Cloud Tasks task for 5 minutes later.
schedules a Cloud Tasks task after a state-specific delay:
- AWAITING_DURATION_CONFIRM: 15 minutes (900s) — user needs to confirm extra cost
- All other blocking states: default delay (IDLE_REMINDER_DELAY_SECONDS)
"""
import asyncio
import threading
@@ -638,6 +670,8 @@ class JobManager:
action_type = "audio_edit"
elif new_status == JobStatus.AWAITING_REVIEW:
action_type = "lyrics"
elif new_status == JobStatus.AWAITING_DURATION_CONFIRM:
action_type = "duration_confirm"
else:
action_type = "instrumental"
@@ -653,12 +687,19 @@ class JobManager:
'state_data': {**existing_state_data, **state_data_update}
})
# Schedule the idle reminder check via worker service (5 min delay)
# Schedule the idle reminder check via worker service.
# Duration-confirm uses 15-min delay; other states use the default.
from backend.services.worker_service import get_worker_service
# Capture action_type for the closure
_action_type = action_type
async def schedule_reminder():
worker_service = get_worker_service()
await worker_service.schedule_idle_reminder(job.job_id)
if _action_type == "duration_confirm":
await worker_service.schedule_idle_reminder(job.job_id, delay_seconds=900)
else:
await worker_service.schedule_idle_reminder(job.job_id)
# Try to get existing event loop, create new one if none exists
try:
@@ -748,6 +789,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.
@@ -829,9 +898,12 @@ class JobManager:
def _refund_credit_for_job(self, job_id: str, job: Job, reason: str) -> bool:
"""
Refund one credit for a job if eligible.
Refund all credits charged for a job if eligible.
Skips refund if: already refunded, no user email, or admin-owned job.
Reads ``state_data.credits_charged`` (defaulting to 1 for legacy jobs
that pre-date the field) and refunds that many credits in a single
``add_credits`` call. Skips refund if: already refunded, no user
email, admin-owned job, or credits_charged == 0 (payment_bypassed).
Never raises — refund failure must not block the calling operation.
Returns:
@@ -851,14 +923,30 @@ class JobManager:
if is_admin_email(job.user_email):
return False
# Determine how many credits to refund. ``credits_charged`` is set
# at job creation (and updated on duration-confirm). Legacy jobs
# that pre-date the field are guaranteed to be 1-credit jobs, so we
# default to 1. payment_bypassed admin/no-email jobs have
# credits_charged=0 and must not be refunded.
state_data = job.state_data or {}
credits_charged = int(state_data.get("credits_charged", 1))
if credits_charged == 0:
# Admin / payment-bypassed job — nothing to refund.
logger.info(f"Job {job_id}: credits_charged=0 (payment_bypassed), skipping refund")
return False
user_service = get_user_service()
refund_ok, new_balance, refund_msg = user_service.refund_credit(
job.user_email, job_id, reason=reason
refund_ok, new_balance, refund_msg = user_service.add_credits(
job.user_email, amount=credits_charged, reason=reason, job_id=job_id
)
if refund_ok:
# Mark job as refunded to prevent double-refund
self.update_job(job_id, {'credit_refunded': True})
logger.info(f"Refunded credit for {reason} job {job_id} to {_mask_email(job.user_email)} (balance: {new_balance})")
logger.info(
f"Refunded {credits_charged} credit(s) for {reason} job {job_id} "
f"to {_mask_email(job.user_email)} (balance: {new_balance})"
)
return True
else:
logger.warning(f"Credit refund failed for job {job_id}: {refund_msg}")
@@ -1001,6 +1089,14 @@ class JobManager:
message=message
)
# Reconcile credit charge against actual audio duration before triggering workers.
# Probes input_media_gcs_path (already set by the upload handler) via ffprobe.
# Returns True when the job is paused (AWAITING_DURATION_CONFIRM) or cancelled,
# in which case we must NOT start downstream workers.
if await reconcile_and_maybe_pause(job_id):
logger.info(f"Job {job_id}: Paused for duration confirmation (or cancelled); workers not started")
return
# Check if audio separation can be skipped
# Jobs with an existing instrumental (e.g. tenant uploads) don't need
# GPU-powered audio separation — saves 5-10 minutes of processing time
@@ -317,6 +317,69 @@ class JobNotificationService:
logger.exception(f"Error sending {action_type} reminder for job {job_id}: {e}")
return False
async def send_duration_confirm_reminder(self, job) -> bool:
"""
Send a 15-minute idle reminder email for jobs awaiting duration confirmation.
Called when a job has been in AWAITING_DURATION_CONFIRM for 15 minutes and
the user has not yet confirmed the extra cost.
Args:
job: Job object with at minimum job_id, user_email, artist, title,
and state_data (may contain pending_additional_credits,
duration_actual_seconds).
Returns:
True if email was sent successfully.
"""
if not ENABLE_AUTO_EMAILS:
logger.info(f"Auto emails disabled, skipping duration-confirm reminder for job {job.job_id}")
return False
user_email = getattr(job, "user_email", None)
if not user_email:
logger.warning(f"No user email for job {job.job_id}, skipping duration-confirm reminder")
return False
try:
user_locale = self._get_user_locale(user_email)
job_id = job.job_id
artist = getattr(job, "artist", None)
title = getattr(job, "title", None)
state_data = getattr(job, "state_data", None) or {}
# Extract extra-cost details from state_data (best-effort)
pending_credits = state_data.get("pending_additional_credits")
duration_seconds = state_data.get("duration_actual_seconds")
confirm_url = (
f"{self.frontend_url}{get_locale_prefix(user_locale)}/app"
)
success = self.email_service.send_duration_confirm_reminder(
to_email=user_email,
job_id=job_id,
artist=artist,
title=title,
pending_credits=pending_credits,
duration_seconds=duration_seconds,
confirm_url=confirm_url,
locale=user_locale,
)
if success:
logger.info(
f"Sent duration_confirm reminder for job {job_id} to {_mask_email(user_email)}"
)
else:
logger.error(f"Failed to send duration_confirm reminder for job {job_id}")
return success
except Exception as e:
logger.exception(f"Error sending duration_confirm reminder for job {job.job_id}: {e}")
return False
def get_completion_message(
self,
job_id: str,
+122 -28
View File
@@ -5,6 +5,7 @@ Scrapes karaokenerds.com to check if a song already has community-approved
karaoke versions available on YouTube. Ported from kjbox/kj-controller/karaoke_nerds.py.
"""
import asyncio
import logging
import re
import time
@@ -14,12 +15,22 @@ from urllib.parse import urlencode
import httpx
from bs4 import BeautifulSoup
from backend.services.match_judge.classifier import normalize_for_match
logger = logging.getLogger(__name__)
SEARCH_URL = "https://karaokenerds.com/Search"
REQUEST_TIMEOUT = 8
USER_AGENT = "NomadKaraokeGen/1.0"
# karaokenerds.com's search silently returns zero results once a query exceeds
# ~10 whitespace-separated terms (observed: 10 terms match, 11 return nothing).
# Long/repetitive titles like "I Do, I Do, I Do, I Do, I Do" combined with the
# artist blow past this, so the song is falsely reported as having no community
# version. When that happens we retry with the title alone (the highest-signal
# term) and keep only results whose artist matches.
MAX_RELIABLE_QUERY_TERMS = 10
# In-memory TTL cache: { cache_key: (expiry_timestamp, data) }
_cache: dict[str, tuple[float, Any]] = {}
CACHE_TTL_SECONDS = 3600 # 1 hour
@@ -145,6 +156,45 @@ def parse_results(html: str) -> list[dict]:
return songs
async def _search_songs(query: str) -> list[dict] | None:
"""Run a single karaokenerds search and parse the results.
Returns the parsed song list, or ``None`` if the HTTP request failed (so the
caller can distinguish "search errored" from "search returned nothing").
"""
params = urlencode({"query": query, "webFilter": "OnlyWeb"})
url = f"{SEARCH_URL}?{params}"
try:
async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT) as client:
resp = await client.get(
url,
headers={"User-Agent": USER_AGENT},
follow_redirects=True,
)
resp.raise_for_status()
except Exception as e:
logger.warning(f"KaraokeNerds search failed for '{query}': {e}")
return None
return parse_results(resp.text)
def _extract_community_songs(songs: list[dict]) -> tuple[list[dict], str | None]:
"""Filter parsed songs to those with community tracks; return (songs, best_url)."""
community_songs: list[dict] = []
best_youtube_url: str | None = None
for song in songs:
community_tracks = [t for t in song["tracks"] if t["is_community"]]
if community_tracks:
community_songs.append({
"title": song["title"],
"artist": song["artist"],
"community_tracks": community_tracks,
})
if best_youtube_url is None:
best_youtube_url = community_tracks[0]["youtube_url"]
return community_songs, best_youtube_url
async def check_community_versions(artist: str, title: str) -> dict:
"""
Check if a song has community-approved karaoke versions on karaokenerds.
@@ -160,39 +210,32 @@ async def check_community_versions(artist: str, title: str) -> dict:
if cached is not None:
return cached
params = urlencode({"query": query, "webFilter": "OnlyWeb"})
url = f"{SEARCH_URL}?{params}"
try:
async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT) as client:
resp = await client.get(
url,
headers={"User-Agent": USER_AGENT},
follow_redirects=True,
)
resp.raise_for_status()
except Exception as e:
logger.warning(f"KaraokeNerds search failed for '{query}': {e}")
songs = await _search_songs(query)
if songs is None:
# Hard failure (network/HTTP) — cache a negative so we don't hammer the
# site, matching prior behaviour.
result = {"has_community": False, "songs": [], "best_youtube_url": None}
_cache_set(cache_key, result)
return result
songs = parse_results(resp.text)
# karaokenerds chokes on overlong queries and returns nothing. If the
# combined "artist title" query was too long AND came back empty, retry with
# the title alone, then keep only results whose artist matches (title-only is
# broader, so this guards against same-titled songs by other artists).
if (
not songs
and title.strip()
and len(query.split()) > MAX_RELIABLE_QUERY_TERMS
):
fallback = await _search_songs(title)
if fallback:
key_artist = normalize_for_match(artist)
songs = [
s for s in fallback
if normalize_for_match(s.get("artist") or "") == key_artist
]
# Filter to only songs that have community tracks with YouTube URLs
community_songs = []
best_youtube_url = None
for song in songs:
community_tracks = [t for t in song["tracks"] if t["is_community"]]
if community_tracks:
community_songs.append({
"title": song["title"],
"artist": song["artist"],
"community_tracks": community_tracks,
})
if best_youtube_url is None:
best_youtube_url = community_tracks[0]["youtube_url"]
community_songs, best_youtube_url = _extract_community_songs(songs)
result = {
"has_community": len(community_songs) > 0,
@@ -201,3 +244,54 @@ async def check_community_versions(artist: str, title: str) -> dict:
}
_cache_set(cache_key, result)
return result
async def check_community_versions_batch(
songs: list[dict], concurrency: int = 5
) -> list[dict]:
"""Check community-version availability for many songs (Bulk Mode).
``songs`` is a list of ``{"artist": str, "title": str}``. Returns a list in the
same order, each ``{"artist", "title", "available": bool, "brands": [str],
"brand_count": int, "versions": [{"brand": str, "url": str}]}``. ``versions`` is
the per-community-version detail (deduped by brand, first YouTube URL kept) the UI
uses to render clickable links; ``brands``/``brand_count`` are retained for
back-compat. Bounded concurrency keeps us polite to karaokenerds.com; per-song
results reuse the existing 1h cache. A failed lookup degrades to
``available=False`` (the track simply stays selectable) — never raises.
"""
sem = asyncio.Semaphore(max(1, concurrency))
async def _one(song: dict) -> dict:
artist = (song.get("artist") or "").strip()
title = (song.get("title") or "").strip()
if not artist or not title:
return {"artist": artist, "title": title, "available": False,
"brands": [], "brand_count": 0, "versions": []}
async with sem:
res = await check_community_versions(artist, title)
versions: list[dict] = []
versioned_brands: set[str] = set()
brands: list[str] = []
for matched in res.get("songs", []):
for track in matched.get("community_tracks", []):
name = track.get("brand_name")
if not name:
continue
if name not in brands:
brands.append(name)
# A clickable version needs a URL; brand still counts as "exists" without one.
url = track.get("youtube_url")
if url and name not in versioned_brands:
versioned_brands.add(name)
versions.append({"brand": name, "url": url})
return {
"artist": artist,
"title": title,
"available": bool(res.get("has_community")),
"brands": brands,
"brand_count": len(brands),
"versions": versions,
}
return await asyncio.gather(*[_one(s) for s in songs])
+25 -4
View File
@@ -325,10 +325,29 @@ class LocalEncodingService:
output_file: str,
) -> bool:
"""
Convert MOV to MP4 format.
Convert the source "With Vocals" video (MOV/MKV) to a standard, portable MP4.
This produces the "(With Vocals).mp4" sing-along deliverable. It is a leaf
output — no later encode reads it — so the encode is chosen purely for the
deliverable itself:
- ``-pix_fmt yuv420p``: the renderer emits High 4:4:4 (yuv444p), which many
browsers/TVs/phones cannot decode. Normalize to 4:2:0 so it plays
everywhere and matches every other output. (Also ~halves this stage's CPU
time vs. re-encoding 4:4:4, and yields a slightly smaller file.)
- ``-preset veryfast``: this is the single longest finalization stage; a fast
preset roughly halves it (~56s → ~28s on a 32-vCPU worker) with negligible
quality difference for karaoke content (static background + text).
- ``-c:a aac``: the source audio is FLAC; FLAC-in-MP4 is non-standard. Encode
AAC 320k so the file is fully portable. Matches the documented spec
("4k H264/AAC with original vocals", see template_service.py).
Both commands force ``-pix_fmt yuv420p`` (h264_nvenc can otherwise *preserve* a
yuv444p input). Prod encoding workers are CPU-only, so ``cpu_command`` is the
real path; if the NVENC command ever errors, ``_execute_command_with_fallback``
drops to the (correct) CPU command.
Args:
input_file: Path to input MOV file
input_file: Path to input MOV/MKV file (source "With Vocals" video)
output_file: Path for output MP4 file
Returns:
@@ -336,11 +355,13 @@ class LocalEncodingService:
"""
gpu_command = (
f'{self._ffmpeg_base_command} {self.hwaccel_decode_flags} -i "{input_file}" '
f'-c:v {self.video_encoder} -c:a copy {self.MP4_FLAGS} "{output_file}"'
f'-c:v {self.video_encoder} -pix_fmt yuv420p -c:a {self.aac_codec} -ar 48000 -b:a 320k '
f'{self.MP4_FLAGS} "{output_file}"'
)
cpu_command = (
f'{self._ffmpeg_base_command} -i "{input_file}" '
f'-c:v libx264 -c:a copy {self.MP4_FLAGS} "{output_file}"'
f'-c:v libx264 -pix_fmt yuv420p -preset veryfast '
f'-c:a {self.aac_codec} -ar 48000 -b:a 320k {self.MP4_FLAGS} "{output_file}"'
)
return self._execute_command_with_fallback(
gpu_command, cpu_command, "Converting MOV to MP4"
+8
View File
@@ -0,0 +1,8 @@
"""Artist/title match-judge: deterministic + catalog + light-AI formatting and
match-acceptance decisions for the job-submission flow.
See docs/archive/2026-06-15-artist-title-matching-rework-plan.md.
"""
from backend.services.match_judge.verdict import MatchVerdict
__all__ = ["MatchVerdict"]
+174
View File
@@ -0,0 +1,174 @@
"""The light-AI layer of the match judge.
Invoked only when the deterministic+catalog classifier can't decide. Uses a
small Vertex Gemini model to judge whether the typed artist/title is a real
song, what its canonical formatting is, and whether any change is cosmetic,
content-level, or ambiguous. The model call is injectable for testing.
"""
from __future__ import annotations
import asyncio
import json
import logging
from typing import Awaitable, Callable, Optional
from backend.services.match_judge.verdict import (
KIND_AMBIGUOUS,
KIND_CONTENT,
KIND_COSMETIC,
KIND_NONE,
MatchVerdict,
)
logger = logging.getLogger(__name__)
_VALID_KINDS = {KIND_COSMETIC, KIND_CONTENT, KIND_AMBIGUOUS}
Generate = Callable[[str, str, str], Awaitable[dict]]
_SYSTEM_PROMPT = (
"You normalise song metadata for a karaoke service. Given what a user typed "
"for an artist and title (plus optional catalog candidates), decide whether it "
"refers to a real, released song and how its artist/title should be formatted.\n"
"Return JSON with: kind, confident, canonical_artist, canonical_title, "
"alternatives, reason.\n"
"kind:\n"
" 'cosmetic' – same song, only formatting/casing/punctuation/diacritics differ.\n"
" 'content' – the user made a typo or used a wrong/variant title; the correct "
"song text differs in actual characters.\n"
" 'ambiguous' – more than one plausible song matches; list them in alternatives.\n"
" 'none' – already correct, or you cannot confidently suggest anything.\n"
"confident: true only when you are sure. Never invent songs. Prefer the user's "
"input when unsure (kind='none'). canonical_artist/canonical_title must use "
"official formatting. alternatives is a list of {artist,title}."
)
# OpenAPI-style schema handed to the Vertex genai client at runtime.
RESPONSE_SCHEMA = {
"type": "object",
"properties": {
"kind": {"type": "string", "enum": ["cosmetic", "content", "ambiguous", "none"]},
"confident": {"type": "boolean"},
"canonical_artist": {"type": "string"},
"canonical_title": {"type": "string"},
"alternatives": {
"type": "array",
"items": {
"type": "object",
"properties": {
"artist": {"type": "string"},
"title": {"type": "string"},
},
},
},
"reason": {"type": "string"},
},
"required": ["kind", "confident"],
}
def _model() -> str:
try:
from backend.config import settings
return getattr(settings, "match_judge_model", "gemini-3.5-flash")
except Exception: # pragma: no cover - config import guard
return "gemini-3.5-flash"
def build_prompts(
artist: str, title: str, candidates: list[dict], audio_tier: Optional[int]
) -> tuple[str, str]:
lines = [f'User typed: artist="{artist}" title="{title}"']
if audio_tier is not None:
lines.append(
f"Audio-search confidence tier: {audio_tier} "
"(1 = strong match found, 3 = weak/no results — a weak tier hints the "
"title may be misspelled)."
)
if candidates:
lines.append("Catalog candidates (canonical formatting):")
for c in candidates:
lines.append(f'- {c.get("artist_name", "")} — {c.get("track_name", "")}')
else:
lines.append("No catalog candidates were found.")
return _SYSTEM_PROMPT, "\n".join(lines)
def _verdict_from_response(
data: object, *, fallback_artist: str, fallback_title: str
) -> MatchVerdict:
if not isinstance(data, dict):
data = {}
kind = data.get("kind")
if kind not in _VALID_KINDS:
return MatchVerdict(
KIND_NONE, True, fallback_artist, fallback_title,
engine="ai", reason="no suggestion",
)
canonical_artist = (data.get("canonical_artist") or "").strip() or fallback_artist
canonical_title = (data.get("canonical_title") or "").strip() or fallback_title
alternatives = []
for alt in data.get("alternatives") or []:
if isinstance(alt, dict) and alt.get("artist") and alt.get("title"):
alternatives.append(
{"artist": str(alt["artist"]), "title": str(alt["title"])}
)
return MatchVerdict(
kind=kind,
confident=bool(data.get("confident", False)),
canonical_artist=canonical_artist,
canonical_title=canonical_title,
alternatives=alternatives,
engine="ai",
reason=str(data.get("reason") or ""),
)
async def ai_judge_match(
artist: str,
title: str,
candidates: list[dict],
audio_tier: Optional[int],
*,
model: Optional[str] = None,
generate: Optional[Generate] = None,
) -> MatchVerdict:
model = model or _model()
gen = generate or _default_generate
system_prompt, user_prompt = build_prompts(artist, title, candidates, audio_tier)
data = await gen(model, system_prompt, user_prompt)
return _verdict_from_response(
data, fallback_artist=artist, fallback_title=title
)
async def _default_generate(model: str, system_prompt: str, user_prompt: str) -> dict:
return await asyncio.to_thread(_blocking_generate, model, system_prompt, user_prompt)
def _blocking_generate(model: str, system_prompt: str, user_prompt: str) -> dict:
import copy
from google import genai
from google.genai import types
from backend.config import settings
timeout_ms = int(getattr(settings, "match_judge_timeout_ms", 3000))
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_prompt],
config=types.GenerateContentConfig(
system_instruction=system_prompt,
response_mime_type="application/json",
response_schema=copy.deepcopy(RESPONSE_SCHEMA),
temperature=0,
),
)
return json.loads(response.text)
@@ -0,0 +1,82 @@
"""Deterministic + catalog match classification (no AI, no network).
`classify_catalog_match` returns a confident :class:`MatchVerdict` when the
typed artist/title clearly correspond to a catalog candidate (a cosmetic
formatting fix, or nothing to change). When it cannot confidently decide, it
returns ``None`` — the caller should then escalate to the AI judge.
"""
from __future__ import annotations
import re
import unicodedata
from typing import Optional
from karaoke_gen.utils import normalize_text
from backend.services.match_judge.verdict import (
KIND_COSMETIC,
KIND_NONE,
MatchVerdict,
)
_NON_ALNUM = re.compile(r"[^0-9a-z\s]")
_WS = re.compile(r"\s+")
def _fold_accents(text: str) -> str:
"""Drop combining marks so 'Beyoncé' and 'beyonce' compare equal."""
decomposed = unicodedata.normalize("NFKD", text)
return "".join(c for c in decomposed if not unicodedata.combining(c))
def normalize_for_match(text: str) -> str:
"""Aggressive key used only for equality comparison (never displayed).
Folds casing, accents, punctuation, whitespace, and treats '&' as 'and'.
"""
s = normalize_text(text or "")
s = s.replace("&", " and ")
s = _fold_accents(s)
s = s.casefold()
s = _NON_ALNUM.sub(" ", s)
s = _WS.sub(" ", s).strip()
return s
def classify_catalog_match(
artist: str, title: str, candidates: list[dict]
) -> Optional[MatchVerdict]:
"""Return a confident verdict from catalog candidates, or None to escalate.
candidates: dicts with ``artist_name`` and ``track_name`` (Spotify/MB canonical).
"""
key_artist = normalize_for_match(artist)
key_title = normalize_for_match(title)
for cand in candidates:
cand_artist = cand.get("artist_name") or ""
cand_title = cand.get("track_name") or ""
if (
normalize_for_match(cand_artist) == key_artist
and normalize_for_match(cand_title) == key_title
):
# Same song. Cosmetic fix unless the user already typed it exactly.
if cand_artist == artist and cand_title == title:
return MatchVerdict(
kind=KIND_NONE,
confident=True,
canonical_artist=artist,
canonical_title=title,
engine="catalog",
reason="already canonical",
)
return MatchVerdict(
kind=KIND_COSMETIC,
confident=True,
canonical_artist=cand_artist,
canonical_title=cand_title,
engine="catalog",
reason="formatting differs from catalog",
)
return None
+128
View File
@@ -0,0 +1,128 @@
"""Match-judge orchestration.
Composes the deterministic+catalog classifier with the AI judge. The AI judge
runs ONLY when the classifier can't confidently decide, and never blocks or
errors the caller — any failure degrades to "no suggestion".
"""
from __future__ import annotations
import logging
from typing import Awaitable, Callable, Literal, Optional
from backend.services.match_judge.classifier import classify_catalog_match
from backend.services.match_judge.verdict import KIND_NONE, MatchVerdict
logger = logging.getLogger(__name__)
CATALOG_CANDIDATE_LIMIT = 8
Stage = Literal["fast", "full"]
# Audio tiers at or above this are "weak" (poor / no results). A weak tier hints
# the typed title may be a typo, so even a confident catalog match is verified
# with the AI judge (it can be a junk/misspelled Spotify entry).
WEAK_TIER = 3
SearchTracks = Callable[[str, Optional[str], int], Awaitable[list[dict]]]
AiJudge = Callable[[str, str, list[dict], Optional[int]], Awaitable[MatchVerdict]]
async def _default_search_tracks(query: str, artist: Optional[str], limit: int) -> list[dict]:
from backend.services.catalog_proxy_service import search_tracks
return await search_tracks(query, artist, limit)
async def _default_ai_judge(
artist: str, title: str, candidates: list[dict], audio_tier: Optional[int]
) -> MatchVerdict:
from backend.services.match_judge.ai import ai_judge_match
return await ai_judge_match(artist, title, candidates, audio_tier)
def _default_enabled() -> bool:
try:
from backend.config import settings
return bool(getattr(settings, "match_judge_enabled", True))
except Exception: # pragma: no cover - config import guard
return True
async def judge_match(
artist: str,
title: str,
audio_tier: Optional[int] = None,
*,
stage: Stage = "full",
search_tracks: Optional[SearchTracks] = None,
ai_judge: Optional[AiJudge] = None,
enabled: Optional[bool] = None,
) -> MatchVerdict:
"""Return a :class:`MatchVerdict` for the typed artist/title.
audio_tier: the audio search's confidence tier (1=best..3=poor), used by the
AI judge to decide whether weak results suggest a typo. May be None.
stage:
"fast" — catalog-only pass (no AI, tier ignored). Runs in parallel with the
audio search so the common cosmetic tidy is ready before results render.
Returns the catalog verdict if confident, else a ``needs_ai=True`` marker
telling the caller to make a "full" call once the tier is known.
"full" — the complete pipeline: catalog, then the AI judge when catalog isn't
confident OR (item 4) when a confident catalog match coincides with a weak
audio tier (the match may be a junk/typo'd entry — let AI override).
"""
search = search_tracks or _default_search_tracks
ai = ai_judge or _default_ai_judge
if enabled is None:
enabled = _default_enabled()
try:
candidates = await search(title, artist, CATALOG_CANDIDATE_LIMIT)
except Exception:
logger.warning(
"match-judge catalog search failed; continuing without candidates",
exc_info=True,
)
candidates = []
catalog_verdict = classify_catalog_match(artist, title, candidates)
# Fast pass: catalog only. Never touches the AI layer.
if stage == "fast":
if catalog_verdict is not None:
return catalog_verdict
return MatchVerdict(
KIND_NONE, False, artist, title,
engine="catalog", reason="needs ai", needs_ai=True,
)
# Full pass.
if catalog_verdict is not None:
weak = audio_tier is not None and audio_tier >= WEAK_TIER
if not (enabled and weak):
return catalog_verdict
# Item 4: weak audio results make the typo hypothesis plausible even though
# the catalog "matched" — verify with AI and let a confident verdict override.
try:
ai_verdict = await ai(artist, title, candidates, audio_tier)
except Exception:
logger.exception(
"match-judge AI verification failed; keeping catalog verdict"
)
return catalog_verdict
if ai_verdict.confident and ai_verdict.kind != KIND_NONE:
return ai_verdict
return catalog_verdict
if not enabled:
return MatchVerdict(
KIND_NONE, True, artist, title, engine="deterministic", reason="ai disabled"
)
try:
return await ai(artist, title, candidates, audio_tier)
except Exception:
logger.exception("match-judge AI call failed; returning no-suggestion")
return MatchVerdict(
KIND_NONE, True, artist, title, engine="ai", reason="ai failed"
)
+47
View File
@@ -0,0 +1,47 @@
"""The verdict returned by the match judge."""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Literal
# kind values:
# "cosmetic" – same song, formatting-only fix → apply invisibly
# "content" – actual characters change (typo/different title) → surface + maybe re-search
# "ambiguous" – more than one plausible song → ask the user first
# "none" – nothing to change (already correct, or no confident suggestion)
KIND_COSMETIC = "cosmetic"
KIND_CONTENT = "content"
KIND_AMBIGUOUS = "ambiguous"
KIND_NONE = "none"
Kind = Literal["cosmetic", "content", "ambiguous", "none"]
Engine = Literal["deterministic", "catalog", "ai"]
@dataclass(frozen=True)
class MatchVerdict:
kind: Kind
confident: bool
canonical_artist: str
canonical_title: str
alternatives: list[dict] = field(default_factory=list) # [{"artist","title"}]
engine: Engine = "deterministic"
reason: str = ""
# True only from a "fast" (catalog-only) pass that couldn't confidently decide:
# the caller should escalate to a "full" pass (with the audio tier) for an AI
# verdict. Always False on a full-pass verdict.
needs_ai: bool = False
def to_dict(self) -> dict:
return {
"kind": self.kind,
"confident": self.confident,
"canonical_artist": self.canonical_artist,
"canonical_title": self.canonical_title,
"alternatives": self.alternatives,
"engine": self.engine,
"reason": self.reason,
"needs_ai": self.needs_ai,
}
+391
View File
@@ -0,0 +1,391 @@
"""MusicBrainz lookup service for Bulk Mode album/release lookup.
Provides artist search, album (release-group) listing, canonical-release
selection, and tracklist retrieval with "extra track" detection (live /
remix / bonus / demo / acoustic / instrumental).
MusicBrainz asks for a descriptive User-Agent and ~1 request/second. We add a
small process-wide throttle and a short in-memory TTL cache because album
lookups are interactive and low-volume.
API shapes (captured from the live API, 2026-06):
- GET /ws/2/artist?query=&fmt=json -> {artists: [{id,name,disambiguation,type,score,country}]}
- GET /ws/2/release-group?artist=&type=album&fmt=json
-> {release-groups: [{id,title,primary-type,secondary-types:[str],first-release-date}]}
- GET /ws/2/release?release-group=&inc=media&fmt=json
-> {releases: [{id,title,status,date,country,packaging,disambiguation,media:[{track-count}]}]}
- GET /ws/2/release/{id}?inc=recordings&fmt=json
-> {id,title,status,date,country,media:[{format,track-count,
tracks:[{position,title,length,recording:{id,title,disambiguation,length}}]}]}
"""
from __future__ import annotations
import asyncio
import logging
import re
import time
from collections import Counter
from typing import Any, Dict, List, Optional
from urllib.parse import urlencode
import httpx
logger = logging.getLogger(__name__)
MB_BASE = "https://musicbrainz.org/ws/2"
USER_AGENT = "NomadKaraoke/1.0 (contact@nomadkaraoke.com)"
_MIN_INTERVAL_S = 1.0 # MusicBrainz politeness: ~1 req/s
_CACHE_TTL_S = 600 # 10 min — album metadata is effectively static
_REQUEST_TIMEOUT_S = 15.0
_MAX_RETRIES = 3 # MusicBrainz 503s / transient transport errors are common from cloud egress
_RETRY_BACKOFF_S = 0.5
# Country preference for canonical-release tie-breaks (worldwide / Europe / US / UK).
_PREFERRED_COUNTRIES = ["XW", "XE", "US", "GB"]
# Locale → ordered country preference for picking which pressing backs a variant.
# Biases the representative release toward the user's likely region; falls back to
# the worldwide default for anything unmapped. Keyed by the language part of the
# locale (region suffix is ignored, e.g. "en-US" → "en").
_LOCALE_COUNTRY_PREFS: Dict[str, List[str]] = {
"en": ["GB", "US", "AU", "CA", "IE", "NZ"],
"es": ["ES", "MX", "AR"],
"fr": ["FR", "CA", "BE"],
"de": ["DE", "AT", "CH"],
"it": ["IT"],
"pt": ["PT", "BR"],
"nl": ["NL", "BE"],
"sv": ["SE"],
"ja": ["JP"],
"ko": ["KR"],
"zh": ["CN", "TW", "HK"],
}
def country_prefs_for_locale(locale: Optional[str]) -> List[str]:
"""Map a next-intl locale to an ordered country preference list.
Returns a copy of the worldwide default (``_PREFERRED_COUNTRIES``) for an
empty/unknown locale so callers can mutate freely.
"""
if not locale:
return list(_PREFERRED_COUNTRIES)
base = re.split(r"[-_]", locale)[0].lower()
return list(_LOCALE_COUNTRY_PREFS.get(base, _PREFERRED_COUNTRIES))
# "Extra" track qualifier keywords. Matched only inside (), [], or after " - "
# so we don't misfire on legitimate titles that happen to contain a word.
_EXTRA_KEYWORDS = [
"live",
"remix",
"remixed",
"bonus",
"demo",
"acoustic",
"instrumental",
"rehearsal",
"alternate",
"alternative",
"radio edit",
"single edit",
"extended",
"re-recorded",
"rerecorded",
"session",
"outtake",
]
_EXTRA_KEYWORDS_RE = "|".join(re.escape(k) for k in _EXTRA_KEYWORDS)
# A qualifier segment: (...keyword...), [...keyword...], or " - ...keyword..."
_QUALIFIER_RE = re.compile(
r"(?:[\(\[][^\)\]]*\b(?:" + _EXTRA_KEYWORDS_RE + r")\b[^\)\]]*[\)\]])"
r"|(?:\s[-–]\s[^\(\[]*\b(?:" + _EXTRA_KEYWORDS_RE + r")\b)",
re.IGNORECASE,
)
def classify_extra(title: str, disambiguation: str = "") -> tuple[bool, str]:
"""Return (is_extra, reason). Conservative: only flags clear qualifiers."""
disamb = (disambiguation or "").strip().lower()
if disamb:
for kw in _EXTRA_KEYWORDS:
if re.search(r"\b" + re.escape(kw) + r"\b", disamb):
return True, disamb
m = _QUALIFIER_RE.search(title or "")
if m:
return True, m.group(0).strip(" -–()[]")
return False, ""
class MusicBrainzService:
"""Thin async client around the MusicBrainz web service."""
def __init__(self) -> None:
self._last_request_at = 0.0
self._throttle_lock = asyncio.Lock()
self._cache: Dict[str, tuple[float, Any]] = {}
# -- HTTP plumbing -----------------------------------------------------
async def _throttle(self) -> None:
# Non-blocking: yields to the event loop instead of stalling it.
async with self._throttle_lock:
now = time.monotonic()
wait = self._last_request_at + _MIN_INTERVAL_S - now
if wait > 0:
await asyncio.sleep(wait)
self._last_request_at = time.monotonic()
async def _get(self, path: str, params: Dict[str, Any]) -> Dict[str, Any]:
cache_key = path + "?" + urlencode(sorted(params.items()))
cached = self._cache.get(cache_key)
if cached and (time.monotonic() - cached[0]) < _CACHE_TTL_S:
return cached[1]
params = {**params, "fmt": "json"}
last_exc: Optional[Exception] = None
for attempt in range(_MAX_RETRIES):
await self._throttle()
try:
async with httpx.AsyncClient(timeout=_REQUEST_TIMEOUT_S) as client:
resp = await client.get(
f"{MB_BASE}/{path}", params=params, headers={"User-Agent": USER_AGENT}
)
# MusicBrainz returns 503 when rate-limited/throttled — retry those.
if resp.status_code == 503 and attempt < _MAX_RETRIES - 1:
last_exc = httpx.HTTPStatusError(
"503 from MusicBrainz", request=resp.request, response=resp
)
await asyncio.sleep(_RETRY_BACKOFF_S * (attempt + 1))
continue
resp.raise_for_status()
data = resp.json()
self._cache[cache_key] = (time.monotonic(), data)
return data
except (httpx.TransportError, httpx.TimeoutException) as e:
# Connection/timeout errors — retry with backoff.
last_exc = e
logger.warning("MusicBrainz %s attempt %d/%d failed: %r", path, attempt + 1, _MAX_RETRIES, e)
if attempt < _MAX_RETRIES - 1:
await asyncio.sleep(_RETRY_BACKOFF_S * (attempt + 1))
# Exhausted retries.
raise last_exc if last_exc else RuntimeError(f"MusicBrainz request failed: {path}")
# -- Public API --------------------------------------------------------
async def search_artists(self, name: str, limit: int = 8) -> List[Dict[str, Any]]:
"""Search artists by name."""
if not name or not name.strip():
return []
data = await self._get("artist", {"query": name.strip(), "limit": limit})
out = []
for a in data.get("artists", []):
out.append(
{
"mbid": a.get("id"),
"name": a.get("name"),
"disambiguation": a.get("disambiguation") or "",
"type": a.get("type"),
"country": a.get("country"),
"score": a.get("score"),
}
)
return out
async def get_albums(self, artist_mbid: str, limit: int = 100) -> List[Dict[str, Any]]:
"""List an artist's albums (release-groups), studio albums first, then by date."""
data = await self._get(
"release-group",
{"artist": artist_mbid, "type": "album|ep", "limit": limit},
)
groups = []
for rg in data.get("release-groups", []):
secondary = rg.get("secondary-types") or []
groups.append(
{
"release_group_mbid": rg.get("id"),
"title": rg.get("title"),
"primary_type": rg.get("primary-type"),
"secondary_types": secondary,
"first_release_date": rg.get("first-release-date") or "",
"is_studio": len(secondary) == 0,
}
)
# Studio albums first, then earliest release date.
groups.sort(key=lambda g: (not g["is_studio"], g["first_release_date"] or "9999"))
return groups
@staticmethod
def _total_tracks(release: Dict[str, Any]) -> int:
return sum((m.get("track-count") or 0) for m in (release.get("media") or []))
async def _list_editions(self, release_group_mbid: str) -> List[Dict[str, Any]]:
data = await self._get(
"release",
{"release-group": release_group_mbid, "inc": "media", "limit": 100},
)
editions = []
for r in data.get("releases", []):
editions.append(
{
"release_mbid": r.get("id"),
"title": r.get("title"),
"status": r.get("status"),
"date": r.get("date") or "",
"country": r.get("country"),
"packaging": r.get("packaging"),
"disambiguation": r.get("disambiguation") or "",
"track_count": self._total_tracks(r),
}
)
return editions
@staticmethod
def pick_canonical_edition(
editions: List[Dict[str, Any]],
preferred_countries: Optional[List[str]] = None,
) -> Optional[Dict[str, Any]]:
"""Pick the standard edition: official, modal track count, earliest, preferred country.
Choosing the most common track count avoids deluxe/remaster editions that
tack bonus tracks on the end. ``preferred_countries`` overrides the default
worldwide-first tie-break (used for locale-aware selection).
"""
if not editions:
return None
prefs = preferred_countries or _PREFERRED_COUNTRIES
official = [e for e in editions if e.get("status") == "Official"] or editions
with_tracks = [e for e in official if e.get("track_count", 0) > 0] or official
counts = Counter(e["track_count"] for e in with_tracks if e.get("track_count", 0) > 0)
if counts:
standard = counts.most_common(1)[0][0]
candidates = [e for e in with_tracks if e["track_count"] == standard]
else:
candidates = with_tracks
def country_rank(e: Dict[str, Any]) -> int:
c = e.get("country")
return prefs.index(c) if c in prefs else len(prefs)
candidates.sort(key=lambda e: (e.get("date") or "9999", country_rank(e)))
return candidates[0]
@staticmethod
def build_variants(
editions: List[Dict[str, Any]],
preferred_countries: Optional[List[str]] = None,
) -> List[Dict[str, Any]]:
"""Collapse a release-group's editions into distinct tracklist *variants*.
Country pressings are irrelevant for karaoke (we only need the track names),
so editions are grouped by ``track_count`` — within one release-group, same
count ≈ same songs. Each variant exposes a representative release (earliest +
preferred-country), the earliest year, how many pressings collapsed in, and a
label/delta relative to the "Original" (earliest) variant. Editions without a
track count are dropped. See
``docs/archive/2026-06-22-bulk-edition-collapse-and-community-versions-design.md``.
"""
if not editions:
return []
official = [e for e in editions if e.get("status") == "Official"] or editions
with_tracks = [e for e in official if (e.get("track_count") or 0) > 0]
if not with_tracks:
return []
groups: Dict[int, List[Dict[str, Any]]] = {}
for e in with_tracks:
groups.setdefault(e["track_count"], []).append(e)
variants: List[Dict[str, Any]] = []
for track_count, group in groups.items():
rep = MusicBrainzService.pick_canonical_edition(group, preferred_countries)
earliest = min((e.get("date") or "9999") for e in group)
year = earliest[:4] if earliest and earliest != "9999" else ""
variants.append(
{
"representative_release_mbid": rep["release_mbid"],
"track_count": track_count,
"year": year,
"pressing_count": len(group),
"_earliest": earliest,
}
)
# Original = earliest release, then most pressings, then fewest tracks.
variants.sort(key=lambda v: (v["_earliest"], -v["pressing_count"], v["track_count"]))
original = variants[0]
original_tc = original["track_count"]
for v in variants:
v["delta_vs_original"] = v["track_count"] - original_tc
v["label"] = "Original" if v is original else "Reissue"
del v["_earliest"]
# Display order: Original first, then by year ascending, then track count.
variants.sort(key=lambda v: (v["label"] != "Original", v["year"] or "9999", v["track_count"]))
return variants
async def get_release_tracklist(self, release_mbid: str) -> Dict[str, Any]:
"""Fetch a release's tracklist with per-track extra detection."""
data = await self._get(f"release/{release_mbid}", {"inc": "recordings"})
tracks: List[Dict[str, Any]] = []
for medium in data.get("media") or []:
for t in medium.get("tracks") or []:
rec = t.get("recording") or {}
title = t.get("title") or rec.get("title") or ""
disamb = rec.get("disambiguation") or ""
is_extra, reason = classify_extra(title, disamb)
length_ms = t.get("length") or rec.get("length")
tracks.append(
{
"position": t.get("position"),
"title": title,
"recording_mbid": rec.get("id"),
"disambiguation": disamb,
"length_ms": length_ms,
"is_extra": is_extra,
"extra_reason": reason,
}
)
return {
"release_mbid": data.get("id"),
"title": data.get("title"),
"date": data.get("date") or "",
"country": data.get("country"),
"tracks": tracks,
}
async def get_album_tracklist(
self,
release_group_mbid: str,
preferred_countries: Optional[List[str]] = None,
) -> Dict[str, Any]:
"""Resolve the canonical edition of an album and return its tracklist, the raw
editions, and the collapsed tracklist ``variants``. ``preferred_countries``
biases representative selection (locale-aware)."""
editions = await self._list_editions(release_group_mbid)
canonical = self.pick_canonical_edition(editions, preferred_countries)
variants = self.build_variants(editions, preferred_countries)
if not canonical:
return {
"release_mbid": None,
"title": None,
"tracks": [],
"editions": editions,
"variants": variants,
"selected_variant_mbid": None,
}
tracklist = await self.get_release_tracklist(canonical["release_mbid"])
tracklist["editions"] = editions
tracklist["canonical_release_mbid"] = canonical["release_mbid"]
tracklist["variants"] = variants
tracklist["selected_variant_mbid"] = canonical["release_mbid"]
return tracklist
_service: Optional[MusicBrainzService] = None
def get_musicbrainz_service() -> MusicBrainzService:
global _service
if _service is None:
_service = MusicBrainzService()
return _service
+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
+73
View File
@@ -0,0 +1,73 @@
"""Helpers for locating and naming a job's original input audio.
The original downloaded/uploaded audio (the source used for separation,
transcription and the With Vocals video) is stored in GCS but is no longer
copied into the final output folder by the distributed pipeline. These helpers
let the orchestrator (and the backfill script) restore it to the Dropbox track
folder with the historical source-tagged name, e.g.::
<artist> - <title> (flacfetch).flac
<artist> - <title> (uploaded).mp3
<artist> - <title> (YouTube).webm
The naming mirrors the legacy monolith convention.
"""
import os
from typing import Optional
# Map a job's audio_source_type to the historical filename suffix.
_SOURCE_TAGS = {
"file_upload": "uploaded",
"youtube_url": "YouTube",
"audio_search": "flacfetch",
}
def original_audio_source_tag(job) -> str:
"""Return the parenthesised source suffix for a job's original audio.
Falls back gracefully for older jobs that predate ``audio_source_type``.
"""
tag = _SOURCE_TAGS.get(getattr(job, "audio_source_type", None))
if tag:
return tag
# Fallbacks for legacy jobs without an explicit source type.
if getattr(job, "url", None):
return "YouTube"
if getattr(job, "filename", None) or getattr(job, "input_media_gcs_path", None):
return "uploaded"
return "input"
def original_audio_gcs_path(job) -> Optional[str]:
"""Return the GCS blob path of the original input audio, or None.
Prefers ``input_media_gcs_path`` (uploads are persisted under jobs/ and URL
jobs record their downloaded file here), then falls back to
``file_urls['input']`` which may be a plain string or a nested
``{'audio': ...}`` dict depending on the code path that wrote it.
"""
path = getattr(job, "input_media_gcs_path", None)
if path:
return path
file_urls = getattr(job, "file_urls", None) or {}
inp = file_urls.get("input")
if isinstance(inp, dict):
return inp.get("audio")
if isinstance(inp, str):
return inp
return None
def original_audio_output_filename(job, base_name: str) -> Optional[str]:
"""Return the output filename for the original audio, or None if absent.
e.g. ``"<artist> - <title> (flacfetch).flac"``. The extension is preserved
from the GCS path.
"""
gcs_path = original_audio_gcs_path(job)
if not gcs_path:
return None
ext = os.path.splitext(gcs_path)[1]
return f"{base_name} ({original_audio_source_tag(job)}){ext}"
+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
+22
View File
@@ -0,0 +1,22 @@
"""Duration-based credit pricing. Single source of truth for credit cost.
credits = max(1, ceil(duration_seconds / 600)) # 10-minute tiers
blocked = duration_seconds > 3600 # 60-minute hard ceiling
"""
from typing import Optional
import math
SECONDS_PER_CREDIT_TIER = 600 # 10 minutes per credit tier
DURATION_CREDIT_BLOCK_SECONDS = 3600 # inputs longer than 60 min are not supported
def duration_to_credits(seconds: Optional[float]) -> int:
"""Credits required to process `seconds` of audio. Minimum 1."""
if seconds is None or not math.isfinite(seconds) or seconds < 0:
return 1
return max(1, math.ceil(seconds / SECONDS_PER_CREDIT_TIER))
def is_blocked(seconds: Optional[float]) -> bool:
"""True if the input exceeds the supported duration ceiling."""
return seconds is not None and seconds > DURATION_CREDIT_BLOCK_SECONDS
@@ -247,6 +247,11 @@ class PushNotificationService:
notif_body = t(locale, "pushNotifications.reviewLyricsBody", title=title, artist=artist)
url = f"/app/jobs#/{job_id}/review"
tag = f"lyrics-{job_id}"
elif action_type == "duration_confirm":
notif_title = t(locale, "pushNotifications.confirmDurationTitle")
notif_body = t(locale, "pushNotifications.confirmDurationBody", title=title, artist=artist)
url = "/app"
tag = f"duration-confirm-{job_id}"
else: # instrumental
notif_title = t(locale, "pushNotifications.selectInstrumentalTitle")
notif_body = t(locale, "pushNotifications.selectInstrumentalBody", title=title, artist=artist)
+39 -2
View File
@@ -7,6 +7,7 @@ import json
from typing import Optional, BinaryIO, Any, Dict
from pathlib import Path
from google.cloud import storage
from google.cloud.exceptions import NotFound
from datetime import timedelta
from backend.config import settings
@@ -54,10 +55,27 @@ class StorageService:
blob.download_to_filename(destination_path)
logger.info(f"Downloaded gs://{settings.gcs_bucket_name}/{source_path} to {destination_path}")
return destination_path
except NotFound:
# A missing object is a routine "not found", not a server-side failure.
# Log at warning so it doesn't trip the error-monitor, and let the caller
# decide how to surface it (e.g. the download route returns HTTP 404).
logger.warning(f"Object not found downloading {source_path}")
raise
except Exception as e:
logger.error(f"Error downloading file {source_path}: {e}")
raise
def copy_blob(self, source_path: str, destination_path: str) -> str:
"""Server-side copy of a blob within the bucket (no download/upload)."""
try:
src = self.bucket.blob(source_path)
self.bucket.copy_blob(src, self.bucket, destination_path)
logger.info(f"Copied gs://{settings.gcs_bucket_name}/{source_path} -> {destination_path}")
return destination_path
except Exception as e:
logger.error(f"Error copying blob {source_path} -> {destination_path}: {e}")
raise
def generate_signed_url(self, blob_path: str, expiration_minutes: int = 60) -> str:
"""Generate a signed URL for downloading a file.
@@ -123,12 +141,31 @@ class StorageService:
logger.error(f"Error generating signed {method} URL for {blob_path}: {e}")
raise
def delete_file(self, blob_path: str) -> None:
"""Delete a file from GCS."""
def delete_file(self, blob_path: str, ignore_missing: bool = False) -> bool:
"""Delete a file from GCS.
Args:
blob_path: Path of the object to delete.
ignore_missing: If True, a missing object (404 NotFound) is treated as a
successful no-op and logged at debug level instead of error. Use for
best-effort deletes over a template of possible paths (e.g. job
restart/regen) where many files legitimately never existed.
Returns:
True if an object was actually deleted, False if it was already absent
(only possible when ignore_missing=True; otherwise a missing object raises).
"""
try:
blob = self.bucket.blob(blob_path)
blob.delete()
logger.info(f"Deleted gs://{settings.gcs_bucket_name}/{blob_path}")
return True
except NotFound:
if ignore_missing:
logger.debug(f"File already absent, skipping delete: {blob_path}")
return False
logger.error(f"Error deleting file {blob_path}: 404 object not found")
raise
except Exception as e:
logger.error(f"Error deleting file {blob_path}: {e}")
raise
+64
View File
@@ -0,0 +1,64 @@
"""Sanitize submitted review corrections so word timings stay within their segment.
Mirrors the frontend sanitizeWordTimings.ts and the render-time
SegmentResizer._sanitize_segment_timings. Operates on the raw corrections dict the
frontend POSTs (Dict[str, Any]); clamps any word whose start/end falls outside its
segment window or is inverted. Segments whose own bounds are non-finite are left
untouched (the editor derives bounds from words elsewhere). Mutates and returns the
same dict for caller convenience, plus the number of fields clamped."""
from __future__ import annotations
import math
from typing import Any, Dict, Tuple
def _finite(v: Any) -> bool:
return isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)
def sanitize_corrections(corrections: Dict[str, Any]) -> Tuple[Dict[str, Any], int]:
segments = corrections.get("corrected_segments")
if not isinstance(segments, list):
return corrections, 0
changes = 0
for seg in segments:
if not isinstance(seg, dict):
continue
seg_start = seg.get("start_time")
seg_end = seg.get("end_time")
# If the segment's own bounds aren't finite, don't touch its words.
if not _finite(seg_start) or not _finite(seg_end):
continue
seg_end = max(seg_end, seg_start)
prev_end = seg_start
for w in seg.get("words", []):
if not isinstance(w, dict):
continue
start = w.get("start_time")
end = w.get("end_time")
# Invalid start = missing/non-finite OR outside the segment window.
if _finite(start) and seg_start <= start <= seg_end:
new_start = start
else:
new_start = min(max(prev_end, seg_start), seg_end)
# Invalid end = missing/non-finite, before start, or past segment end.
if _finite(end) and new_start <= end <= seg_end:
new_end = end
else:
new_end = min(max(new_start, end if _finite(end) else new_start), seg_end)
if new_end < new_start:
new_end = new_start
if new_start != start:
w["start_time"] = new_start
changes += 1
if new_end != end:
w["end_time"] = new_end
changes += 1
prev_end = new_end
return corrections, changes
+91 -18
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,
@@ -900,12 +930,21 @@ class UserService:
return False, None, "An error occurred during validation"
def revoke_session(self, token: str) -> bool:
"""Revoke a session (logout)."""
"""Revoke a session (logout).
Idempotent: a session document that no longer exists is already
revoked, so a missing document is treated as success rather than an
error. Firestore's ``update()`` raises NotFound when the document is
absent (e.g. already logged out, or expired/cleaned up).
"""
try:
doc_ref = self.db.collection(SESSIONS_COLLECTION).document(token)
doc_ref.update({'is_active': False})
logger.info("Session revoked")
return True
except google_exceptions.NotFound:
logger.info("Session already absent; treating revoke as success")
return True
except Exception:
logger.exception("Error revoking session")
return False
@@ -1039,27 +1078,42 @@ class UserService:
logger.exception(f"Error adding credits to {email}")
return False, 0, f"Failed to add credits: {e}"
def deduct_credit(
def deduct_credits(
self,
email: str,
job_id: str,
reason: str = "job_creation"
amount: int = 1,
reason: str = "job_creation",
count_as_job_creation: bool = True,
) -> Tuple[bool, int, str]:
"""
Deduct one credit from a user account.
Atomically deduct N credits from a user account (all-or-nothing).
Uses Firestore transaction to prevent race conditions.
Args:
email: User email address.
job_id: Job ID associated with the deduction.
amount: Number of credits to deduct (default: 1, must be > 0).
reason: Reason for the deduction (default: "job_creation").
count_as_job_creation: When True (default), increments
``total_jobs_created`` by 1. Pass False when deducting
*additional* credits for an already-existing job (e.g. the
reconcile/top-up path) so the counter is not double-counted.
Returns:
(success, remaining_credits, message)
"""
if amount <= 0:
return False, 0, "Deduction amount must be positive"
try:
email = email.lower()
doc_ref = self.db.collection(USERS_COLLECTION).document(email)
@firestore.transactional
def deduct_in_transaction(transaction):
"""Atomically check and deduct credit."""
"""Atomically check and deduct credits."""
doc = doc_ref.get(transaction=transaction)
if not doc.exists:
@@ -1068,13 +1122,13 @@ class UserService:
user_data = doc.to_dict()
current_credits = user_data.get('credits', 0)
if current_credits <= 0:
return False, 0, "Insufficient credits"
if current_credits < amount:
return False, current_credits, "Insufficient credits"
# Create transaction record
credit_txn = CreditTransaction(
id=str(uuid.uuid4()),
amount=-1,
amount=-amount,
reason=reason,
job_id=job_id,
)
@@ -1086,32 +1140,51 @@ class UserService:
transactions.append(credit_txn.model_dump(mode='json'))
# Calculate new values
new_balance = current_credits - 1
total_jobs = user_data.get('total_jobs_created', 0) + 1
new_balance = current_credits - amount
# Update atomically within transaction
transaction.update(doc_ref, {
update_payload = {
'credits': new_balance,
'credit_transactions': transactions,
'total_jobs_created': total_jobs,
'updated_at': datetime.utcnow()
})
'updated_at': datetime.utcnow(),
}
if count_as_job_creation:
update_payload['total_jobs_created'] = user_data.get('total_jobs_created', 0) + 1
return True, new_balance, f"Credit deducted. {new_balance} remaining"
# Update atomically within transaction
transaction.update(doc_ref, update_payload)
return True, new_balance, f"Deducted {amount} credit(s). {new_balance} remaining"
# Execute the transaction
fs_transaction = self.db.transaction()
success, new_balance, message = deduct_in_transaction(fs_transaction)
if success:
logger.info(f"Deducted 1 credit from {email} for job {job_id}. Remaining: {new_balance}")
logger.info(f"Deducted {amount} credit(s) from {email} for job {job_id}. Remaining: {new_balance}")
return success, new_balance, message
except Exception as e:
logger.exception(f"Error deducting credit from {email}")
logger.exception(f"Error deducting credit(s) from {email}")
return False, 0, f"Failed to deduct credit: {e}"
def deduct_credit(
self,
email: str,
job_id: str,
reason: str = "job_creation"
) -> Tuple[bool, int, str]:
"""
Deduct one credit from a user account.
Thin wrapper around deduct_credits(amount=1). Preserved for backwards
compatibility with all existing callers.
Returns:
(success, remaining_credits, message)
"""
return self.deduct_credits(email, job_id, amount=1, reason=reason)
def refund_credit(
self,
email: str,
+177 -38
View File
@@ -57,61 +57,93 @@ class VisibilityChangeService:
"""
Change a public job to private (fast path).
Deletes distributed outputs (YouTube/Dropbox/GDrive) but keeps GCS finals,
then redistributes to private destination.
Distribute-then-delete: the track is first redistributed to the private
destination (private Dropbox archive + NOMADNP code, no YouTube/GDrive),
and only *after* that succeeds are the public outputs (YouTube, public
Dropbox folder, public GDrive files) deleted and the public NOMAD number
recycled. GCS finals are always kept.
This ordering is deliberate: YouTube deletion is irreversible, so nothing
public may be destroyed until the private archive exists. If redistribution
fails, the job is reverted to public and left fully intact (no partial
deletion, no leaked NOMADNP code — see redistribute_video's failure path).
"""
logger.info(f"[job:{job_id}] Starting visibility change: public -> private (by {user_email})")
db = self.job_manager.firestore.db
job_ref = db.collection("jobs").document(job_id)
# Set guard flag
# Capture the public output references BEFORE redistribution overwrites
# state_data with the new private values — we need them to delete the
# public outputs afterwards.
state_data = job.state_data or {}
public_outputs = {
"youtube_url": state_data.get("youtube_url"),
"brand_code": state_data.get("brand_code"),
"gdrive_files": state_data.get("gdrive_files"),
"dropbox_path": getattr(job, "dropbox_path", None),
"artist": job.artist,
"title": job.title,
}
# Set guard flag + flip to private so redistribution targets the private
# destination. Public outputs remain live until the private archive exists.
# No "changed to private" timeline event yet — it is only recorded once the
# move actually succeeds (this is reverted if redistribution fails).
job_ref.update({
"state_data.visibility_change_in_progress": True,
"is_private": True,
"updated_at": datetime.now(timezone.utc),
})
# Step 1: Redistribute to the private destination FIRST (public outputs
# still live). This is the only phase whose failure is safe to fully roll
# back — nothing public has been touched yet. redistribute_video verifies
# the archive actually materialized and recycles any NOMADNP code it
# allocated on failure, so a False return means "no-op, still public".
try:
# Step 1: Delete distributed outputs (keep GCS finals)
await self._delete_distributed_outputs(job_id, job, keep_gcs_finals=True)
# Step 2: Update job to private
job_ref.update({
"is_private": True,
"updated_at": datetime.now(timezone.utc),
"timeline": ArrayUnion([{
"status": "complete",
"timestamp": datetime.now(timezone.utc).isoformat(),
"message": f"Visibility changed to private by {user_email}",
}]),
})
# Step 3: Trigger redistribution via video worker
from backend.workers.video_worker import redistribute_video
success = await redistribute_video(job_id)
if not success:
raise RuntimeError("Redistribution failed - check worker logs")
# Clear guard flag (redistribution updates state_data with new brand_code etc.)
job_ref.update({
"state_data.visibility_change_in_progress": DELETE_FIELD,
})
logger.info(f"[job:{job_id}] Visibility change to private complete")
return {
"status": "success",
"message": "Job changed to private. Outputs redistributed to private destination.",
"reprocessing_required": False,
}
except Exception as e:
logger.error(f"[job:{job_id}] Visibility change to private failed: {e}", exc_info=True)
# Clear guard flag on failure
logger.error(f"[job:{job_id}] Redistribution raised during visibility change: {e}", exc_info=True)
success = False
if not success:
# Roll back to public: no public outputs were deleted, so restoring
# is_private=False leaves the job fully intact and public.
logger.error(f"[job:{job_id}] Visibility change to private failed: redistribution did not succeed")
job_ref.update({
"is_private": False,
"state_data.visibility_change_in_progress": DELETE_FIELD,
"updated_at": datetime.now(timezone.utc),
})
raise
raise RuntimeError("Redistribution failed - check worker logs")
# Step 2: Private archive now exists. From here we do NOT revert to public,
# even if public cleanup hiccups — the private move has committed. Deleting
# the public outputs + recycling the public NOMAD number is best-effort
# (each failure is logged inside the helper, never raised), so a stray
# orphaned public artifact cannot undo the successful private move.
await self._delete_public_outputs(job_id, public_outputs)
# Record the completed move and clear the guard flag. redistribute_video
# already updated state_data with the new private brand_code etc.
job_ref.update({
"state_data.visibility_change_in_progress": DELETE_FIELD,
"updated_at": datetime.now(timezone.utc),
"timeline": ArrayUnion([{
"status": "complete",
"timestamp": datetime.now(timezone.utc).isoformat(),
"message": f"Visibility changed to private by {user_email}",
}]),
})
logger.info(f"[job:{job_id}] Visibility change to private complete")
return {
"status": "success",
"message": "Job changed to private. Outputs redistributed to private destination.",
"reprocessing_required": False,
}
async def change_to_public(self, job_id: str, job, user_email: str) -> dict:
"""
@@ -141,7 +173,11 @@ class VisibilityChangeService:
f"jobs/{job_id}/videos/with_vocals.mov",
]:
try:
storage.delete_file(path)
# Best-effort delete over a template of possible artifacts; many of
# these intermediates legitimately never existed for a given render
# path. ignore_missing keeps a 404 a quiet no-op instead of a noisy
# ERROR log (which would otherwise trip the error-monitor).
storage.delete_file(path, ignore_missing=True)
except Exception:
pass
@@ -212,6 +248,103 @@ class VisibilityChangeService:
"reprocessing_required": True,
}
async def _delete_public_outputs(self, job_id: str, public_outputs: dict):
"""Delete the captured PUBLIC outputs and recycle the public NOMAD number.
Used by change_to_private AFTER a successful private redistribution. Operates
on references captured before redistribution (which overwrites state_data with
private values). Does not touch GCS finals and does not clear state_data keys
(redistribution already set the new private values). Best-effort: individual
failures are logged, not raised, so one orphaned artifact can't undo the move.
"""
import re
# Track whether each public destination was fully cleaned. The NOMAD number
# is only recycled when every deletion succeeded — otherwise a future public
# track could reuse the number while the old public files still linger,
# producing a duplicate. (Mirrors the admin delete-outputs recycle gate.)
youtube_ok = True
dropbox_ok = True
gdrive_ok = True
youtube_url = public_outputs.get("youtube_url")
if youtube_url:
try:
video_id_match = re.search(r'(?:youtu\.be/|youtube\.com/watch\?v=)([^&\s]+)', youtube_url)
if video_id_match:
video_id = video_id_match.group(1)
from karaoke_gen.karaoke_finalise.karaoke_finalise import KaraokeFinalise
from backend.services.youtube_service import get_youtube_service
youtube_service = get_youtube_service()
if youtube_service.is_configured:
finalise = KaraokeFinalise(
dry_run=False, non_interactive=True,
user_youtube_credentials=youtube_service.get_credentials_dict()
)
finalise.delete_youtube_video(video_id)
logger.info(f"[job:{job_id}] Deleted public YouTube video {video_id}")
except Exception as e:
youtube_ok = False
logger.warning(f"[job:{job_id}] Failed to delete public YouTube video: {e}")
brand_code = public_outputs.get("brand_code")
dropbox_path = public_outputs.get("dropbox_path")
if brand_code and dropbox_path:
try:
from backend.services.dropbox_service import get_dropbox_service
dropbox = get_dropbox_service()
if dropbox.is_configured:
from karaoke_gen.utils import sanitize_filename
safe_artist = sanitize_filename(public_outputs.get("artist")) if public_outputs.get("artist") else "Unknown"
safe_title = sanitize_filename(public_outputs.get("title")) if public_outputs.get("title") else "Unknown"
folder_name = f"{brand_code} - {safe_artist} - {safe_title}"
full_path = f"{dropbox_path}/{folder_name}"
dropbox.delete_folder(full_path)
logger.info(f"[job:{job_id}] Deleted public Dropbox folder {full_path}")
except Exception as e:
dropbox_ok = False
logger.warning(f"[job:{job_id}] Failed to delete public Dropbox folder: {e}")
gdrive_files = public_outputs.get("gdrive_files")
if gdrive_files:
try:
from backend.services.gdrive_service import get_gdrive_service
gdrive = get_gdrive_service()
if gdrive.is_configured:
file_ids = list(gdrive_files.values()) if isinstance(gdrive_files, dict) else []
gdrive.delete_files(file_ids)
logger.info(f"[job:{job_id}] Deleted public Google Drive files")
except Exception as e:
gdrive_ok = False
logger.warning(f"[job:{job_id}] Failed to delete public Google Drive files: {e}")
# A track going private should also leave the public Nomad GCS fast-sync
# mirror (and thus kjbox). Prefix-keyed by the public brand_code, non-fatal.
if brand_code:
try:
from backend.services.nomad_master_mirror import cleanup_nomad_masters
cleanup_nomad_masters(brand_code)
except Exception as e:
logger.warning(f"[job:{job_id}] Failed to clean up Nomad mirror for {brand_code}: {e}")
# Recycle the public NOMAD number so the next public track fills the gap —
# but only if every public deletion succeeded. If any lingered, keep the
# number reserved (a permanent gap the validator will flag) rather than
# risk a future duplicate; the leftover artifacts can then be cleaned up.
if brand_code and youtube_ok and dropbox_ok and gdrive_ok:
try:
from backend.services.brand_code_service import BrandCodeService, get_brand_code_service
prefix, number = BrandCodeService.parse_brand_code(brand_code)
get_brand_code_service().recycle_brand_code(prefix, number)
logger.info(f"[job:{job_id}] Recycled public brand code {brand_code}")
except Exception as e:
logger.warning(f"[job:{job_id}] Failed to recycle public brand code {brand_code}: {e}")
elif brand_code:
logger.warning(
f"[job:{job_id}] NOT recycling public brand code {brand_code}: "
f"public cleanup incomplete (youtube={youtube_ok}, dropbox={dropbox_ok}, gdrive={gdrive_ok})"
)
async def _delete_distributed_outputs(self, job_id: str, job, keep_gcs_finals: bool = False):
"""Delete distributed outputs (YouTube, Dropbox, GDrive) and recycle brand code."""
import re
@@ -269,6 +402,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:
+88
View File
@@ -379,6 +379,47 @@ class WorkerService:
worker_module="audio_download_worker",
)
async def trigger_bulk_search_worker(self, batch_id: str) -> bool:
"""Trigger the Bulk Mode search worker for a whole batch as a Cloud Run Job.
The worker processes every job stamped with ``batch_id``: it runs each
audio search, auto-selects confident lossless matches, and parks the rest
in AWAITING_AUDIO_SELECTION. Uses a Cloud Run Job (not BackgroundTasks) so
the batch survives API instance scale-down and the user can close the tab.
"""
try:
from google.cloud import run_v2
project = self.settings.google_cloud_project
if not project:
logger.error("GOOGLE_CLOUD_PROJECT not set, cannot trigger bulk search job")
return False
location = self.settings.gcp_region
job_name = f"projects/{project}/locations/{location}/jobs/bulk-search-job"
client = run_v2.JobsClient()
request = run_v2.RunJobRequest(
name=job_name,
overrides=run_v2.RunJobRequest.Overrides(
container_overrides=[
run_v2.RunJobRequest.Overrides.ContainerOverride(
args=[
"python", "-m", "backend.workers.bulk_search_worker",
"--batch-id", batch_id,
],
)
]
),
)
operation = client.run_job(request=request)
logger.info(f"[batch:{batch_id}] Started Cloud Run Job bulk-search-job: {operation.metadata}")
return True
except Exception as e:
logger.error(
f"[batch:{batch_id}] Failed to trigger bulk-search-job: {e}", exc_info=True
)
return False
async def trigger_audio_worker(self, job_id: str) -> bool:
"""
Trigger audio separation worker.
@@ -410,6 +451,34 @@ class WorkerService:
async def trigger_screens_worker(self, job_id: str) -> bool:
"""Trigger screen generation worker."""
return await self.trigger_worker("screens", job_id)
async def trigger_auto_correct(self, job_id: str, timeout_seconds: int = 200) -> bool:
"""Trigger proactive auto-correct generation on the API service.
Direct, awaited HTTP call (NOT Cloud Tasks): the endpoint runs the work
synchronously, so awaiting it keeps both the caller (lyrics job) and the
service instance alive until the cache is written. Best-effort — returns
False on any failure and never raises, so it can't affect the job.
"""
if not self._base_url:
logger.info(f"[job:{job_id}] auto-correct trigger skipped: no service base URL")
return False
url = f"{self._base_url}/api/internal/workers/auto-correct"
headers = {"Content-Type": "application/json"}
if self._admin_token:
headers["X-Admin-Token"] = self._admin_token
# Propagate trace context so the service-side span links to this job.
headers = inject_trace_context(headers)
try:
async with httpx.AsyncClient(timeout=timeout_seconds) as client:
resp = await client.post(url, json={"job_id": job_id}, headers=headers)
logger.info(
f"[job:{job_id}] auto-correct trigger -> HTTP {resp.status_code}"
)
return resp.status_code < 400
except Exception as e: # noqa: BLE001 — best-effort, never fatal
logger.warning(f"[job:{job_id}] auto-correct trigger failed (non-fatal): {e}")
return False
def _warmup_encoding_worker(self, job_id: str) -> None:
"""Fire-and-forget warmup of the encoding worker VM.
@@ -444,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)
@@ -537,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,
+64 -92
View File
@@ -13,16 +13,11 @@ The flow is:
All entry points (audio search selection, direct URL submission) should use this
service for YouTube downloads to ensure consistent behavior.
"""
import asyncio
import logging
import mimetypes
import os
import re
import tempfile
from typing import Optional
from .flacfetch_client import get_flacfetch_client, FlacfetchServiceError
from .storage_service import StorageService
logger = logging.getLogger(__name__)
@@ -54,14 +49,13 @@ class YouTubeDownloadService:
def __init__(self):
self._flacfetch_client = get_flacfetch_client()
self._storage_service = StorageService()
if self._flacfetch_client:
logger.info("YouTubeDownloadService using REMOTE flacfetch (recommended)")
logger.info("YouTubeDownloadService using REMOTE flacfetch")
else:
logger.warning(
"YouTubeDownloadService using LOCAL yt_dlp - "
"downloads may fail due to YouTube bot detection on Cloud Run IPs"
"YouTubeDownloadService: remote flacfetch NOT configured "
"(FLACFETCH_API_URL) - URL downloads will fail until it is set"
)
def is_remote_enabled(self) -> bool:
@@ -121,20 +115,24 @@ class YouTubeDownloadService:
Raises:
YouTubeDownloadError: If download fails
"""
video_id = self._extract_video_id(url)
if not video_id:
raise YouTubeDownloadError(f"Could not extract video ID from URL: {url}")
logger.info(f"YouTube download: video_id={video_id}, job_id={job_id}")
if self._flacfetch_client:
return await self._download_remote(video_id, job_id, artist, title)
else:
logger.warning(
"Remote flacfetch not configured. Attempting local download, "
"but this may fail due to YouTube bot detection on Cloud Run IPs."
# flacfetch is the SOLE downloader — never run yt-dlp on Cloud Run.
# If it isn't configured, fail loudly rather than silently falling back
# to a local download (which is blocked by bot detection on Cloud Run
# IPs anyway).
if not self._flacfetch_client:
raise YouTubeDownloadError(
"Remote flacfetch is not configured (FLACFETCH_API_URL). "
"URL downloads require the flacfetch service."
)
return await self._download_local(url, job_id, artist, title)
video_id = self._extract_video_id(url)
if video_id:
logger.info(f"URL download (YouTube): video_id={video_id}, job_id={job_id}")
return await self._download_remote(video_id, job_id, artist, title)
# Any other yt-dlp-supported site (Facebook, SoundCloud, TikTok, ...).
logger.info(f"URL download (generic): url={url}, job_id={job_id}")
return await self._download_remote_url(url, job_id, artist, title)
async def download_by_id(
self,
@@ -265,7 +263,7 @@ class YouTubeDownloadService:
logger.error(f"Remote YouTube download error: {e}", exc_info=True)
raise YouTubeDownloadError(f"Remote download failed: {e}") from e
async def _download_local(
async def _download_remote_url(
self,
url: str,
job_id: str,
@@ -273,92 +271,66 @@ class YouTubeDownloadService:
title: Optional[str] = None,
) -> str:
"""
Download using local yt_dlp (fallback when remote not configured).
Download an arbitrary yt-dlp-supported URL via remote flacfetch.
Warning: This may fail on Cloud Run due to YouTube bot detection.
Used for non-YouTube sites (Facebook, SoundCloud, TikTok, Vimeo, ...).
The URL is handed to flacfetch's generic "URL" source, which downloads
on the VM and uploads to GCS.
"""
temp_dir = tempfile.mkdtemp(prefix=f"youtube_{job_id}_")
gcs_destination = f"uploads/{job_id}/audio/"
output_filename = None
if artist and title:
from karaoke_gen.utils import sanitize_filename
output_filename = f"{sanitize_filename(artist)} - {sanitize_filename(title)}"
logger.info(
f"Remote URL download: url={url}, "
f"gcs_path={gcs_destination}, filename={output_filename}"
)
try:
from karaoke_gen.file_handler import FileHandler
from karaoke_gen.utils import sanitize_filename
# Create FileHandler
file_handler = FileHandler(
logger=logger,
ffmpeg_base_command="ffmpeg -hide_banner -loglevel error -nostats -y",
create_track_subfolders=False,
dry_run=False
download_id = await self._flacfetch_client.download_by_id(
source_name="URL",
source_id=url,
download_url=url,
output_filename=output_filename,
gcs_path=gcs_destination,
)
# Build output filename
safe_artist = sanitize_filename(artist) if artist else "Unknown"
safe_title = sanitize_filename(title) if title else "Unknown"
output_filename_no_extension = os.path.join(
temp_dir, f"{safe_artist} - {safe_title}"
logger.info(f"Remote URL download started: {download_id}")
def log_progress(status):
progress = status.get("progress", 0)
logger.debug(f"Download progress: {progress:.1f}%")
final_status = await self._flacfetch_client.wait_for_download(
download_id,
timeout=300,
progress_callback=log_progress,
)
# Get cookies from environment
cookies_str = os.environ.get("YOUTUBE_COOKIES")
if cookies_str:
logger.info("Using YouTube cookies for local download")
# Download
logger.info(f"Local YouTube download: {url}")
downloaded_file = file_handler.download_video(
url=url,
output_filename_no_extension=output_filename_no_extension,
cookies_str=cookies_str
)
if not downloaded_file or not os.path.exists(downloaded_file):
gcs_path = final_status.get("gcs_path")
if not gcs_path:
raise YouTubeDownloadError(
f"Local download failed - no file returned. "
"This is likely due to YouTube bot detection on Cloud Run IPs. "
"Configure FLACFETCH_API_URL for remote downloads."
"Remote download completed but no GCS path returned"
)
logger.info(f"Downloaded video: {downloaded_file}")
if gcs_path.startswith("gs://"):
parts = gcs_path.replace("gs://", "").split("/", 1)
if len(parts) == 2:
gcs_path = parts[1]
# Convert to WAV for processing
wav_file = file_handler.convert_to_wav(
input_filename=downloaded_file,
output_filename_no_extension=output_filename_no_extension
)
if not wav_file or not os.path.exists(wav_file):
raise YouTubeDownloadError("WAV conversion failed")
logger.info(f"Converted to WAV: {wav_file}")
# Upload to GCS
filename = os.path.basename(wav_file)
gcs_path = f"uploads/{job_id}/audio/{filename}"
content_type, _ = mimetypes.guess_type(wav_file)
with open(wav_file, 'rb') as f:
self._storage_service.upload_fileobj(
f,
gcs_path,
content_type=content_type or 'audio/wav'
)
logger.info(f"Uploaded to GCS: {gcs_path}")
logger.info(f"Remote URL download complete: {gcs_path}")
return gcs_path
except FlacfetchServiceError as e:
raise YouTubeDownloadError(f"Remote download failed: {e}") from e
except YouTubeDownloadError:
raise
except Exception as e:
logger.error(f"Local YouTube download error: {e}", exc_info=True)
raise YouTubeDownloadError(f"Local download failed: {e}") from e
finally:
# Cleanup temp directory
try:
import shutil
if os.path.exists(temp_dir):
shutil.rmtree(temp_dir)
except Exception as cleanup_error:
logger.warning(f"Failed to cleanup temp dir: {cleanup_error}")
logger.error(f"Remote URL download error: {e}", exc_info=True)
raise YouTubeDownloadError(f"Remote download failed: {e}") from e
# Singleton instance
@@ -0,0 +1,436 @@
"""
Tests for the parked-job recovery endpoints on audio-search:
- POST /api/audio-search/{job_id}/research — retry / edit-and-re-search
- POST /api/audio-search/{job_id}/provide-url — attach a YouTube/yt-dlp URL
- POST /api/audio-search/{job_id}/attach-upload-url — signed URL for upload
- POST /api/audio-search/{job_id}/attach-upload-complete — finalise an upload
These cover the "0 results / dead-end" bulk-mode scenario where a job is parked
in AWAITING_AUDIO_SELECTION with no usable sources and the user needs a way out.
"""
from __future__ import annotations
from datetime import datetime, UTC
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from backend.models.job import Job, JobStatus
from backend.services.audio_search_service import AudioSearchResult, NoResultsError, AudioSearchError
from backend.services.auth_service import UserType, AuthResult
from backend.services.youtube_download_service import YouTubeDownloadError
NOW = datetime.now(UTC)
@pytest.fixture(autouse=True)
def _auth_overrides():
from backend.api.dependencies import require_auth, require_admin
from backend.main import app
async def mock_require_auth():
return AuthResult(
is_valid=True, user_type=UserType.STRIPE, remaining_uses=5,
message="test", is_admin=False, user_email="buyer@example.com",
)
app.dependency_overrides[require_auth] = mock_require_auth
app.dependency_overrides[require_admin] = mock_require_auth
yield
app.dependency_overrides.pop(require_auth, None)
app.dependency_overrides.pop(require_admin, None)
def _parked_job(job_id="park-1", artist="Arctic Monkeys", title="The View From the Afternoon",
status=JobStatus.AWAITING_AUDIO_SELECTION) -> Job:
return Job(
job_id=job_id, status=status, created_at=NOW, updated_at=NOW,
user_email="buyer@example.com", artist=artist, title=title,
audio_search_artist=artist, audio_search_title=title,
state_data={"credits_charged": 1, "audio_search_results": []},
)
def _result(idx=0, title="The View From the Afternoon", artist="Arctic Monkeys"):
r = AudioSearchResult(
index=idx, title=title, artist=artist, provider="RED",
url="", duration=180, quality="FLAC", source_id=f"id{idx}",
)
r.raw_result = {"target_file": f"{title}.flac", "is_lossless": True, "seeders": 20}
return r
@pytest.fixture
def mock_job_manager():
jm = MagicMock()
jm.get_job.return_value = _parked_job()
jm.update_job.return_value = None
jm.transition_to_state.return_value = True
jm.start_job_processing = AsyncMock(return_value=None)
return jm
# ---------------------------------------------------------------------------
# research (re-search)
# ---------------------------------------------------------------------------
class TestResearch:
def _patched(self, jm, search_mock):
return patch.multiple(
"backend.api.routes.audio_search",
job_manager=jm,
), patch(
"backend.api.routes.audio_search.get_audio_search_service",
return_value=search_mock,
)
def test_research_returns_results(self, mock_job_manager):
from fastapi.testclient import TestClient
from backend.main import app
search = MagicMock()
search.search_async = AsyncMock(return_value=[_result(0), _result(1)])
search.last_remote_search_id = "remote-xyz"
p1, p2 = self._patched(mock_job_manager, search)
with p1, p2:
client = TestClient(app)
resp = client.post("/api/audio-search/park-1/research", json={})
assert resp.status_code == 200, resp.text
data = resp.json()
assert data["results_count"] == 2
assert len(data["results"]) == 2
# results were cached back onto the job
cached = [c for c in mock_job_manager.update_job.call_args_list
if "state_data.audio_search_results" in c.args[1]]
assert cached, "expected results to be cached on the job"
def test_research_empty_is_200_not_error(self, mock_job_manager):
from fastapi.testclient import TestClient
from backend.main import app
search = MagicMock()
search.search_async = AsyncMock(side_effect=NoResultsError("nothing"))
search.last_remote_search_id = None
p1, p2 = self._patched(mock_job_manager, search)
with p1, p2:
client = TestClient(app)
resp = client.post("/api/audio-search/park-1/research", json={})
assert resp.status_code == 200, resp.text
assert resp.json()["results_count"] == 0
def test_research_applies_edited_terms(self, mock_job_manager):
from fastapi.testclient import TestClient
from backend.main import app
search = MagicMock()
search.search_async = AsyncMock(return_value=[_result(0)])
search.last_remote_search_id = None
p1, p2 = self._patched(mock_job_manager, search)
with p1, p2:
client = TestClient(app)
resp = client.post(
"/api/audio-search/park-1/research",
json={"artist": "Arctic Monkeys", "title": "The View from the Afternoon"},
)
assert resp.status_code == 200, resp.text
# search ran with the edited (normalized) title
search.search_async.assert_awaited_once()
args = search.search_async.await_args.args
assert args[0] == "Arctic Monkeys"
assert args[1] == "The View from the Afternoon"
# edit applied to the job (search terms + display metadata)
applied = [c for c in mock_job_manager.update_job.call_args_list
if c.args[1].get("title") == "The View from the Afternoon"]
assert applied, "expected edited title applied to job"
def test_research_502_on_search_error(self, mock_job_manager):
from fastapi.testclient import TestClient
from backend.main import app
search = MagicMock()
search.search_async = AsyncMock(side_effect=AudioSearchError("boom"))
p1, p2 = self._patched(mock_job_manager, search)
with p1, p2:
client = TestClient(app)
resp = client.post("/api/audio-search/park-1/research", json={})
assert resp.status_code == 502
def test_research_rejects_wrong_status(self, mock_job_manager):
from fastapi.testclient import TestClient
from backend.main import app
mock_job_manager.get_job.return_value = _parked_job(status=JobStatus.DOWNLOADING)
search = MagicMock()
search.search_async = AsyncMock(return_value=[])
p1, p2 = self._patched(mock_job_manager, search)
with p1, p2:
client = TestClient(app)
resp = client.post("/api/audio-search/park-1/research", json={})
assert resp.status_code == 400
search.search_async.assert_not_awaited()
def test_research_404_missing_job(self, mock_job_manager):
from fastapi.testclient import TestClient
from backend.main import app
mock_job_manager.get_job.return_value = None
search = MagicMock()
p1, p2 = self._patched(mock_job_manager, search)
with p1, p2:
client = TestClient(app)
resp = client.post("/api/audio-search/nope/research", json={})
assert resp.status_code == 404
# ---------------------------------------------------------------------------
# provide-url
# ---------------------------------------------------------------------------
class TestProvideUrl:
def test_youtube_url_uses_async_worker(self, mock_job_manager):
"""YouTube URLs go through the async download worker (no blocking request)."""
from fastapi.testclient import TestClient
from backend.main import app
yt = MagicMock()
yt.check_availability = AsyncMock(return_value={"available": True})
yt.download = AsyncMock()
ws = MagicMock()
ws.trigger_audio_download_worker = AsyncMock(return_value=True)
with patch.multiple("backend.api.routes.audio_search", job_manager=mock_job_manager), \
patch("backend.api.routes.audio_search.get_youtube_download_service", return_value=yt), \
patch("backend.api.routes.audio_search.get_worker_service", return_value=ws):
client = TestClient(app)
resp = client.post(
"/api/audio-search/park-1/provide-url",
json={"url": "https://www.youtube.com/watch?v=abcdefghijk"},
)
assert resp.status_code == 200, resp.text
ws.trigger_audio_download_worker.assert_awaited_once_with("park-1")
yt.download.assert_not_awaited() # async worker does the download, not inline
# job pointed at the URL source for the worker's job-level fallback
srcd = [c for c in mock_job_manager.update_job.call_args_list
if c.args[1].get("source_name") == "YouTube" and c.args[1].get("download_url")]
assert srcd
def test_youtube_worker_trigger_failure_requeues(self, mock_job_manager):
from fastapi.testclient import TestClient
from backend.main import app
yt = MagicMock()
yt.check_availability = AsyncMock(return_value={"available": True})
ws = MagicMock()
ws.trigger_audio_download_worker = AsyncMock(return_value=False)
with patch.multiple("backend.api.routes.audio_search", job_manager=mock_job_manager), \
patch("backend.api.routes.audio_search.get_youtube_download_service", return_value=yt), \
patch("backend.api.routes.audio_search.get_worker_service", return_value=ws):
client = TestClient(app)
resp = client.post(
"/api/audio-search/park-1/provide-url",
json={"url": "https://www.youtube.com/watch?v=abcdefghijk"},
)
assert resp.status_code == 502
statuses = [c.kwargs.get("new_status") for c in mock_job_manager.transition_to_state.call_args_list]
assert JobStatus.AWAITING_AUDIO_SELECTION in statuses
def test_generic_url_downloads_inline_and_starts(self, mock_job_manager):
"""Non-YouTube (yt-dlp) URLs download inline, then start processing."""
from fastapi.testclient import TestClient
from backend.main import app
yt = MagicMock()
yt.download = AsyncMock(return_value="uploads/park-1/audio/song.opus")
with patch.multiple("backend.api.routes.audio_search", job_manager=mock_job_manager), \
patch("backend.api.routes.audio_search.get_youtube_download_service", return_value=yt):
client = TestClient(app)
resp = client.post(
"/api/audio-search/park-1/provide-url",
json={"url": "https://soundcloud.com/artist/track"},
)
assert resp.status_code == 200, resp.text
yt.download.assert_awaited_once()
pathed = [c for c in mock_job_manager.update_job.call_args_list
if c.args[1].get("input_media_gcs_path") == "uploads/park-1/audio/song.opus"]
assert pathed
mock_job_manager.start_job_processing.assert_awaited()
def test_drm_url_rejected(self, mock_job_manager):
from fastapi.testclient import TestClient
from backend.main import app
yt = MagicMock()
with patch.multiple("backend.api.routes.audio_search", job_manager=mock_job_manager), \
patch("backend.api.routes.audio_search.get_youtube_download_service", return_value=yt):
client = TestClient(app)
resp = client.post(
"/api/audio-search/park-1/provide-url",
json={"url": "https://open.spotify.com/track/xyz"},
)
assert resp.status_code == 400
def test_unavailable_youtube_rejected(self, mock_job_manager):
from fastapi.testclient import TestClient
from backend.main import app
yt = MagicMock()
yt.check_availability = AsyncMock(return_value={"available": False, "is_private": True})
ws = MagicMock()
ws.trigger_audio_download_worker = AsyncMock(return_value=True)
with patch.multiple("backend.api.routes.audio_search", job_manager=mock_job_manager), \
patch("backend.api.routes.audio_search.get_youtube_download_service", return_value=yt), \
patch("backend.api.routes.audio_search.get_worker_service", return_value=ws):
client = TestClient(app)
resp = client.post(
"/api/audio-search/park-1/provide-url",
json={"url": "https://www.youtube.com/watch?v=abcdefghijk"},
)
assert resp.status_code == 400
ws.trigger_audio_download_worker.assert_not_awaited()
def test_generic_download_failure_requeues_and_502(self, mock_job_manager):
from fastapi.testclient import TestClient
from backend.main import app
yt = MagicMock()
yt.download = AsyncMock(side_effect=YouTubeDownloadError("dead"))
with patch.multiple("backend.api.routes.audio_search", job_manager=mock_job_manager), \
patch("backend.api.routes.audio_search.get_youtube_download_service", return_value=yt):
client = TestClient(app)
resp = client.post(
"/api/audio-search/park-1/provide-url",
json={"url": "https://soundcloud.com/artist/track"},
)
assert resp.status_code == 502
# restored to awaiting so the user can retry
statuses = [c.kwargs.get("new_status") for c in mock_job_manager.transition_to_state.call_args_list]
assert JobStatus.AWAITING_AUDIO_SELECTION in statuses
def test_provide_url_rejects_wrong_status(self, mock_job_manager):
from fastapi.testclient import TestClient
from backend.main import app
mock_job_manager.get_job.return_value = _parked_job(status=JobStatus.DOWNLOADING)
yt = MagicMock()
with patch.multiple("backend.api.routes.audio_search", job_manager=mock_job_manager), \
patch("backend.api.routes.audio_search.get_youtube_download_service", return_value=yt):
client = TestClient(app)
resp = client.post(
"/api/audio-search/park-1/provide-url",
json={"url": "https://www.youtube.com/watch?v=abcdefghijk"},
)
assert resp.status_code == 400
# ---------------------------------------------------------------------------
# attach upload
# ---------------------------------------------------------------------------
class TestAttachUpload:
def test_attach_upload_url_returns_signed_url(self, mock_job_manager):
from fastapi.testclient import TestClient
from backend.main import app
storage = MagicMock()
storage.generate_signed_upload_url.return_value = "https://signed.example/put"
with patch.multiple("backend.api.routes.audio_search",
job_manager=mock_job_manager, storage_service=storage):
client = TestClient(app)
resp = client.post(
"/api/audio-search/park-1/attach-upload-url",
json={"filename": "my song.flac", "content_type": "audio/flac"},
)
assert resp.status_code == 200, resp.text
data = resp.json()
assert data["gcs_path"] == "uploads/park-1/audio/my song.flac"
assert data["upload_url"] == "https://signed.example/put"
def test_attach_upload_url_rejects_bad_extension(self, mock_job_manager):
from fastapi.testclient import TestClient
from backend.main import app
storage = MagicMock()
storage.generate_signed_upload_url.return_value = "https://signed.example/put"
with patch.multiple("backend.api.routes.audio_search",
job_manager=mock_job_manager, storage_service=storage):
client = TestClient(app)
resp = client.post(
"/api/audio-search/park-1/attach-upload-url",
json={"filename": "..\\evil.exe", "content_type": "application/octet-stream"},
)
assert resp.status_code == 400
storage.generate_signed_upload_url.assert_not_called()
def test_attach_complete_starts_processing(self, mock_job_manager):
from fastapi.testclient import TestClient
from backend.main import app
storage = MagicMock()
storage.list_files.return_value = ["uploads/park-1/audio/my_song.flac"]
with patch.multiple("backend.api.routes.audio_search",
job_manager=mock_job_manager, storage_service=storage):
client = TestClient(app)
resp = client.post(
"/api/audio-search/park-1/attach-upload-complete",
json={"gcs_path": "uploads/park-1/audio/my_song.flac"},
)
assert resp.status_code == 200, resp.text
pathed = [c for c in mock_job_manager.update_job.call_args_list
if c.args[1].get("input_media_gcs_path") == "uploads/park-1/audio/my_song.flac"]
assert pathed
mock_job_manager.start_job_processing.assert_awaited()
def test_attach_complete_rejects_gcs_path_outside_prefix(self, mock_job_manager):
from fastapi.testclient import TestClient
from backend.main import app
storage = MagicMock()
storage.list_files.return_value = ["uploads/park-1/audio/my_song.flac"]
with patch.multiple("backend.api.routes.audio_search",
job_manager=mock_job_manager, storage_service=storage):
client = TestClient(app)
resp = client.post(
"/api/audio-search/park-1/attach-upload-complete",
json={"gcs_path": "uploads/other-job/audio/steal.flac"},
)
assert resp.status_code == 400
mock_job_manager.start_job_processing.assert_not_awaited()
def test_attach_complete_400_when_no_file(self, mock_job_manager):
from fastapi.testclient import TestClient
from backend.main import app
storage = MagicMock()
storage.list_files.return_value = []
with patch.multiple("backend.api.routes.audio_search",
job_manager=mock_job_manager, storage_service=storage):
client = TestClient(app)
resp = client.post("/api/audio-search/park-1/attach-upload-complete", json={})
assert resp.status_code == 400
mock_job_manager.start_job_processing.assert_not_awaited()
@@ -0,0 +1,573 @@
"""
Tests for duration-based credit delta-charge on audio-search /select.
Covers:
- result with duration=1500s (25 min → 3 credits), credits_charged=1 → deducts 2 MORE,
credits_charged becomes 3, count_as_job_creation=False, duration_estimate_source=search_metadata
- result with duration=4000s (over 60 min) → 422, no deduction, no download
- insufficient credits for top-up → 402
- result with no duration → owed 0, no deduction, selection proceeds
- acknowledged_credits mismatch → 409
"""
from __future__ import annotations
from datetime import datetime, UTC
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from backend.models.job import Job, JobStatus
from backend.services.auth_service import UserType, AuthResult
NOW = datetime.now(UTC)
# ---------------------------------------------------------------------------
# Auth fixtures
# ---------------------------------------------------------------------------
@pytest.fixture(autouse=True)
def _ensure_auth_overrides():
"""Ensure auth dependency overrides are set for every test in this file."""
from backend.api.dependencies import require_auth, require_admin
from backend.main import app
async def mock_require_auth():
return AuthResult(
is_valid=True,
user_type=UserType.STRIPE,
remaining_uses=5,
message="Regular test user",
is_admin=False,
user_email="buyer@example.com",
)
app.dependency_overrides[require_auth] = mock_require_auth
app.dependency_overrides[require_admin] = mock_require_auth
yield
app.dependency_overrides.pop(require_auth, None)
app.dependency_overrides.pop(require_admin, None)
# ---------------------------------------------------------------------------
# Helpers: build mock jobs
# ---------------------------------------------------------------------------
def _awaiting_selection_job(
job_id: str = "sel-job-1",
credits_charged: int = 1,
user_email: str = "buyer@example.com",
search_results: list | None = None,
) -> Job:
"""A job in AWAITING_AUDIO_SELECTION with audio_search_results in state_data."""
if search_results is None:
search_results = [
{
"title": "Waterloo",
"artist": "ABBA",
"provider": "RED",
"quality": "FLAC",
"source_id": "abc123",
"target_file": "Waterloo.flac",
"url": "",
"duration": 300,
}
]
return Job(
job_id=job_id,
status=JobStatus.AWAITING_AUDIO_SELECTION,
created_at=NOW,
updated_at=NOW,
user_email=user_email,
state_data={
"credits_charged": credits_charged,
"audio_search_results": search_results,
},
)
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@pytest.fixture
def mock_job_manager():
jm = MagicMock()
jm.get_job.return_value = _awaiting_selection_job()
jm.update_job.return_value = None
jm.transition_to_state.return_value = True
return jm
@pytest.fixture
def mock_user_service():
us = MagicMock()
us.deduct_credits.return_value = (True, 3, "ok")
return us
@pytest.fixture
def mock_worker_service():
ws = MagicMock()
ws.trigger_audio_download_worker = AsyncMock(return_value=True)
return ws
@pytest.fixture
def patched_app(mock_job_manager, mock_user_service, mock_worker_service):
"""Patch module-level singletons in audio_search route and yield TestClient."""
from fastapi.testclient import TestClient
from backend.main import app
with (
patch("backend.api.routes.audio_search.job_manager", mock_job_manager),
patch(
"backend.api.routes.audio_search.get_user_service",
return_value=mock_user_service,
),
patch(
"backend.api.routes.audio_search.get_worker_service",
return_value=mock_worker_service,
),
patch("backend.api.routes.audio_search.get_audio_search_service", return_value=MagicMock()),
):
yield TestClient(app), mock_job_manager, mock_user_service, mock_worker_service
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _post_select(client, job_id="sel-job-1", *, selection_index=0, **extra):
body = {"selection_index": selection_index}
body.update(extra)
return client.post(f"/api/audio-search/{job_id}/select", json=body)
# ---------------------------------------------------------------------------
# Tests
# ---------------------------------------------------------------------------
class TestSelectPricingDeltaCharge:
"""
Duration 1500s (25 min) → ceil(1500/600) = 3 credits.
credits_charged=1 at search time → owed=2 MORE credits.
"""
def _job_1500s(self) -> Job:
return _awaiting_selection_job(
credits_charged=1,
search_results=[
{
"title": "Long Song",
"artist": "Artist",
"provider": "RED",
"quality": "FLAC",
"source_id": "abc999",
"target_file": "long.flac",
"url": "",
"duration": 1500,
}
],
)
def test_returns_200(self, patched_app):
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_1500s()
resp = _post_select(client)
assert resp.status_code == 200, resp.text
def test_deducts_delta_2_credits(self, patched_app):
"""owed = duration_to_credits(1500) - credits_charged = 3 - 1 = 2."""
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_1500s()
_post_select(client)
us.deduct_credits.assert_called_once()
args, kwargs = us.deduct_credits.call_args
amount = kwargs.get("amount", args[2] if len(args) > 2 else None)
assert amount == 2, f"Expected delta deduction of 2, got {amount}"
def test_count_as_job_creation_false(self, patched_app):
"""Job was already counted at create_job; must NOT double-count."""
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_1500s()
_post_select(client)
us.deduct_credits.assert_called_once()
args, kwargs = us.deduct_credits.call_args
flag = kwargs.get("count_as_job_creation", args[4] if len(args) > 4 else True)
assert flag is False, "must pass count_as_job_creation=False"
def test_credits_charged_updated_to_3(self, patched_app):
"""After deduction, job_manager.update_job must store credits_charged=3."""
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_1500s()
_post_select(client)
# Collect all update_job calls and look for credits_charged update
all_payloads: dict = {}
for call in jm.update_job.call_args_list:
args, kwargs = call
payload = args[1] if len(args) >= 2 else kwargs.get("updates", {})
if isinstance(payload, dict):
all_payloads.update(payload)
assert all_payloads.get("state_data.credits_charged") == 3, (
f"Expected state_data.credits_charged=3 in update_job payload, got: {all_payloads}"
)
def test_duration_estimate_stored(self, patched_app):
"""duration_estimate_seconds and duration_estimate_source must be persisted."""
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_1500s()
_post_select(client)
all_payloads: dict = {}
for call in jm.update_job.call_args_list:
args, kwargs = call
payload = args[1] if len(args) >= 2 else kwargs.get("updates", {})
if isinstance(payload, dict):
all_payloads.update(payload)
assert all_payloads.get("state_data.duration_estimate_seconds") == 1500, (
f"Expected duration_estimate_seconds=1500 in update_job, got: {all_payloads}"
)
assert all_payloads.get("state_data.duration_estimate_source") == "search_metadata", (
f"Expected duration_estimate_source='search_metadata' in update_job, got: {all_payloads}"
)
def test_download_worker_triggered_after_deduction(self, patched_app):
"""Download must be triggered AFTER the credit deduction succeeds."""
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_1500s()
_post_select(client)
ws.trigger_audio_download_worker.assert_called_once_with("sel-job-1")
class TestSelectPricingOverLimit:
"""Duration 4000s > 3600s → is_blocked=True → 422 before download."""
def _job_4000s(self) -> Job:
return _awaiting_selection_job(
credits_charged=1,
search_results=[
{
"title": "Mashup",
"artist": "DJ",
"provider": "RED",
"quality": "FLAC",
"source_id": "big999",
"target_file": "mashup.flac",
"url": "",
"duration": 4000,
}
],
)
def test_returns_422(self, patched_app):
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_4000s()
resp = _post_select(client)
assert resp.status_code == 422, resp.text
def test_no_deduction(self, patched_app):
"""Over-limit: no credits deducted."""
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_4000s()
_post_select(client)
us.deduct_credits.assert_not_called()
def test_no_download_triggered(self, patched_app):
"""Over-limit: download worker must NOT be triggered."""
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_4000s()
_post_select(client)
ws.trigger_audio_download_worker.assert_not_called()
class TestSelectPricingInsufficientCredits:
"""Top-up deduction fails → 402 Insufficient Credits."""
def _job_1500s(self) -> Job:
return _awaiting_selection_job(
credits_charged=1,
search_results=[
{
"title": "Long Song",
"artist": "Artist",
"provider": "RED",
"quality": "FLAC",
"source_id": "abc999",
"target_file": "long.flac",
"url": "",
"duration": 1500,
}
],
)
def test_returns_402_when_deduction_fails(self, patched_app):
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_1500s()
us.deduct_credits.return_value = (False, 0, "Insufficient credits")
resp = _post_select(client)
assert resp.status_code == 402, resp.text
def test_no_download_on_insufficient_credits(self, patched_app):
"""If deduction fails, download worker must NOT be triggered."""
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_1500s()
us.deduct_credits.return_value = (False, 0, "Insufficient credits")
_post_select(client)
ws.trigger_audio_download_worker.assert_not_called()
class TestSelectPricingNoDuration:
"""Result has duration=None → owed=0, no deduction, selection proceeds normally."""
def _job_no_duration(self) -> Job:
return _awaiting_selection_job(
credits_charged=1,
search_results=[
{
"title": "Unknown Length",
"artist": "Band",
"provider": "RED",
"quality": "FLAC",
"source_id": "no-dur-001",
"target_file": "unknown.flac",
"url": "",
# No 'duration' key — simulates missing duration
}
],
)
def test_returns_200(self, patched_app):
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_no_duration()
resp = _post_select(client)
assert resp.status_code == 200, resp.text
def test_no_deduction_when_no_duration(self, patched_app):
"""duration=None → owed=0 → no deduction call."""
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_no_duration()
_post_select(client)
us.deduct_credits.assert_not_called()
def test_download_still_triggered(self, patched_app):
"""Even without duration, the download worker must fire."""
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_no_duration()
_post_select(client)
ws.trigger_audio_download_worker.assert_called_once()
class TestSelectPricingAcknowledgedCreditsMismatch:
"""
acknowledged_credits sent but doesn't match server's target_total → 409.
"""
def _job_1500s(self) -> Job:
return _awaiting_selection_job(
credits_charged=1,
search_results=[
{
"title": "Long Song",
"artist": "Artist",
"provider": "RED",
"quality": "FLAC",
"source_id": "abc999",
"target_file": "long.flac",
"url": "",
"duration": 1500,
}
],
)
def test_mismatch_returns_409(self, patched_app):
"""target_total=3 (1500s), client sends acknowledged_credits=2 → 409."""
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_1500s()
resp = _post_select(client, acknowledged_credits=2)
assert resp.status_code == 409, resp.text
def test_no_deduction_on_mismatch(self, patched_app):
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_1500s()
_post_select(client, acknowledged_credits=2)
us.deduct_credits.assert_not_called()
def test_no_download_on_mismatch(self, patched_app):
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_1500s()
_post_select(client, acknowledged_credits=2)
ws.trigger_audio_download_worker.assert_not_called()
def test_correct_acknowledged_credits_succeeds(self, patched_app):
"""target_total=3, acknowledged_credits=3 → 200."""
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_1500s()
resp = _post_select(client, acknowledged_credits=3)
assert resp.status_code == 200, resp.text
class TestSelectPricingIdempotencyGuard:
"""
When select_charge_applied=True is already set in state_data, a repeated /select
call must NOT deduct any credits, regardless of what owed would compute to.
"""
def _job_already_charged(self) -> Job:
"""Job that has already had its delta charge applied (select_charge_applied=True)."""
return _awaiting_selection_job(
credits_charged=3,
search_results=[
{
"title": "Long Song",
"artist": "Artist",
"provider": "RED",
"quality": "FLAC",
"source_id": "abc999",
"target_file": "long.flac",
"url": "",
# duration=1500 → target_total=3; without guard, owed=3-3=0.
# But seed credits_charged=3 so owed is already 0 here.
# Use duration=1500 to confirm that even if recalculated it stays 0.
"duration": 1500,
}
],
)
def _job_already_charged_would_owe(self) -> Job:
"""
Job with select_charge_applied=True but credits_charged still at 1,
meaning WITHOUT the guard the code would try to charge 2 more credits.
This proves the guard short-circuits based on the flag, not the math.
"""
job = _awaiting_selection_job(
credits_charged=1,
search_results=[
{
"title": "Long Song",
"artist": "Artist",
"provider": "RED",
"quality": "FLAC",
"source_id": "abc999",
"target_file": "long.flac",
"url": "",
"duration": 1500, # would owe 2 credits without guard
}
],
)
# Inject the flag that marks the charge as already applied
job.state_data["select_charge_applied"] = True
return job
def test_reselect_does_not_double_charge(self, patched_app):
"""
Job with select_charge_applied=True and credits_charged=1, duration=1500
(owed=2 without guard) → deduct_credits must NOT be called.
"""
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_already_charged_would_owe()
resp = _post_select(client)
assert resp.status_code == 200, resp.text
us.deduct_credits.assert_not_called()
def test_reselect_does_not_change_credits_charged(self, patched_app):
"""
When the guard fires, update_job must NOT include a credits_charged update.
"""
client, jm, us, ws = patched_app
jm.get_job.return_value = self._job_already_charged_would_owe()
_post_select(client)
# Collect all update_job calls
all_payloads: dict = {}
for call in jm.update_job.call_args_list:
args, kwargs = call
payload = args[1] if len(args) >= 2 else kwargs.get("updates", {})
if isinstance(payload, dict):
all_payloads.update(payload)
assert "state_data.credits_charged" not in all_payloads, (
f"credits_charged must not be updated on repeat select; got: {all_payloads}"
)
def test_first_select_sets_flag(self, patched_app):
"""
A first-time /select (select_charge_applied absent) must write
select_charge_applied=True into the update_job payload.
"""
client, jm, us, ws = patched_app
# Use a job WITHOUT the flag set
jm.get_job.return_value = _awaiting_selection_job(
credits_charged=1,
search_results=[
{
"title": "Long Song",
"artist": "Artist",
"provider": "RED",
"quality": "FLAC",
"source_id": "abc999",
"target_file": "long.flac",
"url": "",
"duration": 1500,
}
],
)
resp = _post_select(client)
assert resp.status_code == 200, resp.text
all_payloads: dict = {}
for call in jm.update_job.call_args_list:
args, kwargs = call
payload = args[1] if len(args) >= 2 else kwargs.get("updates", {})
if isinstance(payload, dict):
all_payloads.update(payload)
assert all_payloads.get("state_data.select_charge_applied") is True, (
f"Expected select_charge_applied=True in update_job payload; got: {all_payloads}"
)
+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
+498
View File
@@ -0,0 +1,498 @@
"""
Tests for POST /api/jobs/{job_id}/confirm-duration endpoint.
Covers:
- reconcile path: deduct pending_additional_credits, trigger workers
- preflight path: deduct pending_additional_credits (delta, not full cost), trigger workers
- insufficient credits → 402
- acknowledged_credits mismatch → 409
- wrong status → 409
- not found / not owner → 404
"""
from __future__ import annotations
import asyncio
from datetime import datetime, UTC
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from backend.models.job import Job, JobStatus
from backend.services.auth_service import UserType, AuthResult
NOW = datetime.now(UTC)
@pytest.fixture(autouse=True)
def _ensure_auth_overrides():
"""Ensure auth dependency overrides are set for every test in this file.
Mirrors the pattern used by test_audio_edit_routes.py — necessary because
the conftest autouse fixture can be cleared by intervening tests when running
the whole suite with -k filters.
"""
from backend.api.dependencies import require_auth, require_admin
from backend.main import app
async def mock_require_auth():
return AuthResult(
is_valid=True,
user_type=UserType.ADMIN,
remaining_uses=999,
message="Test admin token",
is_admin=True,
user_email="test@example.com",
)
app.dependency_overrides[require_auth] = mock_require_auth
app.dependency_overrides[require_admin] = mock_require_auth
yield
app.dependency_overrides.pop(require_auth, None)
app.dependency_overrides.pop(require_admin, None)
def _job(**kwargs) -> Job:
defaults = dict(
job_id="job-dur-1",
created_at=NOW,
updated_at=NOW,
user_email="owner@example.com",
)
defaults.update(kwargs)
return Job(**defaults)
def _dur_confirm_job_reconcile(
job_id="job-dur-1",
credits_charged=2,
pending_additional_credits=1,
user_email="owner@example.com",
):
"""Job in AWAITING_DURATION_CONFIRM with reason=reconcile."""
return _job(
job_id=job_id,
status=JobStatus.AWAITING_DURATION_CONFIRM,
user_email=user_email,
state_data={
"duration_confirm_reason": "reconcile",
"credits_charged": credits_charged,
"pending_additional_credits": pending_additional_credits,
},
)
def _dur_confirm_job_preflight(
job_id="job-dur-2",
credits_charged=1,
pending_additional_credits=2,
user_email="owner@example.com",
):
"""Job in AWAITING_DURATION_CONFIRM with reason=preflight.
Delta model: create_job already charged 1 credit; the upload's duration
estimate (e.g. ~25 min / 3-credit song) means 2 MORE credits are owed.
pending_additional_credits=2, credits_charged=1, expected_total=3.
"""
return _job(
job_id=job_id,
status=JobStatus.AWAITING_DURATION_CONFIRM,
user_email=user_email,
state_data={
"duration_confirm_reason": "preflight",
"credits_charged": credits_charged,
"pending_additional_credits": pending_additional_credits,
},
)
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@pytest.fixture
def mock_job_manager():
jm = MagicMock()
jm.get_job.return_value = _dur_confirm_job_reconcile()
jm.update_job.return_value = None
jm.update_state_data.return_value = None
jm.transition_to_state.return_value = True
return jm
@pytest.fixture
def mock_user_service():
us = MagicMock()
# Default: successful deduction
us.deduct_credits.return_value = (True, 10, "ok")
return us
@pytest.fixture
def mock_worker_service():
ws = MagicMock()
ws.trigger_audio_worker = AsyncMock(return_value=True)
ws.trigger_lyrics_worker = AsyncMock(return_value=True)
return ws
@pytest.fixture
def patched_app(mock_job_manager, mock_user_service, mock_worker_service):
"""Patch module-level singletons and yield the TestClient."""
from fastapi.testclient import TestClient
from backend.main import app
# get_user_service and get_worker_service are called at request-time inside the
# endpoint (not at module load), so we patch them where they are looked up:
# get_user_service at the jobs module scope, get_worker_service at the module level.
with (
patch("backend.api.routes.jobs.job_manager", mock_job_manager),
patch(
"backend.api.routes.jobs.get_user_service",
return_value=mock_user_service,
),
patch(
"backend.api.routes.jobs.get_worker_service",
return_value=mock_worker_service,
),
):
yield TestClient(app), mock_job_manager, mock_user_service, mock_worker_service
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _post(client, job_id, acknowledged_credits):
return client.post(
f"/api/jobs/{job_id}/confirm-duration",
json={"acknowledged_credits": acknowledged_credits},
)
# ---------------------------------------------------------------------------
# Test classes
# ---------------------------------------------------------------------------
class TestConfirmDurationReconcile:
"""Reconcile path: credits_charged=2, pending_additional_credits=1, owed=1, expected_total=3."""
def test_returns_200_and_deducts_one_credit(self, patched_app):
client, jm, us, ws = patched_app
jm.get_job.return_value = _dur_confirm_job_reconcile(
credits_charged=2, pending_additional_credits=1
)
resp = _post(client, "job-dur-1", acknowledged_credits=3)
assert resp.status_code == 200, resp.text
# Verify deduct was called with count_as_job_creation=False
us.deduct_credits.assert_called_once()
call_kwargs = us.deduct_credits.call_args
args, kwargs = call_kwargs
# Signature: deduct_credits(email, job_id, amount, reason, count_as_job_creation)
assert kwargs.get("amount", args[2] if len(args) > 2 else None) == 1
assert kwargs.get("reason", args[3] if len(args) > 3 else None) == "duration_confirm"
count_flag = kwargs.get(
"count_as_job_creation", args[4] if len(args) > 4 else True
)
assert count_flag is False, "reconcile top-up must NOT increment total_jobs_created"
def test_state_data_updated_after_confirm(self, patched_app):
client, jm, us, ws = patched_app
jm.get_job.return_value = _dur_confirm_job_reconcile(
credits_charged=2, pending_additional_credits=1
)
resp = _post(client, "job-dur-1", acknowledged_credits=3)
assert resp.status_code == 200, resp.text
# update_job must have been called to persist state changes
jm.update_job.assert_called()
def test_returns_job_in_response(self, patched_app):
client, jm, us, ws = patched_app
jm.get_job.return_value = _dur_confirm_job_reconcile()
resp = _post(client, "job-dur-1", acknowledged_credits=3)
assert resp.status_code == 200, resp.text
body = resp.json()
assert "job_id" in body
def test_insufficient_credits_returns_402(self, patched_app):
client, jm, us, ws = patched_app
jm.get_job.return_value = _dur_confirm_job_reconcile(
credits_charged=2, pending_additional_credits=1
)
us.deduct_credits.return_value = (False, 0, "Insufficient credits")
resp = _post(client, "job-dur-1", acknowledged_credits=3)
assert resp.status_code == 402, resp.text
def test_acknowledged_mismatch_returns_409(self, patched_app):
"""Client sends acknowledged_credits=99, expected is 3 → 409."""
client, jm, us, ws = patched_app
jm.get_job.return_value = _dur_confirm_job_reconcile(
credits_charged=2, pending_additional_credits=1
)
resp = _post(client, "job-dur-1", acknowledged_credits=99)
assert resp.status_code == 409, resp.text
# No credits should be deducted
us.deduct_credits.assert_not_called()
def test_workers_triggered_on_success(self, patched_app):
"""Verify that create_task was called (worker trigger fired)."""
client, jm, us, ws = patched_app
jm.get_job.return_value = _dur_confirm_job_reconcile()
with patch("backend.api.routes.jobs.asyncio.create_task") as mock_ct:
mock_ct.return_value = MagicMock()
resp = _post(client, "job-dur-1", acknowledged_credits=3)
assert resp.status_code == 200, resp.text
mock_ct.assert_called_once()
def test_workers_not_triggered_on_credit_failure(self, patched_app):
"""If deduction fails, workers must NOT be triggered."""
client, jm, us, ws = patched_app
jm.get_job.return_value = _dur_confirm_job_reconcile()
us.deduct_credits.return_value = (False, 0, "Insufficient credits")
with patch("backend.api.routes.jobs.asyncio.create_task") as mock_ct:
resp = _post(client, "job-dur-1", acknowledged_credits=3)
assert resp.status_code == 402
mock_ct.assert_not_called()
class TestConfirmDurationPreflight:
"""Preflight path (delta model): credits_charged=1, pending_additional_credits=2, owed=2, expected_total=3.
create_job charged 1 credit at upload time; the pause-creating site computed
pending_additional_credits=2 as the delta for a ~25-min (3-credit) song.
confirm_duration deducts ONLY the delta (2), bringing credits_charged to 3.
"""
def test_preflight_returns_200(self, patched_app):
client, jm, us, ws = patched_app
jm.get_job.return_value = _dur_confirm_job_preflight(
credits_charged=1, pending_additional_credits=2
)
resp = _post(client, "job-dur-2", acknowledged_credits=3)
assert resp.status_code == 200, resp.text
def test_preflight_deducts_delta_only(self, patched_app):
"""Delta model: only deduct pending_additional_credits (2), not the full cost (3)."""
client, jm, us, ws = patched_app
jm.get_job.return_value = _dur_confirm_job_preflight(
credits_charged=1, pending_additional_credits=2
)
resp = _post(client, "job-dur-2", acknowledged_credits=3)
assert resp.status_code == 200, resp.text
us.deduct_credits.assert_called_once()
call_args, call_kwargs = us.deduct_credits.call_args
amount = call_kwargs.get("amount", call_args[2] if len(call_args) > 2 else None)
assert amount == 2, (
"preflight must deduct the delta (pending_additional_credits=2), "
"not the full cost — create_job already charged 1 credit"
)
def test_preflight_count_as_job_creation_false(self, patched_app):
"""Preflight uses count_as_job_creation=False (job was already counted at creation)."""
client, jm, us, ws = patched_app
jm.get_job.return_value = _dur_confirm_job_preflight(
credits_charged=1, pending_additional_credits=2
)
resp = _post(client, "job-dur-2", acknowledged_credits=3)
assert resp.status_code == 200, resp.text
call_args, call_kwargs = us.deduct_credits.call_args
count_flag = call_kwargs.get(
"count_as_job_creation",
call_args[4] if len(call_args) > 4 else True,
)
assert count_flag is False, (
"preflight: job already counted at create_job() credit deduction; "
"do not double-count total_jobs_created"
)
def test_preflight_credits_charged_becomes_total(self, patched_app):
"""After confirm, credits_charged should be updated to credits_charged + owed = 3."""
client, jm, us, ws = patched_app
jm.get_job.return_value = _dur_confirm_job_preflight(
credits_charged=1, pending_additional_credits=2
)
resp = _post(client, "job-dur-2", acknowledged_credits=3)
assert resp.status_code == 200, resp.text
jm.update_job.assert_called()
update_call_args = jm.update_job.call_args
update_dict = update_call_args[0][1] if update_call_args[0] else update_call_args[1]
assert update_dict.get("state_data.credits_charged") == 3, (
"credits_charged must be updated to 1 (prior) + 2 (owed) = 3"
)
def test_preflight_insufficient_credits_returns_402(self, patched_app):
client, jm, us, ws = patched_app
jm.get_job.return_value = _dur_confirm_job_preflight(
credits_charged=1, pending_additional_credits=2
)
us.deduct_credits.return_value = (False, 1, "Insufficient credits")
resp = _post(client, "job-dur-2", acknowledged_credits=3)
assert resp.status_code == 402, resp.text
def test_preflight_mismatch_returns_409(self, patched_app):
"""acknowledged_credits=5 but expected 3 (1+2) → 409."""
client, jm, us, ws = patched_app
jm.get_job.return_value = _dur_confirm_job_preflight(
credits_charged=1, pending_additional_credits=2
)
resp = _post(client, "job-dur-2", acknowledged_credits=5)
assert resp.status_code == 409, resp.text
def test_preflight_workers_triggered(self, patched_app):
client, jm, us, ws = patched_app
jm.get_job.return_value = _dur_confirm_job_preflight(
credits_charged=1, pending_additional_credits=2
)
with patch("backend.api.routes.jobs.asyncio.create_task") as mock_ct:
mock_ct.return_value = MagicMock()
resp = _post(client, "job-dur-2", acknowledged_credits=3)
assert resp.status_code == 200, resp.text
mock_ct.assert_called_once()
class TestConfirmDurationIdempotency:
"""Duplicate-confirm and owed=0 paths."""
def test_duplicate_confirm_is_rejected(self, patched_app):
"""A second confirm POST must 409 because the job is no longer AWAITING_DURATION_CONFIRM.
After a successful confirm the endpoint calls transition_to_state →
SEPARATING_STAGE1. The mock default returns True from transition_to_state;
what matters is that the endpoint *issued* the transition so that a
subsequent request (now seeing a different status) would be rejected.
We verify this by asserting that transition_to_state was called with
new_status=SEPARATING_STAGE1 on the first confirm — the status guard at
step 2 would reject a second request once the real Firestore document
reflects the new status.
"""
client, jm, us, ws = patched_app
jm.get_job.return_value = _dur_confirm_job_reconcile(
credits_charged=2, pending_additional_credits=1
)
resp = _post(client, "job-dur-1", acknowledged_credits=3)
assert resp.status_code == 200, resp.text
# Verify the endpoint transitioned the job out of AWAITING_DURATION_CONFIRM
# so a duplicate confirm would hit the status guard (409).
jm.transition_to_state.assert_called_once()
call_kwargs = jm.transition_to_state.call_args[1]
assert call_kwargs.get("new_status") == JobStatus.SEPARATING_STAGE1, (
"confirm_duration must transition to SEPARATING_STAGE1 before triggering "
"workers so a duplicate POST is rejected by the status guard"
)
def test_owed_zero_path(self, patched_app):
"""Job with pending_additional_credits=0: 200, deduct_credits NOT called,
duration_confirmed set, workers triggered, status transitioned out."""
client, jm, us, ws = patched_app
jm.get_job.return_value = _job(
job_id="job-zero",
status=JobStatus.AWAITING_DURATION_CONFIRM,
user_email="owner@example.com",
state_data={
"duration_confirm_reason": "reconcile",
"credits_charged": 3,
"pending_additional_credits": 0,
},
)
with patch("backend.api.routes.jobs.asyncio.create_task") as mock_ct:
mock_ct.return_value = MagicMock()
resp = _post(client, "job-zero", acknowledged_credits=3)
assert resp.status_code == 200, resp.text
# No credits should be deducted when owed == 0
us.deduct_credits.assert_not_called()
# State must still be persisted and workers triggered
jm.update_job.assert_called()
mock_ct.assert_called_once()
# Job must still be transitioned out of the pause state
jm.transition_to_state.assert_called_once()
call_kwargs = jm.transition_to_state.call_args[1]
assert call_kwargs.get("new_status") == JobStatus.SEPARATING_STAGE1
class TestConfirmDurationErrorCases:
"""Status guard, not-found, and not-owner cases."""
def test_wrong_status_returns_409(self, patched_app):
"""Job not in AWAITING_DURATION_CONFIRM → 409."""
client, jm, us, ws = patched_app
jm.get_job.return_value = _job(
job_id="done-job",
status=JobStatus.COMPLETE,
user_email="owner@example.com",
state_data={},
)
resp = _post(client, "done-job", acknowledged_credits=1)
assert resp.status_code == 409, resp.text
def test_job_not_found_returns_404(self, patched_app):
client, jm, us, ws = patched_app
jm.get_job.return_value = None
resp = _post(client, "nonexistent", acknowledged_credits=1)
assert resp.status_code == 404, resp.text
def test_not_owner_returns_404(self, patched_app):
"""Job owned by different user (non-admin) should 404 to avoid leaking job existence."""
client, jm, us, ws = patched_app
# The conftest mock_auth_dependency sets user_email="test@example.com" and is_admin=True.
# To test the non-owner path we need to override auth to return a non-admin user.
from backend.api.dependencies import require_auth
from backend.main import app
async def non_owner_auth():
return AuthResult(
is_valid=True,
user_type=UserType.STRIPE,
remaining_uses=5,
message="regular user",
is_admin=False,
user_email="other@example.com", # different from owner@example.com
)
jm.get_job.return_value = _dur_confirm_job_reconcile(user_email="owner@example.com")
app.dependency_overrides[require_auth] = non_owner_auth
try:
resp = _post(client, "job-dur-1", acknowledged_credits=3)
finally:
app.dependency_overrides.pop(require_auth, None)
assert resp.status_code == 404, resp.text
+132
View File
@@ -0,0 +1,132 @@
"""
Tests for POST /api/jobs/estimate — URL duration probe.
Covers:
- duration 905s → 200, duration_seconds=905, credits=2, blocked=False
- duration 4000s → blocked=True
- probe failure (duration None) → duration_seconds=None, source="unknown", credits=1, blocked=False
`check_availability` is patched at its import location in backend.api.routes.jobs.
"""
from __future__ import annotations
from unittest.mock import AsyncMock, patch
import pytest
from fastapi.testclient import TestClient
@pytest.fixture(autouse=True)
def _ensure_auth_overrides():
"""Ensure auth dependency overrides are set for every test in this file."""
from backend.api.dependencies import require_auth, require_admin
from backend.main import app
from backend.services.auth_service import UserType, AuthResult
async def mock_require_auth():
return AuthResult(
is_valid=True,
user_type=UserType.ADMIN,
remaining_uses=999,
message="Test admin token",
is_admin=True,
user_email="test@example.com",
)
app.dependency_overrides[require_auth] = mock_require_auth
app.dependency_overrides[require_admin] = mock_require_auth
yield
app.dependency_overrides.pop(require_auth, None)
app.dependency_overrides.pop(require_admin, None)
@pytest.fixture
def client():
from backend.main import app
return TestClient(app)
@pytest.fixture
def auth_headers():
return {
"Authorization": "Bearer test-admin-token",
"Content-Type": "application/json",
}
# ---------------------------------------------------------------------------
# Tests
# ---------------------------------------------------------------------------
def test_estimate_returns_credits(client, auth_headers):
"""905s of audio → 2 credits (ceil(905/600)=2), not blocked."""
mock_svc = AsyncMock()
mock_svc.check_availability = AsyncMock(
return_value={"available": True, "duration": 905}
)
with patch(
"backend.api.routes.jobs.get_youtube_download_service",
return_value=mock_svc,
):
resp = client.post(
"/api/jobs/estimate",
json={"url": "https://youtu.be/x"},
headers=auth_headers,
)
assert resp.status_code == 200, resp.text
body = resp.json()
assert body["duration_seconds"] == 905
assert body["credits"] == 2
assert body["blocked"] is False
assert body["source"] == "youtube_metadata"
def test_estimate_blocks_over_60min(client, auth_headers):
"""4000s (>3600s) → blocked=True."""
mock_svc = AsyncMock()
mock_svc.check_availability = AsyncMock(
return_value={"available": True, "duration": 4000}
)
with patch(
"backend.api.routes.jobs.get_youtube_download_service",
return_value=mock_svc,
):
resp = client.post(
"/api/jobs/estimate",
json={"url": "https://youtu.be/x"},
headers=auth_headers,
)
assert resp.status_code == 200, resp.text
body = resp.json()
assert body["blocked"] is True
assert body["duration_seconds"] == 4000
def test_estimate_probe_failure_returns_unknown(client, auth_headers):
"""When probe returns None duration → unknown source, 1 credit hold, not blocked."""
mock_svc = AsyncMock()
mock_svc.check_availability = AsyncMock(
return_value={"available": True, "duration": None}
)
with patch(
"backend.api.routes.jobs.get_youtube_download_service",
return_value=mock_svc,
):
resp = client.post(
"/api/jobs/estimate",
json={"url": "https://youtu.be/x"},
headers=auth_headers,
)
assert resp.status_code == 200, resp.text
body = resp.json()
assert body["duration_seconds"] is None
assert body["source"] == "unknown"
assert body["credits"] == 1
assert body["blocked"] is False
@@ -0,0 +1,340 @@
"""
Tests for the idle reminder mechanism for AWAITING_DURATION_CONFIRM state.
Covers:
- POST /api/internal/jobs/{job_id}/check-idle-reminder sends email when job is in
AWAITING_DURATION_CONFIRM and action_type == "duration_confirm"
- No email sent when job has already left AWAITING_DURATION_CONFIRM
- _schedule_idle_reminder schedules a 900s reminder with action_type="duration_confirm"
when a job enters AWAITING_DURATION_CONFIRM
"""
import os
import pytest
from datetime import datetime, UTC
from unittest.mock import MagicMock, AsyncMock, patch, Mock
# Ensure env vars are set before any backend imports
os.environ.setdefault('ADMIN_TOKENS', 'test-admin-token')
os.environ.setdefault('GOOGLE_CLOUD_PROJECT', 'test-project')
from backend.models.job import Job, JobStatus
from backend.services.job_manager import JobManager
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _make_job(
status: JobStatus = JobStatus.AWAITING_DURATION_CONFIRM,
state_data: dict | None = None,
user_email: str = "user@example.com",
job_id: str = "job-dur-001",
made_for_you: bool = False,
) -> Job:
"""Create a minimal Job for testing."""
return Job(
job_id=job_id,
status=status,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
user_email=user_email,
artist="Test Artist",
title="Test Song",
state_data=state_data or {
"blocking_action_type": "duration_confirm",
"blocking_state_entered_at": "2026-06-04T10:00:00",
"reminder_sent": False,
"pending_additional_credits": 3,
"duration_actual_seconds": 1200,
},
made_for_you=made_for_you,
)
def _make_client():
"""Create a FastAPI TestClient with GCP mocks applied."""
from fastapi.testclient import TestClient
mock_creds = MagicMock()
mock_creds.universe_domain = "googleapis.com"
with patch("google.auth.default", return_value=(mock_creds, "test-project")), \
patch("backend.services.firestore_service.firestore"), \
patch("backend.services.storage_service.storage"):
from backend.main import app
return TestClient(app)
# ---------------------------------------------------------------------------
# Check-idle-reminder endpoint tests
# ---------------------------------------------------------------------------
class TestCheckIdleReminderDurationConfirm:
"""Tests for the check-idle-reminder endpoint handling duration_confirm jobs."""
AUTH = {"Authorization": "Bearer test-admin-token"}
def test_sends_duration_confirm_email_when_job_awaiting(self):
"""
When a job is AWAITING_DURATION_CONFIRM with action_type=duration_confirm,
POST check-idle-reminder should call send_duration_confirm_reminder once
and set reminder_sent=True.
"""
job = _make_job()
mock_job_manager = MagicMock()
mock_job_manager.get_job.return_value = job
mock_notification_service = MagicMock()
mock_notification_service.send_duration_confirm_reminder = AsyncMock(return_value=True)
client = _make_client()
with patch("backend.api.routes.internal.JobManager", return_value=mock_job_manager), \
patch(
"backend.services.job_notification_service.get_job_notification_service",
return_value=mock_notification_service,
):
response = client.post(
"/api/internal/jobs/job-dur-001/check-idle-reminder",
headers=self.AUTH,
)
assert response.status_code == 200
data = response.json()
assert data["status"] == "sent"
# Email method was called exactly once
mock_notification_service.send_duration_confirm_reminder.assert_called_once()
# reminder_sent flag was written back
update_calls = mock_job_manager.firestore.update_job.call_args_list
assert any(
call_args[0][1].get("state_data", {}).get("reminder_sent") is True
for call_args in update_calls
)
def test_no_email_when_job_no_longer_awaiting_duration_confirm(self):
"""
If the job has moved out of AWAITING_DURATION_CONFIRM (e.g. user confirmed),
the endpoint should return 'skipped' and NOT send any email.
"""
# Job is now PROCESSING (user already confirmed)
job = _make_job(status=JobStatus.PROCESSING)
mock_job_manager = MagicMock()
mock_job_manager.get_job.return_value = job
mock_notification_service = MagicMock()
mock_notification_service.send_duration_confirm_reminder = AsyncMock(return_value=True)
client = _make_client()
with patch("backend.api.routes.internal.JobManager", return_value=mock_job_manager), \
patch(
"backend.services.job_notification_service.get_job_notification_service",
return_value=mock_notification_service,
):
response = client.post(
"/api/internal/jobs/job-dur-001/check-idle-reminder",
headers=self.AUTH,
)
assert response.status_code == 200
data = response.json()
assert data["status"] == "skipped"
# No email sent
mock_notification_service.send_duration_confirm_reminder.assert_not_called()
def test_no_email_when_reminder_already_sent(self):
"""
If reminder_sent is already True, the endpoint should return 'already_sent'
without calling send_duration_confirm_reminder.
"""
job = _make_job(
state_data={
"blocking_action_type": "duration_confirm",
"blocking_state_entered_at": "2026-06-04T10:00:00",
"reminder_sent": True, # Already sent
}
)
mock_job_manager = MagicMock()
mock_job_manager.get_job.return_value = job
mock_notification_service = MagicMock()
mock_notification_service.send_duration_confirm_reminder = AsyncMock(return_value=True)
client = _make_client()
with patch("backend.api.routes.internal.JobManager", return_value=mock_job_manager), \
patch(
"backend.services.job_notification_service.get_job_notification_service",
return_value=mock_notification_service,
):
response = client.post(
"/api/internal/jobs/job-dur-001/check-idle-reminder",
headers=self.AUTH,
)
assert response.status_code == 200
data = response.json()
assert data["status"] == "already_sent"
mock_notification_service.send_duration_confirm_reminder.assert_not_called()
def test_no_email_when_made_for_you(self):
"""Made-for-you jobs should be skipped even in AWAITING_DURATION_CONFIRM."""
job = _make_job(made_for_you=True)
mock_job_manager = MagicMock()
mock_job_manager.get_job.return_value = job
mock_notification_service = MagicMock()
mock_notification_service.send_duration_confirm_reminder = AsyncMock(return_value=True)
client = _make_client()
with patch("backend.api.routes.internal.JobManager", return_value=mock_job_manager), \
patch(
"backend.services.job_notification_service.get_job_notification_service",
return_value=mock_notification_service,
):
response = client.post(
"/api/internal/jobs/job-dur-001/check-idle-reminder",
headers=self.AUTH,
)
assert response.status_code == 200
data = response.json()
assert data["status"] == "skipped"
mock_notification_service.send_duration_confirm_reminder.assert_not_called()
# ---------------------------------------------------------------------------
# _schedule_idle_reminder unit test
# ---------------------------------------------------------------------------
class TestScheduleIdleReminderDurationConfirm:
"""Tests for _schedule_idle_reminder when entering AWAITING_DURATION_CONFIRM."""
def test_schedules_reminder_with_900s_delay_for_duration_confirm(self):
"""
Entering AWAITING_DURATION_CONFIRM must schedule a reminder with
action_type='duration_confirm' and delay_seconds=900 (15 min).
"""
manager = JobManager()
manager.firestore = Mock()
mock_job = Mock(spec=Job)
mock_job.job_id = "job-dur-002"
mock_job.user_email = "user@example.com"
mock_job.state_data = {"pending_additional_credits": 2}
captured_calls = []
async def fake_schedule_reminder(job_id, delay_seconds=None):
captured_calls.append({"job_id": job_id, "delay_seconds": delay_seconds})
return True
with patch("backend.services.worker_service.get_worker_service") as mock_get_service:
mock_service = Mock()
mock_service.schedule_idle_reminder = AsyncMock(
side_effect=fake_schedule_reminder
)
mock_get_service.return_value = mock_service
manager._schedule_idle_reminder(mock_job, JobStatus.AWAITING_DURATION_CONFIRM)
# Verify state_data update contains action_type and reminder_sent
update_call = manager.firestore.update_job.call_args
assert update_call is not None
updated_data = update_call[0][1]
state_data = updated_data.get("state_data", {})
assert state_data.get("blocking_action_type") == "duration_confirm"
assert state_data.get("reminder_sent") is False
assert "blocking_state_entered_at" in state_data
def test_schedules_900s_delay_not_default_delay(self):
"""
Verify that the 900s delay is passed explicitly (not the 2-min default),
so other action types are unaffected.
"""
from backend.services import worker_service as ws_module
manager = JobManager()
manager.firestore = Mock()
mock_job = Mock(spec=Job)
mock_job.job_id = "job-dur-003"
mock_job.user_email = "user@example.com"
mock_job.state_data = {}
mock_schedule = AsyncMock(return_value=True)
with patch("backend.services.worker_service.get_worker_service") as mock_get_service:
mock_service = Mock()
mock_service.schedule_idle_reminder = mock_schedule
mock_get_service.return_value = mock_service
manager._schedule_idle_reminder(mock_job, JobStatus.AWAITING_DURATION_CONFIRM)
# Give the daemon thread a moment to run
import time
time.sleep(0.2)
if mock_schedule.called:
call_kwargs = mock_schedule.call_args
# Should pass delay_seconds=900 explicitly
delay = (
call_kwargs.kwargs.get("delay_seconds")
if call_kwargs.kwargs
else (call_kwargs.args[1] if len(call_kwargs.args) > 1 else None)
)
assert delay == 900, (
f"Expected delay_seconds=900 for duration_confirm, got {delay}. "
f"The 2-min default ({ws_module.IDLE_REMINDER_DELAY_SECONDS}s) must NOT be used."
)
def test_does_not_affect_lyrics_reminder_delay(self):
"""
Entering AWAITING_REVIEW must NOT pass 900s (it should use the default delay).
This ensures duration_confirm's explicit delay doesn't bleed into other types.
"""
from backend.services import worker_service as ws_module
manager = JobManager()
manager.firestore = Mock()
mock_job = Mock(spec=Job)
mock_job.job_id = "job-lyrics"
mock_job.user_email = "user@example.com"
mock_job.state_data = {}
mock_schedule = AsyncMock(return_value=True)
with patch("backend.services.worker_service.get_worker_service") as mock_get_service:
mock_service = Mock()
mock_service.schedule_idle_reminder = mock_schedule
mock_get_service.return_value = mock_service
manager._schedule_idle_reminder(mock_job, JobStatus.AWAITING_REVIEW)
import time
time.sleep(0.2)
if mock_schedule.called:
call_kwargs = mock_schedule.call_args
delay = (
call_kwargs.kwargs.get("delay_seconds")
if call_kwargs.kwargs
else (call_kwargs.args[1] if len(call_kwargs.args) > 1 else None)
)
# Lyrics uses default (no explicit override) — delay should be
# IDLE_REMINDER_DELAY_SECONDS or None (meaning default is used)
assert delay != 900, (
f"AWAITING_REVIEW must not use the 900s duration_confirm delay, got {delay}"
)
+215
View File
@@ -0,0 +1,215 @@
"""Route-level tests for POST /api/jobs/{job_id}/corrections — timing sanitizer integration.
Verifies that out-of-bounds word timings submitted by the frontend are clamped
before corrections_updated.json is written to GCS.
"""
from __future__ import annotations
import pytest
from datetime import datetime, UTC
from unittest.mock import MagicMock, patch, call
from backend.models.job import Job, JobStatus
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@pytest.fixture
def review_job():
"""A job in AWAITING_REVIEW state owned by the test admin user."""
job = Job(
job_id="review-job-001",
status=JobStatus.AWAITING_REVIEW,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test Artist",
title="Test Song",
)
return job
@pytest.fixture
def mock_job_manager(review_job):
manager = MagicMock()
manager.get_job.return_value = review_job
manager.update_state_data.return_value = None
manager.update_file_url.return_value = None
manager.transition_to_state.return_value = None
return manager
@pytest.fixture
def mock_worker_service():
return MagicMock()
@pytest.fixture
def mock_theme_service():
svc = MagicMock()
svc.get_default_theme_id.return_value = "nomad"
svc.get_theme.return_value = None
return svc
@pytest.fixture
def client(mock_job_manager, mock_worker_service, mock_theme_service):
"""FastAPI TestClient with mocked dependencies."""
from fastapi.testclient import TestClient
mock_creds = MagicMock()
mock_creds.universe_domain = "googleapis.com"
def _jm_factory(*args, **kwargs):
return mock_job_manager
with patch("backend.api.routes.jobs.job_manager", mock_job_manager), \
patch("backend.api.routes.jobs.worker_service", mock_worker_service), \
patch("backend.api.routes.jobs.get_theme_service", return_value=mock_theme_service), \
patch("backend.services.job_manager.JobManager", _jm_factory), \
patch("backend.services.firestore_service.firestore"), \
patch("backend.services.storage_service.storage"), \
patch("google.auth.default", return_value=(mock_creds, "test-project")):
from backend.main import app
yield TestClient(app)
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _bad_corrections():
"""Corrections payload whose words fall outside segment bounds (start=0, end<0).
Must include the 'lines' and 'metadata' keys required by CorrectionsSubmission
validation before the sanitizer runs.
"""
return {
"lines": [],
"metadata": {"source": "test"},
"corrected_segments": [
{
"id": "s1",
"text": "A whiskey and a beer,",
"start_time": 15.18,
"end_time": 18.04,
"words": [
{"id": "a", "text": "A", "start_time": 0, "end_time": -0.005},
{"id": "b", "text": "whiskey", "start_time": 0, "end_time": -0.005},
{"id": "c", "text": "and", "start_time": 0, "end_time": 0},
{"id": "d", "text": "a", "start_time": 0, "end_time": 0},
{"id": "e", "text": "beer,", "start_time": 16.1, "end_time": 16.42},
],
}
]
}
def _good_corrections():
"""Corrections payload whose word timings are already valid."""
return {
"lines": [],
"metadata": {"source": "test"},
"corrected_segments": [
{
"id": "s1",
"text": "Filling up",
"start_time": 21.4,
"end_time": 22.1,
"words": [
{"id": "w0", "text": "Filling", "start_time": 21.4, "end_time": 21.82},
{"id": "w1", "text": "up", "start_time": 21.86, "end_time": 22.1},
],
}
]
}
# ---------------------------------------------------------------------------
# Tests
# ---------------------------------------------------------------------------
class TestSubmitCorrectionsTimingSanitizer:
"""Verify that submit_corrections clamps out-of-bounds word timings before GCS upload."""
def test_sanitized_timings_uploaded_to_gcs(self, client, auth_headers):
"""Words with start_time/end_time outside segment bounds must be clamped
before corrections_updated.json is written to GCS.
Patch StorageService at the class level in its source module so the local
import inside submit_corrections picks up the mock.
"""
uploaded_payload = {}
with patch("backend.services.storage_service.StorageService") as MockStorage:
storage_instance = MockStorage.return_value
# Capture what gets passed to upload_json
def capture_upload(path, data):
uploaded_payload.update(data)
storage_instance.upload_json.side_effect = capture_upload
response = client.post(
"/api/jobs/review-job-001/corrections",
json={"corrections": _bad_corrections()},
headers=auth_headers,
)
assert response.status_code == 200, response.text
assert uploaded_payload, "upload_json was never called — capture failed"
# All uploaded word timings must be within their segment bounds
words = uploaded_payload["corrected_segments"][0]["words"]
seg_start = 15.18
seg_end = 18.04
for w in words:
assert w["start_time"] >= seg_start, f"word start_time {w['start_time']} < seg start {seg_start}"
assert w["end_time"] >= w["start_time"], f"word end_time {w['end_time']} < start_time {w['start_time']}"
assert w["end_time"] <= seg_end + 1e-9, f"word end_time {w['end_time']} > seg end {seg_end}"
def test_valid_timings_uploaded_unchanged(self, client, auth_headers):
"""Word timings already within bounds must not be modified."""
uploaded_payload = {}
with patch("backend.services.storage_service.StorageService") as MockStorage:
storage_instance = MockStorage.return_value
def capture_upload(path, data):
uploaded_payload.update(data)
storage_instance.upload_json.side_effect = capture_upload
response = client.post(
"/api/jobs/review-job-001/corrections",
json={"corrections": _good_corrections()},
headers=auth_headers,
)
assert response.status_code == 200, response.text
assert uploaded_payload, "upload_json was never called — capture failed"
words = uploaded_payload["corrected_segments"][0]["words"]
assert words[0]["start_time"] == 21.4
assert words[0]["end_time"] == 21.82
assert words[1]["start_time"] == 21.86
assert words[1]["end_time"] == 22.1
class TestSubmitCorrectionsContract:
"""Minimal contract test — does not require the full FastAPI test harness."""
def test_sanitize_contract_bad_timings(self):
"""sanitize_corrections clamps words with start/end outside segment bounds."""
from backend.services.timing_sanitizer import sanitize_corrections
bad = {
"corrected_segments": [
{
"id": "s", "start_time": 15.18, "end_time": 18.04, "text": "A",
"words": [{"id": "a", "text": "A", "start_time": 0, "end_time": -0.005}],
}
]
}
cleaned, count = sanitize_corrections(bad)
assert count >= 1
w = cleaned["corrected_segments"][0]["words"][0]
assert w["start_time"] >= 15.18
assert w["end_time"] >= w["start_time"]
@@ -0,0 +1,139 @@
"""Route tests for POST /api/review/{job_id}/auto-correct."""
from __future__ import annotations
from unittest.mock import MagicMock
import pytest
from fastapi.testclient import TestClient
from backend.main import app
from backend.services.auto_correct.service import (
AutoCorrectResult,
AutoCorrectServiceError,
Suggestion,
)
from backend.services.auto_correct.settings import AutoCorrectSettings
@pytest.fixture
def client() -> TestClient:
return TestClient(app)
@pytest.fixture(autouse=True)
def bypass_auth(monkeypatch):
"""Bypass require_review_auth for these tests."""
from backend.api.dependencies import require_review_auth as real_dep
async def fake_dep():
return ("test-job", "full")
app.dependency_overrides[real_dep] = fake_dep
yield
app.dependency_overrides.pop(real_dep, None)
def _override_service(result_or_exc):
from backend.api.routes.review import _get_auto_correct_service_dep
mock_service = MagicMock()
if isinstance(result_or_exc, Exception):
mock_service.suggest.side_effect = result_or_exc
else:
mock_service.suggest.return_value = result_or_exc
app.dependency_overrides[_get_auto_correct_service_dep] = lambda: mock_service
return mock_service
def teardown_function(_): # noqa: ANN001
from backend.api.routes.review import _get_auto_correct_service_dep
app.dependency_overrides.pop(_get_auto_correct_service_dep, None)
def _make_result(suggestions=None) -> AutoCorrectResult:
return AutoCorrectResult(
suggestions=suggestions
if suggestions is not None
else [
Suggestion(
id="sug-1",
op="replace",
word_ids=["w3"],
segment_ids=["seg-1"],
original_text="glory",
new_text="chlorine",
reason="matches reference",
category="mishearing",
confidence=0.95,
)
],
model="gemini-test",
elapsed_seconds=12.3,
settings_applied=AutoCorrectSettings(),
warnings=["dropped suggestion 3: out of range"],
)
BODY = {
"segments": [{"id": "seg-1", "words": [{"id": "w3", "text": "glory"}]}],
"reference_lyrics": {"genius": {"segments": [{"text": "chlorine"}]}},
"artist": "Twenty One Pilots",
"title": "Chlorine",
}
def test_happy_path(client: TestClient) -> None:
mock = _override_service(_make_result())
resp = client.post("/api/review/test-job/auto-correct", json=BODY)
assert resp.status_code == 200
data = resp.json()
assert data["model"] == "gemini-test"
assert len(data["suggestions"]) == 1
s = data["suggestions"][0]
assert s["op"] == "replace"
assert s["word_ids"] == ["w3"]
assert s["new_text"] == "chlorine"
assert data["warnings"] == ["dropped suggestion 3: out of range"]
assert data["settings_applied"]["suggest_adlib_removal"] is True
mock.suggest.assert_called_once()
def test_settings_passed_through(client: TestClient) -> None:
mock = _override_service(_make_result([]))
resp = client.post(
"/api/review/test-job/auto-correct",
json={**BODY, "settings": {"suggest_adlib_removal": False, "min_confidence": 0.8}},
)
assert resp.status_code == 200
settings = mock.suggest.call_args.kwargs["settings"]
assert settings.suggest_adlib_removal is False
assert settings.min_confidence == 0.8
def test_invalid_settings_400(client: TestClient) -> None:
_override_service(_make_result([]))
resp = client.post(
"/api/review/test-job/auto-correct",
json={**BODY, "settings": {"bogus_knob": True}},
)
assert resp.status_code == 400
assert "invalid settings" in resp.json()["detail"]
def test_no_references_422_propagates(client: TestClient) -> None:
_override_service(AutoCorrectServiceError("no reference lyrics", status_code=422))
resp = client.post("/api/review/test-job/auto-correct", json=BODY)
assert resp.status_code == 422
def test_model_failure_502_propagates(client: TestClient) -> None:
_override_service(AutoCorrectServiceError("AI model call failed", status_code=502))
resp = client.post("/api/review/test-job/auto-correct", json=BODY)
assert resp.status_code == 502
def test_missing_body_fields_422(client: TestClient) -> None:
_override_service(_make_result([]))
resp = client.post("/api/review/test-job/auto-correct", json={"segments": []})
assert resp.status_code == 422 # reference_lyrics is required
+209
View File
@@ -0,0 +1,209 @@
"""
Tests for duration reconciliation wired into start_job_processing (Task 12).
Covers:
- start_job_processing pauses when reconcile_and_maybe_pause returns True
→ workers are NOT triggered
- start_job_processing proceeds when reconcile_and_maybe_pause returns False
→ both workers ARE triggered
- reconcile is called AFTER input_media_gcs_path is set (upload's exact file)
- reconcile is bypassed for existing_instrumental jobs (they only trigger lyrics worker)
— reconcile is still called but the no-instrumental-present path is covered
"""
from __future__ import annotations
import asyncio
from datetime import datetime, UTC
from unittest.mock import AsyncMock, MagicMock, Mock, patch, call
import pytest
import sys
# Prevent real Firestore/GCS imports from being resolved at module load.
sys.modules.setdefault("google.cloud.firestore", MagicMock())
sys.modules.setdefault("google.cloud.storage", MagicMock())
from backend.models.job import Job, JobStatus
from backend.exceptions import InvalidStateTransitionError
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
NOW = datetime.now(UTC)
def _pending_job(
job_id="upload-job-1",
gcs_path="uploads/upload-job-1/audio/song.flac",
existing_instrumental=None,
):
return Job(
job_id=job_id,
status=JobStatus.PENDING,
created_at=NOW,
updated_at=NOW,
input_media_gcs_path=gcs_path,
existing_instrumental_gcs_path=existing_instrumental,
state_data={"credits_charged": 1},
)
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@pytest.fixture()
def mock_firestore():
with patch("backend.services.job_manager.FirestoreService") as cls:
svc = Mock()
# get_job returns a PENDING job with input_media_gcs_path set
svc.get_job.return_value = _pending_job()
cls.return_value = svc
yield svc
@pytest.fixture()
def job_manager(mock_firestore):
from backend.services.job_manager import JobManager
return JobManager()
@pytest.fixture()
def mock_worker_service():
ws = Mock()
ws.trigger_audio_worker = AsyncMock(return_value=True)
ws.trigger_lyrics_worker = AsyncMock(return_value=True)
return ws
# ---------------------------------------------------------------------------
# Tests: reconcile wired into start_job_processing
# ---------------------------------------------------------------------------
class TestStartJobProcessingReconcile:
"""Duration reconciliation is invoked from start_job_processing."""
@pytest.mark.asyncio
async def test_reconcile_called_before_workers(self, job_manager, mock_firestore, mock_worker_service):
"""reconcile_and_maybe_pause is called before triggering workers."""
mock_reconcile = AsyncMock(return_value=False)
with (
patch("backend.services.worker_service.get_worker_service", return_value=mock_worker_service),
patch("backend.services.job_manager.reconcile_and_maybe_pause", mock_reconcile, create=True),
):
await job_manager.start_job_processing("upload-job-1")
mock_reconcile.assert_awaited_once_with("upload-job-1")
@pytest.mark.asyncio
async def test_workers_not_triggered_when_reconcile_pauses(
self, job_manager, mock_firestore, mock_worker_service
):
"""When reconcile_and_maybe_pause returns True, no workers must be started."""
mock_reconcile = AsyncMock(return_value=True)
with (
patch("backend.services.worker_service.get_worker_service", return_value=mock_worker_service),
patch("backend.services.job_manager.reconcile_and_maybe_pause", mock_reconcile, create=True),
):
await job_manager.start_job_processing("upload-job-1")
mock_worker_service.trigger_audio_worker.assert_not_called()
mock_worker_service.trigger_lyrics_worker.assert_not_called()
@pytest.mark.asyncio
async def test_both_workers_triggered_when_reconcile_proceeds(
self, job_manager, mock_firestore, mock_worker_service
):
"""When reconcile_and_maybe_pause returns False, both workers ARE triggered."""
mock_reconcile = AsyncMock(return_value=False)
with (
patch("backend.services.worker_service.get_worker_service", return_value=mock_worker_service),
patch("backend.services.job_manager.reconcile_and_maybe_pause", mock_reconcile, create=True),
):
await job_manager.start_job_processing("upload-job-1")
mock_worker_service.trigger_audio_worker.assert_awaited_once_with("upload-job-1")
mock_worker_service.trigger_lyrics_worker.assert_awaited_once_with("upload-job-1")
@pytest.mark.asyncio
async def test_reconcile_is_called_after_transition_to_downloading(
self, job_manager, mock_firestore, mock_worker_service
):
"""Reconcile must run AFTER the job has transitioned to DOWNLOADING.
input_media_gcs_path is already set by the upload handler before
start_job_processing is called; the job is transitioned to DOWNLOADING
first, then reconcile probes it. This test confirms the ordering by
checking that transition_to_state is called before reconcile.
"""
call_log: list[str] = []
orig_transition = job_manager.transition_to_state
def tracking_transition(*a, **kw):
call_log.append("transition")
return orig_transition(*a, **kw)
async def tracking_reconcile(job_id):
call_log.append("reconcile")
return False
with (
patch("backend.services.worker_service.get_worker_service", return_value=mock_worker_service),
patch("backend.services.job_manager.reconcile_and_maybe_pause", side_effect=tracking_reconcile, create=True),
patch.object(job_manager, "transition_to_state", side_effect=tracking_transition),
):
await job_manager.start_job_processing("upload-job-1")
assert call_log.index("transition") < call_log.index("reconcile"), (
"transition_to_state must precede reconcile_and_maybe_pause; "
f"got order: {call_log}"
)
@pytest.mark.asyncio
async def test_existing_instrumental_job_reconcile_then_lyrics_only(
self, job_manager, mock_firestore, mock_worker_service
):
"""Jobs with existing_instrumental_gcs_path: reconcile is still called,
then only lyrics worker is triggered (audio separation is skipped)."""
mock_firestore.get_job.return_value = _pending_job(
existing_instrumental="uploads/upload-job-1/audio/existing_instrumental.mp3"
)
mock_reconcile = AsyncMock(return_value=False)
with (
patch("backend.services.worker_service.get_worker_service", return_value=mock_worker_service),
patch("backend.services.job_manager.reconcile_and_maybe_pause", mock_reconcile, create=True),
):
await job_manager.start_job_processing("upload-job-1")
# Reconcile must still be called
mock_reconcile.assert_awaited_once_with("upload-job-1")
# Audio worker must NOT be called (separation skipped)
mock_worker_service.trigger_audio_worker.assert_not_called()
# Lyrics worker IS called
mock_worker_service.trigger_lyrics_worker.assert_awaited_once_with("upload-job-1")
@pytest.mark.asyncio
async def test_existing_instrumental_paused_by_reconcile(
self, job_manager, mock_firestore, mock_worker_service
):
"""When reconcile returns True for existing-instrumental job,
even the lyrics worker is NOT triggered."""
mock_firestore.get_job.return_value = _pending_job(
existing_instrumental="uploads/upload-job-1/audio/existing_instrumental.mp3"
)
mock_reconcile = AsyncMock(return_value=True)
with (
patch("backend.services.worker_service.get_worker_service", return_value=mock_worker_service),
patch("backend.services.job_manager.reconcile_and_maybe_pause", mock_reconcile, create=True),
):
await job_manager.start_job_processing("upload-job-1")
mock_worker_service.trigger_audio_worker.assert_not_called()
mock_worker_service.trigger_lyrics_worker.assert_not_called()
@@ -0,0 +1,450 @@
"""
Tests for duration-based credit pricing on URL job creation.
Covers:
- URL create with duration_seconds → charges N credits, stores credits_charged
- duration_seconds over 60 min → 422 (blocked)
- acknowledged_credits mismatch → 409
- default path (no duration_seconds) still charges 1 credit
"""
from __future__ import annotations
import asyncio
from datetime import datetime, UTC
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from backend.models.job import Job, JobStatus
from backend.services.auth_service import UserType, AuthResult
NOW = datetime.now(UTC)
# ---------------------------------------------------------------------------
# Auth fixtures
# ---------------------------------------------------------------------------
@pytest.fixture(autouse=True)
def _ensure_auth_overrides():
"""Ensure auth dependency overrides are set for every test in this file."""
from backend.api.dependencies import require_auth, require_admin
from backend.main import app
async def mock_require_auth():
return AuthResult(
is_valid=True,
user_type=UserType.STRIPE,
remaining_uses=5,
message="Regular test user",
is_admin=False,
user_email="buyer@example.com",
)
app.dependency_overrides[require_auth] = mock_require_auth
app.dependency_overrides[require_admin] = mock_require_auth
yield
app.dependency_overrides.pop(require_auth, None)
app.dependency_overrides.pop(require_admin, None)
# ---------------------------------------------------------------------------
# Helper: build a minimal Job returned by mock job_manager.create_job
# ---------------------------------------------------------------------------
def _pending_job(job_id="url-job-1", credits_charged=1, user_email="buyer@example.com") -> Job:
return Job(
job_id=job_id,
status=JobStatus.PENDING,
created_at=NOW,
updated_at=NOW,
user_email=user_email,
state_data={"credits_charged": credits_charged},
)
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@pytest.fixture
def mock_job_manager():
jm = MagicMock()
# Default: returns a 1-credit job; individual tests override as needed
jm.create_job.return_value = _pending_job(credits_charged=1)
return jm
@pytest.fixture
def mock_worker_service():
ws = MagicMock()
ws.trigger_audio_worker = AsyncMock(return_value=True)
ws.trigger_lyrics_worker = AsyncMock(return_value=True)
return ws
@pytest.fixture
def mock_theme_service():
ts = MagicMock()
ts.get_default_theme_id.return_value = "nomad"
return ts
@pytest.fixture
def mock_user_service():
us = MagicMock()
us.check_credits.return_value = 10
us.has_credits.return_value = True
return us
@pytest.fixture
def patched_app(mock_job_manager, mock_worker_service, mock_theme_service, mock_user_service):
"""Patch module-level singletons and yield the TestClient."""
from fastapi.testclient import TestClient
from backend.main import app
with (
patch("backend.api.routes.jobs.job_manager", mock_job_manager),
patch("backend.api.routes.jobs.worker_service", mock_worker_service),
patch("backend.api.routes.jobs.get_theme_service", return_value=mock_theme_service),
patch("backend.api.routes.jobs.get_user_service", return_value=mock_user_service),
patch("backend.services.firestore_service.FirestoreService.update_job"),
):
yield TestClient(app), mock_job_manager, mock_worker_service, mock_theme_service, mock_user_service
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _post_url_job(client, *, url="https://youtube.com/watch?v=abc", **extra):
body = {"url": url}
body.update(extra)
return client.post("/api/jobs", json=body)
# ---------------------------------------------------------------------------
# Tests: duration-based pricing on URL create
# ---------------------------------------------------------------------------
class TestURLCreatePricing:
"""Duration-based credit pricing on POST /api/jobs."""
def test_905s_with_acknowledged_2_charges_2_credits(self, patched_app):
"""
905 seconds → ceil(905/600) = 2 credits.
User sends acknowledged_credits=2, has ≥2 credits.
Expect: 200, JobCreate called with credits=2,
returned state_data.credits_charged == 2.
"""
client, jm, ws, ts, us = patched_app
# create_job returns a job with credits_charged=2
jm.create_job.return_value = _pending_job(credits_charged=2)
resp = _post_url_job(client, duration_seconds=905, acknowledged_credits=2)
assert resp.status_code == 200, resp.text
# Verify create_job was called with credits=2
jm.create_job.assert_called_once()
call_kwargs = jm.create_job.call_args
job_create_arg = call_kwargs[0][0] if call_kwargs[0] else call_kwargs[1].get("job_create")
assert job_create_arg.credits == 2, (
f"Expected credits=2 in JobCreate, got {job_create_arg.credits}"
)
def test_905s_credits_charged_stored(self, patched_app):
"""state_data.credits_charged on the returned job should equal 2."""
client, jm, ws, ts, us = patched_app
jm.create_job.return_value = _pending_job(credits_charged=2)
resp = _post_url_job(client, duration_seconds=905, acknowledged_credits=2)
assert resp.status_code == 200, resp.text
# The route returns a JobResponse (job_id, status, message) but we can
# confirm the job_manager was called correctly (credits_charged lives in Job.state_data
# which is set by create_job implementation).
body = resp.json()
assert "job_id" in body
def test_4000s_blocked_returns_422(self, patched_app):
"""
4000 seconds > 3600 → is_blocked() = True → 422 before job is created.
"""
client, jm, ws, ts, us = patched_app
resp = _post_url_job(client, duration_seconds=4000)
assert resp.status_code == 422, resp.text
# Job must NOT be created
jm.create_job.assert_not_called()
def test_3600s_exactly_is_blocked_returns_422(self, patched_app):
"""
3600 seconds is NOT blocked (> not >=), should succeed.
Actually: is_blocked checks > 3600, so exactly 3600 is NOT blocked.
"""
from backend.services.pricing import is_blocked
assert not is_blocked(3600), "3600s should not be blocked (ceiling is >3600)"
client, jm, ws, ts, us = patched_app
jm.create_job.return_value = _pending_job(credits_charged=6)
resp = _post_url_job(client, duration_seconds=3600, acknowledged_credits=6)
# 3600s = ceil(3600/600) = 6 credits, not blocked → success
assert resp.status_code == 200, resp.text
def test_3601s_blocked_returns_422(self, patched_app):
"""3601 seconds > 3600 → blocked."""
client, jm, ws, ts, us = patched_app
resp = _post_url_job(client, duration_seconds=3601)
assert resp.status_code == 422, resp.text
jm.create_job.assert_not_called()
def test_acknowledged_credits_mismatch_returns_409(self, patched_app):
"""
duration_seconds=905 → credits=2, but acknowledged_credits=1 → 409.
"""
client, jm, ws, ts, us = patched_app
resp = _post_url_job(client, duration_seconds=905, acknowledged_credits=1)
assert resp.status_code == 409, resp.text
# Job must NOT be created when acknowledged_credits mismatches
jm.create_job.assert_not_called()
def test_no_duration_charges_1_credit(self, patched_app):
"""
When duration_seconds is not provided, fall back to credits=1 (unchanged behaviour).
"""
client, jm, ws, ts, us = patched_app
jm.create_job.return_value = _pending_job(credits_charged=1)
resp = _post_url_job(client)
assert resp.status_code == 200, resp.text
jm.create_job.assert_called_once()
call_kwargs = jm.create_job.call_args
job_create_arg = call_kwargs[0][0] if call_kwargs[0] else call_kwargs[1].get("job_create")
assert job_create_arg.credits == 1, (
f"No duration → credits should default to 1, got {job_create_arg.credits}"
)
def test_duration_estimate_stored_on_job(self, patched_app):
"""
When duration_seconds is provided, the handler must call FirestoreService.update_job
with state_data.duration_estimate_seconds and state_data.duration_estimate_source.
"""
from unittest.mock import patch as _patch
client, jm, ws, ts, us = patched_app
jm.create_job.return_value = _pending_job(credits_charged=2)
with _patch("backend.services.firestore_service.FirestoreService.update_job") as mock_update:
resp = _post_url_job(client, duration_seconds=905, acknowledged_credits=2)
assert resp.status_code == 200, resp.text
# update_job must have been called at least once
assert mock_update.called, "FirestoreService.update_job was never called"
# Collect every update_payload passed across all calls
all_payloads: dict = {}
for call in mock_update.call_args_list:
# call[0] = positional args: (job_id, payload)
payload = call[0][1] if len(call[0]) >= 2 else call[1].get("updates", {})
all_payloads.update(payload)
assert all_payloads.get("state_data.duration_estimate_seconds") == 905, (
f"Expected state_data.duration_estimate_seconds=905 in update_job payload, "
f"got: {all_payloads}"
)
assert all_payloads.get("state_data.duration_estimate_source") == "youtube_metadata", (
f"Expected state_data.duration_estimate_source='youtube_metadata' in update_job payload, "
f"got: {all_payloads}"
)
def test_no_duration_duration_estimate_source_unknown(self, patched_app):
"""Without duration_seconds, duration_estimate_source defaults to 'unknown'."""
client, jm, ws, ts, us = patched_app
jm.create_job.return_value = _pending_job(credits_charged=1)
resp = _post_url_job(client)
assert resp.status_code == 200, resp.text
# ---------------------------------------------------------------------------
# Tests: create_job generalisation (Part A) via JobManager directly
# ---------------------------------------------------------------------------
class TestJobManagerCreditsParam:
"""
Unit tests for JobManager.create_job with configurable credits.
Tests the Part A changes without going through the HTTP layer.
"""
@pytest.fixture
def mock_fs(self):
with patch("backend.services.job_manager.FirestoreService") as cls:
svc = MagicMock()
cls.return_value = svc
yield svc
@pytest.fixture
def mock_storage(self):
with patch("backend.services.job_manager.StorageService") as cls:
svc = MagicMock()
cls.return_value = svc
yield svc
@pytest.fixture
def mock_us(self):
svc = MagicMock()
with patch("backend.services.user_service.get_user_service", return_value=svc):
yield svc
def _jm(self, mock_fs, mock_storage):
from backend.services.job_manager import JobManager
return JobManager()
def test_default_credits_is_1(self, mock_fs, mock_storage, mock_us):
"""JobCreate.credits defaults to 1."""
from backend.models.job import JobCreate
jc = JobCreate(theme_id="nomad")
assert jc.credits == 1
def test_explicit_credits_stored(self, mock_fs, mock_storage, mock_us):
"""JobCreate.credits=3 is accepted."""
from backend.models.job import JobCreate
jc = JobCreate(theme_id="nomad", credits=3)
assert jc.credits == 3
def test_create_job_no_email_skips_credit_check(self, mock_fs, mock_storage, mock_us):
"""Jobs with no user_email skip credit gate (unchanged behaviour)."""
from backend.services.job_manager import JobManager
from backend.models.job import JobCreate
jm = JobManager()
job = jm.create_job(JobCreate(theme_id="nomad"), is_admin=False)
assert job is not None
mock_us.has_credits.assert_not_called()
mock_us.deduct_credits.assert_not_called()
def test_admin_bypasses_credit_check(self, mock_fs, mock_storage, mock_us):
"""Admin bypass unchanged for any credits value."""
from backend.services.job_manager import JobManager
from backend.models.job import JobCreate
jm = JobManager()
job = jm.create_job(
JobCreate(theme_id="nomad", user_email="admin@test.com", credits=5),
is_admin=True,
)
assert job is not None
mock_us.has_credits.assert_not_called()
mock_us.deduct_credits.assert_not_called()
def test_has_credits_gate_uses_credits_param(self, mock_fs, mock_storage, mock_us):
"""has_credits gate should check the user has >= credits, not just >= 1."""
from backend.services.job_manager import JobManager
from backend.models.job import JobCreate
from backend.exceptions import InsufficientCreditsError
mock_us.has_credits.return_value = False
mock_us.check_credits.return_value = 1 # only 1 credit, need 3
jm = JobManager()
with pytest.raises(InsufficientCreditsError) as exc_info:
jm.create_job(
JobCreate(theme_id="nomad", user_email="user@test.com", credits=3),
is_admin=False,
)
# credits_required should match what we asked for
assert exc_info.value.credits_required == 3
def test_deduct_credits_called_with_n(self, mock_fs, mock_storage, mock_us):
"""deduct_credits is called with amount=credits (not always 1)."""
from backend.services.job_manager import JobManager
from backend.models.job import JobCreate
mock_us.has_credits.return_value = True
mock_us.check_credits.return_value = 5
mock_us.deduct_credits.return_value = (True, 3, "Deducted 2. 3 remaining")
jm = JobManager()
jm.create_job(
JobCreate(theme_id="nomad", user_email="user@test.com", credits=2),
is_admin=False,
)
mock_us.deduct_credits.assert_called_once()
call_args, call_kwargs = mock_us.deduct_credits.call_args
amount = call_kwargs.get("amount", call_args[2] if len(call_args) > 2 else None)
assert amount == 2, f"Expected deduct_credits(amount=2), got amount={amount}"
def test_deduct_credits_default_is_1(self, mock_fs, mock_storage, mock_us):
"""Default path (credits=1) still deducts exactly 1 credit."""
from backend.services.job_manager import JobManager
from backend.models.job import JobCreate
mock_us.has_credits.return_value = True
mock_us.check_credits.return_value = 5
mock_us.deduct_credits.return_value = (True, 4, "Deducted 1. 4 remaining")
jm = JobManager()
jm.create_job(
JobCreate(theme_id="nomad", user_email="user@test.com"),
is_admin=False,
)
mock_us.deduct_credits.assert_called_once()
call_args, call_kwargs = mock_us.deduct_credits.call_args
amount = call_kwargs.get("amount", call_args[2] if len(call_args) > 2 else None)
assert amount == 1, f"Default path must deduct 1 credit, got amount={amount}"
def test_credits_charged_in_state_data(self, mock_fs, mock_storage, mock_us):
"""state_data.credits_charged should equal credits on the created job."""
from backend.services.job_manager import JobManager
from backend.models.job import JobCreate
mock_us.has_credits.return_value = True
mock_us.check_credits.return_value = 10
mock_us.deduct_credits.return_value = (True, 7, "Deducted 3. 7 remaining")
jm = JobManager()
job = jm.create_job(
JobCreate(theme_id="nomad", user_email="user@test.com", credits=3),
is_admin=False,
)
assert job.state_data.get("credits_charged") == 3, (
f"state_data.credits_charged should be 3, got {job.state_data}"
)
def test_rollback_on_deduction_failure(self, mock_fs, mock_storage, mock_us):
"""If deduct_credits fails, job is deleted and InsufficientCreditsError raised."""
from backend.services.job_manager import JobManager
from backend.models.job import JobCreate
from backend.exceptions import InsufficientCreditsError
mock_us.has_credits.return_value = True
mock_us.check_credits.return_value = 5
mock_us.deduct_credits.return_value = (False, 0, "Race condition")
jm = JobManager()
with pytest.raises(InsufficientCreditsError):
jm.create_job(
JobCreate(theme_id="nomad", user_email="user@test.com", credits=2),
is_admin=False,
)
mock_fs.create_job.assert_called_once()
mock_fs.delete_job.assert_called_once()
@@ -0,0 +1,617 @@
"""
Integration tests for the duration-pricing reconcile flow.
Tests the end-to-end path through:
1. reconcile_duration (engine) pausing a job at AWAITING_DURATION_CONFIRM
2. POST /api/jobs/{id}/confirm-duration resuming the job and deducting credits
Money-critical: the delta-deduction math (started at 2 credits, ended at 4,
EXACTLY 2 deducted on confirm — not 4, not the full cost again) is the primary
invariant under test.
Also includes a companion DOWN-reconcile assertion (refund path, no pause).
Harness notes
-------------
- Follows the mocking pattern from backend/tests/integration/test_state_machine_flow.py
and test_youtube_flow.py: no Firestore emulator, mocked collaborators.
- The confirm-duration endpoint is exercised via FastAPI's TestClient.
- Worker triggers are patched so no real Cloud Run jobs fire.
"""
import pytest
from datetime import datetime, UTC
from unittest.mock import MagicMock, AsyncMock, Mock, patch, call
# Mock google.cloud.firestore before any module that imports it is loaded.
import sys
sys.modules.setdefault('google.cloud.firestore', MagicMock())
sys.modules.setdefault('google.cloud.storage', MagicMock())
from backend.models.job import Job, JobStatus
from backend.services.duration_reconciliation import reconcile_duration, ReconcileResult
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _make_job(
job_id: str = "dur-test-001",
status: JobStatus = JobStatus.DOWNLOADING,
credits_charged: int = 2,
user_email: str = "user@example.com",
input_media_gcs_path: str = "gs://bucket/jobs/dur-test-001/audio.flac",
extra_state_data: dict = None,
) -> Job:
"""Build a Job instance with the given fields."""
state_data = {"credits_charged": credits_charged}
if extra_state_data:
state_data.update(extra_state_data)
return Job(
job_id=job_id,
artist="Test Artist",
title="Test Song",
status=status,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
input_media_gcs_path=input_media_gcs_path,
state_data=state_data,
user_email=user_email,
)
def _make_mock_job_manager(job: Job) -> MagicMock:
"""Return a JobManager mock whose get_job always returns `job`."""
mgr = MagicMock()
mgr.get_job.return_value = job
mgr.update_job.return_value = None
mgr.transition_to_state.return_value = True
return mgr
def _make_mock_user_service() -> MagicMock:
"""Return a UserService mock with sensible defaults."""
svc = MagicMock()
# deduct_credits returns (success, remaining, message)
svc.deduct_credits.return_value = (True, 8, "2 credits deducted")
# add_credits returns (success, new_balance, message)
svc.add_credits.return_value = (True, 10, "Credits added")
return svc
# ---------------------------------------------------------------------------
# Part A.1 — Reconcile-UP path (engine only)
# ---------------------------------------------------------------------------
class TestReconcileUpEngine:
"""
Engine-level: reconcile_duration produces the correct pause result when
actual duration (2100 s) exceeds what was charged (2 credits at ~15 min).
"""
def test_reconcile_up_pauses_job_at_awaiting_duration_confirm(self):
"""
Given: credits_charged=2, actual=2100 s → required=4, delta=2
Expect: action="pause", pending_additional_credits=2,
job transitioned to AWAITING_DURATION_CONFIRM,
state_data updated with reason="reconcile" and delta=2.
"""
job_id = "dur-test-up-001"
job = _make_job(job_id=job_id, credits_charged=2)
mgr = _make_mock_job_manager(job)
svc = _make_mock_user_service()
result = reconcile_duration(
job_id=job_id,
job_manager=mgr,
user_service=svc,
probe_duration=lambda _job: 2100.0, # ~35 min → 4 credits
)
assert result.action == "pause"
assert result.pending_additional_credits == 2
assert result.actual_seconds == 2100.0
# transition_to_state called with AWAITING_DURATION_CONFIRM
mgr.transition_to_state.assert_called_once()
transition_call = mgr.transition_to_state.call_args
# Engine calls with keyword args: transition_to_state(job_id=..., new_status=..., ...)
new_status = (
transition_call.kwargs.get("new_status")
or (transition_call.args[1] if len(transition_call.args) >= 2 else None)
)
assert new_status == JobStatus.AWAITING_DURATION_CONFIRM, (
f"Expected AWAITING_DURATION_CONFIRM, got {new_status}"
)
# update_job called with duration_confirm_reason and delta
update_calls_flat = {}
for c in mgr.update_job.call_args_list:
if c.args and len(c.args) >= 2 and isinstance(c.args[1], dict):
update_calls_flat.update(c.args[1])
elif c.kwargs.get("updates"):
update_calls_flat.update(c.kwargs["updates"])
assert update_calls_flat.get("state_data.duration_confirm_reason") == "reconcile"
assert update_calls_flat.get("state_data.pending_additional_credits") == 2
# No credits deducted by the engine (deduction happens at confirm time)
svc.deduct_credits.assert_not_called()
def test_reconcile_up_does_not_trigger_workers(self):
"""Engine must NOT trigger workers when pausing — workers are triggered by confirm."""
job_id = "dur-test-up-002"
job = _make_job(job_id=job_id, credits_charged=2)
mgr = _make_mock_job_manager(job)
svc = _make_mock_user_service()
# No worker_service attribute on job_manager — engine should not call it
assert not hasattr(mgr, "trigger_audio_worker") or True # safe to check
reconcile_duration(
job_id=job_id,
job_manager=mgr,
user_service=svc,
probe_duration=lambda _job: 2100.0,
)
# Verify no worker-like calls were made on job_manager
called_methods = [str(c) for c in mgr.mock_calls]
assert not any("trigger" in m for m in called_methods), (
f"Engine should not trigger workers; calls: {called_methods}"
)
# ---------------------------------------------------------------------------
# Part A.2 — Reconcile-DOWN path (engine + user_service.add_credits)
# ---------------------------------------------------------------------------
class TestReconcileDownEngine:
"""
Engine-level: when actual duration (600 s) is less than what was charged
(4 credits), the engine auto-refunds the delta and returns action="proceed".
"""
def test_reconcile_down_refunds_delta_and_proceeds(self):
"""
Given: credits_charged=4, actual=600 s → required=1, delta=-3
Expect: action="proceed", add_credits called with amount=3,
reason="duration_refund", credits_charged updated to 1.
No pause. No transition to AWAITING_DURATION_CONFIRM.
"""
job_id = "dur-test-down-001"
job = _make_job(job_id=job_id, credits_charged=4)
mgr = _make_mock_job_manager(job)
svc = _make_mock_user_service()
result = reconcile_duration(
job_id=job_id,
job_manager=mgr,
user_service=svc,
probe_duration=lambda _job: 600.0, # 10 min → 1 credit
)
assert result.action == "proceed"
assert result.actual_seconds == 600.0
# add_credits called with correct amount and reason
svc.add_credits.assert_called_once_with(
job.user_email,
amount=3,
reason="duration_refund",
job_id=job_id,
)
# credits_charged updated to the new (lower) required amount
refund_update_found = any(
(c.args[1] if (c.args and len(c.args) >= 2 and isinstance(c.args[1], dict))
else c.kwargs.get("updates", {})).get("state_data.credits_charged") == 1
for c in mgr.update_job.call_args_list
)
assert refund_update_found, (
"Expected update_job to set credits_charged=1 after refund. "
f"Actual update_job calls: {mgr.update_job.call_args_list}"
)
# No pause
for c in mgr.transition_to_state.call_args_list:
status = c.args[1] if len(c.args) >= 2 else c.kwargs.get("new_status")
assert status != JobStatus.AWAITING_DURATION_CONFIRM, (
"Reconcile-DOWN must NOT pause at AWAITING_DURATION_CONFIRM"
)
# ---------------------------------------------------------------------------
# Part A.3 — Full reconcile-UP + confirm-duration end-to-end via TestClient
# ---------------------------------------------------------------------------
class TestReconcileUpEndToEnd:
"""
End-to-end: drive the reconcile engine directly (with mocked collaborators)
to produce the paused state, then call the real confirm-duration endpoint
via FastAPI TestClient and verify all credit-math invariants.
"""
@pytest.fixture
def mock_creds(self):
creds = MagicMock()
creds.universe_domain = "googleapis.com"
creds.token = "fake-token"
creds.valid = True
return creds
@pytest.fixture
def test_setup(self, mock_creds):
"""
Build a stable Job fixture that reflects the paused state produced by
reconcile_duration, then wire it into a TestClient with patched
job_manager, user_service, and worker_service.
The fixture simulates exactly the state that reconcile_duration would
write to Firestore:
- status = AWAITING_DURATION_CONFIRM
- state_data.credits_charged = 2
- state_data.pending_additional_credits = 2
- state_data.duration_confirm_reason = "reconcile"
"""
job_id = "dur-test-e2e-001"
user_email = "user@example.com"
# "Paused" job: the state reconcile_duration leaves behind
paused_job = _make_job(
job_id=job_id,
status=JobStatus.AWAITING_DURATION_CONFIRM,
credits_charged=2,
user_email=user_email,
extra_state_data={
"pending_additional_credits": 2,
"duration_confirm_reason": "reconcile",
},
)
# "Resumed" job: what get_job returns AFTER confirm (post-transition)
resumed_job = _make_job(
job_id=job_id,
status=JobStatus.SEPARATING_STAGE1,
credits_charged=4,
user_email=user_email,
extra_state_data={
"pending_additional_credits": 0,
"duration_confirm_reason": "reconcile",
"duration_confirmed": True,
},
)
mock_jm = MagicMock()
# First call returns the paused job; subsequent calls return the resumed one
mock_jm.get_job.side_effect = [paused_job, resumed_job]
mock_jm.update_job.return_value = None
mock_jm.transition_to_state.return_value = True
mock_us = MagicMock()
# User has 10 credits; deduct 2 → 8 remaining
mock_us.deduct_credits.return_value = (True, 8, "2 credits deducted")
mock_ws = MagicMock()
mock_ws.trigger_audio_worker = AsyncMock(return_value=True)
mock_ws.trigger_lyrics_worker = AsyncMock(return_value=True)
yield {
"job_id": job_id,
"user_email": user_email,
"paused_job": paused_job,
"resumed_job": resumed_job,
"mock_jm": mock_jm,
"mock_us": mock_us,
"mock_ws": mock_ws,
}
def _make_client(self, setup, mock_creds):
"""Return a TestClient with all necessary patches applied."""
from fastapi.testclient import TestClient
from backend.main import app
patches = [
patch("backend.api.routes.jobs.job_manager", setup["mock_jm"]),
patch("backend.api.routes.jobs.worker_service", setup["mock_ws"]),
patch("backend.api.routes.jobs.get_user_service", return_value=setup["mock_us"]),
patch("google.auth.default", return_value=(mock_creds, "test-project")),
]
return patches, TestClient(app)
def test_confirm_duration_returns_200_with_sufficient_credits(self, test_setup, mock_creds):
"""
POST /api/jobs/{id}/confirm-duration with acknowledged_credits=4 and a
user who has sufficient balance must return 200.
"""
setup = test_setup
patches = [
patch("backend.api.routes.jobs.job_manager", setup["mock_jm"]),
patch("backend.api.routes.jobs.worker_service", setup["mock_ws"]),
patch("backend.api.routes.jobs.get_user_service", return_value=setup["mock_us"]),
patch("google.auth.default", return_value=(mock_creds, "test-project")),
]
from fastapi.testclient import TestClient
from backend.main import app
with patches[0], patches[1], patches[2], patches[3]:
client = TestClient(app)
response = client.post(
f"/api/jobs/{setup['job_id']}/confirm-duration",
json={"acknowledged_credits": 4},
headers={"Authorization": "Bearer test-admin-token"},
)
assert response.status_code == 200, (
f"Expected 200, got {response.status_code}: {response.text}"
)
def test_confirm_duration_deducts_exactly_the_delta(self, test_setup, mock_creds):
"""
MONEY MATH: Only the delta (2 credits) must be deducted — not the full
cost (4) and not the original charge (2) again.
History: job created with credits_charged=2 (original deduction at job-create).
Reconcile found delta=2 more owed.
Confirm should deduct exactly 2 with count_as_job_creation=False.
"""
setup = test_setup
patches = [
patch("backend.api.routes.jobs.job_manager", setup["mock_jm"]),
patch("backend.api.routes.jobs.worker_service", setup["mock_ws"]),
patch("backend.api.routes.jobs.get_user_service", return_value=setup["mock_us"]),
patch("google.auth.default", return_value=(mock_creds, "test-project")),
]
from fastapi.testclient import TestClient
from backend.main import app
with patches[0], patches[1], patches[2], patches[3]:
client = TestClient(app)
client.post(
f"/api/jobs/{setup['job_id']}/confirm-duration",
json={"acknowledged_credits": 4},
headers={"Authorization": "Bearer test-admin-token"},
)
setup["mock_us"].deduct_credits.assert_called_once()
call_kwargs = setup["mock_us"].deduct_credits.call_args
# Extract positional and keyword args
args = call_kwargs.args
kwargs = call_kwargs.kwargs
# user_email is first positional arg, job_id is second
called_email = args[0] if args else kwargs.get("email", kwargs.get("user_email"))
called_job_id = args[1] if len(args) > 1 else kwargs.get("job_id")
called_amount = kwargs.get("amount", args[2] if len(args) > 2 else None)
called_reason = kwargs.get("reason", args[3] if len(args) > 3 else None)
called_count_as_creation = kwargs.get("count_as_job_creation")
assert called_email == setup["user_email"], (
f"Expected email={setup['user_email']}, got {called_email}"
)
assert called_job_id == setup["job_id"], (
f"Expected job_id={setup['job_id']}, got {called_job_id}"
)
assert called_amount == 2, (
f"MONEY BUG: Expected deduct_credits(amount=2) for the delta, "
f"but got amount={called_amount}. "
"The confirm endpoint must deduct only the delta (pending_additional_credits), "
"not the full cost or the original charge again."
)
assert called_reason == "duration_confirm", (
f"Expected reason='duration_confirm', got {called_reason}"
)
assert called_count_as_creation is False, (
"count_as_job_creation must be False for a delta top-up "
f"(job was already counted at create_job). Got: {called_count_as_creation}"
)
def test_confirm_duration_updates_credits_charged_to_total(self, test_setup, mock_creds):
"""
After confirm, state_data.credits_charged must be updated to 4
(2 original + 2 delta), not left at 2.
"""
setup = test_setup
patches = [
patch("backend.api.routes.jobs.job_manager", setup["mock_jm"]),
patch("backend.api.routes.jobs.worker_service", setup["mock_ws"]),
patch("backend.api.routes.jobs.get_user_service", return_value=setup["mock_us"]),
patch("google.auth.default", return_value=(mock_creds, "test-project")),
]
from fastapi.testclient import TestClient
from backend.main import app
with patches[0], patches[1], patches[2], patches[3]:
client = TestClient(app)
client.post(
f"/api/jobs/{setup['job_id']}/confirm-duration",
json={"acknowledged_credits": 4},
headers={"Authorization": "Bearer test-admin-token"},
)
# Collect all update_job calls and check credits_charged was set to 4
all_updates = {}
for c in setup["mock_jm"].update_job.call_args_list:
updates_arg = c.args[1] if (c.args and len(c.args) >= 2) else c.kwargs.get("updates", {})
if isinstance(updates_arg, dict):
all_updates.update(updates_arg)
assert all_updates.get("state_data.credits_charged") == 4, (
f"Expected credits_charged=4 in update_job call. "
f"Actual updates written: {all_updates}"
)
assert all_updates.get("state_data.pending_additional_credits") == 0, (
"Expected pending_additional_credits=0 after confirm"
)
def test_confirm_duration_transitions_to_separating_stage1(self, test_setup, mock_creds):
"""
The job must be transitioned OUT of AWAITING_DURATION_CONFIRM to
SEPARATING_STAGE1 before workers are triggered.
"""
setup = test_setup
patches = [
patch("backend.api.routes.jobs.job_manager", setup["mock_jm"]),
patch("backend.api.routes.jobs.worker_service", setup["mock_ws"]),
patch("backend.api.routes.jobs.get_user_service", return_value=setup["mock_us"]),
patch("google.auth.default", return_value=(mock_creds, "test-project")),
]
from fastapi.testclient import TestClient
from backend.main import app
with patches[0], patches[1], patches[2], patches[3]:
client = TestClient(app)
client.post(
f"/api/jobs/{setup['job_id']}/confirm-duration",
json={"acknowledged_credits": 4},
headers={"Authorization": "Bearer test-admin-token"},
)
setup["mock_jm"].transition_to_state.assert_called()
call_args = setup["mock_jm"].transition_to_state.call_args
new_status = (
call_args.args[1]
if (call_args.args and len(call_args.args) >= 2)
else call_args.kwargs.get("new_status")
)
assert new_status == JobStatus.SEPARATING_STAGE1, (
f"Expected transition to SEPARATING_STAGE1, got {new_status}"
)
def test_confirm_duration_wrong_acknowledged_credits_returns_409(self, test_setup, mock_creds):
"""
If acknowledged_credits does not match expected_total (credits_charged + owed),
the endpoint must return 409 (stale client; frontend should refresh).
"""
setup = test_setup
# Reset side_effect so get_job always returns paused_job for this test
setup["mock_jm"].get_job.side_effect = None
setup["mock_jm"].get_job.return_value = setup["paused_job"]
patches = [
patch("backend.api.routes.jobs.job_manager", setup["mock_jm"]),
patch("backend.api.routes.jobs.worker_service", setup["mock_ws"]),
patch("backend.api.routes.jobs.get_user_service", return_value=setup["mock_us"]),
patch("google.auth.default", return_value=(mock_creds, "test-project")),
]
from fastapi.testclient import TestClient
from backend.main import app
with patches[0], patches[1], patches[2], patches[3]:
client = TestClient(app)
response = client.post(
f"/api/jobs/{setup['job_id']}/confirm-duration",
json={"acknowledged_credits": 3}, # wrong — expected 4
headers={"Authorization": "Bearer test-admin-token"},
)
assert response.status_code == 409, (
f"Expected 409 for mismatched acknowledged_credits, got {response.status_code}: {response.text}"
)
# No deduction must happen on a 409
setup["mock_us"].deduct_credits.assert_not_called()
def test_confirm_duration_insufficient_credits_returns_402(self, test_setup, mock_creds):
"""
If deduct_credits fails (user is broke), the endpoint must return 402.
No state changes should persist (no transition, job stays paused).
"""
setup = test_setup
setup["mock_jm"].get_job.side_effect = None
setup["mock_jm"].get_job.return_value = setup["paused_job"]
# Simulate insufficient credits
setup["mock_us"].deduct_credits.return_value = (False, 0, "Insufficient credits")
patches = [
patch("backend.api.routes.jobs.job_manager", setup["mock_jm"]),
patch("backend.api.routes.jobs.worker_service", setup["mock_ws"]),
patch("backend.api.routes.jobs.get_user_service", return_value=setup["mock_us"]),
patch("google.auth.default", return_value=(mock_creds, "test-project")),
]
from fastapi.testclient import TestClient
from backend.main import app
with patches[0], patches[1], patches[2], patches[3]:
client = TestClient(app)
response = client.post(
f"/api/jobs/{setup['job_id']}/confirm-duration",
json={"acknowledged_credits": 4},
headers={"Authorization": "Bearer test-admin-token"},
)
assert response.status_code == 402, (
f"Expected 402 for insufficient credits, got {response.status_code}: {response.text}"
)
# Job must NOT be transitioned when user can't pay
setup["mock_jm"].transition_to_state.assert_not_called()
def test_confirm_duration_full_credit_math_invariant(self, test_setup, mock_creds):
"""
FULL CREDIT MATH end-to-end invariant:
- Start: credits_charged=2 (at job creation time, original deduction=2)
- Reconcile: actual=2100s → required=4 → delta=2 (no deduction yet, just pause)
- Confirm: exactly 2 more credits deducted; credits_charged updated to 4
- Total lifetime deduction from account: 2 (at create) + 2 (at confirm) = 4
- Not 4 + anything, not 2 again — exactly the delta
"""
setup = test_setup
patches = [
patch("backend.api.routes.jobs.job_manager", setup["mock_jm"]),
patch("backend.api.routes.jobs.worker_service", setup["mock_ws"]),
patch("backend.api.routes.jobs.get_user_service", return_value=setup["mock_us"]),
patch("google.auth.default", return_value=(mock_creds, "test-project")),
]
from fastapi.testclient import TestClient
from backend.main import app
# Phase 1: simulate reconcile_duration (engine side, mocked collaborators)
engine_jm = _make_mock_job_manager(
_make_job(job_id=setup["job_id"], credits_charged=2)
)
engine_us = _make_mock_user_service()
engine_result = reconcile_duration(
job_id=setup["job_id"],
job_manager=engine_jm,
user_service=engine_us,
probe_duration=lambda _j: 2100.0,
)
# Verify engine produced the correct pause signal
assert engine_result.action == "pause"
assert engine_result.pending_additional_credits == 2
engine_us.deduct_credits.assert_not_called() # engine must NOT deduct
# Phase 2: hit the confirm endpoint
with patches[0], patches[1], patches[2], patches[3]:
client = TestClient(app)
response = client.post(
f"/api/jobs/{setup['job_id']}/confirm-duration",
json={"acknowledged_credits": 4},
headers={"Authorization": "Bearer test-admin-token"},
)
assert response.status_code == 200
# The confirm endpoint must have deducted exactly the delta
setup["mock_us"].deduct_credits.assert_called_once()
deduct_call = setup["mock_us"].deduct_credits.call_args
deducted = deduct_call.kwargs.get("amount", deduct_call.args[2] if len(deduct_call.args) > 2 else None)
assert deducted == 2, (
f"CREDIT MATH INVARIANT FAILED: deduct_credits called with amount={deducted}, "
"expected 2 (the delta only). "
"Total lifetime cost must be original_2 + delta_2 = 4, not more."
)
# credits_charged in state_data must end at 4
all_updates = {}
for c in setup["mock_jm"].update_job.call_args_list:
upd = (c.args[1] if (c.args and len(c.args) >= 2) else c.kwargs.get("updates", {}))
if isinstance(upd, dict):
all_updates.update(upd)
assert all_updates.get("state_data.credits_charged") == 4
+21 -22
View File
@@ -241,10 +241,10 @@ class TestYouTubeDownloadErrorHandling:
assert "Remote download failed" in str(exc.value)
@pytest.mark.asyncio
async def test_invalid_youtube_url_raises_clear_error(self):
async def test_download_without_flacfetch_raises_clear_error(self):
"""
When given an invalid YouTube URL (no video ID extractable),
should raise a clear error.
With no flacfetch configured, download must fail clearly (no local
yt-dlp fallback on Cloud Run).
"""
from backend.services.youtube_download_service import (
YouTubeDownloadService,
@@ -261,11 +261,11 @@ class TestYouTubeDownloadErrorHandling:
with pytest.raises(YouTubeDownloadError) as exc:
await service.download(
url="not-a-valid-youtube-url",
url="https://youtu.be/abcDEF12345",
job_id="job123",
)
assert "Could not extract video ID" in str(exc.value)
assert "flacfetch" in str(exc.value).lower()
class TestRemoteVsLocalDownload:
@@ -306,13 +306,20 @@ class TestRemoteVsLocalDownload:
assert "uploads/job_test/audio/" in result
@pytest.mark.asyncio
async def test_local_download_when_remote_not_configured(self):
async def test_non_youtube_url_uses_generic_url_source(self):
"""
When FLACFETCH_API_URL is not configured, should fall back to local.
A non-YouTube URL is routed through flacfetch's generic 'URL' source.
"""
mock_client = MagicMock()
mock_client.download_by_id = AsyncMock(return_value="download_123")
mock_client.wait_for_download = AsyncMock(return_value={
"status": "complete",
"gcs_path": "gs://bucket/uploads/job_test/audio/test.m4a",
})
with patch(
'backend.services.youtube_download_service.get_flacfetch_client',
return_value=None # No remote client
return_value=mock_client
):
from backend.services.youtube_download_service import (
YouTubeDownloadService,
@@ -321,18 +328,10 @@ class TestRemoteVsLocalDownload:
reset_youtube_download_service()
service = YouTubeDownloadService()
assert service.is_remote_enabled() is False
sc_url = "https://soundcloud.com/forss/flickermood"
result = await service.download(url=sc_url, job_id="job_test")
# Mock the local download to avoid actually calling yt_dlp
with patch.object(
service, '_download_local',
new_callable=AsyncMock,
return_value="uploads/job/audio/test.wav"
) as mock_local:
result = await service.download(
url="https://youtu.be/abcDEF12345",
job_id="job_test",
)
mock_local.assert_called_once()
assert result == "uploads/job/audio/test.wav"
call_kwargs = mock_client.download_by_id.call_args.kwargs
assert call_kwargs["source_name"] == "URL"
assert call_kwargs["download_url"] == sc_url
assert "uploads/job_test/audio/" in result
Whitespace-only changes.
@@ -0,0 +1,203 @@
"""Tests for the per-job auto-correct suggestion cache."""
from __future__ import annotations
from unittest.mock import patch
from backend.services.auto_correct.service import (
AutoCorrectResult,
AutoCorrectService,
Suggestion,
)
from backend.services.auto_correct.settings import AutoCorrectSettings
SEGMENTS = [
{
"id": "seg-1",
"words": [
{"id": "w0", "text": "straight"},
{"id": "w1", "text": "glory"},
],
},
]
REFS = {"genius": {"segments": [{"text": "straight chlorine"}]}}
RAW = {
"suggestions": [
{
"op": "replace",
"start_idx": 1,
"end_idx": 1,
"new_text": "chlorine",
"reason": "r",
"category": "mishearing",
"confidence": 0.9,
}
]
}
FLAT = [("w0", "straight", "seg-1"), ("w1", "glory", "seg-1")]
def _suggest(service, **overrides):
kwargs = dict(
job_id="job-1",
segments=SEGMENTS,
reference_lyrics=REFS,
artist="A",
title="T",
settings=AutoCorrectSettings(),
)
kwargs.update(overrides)
return service.suggest(**kwargs)
def test_cache_hit_skips_model_call() -> None:
service = AutoCorrectService()
cached_result = AutoCorrectResult(
suggestions=[
Suggestion(
id="cached-1",
op="replace",
word_ids=["w1"],
segment_ids=["seg-1"],
original_text="glory",
new_text="chlorine",
reason="r",
category="mishearing",
confidence=0.9,
)
],
model="claude-fable-5",
elapsed_seconds=0.0,
settings_applied=AutoCorrectSettings(),
cached=True,
)
with patch.object(service, "_cache_get", return_value=cached_result), \
patch.object(service, "_call_model") as call, \
patch.object(service, "_cache_put") as put:
result = _suggest(service)
call.assert_not_called()
put.assert_not_called()
assert result.cached is True
assert result.suggestions[0].id == "cached-1"
def test_cache_miss_calls_model_and_writes_cache() -> None:
service = AutoCorrectService()
with patch.object(service, "_cache_get", return_value=None), \
patch.object(service, "_call_model", return_value=(RAW, None)) as call, \
patch.object(service, "_cache_put") as put:
result = _suggest(service)
call.assert_called_once()
put.assert_called_once()
assert result.cached is False
assert put.call_args.args[1] is result
def test_cache_key_stable_for_identical_input() -> None:
s = AutoCorrectSettings()
k1 = AutoCorrectService._cache_path("j", ["m"], s, FLAT, REFS, "A", "T")
k2 = AutoCorrectService._cache_path("j", ["m"], s, FLAT, REFS, "A", "T")
assert k1 == k2
assert k1.startswith("jobs/j/lyrics/auto_correct_cache/")
def test_cache_key_changes_with_input() -> None:
s = AutoCorrectSettings()
base = AutoCorrectService._cache_path("j", ["m"], s, FLAT, REFS, "A", "T")
edited_words = [("w0", "straight", "seg-1"), ("w1", "chlorine", "seg-1")]
assert AutoCorrectService._cache_path("j", ["m"], s, edited_words, REFS, "A", "T") != base
assert AutoCorrectService._cache_path("j", ["m", "m2"], s, FLAT, REFS, "A", "T") != base
other_settings = AutoCorrectSettings(min_confidence=0.8)
assert AutoCorrectService._cache_path("j", ["m"], other_settings, FLAT, REFS, "A", "T") != base
other_refs = {"genius": {"segments": [{"text": "different text"}]}}
assert AutoCorrectService._cache_path("j", ["m"], s, FLAT, other_refs, "A", "T") != base
def test_cache_get_round_trips_via_storage_payload() -> None:
"""_cache_put's payload must be readable by _cache_get."""
service = AutoCorrectService()
stored = {}
class FakeBlob:
def exists(self):
return bool(stored)
class FakeStorage:
class bucket: # noqa: N801 - mimic attribute access
@staticmethod
def blob(path):
return FakeBlob()
@staticmethod
def upload_json(path, data):
stored[path] = data
@staticmethod
def download_json(path):
return stored[path]
with patch.object(service, "_get_storage", return_value=FakeStorage()):
original = AutoCorrectResult(
suggestions=[
Suggestion(
id="s1",
op="replace",
word_ids=["w1"],
segment_ids=["seg-1"],
original_text="glory",
new_text="chlorine",
reason="r",
category="mishearing",
confidence=0.9,
models=["m1", "m2"],
consensus=2,
total_models=2,
conflict_group=None,
)
],
model="m1, m2",
elapsed_seconds=5.0,
settings_applied=AutoCorrectSettings(compare_models=True),
warnings=["w"],
)
service._cache_put("p", original)
restored = service._cache_get("p")
assert restored is not None
assert restored.cached is True
assert restored.model == "m1, m2"
assert restored.warnings == ["w"]
assert restored.settings_applied == AutoCorrectSettings(compare_models=True)
s = restored.suggestions[0]
assert s.consensus == 2 and s.models == ["m1", "m2"]
def test_corrupt_cache_entry_is_a_miss() -> None:
service = AutoCorrectService()
class FakeBlob:
def exists(self):
return True
class FakeStorage:
class bucket: # noqa: N801
@staticmethod
def blob(path):
return FakeBlob()
@staticmethod
def download_json(path):
return {"suggestions": [{"bogus": True}], "model": "m"}
with patch.object(service, "_get_storage", return_value=FakeStorage()):
assert service._cache_get("p") is None
def test_storage_failure_never_breaks_request() -> None:
service = AutoCorrectService()
with patch.object(service, "_get_storage", side_effect=RuntimeError("no gcs")), \
patch.object(service, "_call_model", return_value=(RAW, None)):
result = _suggest(service)
assert result.cached is False
assert len(result.suggestions) == 1
@@ -0,0 +1,172 @@
"""Tests for multi-model compare: parallel calls, dedup, consensus, conflicts."""
from __future__ import annotations
from unittest.mock import patch
import pytest
from backend.services.auto_correct.service import (
AutoCorrectService,
AutoCorrectServiceError,
)
from backend.services.auto_correct.settings import AutoCorrectSettings
SEGMENTS = [
{
"id": "seg-1",
"words": [
{"id": "w0", "text": "Sippin'"},
{"id": "w1", "text": "on"},
{"id": "w2", "text": "straight"},
{"id": "w3", "text": "glory"},
{"id": "w4", "text": "today"},
],
},
]
REFS = {"genius": {"segments": [{"text": "Sippin' on straight chlorine"}]}}
COMPARE = AutoCorrectSettings(compare_models=True)
def _sugg(start, end, text, op="replace", confidence=0.9):
return {
"op": op,
"start_idx": start,
"end_idx": end,
"new_text": text,
"reason": "r",
"category": "mishearing",
"confidence": confidence,
}
def _run_compare(responses_by_model, compare_models_env="model-a;model-b",
settings=COMPARE, single_model="gemini-3.1-pro-preview"):
"""responses_by_model: model name -> raw dict response or Exception."""
service = AutoCorrectService()
def fake_call(model, system_prompt, user_prompt, *, job_id):
resp = responses_by_model[model]
if isinstance(resp, Exception):
raise resp
# _call_model now returns (parsed_json, token_usage).
return resp, None
with patch.object(
service.settings, "auto_correct_compare_models", compare_models_env
), patch.object(
service.settings, "auto_correct_model", single_model
), patch.object(service, "_cache_get", return_value=None), \
patch.object(service, "_cache_put"), \
patch.object(service, "_call_model", side_effect=fake_call):
return service.suggest(
job_id="job-1",
segments=SEGMENTS,
reference_lyrics=REFS,
artist="A",
title="T",
settings=settings,
)
def test_identical_suggestions_deduped_with_consensus() -> None:
result = _run_compare({
"model-a": {"suggestions": [_sugg(3, 3, "chlorine", confidence=0.9)]},
"model-b": {"suggestions": [_sugg(3, 3, "chlorine", confidence=0.95)]},
})
assert len(result.suggestions) == 1
s = result.suggestions[0]
assert sorted(s.models) == ["model-a", "model-b"]
assert s.consensus == 2
assert s.total_models == 2
assert s.confidence == 0.95 # max across models
assert s.conflict_group is None
assert result.model == "model-a, model-b"
def test_conflicting_suggestions_share_group() -> None:
result = _run_compare({
"model-a": {"suggestions": [_sugg(3, 3, "chlorine")]},
"model-b": {"suggestions": [_sugg(2, 3, "straight chlorine gas")]},
})
assert len(result.suggestions) == 2
groups = {s.conflict_group for s in result.suggestions}
assert len(groups) == 1 and None not in groups
assert all(s.consensus == 1 and s.total_models == 2 for s in result.suggestions)
def test_non_overlapping_suggestions_have_no_group() -> None:
result = _run_compare({
"model-a": {"suggestions": [_sugg(3, 3, "chlorine")]},
"model-b": {"suggestions": [_sugg(0, 0, "Sipping")]},
})
assert all(s.conflict_group is None for s in result.suggestions)
# sorted by document position
assert [s.word_ids[0] for s in result.suggestions] == ["w0", "w3"]
def test_insert_after_does_not_conflict_with_replace_on_anchor() -> None:
result = _run_compare({
"model-a": {"suggestions": [_sugg(3, 3, "chlorine")]},
"model-b": {"suggestions": [_sugg(3, 3, "up", op="insert_after")]},
})
assert all(s.conflict_group is None for s in result.suggestions)
def test_one_model_failing_produces_warning_not_error() -> None:
result = _run_compare({
"model-a": {"suggestions": [_sugg(3, 3, "chlorine")]},
"model-b": AutoCorrectServiceError("AI model call failed", status_code=502),
})
assert len(result.suggestions) == 1
assert result.suggestions[0].total_models == 1 # only one model answered
assert any("model-b failed" in w for w in result.warnings)
assert result.model == "model-a"
def test_malformed_model_output_warns_instead_of_aborting_compare() -> None:
result = _run_compare({
"model-a": {"suggestions": [_sugg(3, 3, "chlorine")]},
"model-b": {"not_suggestions": []}, # malformed -> _validate raises
})
assert len(result.suggestions) == 1
assert any("model-b failed" in w for w in result.warnings)
assert result.model == "model-a"
def test_all_models_failing_raises_502() -> None:
with pytest.raises(AutoCorrectServiceError) as exc_info:
_run_compare({
"model-a": AutoCorrectServiceError("boom", status_code=502),
"model-b": AutoCorrectServiceError("boom", status_code=502),
})
assert exc_info.value.status_code == 502
def test_compare_falls_back_to_single_when_unconfigured() -> None:
result = _run_compare(
{"gemini-3.1-pro-preview": {"suggestions": [_sugg(3, 3, "chlorine")]}},
compare_models_env="",
)
s = result.suggestions[0]
assert s.total_models == 1
assert s.consensus == 1
def test_single_model_mode_unchanged() -> None:
result = _run_compare(
{"gemini-3.1-pro-preview": {"suggestions": [_sugg(3, 3, "chlorine")]}},
settings=AutoCorrectSettings(), # compare off
)
assert len(result.suggestions) == 1
assert result.suggestions[0].models == ["gemini-3.1-pro-preview"]
def test_three_way_conflict_chain_unifies_groups() -> None:
# a: w2-w3, b: w3-w4, c: w4 — chained overlaps must land in ONE group
result = _run_compare({
"model-a": {"suggestions": [_sugg(2, 3, "x y")]},
"model-b": {"suggestions": [_sugg(3, 4, "y z"), _sugg(4, 4, "z")]},
})
groups = {s.conflict_group for s in result.suggestions}
assert len(groups) == 1 and None not in groups
@@ -0,0 +1,173 @@
"""Tests for auto-correct token pricing and usage extraction/logging."""
from __future__ import annotations
from types import SimpleNamespace
from unittest.mock import patch
from backend.services.auto_correct.pricing import (
MODEL_PRICING,
estimate_cost_usd,
get_rate,
)
from backend.services.auto_correct.service import AutoCorrectService
from backend.services.auto_correct.settings import AutoCorrectSettings
# ---- pricing ----
def test_estimate_cost_fable_known_rates() -> None:
# 5000 in @ $10/M + 4000 out @ $50/M = 0.05 + 0.20 = 0.25
usage = {
"input_tokens": 5000,
"output_tokens": 4000,
"cache_read_tokens": 0,
"thinking_tokens": None,
}
cost = estimate_cost_usd("claude-fable-5", usage)
assert cost == round(0.05 + 0.20, 10)
def test_estimate_cost_includes_cache_read() -> None:
usage = {
"input_tokens": 1_000_000,
"output_tokens": 0,
"cache_read_tokens": 1_000_000,
"thinking_tokens": None,
}
# 1M input @ $10 + 1M cache_read @ $1 = 11.0
assert estimate_cost_usd("claude-fable-5", usage) == 11.0
def test_estimate_cost_none_usage_returns_none() -> None:
assert estimate_cost_usd("claude-fable-5", None) is None
def test_estimate_cost_unknown_model_returns_none() -> None:
usage = {
"input_tokens": 1000,
"output_tokens": 1000,
"cache_read_tokens": 0,
"thinking_tokens": None,
}
assert estimate_cost_usd("some-unknown-model-9", usage) is None
def test_get_rate_prefix_match_for_dated_snapshot() -> None:
# A dated snapshot id still resolves to its family rate card.
assert get_rate("claude-fable-5-20260601") == MODEL_PRICING["claude-fable-5"]
# ---- usage extraction ----
def test_anthropic_usage_extraction() -> None:
response = SimpleNamespace(
usage=SimpleNamespace(
input_tokens=4321,
output_tokens=3210,
cache_read_input_tokens=100,
)
)
usage = AutoCorrectService._anthropic_usage(response)
assert usage == {
"input_tokens": 4321,
"output_tokens": 3210, # already includes thinking
"cache_read_tokens": 100,
"thinking_tokens": None,
}
def test_gemini_usage_folds_thoughts_into_output() -> None:
response = SimpleNamespace(
usage_metadata=SimpleNamespace(
prompt_token_count=4000,
candidates_token_count=500,
thoughts_token_count=2500,
cached_content_token_count=0,
)
)
usage = AutoCorrectService._gemini_usage(response)
assert usage == {
"input_tokens": 4000,
"output_tokens": 3000, # 500 visible + 2500 thinking
"cache_read_tokens": 0,
"thinking_tokens": 2500,
}
def test_usage_extraction_never_raises_on_bad_shape() -> None:
# Missing usage attribute entirely -> None, not an exception.
assert AutoCorrectService._anthropic_usage(SimpleNamespace()) is None
assert AutoCorrectService._gemini_usage(SimpleNamespace()) is None
# ---- logging ----
SEGMENTS = [
{"id": "seg-1", "words": [{"id": "w0", "text": "glory"}]},
]
REFS = {"genius": {"segments": [{"text": "chlorine"}]}}
def _raw():
return {
"suggestions": [
{
"op": "replace",
"start_idx": 0,
"end_idx": 0,
"new_text": "chlorine",
"reason": "r",
"category": "mishearing",
"confidence": 0.9,
}
]
}
def test_suggest_logs_per_model_and_total_cost(caplog) -> None:
service = AutoCorrectService()
usage = {
"input_tokens": 5000,
"output_tokens": 4000,
"cache_read_tokens": 0,
"thinking_tokens": None,
}
with patch.object(service, "_cache_get", return_value=None), \
patch.object(service, "_cache_put"), \
patch.object(service, "_call_model", return_value=(_raw(), usage)), \
patch.object(service.settings, "auto_correct_model", "claude-fable-5"):
with caplog.at_level("INFO"):
service.suggest(
job_id="job-1",
segments=SEGMENTS,
reference_lyrics=REFS,
artist="A",
title="T",
settings=AutoCorrectSettings(),
)
text = caplog.text
assert "auto-correct usage job=job-1 model=claude-fable-5" in text
assert "input_tokens=5000" in text
assert "output_tokens=4000" in text
assert "est_cost_usd=0.2500" in text
assert "auto-correct cost job=job-1" in text
assert "total_est_cost_usd=0.2500" in text
def test_suggest_logs_unavailable_usage_without_crashing(caplog) -> None:
service = AutoCorrectService()
with patch.object(service, "_cache_get", return_value=None), \
patch.object(service, "_cache_put"), \
patch.object(service, "_call_model", return_value=(_raw(), None)), \
patch.object(service.settings, "auto_correct_model", "claude-fable-5"):
with caplog.at_level("INFO"):
service.suggest(
job_id="job-2",
segments=SEGMENTS,
reference_lyrics=REFS,
artist="A",
title="T",
settings=AutoCorrectSettings(),
)
assert "auto-correct usage job=job-2 model=claude-fable-5 tokens=unavailable" in caplog.text
assert "total_est_cost_usd=unknown" in caplog.text
@@ -0,0 +1,56 @@
"""Tests for auto-correct prompt construction."""
from __future__ import annotations
from backend.services.auto_correct.prompts import (
build_system_prompt,
build_user_prompt,
)
from backend.services.auto_correct.settings import AutoCorrectSettings
def test_system_prompt_default_allows_adlib_suggestions() -> None:
p = build_system_prompt(AutoCorrectSettings())
assert "adlib_removal" in p
assert "NEVER suggest deleting backing vocals" not in p
assert "insert_after" in p
def test_system_prompt_adlib_disabled() -> None:
p = build_system_prompt(AutoCorrectSettings(suggest_adlib_removal=False))
assert "NEVER suggest deleting backing vocals" in p
def test_system_prompt_insertions_disabled() -> None:
p = build_system_prompt(AutoCorrectSettings(allow_insertions=False))
assert 'NEVER use the "insert_after" operation' in p
def test_user_prompt_word_indices_are_global_and_sequential() -> None:
segments = [
{"id": "s1", "words": [{"id": "a", "text": "Hello"}, {"id": "b", "text": "there"}]},
{"id": "s2", "words": [{"id": "c", "text": "world"}]},
]
refs = {
"genius": {"segments": [{"text": "Hello there"}, {"text": "world"}]},
"lrclib": {"segments": [{"text": "Hello their world"}]},
}
p = build_user_prompt(
segments=segments, reference_lyrics=refs, artist="Artist", title="Title"
)
assert "ARTIST: Artist" in p
assert "[L000] 0:Hello 1:there" in p
assert "[L001] 2:world" in p
assert "REFERENCE LYRICS (genius):" in p
assert "REFERENCE LYRICS (lrclib):" in p
assert "Hello their world" in p
def test_user_prompt_handles_missing_metadata() -> None:
p = build_user_prompt(
segments=[{"id": "s1", "words": []}],
reference_lyrics={},
artist=None,
title=None,
)
assert "ARTIST: unknown" in p
assert "TITLE: unknown" in p
@@ -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()
@@ -0,0 +1,281 @@
"""Tests for AutoCorrectService validation and suggestion mapping."""
from __future__ import annotations
from unittest.mock import patch
import pytest
from backend.services.auto_correct.service import (
AutoCorrectService,
AutoCorrectServiceError,
)
from backend.services.auto_correct.settings import AutoCorrectSettings
SEGMENTS = [
{
"id": "seg-1",
"words": [
{"id": "w0", "text": "Sippin'"},
{"id": "w1", "text": "on"},
{"id": "w2", "text": "straight"},
{"id": "w3", "text": "glory"},
],
},
{
"id": "seg-2",
"words": [
{"id": "w4", "text": "yeah"},
{"id": "w5", "text": "yeah"},
],
},
]
REFS = {"genius": {"segments": [{"text": "Sippin' on straight chlorine"}]}}
def _suggest(raw_response, settings=None):
service = AutoCorrectService()
with patch.object(service, "_call_model", return_value=(raw_response, None)), \
patch.object(service, "_cache_get", return_value=None), \
patch.object(service, "_cache_put"):
return service.suggest(
job_id="job-1",
segments=SEGMENTS,
reference_lyrics=REFS,
artist="A",
title="T",
settings=settings or AutoCorrectSettings(),
)
def _raw(op="replace", start=3, end=3, text="chlorine", category="mishearing",
confidence=0.95):
return {
"suggestions": [
{
"op": op,
"start_idx": start,
"end_idx": end,
"new_text": text,
"reason": "matches reference",
"category": category,
"confidence": confidence,
}
]
}
def test_replace_maps_indices_to_word_ids() -> None:
result = _suggest(_raw())
assert len(result.suggestions) == 1
s = result.suggestions[0]
assert s.op == "replace"
assert s.word_ids == ["w3"]
assert s.segment_ids == ["seg-1"]
assert s.original_text == "glory"
assert s.new_text == "chlorine"
assert result.warnings == []
def test_multi_word_span_crossing_segments() -> None:
result = _suggest(_raw(start=3, end=4, text="chlorine yeah"))
s = result.suggestions[0]
assert s.word_ids == ["w3", "w4"]
assert sorted(s.segment_ids) == ["seg-1", "seg-2"]
assert s.original_text == "glory yeah"
def test_delete_suggestion() -> None:
result = _suggest(_raw(op="delete", start=4, end=5, text=""))
s = result.suggestions[0]
assert s.op == "delete"
assert s.new_text == ""
assert s.word_ids == ["w4", "w5"]
def test_insert_after_uses_anchor_word() -> None:
result = _suggest(_raw(op="insert_after", start=2, end=2, text="up"))
s = result.suggestions[0]
assert s.op == "insert_after"
assert s.word_ids == ["w2"]
def test_out_of_range_indices_dropped_with_warning() -> None:
result = _suggest(_raw(start=99, end=99))
assert result.suggestions == []
assert len(result.warnings) == 1
assert "out of range" in result.warnings[0]
def test_replace_with_empty_text_dropped() -> None:
result = _suggest(_raw(text=" "))
assert result.suggestions == []
assert "empty new_text" in result.warnings[0]
def test_below_min_confidence_dropped() -> None:
result = _suggest(
_raw(confidence=0.4), settings=AutoCorrectSettings(min_confidence=0.6)
)
assert result.suggestions == []
assert "below threshold" in result.warnings[0]
def test_adlib_removal_dropped_when_disabled() -> None:
result = _suggest(
_raw(op="delete", start=4, end=5, text="", category="adlib_removal"),
settings=AutoCorrectSettings(suggest_adlib_removal=False),
)
assert result.suggestions == []
assert "adlib removal disabled" in result.warnings[0]
def test_insertions_dropped_when_disabled() -> None:
result = _suggest(
_raw(op="insert_after", start=2, end=2, text="up"),
settings=AutoCorrectSettings(allow_insertions=False),
)
assert result.suggestions == []
assert "insertions disabled" in result.warnings[0]
def test_unknown_category_coerced_to_other() -> None:
result = _suggest(_raw(category="weird"))
assert result.suggestions[0].category == "other"
def test_confidence_clamped() -> None:
result = _suggest(_raw(confidence=1.7))
assert result.suggestions[0].confidence == 1.0
def test_no_reference_lyrics_raises_422() -> None:
service = AutoCorrectService()
with pytest.raises(AutoCorrectServiceError) as exc_info:
service.suggest(
job_id="job-1",
segments=SEGMENTS,
reference_lyrics={},
artist=None,
title=None,
settings=AutoCorrectSettings(),
)
assert exc_info.value.status_code == 422
def test_empty_segments_raises_400() -> None:
service = AutoCorrectService()
with pytest.raises(AutoCorrectServiceError) as exc_info:
service.suggest(
job_id="job-1",
segments=[],
reference_lyrics=REFS,
artist=None,
title=None,
settings=AutoCorrectSettings(),
)
assert exc_info.value.status_code == 400
def test_missing_segment_ids_raises() -> None:
service = AutoCorrectService()
with pytest.raises(AutoCorrectServiceError, match="segments must have ids"):
service.suggest(
job_id="job-1",
segments=[{"words": [{"id": "w0", "text": "hi"}]}],
reference_lyrics=REFS,
artist=None,
title=None,
settings=AutoCorrectSettings(),
)
def test_missing_word_ids_raises() -> None:
service = AutoCorrectService()
with pytest.raises(AutoCorrectServiceError, match="ids"):
service.suggest(
job_id="job-1",
segments=[{"id": "s", "words": [{"text": "no-id"}]}],
reference_lyrics=REFS,
artist=None,
title=None,
settings=AutoCorrectSettings(),
)
def test_malformed_model_response_raises_502() -> None:
with pytest.raises(AutoCorrectServiceError) as exc_info:
_suggest({"not_suggestions": []})
assert exc_info.value.status_code == 502
def test_non_dict_suggestion_entries_dropped() -> None:
result = _suggest({"suggestions": ["bogus", 42]})
assert result.suggestions == []
assert len(result.warnings) == 2
def test_call_model_dispatches_claude_to_anthropic() -> None:
service = AutoCorrectService()
with patch.object(service, "_call_anthropic", return_value=({"suggestions": []}, None)) as anth, \
patch.object(service, "_call_gemini", return_value=({"suggestions": []}, None)) as gem:
service._call_model("claude-fable-5", "s", "u", job_id="j")
anth.assert_called_once()
gem.assert_not_called()
service._call_model("gemini-3.1-pro-preview", "s", "u", job_id="j")
gem.assert_called_once()
def test_anthropic_schema_strips_genai_pollution(monkeypatch) -> None:
"""google-genai mutates schema dicts in place (adds property_ordering);
the anthropic path must send a clean strict schema regardless."""
from unittest.mock import MagicMock
import backend.services.auto_correct.service as svc_mod
import copy
monkeypatch.setenv("ANTHROPIC_API_KEY", "test-key")
# Deep copy so this test never mutates the real module-level schema.
polluted = copy.deepcopy(svc_mod.RESPONSE_SCHEMA)
polluted["property_ordering"] = ["suggestions"]
polluted["properties"]["suggestions"]["items"]["property_ordering"] = ["op"]
monkeypatch.setattr(svc_mod, "RESPONSE_SCHEMA", polluted)
captured = {}
class FakeClient:
def __init__(self, **kwargs):
self.messages = MagicMock()
def create(**ckwargs):
captured.update(ckwargs)
block = MagicMock()
block.type = "text"
block.text = '{"suggestions": []}'
resp = MagicMock()
resp.content = [block]
return resp
self.messages.create = create
import anthropic as anthropic_sdk
monkeypatch.setattr(anthropic_sdk, "Anthropic", FakeClient)
service = AutoCorrectService()
raw, _usage = service._call_anthropic("claude-fable-5", "s", "u", job_id="j")
assert raw == {"suggestions": []}
schema = captured["output_config"]["format"]["schema"]
assert "property_ordering" not in schema
assert "property_ordering" not in schema["properties"]["suggestions"]["items"]
assert schema["additionalProperties"] is False
# and the polluted module constant was not further mutated
assert "property_ordering" in polluted
def test_anthropic_without_api_key_raises_502(monkeypatch) -> None:
monkeypatch.delenv("ANTHROPIC_API_KEY", raising=False)
service = AutoCorrectService()
with pytest.raises(AutoCorrectServiceError) as exc_info:
service._call_anthropic("claude-fable-5", "s", "u", job_id="j")
assert exc_info.value.status_code == 502
assert "not configured" in str(exc_info.value)
@@ -0,0 +1,61 @@
"""Tests for AutoCorrectSettings parsing/validation."""
from __future__ import annotations
import pytest
from backend.services.auto_correct.settings import (
AutoCorrectSettings,
settings_from_dict,
)
def test_default_settings() -> None:
s = AutoCorrectSettings()
assert s.suggest_adlib_removal is True
assert s.allow_insertions is True
assert s.min_confidence == 0.0
def test_settings_from_dict_defaults_when_empty() -> None:
assert settings_from_dict({}) == AutoCorrectSettings()
def test_settings_from_dict_partial() -> None:
s = settings_from_dict({"suggest_adlib_removal": False})
assert s.suggest_adlib_removal is False
assert s.allow_insertions is True
def test_settings_from_dict_full() -> None:
s = settings_from_dict(
{
"suggest_adlib_removal": False,
"allow_insertions": False,
"min_confidence": 0.75,
}
)
assert s == AutoCorrectSettings(
suggest_adlib_removal=False, allow_insertions=False, min_confidence=0.75
)
def test_settings_from_dict_unknown_key_raises() -> None:
with pytest.raises(ValueError, match="unknown settings"):
settings_from_dict({"bogus": 1})
@pytest.mark.parametrize("value", [-0.1, 1.5, "high", None, True, False])
def test_settings_from_dict_invalid_confidence_raises(value) -> None:
with pytest.raises(ValueError, match="min_confidence"):
settings_from_dict({"min_confidence": value})
@pytest.mark.parametrize("key", ["suggest_adlib_removal", "allow_insertions"])
def test_settings_from_dict_non_bool_flag_raises(key) -> None:
with pytest.raises(ValueError, match=key):
settings_from_dict({key: "yes"})
def test_to_dict_round_trip() -> None:
s = AutoCorrectSettings(suggest_adlib_removal=False, min_confidence=0.5)
assert settings_from_dict(s.to_dict()) == s
@@ -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"]
Whitespace-only changes.
Loaded 100 of 520 files, more files were not shown because too many files have changed in this diff. Show more