mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-05 09:28:25 +09:00
36b331f3d7411ecf97c05bf15146e83161ab94de
331
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
36b331f3d7 |
feat(requests-board): admin history view + fix community publish transition (#1008)
## Why Andrew asked whether we can see past community-requests-board submissions and whether our first real user got a video. Investigation surfaced: - **First real user was fully served.** `tas041964@gmail.com` requested *Sam Cooke and the Soul Stirrers – Wonderful* (Sep 15); it was auto-picked, generated, published to YouTube (NOMAD-1650), and he got the completion email + emailed thanks. ✅ - **No admin view existed** to see this — you had to query Firestore directly. - **A real bug:** the community publish fan-out (`mark_published` + voter emails) fired **only** on the `youtube_upload_queue` path. Jobs published via the direct video-worker distribution path (like Sam Cooke's) bypassed it, so the request stayed `in_progress`, never lit up the board's public "Recently made" list, and other up-voters would silently miss their "track is live" email. ## What 1. **Fix the publish transition** — extract the fan-out into `backend/services/community_publish.py` and call it from **both** publish paths (`youtube_queue_processor` + `video_worker`). Also fixes a latent `len(int)` crash in the log line. 2. **Backfill / safety net** — `POST /api/internal/community-requests/reconcile`: idempotent, publishes any `in_progress` pick whose job is already live on YouTube. (Will be run in prod post-deploy to fix the Sam Cooke request.) 3. **Admin history view** — `GET /api/admin/community-requests` + a `/admin/community-requests` page: every request, all statuses, with requester, votes, and job + YouTube links. The public board's "Recently made" section already existed in the UI — it was empty only because of bug #1; fixing the transition (+ reconcile backfill) lights it up. ## Testing - `backend/tests/test_community_voter_notify.py` — fan-out from the shared module, both-path idempotency, voter dedupe/retry, YouTube-url resolution, and the reconcile scan. - `backend/tests/test_community_review_admin.py` — the new admin history endpoint maps all statuses. - All 31 requests-board + 158 worker tests pass. The one unrelated failure in `test_audio_processor_local_gpu.py` is pre-existing (confirmed with changes stashed). ## Notes - Admin surface is English-only (no i18n changes); no `en.json` strings added. - Local CodeRabbit review couldn't run (CLI requires life360-org SSO; no seat on this repo) — leaving to the GitHub bot. Plan: `docs/archive/2026-09-17-requests-board-history-and-publish-transition-plan.md` 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Added an admin Community Requests history page covering all statuses, votes, submitters, review details, linked jobs, and YouTube videos. - Added admin reconciliation for eligible requests with live videos. - Added automatic voter email notifications after community-request publication. - **Bug Fixes** - Improved publication handling across direct and queued video workflows. - Added recovery for incomplete voter notifications and missed publication transitions. - **Documentation** - Documented the community-request history and reconciliation API endpoints. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
083a478aba |
fix(e2e+email): Stripe redirect not source-of-truth + benign Postmark suppressions (#1009)
## Summary Fixes the two remaining open threads from the 2026-09-15 E2E/overnight-error triage — both diagnosed as **benign false alarms**, now hardened so they stop paging. ### 1. Stripe Stage-1 "Credit Purchase" E2E flake (daily #173) **Root cause:** the test failed when the browser redirect back from Stripe timed out (`stripe-checkout.ts` `waitForURL` 60s), even though the charge completed and credits were granted server-side. Prod logs confirmed the Stripe `checkout.session.completed` webhook fired on the "failed" runs too, and the next scheduled daily passed identically — a browser-redirect flake, **not** a credit-delivery outage. **Fix:** make the **server-side credit grant** the authoritative pass/fail gate. - `completeStripeCheckout()` now returns `{ redirected }` instead of throwing on the redirect wait. - The spec polls the read-only admin detail endpoint (`GET /api/users/admin/users/{email}/detail`) for a credit increase above a pre-purchase baseline — that's the real gate. The browser redirect + success-page assertions become best-effort UX checks. ### 2. Postmark 422 "Failed to send magic link" ERROR alerts **Root cause:** junk/placeholder addresses (e.g. `whatever@example.com`) typed into the sign-in form that Postmark has suppressed (hard bounce / spam / manual) → `ErrorCode 406 (InactiveRecipient)` → logged at ERROR → paged. Not the E2E suite (uses testmail.app) and not outreach. **Fix:** detect `ErrorCode 406`, log it at **INFO** (not ERROR), and surface a `suppressed` flag (`SendResult.suppressed` → `provider.last_suppressed` → `EmailService.last_send_suppressed`) so the magic-link + resend handlers log suppressed recipients at INFO instead of paging. ## Testing - 4 new `test_email_service.py` unit tests: suppressed flagging + no ERROR log, non-406 422 still errors, reset-on-success, end-to-end `last_send_suppressed` wiring. - All 47 `test_email_service` + 31 resend/tenant tests pass. Frontend `tsc` clean on both changed files. - The E2E robustness change is exercised by the next E2E Daily (Payment + Happy Path) run post-deploy. ## Notes - Local CodeRabbit CLI review was blocked by a workspace-SSO/org mismatch (CLI is authed to a different org), so this PR is left open for the GitHub CodeRabbit bot to review. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
20c8cc762e |
fix(jobs): durable prep→screens handoff — stop orphaning jobs at downloading (#1002)
## Problem Root cause of the daily E2E happy-path stalls — and real prod jobs freezing at `downloading` with no error, no recovery. Investigation (this session) found the prep→screens handoff was a **fire-and-forget `asyncio.create_task`** in `job_manager._trigger_screens_worker`. In the lyrics Cloud Run Job, `asyncio.run()`'s loop teardown cancels the still-pending dispatch before the screens Cloud Task is enqueued, so the job never advances. Confirmed on prod job `7b5fc85b` (both prep workers `WORKER_END success`, yet status stuck at `downloading`/15). ## Fix (defense-in-depth) - **Await the dispatch.** `mark_lyrics_complete` now only sets the flag; the lyrics worker `await`s `advance_to_screens_if_ready()`, so the Cloud Task enqueue completes before the worker's event loop tears down. - **Idempotent + fallback trigger.** `advance_to_screens_if_ready` is gated on `lyrics_complete` + `status==DOWNLOADING`, and is *also* called by the audio worker — if the lyrics dispatch was lost, whichever worker finishes last rescues the job. Preserves the audio/review decoupling (screens gated on lyrics only). - **Screens worker idempotency.** A duplicate dispatch (both triggers, or a Cloud Tasks redelivery) no-ops via a status guard instead of re-running the invalid `GENERATING_SCREENS` transition. - **Watchdog coverage.** `recover-stuck-jobs` (every 5 min) now re-triggers any job left at `DOWNLOADING` with `lyrics_complete` but no screens — mirrors the existing `REVIEW_COMPLETE` lost-render recovery, closing the `DOWNLOADING` blind spot (it only scanned `DOWNLOADING_AUDIO`). This is workstream **W1 + W3a** of the plan in `docs/archive/2026-09-15-e2e-job-orchestration-stalls-plan.md` (Mode A). Mode B (review-submit reliability) follows in a separate PR. ## Testing - Rewrote `TestPipelineDecoupling` for the flag/advance split: triggers when ready, no-ops when lyrics not done, idempotent when already advanced, and the **audio-fallback rescues a lost lyrics trigger**. - New `test_screens_worker_idempotency.py`: duplicate dispatch no-ops; first dispatch proceeds. - New `recover-stuck-jobs` tests: stale-DOWNLOADING-with-lyrics re-triggers; fresh / without-lyrics don't. - Full affected backend subset green (413 passed; the 5 `*_requires_auth` failures are pre-existing — they fail identically on `main` with these changes stashed). ## Deploy Standard backend deploy (Cloud Run) on merge — no infra/Pulumi change (the watchdog cron already runs every 5 min). <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Bug Fixes** * Improved reliability of screen generation after lyrics transcription completes. * Automatically recovers jobs that remain stuck before screen generation. * Prevented duplicate screen processing when jobs are retried or dispatched more than once. * Added fallback recovery when audio completion occurs after lyrics completion. * **Documentation** * Updated worker coordination documentation to reflect the revised screen-generation flow. * **Chores** * Bumped the package version to 0.225.4. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
d3bc81858a |
Stop scraping karaokenerds.com; read our own community catalog (#998)
## Why
KaraokeNerds (karaokenerds.com) has gotten aggressive with **429 rate
limiting**. We already have an authorized nightly export
(`kn-data-sync`) that lands the community catalog in our own BigQuery
(`karaoke_decide.karaokenerds_community`) + a GCS mirror. This repo's
community-version checks were still **live-scraping**
`karaokenerds.com/Search` on demand (job creation, bulk mode, requests
board, daily picker). This makes them read our own copy instead.
Part of the workspace-wide effort so **nothing** queries
karaokenerds.com except the single `kn-data-sync` export job.
## Changes
- **`backend/services/karaokenerds_service.py`**: replace the
`httpx`+BeautifulSoup scrape of `/Search` with an in-process, TTL-cached
(6h) normalized `{(artist,title) → tracks}` index loaded from the
community export gzip in GCS. Public `check_community_versions` /
`check_community_versions_batch` signatures + return shapes are
**unchanged**, so all four callers and the frontend need no changes.
Fail-open on load error (tracks stay selectable), with a 60s retry
window.
- **`backend/services/kn_brand_names.py`** (new): brand code → human
name map (the export stores only the code). Falls back to the code for
the long tail.
- **`backend/config.py`**: `kn_community_bucket` / `kn_community_blob` /
`kn_community_ttl_seconds`.
- **`infrastructure/functions/divebar_lookup/main.py`**: new
`kn_community_search` action (token-AND normalized query over
`karaokenerds_community`, LIKE-wildcards escaped). This is what
**kjbox** will call to drop its own scrape (follow-up PR).
- No IAM change: the backend SA already has project-level
`storage.objectAdmin`.
## Verification (spot-check: old scrape vs new path, real KN data)
Compared the old live scrape against the new catalog lookup for a
representative set:
- `has_community` matched on every song; brand_name, brand_code, and
canonical YouTube URLs are **byte-identical** to the old scrape
(verified on multi-brand songs, e.g. Nine Inch Nails – Terrible Lie, 5
brands).
- Bonus correctness: the old overlong-query bug (ABBA "I Do, I Do, I Do,
I Do, I Do") returned a false negative; the catalog lookup correctly
finds the NOMAD + RUEABBA versions.
## Tests
`test_karaokenerds_service.py` rewritten (index build/dedupe, normalized
matching, batch, gzip parse, fail-open, URL canonicalization);
`test_bulk_album_lookup.py` batch test reseeded;
`divebar_lookup/test_main.py` gains `kn_community_search` tests. All
green locally.
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
- **New Features**
- Added community catalog search with artist and title matching.
- Search results now include artist, title, brand, and watch
information.
- Added recognizable display names for supported KaraokeNerds brands,
with graceful fallback for unknown codes.
- Community track availability checks now use a refreshed catalog for
faster, more reliable results.
- Added result limits and clear responses for missing or invalid search
queries.
- **Bug Fixes**
- Improved matching, deduplication, and YouTube link normalization for
community tracks.
- Improved handling of unavailable catalog data through safe fallback
behavior.
- **Release**
- Updated the application version to 0.225.0.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
|
||
|
|
3cdb62a058 |
fix: run render-video worker as Cloud Run Job to survive backend deploys (#994)
## Summary Tenant E2E run #107 (`singa`) failed with job `41e06b90` frozen at `rendering_video` — even though the GCE encoder **finished the render and uploaded every output**. Root cause: a backend deploy landed mid-render and killed the render poll, which ran as a FastAPI BackgroundTask on the Cloud Run service. Full investigation: `docs/archive/2026-09-13-render-deploy-survival-investigation.md` ### The failure chain (4 layers, each structurally broken) 1. **BackgroundTask execution** — the render endpoint returns 200 immediately and polls post-response; Cloud Run SIGKILLs old-revision instances ~10s after SIGTERM on every deploy. 2. **Unreachable shutdown parking** — uvicorn waits for background tasks *before* running lifespan shutdown, so `park_active_render_jobs_for_shutdown()` never runs in exactly the scenario it was written for. Its comment claimed a 600s grace period; Cloud Run gives 10s. Verified in logs: the old revision's last lines were uvicorn's `Waiting for background tasks to complete.` — then SIGKILL. 3. **Cloud Tasks retry defeated** — the queue got its 200 at dispatch; `dispatch_deadline=1800s` protects nothing. 4. **45-min stuck sweep** — reachable but slower than the E2E's 30-min budget and a ~50-60 min silent stall + wasted re-render for a real customer, on every deploy that lands mid-render (deploys go out on every merge to main). This is the **identical bug class fixed for the video worker in 2026-03** (`docs/archive/2026-03-08-fix-encoding-deploy-survival.md`, `USE_CLOUD_RUN_JOBS_FOR_VIDEO`) — the render worker was never migrated. ### Changes - **Route `trigger_render_video_worker` through a Cloud Run Job** — reuses `video-encoding-job` with args override `python -m backend.workers.render_video_worker --job-id <id>`, behind `USE_CLOUD_RUN_JOBS_FOR_RENDER` (enabled in deploy env). Job executions run to completion; deploys never touch them. - **New CLI entrypoint** in `render_video_worker.py`. Exit-code contract differs from video_worker deliberately: clean returns (True AND False) exit 0 because `process_render_video` parks/fails/supersedes internally; only an escaped crash exits 1 (job template has `max_retries=2`). - **Worker-side idempotency gate** (review finding): the CRJ path bypasses the HTTP endpoint's `_check_worker_idempotency`, and CRJ retries could re-enter a job in `RENDERING_VIDEO` (hard-failing it via the same-state transition guard) or resurrect a terminal job. The worker now skips terminal + already-rendering jobs cleanly regardless of dispatch path. - **Surface failed video-worker dispatch** (review finding): the ignored `trigger_video_worker` return after render completion now logs at ERROR instead of silently stalling the job at `instrumental_selected`. - **Pulumi**: `video-encoding-job` env gains both `USE_CLOUD_RUN_JOBS_FOR_*` flags so the render execution's in-process video-worker trigger also dispatches a CRJ. **Already applied to prod** (`pulumi up` run locally, verified on the job). - **`main.py`**: corrected the false 600s comment; shrank the unreachable 480s lifespan wait to 5s. Parking hook kept as legacy/flag-off net. ### Rollback Remove `USE_CLOUD_RUN_JOBS_FOR_RENDER=true` from the service env → falls back to the legacy Cloud Tasks path. ## Testing - Backend: 4422 unit + 151 emulator tests pass locally. - New tests: CRJ routing (flag on/off), CLI exit-code contract, worker-side idempotency gate (terminal skip, already-rendering skip). - Post-deploy: will dispatch the Tenant Portals E2E workflow (the failing scenario) against prod. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - Video rendering now runs as durable background jobs, allowing renders to continue through service deployments. - Added safeguards to prevent duplicate processing and safely handle completed or in-progress jobs. - Improved failure reporting when a video-processing job cannot be started. - **Bug Fixes** - Fixed render jobs becoming stuck when deployments interrupted background processing. - **Documentation** - Added troubleshooting guidance and incident lessons for interrupted or stuck renders. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
62843f0286 |
Incident hardening: detection & guardrails (D1 + G1 shadow + D2) (#985)
Part 1 of 3 of the **Incident hardening (post-NOMAD-1632)** initiative (plan: `docs/archive/2026-09-12-incident-hardening-plan.md`, shipped in #984). Follow-up hardening for the incident class — a silent partial publish caught ~24h late, then its fix over-firing and failing real jobs, caught only when a human saw the UI. This PR bundles the three **detection & guardrail** items (the other two PRs cover test-seam/contract/process and deploy/CI/runner robustness). ## D1 — near-real-time alert on ANY job failure The production error monitor is **spike-based** and mathematically blind to a novel low-volume error (`rolling_avg == 0` → never a spike) — exactly why the 2-job guard-over-fire outage went unnoticed. New `backend/services/ops_alerts.py` hooks the single status-write chokepoint (`FirestoreService.update_job_status`) on any transition to `FAILED` and sends an immediate Discord alert to the ops channel, de-duped by a normalized error signature (reuses the error-monitor normalizer). **Novel signatures always alert regardless of count.** - Best-effort: fully wrapped, **never raises** into the status write. - Gated to deployed environments (`is_production`/`FAILURE_ALERTS_ENABLED`); skips `test`/`development` jobs. - Throttle window collapses a burst of the same signature into one alert (configurable). ## G1 — publish-boundary completeness invariant, SHADOW-first New `backend/services/publish_completeness.py` computes the outputs a public GDrive release *should* have shipped (lossy 4K + 720p, CDG when enabled) and compares against what was actually distributed (`gdrive_files`). The orchestrator logs + alerts any shortfall at the end of `_run_distribution` **without failing the job** (shadow mode). Closes the residual silent-partial hole the original encode()-boundary fix leaves open (a `None` slot arising *after* `encode()` — e.g. a per-file download failure — still publishes a partial today), at the right altitude. ## D2 — same-day silent-partial detection The post-job trigger now carries the just-published `brand_code` through (orchestrator → Cloud Tasks → internal endpoint → Cloud Function → validator). The validator verifies that track is present in all expected folders **same-run**, independent of the global-max gap logic (which only notices a missing latest track once a *later* track raises the max). Surfaces as a `missing_for_track` issue ~5 min post-job instead of up to 24h later. `brand_code` is optional; absent → full-scan behaviour as before. ## Tests - `backend/tests/test_ops_alerts.py` — novelty, throttle/collapse, skip-env, fail-open, best-effort-never-raises. - `backend/tests/test_publish_completeness.py` — incl. the exact 720p-missing (NOMAD-1632) case. - `infrastructure/functions/gdrive_validator/test_main.py` — `check_track_completeness` incl. the 720p-missing case + prefix-not-substring. - `backend/tests/test_services.py::TestFirestoreService` — FAILED fires the alert, non-FAILED doesn't, alerter error never breaks the status write. All new + touched-area tests pass locally (`test_ops_alerts`, `test_publish_completeness`, `test_gdrive_validation_delay`, `test_video_worker_orchestrator`, validator suite, `TestFirestoreService`). 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added targeted validation confirming published tracks appear in required Google Drive folders. * Added conditional CDG checks based on whether a CDG package was produced. * Added near-real-time job-failure alerts with duplicate suppression and retry eligibility after delivery failures. * Added completeness checks for public releases, including missing video and CDG outputs. * Added highlighted partial-publish notifications when track files are missing. * **Bug Fixes** * Prevented alert content from triggering Discord mentions. * **Documentation** * Documented targeted validation and failure-alerting lessons. * **Chores** * Updated the project version to 0.223.2. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
ed7c6006be |
Incident hardening: encode→publish seam test + typed contract + guard discipline (T1/P3/P1/P2) (#986)
Part 2 of 3 of the **Incident hardening (post-NOMAD-1632)** initiative (plan: `docs/archive/2026-09-12-incident-hardening-plan.md`). Both incident bugs lived in the **encode→publish seam**, yet no test composed the *real* `GCEEncodingBackend.encode()` with the *real* orchestrator — so green mocked unit tests gave false confidence in both directions. ## T1 — composed encode→publish seam integration test New `TestEncodePublishSeam` in `backend/tests/test_video_worker_orchestrator.py` runs the **real** backend through the **real** orchestrator `_run_encoding`, patching only the network boundary (`encode_videos`) and storage. Asserts all four shapes: - **empty** `output_files` → completeness guard does **NOT** trip → orchestrator downloads 0 → raises "stale" → **re-encodes** and recovers (the Failure-B path the original fix broke); - **partial** (720p missing) → guard trips → job fails loud (the Failure-A defense); - **complete** → success, all result attrs populated (uses the NOMAD-1632 "Portrait of Jennie" title so the 720p classifies correctly); - **malformed** (stray/wrong-extension names) → classified out, treated as empty (no mis-slotting, no crash). ## P3 — kill mock drift: fixtures + typed contract - Golden fixtures under `backend/tests/fixtures/encoding/` (`success`/`cached`/`empty`/`partial`/`malformed`) + README. - Typed `GceEncodeResponse` (TypedDict) in `encoding_interface.py`, shared by producer (`EncodingService.encode_videos`) and consumer (`GCEEncodingBackend.encode`) — type-only import, no runtime cost/cycle. - `backend/tests/test_encoding_contract.py` replays every fixture through `classify_encoded_output` / `encode()` and validates the schema. The "empty" shape that hid Failure B is now in the corpus. ## P1/P2 — process docs `docs/TESTING.md`: **"New Guard / New Enforcement Checklist"** (recoverable ≠ wrong, fail-open on uncertainty, test empty/partial/malformed/complete, shadow-first, composed integration test) and a **"Critical-Path Change Tier"** note + blameless post-mortem template. ## Tests `138 passed` locally — new seam tests + contract tests + existing orchestrator/interface regression. No behavior change to app code (typed annotation only). 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
939f10f12c |
fix(encoding): completeness guard must not fire on empty result (prod hotfix) (#983)
## Production hotfix v0.222.2 (#982) added a completeness guard to `GCEEncodingBackend.encode()` that fails the job when the worker returns fewer formats than requested. It fired too broadly — including when `output_files` was **empty** — which hard-failed real user jobs: > Video generation failed: Encoding failed: Encoder returned an incomplete result: missing ['mp4_4k_lossless', 'mp4_4k_lossy', 'mkv_4k', 'mp4_720p'] (requested [...], got []). Refusing to publish a partial release. ### Root cause An **empty** result is a normal, recoverable condition, distinct from the partial result the guard was built for. A stale GCE job cache (finals deleted from GCS on an admin reset / re-run) returns `output_files=[]`; the orchestrator already recovers by downloading zero files, raising a `"stale"` `RuntimeError` from `_download_gce_encoded_files`, and re-encoding under a fresh job id. The guard sits **inside** `encode()` and raised before that recovery could run. ### Fix Fire the guard **only on a partial result** (`if output_files and missing_formats`) — the actual NOMAD-1632 case (some formats present, 720p missing). Empty results fall through to the existing stale-cache re-encode path, exactly as before v0.222.2. Partial results never hit the stale-retry anyway (they download >0 files), so no recovery path is short-circuited. Adds a regression test asserting an empty result returns `success=True` (not blocked by the guard). Version → 0.222.3. ### Impact Jobs failing since the v0.222.2 deploy (e.g. `252ab966`, `0e21062d`) can be retried once this deploys. No data loss — the jobs failed loud before publishing. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **Bug Fixes** - Improved handling of empty cached encoding results so stale jobs can be detected and retried correctly. - Prevented empty results from being incorrectly treated as partial encoding failures. - **Tests** - Added regression coverage for stale-cache recovery with no output files. - **Chores** - Updated the package version to 0.222.3. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
7c03834aaf |
fix(encoding): map GCE finals by format tag, not whole filename (NOMAD-1632 720p gap) (#982)
## Problem
Validator alert: `MP4-720p: missing 1632`. This was **NOMAD-1632 — Nat
King Cole – "Portrait of Jennie"** (job `21150e73`). Only the **720p**
variant was missing; MP4 and CDG were present and correct (so recycling
the brand code would have been *wrong*).
## Root cause — filename/title substring collision
The encoder produced and uploaded the 720p to GCS correctly (`… (Final
Karaoke Lossy 720p).mp4`), but `GCEEncodingBackend.encode()` mapped the
worker's returned file list to format keys by scanning the **whole
filename**, checking `"portrait"` (to detect the 9:16 portrait video)
**before** `"720p"`. The title contains "Portrait", so the 720p matched
the portrait branch → `mp4_720p` never set → `final_video_720p=None` →
`upload_to_public_share` **silently skips** a `None` path → published to
MP4/ + CDG/ with no MP4-720p/ entry. Deterministic for **any** song
whose artist/title contains a format word ("portrait", "720p", "4k",
"lossless", "vocals", …). Only the daily validator caught it, ~24h
later.
## Fix
- **`classify_encoded_output()`** — a shared, title-collision-proof
classifier that matches the trailing **format parenthetical only** (plus
system short-names), never artist/title text. Used by both
`GCEEncodingBackend.encode()` and `redistribute_video` (same latent
bug).
- **Completeness guard** (defense-in-depth) — `encode()` now returns
`success=False` (orchestrator raises → retry + immediate alert) if the
worker returns fewer formats than requested, so *any* partial-encode
cause fails loud instead of publishing an incomplete release.
- **Portrait Video download button** in `OutputLinks` (shown when the
job has `finals.portrait_1080x1920`) — the feature shipped but had no UI
download. Added the backend download filename suffix and the
`outputLinks.portrait` string translated to all 33 locales.
- Docs: `GDRIVE-VALIDATOR.md` History entry; version bump 0.222.1 →
0.222.2.
## Live gap remediation (already done, outside this PR)
The correct 720p already existed in GCS, so it was uploaded directly to
the `MP4-720p/` public-share folder as `NOMAD-1632 - Nat King Cole -
Portrait of Jennie.mp4` (verified present; mirror backfills nightly). No
re-render, no YouTube disruption. 1632 was **not** recycled.
## Testing
- `test_encoding_interface.py` — 37 pass, incl. a NOMAD-1632
reproduction (`Portrait of Jennie` 720p → `mp4_720p`),
title-with-"720p"/"4k" leakage cases, short-name coverage, and a
completeness-guard failure test.
- `OutputLinks.test.tsx` — portrait button show/hide (frontend unit
suite: 1252 pass).
- Orchestrator (82) + change-visibility (25) suites pass.
- Full backend unit run: 4373 pass (8 failures are pre-existing
`test_emulator_integration` env failures — emulator not running locally;
unrelated to this change).
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
- **New Features**
- Added downloadable portrait-format video output at 1080×1920.
- Added localized “Portrait Video” labels across supported languages.
- **Bug Fixes**
- Improved output recognition so video titles containing format terms
are classified correctly.
- Prevented incomplete encoding results from being published when a
requested format is missing.
- Corrected portrait-format filenames for clearer downloads.
- **Chores**
- Updated the application version to 0.222.2.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
|
||
|
|
2867c22f68 |
fix(review): restore per-suggestion undo for server-pre-applied AI corrections (#981)
## Summary - The server-side pre-apply feature (#957) bakes AI lyric corrections into the review data before the page loads, but the review UI's per-item Undo and "Revert all" controls in the "N auto-corrections applied" panel relied on client-side-only undo bookkeeping that was never populated for pre-applied jobs — so both were silently hidden. Reported by Andrew: `Undo All` did nothing and the auto-corrections panel offered no way to revert individual corrections (e.g. https://gen.nomadkaraoke.com/en/app/jobs/#/8a94db60/review). - `apply.py` now records per-suggestion undo info (removed words, new word ids, segment) at apply time; `pre_apply.py` persists it in `metadata.auto_approval.undo_info`; `useAutoCorrect` seeds its undo map from that on load so per-item Undo / Revert All work the same for pre-applied jobs as for client-applied ones. - Jobs pre-applied *before* this fix ships simply have no undo info (same as a stale suggestion), so the buttons correctly stay hidden only for those older jobs. - The Header "Undo All" button is unchanged — it correctly resets in-session manual edits back to page-load state and was never meant to revert AI corrections baked in before load. - Added a Lessons Learned entry on the underlying pattern (server-applied state needs its own undo data, not just client undo state). ## Test plan - [x] `python -m pytest backend/tests/services/auto_approval/` — 163 passed (18 in `test_apply.py`, including 5 new tests covering `undo_out`/`undo_info` for replace/delete/insert_after) - [x] `npx jest hooks/__tests__/useAutoCorrect.preapplied.test.ts` — 5 passed (3 new, covering undo seeding, `canUndo`, `undoAccept`, and `revertAll` against server-provided undo info) - [x] `npx jest --testPathPattern lyrics-review` — 357 passed, no regressions - [x] `tsc --noEmit` and `eslint` clean on all touched files - [ ] Local CodeRabbit CLI review — could not run (`coderabbit auth status` is tied to a different org's SSO session); opening without `@coderabbitai ignore` so the GitHub bot reviews instead 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com> |
||
|
|
bedbcdc3bd |
Requests board: skip songs with existing community karaoke versions (submit + pick time) (#979)
## Summary Stops the requests board from spending a free track — or wasting voters' time — on a song that **already has a good community karaoke version online**, reusing the same KaraokeNerds check the normal job-submission flow uses, at two points. Follow-up to the requests-board Phase 2 automation (#977). Addresses Andrew's two asks: **A) Submission time (soft, non-blocking).** As a signed-in user types an artist/title on the board, we debounce-check KaraokeNerds and surface any existing community versions in a dismissible banner with YouTube links. They can still request it — but many will just watch the existing one. Reuses the existing `POST /api/catalog/community-check` endpoint + `CommunityVersionBanner` component (added an optional board-appropriate subtitle). **B) Pick time (review).** A song may have had no version when requested but gained one by the time it's upvoted to the top. So the daily picker now KaraokeNerds-checks each candidate **in rank order**: - A candidate that already has a community version is **flagged for review** (`review_state=pending`) instead of auto-made, and the picker **skips to the next clean request** — so a fresh, non-duplicate free track still ships that day. - Andrew is emailed a summary and resolves held picks at **`/admin/community-reviews`**: **Make ours anyway** (creates the job like a normal pick), **Reject** (declines and emails every up-voter a link to the existing version), or **Keep on board** (leaves it votable, snoozing re-review for 30 days). - Held requests stay visible/votable on the board; they just aren't auto-made. Flag/email is idempotent (no daily re-nag). ## Andrew's decisions (via AskUserQuestion) Held pick → **skip to next clean request**. Review surface → **admin queue page + email**. "Keep" → **return to board, snooze re-review (30 days)**. ## Changes - **Model:** `SongRequest.review_state` (pending|snoozed), `community_versions`, `community_checked_at`, `review_snoozed_until`. - **Service:** `list_pick_candidates` (skips review-blocked), `set_review_pending` (transactional/idempotent), `snooze_review`, `clear_review`, `reject_request`, `list_pending_reviews`. - **Picker:** candidate loop + community check; extracted `_provision_and_start` shared by the picker and the admin "make" action. - **Admin:** `GET/POST /api/admin/community-reviews`, `/admin/community-reviews` page + sidebar item. New existing-version email to up-voters (33 locales). - **Frontend:** board submit form debounced check + banner. ## Testing - Picker candidate loop (flag dup → make next clean; all-dup → empty + flagged; resume skips re-check), admin actions (make/reject/keep, 404, 500), emulator coverage for the new service methods. 86 passing across touched suites; frontend typechecks clean; 32/32 locale parity. ## Deploy No `infrastructure/` changes — merge deploys it. The daily picker is already enabled in prod, so the pick-time check goes live with the backend deploy; the submission banner ships with the frontend. ## Review CodeRabbit reviewed locally (one minor grammar nit, fixed). @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
a344783376 |
gen: unify YouTube descriptions + automated back-catalogue rewrite (#978)
## Summary
Unifies the descriptions across all ~1.6k videos on
youtube.com/@nomadkaraoke to one consistent, conversion-focused
template, makes new uploads use it automatically, and adds a
**reusable** automated system to re-apply any future template change
across the whole channel.
Old descriptions were inconsistent: pre-2024 ones linked a dead $10
Fiverr gig; newer ones led with "AI-powered" (bad rep among viewers) and
linked nowhere useful.
## New template
Single source of truth: `Settings.default_youtube_description` rendered
by `backend/services/youtube_description.py` (placeholders `{title}
{artist} {artist_hashtag} {brand_code}`). Drops all "AI" framing; leads
with the craft; CTA to the requests board then the referral link
`nomadkaraoke.com/r/youtube` (50% off, tracked via referrals); Nomad
Discord + decide + KaraokeNerds; fair-use line; preserves the brand
code.
## Live pipeline (new uploads)
Both upload sites (`video_worker_orchestrator.py`,
`youtube_queue_processor.py`) now render via the shared module +
enriched tags — new uploads use the new template automatically.
## Bulk rewrite of the back catalogue
- Shared logic `backend/services/youtube_backfill.py` (classify / target
/ render / update-body / enumeration). **High-confidence-only**
eligibility (title ends in `(Karaoke)`) + curated `skip_ids.txt` /
`include_ids.txt` lists shipped in the package.
- **Manual CLI** `scripts/youtube-descriptions/` (`analyze` / `apply` /
`status`) — read-only report + full old→new diffs before any write.
- **Automated daily drain**
`backend/workers/youtube_description_backfill_worker.py` + `POST
/api/internal/youtube-backfill/run` + Cloud Scheduler (Pulumi). Progress
in Firestore keyed by a **template fingerprint**, so any future template
change auto-re-drains the whole channel with no manual reset.
Quota-coordinated with uploads (reserves headroom via
`YouTubeQuotaService`); Postmark progress + completion emails.
## Verified
- Analyzed all 1,631 videos → **1,614 to rewrite** (1,610 clean + 4
rescued truncated titles), **17 skipped** (lyrics-with-vocals, demos,
tutorials), zero false positives.
- One video (`PmwRXIZoCpg`) updated live and verified on YouTube (new
description + enriched tags; title/category preserved).
## Tests
42 new unit tests (renderer, classifier/targeting/update-body, worker:
full drain, budget cap, quota reserve, dry-run, completion/idempotency,
template-change cycle, quotaExceeded stop). Local review done via the
local code-review fallback (CodeRabbit CLI was rate-limited) — 3
findings fixed, 2 documented trade-offs.
## Deploy notes
- Backend auto-deploys on merge (worker + endpoint + config + data
files).
- **`pulumi up` required** to create the
`youtube-description-backfill-daily` Cloud Scheduler job.
- New config env (all defaulted): `YOUTUBE_BACKFILL_ENABLED`,
`..._DAILY_MAX_UPDATES`, `..._QUOTA_RESERVE`, `..._ENRICH_TAGS`,
`..._REPORT_EMAIL`.
Plan/architecture:
`docs/archive/2026-09-03-youtube-descriptions-plan.md`
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
- **New Features**
- YouTube uploads now use standardized descriptions with artist, title,
brand-code, and hashtag details.
- Tags are generated consistently from karaoke, artist, and title
information.
- Existing channel videos can be analyzed and updated in quota-limited
batches, with dry-run support and progress reporting.
- Added scheduled daily backfills and administrative controls for update
limits, exclusions, and overrides.
- Added safeguards for low-confidence titles and explicitly skipped
videos.
- **Documentation**
- Added guidance for automated and manual YouTube description management
workflows.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
|
||
|
|
05f024bdd4 |
Requests voting board Phase 2: daily free-community-track automation (#977)
## Summary
Phase 2 of the requests voting board (`requests.nomadkaraoke.com`) — the
daily automation that turns the top-voted request into a free,
auto-generated, published karaoke video. **Deploys dark** behind a
kill-switch (`COMMUNITY_DAILY_PICK_ENABLED`, default off); the daily
Scheduler only shadow-logs until it's flipped on.
Picks up
`docs/archive/2026-09-03-requests-voting-board-phase2-handoff.md`.
Design + Andrew's decisions:
`docs/archive/2026-09-03-requests-board-phase2-plan.md`.
## What's included
- **Daily picker** (`community_daily_pick.py`, Scheduler noon US
Eastern, DST-aware): claims the UTC day with a create-only lock
(`daily_community_pick/{YYYY-MM-DD}` → **one free track/day, total**),
picks the top open request with net votes ≥ 0 (source-agnostic; skips
community-rejected), grants the requester a free credit, and submits the
job **as that user** (owned by them, credit consumed) via the same
search → auto-select → download path the web flow uses. Fully idempotent
(resumable per-day lock phase + per-request guard flags).
Shadow/`?dry_run=true` mode.
- **24h ownership handoff** (`community_handoff.py`, hourly): reassigns
a stale review to the next up-voter (compare-and-set guarded), up to **5
voters**, then parks the track (`stalled`). Community jobs excluded from
the normal stale-review auto-cancel.
- **Voter publish fan-out**: YouTube upload-queue hook marks the request
`published` and emails every up-voter (except the owner) a new "track
you voted for is live" email (33 locales). Retry-safe (per-voter success
tracking).
- **Two internal endpoints** + two Cloud Scheduler jobs (Pulumi).
## Andrew's decisions (via AskUserQuestion)
- Trigger: **noon US Eastern**. Trending-agent fallback source:
**deferred** to a follow-up. Net-negative requests: **skipped**. Handoff
cap: **5 voters then park**.
## Deferred / follow-ups (not in this PR)
- **Trending-agent fallback source** (auto-submit a candidate when the
board is empty) — deliberately deferred; must generate candidates the
careful way (karaoke-decide `candidates` + KaraokeNerds).
- **YouTube description board link** — left untouched to avoid
clobbering Andrew's parallel descriptions work; add
`requests.nomadkaraoke.com` to `default_youtube_description` once that
lands.
## Testing
- Worker unit tests (kill-switch shadow, empty board, day-lock
idempotency, credit-grant/job-create guards, handoff cap/stale/CAS,
voter fan-out retry-safety) + emulator tests for the new service methods
against real Firestore transactions.
- All touched existing suites (youtube queue, stale-review,
requests-board routes/logic) pass. 79 passed locally.
## Review
CodeRabbit reviewed locally (2 cycles completed; 2 major + 1 minor
findings all addressed — retry-safe fan-out, CAS owner assignment,
up-voter ordering). 3rd cycle hit the free-OSS rate limit; it would only
re-verify the applied fixes.
@coderabbitai ignore
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
|
||
|
|
d41854f787 |
feat(requests-board): public song-request voting board (Phase 1) (#975)
## What & why
Phase 1 of the **daily-free-community-track** initiative (BACKLOG:
*"Daily free community track via public voting board"*). A public,
Hacker-News-style voting board at **requests.nomadkaraoke.com** where
anyone signs in with an email magic link, submits a song request
(artist/title auto-corrected + deduped), and casts **one vote per
calendar day**. Publicly viewable so it can be linked from YouTube
descriptions to drive top-of-funnel awareness.
Ships the board first (this PR) so the linkable URL exists; the
automation (daily auto-picker, free-credit grant on pick, 24h ownership
handoff, voter publish-emails, and the trending-karaoke agent as a
fallback request source — one free track/day total) is **Phase 2**.
Design doc: `docs/archive/2026-09-02-requests-voting-board-plan.md`.
## Backend
- New `song_request` models + service (Firestore `song_requests` /
`song_request_votes`) with transactional vote arithmetic (create / move
/ flip / toggle-off), dedupe, and ranking. One-vote-per-day is enforced
structurally via the vote doc id (`{email}__{YYYY-MM-DD}`).
- New `/api/requests-board` router: `GET /requests` (public, annotates
the caller's vote), `POST /requests` (submit — auto-corrects via the
existing `match_judge`), `POST /requests/{id}/vote`, `GET /me`.
- Board sign-in (`purpose="requests_board"`): passwordless identity only
— **no welcome credit**, a **higher per-IP signup cap**
(`BOARD_MAX_SIGNUPS_PER_IP`, default 30) so a shared venue WiFi can
register many voters while the per-fingerprint cap stays strict, and
`redirect_path="/requests"`.
- New `POST /users/claim-welcome-credit` powers the "Make it yourself
now" conversion (grants the standard credit the normal way, idempotent).
## Frontend
- `app/[locale]/requests` board: submit form with "we tidied that to…"
feedback, ranked vote list with daily-vote UX, convert-to-gen CTA,
recently-made list with YouTube links.
- API client methods + types; verify page honors `redirect_path`; new
`requests` i18n namespace translated to **all 33 locales**.
- `requests` added to `nonTenantSubdomains`.
## Testing
- 20 backend unit tests (routes + pure logic + sign-in + board signup
limit) and 8 emulator tests exercising **real Firestore transactions**
(vote arithmetic, dedupe, idempotent resubmit, one-vote-per-day). Full
backend unit suite green (4247 passed); frontend typecheck clean.
- Reviewed locally with CodeRabbit CLI (3 cycles); all findings
addressed (auth headers, idempotent resubmit, signup-limit hardening,
blank-input validation, i18n particle, refresh race).
## Deploy note
The board is reachable at `gen.nomadkaraoke.com/en/requests` on deploy.
Wiring the vanity `requests.nomadkaraoke.com` is a **post-deploy
Cloudflare step** — see
`docs/runbooks/requests-subdomain-cloudflare.md`.
@coderabbitai ignore
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
|
||
|
|
9616342562 |
fix(jobs): atomic dot-path writes for file_urls/state_data (lost-update race) (#970)
## Summary
- `JobManager.update_file_url` and `update_state_data` copied the whole
`file_urls`/`state_data` map and re-persisted it. The **audio and
screens workers run in parallel** and both write these maps, so a write
built from a stale snapshot silently dropped a sibling key set in
between (a classic lost update).
- **Real symptom** (job `5588e466`, Keeno "Shelter from the Storm"):
`backing_vocals.flac` was uploaded to GCS but **missing from
`file_urls.stems`** (only the 4th-of-5 stem lost). The
instrumental-review UI couldn't load the backing preview, and
`_analyze_backing_vocals` early-returned → "Very few backing vocals
detected (0%)" → the C1 mirror-skip forwarded `/review` →
`/instrumental`.
- Rare — needs a precise interleaving (~1 in 4 parallel jobs).
Pre-existing; unrelated to the timing-gate work.
## Changes
- `update_file_url` / `update_state_data` now write a single Firestore
dot-path field (`file_urls.<cat>.<type>`, `state_data.<key>`) so
siblings merge server-side — matching the existing
`update_processing_metadata` pattern. All keys are plain snake_case (no
dots), so no path is misread as nesting.
- `screens_worker._analyze_backing_vocals` hardened: recovers a stem
present at the conventional GCS path but missing from `file_urls`
(re-registers it atomically), and stores a fallback analysis instead of
a silent early-return.
- Tests: unit tests asserting dot-path writes; **emulator regression
tests** (`test_file_urls_no_clobber.py`) that reproduce the lost update
via a stale snapshot — they fail against the old read-modify-write and
pass against the fix. Updated one assertion in `test_job_manager.py` and
the missing-stems worker test for the new behavior.
- `docs/LESSONS-LEARNED.md` entry; version bump 0.216.0 → 0.216.1.
## Testing
- [x] Full backend unit suite green (4216 passed; the only failures were
emulator-connection env issues, verified green once the emulator was
started).
- [x] Emulator suite green incl. new regression tests (127 passed); new
tests confirmed to fail on the old impl and pass on the new.
- [x] CodeRabbit CLI review — **No findings**.
## Follow-up (not in this PR)
- Remediate the already-stuck job `5588e466` after deploy via `POST
/api/admin/jobs/{job_id}/regenerate-screens` (the fixed screens worker
recovers + re-registers the stem and recomputes the analysis).
## Review
- [x] Local CodeRabbit review completed — no findings
- [x] Feedback addressed
@coderabbitai ignore
---
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
|
||
|
|
d39dfd6778 |
Encoding worker infra/auth failures: retry instead of terminal-failing the job (#972)
## Why Prod alert burst (2026-08-31): a paying customer's job (`6452888e`) was **terminally failed** — its render worker error was: > Encoding job 6452888e failed: Failed to retrieve `https://metadata.google.internal/.../service-accounts/default/` … **Compute Engine Metadata server unavailable** … `SSLCertVerificationError` Root cause: the c4d primary pair was in a zonal stockout (503 on start), so the render fell back to `encoding-worker-fallback-c4a`. That fallback VM **booted and accepted the job** but then couldn't reach the GCE metadata server to fetch its service-account token, so it couldn't touch GCS and died mid-encode. This surfaced as a bare `RuntimeError`, hit `render_video_worker`'s generic `except Exception` → `fail_job`, and lost the job with **no retry** — even though the exact same work succeeds on any healthy worker. The same alert burst also included the daily E2E happy-path failure (the encoder being offline made the preview step flaky) and a benign `match-judge AI call failed; returning no-suggestion` red-error page. All three are addressed here. ## What **1. Encoding infra/auth failures are now recoverable (primary fix)** - `encoding_errors.py`: `is_worker_infra_error()` classifier (metadata / SSL-cert / missing-credentials markers, deliberately specific so a real ffmpeg/input error never matches) + new `EncodingWorkerInfraError` — a **subclass of `EncodingWorkerStartError`** so it flows through the existing park-for-auto-retry path with zero changes to the render worker's `except` (and the final-encode Cloud Run Job retries too). - `encoding_service.wait_for_completion()`: on a worker-reported infra/auth failure, **demote the broken worker + invalidate the URL cache**, then raise the recoverable typed error instead of `RuntimeError`. - `encoding_worker_manager.demote_active_worker()`: records a capacity-state cooldown for the serving fallback's `machine_type@zone` and clears `active_override`, so the retry re-selects a *different, healthy* VM. Scoped to **fallbacks only** — it never family-demotes the fast c4d primary on a rare blip. **2. match-judge noise** — the two graceful-degradation `logger.exception` calls become `logger.warning(exc_info=True)`, so a transient Vertex/Gemini blip that safely returns no-suggestion stops paging as a red "new error pattern". **3. Happy-path E2E robustness** — tolerate slow encoder cold-starts at the preview step: scope the alert check to the modal (kills the spurious empty-`[role=alert]` "Preview error:" from run #151) and recover the "Proceed to Instrumental" button via reload+reopen. The final assertion stays authoritative, so genuinely broken generation still fails the smoke test. ## Testing - New unit coverage: classifier positive/negative + subclass (`test_encoding_errors.py`), `demote_active_worker` (fallback demote+clear, primary no-op, never-raises), `wait_for_completion` infra classification (+ demote/invalidate, and no-manager path), and render worker **parks** (not fails) on `EncodingWorkerInfraError`. - `python -m pytest` across the encoding / worker / match-judge suites: **177 passed** locally. ## Not in this PR (infra, needs Andrew / GCP write) - **Fault A**: `encoding-worker-a` (c4d, us-central1-c) is chronically 503 on start (zonal stockout) — that's why the "Encoder offline" footer showed in the E2E. This change makes the fallback path robust to it, but the underlying c4d capacity/zone choice is an infra decision (secret/VM change; my GCP access is read-only). Worth deciding whether to repin the primary family/zone or promote a fallback. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Detects infrastructure and authentication failures on encoding workers. * Demotes affected workers and retries jobs using alternate capacity when available. * **Bug Fixes** * Prevents recoverable worker failures from becoming terminal job errors. * Reduces misleading error-level logging for gracefully handled match-judge failures. * Improves preview-flow recovery by waiting for actions to become enabled. * **Documentation** * Clarified that retries prefer, but do not guarantee, a different worker. * **Chores** * Updated the application version to 0.217.0. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
af36975db7 |
Admin create/manage tenants: album batch via tenant bulk flow + full theme customisation (#971)
## Why
Enables the "album for one client" use case: a batch of tracks with
audio provided up front, a client-supplied instrumental per track, and
one shared theme. That pipeline already exists as the **tenant bulk
flow** (folder pick → LLM pairs mixed↔instrumental → resumable uploads →
skip separation → locked theme on every job) — the only missing piece
was an easy way to **mint a tenant** (previously a hand-run
`scripts/setup-*-tenant.py`). This adds admin create **and** manage, so
a client's feedback can be iterated on (edit theme, re-render).
## What
**Backend** (`backend/services/tenant_admin_service.py` +
`backend/api/routes/tenant_admin.py`):
- `POST /api/admin/tenants` (multipart) — mint a tenant: derives a
**self-contained theme** from the default Nomad theme (copies its assets
so every `background_image` basename resolves), applies colour
overrides, overlays uploaded backgrounds, registers the theme, writes
`tenants/{id}/config.json` with B2B defaults (private, no
YouTube/GDrive, locked theme). Reserves the config **create-only before
any theme write**, with rollback on failure.
- `GET /api/admin/tenants` / `GET /api/admin/tenants/{id}` / `GET
/api/admin/tenants/_template` — list, full detail (config + theme
`style_params` + assets), and the default theme JSON as a template.
- `PUT /api/admin/tenants/{id}` (multipart) — **full theme
customisation**: merge config (one level, `id` immutable), replace the
entire `style_params.json`, upload/replace assets (images **or fonts**),
update logo.
- Full `style_params` override accepted on create too. Theme docs
validated to `intro/karaoke/end/cdg`. Guards against a tenant id
colliding with an existing theme.
**Frontend** (`/admin/tenants`):
- Tenants list + **Create** dialog (name→auto-slug, colours,
backgrounds, Dropbox/delivery, logo, + an "Advanced: full theme JSON"
editor seeded from the Nomad template).
- **Manage** dialog: editable config fields + a validated full **theme
JSON editor** + asset list & upload.
- New tenants are driveable immediately via **`?preview_tenant=<id>`** —
no DNS needed.
- Sidebar "Tenants" entry;
`adminApi.listTenants/createTenant/getTenant/updateTenant/getThemeTemplate`.
## Testing
- 36 backend tests (`test_tenant_admin_service.py`,
`test_tenant_admin_route.py`) + 4 frontend tests
(`admin-tenants-page.test.tsx`), incl. atomic-reservation /
conflict-no-clobber / rollback / theme-collision / full-theme-edit.
- Full `make test` green locally (backend + 1245 frontend); typecheck
clean.
- Reviewed locally with CodeRabbit (2 cycles, all findings addressed).
## Notes
- Admin is English-only → no i18n locale files touched.
- Follow-up (out of scope): saved **user** themes in the Custom Video
Style dialog (reuses this theme-derivation core); and an optional
"re-apply theme + re-render existing job" action.
@coderabbitai ignore
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
|
||
|
|
f0e48ac2ee |
Timing-plausibility gate: word timing vs lead-vocal stem (scorer v0.4.0) (#969)
## Summary
Reconstruction-based measurement of real reviews proved **timing is the
dominant residual human-edit class** in the full-auto initiative (14/25
measurable corpus jobs, median human retime 0.70s, 72% > 0.3s = clearly
audible) — and it is 100% invisible to every text-based signal the
scorer has. This PR adds the timing seatbelt so the auto class can keep
widening without silently shipping mistimed karaoke.
## Changes
- **New `backend/services/auto_approval/timing_check.py`** — analyzes
the POST-AI word stream against the job's separated `lead_vocals` stem
(numpy + pydub only; batched numpy spectral-flux onset detection, no
librosa):
- **G1 start-silence** (gates): ≥8% of words start in vocal silence —
hand-retimed section-shift signature
- **G2 suspect-mistimed** (gates): ≥15 structurally suspect words
(equal-duration runs = machine-distributed timing; repeated-phrase runs)
contradicted by the audio
- **G3 unclaimed-vocal** (shadow-only): long sung region no word claims
— recorded + logged, never gates (out-of-sample FP mode: ad-libs/vocal
samples deliberately absent from lyrics)
- **Scorer v0.4.0**: `score_lyrics`/`score_job` accept optional timing
signals; fired ⇒ REVIEW tier `timing-gate` (never-auto gate)
- **Executor**: computes signals only when the text signals would
otherwise let lyrics auto-ship (the only case that can change the
outcome); records `auto_approval.timing.{status, signals, fired,
shadow_fired}`; fail-open on analysis error, `pending_audio` until the
audio-worker re-score
- **C1 summary**: lyrics half not confident while timing is
`pending_audio` (kill-switch-aware) — a pre-audio verdict can't skip the
lyrics screen
- **Kill switch**: `AUTO_APPROVAL_TIMING_GATE_ENABLED` (code default
true, both-envs pattern)
## Validation
- **25-job reconstruction corpus**: 6/6 jobs with ≥8 human timing edits
caught; 0 fires on clean jobs; f986dfe5 (the +4s held-note AUTO leak) in
G3 shadow. Private harness
`docs/automation-corpus/validate_timing_gate.py` imports this exact
module — PASS.
- **Out-of-sample, 65 recent prod jobs (not used for tuning)**: G1+G2
fire on **zero of the 14 currently-auto (ai-resolved) jobs** —
enforcement costs no auto-rate — and catch 6/11 jobs with ≥8 timing
edits. Known partial recall (subtle boundary tweaks inside continuous
singing need forced alignment — the planned fixer direction).
## Testing
- 158 auto-approval unit tests pass (23 new: structural detectors,
synthesized-audio end-to-end incl. silent-stem regression, scorer gate
tier, executor wiring incl. fail-open paths, C1 summary interactions)
- Full `make test` green (backend + 1241 frontend)
- CodeRabbit review: 3 findings (OOM-bounded onset batching, silent-stem
fail-open, C1 kill-switch consistency) — all fixed + regression-tested
Docs: `docs/archive/2026-08-31-timing-gate.md`
@coderabbitai ignore
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
|
||
|
|
feb4c86842 |
gen: vanity referral request approve/deny queue (rename-in-place) (#967)
## Problem When a user requests a custom vanity referral code, the backend only emailed the admin — nothing was persisted. To "approve," the admin had to open **Create Vanity Link** and hand-retype the owner email + desired code, which created a *second* link alongside the user's auto-generated one (split stats, two live codes). The **Edit** modal can't change a link's code. There was no approve/deny concept and no notification to the requester. Confusing and unintuitive (reported first-hand while setting up the YouTube referral link). ## Solution User vanity requests now persist to Firestore and surface as a **"Pending Vanity Requests"** banner at the top of `/admin/referrals` with one-click **Approve** / **Deny**. - **Approve** = renames the user's existing link *in place* (`odu4brd8` → `youtube`): stats/earnings preserved, referral attribution (`referred_by_code` + earnings) migrated, old code disabled as a breadcrumb (stats zeroed so admin totals don't double-count), and the requester is **emailed** that their link is live. - **Deny** = marks the request denied. - One unified code per user — no more duplicate links or split stats. ## Changes **Backend** - `VanityRequestDoc` model (`referral_vanity_requests`, keyed by owner_email so a re-request overwrites). - `referral_service`: `create_vanity_request` / `list` / `get` / `approve` / `deny` + `rename_link` (atomic `create()` to close the destination-code race; migrates attribution; zeroes old-alias stats). `get_or_create_link` now prefers enabled links so the renamed alias never resurfaces. - 3 admin endpoints: `GET/POST /admin/vanity-requests[...]`. `request_vanity_url` now validates the code up-front (before link creation) and persists the request. **Frontend** (`/admin/referrals` is English-only, no i18n) - Pending-requests banner card + `adminApi.listVanityRequests/approveVanityRequest/denyVanityRequest` + `VanityRequest` type. ## Testing - Backend unit/route: **21** (approve/deny/list, request validation, 404/400 paths) - Emulator (real Firestore): **11** (rename preserves stats + migrates attribution + disables/zeroes old alias; atomic create blocks taken codes; approve/deny/re-request) - Frontend: **4** (banner renders, approve/deny wiring, hidden when empty) - Version `0.214.0` → `0.215.0`. Local CodeRabbit review completed (2 fix cycles). @coderabbitai ignore --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
0bebf5c170 |
gen: inline instrumental chooser for all jobs + fix backing-scorer race (#966)
Two fixes for jobs where a backing-vocals song showed **no** inline
chooser and was forced to the heavy `/instrumental` screen — diagnosed
on job `be8231fd` ("The Qemists - Take It Back").
## Diagnosis
The auto-approval verdict is scored by `screens_worker` on lyrics
completion. `mark_audio_complete` is decoupled from status, so when
lyrics finish first and audio is still separating, the backing-vocals
analysis isn't available yet → the backing half is scored `review`
(`analysis_present:false`, `audio_incomplete`). The `audio_worker`
re-score meant to fix this is **skipped once a human opens the editor**
(status `IN_REVIEW`, not `AWAITING_REVIEW`), so the stale "no analysis"
verdict persists forever — even though the analysis later lands and
would score a confident `with_backing` keep.
## Fix 1 — backend: read-time self-correction (race-proof)
`auto_approval_summary` now re-derives the backing verdict from the live
`state_data.backing_vocals_analysis` when the stored verdict was scored
*without* it (`backing_analysis_available` falsy). Pure/read-only —
enforcement & auto-complete are untouched. Unit-tested with the real
job's signals (`corr 0.75`, `-28.7 dB`, `64%` audible → confident
`with_backing`), and that it respects the keep flag and doesn't override
a verdict that already had the analysis.
## Fix 2 — frontend: inline chooser for ALL jobs with both stems
The **"🎬 Your karaoke video will use:"** radio group now shows whenever
both a clean and a with-backing stem exist — not only when the scorer
was confident. Confident → green **"✓ recommended"** badge + confident
copy; not confident → the analysis's recommendation is **preselected**
with a neutral *"Have a listen and choose…"* prompt (no badge). Picking
clean/with-backing **completes inline** ("Complete Track"); **Advanced
mode** is the opt-in to `/instrumental`. The backend `complete` endpoint
already accepts explicit `clean`/`with_backing`, so this is
frontend-only.
**Verified live** on `be8231fd` via the dev server: the chooser now
renders (backing preselected, clean + Advanced offered, CTA "Complete
Track") instead of forcing the advanced screen.
## Tests
- Backend: `auto_approval` suite 121 pass (+3 new self-correction
tests); review/correction-data 142 pass.
- Frontend: full suite **1237 pass**; `ReviewChangesModal` rewritten for
the new prop API incl. the non-confident chooser path. ESLint + tsc
clean.
- i18n: 33 locales, full key parity.
@coderabbitai ignore
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
|
||
|
|
9c20815154 |
Auto-fix phantom parentheticals (P8): delete → auto-ship instead of gate (#963)
## Summary Turns the **P8 phantom-parenthetical** class from a review *gate* into a deterministic *auto-fix*, widening the fully-auto class without loosening the quality bar. Part of the full-auto-review initiative (measurement re-assessment phase). The 2026-08-30 reconstruction re-measure of the corpus (see below) showed that deleting phantom parentheticals — `(Instrumental break)`, `(I'm sorry)`, and unanchored `(Angel baby)` duplicate copies — is a recurring, cleanly-deterministic human edit. Previously these only *gated* the job to human review; now they're auto-deleted so the affected jobs auto-ship with correct output. ## Changes - **`deterministic.phantom_parenthetical_suggestions`** — emits a `delete` for a parenthetical run whose **every word is a gap word** (the decisive signal: this correctly deletes an unanchored duplicate even when its tokens appear elsewhere in the references, e.g. `(Angel baby)`). Guards: skips pure-vocalization parentheticals (left to the vocalization gate) and long runs (> 5 words). Wired into `deterministic_suggestions`, so it flows through the same cache / apply / score paths as P4/P5. - **`scorer._extract_gating_signals`** — now excludes words that a **winning** delete suggestion removes (winner-aware via `pick_accept_all_winners`) before scanning for the phantom/vocalization gates. A phantom that will be auto-deleted no longer trips the phantom gate, while genuine absurd-duration phantoms stay gated. ## Validation - **Corpus + battery (25 jobs):** 6/6 correct-direction deletes, **zero false positives**. The two known-human cases reproduce exactly (`(I'm sorry)`×3, `(Instrumental break)`); two initially-unverified deletes (`(only to my)`, `(Dreaming)`) confirmed correct — neither appears in the human's final. - **Private `validate_scorer.py` green:** safety preserved (33453fa0 still not-auto via its genuine gap/anchor signals; raw phantom safety-net gate intact); P8 fires 33453fa0 ×3, 8e465dc7 ×1, 5f90b799 ×1. - **Tests:** new unit tests for the fixer (8) + scorer delete-awareness incl. winner-vs-loser conflict handling (2). `backend/tests/services` 380 passed; auto_approval + auto_correct 230 passed; review routes + instrumental summary 91 passed. - **CodeRabbit** local review: no findings. ## Measurement note Human-edit measurement now uses **reconstruction** (diff post-AI vs final), not the `edit_log` — which was proven unreliable (never logs timing edits; null path is ambiguous). Documented in `docs/LESSONS-LEARNED.md`. @coderabbitai ignore Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
019289cd0b |
Pre-apply AI corrections on review load too (C2 completeness) — fixes the ~4s flicker on pre-existing jobs (#959)
Follow-up to workstream C (#957). Andrew opened an in-review job (`c00a06d2`) and still saw the review page show uncorrected AudioShake lyrics for ~4s before the AI corrections applied — the exact race C2 was meant to kill. ## Why it still happened The C2 server-side pre-apply runs in `screens_worker`, right before the `AWAITING_REVIEW` transition. Jobs processed **before** that code shipped (or whose suggestion cache landed after that gate) already passed it, so their `corrections_updated.json` has no `pre_applied` marker and the frontend falls back to its on-load client-side apply — the visible flicker. ## Fix Also pre-apply at the **load event itself** — the `/correction-data` fetch, which is literally "when the lyrics review page launches": - The endpoint now calls `ensure_and_pre_apply(job_id, generate_on_miss=False)`. - New `generate_on_miss` flag: the load path applies an **existing** cache only, so the page never blocks on a multi-model LLM call. The `screens_worker` path keeps `generate_on_miss=True` (generates ahead of the notification for new jobs). - Best-effort + idempotent: a no-op when the job was already pre-applied, already human-edited, or has no cache (then the UI's client-side apply still runs). Since prod runs proactive auto-correct, the cache almost always exists → old jobs now load corrected instantly. ## Concurrency (CodeRabbit) The write is now **create-only** (`upload_json(..., if_generation_match=0)`); if the executor auto-complete or an edit submission created `corrections_updated.json` between our existence check and the upload, GCS raises `PreconditionFailed` and we skip — their newer state wins. ## Tests - `test_pre_apply.py`: load-path applies existing cache without generating; load-path cache-miss doesn't generate or mark; screens-path still generates on miss; raced concurrent write doesn't clobber. Full backend suite: 4151 pass. - Frontend unchanged (the `pre_applied` marker handling from #957 already covers this). Local CodeRabbit review completed and addressed (create-only write). @coderabbitai ignore --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
3680ed66b3 |
Full-auto review: per-screen skip + server-side pre-apply + submission autonomy UI (workstream C) (#957)
Completes the fully-automated-review initiative (workstream C — the final build item). Three interlocking parts, all shipped in one PR. ## C1 — Per-screen skip Only show the review screen that actually needs a human. - **Confident backing → skip the instrumental screen.** Completing the lyrics review finishes the whole job. The client sends `instrumental_selection="auto"`; the backend resolves it from the stored verdict (`resolve_auto_instrumental`), so CLI/tenant clients get the skip for free. - **Mirror case (only backing gates) → skip the lyrics screen.** The router deep-links straight to `#/instrumental`; the server-pre-applied corrections are the lyrics payload. - **Escape hatch:** a "let me choose the instrumental myself" toggle in the finish modal. - `always_review` jobs never auto-skip (gated server-side in the shared summary). ## C2 — Server-side pre-apply (kills the on-load edit race) Andrew's directive: apply the AI/heuristic corrections *before* the review-ready notification, so the review screen loads one final state. - New `pre_apply.ensure_and_pre_apply` runs in `screens_worker` before the `AWAITING_REVIEW` transition: ensures the suggestion cache (bounded, fail-open), applies with the same machinery the executor uses (`apply.build_applied_segments`), and writes `corrections_updated.json` with a `pre_applied` marker. - `useAutoCorrect` gains a `preApplied` mode: no client-side auto-run/auto-apply, panel seeded read-only from the server's applied/rejected ids. Backward compatible (no marker → today's behavior). ## C3 — Submission autonomy UI - **Review mode** (fully automatic / always let me review) + **backing-vocals preference** (keep-where-possible / clean / let-me-choose) toggles in the guided flow. - Plumbed through every submission route + `JobCreate`; **33 locales** translated. ## Shared source of truth `instrumental.backing_decision` is the one place the executor, the complete-review `"auto"` resolver, and the UI summary all derive the instrumental decision — they can't drift. ## Tests - Backend: `test_instrumental.py` (decision matrix, summary/resolver incl. always_review gating + stem checks, JobCreate coercion), `test_pre_apply.py` (apply/marker/fail-open), executor `backing_preference` cases. Full auto_approval suite: 112 pass. Touched route suites: green. - Frontend: `useAutoCorrect.preapplied` + `ReviewChangesModal` escape-hatch tests. Full Jest suite: 1218 pass. - i18n completeness enforced by CI. Local CodeRabbit review completed and addressed (always_review gating, stem-availability check, out-of-set preference coercion). @coderabbitai ignore --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
9d4f70a747 |
fix: clean up published outputs before job delete; admin orphaned-outputs cleanup (v0.206.0) (#952)
## Summary
Fixes the root cause of tonight's **NOMAD-1583 duplicate brand code**
incident and adds the tooling needed to clean up the orphaned files.
**Incident**: job `e97475ff` (Mazzy Star – Fade Into You) published with
NOMAD-1583 at 02:15 UTC, was deleted at 03:02 via `DELETE
/api/jobs/{id}?delete_files=true` — which recycled the brand code but
left every published output live (GDrive ×3, Dropbox folder, YouTube
video, kjbox mirror ×2). At 04:16, job `326e1aef` (Chase & Status – No
Problem) reused the recycled 1583 → duplicate in all three public share
folders, validator alerting on every subsequent job.
## Changes
- **`DELETE /api/jobs/{id}` no longer blind-recycles brand codes.** When
a job's outputs are still published, it now runs the full distribution
cleanup first (YouTube + Dropbox + GDrive + kjbox GCS mirror) via a
shared `_run_distribution_cleanup()` helper (extracted from
`cleanup-distribution`); recycle stays gated on Dropbox+GDrive success.
Incomplete cleanup aborts the delete (502) so the job record — the only
place holding the file IDs — is preserved for retry.
`delete_files=false` is rejected (400) for published jobs. Jobs whose
outputs were already deleted no longer re-recycle the code.
- **New `POST /api/admin/orphaned-outputs/cleanup`** — removes
distributed outputs by explicit IDs (YouTube video ID, Dropbox path,
GDrive file IDs, mirror filename prefix) when the owning job doc is
gone. Needed to clean up the Mazzy Star orphans.
- **`NomadMasterMirror.delete_track_objects_by_filename_prefix`** —
single-track mirror delete requiring a `NOMAD-#### - Artist...` prefix,
delimiter-bounded so it can never match the other track legitimately
holding a recycled code.
- New i18n key `jobs.deletePublishedRequiresFiles` translated to all 33
locales.
- Runbook + incident history in `docs/GDRIVE-VALIDATOR.md`.
## Testing
- 4111 backend tests pass (18 new: DELETE-route cleanup semantics, admin
endpoint, mirror prefix guardrails/delimiter bounding).
- Local CodeRabbit review: 2 cycles, all 4 findings addressed
(abort-on-incomplete-cleanup, delete_files honored, delimiter-bounded
prefix, unsafe-prefix 400).
- Post-deploy: will run the orphaned-outputs cleanup for the Mazzy Star
files and re-run the GDrive validator to confirm a clean report.
@coderabbitai ignore
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
|
||
|
|
d061b480dc |
feat: auto-complete user-supplied-instrumental jobs with selection=custom (v0.205.0) (#951)
## Summary Phase 2D of fully-automated review (follows #949/#950) — the highest-business-value slice: tenant bulk-upload jobs (and any job with a user-supplied instrumental) can now complete fully automatically. Jobs with `existing_instrumental_gcs_path` or a `custom_instrumental` stem have **no instrumental decision to make** — the human complete-review flow submits `instrumental_selection="custom"` (review.py validates it exactly under these conditions; the video worker prefers the user-provided source). The executor previously excluded these jobs outright via the `custom_instrumental` blocker. Now: - **Confident lyrics alone auto-complete them** with `instrumental_selection="custom"`, mirroring the human tenant complete-review exactly. The backing verdict is moot (no separated-stem requirements; the video worker validates custom sources itself). - Non-custom jobs are unchanged: the `overall_auto` intersection (confident lyrics AND non-subjective backing) still applies. - `processing_metadata.auto_approval` now records `enforcement_basis` (`lyrics_only_custom_instrumental` vs `overall_auto`) and `custom_instrumental` for shadow analysis, and `enforcement_eligible` now reflects verdict eligibility AND blockers (CodeRabbit catch). - Per-job opt-out remains `review_mode="always_review"` (admin-editable). A per-tenant default is future work. This makes tenant bulk uploads the highest-auto-rate population: their jobs skip both review screens whenever the scorer is confident in the lyrics, going straight to render with the instrumental the tenant supplied. ## Testing - Executor tests updated: the old `custom_instrumental`-blocks test replaced by three new tests — auto-complete with selection="custom" even with NO backing analysis (moot), custom-stem variant without separated stems, and weak-lyrics still gating to review. - Full backend suite: 4056 passed, 0 failed. Backend-only change. - Live validation planned tonight: a Vocal Star tenant bulk upload (~10 tracks) after deploy, watching `enforcement_basis`/outcomes in prod. @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
c2e31a5325 |
feat: 3-stem backing-vocals decider — confident WITH_BACKING verdict, shadow-first enforcement (v0.204.0) (#950)
## Summary Phase 2B of fully-automated review (follows #949): the backing-vocals decision gets a real decider. Today any track with audible ("pink") backing content goes to human review; per the 20-job replay-review corpus, pink → KEEP is right essentially always — the human systematically *under*-keeps — except three detectable "pink but don't keep" failure modes. This PR builds the 3-stem analysis that detects them and lets the scorer emit a confident **WITH_BACKING** verdict. - **New `karaoke_gen/instrumental_review/stem_comparison.py`** (pure pydub): compares the backing / lead / full-vocals stems — per-stem audible coverage + coverage ratio, envelope Pearson correlations, median audible levels, lead-overlap fraction, within-run flatness. Runs in the existing backing-vocals analysis step (screens_worker → AudioAnalysisService) and is stored as `backing_vocals_analysis.stem_comparison` on every new job. Best-effort: any failure stores an error marker, never blocks the job. - **Scorer v0.3.0**: the pink-present branch now decides — confident WITH_BACKING (non-subjective, bias-to-keep per corpus) unless: - **backing stem IS the lead** (catastrophic if kept): coverage ratio ≥0.80 + backing↔vocals correlation ≥0.80 + backing more audible than the lead stem (the decisive discriminator — a plain dB-margin rule nearly misfired on a genuine keep) → review; - **noise-floor pink** (lo-fi mixes): median ≤ −35 dB across ≥15% of the track, uncorrelated with the vocal line → review (marginal either way per corpus); - **lead bleed** (narrow): ≤3% audible with ≥0.95 lead overlap → review. - **Executor**: a WITH_BACKING verdict auto-selects the with-backing instrumental **only** behind `AUTO_APPROVAL_BACKING_KEEP_ENABLED` (default **false** — shadow-first). While off, such jobs record blocker `backing_keep_disabled` plus the full verdict/signals in `processing_metadata.auto_approval`, accumulating prod shadow data alongside human picks. Also requires the `instrumental_with_backing` stem. ## Validation (real corpus stems, ~2.4 GB, private harness) Downloaded all 20 corpus jobs' three stems from GCS and ran the decider against the replay-review ground truth: - **13/14 true keeps → confident WITH_BACKING**, including BOTH jobs the human wrongly cleaned on quick review (44622ffa harmonized ahhs, 35ed9697 self-harmony hooks) — the decider beats the human here. - 95d8e844 (marginal grungegaze, mostly noise pink) → review. All clean-correct jobs → clean. **1d45b286 (backing stem is the lead — worst-case if kept) → review.** Zero unsafe outcomes. - Lyrics-side corpus validation (validate_scorer.py) unchanged and green. ## Testing - 21 new unit tests: synthetic-audio stem-comparison signal tests, scorer decision branches modeled on the real corpus signal profiles, executor flag/stem gating. - Full backend suite: 4056 passed, 0 failed. Backend-only change (no frontend, no user-facing strings). ## Rollout Shadow-first: nothing changes for users at deploy. After reviewing prod shadow verdicts vs human picks, set `AUTO_APPROVAL_BACKING_KEEP_ENABLED=true` to let confident-keep jobs (e.g. the Cher-class: lyrics solved, gated only by audible backing) complete fully auto. @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
b1126583c0 |
feat: deterministic P4/P1/P5 lyrics auto-fixers in the auto-correct pipeline (v0.203.0) (#949)
## Summary
Phase 2A of fully-automated review (follows #947/#948): the three
mechanical residual-edit classes from the 20-job replay-review corpus
become **deterministic suggestion generators inside the auto-correct
pipeline** — one mechanism feeding the review UI's on-load auto-apply,
the auto-approval executor's server-side apply, the scorer's
gap-coverage signal, and the proactive suggestion cache.
- **P4 — leading-connective over-insertion** (most common residual
class): a segment starting with And/But/So/Oh/A that is a gap word and
unsupported by every reference source's reading of that gap → `delete` +
re-capitalize the next word. Guard: skipped when the next word is a
vocalization token (an "Oh- whoa," run is a musical judgement).
- **P5 — reference-majority resolution**: a gap whose transcription
contains an implausible proper noun (capitalized mid-line token absent
from every reference) where ≥2/3 of reference sources agree on the same
reading → replace with the majority reading. The red flag is REQUIRED
(plain 2/3-majority over-fires on gaps the human deliberately left), and
a spelling-variant guard (similarity ≥0.75 to a reference token) skips
transliteration/truncation cases whose gap alignment is typically junk.
- **P1 — AI self-conflict fixed at source**: conflict grouping now also
unions an `insert_after` with any suggestion targeting/anchored on the
same word whose new_text shares a token, so accept-all picks one winner
instead of double-applying ("you're you're"). The executor's
duplicate-word abort stays as belt-and-braces.
Per-source gap readings come from the gap's own reference alignment,
else are derived by walking the reference stream past the surrounding
anchors (recovers the readings the aligner left empty). Suggestion-cache
key bumped to v2 so pre-fixer cached results aren't served.
## Validation
- **Corpus (private validate_scorer.py, extended with FIXER assertions):
all safety + gate checks still 100%.** P4 fires on all six corpus
examples (8f2305ee, ae0cd7e8, 1d45b286, 5f90b799, 33453fa0, f247364e);
P5 reproduces the human's exact edit on 6d0640fa ("yo Mick," → "Come
here,") and fires nowhere the human deliberately made no edit (507513ba,
d508adb6, and the other 6d0640fa gaps).
- The Miguel corpus job (6d0640fa) now scores lyrics=auto with clean
backing → would fully auto-ship **with the human's exact edit applied**;
the Samson corpus job's P4 edits now get applied rather than skipped.
- `ai-resolved` caps deliberately NOT loosened.
## Testing
- 27 new unit tests
(`backend/tests/services/auto_correct/test_deterministic.py`) covering
both generators, all guards, P1 grouping, and pipeline integration
(append/dedupe/conflict/min-confidence/no-corrections fallback).
- Full backend suite: 4033 passed, 0 failed.
- Backend-only change; no frontend files or user-facing strings.
@coderabbitai ignore
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
|
||
|
|
9b6c4f236e |
fix: Cloud Tasks queue region from GPU workers + REVIEW_COMPLETE lost-trigger recovery (v0.202.1) (#948)
## Summary Follow-up to #947, found by live-testing auto-approval in prod (job `b8bda9c2` — the first real fully-auto-approved job). **Bug:** the GPU `audio-separation-job` sets `GCP_REGION` to its GPU region, but every Cloud Tasks queue lives in `us-central1`. Any queue enqueue from inside that worker fails with `404 Queue does not exist` — which silently dropped the auto-approval render trigger (job auto-approved perfectly, then sat at `review_complete` forever). This is also a latent pre-existing bug for any other enqueue attempted from the GPU job. **Fixes:** 1. New `settings.cloud_tasks_region` (default `us-central1`, overridable via `CLOUD_TASKS_REGION`) used for all Cloud Tasks queue paths. `gcp_region` is still used for Cloud Run Job locations (correct). 2. `recover-stuck-jobs` cron gains a sweep for `REVIEW_COMPLETE` jobs stalled >10 min with no `render_progress` — re-triggers the render worker (idempotent via worker-generation fence). This closes the lost-trigger orphan gap for BOTH the human complete-review fire-and-forget task and the auto-approval path, and will auto-rescue `b8bda9c2` on the first tick after deploy. ## Testing - New unit tests: queue path uses `us-central1` even when `GCP_REGION=us-east4`; stall detector (stalled / fresh / render-underway). - Note: `test_internal_api.py` auth tests fail identically on pristine `main` in this local env (green in CI) — pre-existing, unrelated. @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
f01213f5cb |
Fully-auto review for confident jobs: review_mode framework + auto-approval scorer/executor + replay tool (v0.202.0) (#947)
## Summary Ships the **fully-automated review framework**: jobs now default to `review_mode="auto"` — when the auto-approval scorer is fully confident on BOTH axes, the combined review screens are skipped entirely and the job renders straight through. Everything else falls back to human review exactly as before. **The confident class (deliberately narrow to start, ~5% of jobs expected):** - **Lyrics**: synced reference present, ≥90-99% anchor coverage, and every gap word covered by the pre-generated AI auto-correct suggestions (which the executor applies server-side — a faithful port of the review UI's on-load auto-apply, including conflict-group resolution) — OR zero gaps outright. - **Backing vocals**: non-subjective only — no audible backing content → clean instrumental. - **Never-auto gates**: vocalization sections (da-da-dun/woo-woo — P3), phantom/absurd-duration lines (P8), too-few-words, no/unsynced reference, errored backing analysis. **Calibrated against a 20-job human-review corpus** (all recent admin reviews replayed + annotated): safety 100% (every job that truly needed a human stays in review), lyrics-auto 3/20, overall-auto 1/20. ## How it works - `screens_worker` (pre-AWAITING_REVIEW) and `audio_worker` (post-stems, for the audio-lags-lyrics ordering) both call `maybe_auto_complete_review()`. Every job gets a verdict recorded in `processing_metadata.auto_approval` (shadow data keeps accumulating for calibration); enforcement additionally requires: flag on + `review_mode="auto"` + not made-for-you + no existing/custom instrumental + audio complete. - Enforce path mirrors a human "Complete Review": apply cached AI suggestions → sanity checks → `corrections_updated.json` → `instrumental_selection="clean"` → clear progress keys → `GENERATING_SCREENS→REVIEW_COMPLETE` (new legal edge; no review token or "ready for review" notification is ever issued) → trigger render worker. - **Fail-safe everywhere**: stale suggestions, duplicate-word artifacts (P1 self-conflict signature), state changed mid-enforce (human opened editor), any exception → normal human review. Auto-approval can never fail a job. - Kill switch: `AUTO_APPROVAL_ENFORCE_ENABLED=false` (scoring continues). Per-job: `review_mode="always_review"` (admin PATCH, validated). - Excluded from enforcement (still shadow-scored): made-for-you orders (human QC is part of that product), custom-instrumental jobs. ## Also in this PR (sessions 1-3 of the initiative) - **Review replay tool** (admin-only, prod-inert): `?replay=1` reopens the real lyrics/instrumental review UIs read-only for completed jobs — queue nav, Post-AI/Final toggle, edit-log action panel, dev-only audio byte-proxy (env-gated `REVIEW_AUDIO_PROXY`, path-anchored). This is what produced the calibration corpus. - `auto_approval` service package: scorer (anchor/gap/AI-coverage signals + P3/P8 gate detectors), apply engine, executor, lyrics-diff, offline capture script. ## Testing - 100+ new unit tests across scorer/apply/executor/replay routes; full backend suite 4000+ green locally (8 pre-existing emulator failures reproduce identically on pristine `main` — local-env only, green in CI). Frontend: 1196 Jest tests green. - Scorer validated read-only against the 20 real prod jobs in the private calibration corpus. @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
70ea964ca9 |
feat(dev): full local backend for external contributors (no GCP creds needed) (#946)
## Summary Motivated by external contributor Martín (netux) asking "is there an easy way to run the full backend without GCS?" — he couldn't test PR #895's backend changes locally. This PR makes the whole backend runnable locally against emulators with **zero GCP credentials and zero paid API keys**. ### What was broken for contributors - Workers migrated to Cloud Run Jobs for prod robustness (audio-download, audio-separation, lyrics-transcription, bulk-search) silently bypassed the direct-HTTP dev mode → local jobs stalled at PENDING forever - Signed URL generation called `google.auth.default()` → crashed with no credentials (review audio, downloads, theme previews, upload URLs) - Magic-link login 503'd locally (console email provider counted as "not configured") - Fresh emulator had no default theme → every job create returned 422 - `docs/DEVELOPMENT.md` told people to `cp .env.example .env` but the file didn't exist — and nothing loaded `.env` anyway - `run-backend-local.sh` defaulted to the production GCP project ### Changes - **worker_service**: CRJ-based workers run as local subprocesses (`python -m backend.workers.X --job-id Y`, exact CRJ parity) when `ENABLE_CLOUD_TASKS=false` **and** not `is_production()` (regression-tested both ways) - **storage_service**: signed URLs → plain fake-gcs-server URLs when `STORAGE_EMULATOR_HOST` set (GET via JSON API download path; PUT via unvalidated-signature path, enabled by `-public-host` on the emulator) - **users route**: magic-link 503 only in production; dev prints the link to the console - **file_upload bugfix**: a theme with style params but no asset files never got `style_params_gcs_path` written (empty-dict falsiness in `elif theme_style_assets:`) — surfaced by the minimal seed theme, latent in prod - **scripts/seed-local-data.py** (new): creates bucket + default theme; wired into `run-backend-local.sh --with-emulators`, which now uses `test-project` - **config**: `load_dotenv()` so `.env` actually works; new root `.env.example` - **CONTRIBUTING.md** (new): no-credentials quickstart; README + DEVELOPMENT.md link to it ### Verified end-to-end locally (no GCP credentials) Upload job → local audio separation (real models) → transcription → screens → `awaiting_review`; review endpoints all working including `/api/review/{job}/audio/vocals` (the PR #895 endpoint) and 302 → emulator audio URLs. Magic-link login round-trip via console link. ### Tests - 224 tests across affected files pass; full backend unit suite: 3969 passed - `backend/tests/test_emulator_integration.py` has 8 pre-existing failures that reproduce identically on unmodified `main` locally (broken theme-service mock in that file) — unrelated to this PR - New tests: dev-mode subprocess dispatch (audio + bulk-search), prod-mode never-Popen guard, emulator URL generation (GET + PUT) @coderabbitai ignore --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
156d4369f9 |
Tenant bulk upload: folder pick + LLM pairing + review table + resumable uploads (v0.200.0) (#943)
## Summary Adds a **Bulk** mode to tenant portals (frog #3, Vocal Star ask): drop a folder of tracks, automation pairs Mixed vs Instrumental audio and extracts Artist/Title from filenames, the operator reviews/fixes an editable table, then submits all as jobs — with uploads that survive slow/flaky connections. ### Bulk mode - `POST /api/tenant/bulk/analyze` — authed, gated on new `TenantFeatures.bulk_upload` (default on), cap 100 audio files. Regex fast path for the `S####-1/-2 … Guide/BV/Instru` convention + Vertex-Gemini pass for leftovers (`backend/services/tenant_bulk/analyze.py`), regex-only fallback if the model errors. Pure analysis — filenames only, no state written. - Label parsing: STRONG labels (guide/instru/bv/backing vocals) override the `-1`/`-2` slot (surfaces the real-world `S1102-2 … Guide` anomaly as mixed-only unpaired); WEAK words (Off/Lead/Vocals/Karaoke) stay in the title unless bracketed. - `TenantBulkFlow.tsx`: folder/file pick → editable review table (reassignable Mixed/Instrumental dropdowns, warnings strip, low-confidence cautions) → bounded-concurrency submit reusing the tenant single-submit sequence. Mixed-only rows blocked + flagged. Jobs stamped `state_data.batch_id` + `created_from='tenant-bulk'`. ### Resilient uploads (opt-in `upload_mode: "resumable"`) - Backend returns **GCS resumable session URIs** (created server-side with the caller's Origin → GCS answers session CORS itself; **no bucket CORS changes**). Signed PUT stays the default for all existing clients. - `frontend/lib/resumable-upload.ts` (dependency-free): 256KiB-aligned adaptive chunks, always-query-offset resume (no persisted byte ever re-sent), stall detection instead of hard timeouts, backoff+jitter cut short by online/visibility events, waiting-offline pause, EWMA throughput + per-row ETA, non-advancing-308 loop guard. - `frontend/lib/upload-recovery.ts`: IndexedDB persistence → after a reload/crash a "Resume unfinished batch?" banner lets the operator re-pick the folder and every upload resumes from its server-side offset against the same jobs (never duplicates). ### Tests - Backend: 26 new (real Bulk-Batch-1 fixture incl. S1102 anomaly, label-in-title regressions, endpoint auth/feature/cap gates, upload_mode contract) - Frontend: 22 new (engine chunk choreography/offset recovery/permanent errors/retry caps; component resumable routing, re-pick recovery, retry-no-duplicate) - Full suite green: backend (incl. emulator) + 1194 frontend - Prod E2E extension of `tenant-happy-path` is a documented follow-up (needs this deployed first) ### Docs - `docs/API.md`: new endpoint + `upload_mode`/`batch_id` fields - Design + decision record: workspace `docs/archive/2026-08-25-tenant-bulk-upload-plan.md` Local CodeRabbit review: 3 completed rounds on this branch, all 9 findings fixed. @coderabbitai ignore 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
7a3c1d6683 |
Clearer job status labels: 'Preparing your audio' for uploads + fix raw jobStatus.Processing key (#940)
## Why
Two frontend job-status **label** bugs, both surfaced while manually
driving the Vocal Star tenant flow:
1. **Tenant/upload jobs show "Downloading"** even though the operator
uploaded their own audio — there's nothing to download. (Andrew hit this
on a real job: "it's currently Downloading — what is there to download
though, since I uploaded the files?")
2. **Backlog item — raw i18n key rendered verbatim:** status sometimes
reads `[4/10] jobStatus.Processing`.
Both live in `frontend/lib/job-status.ts`.
## Fixes
**1. "Preparing your audio" for upload-based jobs.** The download stage
reused the consumer "Downloading" label. For jobs with a pre-supplied
instrumental (`existing_instrumental_gcs_path`), the staging stage now
shows **"Preparing your audio"**. Added `existing_instrumental_gcs_path`
to the job-list summary projection (`SUMMARY_FIELD_PATHS`) — it's a
top-level field (no `state_data` prune needed), so the list view can
detect upload jobs.
**2. No more raw `jobStatus.X`.** The "downloading + workers running"
path passed the **literal string `"Processing"`** (not a `jobStatus`
key) as the label, so `t("Processing")` missed and rendered
`jobStatus.Processing`. Now it uses a valid `processing` key, and when
only one parallel worker is reporting (tenant jobs run lyrics only — no
separation), it shows that worker's real status (e.g. "Transcribing
lyrics") instead of a generic label.
## Guardrail
Added a regression test asserting **every label `getJobStep` can emit
exists in `en.json` jobStatus** — so this whole class of raw-key bug
can't recur.
## Testing
- Frontend `job-status.test.ts`: 90/90 pass (new cases: upload-job
relabel, downloading_audio, advance-to-transcribing,
no-relabel-for-normal-jobs, raw-key regression, en.json completeness).
- Backend: new `SUMMARY_FIELD_PATHS` projection guard test.
- New keys `jobStatus.preparingAudio` + `jobStatus.processing`
translated to all 33 locales.
- Version bumped 0.199.2 → 0.199.3.
- CodeRabbit local review: 0 findings.
@coderabbitai ignore
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
|
||
|
|
c36bcb0850 |
Tenant flow: harden E2E invariants + retry transient Cloud Run Jobs trigger errors (#939)
## Why FROG: validate the white-label tenant portals (Vocal Star) work seamlessly end-to-end, and make the flow robust. Two related changes, both about the exact flow tenant operators rely on. ## 1. Harden the tenant E2E to actually test the real scenario The tenant happy-path E2E verified a job *completed and distributed privately*, but **tolerated a regression in the tenant-specific flow**: it "handled both" an instrumental-selection step appearing or not, so a regression that forced audio separation / an instrumental-review step on a tenant (who always uploads their own instrumental) would still have passed — the same "looks done but is broken" class as the June latent bugs. Tightened `tenant-happy-path.spec.ts` to lock the real-world invariants: - Assert the InstrumentalSelector **never** renders (no separation → no stem to pick). - Assert `state_data.instrumental_selection === 'custom'` (the uploaded instrumental is used, not a separated stem). - Assert `state_data.lyrics_complete` (transcription actually ran; not a short-circuit). Verified against a real completed vocalstar prod job (`ef72f5f8`): all new assertions hold. ## 2. Retry transient Cloud Run Jobs Admin API errors when triggering workers During validation, a real singa job hit `Failed to trigger Cloud Run Job lyrics-transcription-job: 503 The service is currently unavailable`. Root cause: `JobsClient.run_job()` had **no retry** — a one-off transient 5xx/429 from the Jobs Admin control plane hard-failed the trigger (the except just logged + returned False). `run_job` only *enqueues* an execution, so this is safe to retry. The daily E2E masked it with a workflow-level retry; a real customer job would have just failed at transcription. Added `_run_job_with_retry` (bounded async retry, 3 attempts, `asyncio.sleep` backoff) shared by **both** `run_job` call sites (`_trigger_worker_cloud_run_job` — audio-download / separation / lyrics / video — and `trigger_bulk_search_worker`). Retries transient errors only (503/500/504/429); permanent errors (NotFound/PermissionDenied/InvalidArgument) fail fast; re-raises after exhausting so the existing handler logs + returns False. ## Testing - New unit tests: transient-then-success retries once; persistent transient exhausts to False after N attempts; permanent error fails fast without retry. `backend/tests/test_services.py -k trigger` → 13/13 pass. - E2E assertions verified against a real completed prod job. - CodeRabbit local review: 0 findings. - Version bumped 0.199.1 → 0.199.2. @coderabbitai ignore --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
723207070a |
fix(review): proxy vocals audio through the API (fixes waveform CORS) (#933)
Proxy vocals audio bytes through the API instead of 302-redirecting to GCS, fixing the waveform CORS failure (cross-origin redirect made the browser send Origin: null, which the bucket CORS rejects). Backend-only; input audio keeps the redirect. |
||
|
|
1e99f9e0d5 |
feat(admin): per-job/user locale badge + "emails sent to user" history (#930)
## Summary
Two admin-only features so support/intervention work can (a) know what
language/country a user is using the product in, and (b) see the exact
emails ever sent to a user, rendered as they appeared in the inbox with
full delivery metadata.
### A — Language / country visibility (admin-only)
- New `get_full_locale_from_request()` captures the real UI language
(any of 33, not the narrowed en/es/de email locale) on **every**
job-creation path (URL, upload, audio-search, bulk, made-for-you via
Stripe metadata). Stored as `Job.locale` (+ added to the dashboard
summary projection) and `User.ui_locale` (kept separate from
`User.locale`).
- `LocaleBadge` (flag + language) shown in the admin jobs table, admin
job detail (+ country via the existing `IpInfo` on the creation IP), the
user-detail header, and the customer `JobCard` **gated to admins only**
— regular users never see it.
- Country is derived from IP (existing `ip_geolocation_service`); no new
capture.
### B — "Emails sent to this user"
- Every send routes through one `EmailService._log_and_send` chokepoint
that persists each email to a new Firestore `email_log` collection
(rendered HTML + Postmark MessageID), best-effort so it can never break
or delay a send. Single-use auth/capability tokens (magic-link, review,
referral) are **redacted** before persistence.
- `PostmarkAdminService` merges the Postmark Messages API (last ~45
days: exact HTML + opens/clicks/bounce/delivery status, paginated) with
the Firestore log (permanent), de-duplicated by message id.
- Endpoints `GET /api/admin/users/{email}/emails` and `GET
/api/admin/emails/{id}`; the user-detail "Emails Sent" card opens a
modal rendering the email in a sandboxed `<iframe srcDoc>` with a
metadata side panel.
- New Firestore composite index (`email_log` recipient + created_at)
added to Pulumi.
## Testing
- **41 new backend tests** (locale capture incl. q=0, email logging +
token redaction, PostmarkAdminService incl. pagination + 45-day
fallback, job-locale persistence, admin endpoints) — all pass.
- **10 new frontend tests** (LocaleBadge, UserEmailsCard list +
sandboxed-iframe modal) — all pass.
- Regression sweep on related existing suites: green. Preview-email flow
smoke-tested through the new chokepoint.
## Notes
- `pulumi up` for the new `email_log` index should be applied before
merge (done locally).
- `Job.locale` populates for new jobs going forward; historical jobs
fall back to the submitting user's locale where shown.
Local CodeRabbit review completed and addressed (token redaction,
pagination, row a11y, locale-overwrite guard, q=0 handling).
🤖 Generated with [Claude Code](https://claude.com/claude-code)
@coderabbitai ignore
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
|
||
|
|
d98e90c1d7 |
fix(audio-download): wire POSTMARK_SERVER_TOKEN into audio-download-job + resilient email construct (#925)
## Summary Fixes production job `a453d1d5` (Regina Spektor – Laughing With), which failed with: > Audio download failed: POSTMARK_SERVER_TOKEN is not set in production. Refusing to silently drop emails via the console provider — set the Postmark token secret. ### Root cause The audio download worker runs as its **own Cloud Run Job** (`audio-download-job`) — a thin orchestrator that calls the flacfetch VM over the VPC and waits, then triggers separation + lyrics. Each Cloud Run Job has an **independent env block**, and `audio-download-job`'s block omitted `POSTMARK_SERVER_TOKEN` (it was wired only into `karaoke-backend` and `video-encoding-job`). `audio_download_worker` → `reconcile_and_maybe_pause()` **eagerly** builds `get_email_service()` on every no-edit download, even though email is only sent in the rare over‑60‑min cancel branch. `EmailService()` deliberately raises in production when the token is absent (2026‑06‑09 fallback‑audit "fail loudly" guard), so the whole download failed. Blast radius was small (1 job in Firestore) because jobs that stop at `AWAITING_AUDIO_EDIT` never reach reconcile — but it recurs for every automated/no‑edit download. ## Changes - **infra** (`infrastructure/modules/cloud_run.py`): add `POSTMARK_SERVER_TOKEN` secret env to `audio-download-job` so the over‑limit cancellation email works. *(Needs `pulumi up` — applied locally before merge.)* - **`backend/services/duration_reconciliation.py`**: wrap `get_email_service()` in try/except → log and proceed with `email_service=None`. A construct‑time email failure can no longer crash an otherwise‑successful paid download (`reconcile_duration` already tolerates `None`; over‑limit still cancels + refunds). - **tests**: `survives-email-service-failure` (proceeds) and `over-limit-still-cancels-without-email`. - **`backend/config.py`**: corrected a stale comment claiming `lyrics-transcription-job` needs `ANTHROPIC_API_KEY` — the LLM work actually runs on the API service (`auto_correct_worker`), not the lyrics job. - version bump 0.196.9 → 0.196.10. ## Env audit Audited **all** Cloud Run Jobs' env vs. their worker code paths. The only production hard‑fail pattern is the `EmailService` guard; the POSTMARK gap was **unique to `audio-download-job`**. `bulk-search-job` and `lyrics-transcription-job` never construct `EmailService` on their path; `video-encoding-job` already has the token and is doubly defended. No other env vars need adding. ## Testing - `test_duration_reconciliation.py` 14/14, `test_audio_download_worker.py` 37/37, `test_email_service.py` included — 94 passed. - CodeRabbit local review: no findings. @coderabbitai ignore Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
0bba4ff041 |
fix(made-for-you): isolate order emails from audio-acquisition failures (#924)
## Problem Job `17dc6f48` (a Made-For-You order) failed on a YouTube "confirm you're not a bot" download error, and the admin **never received the "New Made-For-You Order Received!" email** — leaving no signal that a paid order needed attention, and no certainty the customer got their confirmation. The Discord error monitor also fired `'EmailService' object has no attribute 'send_email'`. Two root causes in `_handle_made_for_you_order` (`backend/api/routes/users.py`): 1. **Emails were sent *after* audio acquisition.** Both the customer confirmation and the admin notification ran only after the fallible YouTube download / audio search. When acquisition raised, execution jumped to the error handler, **skipping both emails.** 2. **The error fallback itself crashed.** It called `email_service.send_email(...)`, but that method existed only on the *provider* (`self.provider.send_email`), never on `EmailService` — so even the failure alert was lost. ## Changes - **Send the customer order-confirmation email up-front**, right after job creation and *before* audio acquisition. The order is paid/confirmed regardless of the download/search outcome. Resilient: a delivery failure is logged, not fatal. - **Wrap the admin notification** so an email hiccup on a successful order can't fake a `[FAILED]` alert. - **Route the outer failure handler through `_send_mfy_failure_alert()`** — never raises, HTML-escapes user input, tolerates `job_id=None`. Success → normal admin notification; audio-acquisition failure → `[FAILED]` admin alert while the customer stays confirmed. - **Add a thin `EmailService.send_email()` passthrough** to the provider (fixes the `AttributeError`). - **Handle `False` provider results** (providers signal rejection by returning `False`, not raising): log accurately instead of always "Sent"; a rejected *customer* confirmation is escalated to the admin so it can be resent manually. - **Retry dropped paid orders:** if job creation fails (no `job_id`, session never marked processed), re-raise after alerting so the Stripe webhook returns non-2xx and Stripe retries. Post-creation failures keep `job_id` set and return 200 to avoid duplicate jobs on retry. - Idempotency preserved: the Stripe session is marked processed before the confirmation send, so a webhook retry can't double-send. ## Out of scope The YouTube "confirm you're not a bot" download error itself is a separate flacfetch/yt-dlp cookies issue (credential keeper) — this PR only makes the order emails resilient to it. ## Testing - `make`-level backend suites for made-for-you, tenant/email, admin-feedback, internal-webhook all green (138 passed locally). - New/updated regression tests: - customer confirmation survives a YouTube download failure - confirmation-email failure doesn't abort order processing (and is escalated) - provider-returns-`False` confirmation is escalated - job-creation failure re-raises (Stripe retry) after alerting - `EmailService.send_email` passthrough delegates to the provider - Local CodeRabbit review: 2 findings addressed, re-run clean (no new findings). @coderabbitai ignore --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
c76d58394d |
fix(fallbacks): T7 — prod fail-fast on missing config + tenant gate safe-by-default (#808)
## Summary Theme 7 of the silent-fallback audit (`docs/archive/2026-06-09-fallback-audit-plan.md`, in #805). A single unset/rotated env var used to silently produce wrong behaviour in prod with only a warning. Now production fails fast / is safe-by-default. Verified against Pulumi infra: prod sets `ENVIRONMENT=production`, `CLOUD_RUN_SERVICE_URL`, `GCS_BUCKET_NAME`, `GOOGLE_CLOUD_PROJECT`, and Postmark (secret); Cloud Run also auto-sets `K_SERVICE`. ## Changes - **`config.is_production()` + `validate_production_config()`** (called from `main.py` lifespan): production refuses to boot if `GOOGLE_CLOUD_PROJECT`, `GCS_BUCKET_NAME`, or `CLOUD_RUN_SERVICE_URL` are unset — instead of silently using a dev default (wrong project for secret lookups / wrong bucket / localhost worker URL). This **subsumes 7.3** (worker_service localhost fallback). `is_production()` treats Cloud Run's auto-set `K_SERVICE` as production, so it's robust even if `ENVIRONMENT` were unset. - **Tenant middleware (7.4, security)**: the `?tenant=` override (a spoofing vector) is now disabled whenever `K_SERVICE` is present, not only when `ENVIRONMENT=production` — production-safe by default. - **dropbox_service (7.1)**: `GOOGLE_CLOUD_PROJECT` default was the **wrong literal** `"karaoke-gen"` (real project is `nomadkaraoke`); replaced with an empty default (prod requires it via the startup gate). - **email_service (7.5)**: a missing `POSTMARK_SERVER_TOKEN` in production used to silently use the console provider (sends "succeed" while emails vanish). Now raises in production; console fallback remains for dev/test. ## Deferred (flagged) **7.2** `GCS_TEMP_BUCKET` / `GCS_OUTPUT_BUCKET` — these are **not** set via env in infra, so their config defaults are load-bearing. Requiring or changing them risks prod, so deferred pending confirmation of whether those buckets are actually used. ## Testing - [x] New `backend/tests/test_fallback_prod_config.py` (is_production, validate gate raise/pass/no-op, email prod-raise vs dev-console, tenant K_SERVICE) - [x] 111 related tests pass (email, tenant, config) — no regressions, no cross-test pollution from the tenant module reload ## 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> |
||
|
|
5fff6d67b0 |
fix(fallbacks): T1 — flacfetch sole downloader, no silent YouTube downgrade (#806)
## Summary Theme 1 of the silent-fallback audit (`docs/archive/2026-06-09-fallback-audit-plan.md`, added in #805). flacfetch is the sole/lossless downloader — a configured-remote failure must not silently downgrade to a local YouTube-only rip. This is the exact class as the 2026-06-08 Facebook-URL incident. ## Changes - **`audio_search_service._search_remote`**: a `FlacfetchServiceError` from the remote service was swallowed and silently re-run against the local YouTube-only fetcher. Now fails loudly (`AudioSearchError`) and clears cached state. **No silent downgrade.** - **`create_audio_fetcher`** (local CLI factory): a half-configured remote (exactly one of `FLACFETCH_API_URL`/`FLACFETCH_API_KEY`) used to warn and silently use local mode, masking a deploy/secret typo. Now raises `AudioFetcherError`. ## Scope / deferred (needs your call) Findings **1.2** (tracker configured-but-unusable → silently YouTube-only) and **1.4** (`select_best` → first result on ranking failure) live in the **shared local `FlacFetcher`** and have dedicated tests asserting graceful local-CLI behaviour (`test_select_best_handles_exception`). Your "fail loud" directive was framed around the *cloud* silent-downgrade; hard-failing the local CLI when a user simply has no usable tracker would change intentional local behaviour. **Deferred for a per-item decision** rather than steamrolled — see the audit plan doc. ## Testing - [x] `backend/tests/test_audio_search.py` + `tests/unit/test_audio_fetcher.py` pass (209) - Added: remote-error-does-not-fall-back-to-local; updated the two half-config factory tests to expect a raise. ## Review - [x] CodeRabbit CLI review completed locally (1 major finding: clear cached results on failure — fixed) @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> |
||
|
|
27a5d8fdff |
fix(fallbacks): T8 — fail loud cleanups (docstrings, download errors, admin-token signal) (#805)
## Summary
First (low-risk) batch of the silent-fallback audit — see
`docs/archive/2026-06-09-fallback-audit-plan.md` for the full catalogue
and Andrew's per-theme decisions. This PR is **Theme 8**: fix
lying/stale docstrings, surface specific download-failure reasons, and
make an empty admin-token config a loud signal.
## Changes
- **Fail-open docstring lie → fail-closed**
(`credit_evaluation_service.py`, `config.py`): the AI credit evaluator
is fail-CLOSED (`pending_review`, no auto-grant) but its docstrings
claimed fail-open. Corrected so a future maintainer can't "fix" the code
into a free-credit-abuse hole.
- **Stale yt-dlp docstrings** (`youtube_download_service.py`,
`lyrics_worker.py`): removed text still describing the deleted
local-yt-dlp fallback. flacfetch is the sole downloader; the service
raises when unconfigured.
- **Specific download errors** (`audio_worker.py`, `lyrics_worker.py`):
`download_audio()` now raises a specific `DownloadError` per failure
mode instead of returning `None` → generic "Failed to download audio
file". Workers map it to a clear `Audio download failed: <reason>`
job-failure message.
- **Loud admin-token signal** (`auth_service.py`): empty `ADMIN_TOKENS`
now logs at ERROR (error-monitor → Discord) instead of a quiet warning.
It fails closed (403 everywhere) and looked like an auth bug rather than
a config error.
- Adds the audit plan doc + a `LESSONS-LEARNED` principle ("don't invent
silent fallbacks — ask or fail loud").
## Testing
- [x] Affected backend tests pass locally (85 passed): `test_workers`,
`test_workers_extended`, `test_audio_worker_download`,
`test_auth_admin_tokens`
- [x] Import sanity check (no circular import from new `DownloadError`
imports)
- Updated `test_download_audio_url_without_gcs_path_refuses` to expect
`DownloadError`; added no-source raise tests for both workers +
admin-token tests.
## Review
- [x] CodeRabbit CLI review completed locally (1 minor doc finding,
fixed)
@coderabbitai ignore
---
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
|
||
|
|
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> |
||
|
|
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>
|
||
|
|
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> |
||
|
|
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 |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |
||
|
|
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> |