Compare commits

...
6 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 4.8 0e3b2f6e08 fix(jobs): don't hide the caller's own jobs from exclude_test filter (canary regression) (#1020)
## Regression

Follow-up to #1019. That PR made `is_test_email()` match
`e2e-test-runner@nomadkaraoke.com` so its jobs are hidden from admin
dashboards. But the CI **post-deploy happy-path canary impersonates that
admin account**, and the guided-flow "Recent Jobs" panel lists jobs
through `list_jobs` with the default `exclude_test=true`. Because the
runner is an admin, the filter removed **its own just-created job** from
its own view — so the canary failed at STEP 5 (the new job card never
appears in Recent Jobs). Confirmed: the pre-#1019 canary passed this
step; the first canary carrying #1019 failed there on both attempts,
right after `Job created successfully!`.

Real users are unaffected — non-admins are already scoped to their own
`user_email` and never reach this filter. A normal admin (Andrew) is
unaffected too — their own email isn't a test email. The only impact was
the e2e-test-runner seeing an empty own-jobs list.

## Fix

`exclude_test` now never hides the **caller's own** jobs, in both
summary and full modes of `list_jobs`:
- e2e-test-runner sees the jobs it creates → canary STEP 5 passes.
- A real admin still has all test-account jobs (testmail +
e2e-test-runner) filtered from their dashboard.

## Testing

New `backend/tests/test_list_jobs_exclude_test_own.py` drives
`list_jobs` directly:
- test-account admin (e2e-test-runner) sees its own job, but not another
test account's;
- normal admin still has all test jobs hidden.
Both pass.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-17 14:54:28 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 bb743b49e4 Review fast full load: remove IAM signBlob from the review hot path (v0.229.0) (#1018)
## Why

Root-cause fix for the **2026-09-17 signing-hang incident**. `GET
/api/review/{id}/correction-data` signed 2-3 GCS URLs per load via the
IAM **signBlob** API — a network round-trip that made review loads slow
and, when it stalled (~120s), exhausted the request thread pool and took
gen down (`Service Unavailable`, "Loading lyrics data…" hang).

`v0.228.1` bounded/timed signing and made audio + waveform
**best-effort** (the degraded fail-soft path). Andrew's ask was to fix
the root cause so the review page **always loads fast with all features
— audio + waveform — present on first paint**, not the degraded path.

## What (Option B — same-origin byte proxy)

Removes IAM signBlob from the review hot path **entirely** —
`correction-data` now performs **zero** signing calls.

**Backend** (`backend/api/routes/review.py`)
- New `GET /{job_id}/instrumental-audio/{option_id}`: streams the
transcoded OGG bytes with HTTP **Range (206)** support (so `<audio>` can
seek), authenticated by `require_review_auth` (token in the query string
for raw-media-src use, exactly like `/audio/vocals`). The stem GCS path
is resolved **server-side** from the option id — clients can't request
arbitrary blobs. Bounded **LRU byte cache** (prod-safe, unlike the
unbounded dev cache).
- `_build_instrumental_options`: returns **relative same-origin proxy
paths** as `audio_url`, no signing. Local-dev byte proxy path unchanged.
- Dropped the `backing_vocals_waveform_url` signing — it was a **dead
field** (0 consumers repo-wide; the waveform is drawn from the
Bearer-auth JSON `/waveform-data` endpoint).
- Also removed a now-unused `storage` param + refreshed stale
docstrings.

**Frontend** (`frontend/lib/api.ts`)
- Resolves each option's relative proxy path into an absolute,
`?token=`-authenticated `<audio>` src in the API layer
(`getCorrectionData` + `refreshInstrumentalUrls`) — **zero component
changes**, mirrors the proven `getVocalsAudioUrl` pattern. Also fixes
the CORS `Origin: null` issue for good, and the proxy URLs never expire
(the whole signed-URL expiry/refresh dance is now moot).

The `v0.228.1` signing timeout + bounded admission stays as
**defense-in-depth** for the remaining, non-review-hot-path signing
(e.g. preview-video).

## Tests
- Backend: new endpoint (bytes / Range 206 / auth / 404s), plus
**positive assertions that the hot path signs nothing**
(`generate_signed_url` / `get_review_audio_url_async` not called).
- Frontend: URL-resolution unit tests (relative→absolute+token; dev
absolute + null left untouched; refresh path).
- Prod E2E: `frontend/e2e/production/review-fast-load.spec.ts` —
env-gated contract (proxy `audio_url`s present, endpoint serves
`audio/ogg` + Range, loads fast).
- Full suites green: **backend 4469 passed**, **frontend jest 1286
passed**.

## Deploy note
Minor, self-healing skew: during the backend↔frontend deploy gap, only
the **instrumental preview player** for a job opened in that window may
not play (lyrics + everything else fine); a reload after both deploy
fixes it. Far less severe than the signBlob-stall outage this removes.

Plan + rationale:
`docs/archive/2026-09-17-review-fast-full-load-plan.md`. Runbook updated
in `docs/TROUBLESHOOTING.md`.

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

## Summary by CodeRabbit

- **New Features**
- Review pages now load instrumental audio through same-origin,
authenticated audio URLs.
- Audio playback supports streaming and range requests for faster, more
reliable access.
- Instrumental audio options automatically include usable
token-authenticated URLs.

- **Bug Fixes**
- Review data no longer depends on URL-signing round trips, preventing
loading delays caused by signing timeouts.
- Removed the unused backing-vocals waveform URL from review responses.

- **Documentation**
- Updated API and troubleshooting documentation for the new audio
streaming behavior.

- **Chores**
  - Version updated to 0.229.0.

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-17 18:11:56 +00:00
Andrew Beveridge ☄️andClaude Opus 4.8 fb9d86d17f fix(e2e): hide test-runner jobs from admin, stop stranding + name drift (#1019)
Follow-up to the investigation of why E2E "piri/dog" jobs started
appearing in the live admin dashboard. Three related fixes (the
transcription-cache cost bug from the same investigation ships
separately in #1017).

## #2 — Hide `e2e-test-runner` jobs from the admin "My Jobs" view
`list_jobs`' `exclude_test` filter uses `is_test_email()`, which only
matched `@inbox.testmail.app`. When the CI post-deploy canary + daily
E2E workflows switched to impersonating the **persistent**
`e2e-test-runner@nomadkaraoke.com` account, their jobs stopped being
filtered and leaked into the admin dashboard (previously every E2E job
ran under an ephemeral testmail user and was hidden).

Fix: add a `TEST_EMAIL_ADDRESSES` allowlist in
`backend/utils/test_data.py` so this internal test account is treated as
test data everywhere `is_test_email()` is used.

## #3 — Safety-net teardown for the happy-path spec
`happy-path-real-user.spec.ts` only deleted its job at **Step 12**,
which runs solely on a fully successful pass. A run that failed/timed
out earlier (e.g. stuck at `awaiting_review`) stranded its job in
production forever. Added a `test.afterEach` that deletes the tracked
job on every attempt (including retries), regardless of where the test
stopped. Idempotent with Step 12.

## #5 — Deterministic E2E song identity (`piri` vs `piri & tommy`)
The guided-flow **AI match-judge** nondeterministically rewrote the
typed artist to its canonical form (`piri` → `piri & tommy`) depending
on the audio-confidence tier and LLM output — a legitimate product
feature, but it produced two differently-named jobs across runs. The
test now stubs `POST /api/catalog/match-judge` to a no-op verdict
echoing the typed values, pinning the job to `piri - dog`. **Product
behavior is unchanged** — only the test is pinned.

## Testing
- New `backend/tests/test_test_data_utils.py` — `is_test_email` /
`is_internal_email` classification incl. `e2e-test-runner`
(case-insensitive), plus real/team accounts.
- Extended the existing `exclude_test` summary-dict test to include the
runner account.
- Frontend spec typechecks (`tsc`) and lints (`eslint`) clean.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-17 13:57:57 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 11bf84f296 fix(auth): hard-navigate for hash-carrying post-login redirects (#1016)
## Summary
Follow-up to #1015: the verify page's client-side `router.push` renders
a 404 for hash-carrying redirect paths (`/app/jobs#/<id>/review`).
Reproduced in prod with a minted one-click link; a full
`window.location.assign` navigation loads the review page correctly.

## Testing
- Reproduced + verified path behavior in prod browser session
(fresh-load of the same URL works; push 404s).
- Backend unaffected; no new strings.

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

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

## Summary by CodeRabbit

- **Bug Fixes**
- Magic-link verification now correctly redirects to destinations
containing URL fragments.
- Standard destinations continue using in-app navigation for a smoother
transition.

- **Chores**
  - Updated the application version to 0.228.3.

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-17 16:35:11 +00:00
Andrew Beveridge ☄️andClaude Opus 4.8 45504e92b8 admin: mint one-click login links with job-review redirect (#1015)
## Summary
Enables one-click authed review links for the KaraokeHunt outreach
emails: an admin-minted magic-link token (up to 7-day expiry, nothing
sent by the API) whose `purpose: job_review:<job_id>` makes the verify
endpoint return a redirect straight to that job's lyrics review page.

## Testing
- backend/tests/test_admin_login_link.py — mint endpoint +
purpose→redirect mapping (incl. malformed job-id rejection)
- Full non-emulator backend suite: 4468 passed.

🤖 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 generate one-click login links for users with
configurable expiration times and optional purposes.
- Login links can direct users to the requests board or a specific job’s
lyrics review page.
- Generated links include the destination URL, expiration details, and
purpose for convenient manual sharing.

- **Bug Fixes**
- Magic-link verification now correctly honors supported redirect
destinations while rejecting malformed or unsupported values.
- Login-link expiration values are validated between 1 and 168 hours,
preventing invalid requests from causing server errors.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-17 15:46:10 +00:00
Andrew Beveridge ☄️andClaude Opus 4.8 09150c7603 docs: session record — Firestore job-doc 1MB self-heal (#1014)
Session record for the review-submit 500 fix (PR #1013, v0.228.0).
Docs-only.

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-17 11:08:41 -04:00
23 changed files with 1011 additions and 146 deletions

No files matched your search

+36 -1
View File
@@ -14,7 +14,7 @@ from datetime import datetime, timedelta, timezone
from typing import Tuple, List, Literal, Optional, Any, Dict
from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import BaseModel
from pydantic import BaseModel, Field
from backend.api.dependencies import require_admin
from backend.i18n import t, get_locale_from_request
@@ -2173,6 +2173,41 @@ async def send_job_completion_email(
)
class MintLoginLinkRequest(BaseModel):
"""Request to mint a one-click login link for a user."""
expiry_hours: int = Field(168, ge=1, le=168)
# e.g. "job_review:<job_id>" — verify maps known purposes to a redirect
purpose: Optional[str] = None
@router.post("/users/{email}/login-link")
async def mint_user_login_link(
email: str,
request: MintLoginLinkRequest,
auth_data: AuthResult = Depends(require_admin),
user_service: UserService = Depends(get_user_service),
):
"""
Mint a one-click login link for a user (admin only). Sends NOTHING — returns
the URL for embedding in manually-reviewed outreach emails. The link logs the
user in and, when purpose is "job_review:<job_id>", lands them directly on
that job's lyrics review page. Expiry up to 168h (7 days).
"""
import os as _os
token = user_service.create_admin_login_token(
email=email.strip().lower(),
expiry_hours=request.expiry_hours,
purpose=request.purpose,
)
frontend_url = _os.getenv("FRONTEND_URL", "https://gen.nomadkaraoke.com")
return {
"email": token.email,
"url": f"{frontend_url}/auth/verify?token={token.token}",
"expires_at": token.expires_at.isoformat(),
"purpose": request.purpose,
}
# =============================================================================
# User Impersonation
# =============================================================================
+19 -4
View File
@@ -755,9 +755,18 @@ async def list_jobs(
limit=fetch_limit,
)
# Exclude test user jobs (Python-side, same as full mode)
# Exclude test user jobs (Python-side, same as full mode).
# Never hide the caller's OWN jobs: an admin that is itself a test
# account (e.g. the e2e-test-runner the CI canary impersonates) must
# still see the jobs it just created in its own "My Jobs" list —
# otherwise the happy-path E2E breaks right after job creation.
if exclude_test and auth_result.is_admin:
jobs_dicts = [j for j in jobs_dicts if not is_test_email(j.get('user_email') or "")]
own_email = (auth_result.user_email or "").lower()
jobs_dicts = [
j for j in jobs_dicts
if not is_test_email(j.get('user_email') or "")
or (own_email and (j.get('user_email') or "").lower() == own_email)
]
# Apply search filter if provided
if search:
@@ -782,9 +791,15 @@ async def list_jobs(
limit=limit
)
# Filter out test user jobs if exclude_test is True (admin only)
# Filter out test user jobs if exclude_test is True (admin only).
# Never hide the caller's OWN jobs (see summary-mode note above).
if exclude_test and auth_result.is_admin:
jobs = [j for j in jobs if not is_test_email(j.user_email or "")]
own_email = (auth_result.user_email or "").lower()
jobs = [
j for j in jobs
if not is_test_email(j.user_email or "")
or (own_email and (j.user_email or "").lower() == own_email)
]
logger.debug(f"Listed {len(jobs)} jobs for user={auth_result.user_email}, admin={auth_result.is_admin}")
return jobs
+136 -68
View File
@@ -18,11 +18,14 @@ import hashlib
import json
import os
import tempfile
import threading
from collections import OrderedDict
from pathlib import Path
from typing import Dict, Any, List, Literal, Optional, Set, Tuple
from fastapi import APIRouter, HTTPException, Request, Depends, Form, File, UploadFile
from fastapi.responses import RedirectResponse, Response
from google.cloud.exceptions import NotFound
from google.cloud.firestore_v1.field_path import FieldPath
from backend.models.job import JobStatus
@@ -410,47 +413,49 @@ def _dev_audio_url(job_id: str, gcs_path: Optional[str], base_url: str = "") ->
return f"{base_url.rstrip('/')}/api/review/{job_id}/dev-audio?path={quote(gcs_path, safe='')}"
async def _build_instrumental_options(job, storage, request) -> List[Dict[str, Any]]:
"""Build the ``instrumental_options`` list (transcoded, freshly-signed OGG URLs).
# Maps the public instrumental option id to the stem key in job.file_urls["stems"].
# Used both when building instrumental_options and when the byte-proxy endpoint
# resolves an option id back to its GCS stem path (server-side, never client-supplied).
_INSTRUMENTAL_OPTION_STEMS = {
"clean": "instrumental_clean",
"with_backing": "instrumental_with_backing",
}
Signed GCS URLs expire (see ``AudioTranscodingService`` — 120 min), so the
review payload's baked-in URLs go stale during a long review session. This
helper is shared by the combined-review corrections endpoint (initial load)
and ``GET /{job_id}/instrumental-urls`` (frontend refresh-on-expiry), so both
return the identical shape with URLs signed at call time.
def _instrumental_proxy_path(job_id: str, option_id: str) -> str:
"""Relative same-origin proxy path for an instrumental option's audio bytes.
Returned as ``instrumental_options[*].audio_url``. The frontend turns this into an
absolute, token-authenticated URL (``API_BASE_URL`` + ``?token=``) before using it
as an ``<audio>`` src — see ``resolveInstrumentalAudioUrls()`` in ``frontend/lib/api.ts``.
Kept RELATIVE because the backend has no trustworthy public base URL behind Cloudflare
(``request.base_url`` reports the wrong scheme/host), and a raw absolute-to-the-wrong-host
src would break.
"""
from backend.services.audio_transcoding_service import AudioTranscodingService
return f"/api/review/{job_id}/instrumental-audio/{option_id}"
transcoding = AudioTranscodingService(storage_service=storage)
async def _build_instrumental_options(job, request) -> List[Dict[str, Any]]:
"""Build the ``instrumental_options`` list (id/label + same-origin audio proxy URL).
Root-cause fix (2026-09-17, Option B — see docs/archive/2026-09-17-review-fast-full-load-plan.md):
the review hot path no longer signs GCS URLs here. Signing went through the IAM
signBlob API over the network (~120 s worst-case), which made review loads slow and,
when it stalled, took the whole service down. Instead each option's ``audio_url`` is a
relative path to the ``GET /{job_id}/instrumental-audio/{option_id}`` byte proxy — no
signing, cannot stall, never expires. Shared by the corrections endpoint (initial
load) and ``GET /{job_id}/instrumental-urls`` (kept for backwards compatibility).
"""
stems = job.file_urls.get("stems", {})
clean_url = stems.get("instrumental_clean")
backing_url = stems.get("instrumental_with_backing")
signed_urls: Dict[str, Optional[str]] = {}
if _dev_audio_proxy_enabled():
_base = str(request.base_url)
if clean_url:
signed_urls["clean"] = _dev_audio_url(job.job_id, clean_url, _base)
if backing_url:
signed_urls["with_backing"] = _dev_audio_url(job.job_id, backing_url, _base)
else:
url_tasks = {}
if clean_url:
url_tasks["clean"] = transcoding.get_review_audio_url_async(clean_url, expiration_minutes=120)
if backing_url:
url_tasks["with_backing"] = transcoding.get_review_audio_url_async(backing_url, expiration_minutes=120)
if url_tasks:
# Best-effort: signing goes through IAM signBlob over the network and is
# now bounded to SIGNED_URL_TIMEOUT_S (see storage_service). A stall must
# NOT blow up the whole review load — on failure we return the option with
# a null audio_url; the frontend re-fetches via GET /{job_id}/instrumental-urls.
results = await asyncio.gather(*url_tasks.values(), return_exceptions=True)
for key, res in zip(url_tasks.keys(), results):
if isinstance(res, Exception):
logger.warning(f"Signing review audio URL failed ({key}): {res}")
signed_urls[key] = None
else:
signed_urls[key] = res
def _audio_url(option_id: str, source_gcs_path: str) -> Optional[str]:
# Local dev (no URL-signing creds) keeps its existing byte proxy, which takes the
# GCS path directly; prod/default returns the option-scoped proxy path.
if _dev_audio_proxy_enabled():
return _dev_audio_url(job.job_id, source_gcs_path, str(request.base_url))
return _instrumental_proxy_path(job.job_id, option_id)
instrumental_options: List[Dict[str, Any]] = []
if clean_url:
@@ -458,14 +463,14 @@ async def _build_instrumental_options(job, storage, request) -> List[Dict[str, A
"id": "clean",
"label": "Clean Instrumental",
"description": "No backing vocals - just the music",
"audio_url": signed_urls.get("clean"),
"audio_url": _audio_url("clean", clean_url),
})
if backing_url:
instrumental_options.append({
"id": "with_backing",
"label": "Instrumental with Backing Vocals",
"description": "Includes harmonies and background vocals",
"audio_url": signed_urls.get("with_backing"),
"audio_url": _audio_url("with_backing", backing_url),
})
return instrumental_options
@@ -693,10 +698,9 @@ async def get_correction_data(
}
# === Add instrumental data for combined review ===
# Transcoded signed OGG URLs (freshly signed here; the frontend re-fetches
# them via GET /{job_id}/instrumental-urls when they expire mid-review).
# Same-origin audio proxy paths (no signing; see _build_instrumental_options).
corrections_data['instrumental_options'] = await _build_instrumental_options(
job, storage, request
job, request
)
# Get backing vocals analysis from state_data (populated by screens_worker)
@@ -711,24 +715,12 @@ async def get_correction_data(
from backend.services.auto_approval.instrumental import auto_approval_summary
corrections_data['auto_approval'] = auto_approval_summary(job, _get_settings())
# Get waveform URL if available. Best-effort + off the event loop: signing is
# a network round-trip (IAM signBlob, bounded to SIGNED_URL_TIMEOUT_S), so run
# it in a thread and never let a stall/timeout fail the review load — the
# waveform is a nice-to-have, the lyrics are not.
analysis_files = job.file_urls.get('analysis', {})
waveform_url = analysis_files.get('backing_vocals_waveform')
if waveform_url:
try:
if _dev_audio_proxy_enabled():
corrections_data['backing_vocals_waveform_url'] = _dev_audio_url(
job_id, waveform_url, str(request.base_url)
)
else:
corrections_data['backing_vocals_waveform_url'] = await asyncio.to_thread(
storage.generate_signed_url, waveform_url, expiration_minutes=120
)
except Exception as e:
logger.warning(f"Job {job_id}: waveform URL signing failed, omitting: {e}")
# NOTE: we intentionally do NOT sign/emit a ``backing_vocals_waveform_url`` here.
# The frontend renders the backing-vocals waveform from the Bearer-authenticated
# JSON endpoint ``GET /{job_id}/waveform-data`` (amplitudes drawn on a canvas), and
# never consumed this field. Signing it was a pure IAM-signBlob round-trip on the
# review hot path with no consumer — removed as part of the 2026-09-17 fast-load
# re-architecture so ``correction-data`` performs zero signing.
# Transition to IN_REVIEW if not already (never in replay — read-only)
if not replay and job.status == JobStatus.AWAITING_REVIEW:
@@ -878,6 +870,33 @@ async def _stream_audio(job_id: str, stem: Literal["input"] | Literal["vocals"]
_DEV_AUDIO_CACHE: Dict[str, Tuple[bytes, str]] = {}
# BOUNDED cache of transcoded review-audio bytes for the PROD byte proxy (Option B).
# Serving the ~3 MB OGG through the API means each play/seek would otherwise re-download
# the object from GCS; cache a small number of recently-served objects so Range seeks and
# repeat plays are cheap. Unlike _DEV_AUDIO_CACHE this is size-capped (LRU) so a busy prod
# instance can't grow memory without limit — worst case ~_REVIEW_AUDIO_CACHE_MAX × object
# size. Keyed by GCS path (the transcoded-OGG source), guarded by a lock for thread safety.
_REVIEW_AUDIO_CACHE_MAX = int(os.getenv("REVIEW_AUDIO_CACHE_MAX", "16"))
_review_audio_cache: "OrderedDict[str, Tuple[bytes, str]]" = OrderedDict()
_review_audio_cache_lock = threading.Lock()
def _review_audio_cache_get(path: str) -> Optional[Tuple[bytes, str]]:
with _review_audio_cache_lock:
item = _review_audio_cache.get(path)
if item is not None:
_review_audio_cache.move_to_end(path) # mark most-recently-used
return item
def _review_audio_cache_put(path: str, value: Tuple[bytes, str]) -> None:
with _review_audio_cache_lock:
_review_audio_cache[path] = value
_review_audio_cache.move_to_end(path)
while len(_review_audio_cache) > _REVIEW_AUDIO_CACHE_MAX:
_review_audio_cache.popitem(last=False) # evict least-recently-used
def _ranged_response(request: Request, data: bytes, content_type: str) -> Response:
"""Serve ``data`` honoring an HTTP Range header (206) so <audio> can seek."""
total = len(data)
@@ -935,6 +954,58 @@ async def get_dev_audio(job_id: str, path: str, request: Request):
raise HTTPException(status_code=500, detail="dev-audio proxy error")
@router.get("/{job_id}/instrumental-audio/{option_id}")
async def get_instrumental_audio(
job_id: str,
option_id: str,
request: Request,
auth_info: Tuple[str, str] = Depends(require_review_auth),
):
"""Stream a review instrumental stem's transcoded OGG bytes (same-origin proxy).
Option B of the fast-review-load re-architecture (2026-09-17): replaces the per-load
IAM signBlob round-trip with a same-origin byte proxy, so the review page never depends
on URL signing to play audio (signing could stall ~120 s and take the service down).
Serves the ~3 MB transcoded OGG with HTTP Range support so ``<audio>`` can seek,
authenticated by ``require_review_auth`` (the token rides in the query string for
raw-media-src use — the same mechanism as ``/audio/vocals``). The stem GCS path is
resolved SERVER-SIDE from ``option_id``, so a client can only ever fetch this job's own
instrumental stems, never an arbitrary blob.
"""
stem_key = _INSTRUMENTAL_OPTION_STEMS.get(option_id)
if not stem_key:
raise HTTPException(status_code=404, detail=t("en", "review.audioNotFound"))
job = JobManager().get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
stems = job.file_urls.get("stems", {}) if job.file_urls else {}
source_gcs_path = stems.get(stem_key)
if not source_gcs_path:
raise HTTPException(status_code=404, detail=t("en", "review.audioNotFound"))
try:
cached = _review_audio_cache_get(source_gcs_path)
if cached is None:
from backend.services.audio_transcoding_service import AudioTranscodingService
transcoding = AudioTranscodingService(storage_service=StorageService())
cached = await transcoding.get_review_audio_bytes_async(source_gcs_path)
_review_audio_cache_put(source_gcs_path, cached)
data, content_type = cached
logger.info(f"Job {job_id}: Proxying {len(data)}B instrumental audio ({option_id})")
return _ranged_response(request, data, content_type)
except NotFound:
# The stem is referenced in file_urls but its GCS object (and any transcoded
# cache) is gone — a genuine 404, not a server error.
logger.warning(f"Job {job_id}: instrumental audio object missing for {option_id}")
raise HTTPException(status_code=404, detail=t("en", "review.audioNotFound"))
except Exception as e:
logger.error(f"Job {job_id}: error proxying instrumental audio {option_id}: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=t("en", "review.audioServeError", error=str(e)))
@router.post("/{job_id}/complete")
async def complete_review(
job_id: str,
@@ -1900,22 +1971,19 @@ async def get_instrumental_urls(
request: Request,
auth_info: Tuple[str, str] = Depends(require_review_auth)
):
"""Return freshly-signed instrumental stem URLs for the combined review.
"""Return instrumental stem options (same-origin audio proxy paths) for the review.
The signed URLs baked into the initial review payload expire after 120 min,
and a long review session (or a page reload that rehydrates cached correction
data from localStorage) can outlive them — the preview modal's instrumental
audio then fails to load (``NS_ERROR_DOM_NETWORK_ERR``). The frontend calls
this on an audio load error to swap in a fresh URL and resume playback.
Since the 2026-09-17 fast-load re-architecture these are non-expiring proxy paths, so
a refresh is no longer strictly needed — but the preview modal still calls this on an
audio load error (e.g. a transient network blip) to swap in a fresh URL, and it's a
cheap, backwards-compatible way to do so. Returns the same shape as correction-data's
``instrumental_options``.
"""
job_manager = JobManager()
storage = StorageService()
job = job_manager.get_job(job_id)
job = JobManager().get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
instrumental_options = await _build_instrumental_options(job, storage, request)
instrumental_options = await _build_instrumental_options(job, request)
return {"instrumental_options": instrumental_options}
+18 -1
View File
@@ -369,6 +369,23 @@ async def send_magic_link(
)
def _magic_link_redirect_path(purpose) -> "Optional[str]":
"""Map a magic-link purpose to a post-login redirect path.
"requests_board" -> the voting board; "job_review:<job_id>" -> straight to
that job's lyrics review (used by outreach one-click links). Unknown or
malformed purposes fall through to None (frontend default: /app).
"""
import re as _re
if purpose == "requests_board":
return "/requests"
if isinstance(purpose, str) and purpose.startswith("job_review:"):
job_id = purpose.split(":", 1)[1]
if _re.fullmatch(r"[A-Za-z0-9_-]{4,64}", job_id):
return f"/app/jobs#/{job_id}/review"
return None
@router.get("/auth/verify", response_model=VerifyMagicLinkResponse)
async def verify_magic_link(
token: str,
@@ -519,7 +536,7 @@ async def verify_magic_link(
tenant_subdomain=tenant_subdomain,
credits_granted=credits_granted,
credit_status=credit_status,
redirect_path="/requests" if is_board_signin else None,
redirect_path=_magic_link_redirect_path(magic_link_purpose),
)
+4
View File
@@ -285,6 +285,7 @@ class UserService:
self,
email: str,
expiry_hours: int = 24,
purpose: Optional[str] = None,
) -> MagicLinkToken:
"""
Create an admin login token for email-embedded authentication links.
@@ -295,6 +296,8 @@ class UserService:
Args:
email: Admin's email address to authenticate as
expiry_hours: Hours until token expires (default: 24, max: 168)
purpose: Optional purpose tag (e.g. "job_review:<job_id>") — the
verify endpoint maps known purposes to a post-login redirect
Returns:
MagicLinkToken object containing the token
@@ -318,6 +321,7 @@ class UserService:
token=token,
email=email,
expires_at=datetime.utcnow() + timedelta(hours=expiry_hours),
purpose=purpose,
)
# Save to Firestore (same collection as magic links for unified verification)
+67
View File
@@ -0,0 +1,67 @@
"""Tests for the admin mint-login-link endpoint and purpose->redirect mapping."""
from datetime import datetime, timedelta
from unittest.mock import Mock, patch
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from backend.api.routes.admin import router
from backend.api.dependencies import require_admin
from backend.api.routes.users import _magic_link_redirect_path
from backend.services.user_service import get_user_service
app = FastAPI()
app.include_router(router, prefix="/api")
def _mock_admin():
from backend.api.dependencies import AuthResult, UserType
return AuthResult(is_valid=True, user_type=UserType.ADMIN, remaining_uses=999,
message="ok", user_email="admin@example.com", is_admin=True)
app.dependency_overrides[require_admin] = _mock_admin
@pytest.fixture
def client():
mock_us = Mock()
tok = Mock()
tok.email = "user@example.com"
tok.token = "tok123"
tok.expires_at = datetime.utcnow() + timedelta(hours=168)
mock_us.create_admin_login_token.return_value = tok
app.dependency_overrides[get_user_service] = lambda: mock_us
yield TestClient(app), mock_us
app.dependency_overrides.pop(get_user_service, None)
class TestMintLoginLink:
def test_mints_link_with_purpose(self, client):
c, mock_us = client
resp = c.post("/api/admin/users/User@Example.com/login-link",
json={"expiry_hours": 100, "purpose": "job_review:abc12345"})
assert resp.status_code == 200
data = resp.json()
assert "auth/verify?token=tok123" in data["url"]
assert data["purpose"] == "job_review:abc12345"
mock_us.create_admin_login_token.assert_called_once_with(
email="user@example.com", expiry_hours=100, purpose="job_review:abc12345")
class TestMagicLinkRedirectPath:
def test_board(self):
assert _magic_link_redirect_path("requests_board") == "/requests"
def test_job_review(self):
assert _magic_link_redirect_path("job_review:abc12345") == "/app/jobs#/abc12345/review"
def test_malformed_job_id_rejected(self):
assert _magic_link_redirect_path("job_review:../evil") is None
assert _magic_link_redirect_path("job_review:") is None
def test_none_and_unknown(self):
assert _magic_link_redirect_path(None) is None
assert _magic_link_redirect_path("something_else") is None
+17 -14
View File
@@ -148,19 +148,19 @@ class TestGetCorrectionDataReturnsUpdatedCorrections:
# Verify the returned data is the original
assert result["corrected_segments"][0]["text"] == "Hello world"
def test_signing_stall_returns_200_and_omits_waveform_url(
def test_returns_proxy_audio_urls_and_omits_waveform_without_signing(
self, mock_job, original_corrections
):
"""A stalled IAM signBlob must not fail the review load (incident 2026-09-17).
When signing raises SignedUrlTimeout, get_correction_data must still return
the lyrics payload with HTTP 200, omit ``backing_vocals_waveform_url``, and
return instrumental options with null audio_url (the frontend re-fetches).
"""Root-cause fix (2026-09-17, Option B): the review hot path performs NO URL
signing. get_correction_data returns 200 with the lyrics payload, same-origin
proxy paths for the instrumental options, and no ``backing_vocals_waveform_url``
(the frontend renders the waveform from the JSON /waveform-data endpoint, and
never consumed this field). The IAM signBlob round-trip that stalled and took gen
down on 2026-09-17 is gone entirely.
"""
from backend.api.routes.review import get_correction_data
from backend.services.storage_service import SignedUrlTimeout
# Job has both a waveform and instrumental stems, so all signing paths run.
# Job has both a waveform and instrumental stems, so every former signing path runs.
mock_job.file_urls["analysis"] = {
"backing_vocals_waveform": "jobs/test-job-123/analysis/backing_vocals_waveform.png"
}
@@ -179,21 +179,24 @@ class TestGetCorrectionDataReturnsUpdatedCorrections:
storage = MockStorageService.return_value
storage.file_exists.side_effect = lambda path: "corrections_updated" not in path
storage.download_json.return_value = original_corrections.copy()
# Every sign stalls — the whole point of the incident.
storage.generate_signed_url.side_effect = SignedUrlTimeout("stalled")
import asyncio
result = asyncio.run(
get_correction_data("test-job-123", ("user@test.com", "job_owner"))
)
# Endpoint succeeded with the lyrics payload despite the signing stall.
# Endpoint succeeded with the lyrics payload.
assert result["corrected_segments"][0]["text"] == "Hello world"
# Waveform URL omitted rather than 500-ing the load.
# Waveform URL is not emitted at all (dead field, no consumer).
assert "backing_vocals_waveform_url" not in result
# Instrumental options present but with null audio_url (client retries).
# Instrumental options carry same-origin proxy paths (no signing, never expire).
opts = {o["id"]: o["audio_url"] for o in result["instrumental_options"]}
assert opts == {"clean": None, "with_backing": None}
assert opts == {
"clean": "/api/review/test-job-123/instrumental-audio/clean",
"with_backing": "/api/review/test-job-123/instrumental-audio/with_backing",
}
# The critical assertion: the hot path signed nothing.
storage.generate_signed_url.assert_not_called()
def test_checks_direct_gcs_path_when_not_in_file_urls(
self, mock_job, updated_corrections
@@ -0,0 +1,67 @@
"""
Regression tests for list_jobs' exclude_test filter and the caller's own jobs.
An admin account that is *itself* a test account (the e2e-test-runner the CI
canary impersonates) must still see the jobs it just created in its own
"My Jobs" list. The exclude_test filter hides test-account jobs from admin
dashboards, but it must never hide the CALLER's own jobs — otherwise the
happy-path E2E breaks immediately after creating its job (STEP 5: the new job
card never appears in Recent Jobs).
"""
from unittest.mock import MagicMock, patch
import pytest
from backend.api.routes.jobs import list_jobs
from backend.services.auth_service import AuthResult, UserType
E2E_RUNNER = "e2e-test-runner@nomadkaraoke.com"
JOBS = [
{"job_id": "own1", "user_email": E2E_RUNNER}, # caller's own (test acct)
{"job_id": "othertest", "user_email": "x@inbox.testmail.app"}, # other test acct
{"job_id": "real", "user_email": "real@example.com"}, # real user
]
def _admin(email: str) -> AuthResult:
return AuthResult(
is_valid=True,
user_type=UserType.ADMIN,
remaining_uses=0,
message="",
user_email=email,
is_admin=True,
tenant_id="",
)
async def _call_summary(auth: AuthResult):
request = MagicMock()
with patch("backend.api.routes.jobs.get_locale_from_request", return_value="en"), \
patch("backend.api.routes.jobs.get_tenant_from_request", return_value=""), \
patch("backend.api.routes.jobs.job_manager") as mock_jm:
# Return a fresh copy each call so pruning doesn't mutate shared state.
mock_jm.list_jobs_summary.return_value = [dict(j) for j in JOBS]
return await list_jobs(request, fields="summary", auth_result=auth)
@pytest.mark.asyncio
async def test_e2e_runner_sees_its_own_jobs():
"""The e2e-test-runner admin must still see its own test-account jobs."""
result = await _call_summary(_admin(E2E_RUNNER))
ids = {j["job_id"] for j in result}
assert "own1" in ids # caller's own job kept
assert "real" in ids # real job kept
assert "othertest" not in ids # OTHER test-account job still hidden
@pytest.mark.asyncio
async def test_regular_admin_still_hides_all_test_jobs():
"""A normal admin (not a test account) still has all test jobs filtered out."""
result = await _call_summary(_admin("andrew@nomadkaraoke.com"))
ids = {j["job_id"] for j in result}
assert "real" in ids
assert "own1" not in ids # e2e-test-runner jobs hidden from real admin
assert "othertest" not in ids # testmail jobs hidden
+3
View File
@@ -770,6 +770,9 @@ class TestSummaryEndpoint:
{'job_id': '1', 'user_email': 'real@example.com'},
{'job_id': '2', 'user_email': 'test@inbox.testmail.app'},
{'job_id': '3', 'user_email': None},
# The persistent account impersonated by the CI canary + daily E2E
# runs. Its jobs must be filtered out of the admin dashboard too.
{'job_id': '4', 'user_email': 'e2e-test-runner@nomadkaraoke.com'},
]
filtered = [j for j in job_dicts if not is_test_email(j.get('user_email') or "")]
+133 -38
View File
@@ -314,12 +314,12 @@ class TestAddLyricsRejectionHandling:
class TestInstrumentalUrlsRefresh:
"""GET /{job_id}/instrumental-urls re-signs the stem URLs on demand.
"""GET /{job_id}/instrumental-urls returns same-origin audio proxy paths.
The signed URLs baked into the initial review payload expire after 120 min;
a long review session (or a reload that rehydrates cached correction data)
outlives them and the preview modal's overlaid audio fails to load. This
endpoint hands the frontend a freshly-signed batch to swap in.
Since the 2026-09-17 fast-load re-architecture (Option B) the review hot path no
longer signs GCS URLs. Each option's ``audio_url`` is a RELATIVE proxy path to
``/{job_id}/instrumental-audio/{option_id}`` (served as bytes, no signing, never
expires). The frontend turns it into an absolute token URL before use.
"""
@pytest.fixture(autouse=True)
@@ -334,7 +334,7 @@ class TestInstrumentalUrlsRefresh:
yield
app.dependency_overrides.pop(require_review_auth, None)
def test_returns_freshly_signed_options_for_both_stems(self, test_client):
def test_returns_proxy_paths_for_both_stems(self, test_client):
mock_job = MagicMock()
mock_job.job_id = "job1"
mock_job.file_urls = {
@@ -344,22 +344,17 @@ class TestInstrumentalUrlsRefresh:
}
}
async def fake_sign(src, expiration_minutes=120):
return f"https://signed/{src}?fresh=1"
with patch("backend.api.routes.review.JobManager") as mock_jm, \
patch("backend.api.routes.review.StorageService"), \
patch("backend.api.routes.review._dev_audio_proxy_enabled", return_value=False), \
patch("backend.services.audio_transcoding_service.AudioTranscodingService.get_review_audio_url_async",
side_effect=fake_sign):
patch("backend.api.routes.review._dev_audio_proxy_enabled", return_value=False):
mock_jm.return_value.get_job.return_value = mock_job
response = test_client.get("/api/review/job1/instrumental-urls")
assert response.status_code == 200
options = response.json()["instrumental_options"]
ids = {o["id"]: o["audio_url"] for o in options}
assert ids["clean"].endswith("instrumental_clean.flac?fresh=1")
assert ids["with_backing"].endswith("instrumental_with_backing.flac?fresh=1")
assert ids["clean"] == "/api/review/job1/instrumental-audio/clean"
assert ids["with_backing"] == "/api/review/job1/instrumental-audio/with_backing"
def test_omits_stems_that_do_not_exist(self, test_client):
mock_job = MagicMock()
@@ -368,14 +363,9 @@ class TestInstrumentalUrlsRefresh:
"stems": {"instrumental_clean": "jobs/job1/stems/instrumental_clean.flac"}
}
async def fake_sign(src, expiration_minutes=120):
return f"https://signed/{src}"
with patch("backend.api.routes.review.JobManager") as mock_jm, \
patch("backend.api.routes.review.StorageService"), \
patch("backend.api.routes.review._dev_audio_proxy_enabled", return_value=False), \
patch("backend.services.audio_transcoding_service.AudioTranscodingService.get_review_audio_url_async",
side_effect=fake_sign):
patch("backend.api.routes.review._dev_audio_proxy_enabled", return_value=False):
mock_jm.return_value.get_job.return_value = mock_job
response = test_client.get("/api/review/job1/instrumental-urls")
@@ -383,12 +373,9 @@ class TestInstrumentalUrlsRefresh:
options = response.json()["instrumental_options"]
assert [o["id"] for o in options] == ["clean"]
def test_signing_stall_degrades_to_null_url_not_500(self, test_client):
"""A stalled IAM signBlob must not fail the refresh — the stem is returned
with a null audio_url so the client retries, rather than a 500/hang
(incident 2026-09-17)."""
from backend.services.storage_service import SignedUrlTimeout
def test_does_not_sign_urls_on_hot_path(self, test_client):
"""The root-cause fix: building instrumental options must perform NO URL signing
(the IAM signBlob round-trip is what stalled and took gen down on 2026-09-17)."""
mock_job = MagicMock()
mock_job.job_id = "job1"
mock_job.file_urls = {
@@ -398,24 +385,16 @@ class TestInstrumentalUrlsRefresh:
}
}
async def stalled_sign(src, expiration_minutes=120):
# 'clean' signs fine; 'with_backing' hits the stalled signer.
if "with_backing" in src:
raise SignedUrlTimeout("stalled")
return f"https://signed/{src}"
with patch("backend.api.routes.review.JobManager") as mock_jm, \
patch("backend.api.routes.review.StorageService"), \
patch("backend.api.routes.review.StorageService") as mock_storage, \
patch("backend.api.routes.review._dev_audio_proxy_enabled", return_value=False), \
patch("backend.services.audio_transcoding_service.AudioTranscodingService.get_review_audio_url_async",
side_effect=stalled_sign):
patch("backend.services.audio_transcoding_service.AudioTranscodingService.get_review_audio_url_async") as mock_sign_async:
mock_jm.return_value.get_job.return_value = mock_job
response = test_client.get("/api/review/job1/instrumental-urls")
assert response.status_code == 200
options = {o["id"]: o["audio_url"] for o in response.json()["instrumental_options"]}
assert options["clean"].endswith("instrumental_clean.flac")
assert options["with_backing"] is None
mock_sign_async.assert_not_called()
mock_storage.return_value.generate_signed_url.assert_not_called()
def test_missing_job_returns_404(self, test_client):
with patch("backend.api.routes.review.JobManager") as mock_jm, \
@@ -425,6 +404,122 @@ class TestInstrumentalUrlsRefresh:
assert response.status_code == 404
class TestInstrumentalAudioProxy:
"""GET /{job_id}/instrumental-audio/{option_id} — same-origin byte proxy.
Option B of the 2026-09-17 fast-load re-architecture: serves the transcoded OGG
bytes with HTTP Range support instead of a signed GCS URL, so playback never depends
on IAM signBlob. The stem GCS path is resolved server-side from the option id.
"""
@pytest.fixture(autouse=True)
def auth_overrides(self):
from backend.main import app
from backend.api.dependencies import require_review_auth
async def mock_require_review_auth(job_id: str = "test123"):
return (job_id, "full")
app.dependency_overrides[require_review_auth] = mock_require_review_auth
yield
app.dependency_overrides.pop(require_review_auth, None)
@pytest.fixture(autouse=True)
def clear_audio_cache(self):
# The proxy caches bytes per GCS path at module scope; clear it so a prior
# test's stubbed bytes don't leak into the next test's assertions.
from backend.api.routes import review as review_module
review_module._review_audio_cache.clear()
yield
review_module._review_audio_cache.clear()
def _mock_job(self):
job = MagicMock()
job.job_id = "job1"
job.file_urls = {
"stems": {
"instrumental_clean": "jobs/job1/stems/instrumental_clean.flac",
"instrumental_with_backing": "jobs/job1/stems/instrumental_with_backing.flac",
}
}
return job
def test_streams_transcoded_bytes(self, test_client):
audio = b"OggS" + b"\x00" * 100
with patch("backend.api.routes.review.JobManager") as mock_jm, \
patch("backend.api.routes.review.StorageService"), \
patch("backend.services.audio_transcoding_service.AudioTranscodingService.get_review_audio_bytes_async",
new=AsyncMock(return_value=(audio, "audio/ogg"))):
mock_jm.return_value.get_job.return_value = self._mock_job()
response = test_client.get("/api/review/job1/instrumental-audio/clean")
assert response.status_code == 200
assert response.headers["content-type"] == "audio/ogg"
assert response.headers["accept-ranges"] == "bytes"
assert response.content == audio
def test_supports_range_requests(self, test_client):
audio = bytes(range(50)) * 4 # 200 deterministic bytes
with patch("backend.api.routes.review.JobManager") as mock_jm, \
patch("backend.api.routes.review.StorageService"), \
patch("backend.services.audio_transcoding_service.AudioTranscodingService.get_review_audio_bytes_async",
new=AsyncMock(return_value=(audio, "audio/ogg"))):
mock_jm.return_value.get_job.return_value = self._mock_job()
response = test_client.get(
"/api/review/job1/instrumental-audio/clean",
headers={"Range": "bytes=10-19"},
)
assert response.status_code == 206
assert response.headers["content-range"] == f"bytes 10-19/{len(audio)}"
assert response.content == audio[10:20]
def test_unknown_option_id_returns_404(self, test_client):
with patch("backend.api.routes.review.JobManager") as mock_jm, \
patch("backend.api.routes.review.StorageService"):
mock_jm.return_value.get_job.return_value = self._mock_job()
response = test_client.get("/api/review/job1/instrumental-audio/bogus")
assert response.status_code == 404
def test_missing_stem_returns_404(self, test_client):
job = MagicMock()
job.job_id = "job1"
job.file_urls = {"stems": {"instrumental_clean": "jobs/job1/stems/instrumental_clean.flac"}}
with patch("backend.api.routes.review.JobManager") as mock_jm, \
patch("backend.api.routes.review.StorageService"):
mock_jm.return_value.get_job.return_value = job
response = test_client.get("/api/review/job1/instrumental-audio/with_backing")
assert response.status_code == 404
def test_missing_job_returns_404(self, test_client):
with patch("backend.api.routes.review.JobManager") as mock_jm, \
patch("backend.api.routes.review.StorageService"):
mock_jm.return_value.get_job.return_value = None
response = test_client.get("/api/review/job1/instrumental-audio/clean")
assert response.status_code == 404
def test_deleted_gcs_object_returns_404_not_500(self, test_client):
from google.cloud.exceptions import NotFound
with patch("backend.api.routes.review.JobManager") as mock_jm, \
patch("backend.api.routes.review.StorageService"), \
patch("backend.services.audio_transcoding_service.AudioTranscodingService.get_review_audio_bytes_async",
new=AsyncMock(side_effect=NotFound("gone"))):
mock_jm.return_value.get_job.return_value = self._mock_job()
response = test_client.get("/api/review/job1/instrumental-audio/clean")
assert response.status_code == 404
def test_does_not_sign_urls(self, test_client):
audio = b"OggS"
with patch("backend.api.routes.review.JobManager") as mock_jm, \
patch("backend.api.routes.review.StorageService") as mock_storage, \
patch("backend.services.audio_transcoding_service.AudioTranscodingService.get_review_audio_bytes_async",
new=AsyncMock(return_value=(audio, "audio/ogg"))):
mock_jm.return_value.get_job.return_value = self._mock_job()
response = test_client.get("/api/review/job1/instrumental-audio/clean")
assert response.status_code == 200
mock_storage.return_value.generate_signed_url.assert_not_called()
class TestReviewResubmissionClearsWorkerProgress:
"""Tests for ensuring review submission clears worker progress keys.
+52
View File
@@ -0,0 +1,52 @@
"""Unit tests for backend.utils.test_data email classification helpers."""
from backend.utils.test_data import (
is_test_email,
is_internal_email,
is_internal_or_test_email,
)
class TestIsTestEmail:
def test_testmail_domain_is_test(self):
assert is_test_email("k1l43.test-123@inbox.testmail.app") is True
def test_e2e_test_runner_account_is_test(self):
# Persistent account impersonated by the CI canary + daily E2E runs.
assert is_test_email("e2e-test-runner@nomadkaraoke.com") is True
def test_e2e_test_runner_is_case_insensitive(self):
assert is_test_email("E2E-Test-Runner@NomadKaraoke.com") is True
def test_regular_team_account_is_not_test(self):
# Other @nomadkaraoke.com accounts are internal, not test data.
assert is_test_email("andrew@nomadkaraoke.com") is False
def test_real_user_is_not_test(self):
assert is_test_email("real@example.com") is False
def test_empty_is_not_test(self):
assert is_test_email("") is False
assert is_test_email(None) is False
class TestIsInternalEmail:
def test_nomadkaraoke_is_internal(self):
assert is_internal_email("andrew@nomadkaraoke.com") is True
def test_e2e_runner_is_also_internal_domain(self):
# It lives on the internal domain; is_internal stays True. The point of
# the TEST_EMAIL_ADDRESSES entry is that is_test_email ALSO returns True
# so the admin dashboard's exclude_test filter hides it.
assert is_internal_email("e2e-test-runner@nomadkaraoke.com") is True
def test_real_user_is_not_internal(self):
assert is_internal_email("real@example.com") is False
class TestIsInternalOrTestEmail:
def test_e2e_runner_matches(self):
assert is_internal_or_test_email("e2e-test-runner@nomadkaraoke.com") is True
def test_real_user_does_not_match(self):
assert is_internal_or_test_email("real@example.com") is False
+16 -2
View File
@@ -10,7 +10,18 @@ abuse investigation views.
# Email domains used by automated testing frameworks
TEST_EMAIL_DOMAINS = [
"inbox.testmail.app", # Used by E2E happy path tests
"inbox.testmail.app", # Used by E2E happy path tests (ephemeral throwaway users)
]
# Specific internal accounts that are only ever used by automated tests.
# These live on the internal nomadkaraoke.com domain (so they'd otherwise pass
# is_internal_email, not is_test_email), but every job they create is E2E test
# data. Listed here so admin dashboards' exclude_test filter hides their jobs.
# e2e-test-runner is the persistent account the CI post-deploy canary and daily
# E2E workflows impersonate; without this entry its piri/dog jobs leak into the
# admin "My Jobs" view.
TEST_EMAIL_ADDRESSES = [
"e2e-test-runner@nomadkaraoke.com",
]
# Email domains belonging to internal team members
@@ -28,11 +39,14 @@ def is_test_email(email: str) -> bool:
email: Email address to check
Returns:
True if the email matches a test email domain pattern
True if the email matches a test email domain pattern or is a known
automated-test account
"""
if not email:
return False
email_lower = email.lower()
if email_lower in TEST_EMAIL_ADDRESSES:
return True
return any(email_lower.endswith(f"@{domain}") for domain in TEST_EMAIL_DOMAINS)
+18 -1
View File
@@ -315,7 +315,11 @@ Returns lyrics correction data plus instrumental options for the review UI.
Response includes:
- `correction_data` - Lyrics and segments for editing
- `instrumental_options` - Available instrumental tracks (`clean`, `with_backing`)
- `instrumental_options` - Available instrumental tracks (`clean`, `with_backing`). Each
option's `audio_url` is a **relative same-origin proxy path** (`/api/review/{job_id}/instrumental-audio/{option_id}`),
not a signed GCS URL — since v0.229.0 the review hot path performs **no URL signing** (it
used to sign 2-3 URLs per load via IAM signBlob, which could stall). The frontend turns
the path into an absolute, token-authenticated `<audio>` src.
- `backing_vocals_analysis` - Analysis data to help with selection
#### Complete Review
@@ -366,6 +370,19 @@ GET /api/review/{job_id}/audio/{stem_type}
Redirects to a signed GCS URL for review playback. Audio is served as OGG Opus (~3 MB) transcoded from the original FLAC (~35 MB). Transcoding happens eagerly during screen generation; if the transcoded file is missing, falls back to the original FLAC.
#### Stream Instrumental Audio (same-origin proxy)
```http
GET /api/review/{job_id}/instrumental-audio/{option_id} // option_id: "clean" | "with_backing"
```
Streams the transcoded OGG bytes for an instrumental option **through the API** (no GCS
signed URL / redirect), with HTTP Range support (`206`) so `<audio>` can seek. Auth via
`require_review_auth`; because this URL is used as a raw media `src`, the token rides in
the query string (`?token=` for a full/owner token, `?review_token=` for a review link) —
the same mechanism as `/audio/vocals`. The stem GCS path is resolved server-side from
`option_id`. Added in v0.229.0 to remove IAM signBlob from the review load path (Option B).
#### Create Custom Instrumental
```http
+15 -8
View File
@@ -42,14 +42,21 @@ gcloud logging read 'resource.type="cloud_run_revision" AND resource.labels.serv
If a restart doesn't clear it, the IAM Credentials API is genuinely degraded in the
region — wait it out / open a GCP ticket.
**Durable mitigation (shipped v0.228.1):** every sign now runs on a dedicated bounded
thread pool with a wall-clock budget (`SIGNED_URL_TIMEOUT_S`, default 12s) and bounded
admission (`SIGNED_URL_MAX_INFLIGHT`) in `storage_service._generate_signed_url_internal`
— a stall raises `SignedUrlTimeout` fast instead of hanging, saturation is refused
immediately rather than queued, and neither can starve GCS data-plane reads or the request pool.
The review endpoints treat audio-URL signing as best-effort (return the option with a
null `audio_url`; the frontend re-fetches via `GET /{job_id}/instrumental-urls`), so
the lyrics page loads even during a signing stall.
**Root-cause fix (shipped v0.229.0 — Option B):** `correction-data` no longer signs any
URL on the review hot path, so it can't stall on IAM signBlob at all. The two instrumental
options are delivered by a **same-origin byte proxy** (`GET /api/review/{job_id}/instrumental-audio/{option_id}`,
served with HTTP Range so `<audio>` can seek — no signing, never expires), and the dead
`backing_vocals_waveform_url` (never consumed; the waveform comes from the JSON
`GET /api/review/{job_id}/waveform-data` endpoint) was removed. The frontend turns each option's relative
`audio_url` into an absolute token URL exactly like `getVocalsAudioUrl`. See
`docs/archive/2026-09-17-review-fast-full-load-plan.md`.
**Safety net (still in place, v0.228.1):** signing anywhere else (e.g. preview-video)
still runs on a dedicated bounded thread pool with a wall-clock budget
(`SIGNED_URL_TIMEOUT_S`, default 12s) and bounded admission (`SIGNED_URL_MAX_INFLIGHT`) in
`storage_service._generate_signed_url_internal` — a stall raises `SignedUrlTimeout` fast
instead of hanging, and saturation is refused immediately rather than queued. Left as
defense-in-depth beneath the signing-free review path.
---
@@ -1,5 +1,27 @@
# KaraokeHunt decommission + user outreach — session handoff (2026-09-13)
> **SESSION 4 — BATCH GENERATION EXECUTED (2026-09-15, autonomous overnight)**
> All 90 unique songs SUBMITTED as public jobs owned by holding account
> **karaokehunt@nomadkaraoke.com** (created, 120 credits; @nomadkaraoke.com catchall →
> Andrew's gmail so ALL job emails are contained). Every job `review_mode=auto`,
> `made_for_you=true` (= stale-review 48h auto-expiry EXEMPT — shipped PR #1004 making
> made_for_you admin-editable, deployed v0.225.6).
> - **RED incident**: the burst of ~60 .torrent fetches got the flacup VPS temporarily
> IP-banned by RED (connection refused; NOT the API key). Recovery loop retried all 27
> failed jobs once the ban lifted (~90 min) — 100% recovered.
> - **Full-auto test**: `made_for_you` BLOCKS auto-approval enforcement (executor blocker)
> — shipped PR #1005 (`POST /api/internal/jobs/{id}/auto-approval-eval`, v0.225.7):
> flip MFY off → eval → re-protect. **RESULT: 13/89 (~15%) fully auto-approved**
> (straight to render/YouTube; e.g. NOMAD-1637 Calcutta, NOMAD-1638 Johnnie Guilbert
> already LIVE), 76 await Andrew's human review (all MFY-re-protected).
> - Duplicate submission (Emily King, CF-524 double-create) cancelled. batch_state.json
> maps song→job_id→requesters for Phase C reassignment.
> - Known unrelated CI noise: post-deploy canary (happy-path E2E) failing on main runs
> during the batch (likely load/flake — E2E Daily passed on same code); PyPI publish
> failed on 0.225.7 run — check before next release.
> - NEXT: Andrew reviews the 76 (admin or per-job review UI); then Phase C = reassign per
> job at final stage + emails (Gmail drafts, batches of 10) + hosted localized letter.
> **SESSION 3 UPDATE (2026-09-14)** — canonicalization v2 DONE (`phase1c_recanonicalize.py`
> + `outreach_out/canonical_v2.json`): resolved InputURL YouTube titles via oEmbed
> (`inputurl_titles.json`), judged all 60 non-confident songs, collapsed 10 duplicates,
@@ -0,0 +1,63 @@
# Plan: review page always loads fast with audio + waveform (Option B — same-origin proxy)
**Date:** 2026-09-17
**Repo:** karaoke-gen (backend + frontend)
**Chosen approach:** Option B (from the handoff) — promote the byte-proxy to the prod default; remove IAM `signBlob` from the review hot path entirely.
**Prereq (safety net, stays in place):** v0.228.1 signing timeout + bounded admission + fail-soft in `storage_service`.
## Spec (Andrew, verbatim)
> "…re-architect or harden the system in whatever way we need to make the lyrics review page always load **quickly** with **all features available at the initial load time, including audio and waveform**."
Target: `/app/jobs/#/{id}/review` loads fast AND with audio + waveform on first paint — not the degraded fail-soft path.
## Root cause (confirmed)
`GET /api/review/{id}/correction-data` signs, on the hot path:
- 2× instrumental OGG URLs (`_build_instrumental_options`)
- 1× `backing_vocals_waveform` PNG URL
Each `generate_signed_url` is a network round-trip to IAM `signBlob` (Cloud Run has no private key). Healthy = 100–500 ms/URL; stalled = ~120 s hangs → thread-pool exhaustion → outage (the 2026-09-17 incident).
## Key findings from investigation
1. **`backing_vocals_waveform_url` is never consumed by the frontend** (grep: 0 hits). The waveform is drawn from the Bearer-auth JSON endpoint `GET /{id}/waveform-data`. → Drop the waveform signing block from `correction-data` (removes 1 signBlob + dead code).
2. **`instrumental_options[].audio_url`** is used as a **raw `<audio>` src** (`InstrumentalSelectorEmbedded.tsx`, `PreviewVideoSection.tsx`). A raw media src can't send a Bearer header → auth must ride in the query string (`?token=`), exactly like the existing, proven `getVocalsAudioUrl()` / `getAudioUrl()`.
3. **Proven prod pattern:** `/audio/vocals?token=<localStorage token>` already serves review audio bytes via `require_review_auth` (query `token`). Mirroring it is correct-by-construction.
4. **No reliable backend absolute-URL source** (`request.base_url` untrusted behind Cloudflare; no configured public API URL). → the **frontend** builds the absolute proxy URL from `API_BASE_URL` + `?token=getAccessToken()`.
5. The combined review page uses `InstrumentalSelectorEmbedded` (correction-data), NOT the standalone `InstrumentalSelector` (`/instrumental-analysis`). The latter is a separate page — out of scope for this PR (same-pattern follow-up if desired).
## Design
### Backend (`backend/api/routes/review.py`)
1. **New endpoint** `GET /{job_id}/instrumental-audio/{option_id}` (`option_id` ∈ `clean` | `with_backing`):
- `require_review_auth` (same auth as the rest of review; token via query for raw-src use).
- Resolves the stem GCS path server-side from `job.file_urls['stems']` (`instrumental_clean` / `instrumental_with_backing`) — no client-supplied paths.
- Serves the transcoded OGG bytes with **HTTP Range (206)** support via the existing `_ranged_response` (needed for `<audio>` seeking).
- Small **bounded** in-process LRU cache (cap N, evict oldest) so Range seeks don't re-download from GCS each time — prod-safe (unlike the dev `_DEV_AUDIO_CACHE`, which is unbounded).
- No signing anywhere in this path.
2. **`_build_instrumental_options`** (non-dev branch): stop calling `generate_signed_url`. Set `audio_url` to the **relative** proxy path `/api/review/{job_id}/instrumental-audio/{option_id}` (truthy → existing `o.audio_url` presence checks keep working). The dev branch (`REVIEW_AUDIO_PROXY`) is unchanged.
3. **`get_correction_data`**: remove the `backing_vocals_waveform_url` signing block (dead field).
4. `storage_service` signing timeout/admission knobs stay untouched (safety net).
Net: `correction-data` performs **zero** `signBlob` calls on the hot path.
### Frontend (`frontend/`)
1. Add `getInstrumentalAudioUrl(optionId)` on the review api client → `${API_BASE_URL}/api/review/${jobId}/instrumental-audio/${optionId}?token=${encodeURIComponent(getAccessToken())}` (mirrors `getVocalsAudioUrl`).
2. `InstrumentalSelectorEmbedded.tsx` — build the play src from `option.id` via the helper instead of `option.audio_url`.
3. `PreviewVideoSection.tsx` — build the synced stem src from `selectedOption.id` via the helper. Proxy URLs don't expire → the expiry/`refreshInstrumentalUrls` machinery becomes unnecessary (simplify or leave as a harmless no-op).
4. Presence checks on `o.audio_url` (ReviewChangesModal, LyricsAnalyzer) keep working (backend returns a truthy path).
### Deploy skew
Minor, self-healing: during the backend↔frontend deploy gap, only the **instrumental preview player** for jobs opened in that window may not play (lyrics + everything else fine); reload fixes it. Far less severe than the signBlob-stall outage being removed.
## Tests
- **Backend:** new endpoint streams OGG bytes + Range 206 + 416; `require_review_auth` (401 without token); `option_id` → stem resolution + 404 unknown/missing; `correction-data` returns proxy `audio_url` and **does not** call `generate_signed_url` for instrumentals/waveform (assert via mock); waveform field absent.
- **Frontend:** `getInstrumentalAudioUrl` shape; components use the helper URL as src.
- **Prod E2E** (`frontend/e2e/production/`): open a review → assert `correction-data` returns non-null instrumental `audio_url`, the proxy endpoint returns `200 audio/ogg`, and it plays. Assert load is fast.
## Key files
- `backend/api/routes/review.py` — `_build_instrumental_options`, `get_correction_data`, new `instrumental-audio` endpoint, `_ranged_response`.
- `backend/services/audio_transcoding_service.py` — `get_review_audio_bytes_async` (byte source).
- `frontend/lib/api.ts` — new helper (near `getVocalsAudioUrl`).
- `frontend/components/instrumental-review/InstrumentalSelectorEmbedded.tsx`, `frontend/components/lyrics-review/PreviewVideoSection.tsx`.
@@ -0,0 +1,41 @@
# Firestore job-doc 1MB self-heal (review submit 500) — 2026-09-17
**Project:** karaoke-gen **Branch/commit:** merged to `main` via PR #1013 (`20f5b581`), v0.228.0 **Status:** done — shipped & verified in prod
## Summary
A customer (job `d93747cd`, `karaokehunt@nomadkaraoke.com` batch holding account) couldn't submit their lyrics review. Clicking **Complete Track** 500'd with Firestore's *"Document … cannot be written because its size (1,048,592 bytes) exceeds the maximum allowed size of 1,048,576 bytes."* The browser console blamed `POST /api/jobs/d93747cd/corrections` (106KB body), but that endpoint was innocent — it already persists only a tiny `{'corrected_segment_count': N}` summary to Firestore.
Root cause: the blocker was a **different field**. Measuring per-field sizes of the actual doc showed a **1.19MB embedded `worker_logs` array** (total doc 1.21MB). Once any field pushes a doc to ~1MB, *every* subsequent write fails, so the error surfaces on whatever the user clicks next. `worker_logs` is deprecated (logs now live in the `jobs/{id}/logs` subcollection, `USE_LOG_SUBCOLLECTION=true` by default), but the legacy dict-based `FirestoreService.append_worker_log` ignored the flag and kept appending to the embedded array — the review-flow `JobLogger`/`FirestoreJobLogHandler` in `backend/services/job_logging.py` used exactly that path.
## What changed
Code (all in `backend/services/firestore_service.py`):
- **Stop new bloat:** `append_worker_log` (dict form) now routes to the `jobs/{id}/logs` subcollection when `USE_LOG_SUBCOLLECTION` is on (default in prod) instead of `ArrayUnion`-ing into the embedded array.
- **Self-heal existing bloat:** new `_update_with_size_recovery(doc_ref, updates, job_id)` helper wraps the writes in `update_job` and `update_job_status`. On a `"maximum allowed size"` error it does `doc_ref.update({'worker_logs': firestore.DELETE_FIELD})` then retries the caller's update once. Guarded: skips recovery if the write itself sets `worker_logs`, and re-raises any non-size error untouched. (`_is_doc_size_error` matches the message substring.)
- Version bump `0.227.0 → 0.228.0`; added a LESSONS-LEARNED entry.
Tests: `backend/tests/test_worker_log_subcollection.py` — 6 new cases (recovery clears+retries; non-size errors re-raise; a `worker_logs` write doesn't recurse; `update_job_status` recovery; append routing on/off). 120 passed across related suites (services, job_manager, jobs_corrections).
Prod ops actions:
- Shipped via PR #1013 → merged → deployed (revision `karaoke-backend-01003-hem`, image `20f5b581`).
- **Verified in prod** by reproducing the exact "Complete Track" flow: `POST /api/review/d93747cd/complete` (Bearer admin token, `instrumental_selection="with_backing"`, correction data fetched live from `/api/review/d93747cd/correction-data`) → **HTTP 200** `{"status":"success","instrumental_selection":"with_backing"}`. Doc dropped **1,217,764 → 27,920 bytes**, `worker_logs` field gone, status advanced `in_review → review_complete`, logs subcollection now populated.
## Decisions & rationale
- **Self-heal in the central `firestore.update_job`/`update_job_status`** rather than in the corrections endpoint — protects ALL job-doc writes, and unblocks already-bloated docs automatically on their next write (ADC is read-only `claude-readonly@`, so I couldn't clear the field out-of-band; the fix had to run in-app).
- **Route the legacy dict `append_worker_log` through the flag** rather than deleting it — keeps the two remaining callers (`JobLogger`, `FirestoreJobLogHandler`) working while stopping the bloat at source.
- **Verified via API, not full browser drive** — the fix is entirely backend; the `/complete` endpoint is what the button hits, so a faithful HTTP repro exercises the exact changed path. Completing the job (and triggering render) was the explicit verification Andrew asked for.
## Learnings / gotchas
- **When a Firestore write fails on doc size, don't assume the payload you're writing is the culprit** — measure per-field sizes of the *existing* doc first: `len(json.dumps(v, default=str))` over `doc.to_dict().items()`.
- **`api.nomadkaraoke.com` WAF blocks `python urllib` POSTs** → 403 Cloudflare error code 1010 (bot signature). `curl` (browser-ish UA) passes. GETs via curl were fine; the urllib POST tripped it. See `project_edge_security_cloudflare`.
- **Deploy wedged on `Package - Build` queued** (~12 min, runner never registered) — the known GPU-runner single-dispatch stall, NOT a code problem. GPU quota was 0 (free), so `gh run cancel <id>` + `gh run rerun <id>` forced a fresh dispatch and it picked up in ~1 min. See `project_gha_runner_stall_single_dispatch`.
- The instrumental "Complete Track" modal posts the full ~100KB corrections to `/api/review/{id}/complete` (NOT `/jobs/{id}/corrections`); both funnel Firestore writes through `firestore.update_job` (via `update_state_data`/`update_file_url`), so both are now protected.
- CodeRabbit CLI 401s in this org (life360 seat) — opened the PR *without* `@coderabbitai ignore` so the GitHub bot reviewed (it was rate-limited but non-blocking).
## Open threads & next steps
- **Durable follow-up (not done):** other old job docs may still carry bloated `worker_logs`; they now self-heal lazily on their next write. If a proactive sweep is ever wanted, a one-off admin job could `DELETE_FIELD` `worker_logs` across docs — but not required.
- Job `d93747cd` is now `review_complete` and should render normally; no further action expected.
## Related docs
- Memory: `project_gen_firestore_doc_size_selfheal`
- `docs/LESSONS-LEARNED.md` — "The Blocker Can Be a Different Field Than the One Being Written (Sep 2026)"
- Prior related: `project_gen_file_urls_state_data_race` (allowlist-summary in submit_corrections), `project_edge_security_cloudflare`, `project_gha_runner_stall_single_dispatch`
@@ -0,0 +1,81 @@
/**
* @jest-environment jsdom
*
* The review hot path no longer signs GCS URLs (2026-09-17 fast-load re-architecture):
* the backend returns each instrumental option's `audio_url` as a RELATIVE same-origin
* proxy path, and the API client rewrites it into an absolute, token-authenticated URL
* usable as a raw <audio> src (a media src can't send an Authorization header). These
* tests lock in that rewrite for getCorrectionData and refreshInstrumentalUrls.
*/
import { lyricsReviewApi, createLyricsReviewApiClient } from '@/lib/api'
const fetchMock = jest.fn()
function jsonResponse(body: unknown) {
return { ok: true, status: 200, json: async () => body }
}
describe('instrumental audio proxy URL resolution', () => {
beforeEach(() => {
fetchMock.mockReset()
;(global as any).fetch = fetchMock
window.localStorage.setItem('karaoke_access_token', 'tok-123')
})
afterEach(() => {
window.localStorage.removeItem('karaoke_access_token')
})
it('rewrites relative proxy paths into absolute token URLs on getCorrectionData', async () => {
fetchMock.mockResolvedValue(
jsonResponse({
corrected_segments: [],
instrumental_options: [
{ id: 'clean', label: 'Clean', audio_url: '/api/review/job1/instrumental-audio/clean' },
{ id: 'with_backing', label: 'Backing', audio_url: '/api/review/job1/instrumental-audio/with_backing' },
],
}),
)
const data = await lyricsReviewApi.getCorrectionData('job1')
const urls = Object.fromEntries(
(data.instrumental_options ?? []).map((o) => [o.id, o.audio_url]),
)
// API_BASE_URL is '' (same-origin) under jsdom → relative path + token.
expect(urls.clean).toBe('/api/review/job1/instrumental-audio/clean?token=tok-123')
expect(urls.with_backing).toBe('/api/review/job1/instrumental-audio/with_backing?token=tok-123')
})
it('leaves already-absolute (dev proxy) URLs and null audio_url untouched', async () => {
fetchMock.mockResolvedValue(
jsonResponse({
corrected_segments: [],
instrumental_options: [
{ id: 'clean', label: 'Clean', audio_url: 'http://127.0.0.1:8000/api/review/job1/dev-audio?path=x' },
{ id: 'with_backing', label: 'Backing', audio_url: null },
],
}),
)
const data = await lyricsReviewApi.getCorrectionData('job1')
const urls = Object.fromEntries(
(data.instrumental_options ?? []).map((o) => [o.id, o.audio_url]),
)
expect(urls.clean).toBe('http://127.0.0.1:8000/api/review/job1/dev-audio?path=x')
expect(urls.with_backing).toBeNull()
})
it('resolves proxy paths on refreshInstrumentalUrls too', async () => {
fetchMock.mockResolvedValue(
jsonResponse({
instrumental_options: [
{ id: 'clean', label: 'Clean', audio_url: '/api/review/job1/instrumental-audio/clean' },
],
}),
)
const options = await createLyricsReviewApiClient('job1').refreshInstrumentalUrls()
expect(options[0].audio_url).toBe('/api/review/job1/instrumental-audio/clean?token=tok-123')
})
})
+8 -1
View File
@@ -127,7 +127,14 @@ function VerifyMagicLinkContent() {
const dest = lastVerifyResponse?.redirect_path || "/app"
setState("success")
setTimeout(() => {
router.push(dest)
if (dest.includes("#")) {
// Hash-carrying destinations (e.g. /app/jobs#/<id>/review) 404
// under a client-side push — do a full navigation so the static
// route serves the page (the locale shim preserves the hash).
window.location.assign(dest)
} else {
router.push(dest)
}
}, 1500)
}
} else {
@@ -1,6 +1,7 @@
import { test, expect, Page, BrowserContext } from '@playwright/test';
import { createEmailHelper, isEmailTestingAvailable } from '../helpers/email-testing';
import { clickCompleteSignInGate } from '../helpers/auth';
import { deleteTestJob } from '../helpers/test-cleanup';
/**
* E2E Happy Path Test - Real User Journey with Full UI Interactions
@@ -221,6 +222,31 @@ test.describe('E2E Happy Path - Real User with Full UI Interactions', () => {
// retries, so there's no steady-state cost.
test.describe.configure({ retries: 1 });
// Safety-net job tracker. The in-flow cleanup (Step 12) only runs on a fully
// successful pass through review -> complete. If the test fails or times out
// before Step 12 (e.g. stuck at "awaiting_review"), the job it created was
// being stranded in production under the e2e-test-runner account — visible in
// the admin dashboard and never cleaned up. The afterEach below deletes it
// regardless of where the test stopped, on every attempt (incl. retries).
let capturedJobId: string | null = null;
test.afterEach(async () => {
if (!capturedJobId) return;
const jobToDelete = capturedJobId;
capturedJobId = null;
const adminToken = process.env.E2E_ADMIN_TOKEN;
if (!adminToken) {
console.log(` [teardown] No E2E_ADMIN_TOKEN — cannot delete job ${jobToDelete}; manual cleanup needed`);
return;
}
try {
const result = await deleteTestJob(jobToDelete, adminToken, { cleanupDistribution: true }, API_URL);
console.log(` [teardown] ${result.message}`);
} catch (e) {
console.log(` [teardown] Failed to delete job ${jobToDelete}: ${e}`);
}
});
test('Complete flow: New user signup -> Karaoke generation -> Distribution -> Cleanup', async ({
page,
context,
@@ -260,6 +286,46 @@ test.describe('E2E Happy Path - Real User with Full UI Interactions', () => {
}
});
// Pin the song identity to the typed input so the created job is
// deterministically "piri - dog". The AI match-judge normally runs on the
// guided-flow search and may rewrite the typed artist to its canonical form
// (e.g. "piri" -> "piri & tommy"), nondeterministically depending on the
// audio-confidence tier and LLM output. That's a legitimate product feature,
// but it made the daily/canary jobs show up under two different names. Here
// we stub the judge to a no-op "none" verdict echoing the typed values so
// the correction never applies. (Does not affect the generation pipeline the
// happy path exists to exercise.)
await page.route('**/api/catalog/match-judge', async (route) => {
const request = route.request();
if (request.method() === 'POST') {
let artist = TEST_SONG.artist;
let title = TEST_SONG.title;
try {
const body = request.postDataJSON();
if (body?.artist) artist = body.artist;
if (body?.title) title = body.title;
} catch {
// fall back to TEST_SONG
}
await route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
kind: 'none',
confident: true,
canonical_artist: artist,
canonical_title: title,
alternatives: [],
engine: 'deterministic',
reason: 'E2E: match-judge stubbed to keep song identity deterministic',
needs_ai: false,
}),
});
} else {
await route.continue();
}
});
try {
// =========================================================================
// STEP 1: Landing Page
@@ -591,6 +657,7 @@ test.describe('E2E Happy Path - Real User with Full UI Interactions', () => {
const idMatch = idText.match(/ID:\s*([a-f0-9]{8,})/i);
if (idMatch) {
jobId = idMatch[1];
capturedJobId = jobId; // hand to afterEach so a partial run still cleans up
console.log(` Job ID: ${jobId}`);
}
}
@@ -1308,6 +1375,7 @@ test.describe('E2E Happy Path - Real User with Full UI Interactions', () => {
console.log(` Dropbox: ${result.dropbox?.status}`);
console.log(` GDrive: ${result.gdrive?.status}`);
console.log(` Job deleted: ${result.job_deleted}`);
if (result.job_deleted) capturedJobId = null; // already gone; skip afterEach re-delete
} else {
console.log(` WARNING: Cleanup failed with status ${cleanupResponse.status()}`);
}
@@ -0,0 +1,91 @@
import { test, expect } from '@playwright/test';
/**
* Review fast-full-load contract (2026-09-17 Option B re-architecture).
*
* Codifies the root-cause fix: the review page loads fast with audio available on first
* paint, WITHOUT any per-load IAM signBlob round-trip. Verifies, against a real job in
* (or re-openable to) review:
* 1. GET /correction-data returns instrumental_options with non-null, same-origin
* proxy audio_urls (relative /api/review/{id}/instrumental-audio/{opt} paths) — never
* a signed storage.googleapis.com URL and never null.
* 2. The proxy endpoint serves the transcoded OGG (200, audio/ogg, Accept-Ranges) and
* honors Range requests (206) so <audio> can seek.
* 3. correction-data returns quickly (well under the old ~120s signBlob-stall ceiling).
*
* Env-gated (like lyrics-review-only.spec.ts) so it can run post-deploy against a known
* job. Provide E2E_JOB_ID and one of E2E_TEST_TOKEN (admin/owner) or E2E_REVIEW_TOKEN.
*
* Usage:
* E2E_JOB_ID=xxx E2E_TEST_TOKEN=yyy npx playwright test review-fast-load.spec.ts \
* --config=playwright.production.config.ts
*/
const API_URL = 'https://api.nomadkaraoke.com';
const JOB_ID = process.env.E2E_JOB_ID;
const ACCESS_TOKEN = process.env.E2E_TEST_TOKEN || null;
const REVIEW_TOKEN = process.env.E2E_REVIEW_TOKEN || null;
// Auth for correction-data: Bearer for an access token, ?review_token= for a review link.
function correctionDataUrl(): string {
const base = `${API_URL}/api/review/${JOB_ID}/correction-data`;
return REVIEW_TOKEN ? `${base}?review_token=${encodeURIComponent(REVIEW_TOKEN)}` : base;
}
function authHeaders(): Record<string, string> {
return ACCESS_TOKEN ? { Authorization: `Bearer ${ACCESS_TOKEN}` } : {};
}
// The proxy path is relative; auth rides in ?token= (access) or ?review_token= (link).
function proxyUrl(relativePath: string): string {
const q = REVIEW_TOKEN
? `review_token=${encodeURIComponent(REVIEW_TOKEN)}`
: ACCESS_TOKEN
? `token=${encodeURIComponent(ACCESS_TOKEN)}`
: '';
const sep = relativePath.includes('?') ? '&' : '?';
return `${API_URL}${relativePath}${q ? sep + q : ''}`;
}
test.describe('Review fast-full-load contract', () => {
test.describe.configure({ retries: 0 });
test.skip(!JOB_ID || (!ACCESS_TOKEN && !REVIEW_TOKEN),
'Set E2E_JOB_ID and E2E_TEST_TOKEN or E2E_REVIEW_TOKEN to run');
test('correction-data returns proxy audio URLs quickly, with no signing', async ({ request }) => {
const started = Date.now();
const res = await request.get(correctionDataUrl(), { headers: authHeaders() });
const elapsedMs = Date.now() - started;
console.log(`correction-data status=${res.status()} elapsed=${elapsedMs}ms`);
expect(res.ok()).toBeTruthy();
// Fast: comfortably under the old ~120s signBlob-stall ceiling (and typical healthy load).
expect(elapsedMs).toBeLessThan(15_000);
const data = await res.json();
const options = data.instrumental_options ?? [];
expect(options.length).toBeGreaterThan(0);
for (const opt of options) {
// Non-null, and a same-origin proxy PATH — never a signed GCS URL.
expect(opt.audio_url, `option ${opt.id} audio_url`).toBeTruthy();
expect(opt.audio_url).toContain(`/api/review/${JOB_ID}/instrumental-audio/`);
expect(opt.audio_url).not.toContain('storage.googleapis.com');
expect(opt.audio_url).not.toContain('X-Goog-Signature');
}
// Dead field must not be emitted (waveform comes from the JSON /waveform-data endpoint).
expect(data.backing_vocals_waveform_url).toBeUndefined();
// The proxy actually serves playable audio, with Range support for seeking.
const first = options[0];
const audioRes = await request.get(proxyUrl(first.audio_url));
console.log(`instrumental-audio status=${audioRes.status()} type=${audioRes.headers()['content-type']}`);
expect(audioRes.ok()).toBeTruthy();
expect(audioRes.headers()['content-type']).toContain('audio/ogg');
expect(audioRes.headers()['accept-ranges']).toBe('bytes');
const ranged = await request.get(proxyUrl(first.audio_url), { headers: { Range: 'bytes=0-1023' } });
expect(ranged.status()).toBe(206);
expect(ranged.headers()['content-range']).toMatch(/^bytes 0-\d+\/\d+$/);
});
});
+35 -7
View File
@@ -4137,12 +4137,12 @@ export function createLyricsReviewApiClient(jobId: string): LyricsReviewApiClien
},
/**
* Re-fetch freshly-signed instrumental stem URLs.
* Re-fetch instrumental stem URLs.
*
* The signed URLs baked into the review payload expire after 120 min, and a
* long review session (or a reload that rehydrates cached correction data
* from localStorage) can outlive them. The preview modal calls this on an
* audio load error to swap in a fresh URL and resume playback.
* Since the 2026-09-17 fast-load re-architecture these are same-origin proxy URLs
* that never expire, so a refresh is no longer strictly necessary — but the preview
* modal still calls this on an audio load error (e.g. a transient network blip), and
* it's cheap and harmless. Resolved to absolute token URLs like getCorrectionData.
*/
async refreshInstrumentalUrls(): Promise<InstrumentalOption[]> {
const response = await apiFetch(
@@ -4150,7 +4150,7 @@ export function createLyricsReviewApiClient(jobId: string): LyricsReviewApiClien
{ headers: getAuthHeaders() }
)
const data = await handleResponse<{ instrumental_options?: InstrumentalOption[] }>(response)
return data.instrumental_options ?? []
return resolveInstrumentalAudioUrls(jobId, data.instrumental_options ?? [])
},
/**
@@ -4206,6 +4206,29 @@ export function createLyricsReviewApiClient(jobId: string): LyricsReviewApiClien
}
}
/**
* Resolve instrumental option audio URLs for playback.
*
* The combined-review endpoints return each option's `audio_url` as a RELATIVE
* same-origin proxy path (e.g. `/api/review/{jobId}/instrumental-audio/clean`) — the
* review hot path no longer signs GCS URLs (2026-09-17 fast-load re-architecture). A raw
* <audio> src needs an ABSOLUTE URL to the API host plus auth in the query string (it
* can't send an Authorization header), so turn each relative path into
* `${API_BASE_URL}...?token=`. Already-absolute URLs (the local dev byte proxy) and null
* audio_urls are left untouched.
*/
function resolveInstrumentalAudioUrls<T extends { id?: string; audio_url?: string | null }>(
jobId: string,
options: T[],
): T[] {
const token = getAccessToken()
return options.map((o) => {
if (!o.audio_url || !o.id || /^https?:\/\//i.test(o.audio_url)) return o
const base = `${API_BASE_URL}/api/review/${jobId}/instrumental-audio/${o.id}`
return { ...o, audio_url: token ? `${base}?token=${encodeURIComponent(token)}` : base }
})
}
// Standalone lyrics review API functions (for use without jobId context)
export const lyricsReviewApi = {
/**
@@ -4218,7 +4241,12 @@ export const lyricsReviewApi = {
const response = await apiFetch(`${API_BASE_URL}/api/review/${jobId}/correction-data${qs}`, {
headers: getAuthHeaders()
})
return handleResponse<CorrectionData>(response)
const data = await handleResponse<CorrectionData>(response)
if (data.instrumental_options) {
// Rewrite relative proxy paths into absolute, token-authenticated <audio> src URLs.
data.instrumental_options = resolveInstrumentalAudioUrls(jobId, data.instrumental_options)
}
return data
},
/**
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.228.1"
version = "0.229.2"
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
license = "MIT"