mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-28 01:49:00 +09:00
36b331f3d7411ecf97c05bf15146e83161ab94de
1791
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>v0.226.0 |
||
|
|
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>v0.225.10 |
||
|
|
ecd114c6e3 |
fix(admin): AuthResult is not subscriptable — 3 admin endpoints 500'd (#1007)
## Problem
Overnight alert (2026-09-15): `Exception in ASGI application` +
`request_audit_error` on `POST /api/admin/jobs/{id}/reset-worker-state`.
Root cause:
```
File "backend/api/routes/admin.py", line 688, in reset_worker_state
logger.info(f"Admin {auth_data[0]} reset worker state for job {job_id}")
TypeError: 'AuthResult' object is not subscriptable
```
`require_admin` returns an `AuthResult` object, but three endpoints
logged `auth_data[0]` (tuple-style) → 500 on **every** call. (The reset
endpoint's partial run also caused a downstream screens *"prerequisites
not met"* because it cleared progress state before the log line blew
up.)
Affected: `reset_worker_state` (:688), `clear_audio_search_cache`
(:638), `clear_all_flacfetch_cache` (:721). Every other admin endpoint
already uses `auth_data.user_email` — these three were outliers.
## Fix
- `auth_data[0]` → `auth_data.user_email` in the 3 log lines.
- **Regression tests** (these endpoints had *no* coverage, which is why
it shipped): `reset-worker-state` and `DELETE /cache` now assert **200,
not 500**. The require_admin test mock already returns an `AuthResult`,
so these tests fail on the old code.
The stale `auth_data: Tuple[str, UserType, int]` type hints elsewhere
are harmless (nothing else subscripts `auth_data`) and left untouched to
keep the diff minimal — noted in
`docs/archive/2026-09-15-e2e-flakiness-error-triage-handoff.md` for a
later cleanup.
## Not related to the E2E orchestration fixes
This is item 2 from the overnight triage — an admin endpoint bug
triggered by a manual/admin reset of a failed job, unrelated to the
prep→screens / review-submit fixes (#1002/#1003).
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
- **Bug Fixes**
- Fixed administrator cache-clearing and worker-state reset actions that
could fail with a server error.
- These admin operations now correctly record the authenticated
administrator and complete successfully.
- Improved reliability for full cache clearing, audio-cache clearing,
and worker-state reset requests.
- **Tests**
- Added regression coverage for administrator authentication and audit
logging across affected endpoints.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
|
||
|
|
727329d458 |
fix(e2e): seed test-token via addInitScript — fix canary execution-context race (#1006)
## Problem Regression from #1003. That PR changed `gotoWithRetry`'s default `networkidle`→`domcontentloaded` (to fix the #170 goto-timeout), so `page.goto` now returns before the `/app` SPA settles. The **test-token auth path** then did: ```ts await gotoWithRetry(page, `${PROD_URL}/app`); await page.evaluate((token) => localStorage.setItem('karaoke_access_token', token), accessToken); ``` The `page.evaluate` raced the `/app` client-side redirect → **`Execution context was destroyed, most likely because of a navigation`**. This path is used by the **post-deploy canary** (the daily E2E uses magic-link, which is why the *daily* passed but *every deploy's canary* failed on v0.225.5+, e.g. run #3410 on v0.225.7). ## Fix Seed the token with `page.addInitScript` **before** navigating — `addInitScript` runs before page scripts on every navigation, so the app is authenticated on first load with no post-navigation `evaluate`. Drops the racy `evaluate` + `reload` + `networkidle` wait. Audited the other `gotoWithRetry` sites: the `PROD_URL` goto is followed by auto-waiting `expect()` asserts; the review-page gotos settle via `expect().toBeVisible()` / `waitForTimeout` before their `scrollTo` evaluates — the token path was the only actual race. ## Testing - Spec typechecks clean. - Verified by the **post-deploy canary** on this version's deploy (it runs the token path) — should go green where v0.225.5–.7 failed. Root-cause detail + triage of the other overnight alerts (Stripe Stage-1 flake, admin `reset-worker-state` 500, Postmark suppressed-recipient) is in `docs/archive/2026-09-15-e2e-flakiness-error-triage-handoff.md`. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **Bug Fixes** - Improved the pre-configured-token sign-in flow to load more reliably and avoid navigation timing issues in end-to-end testing. - **Chores** - Incremented the project version to 0.225.8. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>v0.225.8 |
||
|
|
462f246768 |
internal: admin endpoint to re-run auto-approval eval on parked review jobs (#1005)
## Summary
Adds `POST /api/internal/jobs/{job_id}/auto-approval-eval` (admin-only):
re-runs the auto-approval evaluator on a job parked at AWAITING_REVIEW.
The KaraokeHunt outreach batch runs with `made_for_you: true`
(stale-review exemption), which is also an enforcement blocker at
scoring time — this endpoint lets us lift the flag and re-evaluate so
confident jobs full-auto through review.
## Testing
- `test_internal_api.py::TestAutoApprovalEval` — outcome passthrough +
auth required; file green in full-collection run.
🤖 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**
- Administrators can manually re-run auto-approval evaluation for jobs
awaiting review.
- Jobs remain in review unless the evaluation is fully confident,
providing a fail-safe review process.
- **Bug Fixes**
- Improved batch job processing so an issue updating an optional job
setting no longer stops the remaining workflow.
- Prevented missing cached results from causing failures during
recanonicalization tasks.
- **Tests**
- Added coverage for authorized evaluation requests and unauthorized
access.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
|
||
|
|
6800c14e57 |
admin: make made_for_you editable on jobs (stale-review exemption) + KaraokeHunt outreach tooling (#1004)
## Summary - Add `made_for_you` to `EDITABLE_JOB_FIELDS` (with a boolean guard) so admin batch flows can exempt jobs from the 48h stale-review auto-expiry (`stale_review_processor` skips MFY jobs). Needed for the KaraokeHunt outreach batch: ~90 jobs held at review under a holding account until coordinated emails go out. - KaraokeHunt outreach tooling under `scripts/karaokehunt_outreach/` (phase1b/1c analysis, phase2 executor, batch generator, torrent review) — standalone scripts, no runtime impact. - Session handoff docs in `docs/archive/`. ## Testing - `backend/tests/test_admin_job_update.py`: new `TestUpdateJobMadeForYou` (editable + non-bool rejected) — 20/20 pass. - Full backend suite: 4417 passed (unit) + emulator suite green via `make test-e2e`. 🤖 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** - Administrators can mark jobs as “made for you,” keeping them available for review indefinitely instead of automatically expiring after 48 hours. - Invalid values for this setting are rejected with a clear validation error. - **Documentation** - Added operational documentation for the KaraokeHunt outreach and migration workflow, including request review, song matching, account credits, and generation stages. - **Chores** - Updated the application 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>v0.225.6 |
||
|
|
38350053f6 |
fix(e2e,review): deterministic review-submit + durable render dispatch (#1003)
## Problem
Mode B of the E2E job-orchestration stalls (plan:
`docs/archive/2026-09-15-e2e-job-orchestration-stalls-plan.md`).
Investigation this session found every `in_review`-stuck job was an
**E2E test job**, and `POST /api/review/{id}/complete` was **never
called** for them (real jobs complete fine — 200s). So the job correctly
waits at `in_review`; the **test's review-completion step is flaky**. It
failed silently: Step 8 clicked submit + `waitForTimeout`, never
verifying the transition — so a dropped click / swallowed
`completeReview` surfaced ~40 min later as a misleading "Timeout waiting
for job completion".
## E2E — fix the flakiness at its source
- **`assertReviewSubmitted()`** polls `/api/jobs/{id}` (as the job
owner, admin-token fallback) and asserts the job left
`awaiting_review`/`in_review` after a submit — fails **loud at the
submit step** with an actionable message instead of a misleading
completion timeout.
- **Step 8** now verifies the instrumental submit landed and **retries
the submit once** before failing; **Step 7 "Complete Track"** confirms
the transition too.
- **`gotoWithRetry` now defaults to `domcontentloaded`** instead of
`networkidle` — this long-polling SPA never reaches network-idle, which
timed out `page.goto` at 60s (the real run #170 retry failure).
## Backend — durability (W1c)
- `complete_review` now **awaits** the render-worker dispatch instead of
a fire-and-forget `asyncio.create_task` (which can be dropped if the
Cloud Run instance is recycled right after the 200, stranding the job at
`review_complete`). A dispatch failure does **not** fail the user's
approval — `recover-stuck-jobs` re-triggers `review_complete` jobs with
no render within ~5 min.
## Testing
- Backend review suite green (298 passed; 2 failures are pre-existing
emulator-dependent `song_request_service` tests, unrelated).
- `happy-path-real-user.spec.ts` typechecks clean (the pre-existing
`next-intl`/`stripe-webhook-security` tsc errors are unrelated).
- The hardened E2E is self-verifying by design — the next scheduled run
exercises it end-to-end in prod.
## Notes / deferred
- Complements PR #1002 (Mode A — durable prep→screens handoff, the
backend root cause). Independent files.
- **Deferred (follow-up):** a speculative frontend change to
`LyricsAnalyzer`/`InstrumentalSelector` error handling — the current
fallback (route to the instrumental screen on error) is reasonable, and
the hardened test will now pinpoint the exact client-side failure if it
recurs, enabling a targeted fix rather than a guess. Also deferred:
broadening the stale-review watchdog to non-cancel alerting for
tenant/test jobs (needs a product call on auto-cancel vs alert).
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
v0.225.5
|
||
|
|
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>v0.225.4 |
||
|
|
ed73e34a8d |
feat: typo-tolerant kn_community_search (fuzzy matching, like gen) (#1001)
## Ask Make kjbox's KaraokeNerds search tolerate typos like karaoke-gen does (e.g. Andrew typed "books from boxs" → gen corrected to "Books From Boxes" and found the NOMAD match). ## Approach gen corrects the query upstream via a catalog/LLM match step. The Cloud Function is lightweight, so this adds self-contained fuzzy matching in BigQuery: each query token matches a catalog word by **exact substring (STRPOS) OR Levenshtein `EDIT_DISTANCE`** within a length-scaled threshold (0 for <4 chars, 1 for 4–6, 2 for 7+). Diacritic-folded on both sides (from the prior accent fix); a CTE computes the folded haystack once per row. ## Validated against real BigQuery (not just mocked tests) | query | result | |---|---| | `maximo park books from boxs` | exactly **Maxïmo Park – Books From Boxes (NOMAD)** | | `books from boxs` | Maxïmo Park – Books From Boxes | | `fletwood mac dreems` (2 typos) | Fleetwood Mac – Dreams ×3 | | `maximo park` | all 12 Maxïmo Park rows (unchanged) | **Gotcha caught by live-testing:** `EDIT_DISTANCE(w, tok, max_distance => thr) <= thr` matched the *entire table* — BigQuery caps the return value at `max_distance`, so the comparison is always true. Fixed by comparing the true distance (the table is small, so full Levenshtein per word is cheap). ## Deploy Infra change — `pulumi up` locally (gen infra doesn't deploy via CI). Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>v0.225.3 |
||
|
|
e236a80268 |
fix: accent-insensitive kn_community_search (Maxïmo Park etc.) (#1000)
## Bug
kjbox "Search Karaoke Nerds" for **maximo park** returned *No results
found*, while karaokenerds.com shows 13 songs. Root cause: the artist is
stored as **Maxïmo Park** (ï), and the divebar Cloud Function's
`kn_community_search` did a raw `LOWER(...) LIKE '%maximo%'` with **no
diacritic folding**, so the ASCII query never matched — hiding real
results, **including our own NOMAD tracks** (10 of the 12 community rows
are NOMAD).
The KaraokeNerds site folds accents; gen's backend path already folds
via `normalize_for_match`. Only this CF path was affected.
## Fix
Diacritic-fold on **both** sides:
- Query tokens (Python): NFD → drop combining marks → lower.
- Haystack (BigQuery): `LOWER(REGEXP_REPLACE(NORMALIZE(CONCAT(Artist,'
',Title), NFD), r'\p{Mn}', ''))`.
Verified against the community export: "maximo park" now returns all
**12** Maxïmo Park rows. Will re-verify against the live CF + kjbox
after `pulumi up`.
## Deploy
Infra change — `pulumi up` locally (gen infra doesn't deploy via CI).
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
- **New Features**
- Search now matches catalog entries regardless of accents or
diacritical marks. For example, entering “maximo” can find “Maxïmo.”
- Accent-insensitive matching applies to both search terms and catalog
artist or title information.
- **Bug Fixes**
- Improved search behavior for queries that use unaccented text when
catalog results contain accented characters.
- **Chores**
- Updated the application version to 0.225.2.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
v0.225.2
|
||
|
|
5ede33b529 |
fix: remove invalid BigQuery LIKE ESCAPE clause in kn_community_search (#999)
Follow-up to #998. Live-testing the deployed `divebar-lookup` Cloud Function revealed `kn_community_search` failed on every query: > Syntax error: Expected end of input but got keyword ESCAPE **BigQuery's `LIKE` has no `ESCAPE` clause** — backslash is its default escape character. The `LIKE @tok ESCAPE '\\'` added in #998 is a syntax error. This drops the clause; the parameter value is still backslash-escaped (`%`→`\%`, `_`→`\_`), which BigQuery honors natively, so `%`/`_` in a query token still match literally. Unit tests mock BigQuery so they never exercised the real SQL — added an assertion that the SQL contains no `ESCAPE`, and will re-verify against the live CF after `pulumi up`. kjbox is not yet deployed, so there was no user impact. Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>v0.225.1 |
||
|
|
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>
v0.225.0
|
||
|
|
e460b6d73e |
perf(dr-backup): parallel + incremental + deduped S3 upload (#997)
## Why Follow-up to #996. The nightly `backup-to-aws` blew past its 1800s timeout even though it's supposedly an *incremental* cloud-to-cloud copy. Root causes (verified against prod S3 + staging): 1. **Serialized transfer through the function.** `upload_staging_to_s3` streamed each GCS blob → S3 in a single `for` loop (`blob.open` → `upload_fileobj`) on a 1-CPU / `maxInstanceRequestConcurrency:1` instance. Throughput was capped by one stream + per-file open/close overhead + SSL-retry stalls — not by bandwidth. 100 GB serialized ≈ 30 min; parallel ≈ minutes. 2. **No idempotency.** Uploads relied on delete-after-success; a file whose S3 upload flaked or wasn't reached before timeout was never deleted, so **every subsequent night re-attempted it** and new deltas piled on — a compounding backlog (found files stuck in staging since 09-13). 3. **Duplicate finals.** The render pipeline writes every final under both a machine name (`lossless_4k_mp4.mp4`) and a human name (`Artist - Title (Final Karaoke Lossless 4k).mp4`), byte-identical, in the same `finals/` dir. The backup stored/transferred the largest, most-regenerable data twice — `gcs/job-files/` on S3 is 590 GB, ~half of it duplication. ## What `upload_staging_to_s3` now: - **Parallel** — transfers fan out across a thread pool (boto3 low-level clients are thread-safe) with a tuned multipart `TransferConfig` (peak mem `workers × max_concurrency × chunksize` ≈ 512 MB, well under 4 Gi). - **Incremental** — `_s3_object_matches` HEADs S3 by key+size and skips anything already backed up (deletes it from staging). Only genuinely new/changed bytes cross the wire; a prior partial run self-heals instead of re-transferring the backlog. - **Deduped** — `_dedupe_final_duplicates` keeps one blob per content checksum (crc32c) per `finals/` directory and drops the twin. Scoped to one dir + matched on checksum, so a coincidental cross-job size collision can't cause a false drop. **Ordering guarantee from #996 preserved**: two phases — small/irreplaceable prefixes (`secrets/`, `git-repos/`, `gcs/kn-data/`, `firestore/`) upload to completion (barrier) before the large `gcs/job-files/` finals — so a mid-run timeout can still only ever cost regenerable finals. ## Testing `test_s3_upload.py` (5 tests, all backup-fn tests green — 31 passed): - exclude-prefix hold-back (unchanged behavior) - byte-identical final duplicate deduped (one upload, both twins cleared) - already-in-S3 object skipped, not re-uploaded - critical prefixes complete before large finals (phase barrier) ## Deploy note ⚠️ Ships via `infrastructure/functions/backup_to_aws/deploy.sh` (manual `gcloud functions deploy`), **not** Pulumi/CI — must run `deploy.sh` after merge. ## Not in scope Existing ~590 GB in S3 still contains the historical duplicates; this prevents *future* dup transfer/storage. A one-time cleanup pass to reclaim the existing dup storage can follow if wanted. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Enhancements** * Improved backup uploads with parallel, incremental multipart transfers. * Avoids re-uploading unchanged files and removes duplicate final files. * Cleans up staging files after successful uploads or confirmed skips. * Prioritizes critical files before bulk uploads. * Provides clearer upload summaries, including skipped, duplicate, and error counts. * **Chores** * Updated the project version to 0.224.2. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>v0.224.2 |
||
|
|
db7e010fdb |
fix(dr-backup): upload irreplaceable prefixes to S3 before large finals (#996)
## Problem The `backup-to-aws` Cloud Function alerted: **git repos + encrypted secrets backups stale** (61h old vs 36h limit, last fresh 2026-09-12), while Firestore/GCS/BigQuery stayed fresh. ## Root cause The function has a hard **1800s (30 min) request timeout** and was being killed at that limit (`The request has been terminated because it has reached the maximum request timeout`). `upload_staging_to_s3` (Step 5) walked staging blobs via `bucket.list_blobs()`, which returns objects in **lexicographic order**. The staging prefixes sort as: ``` firestore/ < gcs/job-files/ < git-repos/ < secrets/ ``` The multi-GB `gcs/job-files/` finals (e.g. 4k MP4/MKV outputs, aggravated by transient S3/GCS SSL-retry stalls) upload **before** `git-repos/` and `secrets/`. The function hit its 30-min wall mid–`gcs/job-files/` upload and **never reached** `git-repos/` or `secrets/` — exactly matching the monitor (GCS fresh, git+secrets stale since the day it last fit in budget). ## Fix Upload the small, irreplaceable prefixes first and the large, regenerable finals last: - `_upload_priority()` sorts `secrets/`, `git-repos/`, `gcs/kn-data/`, `firestore/` first, unknown prefixes next, and `gcs/job-files/` **always last**. - A mid-run timeout can now only ever cost the replaceable video finals — never code history or secrets. No behavior change to *what* gets uploaded/excluded/deleted — only the order. ## Testing - Added regression test `test_small_irreplaceable_prefixes_upload_before_large_finals` asserting secrets + git-repos upload before, and `gcs/job-files/` uploads last, even when input is in the buggy lexicographic order. - Existing exclude-prefix tests still pass (`3 passed`). ## Deploy note ⚠️ This function's **source ships via `infrastructure/functions/backup_to_aws/deploy.sh`** (manual `gcloud functions deploy`), NOT via Pulumi/CI. Merging does not deploy it — `deploy.sh` must be run after merge. The next nightly run (05:00 UTC) will then confirm git+secrets return to fresh via the freshness monitor. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **Reliability** - Backup uploads now prioritize small, irreplaceable data before large, regenerable job files. - If an upload is interrupted, critical backups are more likely to be preserved before the interruption occurs. - **Bug Fixes** - Corrected backup upload ordering so large job-file finals are consistently uploaded last, regardless of listing order. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>v0.224.1 |
||
|
|
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>v0.224.0 |
||
|
|
b41664a2fc |
docs: mark E2E reliability handoff resolved (PR #992, 3 green dailies) (#993)
Docs-only: adds the resolution note to `docs/archive/2026-09-12-e2e-reliability-handoff.md` — real root cause (nondeterministic "Complete Track" vs "Proceed to Instrumental Review" CTA), fix (PR #992), and DoD verification (3 consecutive green dailies covering both CTA branches + tenant green) — so a future session doesn't pick it up as open work. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
65285f7386 |
test(e2e): happy-path accepts all review CTA variants (root cause of the Stage-2 flake) (#992)
## Summary
Root-causes and fixes the daily Stage-2 / post-deploy-canary happy-path
"flake" (handoff: `docs/archive/2026-09-12-e2e-reliability-handoff.md`
§3).
**The flake was not a review data-load problem.** Artifacts from failed
run 34729291204 show the review page fully loaded (lyrics visible,
preview video rendered) — the Playwright error was `waiting for
getByRole('button', { name: /proceed to instrumental/i })`: the button
was **absent**, not disabled. The finish modal's CTA is nondeterministic
per job (`ReviewChangesModal` `completesReview`, driven by the
auto-scorer's backing verdict + stem availability, both of which vary
with each fresh transcription/separation):
- scorer **not** confident → **"Proceed to Instrumental Review"**
(two-screen flow) → test passed (e.g. the 22:15 UTC canary)
- backing confident and/or both stems ready → **"Complete Track"**
(inline instrumental chooser; completes the whole review;
`/instrumental` screen never appears) → test timed out (all of last
night's failures, same signature both retry attempts)
Both are correct product flows — this is a test-side fix, as steered by
the handoff's product-vs-test guidance (real users are not affected; the
review loads fine).
## Changes (spec-only, `happy-path-real-user.spec.ts`)
- **Step 7 finish CTA**: accept `Proceed to Instrumental Review` **or**
`Complete Track`. On Complete Track, wait for the success redirect to
`/app` and skip Step 8; also detect the product's `completeReview`
failure fallback (hash → `#/{id}/instrumental`) and fall through to Step
8 instead of timing out.
- **C1 mirror skip**: lyrics-confident jobs hash-redirect straight to
`#/{id}/instrumental` with no lyrics screen — detect via the hash and
jump to Step 8.
- **Real auto-waits**: the surface/readiness gates now use
`locator.waitFor()` / `expect().toBeEnabled()` — `isVisible({timeout})`
/ `isEnabled({timeout})` are instant snapshots (the timeout option is
deprecated/ignored) and gambled the run on render timing.
- **Fixed the always-firing "Review page content not found,
reloading..."**: the `.or()` union matched many elements → strict-mode
violation threw instantly on every run (including passing ones); scoped
with `.first()`.
- **Step 8 redirect check anchored on pathname**: bare `/\/app/` matched
the current `/app/jobs` URL and resolved instantly.
No version bump (test-only, matching #989/#990 precedent).
## Testing
- `eslint` clean; `playwright --list` parses the spec under the
production config.
- Local code review (8-angle finder + verify pass): 5 correctness
findings found and fixed (see commit 2); cycle-2 verification clean.
- Real validation is the next daily E2E runs (~$0.50 each): last night's
runs show the scorer currently hitting the "Complete Track" branch
consistently, so the new branch gets exercised immediately after merge.
Tenant E2E already re-verified green (run 34730560382).
## Success criteria (handoff §5)
This PR addresses criterion 1 (root cause + fix + written explanation).
Criteria 2–4 (≥3 consecutive green dailies, green canary on next version
bump, tenant green) verified post-merge.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit
* **Tests**
* Improved end-to-end coverage for lyric review flows with varying
automated verification outcomes.
* Added validation for both direct completion and instrumental-review
paths.
* Improved navigation checks and review-page readiness handling to
reduce test failures caused by timing or redirect differences.
* Updated test guidance and comments to reflect the supported review
scenarios.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
|
||
|
|
adc896dc7d |
docs: E2E reliability handoff (root-cause the happy-path flake) (#991)
Handoff doc for a dedicated session to get the production E2E tests reliably green. `docs/archive/2026-09-12-e2e-reliability-handoff.md` covers: - ✅ Stage 1 payment — fixed this session (e2etest95 95%-off → $0.50 on the Nomad debit card) - 🔴 **Stage 2 happy-path — the main task**: intermittent review-page **data-load** flake (`hasNoLyrics` → Proceed disabled → timeout at `happy-path-real-user.spec.ts:764`), with grounded file:line refs, hypothesis, repro steps, and likely product-vs-test fix shapes. Worker is healthy; not a regression. - 🟢 Tenant E2E — was a Sept-11 one-off, green since; re-verify. - R1 canary reuses the happy-path spec, so §3's fix fixes it too. `retries: 1` (#990) already stops single-flake paging (band-aid, not the cure). - Success criteria, ops access, relevant memories. Docs-only — no version bump. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
0895b142f6 |
test(e2e): allow one retry on happy-path (stop paging on review-page flake) (#990)
When verifying the payment fix end-to-end, Stage 1 (Credit Purchase) **passed** (~$0.50 on the Nomad debit card ✅) but Stage 2 (Happy Path) failed on the intermittent review-page flake: ``` WARNING: Review page content not found, reloading... WARNING: No video element found, but continuing anyway WARNING: Proceed button not ready after preview — recovering... ✘ expect(getByRole('button', {name:/proceed to instrumental/i})).toBeEnabled() — Timeout 30000ms ``` The same spec passed on the 0.223.2 canary earlier — it's flaky, not broken. **Root cause of the paging:** the spec pinned `retries: 0` (each retry = a fresh 15-20 min job), which also overrode the canary's `--retries=2` (spec-level `describe.configure` beats the CLI flag). So any single flake hard-fails and pages the daily E2E + the post-deploy canary. **Fix:** `retries: 1` — a genuine flake self-heals on a clean run; a passing run never retries, so no steady-state cost, capped at one extra attempt. Follow-up worth a separate look: *why* the review page / preview video is intermittently not-ready in prod (the underlying flake this masks). Frontend/e2e only — no version bump. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **Tests** - Improved production end-to-end test reliability by allowing one retry for intermittent preview and review-page readiness issues. - Preserved fast execution for passing runs while limiting additional time when a retry is needed. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
9e4e7f4876 |
test(e2e): daily credit-purchase ~$0.50 via 95%-off code (off personal card) (#989)
The daily E2E has failed 6 days straight at **Stage 1: Credit Purchase** — the real Stripe checkout couldn't complete because the personal card behind `E2E_STRIPE_CARD_*` was frozen (`stripe-checkout.ts:236` timed out waiting for the success redirect). Per Andrew's steer, keep real-payment coverage but make it cheap and off the personal card: - **Referral code `e2etest70` (70% off, ~$3) → `e2etest95` (95% off, ~$0.50).** $10 base × 5% = **$0.50 = Stripe's USD minimum** (a literal $0.10 isn't possible — Stripe rejects sub-$0.50 USD charges). The `e2etest95` vanity link is **already created in prod** (owner `admin@nomadkaraoke.com`, 95% off, 0% kickback, enabled). - Updated the discount-badge assertion (70%→95%) and cost comments. ## ⚠️ Action required (Andrew) Point the **`E2E_STRIPE_CARD_*` GitHub secrets at the Nomad debit card** (not your personal card). Until then the daily/canary purchase test will keep failing at checkout — this PR only makes it cheap; the frozen card is what's blocking completion. Frontend/e2e only — no backend change, no version bump. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **Tests** - Updated the production credit-purchase test to use a 95% referral discount. - Updated expected discount messaging and pricing to reflect the new offer and Stripe’s minimum charge. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
d93dbddd48 |
ci: reliable R1 canary version-gate + retry (stop false pages) (#988)
Follow-up to the incident-hardening initiative — fixes the false "Post-deploy canary FAILED (v0.222.3)" page from the #987 deploy. **Root cause:** the R1 version-change gate did a single un-retried curl to the raw Cloud Run **origin** `/api/health/detailed`, which came back empty (cold start on the scaled-to-zero prior revision and/or origin edge-auth on the detailed endpoint). It logged `Currently-serving version: <unknown>` and **fail-opened → ran the canary on a no-bump deploy**, which then flake-failed on a review-page timing wait and paged. **Fixes:** 1. **Reliable gate** — read the currently-serving version via the **edge** (`https://api.nomadkaraoke.com/api/health/detailed`, warm + Cloudflare-fronted, verified to return the version) with retries. A no-bump deploy now correctly **skips** the canary. 2. **Retry the canary** — `--retries=2` so a single flaky UI wait doesn't page; only a failure surviving retries is real. (The happy-path's review-page waits are inherently flaky; the identical spec passed on the 0.223.2 deploy.) No app code changed → no version bump. YAML validated. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.8 <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>v0.223.2 |
||
|
|
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>v0.223.1 |
||
|
|
5b5264dc54 |
Incident hardening: deploy/CI/runner resilience (R1/R2/R3/R4/C1/C2) (#987)
Part 3 of 3 of the **Incident hardening (post-NOMAD-1632)** initiative (plan: `docs/archive/2026-09-12-incident-hardening-plan.md`). Closes the deploy/CI/runner gaps: no functional gate, no codified rollback, bad revision serves 100% immediately, fire-and-forget runner stranding, and a flaky smoke. **No backend app code changed → no version bump.** ## ⚠️ Reviewer note — read first **R3/R4 rewrites the live `deploy-backend` step.** It's designed to be *auto-revert-safe* (a failed candidate smoke means we simply never migrate traffic, so the prior revision keeps serving 100% — a bad revision serves **0%**, not an outage). But it changes how **every** backend deploy works and **can't be fully exercised in CI**. This is the one to watch on first merge. If you'd rather de-risk, R3/R4 is the only item here that's safe to split out — the rest (R1/R2/C1/C2) are independent and lower-risk. ## R2 — codified fast rollback (`scripts/rollback.sh` + runbook) Dry-run-able, explicit-target-required rollback for the Cloud Run **service** (traffic-shift to a prior revision — instant, no rebuild) and the three **jobs** (image re-pin, correct per-job region/repo — verified against ci.yml). `--list` shows available revisions/tags; `--dry-run` prints every gcloud command. `docs/TROUBLESHOOTING.md` "Fast rollback" runbook added as the first section. ## R3/R4 — service traffic-canary `deploy-backend` now deploys `--no-traffic --tag candidate`, smokes the tagged candidate URL (health + expected version, with retries), then `update-traffic --to-latest` **only on pass**. Cloud Run Jobs can't traffic-split (noted inline) → they rely on R1 + R2. ## R1 — post-deploy functional canary, version-change-gated New `deploy-verify` job runs the real production happy-path (`happy-path-real-user.spec.ts`, admin-credit variant — reuses e2e-daily's impersonate token refresh, secret names verified identical) after a backend deploy, **only when the backend version actually changed** (new "Detect backend version change" step compares `poetry version` to the currently-served `/api/health/detailed`). Frontend/docs/infra-only merges short-circuit. On failure → Discord alert + loud fail printing the exact `scripts/rollback.sh` invocation. Per the plan's caveat, a fresh happy-path won't reproduce every incident class (e.g. Failure B's stale-cache) — an admin reset+retry variant is a noted follow-up. ## C1 — ephemeral-runner stranding fix `infrastructure/functions/runner_manager/ephemeral.py` now confirms the VM insert **operation** succeeded instead of fire-and-forget: a late stockout/quota/transient error raises → existing zone-fallback / webhook redelivery kicks in instead of silently stranding a queued job for ~15 min. An insert-confirm *timeout* is treated as "still provisioning" (not a failure); guarded for older clients. **+4 tests (46 pass).** ## C2 — de-flake the E2E smoke `networkidle` → `domcontentloaded` + explicit element waits (the marketing page's background requests made `networkidle` time out and redden real deploys). ## Validation (local only — no deploy) - `ci.yml` + `e2e-daily.yml` parse; **actionlint clean** on new code. - `rollback.sh`: `bash -n` + `shellcheck` clean; constants cross-checked against ci.yml. - `test_ephemeral.py`: **46 passed**. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> |
||
|
|
da5b575f05 |
docs: incident hardening plan (post-NOMAD-1632 follow-up) (#984)
Docs-only. Lands the grounded, prioritized hardening plan produced as a follow-up to the 2026-09-11→12 incidents (silent partial 720p publish + the fix's guard over-firing on empty/stale-cache results). `docs/archive/2026-09-12-incident-hardening-plan.md` — case study, current-state map (CI/CD, deploy, test infra, detection) with file:line refs, and prioritized recommendations across Testing / Guardrails / Deployment / Detection / Process / CI-reliability, with a §0 resume section and §5 sequencing. Tracked as the `Incident hardening (post-NOMAD-1632)` engine item in workspace `BACKLOG.md`. No code changes. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Documentation** * Added an archived incident-hardening plan covering two production incidents, their shared process gap, and current deployment and detection practices. * Documented prioritized recommendations for preventing silent partial publishes, improving rollout robustness, strengthening guard discipline, and increasing CI reliability. * Included failure-to-recommendation mappings and suggested implementation sequencing. <!-- end of auto-generated comment: release notes by coderabbit.ai --> 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>v0.222.3 |
||
|
|
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>
v0.222.2
|
||
|
|
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>v0.222.1 |
||
|
|
ccbb0c1aea |
Add YouTube description updater architecture diagram (svg + png) (#980)
## Summary - Adds `docs/images/youtube-description-updater-architecture.svg` and the rendered `.png` — supporting assets for the YouTube API quota-increase compliance review. - Docs-only change (new binary/vector assets), no code touched. ## Test plan - [x] Verified PNG renders correctly (4320x2760, valid PNG) via `rsvg-convert` - [x] Verified SVG is valid |
||
|
|
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>v0.222.0 |
||
|
|
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>
v0.221.0
|
||
|
|
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>
v0.220.0
|
||
|
|
535135249c |
docs(requests-board): product overview + Phase 2 handoff (#976)
Documentation-only follow-up to #975 (requests voting board Phase 1). - **`docs/REQUESTS-BOARD.md`** — self-contained explanation of the requests system: the vision (one free track/day, funnel to paying users), the live Phase-1 user experience, how it works, where it lives (`requests.nomadkaraoke.com`), and explicit **marketing / YouTube-description guidance** (link + framing + an honest note about not over-promising the daily cadence until Phase 2 ships). This is the doc to point the YouTube-descriptions work at. - **`docs/archive/2026-09-03-requests-voting-board-phase2-handoff.md`** — cold-start handoff for a fresh session to build Phase 2: the source-agnostic daily picker (which merges the "Autogen trending-karaoke agent" backlog item per Andrew's decision), free-credit grant, 24h ownership hand-off, voter publish-emails, and the YT-description link — with design decisions, reuse map, gotchas, suggested build order, and open questions. - `docs/README.md` — links REQUESTS-BOARD.md in Quick Links. No code changes; no version bump. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Documentation** * Added documentation for the Requests Voting Board, including its current experience, voting workflow, and planned automation. * Added the Requests Voting Board to the documentation quick links. * Added an archived handoff guide covering the planned second phase of the voting board. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- 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>
v0.219.0
|
||
|
|
ff18ecbaab |
fix(jobs): atomic dot-path state_data writes (distribution + audio-edit races) (#974)
## Summary Follow-up hardening sweep to the `file_urls`/`state_data` lost-update fix (#970). An audit found the same **read-copy-mutate-write-whole-map** pattern in 8 more sites; this converts them to atomic Firestore dot-path writes so a stale snapshot can't clobber a concurrent sibling key. ## Changes - **`video_worker` distribution / redistribution / finalize (3 sites)** — the most dangerous: they rewrote the whole `state_data` map and `.pop('visibility_change_in_progress')`, so a stale write could **revert the `worker_generation` supersession fence** (an atomic `Increment`) or resurrect the visibility guard — the "visibility-recycle-dataloss" surface. Now dot-path writes, with `DELETE_FIELD` for the guard. - **Audio-editor undo / redo / apply (`review.py`)** — full-map rewrites that could race with rapid clicks or the idle-reminder scheduler active during audio-edit → dot-path writes. - **Audio-editor upload-for-join** — now writes only *this* upload's entry via `FieldPath(...).to_api_repr()` (backtick-escapes the hyphenated uuid, string key), so concurrent uploads **merge** instead of one dropping the other (which orphaned a GCS file and 404'd on join). *(CodeRabbit finding #1.)* - **Deferred YouTube-URL write (`youtube_queue_processor`)** → dot-path. ## Out of scope (documented) - The two audio-edit **list** fields (`audio_edit_stack` / `audio_edit_redo_stack`) remain last-write-wins across concurrent edits to the *same* job — a list can't be dot-path-merged. Acceptable for the single-reviewer sequential audio-editor UI; true multi-writer safety needs a transaction/CAS. Documented inline. *(CodeRabbit finding #2 — deliberately deferred.)* - Two low-risk fresh-dict-*replace* sites (create-from-search / admin re-search) — single-request, early-lifecycle — left as-is. ## Testing - [x] Full backend unit suite green (4266 passed) + emulator suite green (118 passed). - [x] New emulator regression tests: distribution write preserves the `worker_generation` fence + clears the visibility guard (with a contrast test showing the old full-map write reverted the fence); concurrent audio-edit uploads both survive. - [x] Updated the 2 unit tests that asserted the old full-map shape. - [x] CodeRabbit CLI: finding #1 fixed, finding #2 documented/deferred; no new findings on re-review. ## Review - [x] Local CodeRabbit review completed (2 cycles); feedback addressed @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>v0.218.1 |
||
|
|
3c58143f75 |
fix(review): re-sign instrumental preview URLs on expiry (refresh-on-error) (#973)
## Problem
Completing a combined review failed to play the instrumental in the
preview modal — toggling to **Instrumental** loaded nothing, with
`NS_ERROR_DOM_NETWORK_ERR` in DevTools (Firefox) on the
`review-audio/instrumental_with_backing.ogg` GCS request.
**Root cause:** the overlaid instrumental `<audio>` uses the signed GCS
URL baked into the review payload at page load, which has a **120-minute
expiry**. A long review session outlives it, so the stem fetch returns
`400 ExpiredToken` and playback silently fails. Confirmed by fetching
the exact URL from the report: `ExpiredToken — Request signature expired
at 2026-09-01T20:16:26Z` (page had been open ~2h11m).
Reloading didn't help because the review UI persists the full
`CorrectionData` — including `instrumental_options[].audio_url` — to
`localStorage` (`lyrics_analyzer_data`) and rehydrates it when the user
has unsaved edits, so the *same* expired URL came back.
The `[SW] Service worker registered` log is a red herring:
`frontend/public/sw.js` has no `fetch` handler.
## Fix (refresh-on-error)
- **Backend:** extract a shared `_build_instrumental_options` helper and
add `GET /api/review/{job_id}/instrumental-urls` returning
freshly-signed stem URLs.
- **Frontend:** on the stem `<audio>` `error` event, re-fetch fresh URLs
via the new endpoint and swap them in. The existing video↔audio sync
effect (keyed on the URL) resumes playback in place. Capped at 3
refreshes per modal open so a genuinely-broken stem (404) can't loop.
No new user-facing strings (the recovery is silent) → no i18n changes.
## Testing
- Backend: 3 new tests for the endpoint (both stems / single stem / 404)
— `TestInstrumentalUrlsRefresh`. Full `test_routes_review.py` +
`test_combined_review_flow.py` + `test_audio_transcoding_service.py` =
111 passed.
- Frontend: 3 new `PreviewVideoSection` tests (swap on error / cap at 3
/ no-op without refresh fn). Full unit suite = 1248 passed.
- CodeRabbit local review: no findings.
@coderabbitai ignore
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
v0.218.0
|
||
|
|
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>
v0.217.1
|
||
|
|
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>v0.217.0 |
||
|
|
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>
v0.216.0
|
||
|
|
50462e1934 |
docs: measure human edits across all 3 axes (text + timing + structure) (#968)
## Summary Docs-only. Refines the `LESSONS-LEARNED.md` reconstruction-measurement note to reflect this session's hardening of `docs/automation-corpus/reconstruct_edits.py`: - Measures **all three edit axes** now — TEXT + **TIMING** (edit_log's blind spot) + **STRUCTURE** (line split/merge), not just text. - `best_effort` mode so vocalization-heavy jobs still measure; `tier=none` correction-disabled jobs are now measurable. - Documents the **net-vs-gross** limitation (an edit coinciding with an AI suggestion nets to 0). Motivated by a 5-job battery where `edit_count`=0 on all 5 yet each had real edits (e.g. Pendulum "The Other Side" = 45 timing edits). Ensures future agents measure edits thoroughly and never fall back to the retired `edit_log`/`edit_count` metric. No code change, no version bump. Co-authored-by: Claude Opus 4.8 <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>v0.215.0 |
||
|
|
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>
v0.214.0
|
||
|
|
7abd0a9617 |
gen: shrink preview video + name the instrumental variant in the preview pill (#965)
Follow-ups to the review-modal audio split (#964), from Andrew's feedback: 1. **Smaller preview video** — the `<video>` height is now capped (`max-h-[45vh]`, aspect ratio preserved, works for portrait too) so the **"🎬 Your karaoke video will use:"** choice is visible without scrolling. Previously the player filled most of the modal and pushed the options off-screen. 2. **Preview pill names the variant** — the "Instrumental" preview pill now reads **"Instrumental (plus backing vocals)"** or **"Instrumental (clean)"** depending on the current final-output selection below, so it's clear which stem you're auditioning (it was ambiguous before — you had to experiment to find out it tracked the radio choice). ## Tests - `PreviewVideoSection` + `ReviewChangesModal` suites updated (dynamic pill label asserted, incl. live update when `auditionInstrumental` swaps the stem). Full frontend suite: **1237/1237 pass**. ESLint clean. ## i18n - New keys `previewVideo.audioInstrumentalPillBacking` / `audioInstrumentalPillClean` translated across all 33 locales; full key parity. Note: local CodeRabbit CLI hit its free-OSS review cap this cycle, so this PR is left open for the GitHub bot to review (no `@coderabbitai ignore`). Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>v0.213.1 |
||
|
|
b48a721d03 |
gen: split preview audio from final-instrumental choice in review modal (#964)
## Problem In the finish/preview modal the single **"Audio:"** segmented control did two unrelated jobs at once — audition playback (incl. "Original with vocals", which is never a valid output) *and* the final-output instrumental selection — with no signal telling the user which instrumental the produced video would actually use. The prose "switch to the clean instrumental" had no obvious target, and the escape-hatch checkbox wording was long/confusing. ## Change Split the two concerns into distinct, clearly-labelled controls. **`PreviewVideoSection`** — now a pure preview component: - Always the simple **`Preview audio: [ Original (with vocals) ] [ Instrumental ]`** toggle (audition only). - Exposes an imperative `auditionInstrumental(id, seekTime?)` so a decision made in the modal also plays that stem. **`ReviewChangesModal`** — owns one unambiguous decision control: ``` 🎬 Your karaoke video will use: (●) Instrumental + backing vocals ✓ recommended (○) Clean instrumental ← only when a clean stem exists (○) Advanced mode (edit backing vocals or upload your own instrumental) ``` - Picking **backing/clean** both *selects* (final output) and *auditions* it. - **Advanced mode** replaces the old wordy escape-hatch checkbox — it opts into the full instrumental screen (CTA flips to "Proceed to Instrumental Review"). - Helper text now uses plain language (no "bleed" jargon): "…if you can hear the lead singer's voice coming through, switch to Clean instrumental above." No backend change — still submits `clean` vs `auto` exactly as before. ## Tests - Rewrote the obsolete choice-pill tests to cover the new radio group (recommended badge, Advanced-mode wording per backing/clean case, clean-radio reports choice + clears review-anyway, hidden when not confident) and the imperative audition handle. - Full frontend suite: **1237/1237 pass**. ESLint clean on changed files. ## i18n All 33 locales at full key parity. New keys (`finalChoiceLabel`, `recommended`, `advancedMode`, `advancedModeClean`) translated; reworded `autoInstrumentalBacking` refreshed; obsolete checkbox keys pruned. Ambiguous "upload your own" phrasing made explicit ("…your own instrumental") after a local CodeRabbit pass flagged 6 mistranslations. @coderabbitai ignore Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>v0.213.0 |
||
|
|
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>v0.212.0 |
||
|
|
b464e40d84 |
Inline clean-instrumental choice via 3-way audio toggle on the finish modal (#962)
## Summary
On the lyrics-review **finish modal**, when the backing instrumental is
confidently auto-selected, reviewers previously had only a heavyweight
escape hatch ("Let me choose the instrumental myself" → the full
instrumental-review screen). The common override — "the backing vocals
sound bad, just give me the clean instrumental" — is now a **single
click**.
The clean instrumental becomes a **third pill in the "Audio:" preview
toggle** so the two instrumentals can be A/B'd and chosen in one place:
- **`PreviewVideoSection`** — when both stems exist and are meaningfully
different (verdict `with_backing` + a clean stem present), the single
"Instrumental" pill splits into **Instrumental + backing vocals** /
**Clean instrumental**. Selecting a variant both auditions and selects
it (last activated wins); the backing-vocals waveform auditions the
with-backing stem. When clean is already the default (or only one stem
exists), the single "Instrumental" pill is kept — nothing to choose.
- **`LyricsAnalyzer`** submits the reviewer's choice (`clean` vs
`auto`). The backend already accepts an explicit `clean` selection at
`POST /api/review/{id}/complete`, so **no backend change**.
- The confident-box note reflects the current choice, and the
escape-hatch checkbox is reworded to the specific, rarely-used action
(keep BV but mute sections / upload custom), with a clean-case variant.
- **i18n:** reworded + new keys across all 33 locales (`translate.py
--target all`; key parity verified).
## Testing
- `PreviewVideoSection.test.tsx` — 3-way toggle: splits pills when
offered, reports choice + swaps stem on clean click, keeps single pill
when only one stem / not offered.
- `ReviewChangesModal.test.tsx` — note reflects the reported choice;
per-case escape-hatch wording.
- Full frontend suite: **98 suites / 1236 tests pass**. Changed source
files typecheck clean.
## Notes
- New completion toasts are kept in English to match the 7 existing
hardcoded toasts in the same submit function (localizing only the new
ones would be inconsistent; localizing all is out of scope).
- **Pending live-verify (Andrew's ear):** an in-review
confident-`with_backing` job — confirm the 3-pill toggle A/Bs cleanly
and that picking "Clean instrumental" ships the clean stem.
@coderabbitai ignore
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
v0.211.0
|
||
|
|
e58334e461 |
Preview modal UX: audio toggle, backing-vocals waveform, cohesive loading & saving flow (#961)
## Summary
Five UX improvements to the lyrics-review **Preview Video** modal (shown
when the reviewer clicks "Preview Video").
1. **Unified loading** — the `generating` and `encoding` states now
share one centred spinner; only the stage message changes ("Preparing
your preview…" → "Encoding preview video…" → slow-encoder hint). No more
janky layout swap.
2. **Audio toggle (Original ↔ auto-selected Instrumental)** — a hidden
stem `<audio>` element (from `instrumental_options`, already in the
review correction-data) is kept in lock-step with the video
(play/pause/seek/rate/drift ≤0.25s). Switchable mid-playback with
position preserved. Title dropped "(With Vocals)" → just "Preview
Video".
3. **Removed low-value text** — deleted "No manual corrections
detected…" and "Total segments: X". The manual-corrections note now only
shows when the reviewer actually edited.
4. **Backing-vocals waveform** (new `BackingVocalsWaveform`) — only when
the auto-selector kept backing vocals (`with_backing`, confident, and
the stem is playable). Thin 35px canvas of the backing stem (from `GET
/api/review/{jobId}/waveform-data`); clicking seeks the video and
switches audio to the instrumental, for quick sanity-checking of the
automatic pick.
5. **"Complete Track" saving flow** — the modal stays in its "Saving…"
state through the slow `completeReview` call, so it no longer flashes
back to the review screen before the "Review Submitted" view.
Also: `getWaveformData` added to the review API client factory; version
`0.209.2 → 0.210.0`.
## i18n
- Keys added
(`previewVideo.audioLabel/audioOriginal/audioInstrumental/backingVocalsWaveformHint`,
`modals.reviewChanges.previewTitle`) and removed (`previewWithVocals`,
`noManualCorrections`, `totalSegments`); all 33 locales synced via
`translate.py`. Keys-only parity passes.
## Testing
- Frontend jest: **1230 passed / 98 suites** (26 in the two touched
modal/preview suites, incl. audio-toggle mute + backing-waveform
gating).
- Manually verified against **real prod jobs** via local dev (proxying
to prod API):
- `ae225662` (clean pick): audio toggle mutes video + plays clean stem
synced to the same position; waveform correctly hidden.
- `370f7b92` (with_backing pick): 35px backing waveform renders;
clicking it seeks the video (102.5s→138.8s) and the instrumental audio
follows in lock-step.
- Local CodeRabbit review run and its 2 minor findings addressed
(playbackRate sync on audio switch; gate waveform on stem availability).
@coderabbitai ignore
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
v0.210.0
|
||
|
|
37b9e6088b |
ci(pypi): recurring storage-cap prune reminder (fix failing PyPI publish) (#960)
## Problem The `Deploy - Publish to PyPI` step on `main` has been failing: ``` HTTP Error 400: Project size too large. Limit for project 'karaoke-gen' total size is 10 GB. ``` This is a recurrence of the known 10 GB PyPI project cap. The project is at **10.71 GB / 479 releases**; each release is a ~62 MiB universal wheel (bundled 33-locale frontend) auto-published on every merge (~3 GB/month), so it refills the cap every few months. **Only the public `pip install` publish step fails** — Cloud Run and the GCE encoding worker (pulls the wheel from GCS) are unaffected. The prior fix (v0.187.5) was wheel-only publishing + a one-time manual deletion, which only bought ~2 months. This makes the cleanup **recurring and durable**. ## Why not just automate deletion in CI? PyPI has **no deletion API** (upload tokens / Trusted Publishing are upload-only, and 2FA is mandatory). Deletion is only possible from a logged-in browser session, which can't be safely/durably stored in CI. So we automate the *decision + reminder* and keep the *deletion* a ~1-minute human step. ## What this adds - **`scripts/prune_pypi_releases.py`** (stdlib-only) — reads the public JSON API and computes a retention plan: **keep last 60 days + newest release per older calendar month + latest overall**. Renders a table / JSON / Markdown report and a **paste-into-browser-console** deletion snippet. Never deletes anything itself. Today's plan: keep 82, delete 397, **10.71 GB → 4.17 GB**. - **`.github/workflows/pypi-prune-reminder.yml`** — monthly cron (+ manual dispatch) that runs the planner and, once the project crosses a 7 GB watermark, opens/updates a single tracking issue with the plan + snippet. No secrets. - **`docs/PYPI-STORAGE-PRUNE.md`** runbook + a `TROUBLESHOOTING.md` entry. - **`tests/unit/test_prune_pypi_releases.py`** — 13 tests covering the policy (recency window, per-month keeper, latest-overall, same-day timestamp ranking, empty/undated releases, sizes, rendering). ## Testing - `pytest tests/unit/test_prune_pypi_releases.py` → 13 passed. - Ran the planner against live PyPI data; generated JS validated with `node --check`. - `black` clean; workflow YAML validated; `should_nag` gate verified. ## Notes - **No version bump** — tooling/CI/docs only, nothing in the wheel changes. Merging therefore **skips** the publish step (tag `v0.209.1` already exists), so this PR does not itself add another fat wheel while we're over the cap. - **To unblock publishing now:** after merge, run the prune (locally via the script or trigger the workflow with `workflow_dispatch`), paste the snippet on the logged-in PyPI releases page, then re-run the publish. The monthly cron keeps it under the cap going forward. - Related: filed [pypi/support#12050](https://github.com/pypi/support/issues/12050) requesting a 50 GB limit as a one-off buffer; the recurring prune is the durable fix. @coderabbitai ignore --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>v0.209.2 |
||
|
|
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> |