mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-03 16:48:05 +09:00
Compare commits
No files matched your search
@@ -1976,6 +1976,12 @@ jobs:
|
||||
echo "Version: $VERSION"
|
||||
echo "Previously-serving revision: ${PREV_REVISION:-<unknown>}"
|
||||
|
||||
# --concurrency 16 (was 80): the backend is one uvicorn process per
|
||||
# 2-vCPU instance; review-page loads are heavy (audio byte-serving,
|
||||
# waveform work). At 80 a 10-tab burst all landed on the single
|
||||
# min-instance and wedged it ("no available instance" aborts,
|
||||
# 2026-09-18 investigation). 16 makes bursts trigger scale-out while
|
||||
# staying comfortably above normal per-instance load.
|
||||
gcloud run deploy karaoke-backend \
|
||||
--image $IMAGE \
|
||||
--no-traffic \
|
||||
@@ -1989,7 +1995,7 @@ jobs:
|
||||
--cpu-throttling \
|
||||
--execution-environment gen2 \
|
||||
--timeout 1800 \
|
||||
--concurrency 80 \
|
||||
--concurrency 16 \
|
||||
--max-instances 20 \
|
||||
--min-instances 1 \
|
||||
--vpc-connector projects/nomadkaraoke/locations/us-central1/connectors/cloud-run-connector \
|
||||
|
||||
@@ -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
|
||||
@@ -135,6 +135,10 @@ EDITABLE_JOB_FIELDS = {
|
||||
"is_private",
|
||||
"review_mode",
|
||||
"backing_preference",
|
||||
# Exempts a job from the stale-review auto-expiry (48h cancel+refund) —
|
||||
# the stale_review_processor skips made_for_you jobs. Used for admin-driven
|
||||
# batches (e.g. KaraokeHunt outreach) that must wait at review indefinitely.
|
||||
"made_for_you",
|
||||
}
|
||||
|
||||
|
||||
@@ -631,7 +635,7 @@ async def clear_audio_search_cache(
|
||||
logger.debug(f"Skipping flacfetch cache clear - missing artist ({artist}) or title ({title})")
|
||||
|
||||
logger.info(
|
||||
f"Admin {auth_data[0]} cleared audio search cache for job {job_id}. "
|
||||
f"Admin {auth_data.user_email} cleared audio search cache for job {job_id}. "
|
||||
f"Cleared {results_count} results. Status changed from {previous_status} to pending. "
|
||||
f"Flacfetch cache cleared: {flacfetch_cache_cleared}"
|
||||
)
|
||||
@@ -681,7 +685,7 @@ async def reset_worker_state(
|
||||
job_manager.update_state_data(job_id, 'render_progress', {'stage': 'pending'})
|
||||
job_manager.update_state_data(job_id, 'screens_progress', {'stage': 'pending'})
|
||||
|
||||
logger.info(f"Admin {auth_data[0]} reset worker state for job {job_id}")
|
||||
logger.info(f"Admin {auth_data.user_email} reset worker state for job {job_id}")
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
@@ -714,7 +718,7 @@ async def clear_all_flacfetch_cache(
|
||||
try:
|
||||
deleted_count = await flacfetch_client.clear_all_cache()
|
||||
logger.info(
|
||||
f"Admin {auth_data[0]} cleared all flacfetch cache. "
|
||||
f"Admin {auth_data.user_email} cleared all flacfetch cache. "
|
||||
f"Deleted {deleted_count} entries."
|
||||
)
|
||||
return ClearAllCacheResponse(
|
||||
@@ -994,6 +998,13 @@ async def update_job(
|
||||
f"no account existed, created one"
|
||||
)
|
||||
|
||||
# A non-bool would silently break the stale-review exemption check.
|
||||
if "made_for_you" in updates and not isinstance(updates["made_for_you"], bool):
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="made_for_you must be a boolean",
|
||||
)
|
||||
|
||||
# The executor treats any value other than "auto" as an enforcement blocker,
|
||||
# so a typo (e.g. "always-review") would silently force human review.
|
||||
if "review_mode" in updates and updates["review_mode"] not in ("auto", "always_review"):
|
||||
@@ -2162,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
|
||||
# =============================================================================
|
||||
@@ -4191,6 +4237,52 @@ def list_user_feedback(
|
||||
)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Requests board — full request history (admin view)
|
||||
# =============================================================================
|
||||
|
||||
class CommunityRequestItem(BaseModel):
|
||||
"""A requests-board song request, any status, for the admin history view."""
|
||||
id: str
|
||||
artist: str
|
||||
title: str
|
||||
status: str
|
||||
submitted_by: str
|
||||
owner_email: Optional[str] = None
|
||||
vote_count: int
|
||||
job_id: Optional[str] = None
|
||||
youtube_url: Optional[str] = None
|
||||
review_state: Optional[str] = None
|
||||
created_at: Optional[str] = None
|
||||
picked_at: Optional[str] = None
|
||||
|
||||
|
||||
class CommunityRequestListResponse(BaseModel):
|
||||
requests: List[CommunityRequestItem]
|
||||
|
||||
|
||||
@router.get("/community-requests", response_model=CommunityRequestListResponse)
|
||||
async def list_community_requests(
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
|
||||
):
|
||||
"""Full history of requests-board submissions across every status — who asked,
|
||||
how it was voted, which job made it, and where it landed on YouTube."""
|
||||
from backend.services.song_request_service import get_song_request_service
|
||||
service = get_song_request_service()
|
||||
items = [
|
||||
CommunityRequestItem(
|
||||
id=r.id, artist=r.artist, title=r.title, status=r.status,
|
||||
submitted_by=r.submitted_by, owner_email=r.owner_email,
|
||||
vote_count=r.vote_count, job_id=r.job_id, youtube_url=r.youtube_url,
|
||||
review_state=r.review_state,
|
||||
created_at=r.created_at.isoformat() if r.created_at else None,
|
||||
picked_at=r.picked_at.isoformat() if r.picked_at else None,
|
||||
)
|
||||
for r in service.list_all()
|
||||
]
|
||||
return CommunityRequestListResponse(requests=items)
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Requests board — existing-community-version review queue
|
||||
# =============================================================================
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
"""POST /api/client-events — persistent telemetry for user-visible degradation.
|
||||
|
||||
Records every time the frontend shows a user a degraded-service surface (the
|
||||
orange "trouble reaching our servers" banner, the stronger "temporarily
|
||||
unavailable" error, a failed lyrics load, a slow/failed waveform), with enough
|
||||
metadata to review frequency and context later. Two sinks per event:
|
||||
|
||||
1. A structured INFO log line (``client_event type=…``) — queryable in Cloud
|
||||
Logging / Log Analytics alongside backend symptoms from the same window.
|
||||
2. A Firestore doc in ``client_events`` — survives log retention, cheap to
|
||||
aggregate for "how often are users seeing this?" reviews.
|
||||
|
||||
Unauthenticated (review-token users must be able to report) and rate-limited
|
||||
per IP, mirroring /api/client-errors. The limiter is process-local, so the
|
||||
effective ceiling is 120/min/IP × live instances — acceptable for this threat
|
||||
model (non-malicious browsers, 60s client-side per-type throttle); Cloudflare's
|
||||
zone-wide rate limit sits in front as a flood backstop. Events are dropped,
|
||||
never queued, when the limiter trips — telemetry, not a delivery guarantee.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Literal, Optional
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
from backend.services.error_monitor.frontend_ingestion import (
|
||||
RateLimiter,
|
||||
is_bot_user_agent,
|
||||
sanitize_url,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter(prefix="/client-events", tags=["client-events"])
|
||||
|
||||
# Sized for a legitimate worst case from ONE IP: a many-tab burst (e.g. 16 review
|
||||
# tabs at once) where every tab reports a banner + a waveform event — that must be
|
||||
# fully recorded, not self-suppressed. Each tab throttles per-type client-side.
|
||||
_limiter = RateLimiter(max_per_minute=120)
|
||||
_db_singleton = None
|
||||
|
||||
# The full closed set of reportable events. Reject anything else so the
|
||||
# collection stays reviewable (no free-form types accumulating).
|
||||
EventType = Literal[
|
||||
"banner_reconnecting",
|
||||
"banner_unavailable",
|
||||
"lyrics_load_failed",
|
||||
"waveform_slow",
|
||||
"waveform_failed",
|
||||
]
|
||||
|
||||
|
||||
def _get_db():
|
||||
global _db_singleton
|
||||
if _db_singleton is None:
|
||||
from google.cloud import firestore # type: ignore[import]
|
||||
|
||||
_db_singleton = firestore.Client(project="nomadkaraoke")
|
||||
return _db_singleton
|
||||
|
||||
|
||||
class ClientEventPayload(BaseModel):
|
||||
type: EventType
|
||||
url: str = Field("", max_length=2048)
|
||||
job_id: Optional[str] = Field(None, max_length=64)
|
||||
user_email: Optional[str] = Field(None, max_length=320)
|
||||
locale: str = Field("en", max_length=10)
|
||||
release: str = Field("", max_length=64)
|
||||
# Small free-form context (stall age, http status, elapsed ms, probe state…).
|
||||
# Size-capped server-side; values are stored as-is.
|
||||
detail: Optional[dict] = None
|
||||
|
||||
@field_validator("url", "locale", "release")
|
||||
@classmethod
|
||||
def strip(cls, v: str) -> str:
|
||||
return (v or "").strip()
|
||||
|
||||
|
||||
def _capped_detail(detail: Optional[dict]) -> dict[str, Any]:
|
||||
"""Keep detail reviewable: at most 12 keys, scalar-ish values, short strings."""
|
||||
if not isinstance(detail, dict):
|
||||
return {}
|
||||
out: dict[str, Any] = {}
|
||||
for key, value in list(detail.items())[:12]:
|
||||
k = str(key)[:40]
|
||||
if isinstance(value, (int, float, bool)) or value is None:
|
||||
out[k] = value
|
||||
else:
|
||||
out[k] = str(value)[:200]
|
||||
return out
|
||||
|
||||
|
||||
@router.post("", status_code=202)
|
||||
def report_client_event(payload: ClientEventPayload, request: Request) -> dict:
|
||||
client_ip = request.client.host if request.client else "unknown"
|
||||
if not _limiter.allow(client_ip, time.monotonic()):
|
||||
raise HTTPException(status_code=429, detail="too many events")
|
||||
|
||||
user_agent = request.headers.get("user-agent", "")[:1024]
|
||||
if is_bot_user_agent(user_agent):
|
||||
return {"status": "ignored"}
|
||||
|
||||
event = {
|
||||
"type": payload.type,
|
||||
"url": sanitize_url(payload.url),
|
||||
"job_id": payload.job_id,
|
||||
"user_email": payload.user_email,
|
||||
"locale": payload.locale,
|
||||
"release": payload.release,
|
||||
"user_agent": user_agent,
|
||||
"detail": _capped_detail(payload.detail),
|
||||
"created_at": datetime.now(timezone.utc),
|
||||
}
|
||||
|
||||
# Sink 1: structured log line — correlate with backend symptoms in Logging.
|
||||
logger.info(
|
||||
"client_event type=%s job_id=%s user=%s url=%s release=%s detail=%s",
|
||||
event["type"],
|
||||
event["job_id"],
|
||||
event["user_email"],
|
||||
event["url"],
|
||||
event["release"],
|
||||
event["detail"],
|
||||
)
|
||||
|
||||
# Sink 2: Firestore — best-effort; telemetry must never error back to users.
|
||||
try:
|
||||
_get_db().collection("client_events").add(event)
|
||||
except Exception:
|
||||
logger.exception("Failed to persist client event (non-fatal)")
|
||||
|
||||
return {"status": "recorded"}
|
||||
@@ -13,6 +13,7 @@ abuse posture identical to the rest of the review surface: you can only warm
|
||||
the shared encoding VM if you already have review access to a real job.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from typing import Tuple
|
||||
from fastapi import APIRouter, Depends
|
||||
@@ -56,7 +57,13 @@ async def warmup_encoding_worker(
|
||||
reviewer previews a render. ``job_id`` scopes auth to the job under review.
|
||||
"""
|
||||
try:
|
||||
result = manager.ensure_primary_running()
|
||||
# ensure_primary_running does Firestore reads + GCE compute-API calls
|
||||
# (instances.get / instances.start) that can take 10s+. Run it off the
|
||||
# event loop: on the single-process server a sync call here froze the
|
||||
# WHOLE instance for ~11s on every review-page open with a cold VM,
|
||||
# stalling that same page's audio/lyrics requests behind it
|
||||
# (2026-09-19, follow-up to the concurrent-load investigation).
|
||||
result = await asyncio.to_thread(manager.ensure_primary_running)
|
||||
if result["started"]:
|
||||
logger.info(f"Started encoding worker VM: {result['vm_name']}")
|
||||
return result
|
||||
@@ -89,7 +96,8 @@ async def heartbeat_encoding_worker(
|
||||
job under review.
|
||||
"""
|
||||
try:
|
||||
manager.update_activity()
|
||||
# Sync Firestore write — keep it off the event loop (see warmup above).
|
||||
await asyncio.to_thread(manager.update_activity)
|
||||
return {"status": "ok"}
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to update encoding worker heartbeat: {e}")
|
||||
|
||||
@@ -185,6 +185,25 @@ async def trigger_audio_worker(
|
||||
)
|
||||
|
||||
|
||||
@router.post("/jobs/{job_id}/auto-approval-eval")
|
||||
async def trigger_auto_approval_eval(
|
||||
job_id: str,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
):
|
||||
"""
|
||||
Re-run the auto-approval evaluation on a job parked at AWAITING_REVIEW
|
||||
(admin only). Normally scoring runs from the screens/audio workers; this
|
||||
endpoint lets an admin re-evaluate after conditions change (e.g. a batch
|
||||
job's made_for_you enforcement blocker was lifted). Fail-safe: anything
|
||||
short of fully confident leaves the job in review untouched.
|
||||
"""
|
||||
from backend.services.auto_approval.executor import maybe_auto_complete_review
|
||||
|
||||
logger.info(f"[job:{job_id}] admin auto-approval eval requested")
|
||||
result = await maybe_auto_complete_review(job_id, trigger="admin_eval")
|
||||
return {"job_id": job_id, **result}
|
||||
|
||||
|
||||
@router.post("/workers/lyrics", response_model=WorkerResponse)
|
||||
async def trigger_lyrics_worker(
|
||||
request: WorkerRequest,
|
||||
@@ -665,6 +684,30 @@ async def community_daily_pick_endpoint(
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.post("/community-requests/reconcile")
|
||||
async def community_requests_reconcile_endpoint(
|
||||
http_request: Request,
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
):
|
||||
"""Reconcile community picks whose video is already live on YouTube but whose
|
||||
request is still ``in_progress`` (publish fan-out never fired for them).
|
||||
|
||||
Idempotent safety net / backfill: advances each to ``published`` and fans out
|
||||
voter emails. Safe to call any time.
|
||||
"""
|
||||
from backend.services.community_publish import reconcile_community_publishes
|
||||
|
||||
logger.info("COMMUNITY_REQUESTS_RECONCILE starting")
|
||||
add_span_attribute("operation", "community_requests_reconcile")
|
||||
try:
|
||||
result = await reconcile_community_publishes()
|
||||
logger.info(f"COMMUNITY_REQUESTS_RECONCILE complete: {result}")
|
||||
return result
|
||||
except Exception as e:
|
||||
logger.exception(f"COMMUNITY_REQUESTS_RECONCILE failed: {e}")
|
||||
raise HTTPException(status_code=500, detail=str(e))
|
||||
|
||||
|
||||
@router.post("/community-handoffs")
|
||||
async def community_handoffs_endpoint(
|
||||
http_request: Request,
|
||||
@@ -1035,11 +1078,47 @@ async def recover_stuck_jobs(
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] render re-trigger failed: {e}")
|
||||
|
||||
# --- DOWNLOADING with lyrics done but screens never triggered: lost screens trigger ---
|
||||
# The lyrics worker triggers screen generation once transcription completes
|
||||
# (audio separation is decoupled). If that dispatch is lost — historically a
|
||||
# fire-and-forget task cancelled on Cloud Run Job loop teardown, now awaited,
|
||||
# but a Cloud Tasks enqueue can still fail — the job sits at `downloading` with
|
||||
# lyrics_complete=True and never advances, with no error. Re-trigger is
|
||||
# idempotent (advance_to_screens_if_ready status-guards + the screens worker
|
||||
# no-ops a duplicate). Mirrors the REVIEW_COMPLETE lost-render recovery above.
|
||||
screens_retriggered = []
|
||||
# Bound the scan so a large active DOWNLOADING population can't consume the
|
||||
# request deadline / Firestore reads before the per-tick re-trigger cap kicks
|
||||
# in. DOWNLOADING is a transient processing state (jobs move through in
|
||||
# minutes), so this ceiling is far above any realistic concurrent population.
|
||||
dl_query = jobs_ref.where(
|
||||
filter=FieldFilter("status", "==", JobStatus.DOWNLOADING.value)
|
||||
).limit(SCREENS_RECOVERY_SCAN_LIMIT).stream()
|
||||
for doc in dl_query:
|
||||
if len(screens_retriggered) >= SCREENS_RETRIGGERS_PER_TICK:
|
||||
break
|
||||
job_id = (doc.to_dict() or {}).get("job_id", doc.id)
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
continue
|
||||
if not _prep_screens_stalled(job):
|
||||
continue
|
||||
logger.warning(
|
||||
f"[job:{job_id}] DOWNLOADING stalled >10 min with lyrics complete but "
|
||||
"no screens — re-triggering"
|
||||
)
|
||||
try:
|
||||
if await job_manager.advance_to_screens_if_ready(job_id):
|
||||
screens_retriggered.append(job_id)
|
||||
except Exception as e:
|
||||
logger.warning(f"[job:{job_id}] screens re-trigger failed: {e}")
|
||||
|
||||
logger.info(
|
||||
f"RECOVER_STUCK_JOBS complete: recovered={len(recovered)} "
|
||||
f"download_parked={len(download_parked)} download_retried={len(download_retried)} "
|
||||
f"download_timed_out={len(download_timed_out)} reparked={len(reparked)} "
|
||||
f"render_retriggered={len(render_retriggered)}"
|
||||
f"render_retriggered={len(render_retriggered)} "
|
||||
f"screens_retriggered={len(screens_retriggered)}"
|
||||
)
|
||||
add_span_event("recovery_complete", {
|
||||
"recovered_count": len(recovered),
|
||||
@@ -1060,11 +1139,45 @@ async def recover_stuck_jobs(
|
||||
"reparked_render_count": len(reparked),
|
||||
"render_retriggered_jobs": render_retriggered,
|
||||
"render_retriggered_count": len(render_retriggered),
|
||||
"screens_retriggered_jobs": screens_retriggered,
|
||||
"screens_retriggered_count": len(screens_retriggered),
|
||||
}
|
||||
|
||||
|
||||
REVIEW_COMPLETE_STALL_SECONDS = 10 * 60 # render normally starts within seconds
|
||||
RENDER_RETRIGGERS_PER_TICK = 10 # bound the blast radius per 5-min tick
|
||||
PREP_SCREENS_STALL_SECONDS = 10 * 60 # screens normally start within seconds of lyrics done
|
||||
SCREENS_RETRIGGERS_PER_TICK = 10 # bound the blast radius per 5-min tick
|
||||
SCREENS_RECOVERY_SCAN_LIMIT = 500 # cap DOWNLOADING docs scanned per tick (transient state)
|
||||
|
||||
|
||||
def _job_updated_age_seconds(job):
|
||||
"""Seconds since a job's ``updated_at``, or None if unavailable/unparseable."""
|
||||
updated_at = getattr(job, "updated_at", None)
|
||||
if updated_at is None:
|
||||
return None
|
||||
from datetime import datetime, timezone as _tz
|
||||
now = datetime.now(_tz.utc)
|
||||
if updated_at.tzinfo is None:
|
||||
now = datetime.utcnow()
|
||||
try:
|
||||
return (now - updated_at).total_seconds()
|
||||
except TypeError:
|
||||
return None
|
||||
|
||||
|
||||
def _prep_screens_stalled(job) -> bool:
|
||||
"""True when a DOWNLOADING job has lyrics complete but has sat >10 min without
|
||||
advancing to screen generation — i.e. the screens trigger was lost.
|
||||
|
||||
While audio separation is still running it keeps ``updated_at`` fresh, so this
|
||||
only fires once the job has genuinely gone quiet (both prep workers done, no
|
||||
screens dispatch), which is exactly the orphaned-trigger signature.
|
||||
"""
|
||||
if not (job.state_data or {}).get("lyrics_complete", False):
|
||||
return False
|
||||
age = _job_updated_age_seconds(job)
|
||||
return age is not None and age > PREP_SCREENS_STALL_SECONDS
|
||||
|
||||
|
||||
def _review_complete_stalled(job) -> bool:
|
||||
|
||||
@@ -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
|
||||
|
||||
+392
-103
@@ -13,16 +13,20 @@ Usage:
|
||||
The baseApiUrl includes the job_id, and all endpoints are relative to that.
|
||||
"""
|
||||
import asyncio
|
||||
import concurrent.futures
|
||||
import logging
|
||||
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 fastapi.responses import JSONResponse, RedirectResponse, Response
|
||||
from google.cloud.exceptions import NotFound
|
||||
from google.cloud.firestore_v1.field_path import FieldPath
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
@@ -34,10 +38,12 @@ from backend.services.job_logging import job_log_context, JobLogger
|
||||
from backend.services.tracing import create_span, add_span_attribute, add_span_event
|
||||
from backend.services.encoding_service import get_encoding_service
|
||||
from backend.api.dependencies import require_auth, require_review_auth
|
||||
from backend.utils.stems import vocals_stem_path as _vocals_stem_path
|
||||
from backend.services.auth_service import UserType
|
||||
from backend.config import get_settings
|
||||
from backend.i18n import t, get_locale_from_request
|
||||
from backend.services.duration_reconciliation import reconcile_and_maybe_pause
|
||||
from backend.utils.audio_filenames import local_audio_filename
|
||||
|
||||
from pydantic import BaseModel as _PydBaseModel
|
||||
from backend.services.custom_lyrics_service import (
|
||||
@@ -242,7 +248,7 @@ def _prepare_preview_inputs(job, temp_dir: str, storage, is_duet: bool):
|
||||
with open(corrections_path, 'r', encoding='utf-8') as f:
|
||||
original_data = json.load(f)
|
||||
|
||||
audio_path = os.path.join(temp_dir, "audio.flac")
|
||||
audio_path = os.path.join(temp_dir, local_audio_filename(job.input_media_gcs_path, "audio"))
|
||||
storage.download_file(job.input_media_gcs_path, audio_path)
|
||||
download_span.set_attribute("audio_gcs_path", job.input_media_gcs_path)
|
||||
|
||||
@@ -274,12 +280,65 @@ def _prepare_preview_inputs(job, temp_dir: str, storage, is_duet: bool):
|
||||
return correction_result, audio_path, output_config
|
||||
|
||||
|
||||
def _render_preview_locally(job, updated_data: Dict[str, Any], is_duet: bool) -> str:
|
||||
"""Render the full 360p preview locally and upload it to GCS.
|
||||
# At most this many local preview renders at once. The local path runs ffmpeg
|
||||
# ON the 2-vCPU API instance (it's the fallback when GCE preview encoding is
|
||||
# down); unbounded, a GCE outage plus a few users clicking Preview saturates
|
||||
# the instance's CPU, stalls the health probe, and shows everyone the orange
|
||||
# "trouble reaching our servers" banner. Serializing renders keeps the API
|
||||
# responsive — previews just queue a little longer during an encoder outage.
|
||||
_LOCAL_PREVIEW_MAX_CONCURRENCY = max(1, int(os.getenv("LOCAL_PREVIEW_MAX_CONCURRENCY", "1")))
|
||||
_LOCAL_PREVIEW_QUEUE_TIMEOUT_S = int(os.getenv("LOCAL_PREVIEW_QUEUE_TIMEOUT_S", "900"))
|
||||
_local_preview_slots = asyncio.Semaphore(_LOCAL_PREVIEW_MAX_CONCURRENCY)
|
||||
# Dedicated executor: admitted renders never compete with the shared to_thread
|
||||
# pool, and its concurrent.futures-level done callbacks fire when the WORKER
|
||||
# THREAD finishes — the asyncio wrapper future can be "cancelled" while the
|
||||
# thread is still running, so it must not drive the slot release.
|
||||
_local_preview_executor = concurrent.futures.ThreadPoolExecutor(
|
||||
max_workers=_LOCAL_PREVIEW_MAX_CONCURRENCY, thread_name_prefix="local-preview"
|
||||
)
|
||||
|
||||
Blocking (downloads + ffmpeg) — call via asyncio.to_thread. Used when GCE
|
||||
preview encoding is disabled and as the fallback when it fails.
|
||||
|
||||
async def _render_preview_locally(job, updated_data: Dict[str, Any], is_duet: bool) -> str:
|
||||
"""Render the full 360p preview locally (bounded) and upload it to GCS.
|
||||
|
||||
Used when GCE preview encoding is disabled and as the fallback when it
|
||||
fails. Admission happens HERE on the event loop (async semaphore +
|
||||
wait_for) so queued renders wait as cheap coroutines — only an ADMITTED
|
||||
render occupies a thread-pool worker for its blocking downloads + ffmpeg.
|
||||
"""
|
||||
try:
|
||||
await asyncio.wait_for(
|
||||
_local_preview_slots.acquire(), timeout=_LOCAL_PREVIEW_QUEUE_TIMEOUT_S
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
raise RuntimeError(
|
||||
"Local preview encoder is busy (waited "
|
||||
f"{_LOCAL_PREVIEW_QUEUE_TIMEOUT_S}s for a slot) — try again shortly"
|
||||
)
|
||||
def _run_render():
|
||||
return _render_preview_locally_unbounded(job, updated_data, is_duet)
|
||||
|
||||
loop = asyncio.get_running_loop()
|
||||
worker_future = _local_preview_executor.submit(_run_render)
|
||||
|
||||
def _release_slot(fut: "concurrent.futures.Future") -> None:
|
||||
# Runs when the WORKER THREAD actually finishes. Releasing from an
|
||||
# async finally (or the asyncio wrapper's callback) would free the slot
|
||||
# the moment the awaiting request is cancelled — while the ffmpeg
|
||||
# render thread is still consuming CPU — letting a second render start
|
||||
# and defeating the concurrency bound.
|
||||
if not fut.cancelled():
|
||||
fut.exception() # mark retrieved when the caller was cancelled/abandoned
|
||||
try:
|
||||
loop.call_soon_threadsafe(_local_preview_slots.release)
|
||||
except RuntimeError:
|
||||
pass # loop already closed (shutdown) — nothing left to bound
|
||||
|
||||
worker_future.add_done_callback(_release_slot)
|
||||
return await asyncio.wrap_future(worker_future)
|
||||
|
||||
|
||||
def _render_preview_locally_unbounded(job, updated_data: Dict[str, Any], is_duet: bool) -> str:
|
||||
job_id = job.job_id
|
||||
storage = StorageService()
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
@@ -345,7 +404,7 @@ async def _encode_preview_in_background(
|
||||
logger.warning(f"Job {job_id}: GCE preview encoding failed, falling back to local: {gce_error}")
|
||||
|
||||
try:
|
||||
await asyncio.to_thread(_render_preview_locally, job, updated_data, is_duet)
|
||||
await _render_preview_locally(job, updated_data, is_duet)
|
||||
logger.info(f"Job {job_id}: Preview generated locally after GCE failure: {preview_hash}")
|
||||
except Exception as local_error:
|
||||
logger.error(
|
||||
@@ -410,38 +469,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:
|
||||
results = await asyncio.gather(*url_tasks.values())
|
||||
signed_urls = dict(zip(url_tasks.keys(), results))
|
||||
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:
|
||||
@@ -449,14 +519,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
|
||||
|
||||
@@ -617,7 +687,11 @@ async def get_correction_data(
|
||||
job_manager = JobManager()
|
||||
storage = StorageService()
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
# All Firestore/GCS round-trips in this handler run via to_thread: they're
|
||||
# blocking client-library calls, and on the single-process/single-loop
|
||||
# server anything left on the event loop serializes EVERY in-flight request
|
||||
# behind it under concurrent load (see 2026-09-18 investigation doc).
|
||||
job = await asyncio.to_thread(job_manager.get_job, job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
|
||||
|
||||
@@ -651,7 +725,7 @@ async def get_correction_data(
|
||||
# Try direct path for updated corrections
|
||||
corrections_updated_gcs = f"jobs/{job_id}/lyrics/corrections_updated.json"
|
||||
|
||||
if corrections_updated_gcs and storage.file_exists(corrections_updated_gcs):
|
||||
if corrections_updated_gcs and await asyncio.to_thread(storage.file_exists, corrections_updated_gcs):
|
||||
corrections_gcs = corrections_updated_gcs
|
||||
logger.info(f"Job {job_id}: Using updated corrections from previous review")
|
||||
else:
|
||||
@@ -659,7 +733,7 @@ async def get_correction_data(
|
||||
corrections_gcs = job.file_urls.get('lyrics', {}).get('corrections')
|
||||
if not corrections_gcs:
|
||||
corrections_gcs = f"jobs/{job_id}/lyrics/corrections.json"
|
||||
if not storage.file_exists(corrections_gcs):
|
||||
if not await asyncio.to_thread(storage.file_exists, corrections_gcs):
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail=t("en", "review.correctionsNotFound")
|
||||
@@ -667,7 +741,7 @@ async def get_correction_data(
|
||||
|
||||
# Download and return corrections data
|
||||
try:
|
||||
corrections_data = storage.download_json(corrections_gcs)
|
||||
corrections_data = await asyncio.to_thread(storage.download_json, corrections_gcs)
|
||||
|
||||
# Add audio hash for the frontend
|
||||
audio_hash = _get_audio_hash(job_id)
|
||||
@@ -684,10 +758,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)
|
||||
@@ -702,30 +775,31 @@ 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
|
||||
analysis_files = job.file_urls.get('analysis', {})
|
||||
waveform_url = analysis_files.get('backing_vocals_waveform')
|
||||
if waveform_url:
|
||||
corrections_data['backing_vocals_waveform_url'] = (
|
||||
_dev_audio_url(job_id, waveform_url, str(request.base_url)) if _dev_audio_proxy_enabled()
|
||||
else storage.generate_signed_url(waveform_url, expiration_minutes=120)
|
||||
)
|
||||
# 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:
|
||||
job_manager.transition_to_state(
|
||||
await asyncio.to_thread(
|
||||
job_manager.transition_to_state,
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.IN_REVIEW,
|
||||
message="User opened combined review interface"
|
||||
message="User opened combined review interface",
|
||||
)
|
||||
|
||||
# Replay: attach the reviewer's ordered edit_log so the UI can show the
|
||||
# sequence of actions (AI-accept/reject/manual/timing) beside the final state.
|
||||
if replay:
|
||||
edit_log = _load_edit_log(job, storage)
|
||||
edit_log = await asyncio.to_thread(_load_edit_log, job, storage)
|
||||
post_ai_segments = None
|
||||
try:
|
||||
raw_data = storage.download_json(f"jobs/{job_id}/lyrics/corrections.json")
|
||||
raw_data = await asyncio.to_thread(
|
||||
storage.download_json, f"jobs/{job_id}/lyrics/corrections.json"
|
||||
)
|
||||
post_ai_segments = _reconstruct_post_ai_segments(
|
||||
raw_data.get('corrected_segments', []), edit_log
|
||||
)
|
||||
@@ -753,33 +827,36 @@ async def get_correction_data(
|
||||
@router.get("/{job_id}/audio/vocals")
|
||||
async def get_vocals_audio(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""Stream the vocals audio file for playback."""
|
||||
return await _stream_audio(job_id, stem="vocals")
|
||||
return await _stream_audio(job_id, request, stem="vocals")
|
||||
|
||||
|
||||
@router.get("/{job_id}/audio/{audio_hash}")
|
||||
async def get_audio_with_hash(
|
||||
job_id: str,
|
||||
audio_hash: str,
|
||||
request: Request,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""Stream the audio file for playback (with hash parameter)."""
|
||||
return await _stream_audio(job_id)
|
||||
return await _stream_audio(job_id, request)
|
||||
|
||||
|
||||
@router.get("/{job_id}/audio/")
|
||||
@router.get("/{job_id}/audio")
|
||||
async def get_audio_no_hash(
|
||||
job_id: str,
|
||||
request: Request,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""Stream the audio file for playback (without hash parameter)."""
|
||||
return await _stream_audio(job_id)
|
||||
return await _stream_audio(job_id, request)
|
||||
|
||||
|
||||
async def _stream_audio(job_id: str, stem: Literal["input"] | Literal["vocals"] = "input"):
|
||||
async def _stream_audio(job_id: str, request: Optional[Request] = None, stem: Literal["input"] | Literal["vocals"] = "input"):
|
||||
"""
|
||||
Redirect to a signed GCS URL for audio playback in the review interface.
|
||||
|
||||
@@ -790,7 +867,7 @@ async def _stream_audio(job_id: str, stem: Literal["input"] | Literal["vocals"]
|
||||
|
||||
job_manager = JobManager()
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
job = await asyncio.to_thread(job_manager.get_job, job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
|
||||
|
||||
@@ -798,18 +875,7 @@ async def _stream_audio(job_id: str, stem: Literal["input"] | Literal["vocals"]
|
||||
if stem == "input":
|
||||
audio_gcs_path = job.input_media_gcs_path
|
||||
elif stem == "vocals":
|
||||
stems = job.file_urls.get("stems", {}) if job.file_urls else {}
|
||||
# Stem keys vary by separation model. We want the full vocal mix
|
||||
# (lead + backing) so every word can be lined up against the waveform:
|
||||
# - "vocals" : full vocal from a 2-stem split (rare)
|
||||
# - "vocals_clean" : full vocal from the primary vocal/instrumental
|
||||
# split (present on essentially all cloud jobs)
|
||||
# - "lead_vocals" : last-resort fallback (misses backing lines)
|
||||
# Use .get() so a missing key yields a clean 404 below, not a KeyError/500.
|
||||
for key in ("vocals", "vocals_clean", "lead_vocals"):
|
||||
if stems.get(key):
|
||||
audio_gcs_path = stems[key]
|
||||
break
|
||||
audio_gcs_path = _vocals_stem_path(job)
|
||||
if not audio_gcs_path:
|
||||
# Audio separation is decoupled from the lyrics-review critical path, so a
|
||||
# user can open review before the vocal stems have been uploaded (the stem
|
||||
@@ -834,8 +900,13 @@ async def _stream_audio(job_id: str, stem: Literal["input"] | Literal["vocals"]
|
||||
# the (~3 MB) bytes from the API keeps it same-origin to api.* whose
|
||||
# CORS already allows the frontend. <audio> playback (stem="input")
|
||||
# doesn't need CORS, so it keeps the lighter redirect below.
|
||||
audio_bytes, content_type = await transcoding.get_review_audio_bytes_async(audio_gcs_path)
|
||||
# Cached in the bounded LRU (same as /instrumental-audio) with
|
||||
# single-flight misses, so ten tabs of the same job — or a play after
|
||||
# the waveform decode — share one GCS fetch instead of N.
|
||||
audio_bytes, content_type = await _get_review_audio(audio_gcs_path, transcoding)
|
||||
logger.info(f"Job {job_id}: Proxying {len(audio_bytes)}B vocals audio for waveform")
|
||||
if request is not None:
|
||||
return _ranged_response(request, audio_bytes, content_type)
|
||||
return Response(content=audio_bytes, media_type=content_type)
|
||||
|
||||
if _dev_audio_proxy_enabled():
|
||||
@@ -859,11 +930,94 @@ 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 capped by BOTH entry count and
|
||||
# total retained bytes (the transcode-failure fallback can serve a 35+ MB raw FLAC — a
|
||||
# count-only LRU of those would OOM a 2 GiB instance). Keyed by GCS path, guarded by a
|
||||
# lock for thread safety.
|
||||
_REVIEW_AUDIO_CACHE_MAX = int(os.getenv("REVIEW_AUDIO_CACHE_MAX", "16"))
|
||||
_REVIEW_AUDIO_CACHE_MAX_BYTES = int(os.getenv("REVIEW_AUDIO_CACHE_MAX_BYTES", str(192 * 1024 * 1024)))
|
||||
_review_audio_cache: "OrderedDict[str, Tuple[bytes, str]]" = OrderedDict()
|
||||
_review_audio_cache_bytes = 0
|
||||
_review_audio_cache_lock = threading.Lock()
|
||||
|
||||
# Single-flight coordination for cache misses: N tabs of the same job must share ONE
|
||||
# transcode/GCS-download instead of duplicating it N times. Keyed by GCS path; only
|
||||
# ever touched from the event loop (async handlers), so no extra lock is needed.
|
||||
_review_audio_inflight: Dict[str, "asyncio.Future[Tuple[bytes, str]]"] = {}
|
||||
|
||||
|
||||
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:
|
||||
global _review_audio_cache_bytes
|
||||
size = len(value[0])
|
||||
if size > _REVIEW_AUDIO_CACHE_MAX_BYTES // 4:
|
||||
# One oversized fallback (raw FLAC) must not evict the whole working set.
|
||||
return
|
||||
with _review_audio_cache_lock:
|
||||
old = _review_audio_cache.pop(path, None)
|
||||
if old is not None:
|
||||
_review_audio_cache_bytes -= len(old[0])
|
||||
_review_audio_cache[path] = value
|
||||
_review_audio_cache_bytes += size
|
||||
while _review_audio_cache and (
|
||||
len(_review_audio_cache) > _REVIEW_AUDIO_CACHE_MAX
|
||||
or _review_audio_cache_bytes > _REVIEW_AUDIO_CACHE_MAX_BYTES
|
||||
):
|
||||
_, evicted = _review_audio_cache.popitem(last=False) # least-recently-used
|
||||
_review_audio_cache_bytes -= len(evicted[0])
|
||||
|
||||
|
||||
async def _get_review_audio(source_gcs_path: str, transcoding) -> Tuple[bytes, str]:
|
||||
"""Cached, single-flight fetch of transcoded review-audio bytes.
|
||||
|
||||
Cache hit → served from memory. Miss → exactly one caller runs the
|
||||
transcode/download; concurrent callers for the same path await its result
|
||||
(success and failure are both shared). Used by /audio/vocals and
|
||||
/instrumental-audio.
|
||||
"""
|
||||
cached = _review_audio_cache_get(source_gcs_path)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
inflight = _review_audio_inflight.get(source_gcs_path)
|
||||
if inflight is not None:
|
||||
return await asyncio.shield(inflight)
|
||||
|
||||
future: "asyncio.Future[Tuple[bytes, str]]" = asyncio.get_running_loop().create_future()
|
||||
_review_audio_inflight[source_gcs_path] = future
|
||||
try:
|
||||
value = await transcoding.get_review_audio_bytes_async(source_gcs_path)
|
||||
_review_audio_cache_put(source_gcs_path, value)
|
||||
future.set_result(value)
|
||||
return value
|
||||
except Exception as e:
|
||||
future.set_exception(e)
|
||||
# The originator re-raises; mark the future's exception as observed so
|
||||
# an awaiter-less failure doesn't log "exception was never retrieved".
|
||||
future.exception()
|
||||
raise
|
||||
finally:
|
||||
_review_audio_inflight.pop(source_gcs_path, None)
|
||||
|
||||
|
||||
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)
|
||||
range_header = request.headers.get("range")
|
||||
headers = {"Accept-Ranges": "bytes"}
|
||||
# Let the browser reuse review audio across reloads/tabs for a few minutes
|
||||
# instead of re-pulling multi-MB bodies through the API. Short-lived because
|
||||
# audio-edit can replace a stem's bytes at the same URL.
|
||||
headers = {"Accept-Ranges": "bytes", "Cache-Control": "private, max-age=600"}
|
||||
if range_header and range_header.startswith("bytes="):
|
||||
try:
|
||||
spec = range_header.split("=", 1)[1].split(",")[0].strip()
|
||||
@@ -916,6 +1070,54 @@ 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 = await asyncio.to_thread(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:
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
transcoding = AudioTranscodingService(storage_service=StorageService())
|
||||
data, content_type = await _get_review_audio(source_gcs_path, transcoding)
|
||||
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,
|
||||
@@ -1049,16 +1251,24 @@ async def complete_review(
|
||||
message=f"Review complete (instrumental: {instrumental_selection}), rendering video"
|
||||
)
|
||||
|
||||
# Trigger render video worker
|
||||
# Trigger the render video worker. AWAIT the dispatch (don't fire-and-forget)
|
||||
# so the Cloud Task / Cloud Run Job dispatch is guaranteed enqueued before we
|
||||
# return — a background asyncio task can be dropped if the Cloud Run instance
|
||||
# is recycled right after the response, stranding the job at REVIEW_COMPLETE.
|
||||
# If the dispatch itself fails we DON'T fail the user's approval: the job is
|
||||
# safely at REVIEW_COMPLETE and the recover-stuck-jobs watchdog re-triggers
|
||||
# render for REVIEW_COMPLETE jobs with no render underway within ~5 min.
|
||||
from backend.services.worker_service import get_worker_service
|
||||
worker_service = get_worker_service()
|
||||
|
||||
# Run in background, keep reference to prevent garbage collection
|
||||
task = asyncio.create_task(worker_service.trigger_render_video_worker(job_id))
|
||||
_background_tasks.add(task)
|
||||
task.add_done_callback(_background_tasks.discard)
|
||||
|
||||
logger.info(f"Job {job_id}: Combined review complete, triggered render video worker")
|
||||
try:
|
||||
await worker_service.trigger_render_video_worker(job_id)
|
||||
logger.info(f"Job {job_id}: Combined review complete, render video worker triggered")
|
||||
except Exception as e:
|
||||
logger.error(
|
||||
f"Job {job_id}: render trigger failed after review completion "
|
||||
f"(watchdog will recover): {e}",
|
||||
exc_info=True,
|
||||
)
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
@@ -1707,9 +1917,7 @@ async def generate_preview_video(
|
||||
|
||||
# Local path (GCE preview disabled, or GCE setup failed): render
|
||||
# the full preview synchronously — no cold-start problem, but slow.
|
||||
preview_hash = await asyncio.to_thread(
|
||||
_render_preview_locally, job, updated_data, is_duet
|
||||
)
|
||||
preview_hash = await _render_preview_locally(job, updated_data, is_duet)
|
||||
|
||||
logger.info(f"Job {job_id}: Preview video generated: {preview_hash}")
|
||||
span.set_attribute("preview_hash", preview_hash)
|
||||
@@ -1873,22 +2081,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 = await asyncio.to_thread(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}
|
||||
|
||||
|
||||
@@ -1909,7 +2114,7 @@ async def get_instrumental_analysis(
|
||||
job_manager = JobManager()
|
||||
storage = StorageService()
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
job = await asyncio.to_thread(job_manager.get_job, job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
|
||||
|
||||
@@ -1945,8 +2150,15 @@ async def get_instrumental_analysis(
|
||||
for key, src in audio_url_sources.items() if src
|
||||
}
|
||||
if url_tasks:
|
||||
results = await asyncio.gather(*url_tasks.values())
|
||||
audio_urls = dict(zip(url_tasks.keys(), results))
|
||||
# Best-effort per URL (signing is a bounded IAM round-trip): a stall on one
|
||||
# stem yields a null URL the client can retry, not a failed refresh call.
|
||||
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}")
|
||||
audio_urls[key] = None
|
||||
else:
|
||||
audio_urls[key] = res
|
||||
|
||||
# Format response to match InstrumentalAnalysis type
|
||||
return {
|
||||
@@ -1969,6 +2181,76 @@ async def get_instrumental_analysis(
|
||||
}
|
||||
|
||||
|
||||
# Bound how many waveform computations/loads can run at once on an instance.
|
||||
# A cache miss decodes a whole audio file (seconds of CPU); before this bound —
|
||||
# and before the compute moved off the event loop — ~10 concurrent review-page
|
||||
# loads could wedge the single uvicorn event loop and take the whole service
|
||||
# down ("no available instance" aborts; see 2026-09-18 investigation doc).
|
||||
# max(1, …): a zero/negative override would otherwise deadlock every request.
|
||||
_WAVEFORM_MAX_CONCURRENCY = max(1, int(os.getenv("REVIEW_WAVEFORM_MAX_CONCURRENCY", "4")))
|
||||
_waveform_semaphore = asyncio.Semaphore(_WAVEFORM_MAX_CONCURRENCY)
|
||||
|
||||
|
||||
@router.get("/{job_id}/vocals-peaks")
|
||||
async def get_vocals_peaks(
|
||||
job_id: str,
|
||||
peaks_per_second: int = 400,
|
||||
auth_info: Tuple[str, str] = Depends(require_review_auth)
|
||||
):
|
||||
"""
|
||||
Pre-computed peak envelope of the vocal stem (Waveforms review mode).
|
||||
|
||||
Replaces the frontend's download-and-decode of the whole vocals OGG
|
||||
(~7 MB + WebAudio decode) with a ~150 KB JSON, so the per-segment
|
||||
waveform strips paint sub-second on page load. Served from a persistent
|
||||
GCS cache, pre-computed by screens_worker; a miss computes off the event
|
||||
loop, bounded by the shared waveform semaphore. Returns 202 while audio
|
||||
separation is still producing the stem (frontend polls, mirroring
|
||||
/audio/vocals).
|
||||
|
||||
Response: {peaks_b64 (base64 uint8 per bucket), encoding: "u8",
|
||||
peaks_per_second, duration_seconds}.
|
||||
"""
|
||||
from backend.services.audio_analysis_service import AudioAnalysisService
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
peaks_per_second = max(50, min(peaks_per_second, 1000))
|
||||
|
||||
job = await asyncio.to_thread(JobManager().get_job, job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
|
||||
|
||||
vocals_path = _vocals_stem_path(job)
|
||||
if not vocals_path:
|
||||
if not job.state_data.get("audio_complete", False):
|
||||
return Response(status_code=202, headers={"Retry-After": "15"})
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.audioNotFound"))
|
||||
|
||||
try:
|
||||
analysis_service = AudioAnalysisService()
|
||||
async with _waveform_semaphore:
|
||||
payload = await asyncio.to_thread(
|
||||
analysis_service.get_vocals_peaks,
|
||||
vocals_path,
|
||||
job_id,
|
||||
peaks_per_second,
|
||||
AudioTranscodingService(),
|
||||
)
|
||||
return JSONResponse(
|
||||
content={
|
||||
"peaks_b64": payload["peaks_b64"],
|
||||
"encoding": payload.get("encoding", "u8"),
|
||||
"peaks_per_second": payload["peaks_per_second"],
|
||||
"duration_seconds": payload["duration_seconds"],
|
||||
},
|
||||
# Immutable per stem path; short-lived like the audio responses.
|
||||
headers={"Cache-Control": "private, max-age=600"},
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Job {job_id}: Error generating vocals peaks: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=t("en", "review.waveformGenerationError", error=str(e)))
|
||||
|
||||
|
||||
@router.get("/{job_id}/waveform-data")
|
||||
async def get_waveform_data(
|
||||
job_id: str,
|
||||
@@ -1979,12 +2261,16 @@ async def get_waveform_data(
|
||||
Get waveform amplitude data for client-side rendering.
|
||||
|
||||
Returns amplitude values for drawing the waveform in the frontend.
|
||||
Served from a persistent GCS cache (precomputed by screens_worker before
|
||||
the job reaches review); a miss decodes off the event loop, bounded by
|
||||
``_waveform_semaphore``.
|
||||
"""
|
||||
from backend.services.audio_analysis_service import AudioAnalysisService
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
job_manager = JobManager()
|
||||
|
||||
job = job_manager.get_job(job_id)
|
||||
job = await asyncio.to_thread(job_manager.get_job, job_id)
|
||||
if not job:
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
|
||||
|
||||
@@ -2001,11 +2287,14 @@ async def get_waveform_data(
|
||||
|
||||
try:
|
||||
analysis_service = AudioAnalysisService()
|
||||
amplitudes, duration = analysis_service.get_waveform_data(
|
||||
gcs_audio_path=backing_vocals_path,
|
||||
job_id=job_id,
|
||||
num_points=num_points,
|
||||
)
|
||||
async with _waveform_semaphore:
|
||||
amplitudes, duration = await asyncio.to_thread(
|
||||
analysis_service.get_review_waveform,
|
||||
backing_vocals_path,
|
||||
job_id,
|
||||
num_points,
|
||||
AudioTranscodingService(),
|
||||
)
|
||||
|
||||
return {
|
||||
"amplitudes": amplitudes,
|
||||
|
||||
@@ -340,7 +340,13 @@ async def send_magic_link(
|
||||
)
|
||||
|
||||
if not sent:
|
||||
logger.error(f"Failed to send magic link email to {email}")
|
||||
if getattr(email_service, "last_send_suppressed", False):
|
||||
# Benign: the address is Postmark-suppressed (hard bounce / spam /
|
||||
# manual suppression) — typically a junk/placeholder address entered
|
||||
# at the sign-in form. Not an outage, so don't page on it.
|
||||
logger.info(f"Magic link recipient {email} is suppressed by Postmark — skipping send")
|
||||
else:
|
||||
logger.error(f"Failed to send magic link email to {email}")
|
||||
# Don't reveal failure to prevent email enumeration
|
||||
# Still return success
|
||||
|
||||
@@ -363,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,
|
||||
@@ -513,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),
|
||||
)
|
||||
|
||||
|
||||
@@ -703,7 +726,12 @@ async def resend_magic_link_from_token(
|
||||
)
|
||||
|
||||
if not sent:
|
||||
logger.error(f"Failed to resend magic link email to {_mask_email(email)}")
|
||||
if getattr(email_service, "last_send_suppressed", False):
|
||||
logger.info(
|
||||
f"Resend magic link recipient {_mask_email(email)} is suppressed by Postmark — skipping send"
|
||||
)
|
||||
else:
|
||||
logger.error(f"Failed to resend magic link email to {_mask_email(email)}")
|
||||
|
||||
# Stamp the original token so the cooldown applies to subsequent clicks.
|
||||
try:
|
||||
|
||||
+20
-1
@@ -36,7 +36,16 @@ class Settings(BaseSettings):
|
||||
# a sibling prefix in the same Divebar bucket, which kjbox mirrors into NOMAD-vocals-padded/
|
||||
# to power the "Original Vocals" sing-along slider. Same brand gating as the master push.
|
||||
nomad_vocals_guide_gcs_prefix: str = os.getenv("NOMAD_VOCALS_GUIDE_GCS_PREFIX", "files/Nomad Karaoke/vocals-padded")
|
||||
|
||||
|
||||
# KaraokeNerds community catalog: our own daily-refreshed copy of KN's community
|
||||
# (web-only, directly-playable) tracks, written by the authorized `kn-data-sync`
|
||||
# export job. The community-version check reads THIS, never scrapes karaokenerds.com.
|
||||
# Source of truth is BigQuery `karaoke_decide.karaokenerds_community`; the export job
|
||||
# also mirrors it to this gzipped-JSON GCS object, which the backend loads in-process.
|
||||
kn_community_bucket: str = os.getenv("KN_COMMUNITY_BUCKET", "nomadkaraoke-kn-data")
|
||||
kn_community_blob: str = os.getenv("KN_COMMUNITY_BLOB", "community/community-data-latest.json.gz")
|
||||
kn_community_ttl_seconds: int = int(os.getenv("KN_COMMUNITY_TTL_SECONDS", "21600")) # 6h
|
||||
|
||||
# Audio Separator API (for GPU processing)
|
||||
audio_separator_api_url: Optional[str] = os.getenv("AUDIO_SEPARATOR_API_URL")
|
||||
|
||||
@@ -254,6 +263,16 @@ class Settings(BaseSettings):
|
||||
flacfetch_retry_min_wait: float = float(os.getenv("FLACFETCH_RETRY_MIN_WAIT", "10.0")) # seconds
|
||||
flacfetch_retry_max_wait: float = float(os.getenv("FLACFETCH_RETRY_MAX_WAIT", "60.0")) # seconds
|
||||
|
||||
# Search retry settings are much lighter than the download defaults above:
|
||||
# search is called synchronously from user-facing requests that sit behind
|
||||
# Cloudflare's ~100s edge timeout, so there's only room for one quick retry
|
||||
# (worst case: 60s timeout + 1s wait + fast cache-hit retry).
|
||||
flacfetch_search_retry_max_attempts: int = int(os.getenv("FLACFETCH_SEARCH_RETRY_MAX_ATTEMPTS", "2"))
|
||||
flacfetch_search_retry_wait: float = float(os.getenv("FLACFETCH_SEARCH_RETRY_WAIT", "1.0")) # seconds
|
||||
# Total budget across all search attempts, kept under Cloudflare's ~100s edge
|
||||
# deadline so callers get a clean FlacfetchServiceError instead of an edge 524.
|
||||
flacfetch_search_total_timeout: float = float(os.getenv("FLACFETCH_SEARCH_TOTAL_TIMEOUT", "95.0")) # seconds
|
||||
|
||||
# Default distribution settings (can be overridden per-request)
|
||||
default_dropbox_path: Optional[str] = os.getenv("DEFAULT_DROPBOX_PATH")
|
||||
default_gdrive_folder_id: Optional[str] = os.getenv("DEFAULT_GDRIVE_FOLDER_ID")
|
||||
|
||||
+2
-1
@@ -10,7 +10,7 @@ from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from backend.config import settings, validate_production_config
|
||||
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, tenant_admin, tenant_bulk, rate_limits, push, catalog, encoding_worker, client_errors, bulk, parse_titles
|
||||
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, tenant_admin, tenant_bulk, rate_limits, push, catalog, encoding_worker, client_errors, client_events, bulk, parse_titles
|
||||
from backend.services.tracing import setup_tracing, instrument_app, get_current_trace_id
|
||||
from backend.services.structured_logging import setup_structured_logging
|
||||
from backend.services.spacy_preloader import preload_spacy_model
|
||||
@@ -213,6 +213,7 @@ app.include_router(bulk.router, prefix="/api") # Bulk Mode: multi-job submissio
|
||||
from backend.api.routes import requests_board
|
||||
app.include_router(requests_board.router, prefix="/api") # Public song-request voting board
|
||||
app.include_router(client_errors.router, prefix="/api") # Frontend crash reports
|
||||
app.include_router(client_events.router, prefix="/api") # Frontend degradation telemetry (banner/unavailable/waveform events)
|
||||
app.include_router(tenant.router) # Tenant/white-label configuration (no /api prefix, router has it)
|
||||
app.include_router(tenant_admin.router) # Admin tenant provisioning (router has /api prefix)
|
||||
app.include_router(tenant_bulk.router) # Tenant bulk-upload filename analysis (router has /api prefix)
|
||||
|
||||
@@ -12,6 +12,7 @@ import tempfile
|
||||
from typing import Optional
|
||||
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.utils.audio_filenames import local_audio_filename
|
||||
from karaoke_gen.instrumental_review import (
|
||||
AudioAnalyzer,
|
||||
AnalysisResult,
|
||||
@@ -81,7 +82,7 @@ class AudioAnalysisService:
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
# Download audio file
|
||||
local_audio_path = os.path.join(temp_dir, "backing_vocals.flac")
|
||||
local_audio_path = os.path.join(temp_dir, local_audio_filename(gcs_audio_path, "backing_vocals"))
|
||||
self.storage_service.download_file(gcs_audio_path, local_audio_path)
|
||||
|
||||
# Run analysis
|
||||
@@ -132,7 +133,7 @@ class AudioAnalysisService:
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
# Download audio file
|
||||
local_audio_path = os.path.join(temp_dir, "backing_vocals.flac")
|
||||
local_audio_path = os.path.join(temp_dir, local_audio_filename(gcs_audio_path, "backing_vocals"))
|
||||
self.storage_service.download_file(gcs_audio_path, local_audio_path)
|
||||
|
||||
# Run analysis
|
||||
@@ -185,8 +186,8 @@ class AudioAnalysisService:
|
||||
from karaoke_gen.instrumental_review.stem_comparison import compare_stems
|
||||
|
||||
try:
|
||||
local_lead = os.path.join(temp_dir, "lead_vocals.flac")
|
||||
local_vocals = os.path.join(temp_dir, "vocals.flac")
|
||||
local_lead = os.path.join(temp_dir, local_audio_filename(gcs_lead_vocals_path, "lead_vocals"))
|
||||
local_vocals = os.path.join(temp_dir, local_audio_filename(gcs_vocals_path, "vocals"))
|
||||
self.storage_service.download_file(gcs_lead_vocals_path, local_lead)
|
||||
self.storage_service.download_file(gcs_vocals_path, local_vocals)
|
||||
except Exception as e:
|
||||
@@ -231,7 +232,7 @@ class AudioAnalysisService:
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
# Download audio file
|
||||
local_audio_path = os.path.join(temp_dir, "backing_vocals.flac")
|
||||
local_audio_path = os.path.join(temp_dir, local_audio_filename(gcs_audio_path, "backing_vocals"))
|
||||
self.storage_service.download_file(gcs_audio_path, local_audio_path)
|
||||
|
||||
# Generate waveform data
|
||||
@@ -242,6 +243,171 @@ class AudioAnalysisService:
|
||||
|
||||
return amplitudes, duration
|
||||
|
||||
@staticmethod
|
||||
def review_waveform_cache_path(job_id: str, num_points: int) -> str:
|
||||
"""GCS path of the cached review-page waveform JSON for a job."""
|
||||
return f"jobs/{job_id}/review-audio/waveform_review_{num_points}.json"
|
||||
|
||||
def get_review_waveform(
|
||||
self,
|
||||
gcs_audio_path: str,
|
||||
job_id: str,
|
||||
num_points: int = 1000,
|
||||
transcoding_service=None,
|
||||
) -> tuple[list[float], float]:
|
||||
"""
|
||||
Waveform data for the review page, cached persistently in GCS.
|
||||
|
||||
Decoding a full stem (pydub -> ffmpeg + a pure-Python RMS loop) takes
|
||||
seconds of CPU, so it must only ever happen once per job: results are
|
||||
cached at ``review_waveform_cache_path`` and validated against the
|
||||
source path + num_points (a replaced stem or different resolution
|
||||
recomputes). On a miss, decode the small transcoded review OGG when it
|
||||
exists (~3 MB) instead of the raw stem (~35 MB FLAC).
|
||||
|
||||
The cache upload is best-effort — a failed write still returns the
|
||||
computed data.
|
||||
"""
|
||||
cache_path = self.review_waveform_cache_path(job_id, num_points)
|
||||
cached = self._load_review_waveform_cache(cache_path, gcs_audio_path, num_points)
|
||||
if cached is not None:
|
||||
logger.info(f"[{job_id}] Review waveform cache hit: {cache_path}")
|
||||
return cached
|
||||
|
||||
decode_path = gcs_audio_path
|
||||
if transcoding_service is not None:
|
||||
try:
|
||||
ogg_path = transcoding_service.get_transcoded_cache_path(gcs_audio_path)
|
||||
if self.storage_service.file_exists(ogg_path):
|
||||
decode_path = ogg_path
|
||||
except Exception as e:
|
||||
logger.warning(f"[{job_id}] Could not resolve transcoded OGG for waveform: {e}")
|
||||
|
||||
amplitudes, duration = self.get_waveform_data(
|
||||
gcs_audio_path=decode_path,
|
||||
job_id=job_id,
|
||||
num_points=num_points,
|
||||
)
|
||||
|
||||
try:
|
||||
self.storage_service.upload_json(cache_path, {
|
||||
"amplitudes": list(amplitudes),
|
||||
"duration_seconds": duration,
|
||||
"num_points": num_points,
|
||||
# Keyed to the LOGICAL source (the stem path), not decode_path,
|
||||
# so swapping in/out the OGG shortcut never invalidates the cache
|
||||
# but a regenerated stem at a new path does.
|
||||
"source_gcs_path": gcs_audio_path,
|
||||
})
|
||||
logger.info(f"[{job_id}] Review waveform cached at {cache_path}")
|
||||
except Exception as e:
|
||||
logger.warning(f"[{job_id}] Failed to cache review waveform (non-fatal): {e}")
|
||||
|
||||
return amplitudes, duration
|
||||
|
||||
def _load_review_waveform_cache(
|
||||
self,
|
||||
cache_gcs_path: str,
|
||||
source_gcs_path: str,
|
||||
num_points: int,
|
||||
) -> Optional[tuple[list[float], float]]:
|
||||
"""Load + validate the review waveform cache; None on any mismatch/error."""
|
||||
try:
|
||||
if not self.storage_service.file_exists(cache_gcs_path):
|
||||
return None
|
||||
data = self.storage_service.download_json(cache_gcs_path)
|
||||
if data.get("source_gcs_path") != source_gcs_path:
|
||||
return None
|
||||
if data.get("num_points") != num_points:
|
||||
return None
|
||||
amplitudes = data.get("amplitudes") or []
|
||||
if not amplitudes:
|
||||
return None
|
||||
return amplitudes, float(data.get("duration_seconds", 0.0))
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to load review waveform cache {cache_gcs_path}: {e}")
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def vocals_peaks_cache_path(job_id: str, peaks_per_second: int) -> str:
|
||||
"""GCS path of the cached vocals peak-envelope JSON for a job."""
|
||||
return f"jobs/{job_id}/review-audio/vocals_peaks_{peaks_per_second}.json"
|
||||
|
||||
def get_vocals_peaks(
|
||||
self,
|
||||
gcs_audio_path: str,
|
||||
job_id: str,
|
||||
peaks_per_second: int = 400,
|
||||
transcoding_service=None,
|
||||
) -> dict:
|
||||
"""
|
||||
Pre-computed peak envelope of the vocal stem for the review page's
|
||||
Waveforms mode, cached persistently in GCS.
|
||||
|
||||
Returns the serve-ready payload::
|
||||
|
||||
{peaks_b64, encoding: "u8", peaks_per_second, duration_seconds,
|
||||
source_gcs_path}
|
||||
|
||||
``peaks_b64`` is base64 of one uint8 per bucket (max-abs amplitude
|
||||
quantized to 0-255) — ~150 KB for a 5-minute track vs the ~7 MB OGG
|
||||
the frontend previously downloaded and decoded client-side. On a cache
|
||||
miss, decode the small transcoded review OGG when it exists.
|
||||
The cache upload is best-effort.
|
||||
"""
|
||||
import base64
|
||||
|
||||
cache_path = self.vocals_peaks_cache_path(job_id, peaks_per_second)
|
||||
try:
|
||||
if self.storage_service.file_exists(cache_path):
|
||||
data = self.storage_service.download_json(cache_path)
|
||||
if (
|
||||
data.get("source_gcs_path") == gcs_audio_path
|
||||
and data.get("peaks_per_second") == peaks_per_second
|
||||
and data.get("peaks_b64")
|
||||
):
|
||||
logger.info(f"[{job_id}] Vocals peaks cache hit: {cache_path}")
|
||||
return data
|
||||
except Exception as e:
|
||||
logger.warning(f"[{job_id}] Failed to load vocals peaks cache: {e}")
|
||||
|
||||
decode_path = gcs_audio_path
|
||||
if transcoding_service is not None:
|
||||
try:
|
||||
ogg_path = transcoding_service.get_transcoded_cache_path(gcs_audio_path)
|
||||
if self.storage_service.file_exists(ogg_path):
|
||||
decode_path = ogg_path
|
||||
except Exception as e:
|
||||
logger.warning(f"[{job_id}] Could not resolve transcoded OGG for peaks: {e}")
|
||||
|
||||
import numpy as np
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
local_audio_path = os.path.join(temp_dir, local_audio_filename(decode_path, "vocals"))
|
||||
self.storage_service.download_file(decode_path, local_audio_path)
|
||||
peaks, duration = self.waveform_generator.generate_peaks(
|
||||
local_audio_path, peaks_per_second=peaks_per_second
|
||||
)
|
||||
|
||||
quantized = np.clip(np.round(peaks * 255.0), 0, 255).astype(np.uint8)
|
||||
payload = {
|
||||
"peaks_b64": base64.b64encode(quantized.tobytes()).decode("ascii"),
|
||||
"encoding": "u8",
|
||||
"peaks_per_second": peaks_per_second,
|
||||
"duration_seconds": duration,
|
||||
# Keyed to the LOGICAL source (the stem path) so a regenerated stem
|
||||
# at a new path invalidates, while the OGG decode shortcut doesn't.
|
||||
"source_gcs_path": gcs_audio_path,
|
||||
}
|
||||
|
||||
try:
|
||||
self.storage_service.upload_json(cache_path, payload)
|
||||
logger.info(f"[{job_id}] Vocals peaks cached at {cache_path}")
|
||||
except Exception as e:
|
||||
logger.warning(f"[{job_id}] Failed to cache vocals peaks (non-fatal): {e}")
|
||||
|
||||
return payload
|
||||
|
||||
def cache_waveform_data(
|
||||
self,
|
||||
gcs_audio_path: str,
|
||||
@@ -343,7 +509,7 @@ class AudioAnalysisService:
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
# Download audio file
|
||||
local_audio_path = os.path.join(temp_dir, "backing_vocals.flac")
|
||||
local_audio_path = os.path.join(temp_dir, local_audio_filename(gcs_audio_path, "backing_vocals"))
|
||||
self.storage_service.download_file(gcs_audio_path, local_audio_path)
|
||||
|
||||
# First run analysis to get segments
|
||||
|
||||
@@ -19,7 +19,8 @@ import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.storage_service import SignedUrlTimeout, StorageService
|
||||
from backend.utils.audio_filenames import audio_content_type, local_audio_filename
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -55,6 +56,10 @@ class AudioTranscodingService:
|
||||
filename = Path(source_gcs_path).stem + ".ogg"
|
||||
return f"jobs/{job_id}/review-audio/{filename}"
|
||||
|
||||
def get_transcoded_cache_path(self, source_gcs_path: str) -> str:
|
||||
"""Public accessor for the transcoded-OGG cache path of a source file."""
|
||||
return self._get_cache_path(source_gcs_path)
|
||||
|
||||
def _transcode_and_upload(self, source_gcs_path: str, cache_path: str) -> str:
|
||||
"""
|
||||
Download FLAC from GCS, transcode to OGG Opus, upload to cache path.
|
||||
@@ -63,7 +68,7 @@ class AudioTranscodingService:
|
||||
Raises on failure.
|
||||
"""
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
local_input = os.path.join(temp_dir, "input.flac")
|
||||
local_input = os.path.join(temp_dir, local_audio_filename(source_gcs_path, "input"))
|
||||
local_output = os.path.join(temp_dir, "output.ogg")
|
||||
|
||||
# Download source
|
||||
@@ -115,6 +120,11 @@ class AudioTranscodingService:
|
||||
try:
|
||||
cache_path = self.transcode_if_needed(source_gcs_path)
|
||||
return self.storage.generate_signed_url(cache_path, expiration_minutes)
|
||||
except SignedUrlTimeout:
|
||||
# The signing backend (IAM signBlob) is stalling — every fallback below
|
||||
# would sign too and stall identically. Bail immediately so the caller
|
||||
# degrades fast (null audio_url) instead of burning 2-3× the timeout.
|
||||
raise
|
||||
except Exception as e:
|
||||
# Source may be deleted but cache from earlier transcode persists
|
||||
try:
|
||||
@@ -159,7 +169,7 @@ class AudioTranscodingService:
|
||||
return self.storage.download_bytes(cache_path), "audio/ogg"
|
||||
except Exception as e:
|
||||
logger.warning(f"Transcoding failed for {source_gcs_path}, serving source audio: {e}")
|
||||
return self.storage.download_bytes(source_gcs_path), "audio/flac"
|
||||
return self.storage.download_bytes(source_gcs_path), audio_content_type(source_gcs_path)
|
||||
|
||||
async def get_review_audio_bytes_async(self, source_gcs_path: str) -> tuple[bytes, str]:
|
||||
"""Async wrapper around get_review_audio_bytes via asyncio.to_thread."""
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
"""Requests-board publish fan-out.
|
||||
|
||||
When a community-pick job goes live on YouTube, its ``song_request`` must advance
|
||||
to ``published`` and every up-voter (other than the owner, who already got the job
|
||||
completion email) should get a "your track is live" email.
|
||||
|
||||
A job can reach YouTube via **two** paths, and both must trigger this:
|
||||
1. the quota-managed ``youtube_upload_queue`` (``youtube_queue_processor``), and
|
||||
2. a direct upload during video-worker distribution (``video_worker``), which
|
||||
never touches that queue.
|
||||
|
||||
Historically only path (1) ran the fan-out, so direct-published community picks
|
||||
(e.g. the first real user request) stayed stuck at ``in_progress`` and their
|
||||
board "Recently made" entry never appeared. This shared helper is called from
|
||||
both paths so the outcome is identical regardless of how the video was published.
|
||||
"""
|
||||
import logging
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _youtube_url_for_job(job) -> Optional[str]:
|
||||
"""The published YouTube URL for a job, if any, checking both the state_data
|
||||
field (set on the direct-publish path) and the distribution metadata."""
|
||||
if job is None:
|
||||
return None
|
||||
state = getattr(job, "state_data", None) or {}
|
||||
url = state.get("youtube_url")
|
||||
if url:
|
||||
return url
|
||||
meta = getattr(job, "processing_metadata", None) or {}
|
||||
dist = meta.get("distribution") or {}
|
||||
return dist.get("youtube_video_url") or None
|
||||
|
||||
|
||||
async def notify_community_publish(job_id: str, youtube_url: str) -> Optional[str]:
|
||||
"""Advance a community pick to ``published`` and fan out voter emails.
|
||||
|
||||
Idempotent and best-effort: safe to call from both publish paths and to
|
||||
re-run after a partial failure. Marking published is always safe to repeat;
|
||||
voter emails are guarded by the request's ``notified_voters`` /
|
||||
``voters_notified`` flags so no one is emailed twice.
|
||||
|
||||
Returns the request id if this was a community pick, else ``None`` (a normal,
|
||||
non-community job — no-op).
|
||||
"""
|
||||
try:
|
||||
from backend.services.song_request_service import get_song_request_service
|
||||
service = get_song_request_service()
|
||||
request = service.get_by_job_id(job_id)
|
||||
if request is None:
|
||||
return None # Not a community pick — normal job.
|
||||
|
||||
service.mark_published(request.id, youtube_url)
|
||||
|
||||
if request.voters_notified:
|
||||
return request.id
|
||||
|
||||
# Email up-voters we haven't already reached (retry-safe): exclude the
|
||||
# owner (already got the completion email) and anyone previously notified.
|
||||
owner = (request.owner_email or request.submitted_by or "").lower()
|
||||
already = {v.lower() for v in (request.notified_voters or [])}
|
||||
pending = [
|
||||
v for v in service.list_upvoters(request.id)
|
||||
if v != owner and v not in already
|
||||
]
|
||||
|
||||
from backend.services.job_notification_service import get_job_notification_service
|
||||
notification_service = get_job_notification_service()
|
||||
succeeded = 0
|
||||
for voter in pending:
|
||||
try:
|
||||
ok = await notification_service.send_community_track_live_email(
|
||||
to_email=voter,
|
||||
artist=request.artist,
|
||||
title=request.title,
|
||||
youtube_url=youtube_url,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Failed community voter email for job %s / %s", job_id, voter)
|
||||
continue
|
||||
if ok:
|
||||
# Record each success immediately so a crash mid-loop never
|
||||
# re-emails an already-notified voter on the retry.
|
||||
service.add_notified_voters(request.id, [voter])
|
||||
succeeded += 1
|
||||
|
||||
# Only flag "fully notified" when every pending voter was reached — a
|
||||
# partial failure leaves the flag unset so a re-run retries just the misses.
|
||||
if succeeded == len(pending):
|
||||
service.mark_voters_notified(request.id)
|
||||
logger.info(
|
||||
"community pick %s published (job %s): notified %d/%d pending voters",
|
||||
request.id, job_id, succeeded, len(pending),
|
||||
)
|
||||
return request.id
|
||||
except Exception as e:
|
||||
logger.error("Failed community voter fan-out for job %s: %s", job_id, e)
|
||||
return None
|
||||
|
||||
|
||||
async def reconcile_community_publishes() -> Dict[str, Any]:
|
||||
"""Safety net / backfill for the community publish fan-out. Two passes:
|
||||
|
||||
1. Picks stuck at ``in_progress`` whose job is actually live on YouTube — run
|
||||
the publish transition (covers picks published before the fan-out was wired
|
||||
into every path, or any future path that forgets to call it).
|
||||
2. Picks already ``published`` but with ``voters_notified == False`` — a voter
|
||||
send failed (or raised) after the request was marked published, and no other
|
||||
path retries them. Re-run the fan-out (idempotent; only un-notified voters
|
||||
are re-emailed).
|
||||
|
||||
Fully idempotent — safe to call any time.
|
||||
"""
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.song_request_service import get_song_request_service
|
||||
|
||||
service = get_song_request_service()
|
||||
job_manager = JobManager()
|
||||
|
||||
scanned = 0
|
||||
published = []
|
||||
|
||||
# Pass 1: in_progress picks whose job is live.
|
||||
for request in service.list_in_progress():
|
||||
scanned += 1
|
||||
if not request.job_id:
|
||||
continue
|
||||
url = _youtube_url_for_job(job_manager.get_job(request.job_id))
|
||||
if not url:
|
||||
continue
|
||||
result_id = await notify_community_publish(request.job_id, url)
|
||||
if result_id:
|
||||
published.append({"request_id": result_id, "job_id": request.job_id, "youtube_url": url})
|
||||
|
||||
# Pass 2: published picks whose voter fan-out never fully completed.
|
||||
retried = 0
|
||||
for request in service.list_published_unnotified():
|
||||
scanned += 1
|
||||
if not request.job_id:
|
||||
continue
|
||||
# Prefer the URL already recorded on the request; fall back to the job.
|
||||
url = request.youtube_url or _youtube_url_for_job(job_manager.get_job(request.job_id))
|
||||
if not url:
|
||||
continue
|
||||
if await notify_community_publish(request.job_id, url):
|
||||
retried += 1
|
||||
|
||||
logger.info(
|
||||
"community publish reconcile: scanned %d, published %d, retried-fanout %d",
|
||||
scanned, len(published), retried,
|
||||
)
|
||||
return {"scanned": scanned, "published": published, "retried_fanout": retried}
|
||||
@@ -37,6 +37,11 @@ class SendResult(NamedTuple):
|
||||
"""
|
||||
success: bool
|
||||
message_id: Optional[str] = None
|
||||
# True when the send failed specifically because Postmark has the recipient
|
||||
# marked inactive (hard bounce / spam complaint / manual suppression). This
|
||||
# is expected, benign traffic (e.g. someone typing a junk address into the
|
||||
# sign-in form), not an outage — callers log it at INFO, not ERROR.
|
||||
suppressed: bool = False
|
||||
|
||||
|
||||
class EmailProvider(ABC):
|
||||
@@ -176,6 +181,11 @@ class PostmarkEmailProvider(EmailProvider):
|
||||
# Postmark MessageID of the most recent successful send, so the email_log
|
||||
# chokepoint can link a persisted record to its Postmark message.
|
||||
self.last_message_id: Optional[str] = None
|
||||
# True when the most recent send failed because the recipient is
|
||||
# suppressed by Postmark (see SendResult.suppressed). Lets the send
|
||||
# chokepoint / route handlers downgrade the failure log from ERROR to
|
||||
# INFO without threading a richer return type through every caller.
|
||||
self.last_suppressed: bool = False
|
||||
|
||||
def send_email(
|
||||
self,
|
||||
@@ -207,6 +217,7 @@ class PostmarkEmailProvider(EmailProvider):
|
||||
bcc_emails: Optional[List[str]] = None,
|
||||
from_email_override: Optional[str] = None,
|
||||
) -> SendResult:
|
||||
self.last_suppressed = False
|
||||
try:
|
||||
sender_email = from_email_override or self.from_email
|
||||
payload = {
|
||||
@@ -252,6 +263,18 @@ class PostmarkEmailProvider(EmailProvider):
|
||||
# Surface Postmark's structured error so we can see suppressions, invalid signature, etc.
|
||||
try:
|
||||
err = response.json()
|
||||
# ErrorCode 406 (InactiveRecipient) = the address is suppressed
|
||||
# (hard bounce / spam complaint / manual suppression). This is
|
||||
# expected when someone enters a junk/placeholder address at the
|
||||
# sign-in form — it is not an outage, so log it at INFO and flag
|
||||
# it so callers don't raise a scary "failed to send" ERROR.
|
||||
if response.status_code == 422 and err.get("ErrorCode") == 406:
|
||||
self.last_suppressed = True
|
||||
logger.info(
|
||||
f"Postmark skipped suppressed recipient {to_email} "
|
||||
f"(inactive: hard bounce / spam complaint / manual suppression)"
|
||||
)
|
||||
return SendResult(success=False, message_id=None, suppressed=True)
|
||||
logger.error(
|
||||
f"Postmark returned status {response.status_code}: "
|
||||
f"ErrorCode={err.get('ErrorCode')} Message={err.get('Message')}"
|
||||
@@ -311,6 +334,9 @@ class EmailService:
|
||||
self.frontend_url = os.getenv("FRONTEND_URL", "https://gen.nomadkaraoke.com")
|
||||
# After consolidation, buy URL is the same as frontend URL
|
||||
self.buy_url = os.getenv("BUY_URL", self.frontend_url)
|
||||
# Set by _log_and_send: True when the last send failed only because the
|
||||
# recipient is Postmark-suppressed (benign — see SendResult.suppressed).
|
||||
self.last_send_suppressed: bool = False
|
||||
|
||||
def _get_provider(self) -> EmailProvider:
|
||||
"""Get the configured email provider.
|
||||
@@ -414,6 +440,12 @@ class EmailService:
|
||||
from_email_override=from_email_override,
|
||||
)
|
||||
|
||||
# Mirror the provider's suppression flag so route handlers can tell a
|
||||
# benign "recipient suppressed" failure (junk sign-in address) apart
|
||||
# from a real send failure without threading a richer return type
|
||||
# through every send_* method.
|
||||
self.last_send_suppressed = getattr(self.provider, "last_suppressed", False)
|
||||
|
||||
# Only persist genuine outbound mail (Postmark). Console/preview providers
|
||||
# are dev/test only and have no real inbox to reflect.
|
||||
if success and isinstance(self.provider, PostmarkEmailProvider):
|
||||
|
||||
@@ -57,15 +57,51 @@ class FirestoreService:
|
||||
logger.error(f"Error getting job {job_id}: {e}")
|
||||
raise
|
||||
|
||||
@staticmethod
|
||||
def _is_doc_size_error(exc: Exception) -> bool:
|
||||
"""True when a Firestore write failed the 1MB per-document size limit."""
|
||||
return "maximum allowed size" in str(exc).lower()
|
||||
|
||||
def _update_with_size_recovery(
|
||||
self, doc_ref, updates: Dict[str, Any], job_id: str
|
||||
) -> None:
|
||||
"""
|
||||
Apply ``doc_ref.update(updates)``, self-healing past the 1MB doc limit.
|
||||
|
||||
Old job documents can accumulate a large embedded ``worker_logs`` array
|
||||
(the legacy logging path, superseded by the ``jobs/{id}/logs``
|
||||
subcollection). Once that array pushes a document to ~1MB, EVERY
|
||||
subsequent write — including a customer submitting lyrics corrections —
|
||||
fails with Firestore's "exceeds the maximum allowed size" 400. The
|
||||
embedded array is deprecated dead weight, so drop it and retry once.
|
||||
"""
|
||||
try:
|
||||
doc_ref.update(updates)
|
||||
except Exception as e:
|
||||
# Don't recurse if the caller is itself writing worker_logs, and
|
||||
# only recover from the specific size-limit failure.
|
||||
if 'worker_logs' in updates or not self._is_doc_size_error(e):
|
||||
raise
|
||||
logger.warning(
|
||||
f"Job {job_id}: Firestore write hit the 1MB document limit; "
|
||||
f"clearing the legacy embedded worker_logs array and retrying ({e})"
|
||||
)
|
||||
# Deleting a field only shrinks the document, so this write is safe.
|
||||
doc_ref.update({'worker_logs': firestore.DELETE_FIELD})
|
||||
doc_ref.update(updates)
|
||||
logger.info(
|
||||
f"Job {job_id}: cleared legacy worker_logs; write succeeded on retry"
|
||||
)
|
||||
|
||||
def update_job(self, job_id: str, updates: Dict[str, Any]) -> None:
|
||||
"""Update a job with partial data."""
|
||||
try:
|
||||
doc_ref = self.db.collection(self.collection).document(job_id)
|
||||
|
||||
|
||||
# Add updated_at timestamp
|
||||
updates['updated_at'] = datetime.utcnow()
|
||||
|
||||
doc_ref.update(updates)
|
||||
|
||||
self._update_with_size_recovery(doc_ref, updates, job_id)
|
||||
logger.info(f"Updated job {job_id} in Firestore")
|
||||
except Exception as e:
|
||||
logger.error(f"Error updating job {job_id}: {e}")
|
||||
@@ -107,8 +143,8 @@ class FirestoreService:
|
||||
|
||||
# Add any additional fields
|
||||
updates.update(additional_fields)
|
||||
|
||||
doc_ref.update(updates)
|
||||
|
||||
self._update_with_size_recovery(doc_ref, updates, job_id)
|
||||
logger.info(f"Updated job {job_id} status to {status.value}")
|
||||
except Exception as e:
|
||||
logger.error(f"Error updating job status {job_id}: {e}")
|
||||
@@ -383,18 +419,31 @@ class FirestoreService:
|
||||
|
||||
def append_worker_log(self, job_id: str, log_entry: Dict[str, Any]) -> None:
|
||||
"""
|
||||
Atomically append a log entry to worker_logs using ArrayUnion.
|
||||
Append a log entry to the job's log stream.
|
||||
|
||||
This avoids the race condition of read-modify-write when multiple
|
||||
workers are logging concurrently.
|
||||
|
||||
DEPRECATED: Use append_log_to_subcollection() instead to avoid
|
||||
the 1MB document size limit.
|
||||
DEPRECATED embedded-array behaviour: with USE_LOG_SUBCOLLECTION=false
|
||||
this appends to the ``worker_logs`` array via ArrayUnion (atomic, but
|
||||
subject to the 1MB per-document limit). With the flag on (default) the
|
||||
entry is routed to the ``jobs/{id}/logs`` subcollection instead, so the
|
||||
legacy dict-based callers (job_logging.JobLogger, FirestoreJobLogHandler)
|
||||
stop bloating the embedded array toward that limit.
|
||||
|
||||
Args:
|
||||
job_id: Job ID
|
||||
log_entry: Log entry dict with timestamp, level, worker, message
|
||||
"""
|
||||
# Route legacy dict-based callers to the subcollection when enabled so
|
||||
# they no longer grow the embedded worker_logs array (which, once near
|
||||
# 1MB, blocks all writes to the job document — including review submits).
|
||||
if settings.use_log_subcollection:
|
||||
entry = WorkerLogEntry.create(
|
||||
job_id=job_id,
|
||||
worker=log_entry.get('worker', 'unknown'),
|
||||
level=log_entry.get('level', 'INFO'),
|
||||
message=log_entry.get('message', ''),
|
||||
)
|
||||
self.append_log_to_subcollection(job_id, entry)
|
||||
return
|
||||
try:
|
||||
doc_ref = self.db.collection(self.collection).document(job_id)
|
||||
doc_ref.update({
|
||||
|
||||
@@ -92,17 +92,21 @@ def should_retry_flacfetch_error(exception: Exception) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
async def with_retry(func, *args, **kwargs):
|
||||
async def with_retry(func, *args, retry_max_attempts=None, retry_min_wait=None, retry_max_wait=None, **kwargs):
|
||||
"""
|
||||
Execute an async function with retry logic using exponential backoff.
|
||||
|
||||
This implementation uses manual retry logic instead of tenacity decorators
|
||||
for better testability and runtime configuration.
|
||||
|
||||
The retry_* keyword-only arguments override the FLACFETCH_RETRY_* settings
|
||||
for callers that need a different retry profile (e.g. search, which sits on
|
||||
a latency-sensitive user-facing path).
|
||||
"""
|
||||
settings = get_settings()
|
||||
max_attempts = settings.flacfetch_retry_max_attempts
|
||||
min_wait = settings.flacfetch_retry_min_wait
|
||||
max_wait = settings.flacfetch_retry_max_wait
|
||||
max_attempts = retry_max_attempts if retry_max_attempts is not None else settings.flacfetch_retry_max_attempts
|
||||
min_wait = retry_min_wait if retry_min_wait is not None else settings.flacfetch_retry_min_wait
|
||||
max_wait = retry_max_wait if retry_max_wait is not None else settings.flacfetch_retry_max_wait
|
||||
|
||||
last_exception = None
|
||||
|
||||
@@ -218,37 +222,65 @@ class FlacfetchClient:
|
||||
|
||||
Returns:
|
||||
Search response dict with search_id and results list
|
||||
|
||||
|
||||
Raises:
|
||||
FlacfetchServiceError: On search failure
|
||||
FlacfetchServiceError: On search failure (after all retries exhausted)
|
||||
|
||||
Search is idempotent, so transient network errors (e.g. a ReadTimeout
|
||||
while the flacfetch server is busy with an uncached provider sweep) are
|
||||
retried once with a short wait. The retry usually hits the server-side
|
||||
search cache warmed by the first attempt and returns in seconds.
|
||||
|
||||
All attempts share a total time budget kept below Cloudflare's ~100s
|
||||
edge deadline, so a slow retry surfaces as FlacfetchServiceError rather
|
||||
than an opaque edge 524.
|
||||
"""
|
||||
settings = get_settings()
|
||||
total_timeout = settings.flacfetch_search_total_timeout
|
||||
try:
|
||||
async with httpx.AsyncClient() as client:
|
||||
resp = await client.post(
|
||||
f"{self.base_url}/search",
|
||||
headers=self._headers(),
|
||||
json={"artist": artist, "title": title},
|
||||
timeout=self.timeout,
|
||||
)
|
||||
|
||||
if resp.status_code == 404:
|
||||
# No results found - return empty results
|
||||
return {
|
||||
"search_id": None,
|
||||
"artist": artist,
|
||||
"title": title,
|
||||
"results": [],
|
||||
"results_count": 0,
|
||||
}
|
||||
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
return await asyncio.wait_for(
|
||||
with_retry(
|
||||
self._search_impl,
|
||||
artist,
|
||||
title,
|
||||
retry_max_attempts=settings.flacfetch_search_retry_max_attempts,
|
||||
retry_min_wait=settings.flacfetch_search_retry_wait,
|
||||
retry_max_wait=settings.flacfetch_search_retry_wait,
|
||||
),
|
||||
timeout=total_timeout,
|
||||
)
|
||||
except asyncio.TimeoutError:
|
||||
raise FlacfetchServiceError(
|
||||
f"Search timed out after {total_timeout:.0f}s total (including retries)"
|
||||
)
|
||||
except httpx.RequestError as e:
|
||||
raise FlacfetchServiceError(f"Search request failed: {_format_httpx_error(e)}")
|
||||
except httpx.HTTPStatusError as e:
|
||||
raise FlacfetchServiceError(f"Search failed: {e.response.status_code} - {e.response.text}")
|
||||
|
||||
async def _search_impl(self, artist: str, title: str) -> Dict[str, Any]:
|
||||
"""Implementation of search without error wrapping - lets httpx exceptions bubble up."""
|
||||
async with httpx.AsyncClient() as client:
|
||||
resp = await client.post(
|
||||
f"{self.base_url}/search",
|
||||
headers=self._headers(),
|
||||
json={"artist": artist, "title": title},
|
||||
timeout=self.timeout,
|
||||
)
|
||||
|
||||
if resp.status_code == 404:
|
||||
# No results found - return empty results
|
||||
return {
|
||||
"search_id": None,
|
||||
"artist": artist,
|
||||
"title": title,
|
||||
"results": [],
|
||||
"results_count": 0,
|
||||
}
|
||||
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
|
||||
async def download(
|
||||
self,
|
||||
search_id: str,
|
||||
|
||||
@@ -21,6 +21,7 @@ from packaging.version import Version
|
||||
from pydantic import BaseModel
|
||||
|
||||
from .persistence import JobStatePersister
|
||||
from backend.utils.audio_filenames import local_audio_filename
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -305,7 +306,7 @@ def run_preview_encoding(job_id: str, work_dir: Path, request: "EncodePreviewReq
|
||||
try:
|
||||
# Download input files
|
||||
ass_path = work_dir / "subtitles.ass"
|
||||
audio_path = work_dir / "audio.flac"
|
||||
audio_path = work_dir / local_audio_filename(request.audio_gcs_path, "audio")
|
||||
|
||||
download_single_file_from_gcs(request.ass_gcs_path, ass_path)
|
||||
jobs[job_id]["progress"] = 20
|
||||
@@ -454,7 +455,7 @@ def run_render_video(job_id: str, work_dir: Path, request: "RenderVideoRequest")
|
||||
jobs[job_id]["progress"] = 25
|
||||
|
||||
# 3. Download audio
|
||||
audio_path = work_dir / "audio.flac"
|
||||
audio_path = work_dir / local_audio_filename(request.audio_gcs_path, "audio")
|
||||
download_single_file_from_gcs(request.audio_gcs_path, audio_path)
|
||||
jobs[job_id]["progress"] = 35
|
||||
|
||||
|
||||
@@ -1136,49 +1136,58 @@ class JobManager:
|
||||
|
||||
def mark_lyrics_complete(self, job_id: str) -> None:
|
||||
"""
|
||||
Mark lyrics processing as complete and trigger screens if ready.
|
||||
Mark lyrics processing as complete.
|
||||
|
||||
Lyrics completion is the sole gate for screen generation and review.
|
||||
Audio separation runs independently in the background.
|
||||
Lyrics completion is the sole gate for screen generation and review
|
||||
(audio separation runs independently in the background). This ONLY sets
|
||||
the flag — the caller must then ``await advance_to_screens_if_ready()`` so
|
||||
the screens dispatch is durable. A previous fire-and-forget
|
||||
``asyncio.create_task`` trigger was being cancelled when the lyrics Cloud
|
||||
Run Job's event loop tore down, orphaning jobs at ``downloading`` with no
|
||||
error (E2E job-orchestration stall incident, 2026-09).
|
||||
"""
|
||||
self.update_state_data(job_id, 'lyrics_complete', True)
|
||||
|
||||
if self.check_parallel_processing_complete(job_id):
|
||||
logger.info(f"Job {job_id}: Lyrics complete, triggering screens worker")
|
||||
self._trigger_screens_worker(job_id)
|
||||
|
||||
def _trigger_screens_worker(self, job_id: str) -> None:
|
||||
async def advance_to_screens_if_ready(self, job_id: str) -> bool:
|
||||
"""
|
||||
Trigger screens generation worker.
|
||||
|
||||
Uses WorkerService to make HTTP call to internal API.
|
||||
This must be async, so we use asyncio to create a task.
|
||||
Idempotently trigger the screens worker once lyrics processing is complete.
|
||||
|
||||
Awaited (not fire-and-forget) so the Cloud Task enqueue completes before
|
||||
the calling worker's event loop tears down. Safe to call from BOTH the
|
||||
lyrics worker (primary trigger) and the audio worker (fallback, in case
|
||||
the lyrics trigger was lost): the status guard here plus the screens
|
||||
worker's own idempotency make a double-trigger a harmless no-op.
|
||||
|
||||
Screen generation is gated on LYRICS only (audio separation is decoupled
|
||||
so reviewers can start while it finishes), so this no-ops until lyrics are
|
||||
done, and only fires while the job is still at ``downloading``.
|
||||
|
||||
Returns:
|
||||
True iff a screens dispatch was issued.
|
||||
"""
|
||||
import asyncio
|
||||
job = self.get_job(job_id)
|
||||
if not job:
|
||||
return False
|
||||
if not job.state_data.get('lyrics_complete', False):
|
||||
# Lyrics not finished yet — whichever worker finishes lyrics triggers.
|
||||
return False
|
||||
if job.status != JobStatus.DOWNLOADING:
|
||||
# Already advanced past prep (or parked in a special state). Keeps the
|
||||
# audio-worker fallback from re-triggering a job that already reached
|
||||
# screens/review.
|
||||
logger.info(
|
||||
f"Job {job_id}: screens not (re)triggered — status={job.status} "
|
||||
"(expected downloading)"
|
||||
)
|
||||
return False
|
||||
from backend.services.worker_service import get_worker_service
|
||||
|
||||
logger.info(f"Job {job_id}: Triggering screens worker")
|
||||
|
||||
# Create async task to trigger worker
|
||||
# This allows us to call async code from sync context
|
||||
async def _trigger():
|
||||
worker_service = get_worker_service()
|
||||
await worker_service.trigger_screens_worker(job_id)
|
||||
|
||||
# Create task in event loop
|
||||
try:
|
||||
loop = asyncio.get_event_loop()
|
||||
if loop.is_running():
|
||||
# If loop is already running, create task
|
||||
asyncio.create_task(_trigger())
|
||||
else:
|
||||
# If no loop, run directly
|
||||
asyncio.run(_trigger())
|
||||
except RuntimeError:
|
||||
# Fallback: just log
|
||||
logger.warning(f"Job {job_id}: Could not trigger screens worker (no event loop)")
|
||||
# TODO: In production, use message queue instead
|
||||
|
||||
logger.info(f"Job {job_id}: lyrics complete — triggering screens worker (awaited)")
|
||||
# Propagate the dispatch result: trigger_screens_worker returns False on a
|
||||
# Cloud Tasks enqueue failure / HTTP error / timeout. Returning False here
|
||||
# keeps recover_stuck_jobs from counting a failed re-trigger against its
|
||||
# per-tick cap (which would delay other stalled jobs), and lets it retry.
|
||||
return await get_worker_service().trigger_screens_worker(job_id)
|
||||
|
||||
def cancel_job(self, job_id: str, reason: Optional[str] = None) -> bool:
|
||||
"""
|
||||
Cancel a job.
|
||||
|
||||
@@ -1,249 +1,208 @@
|
||||
"""
|
||||
KaraokeNerds community version detection service.
|
||||
|
||||
Scrapes karaokenerds.com to check if a song already has community-approved
|
||||
karaoke versions available on YouTube. Ported from kjbox/kj-controller/karaoke_nerds.py.
|
||||
Checks whether a song already has community-approved karaoke versions (free,
|
||||
directly-playable, on YouTube). This reads OUR OWN daily-refreshed copy of the
|
||||
KaraokeNerds community catalog — it does NOT scrape or live-query
|
||||
karaokenerds.com. The catalog is populated by the authorized `kn-data-sync`
|
||||
export job (the only thing permitted to hit karaokenerds.com) into BigQuery
|
||||
`karaoke_decide.karaokenerds_community` and mirrored to a gzipped-JSON object in
|
||||
GCS, which this module loads into an in-process index.
|
||||
|
||||
Public API (`check_community_versions` / `check_community_versions_batch`) and
|
||||
its return shapes are unchanged from the previous scraping implementation, so
|
||||
callers and the frontend need no changes.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import gzip
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
from typing import Any
|
||||
from urllib.parse import urlencode
|
||||
|
||||
import httpx
|
||||
from bs4 import BeautifulSoup
|
||||
from google.cloud import storage
|
||||
|
||||
from backend.config import settings
|
||||
from backend.services.kn_brand_names import brand_name_for
|
||||
from backend.services.match_judge.classifier import normalize_for_match
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
SEARCH_URL = "https://karaokenerds.com/Search"
|
||||
REQUEST_TIMEOUT = 8
|
||||
USER_AGENT = "NomadKaraokeGen/1.0"
|
||||
|
||||
# karaokenerds.com's search silently returns zero results once a query exceeds
|
||||
# ~10 whitespace-separated terms (observed: 10 terms match, 11 return nothing).
|
||||
# Long/repetitive titles like "I Do, I Do, I Do, I Do, I Do" combined with the
|
||||
# artist blow past this, so the song is falsely reported as having no community
|
||||
# version. When that happens we retry with the title alone (the highest-signal
|
||||
# term) and keep only results whose artist matches.
|
||||
MAX_RELIABLE_QUERY_TERMS = 10
|
||||
|
||||
# In-memory TTL cache: { cache_key: (expiry_timestamp, data) }
|
||||
_cache: dict[str, tuple[float, Any]] = {}
|
||||
CACHE_TTL_SECONDS = 3600 # 1 hour
|
||||
# Extract a YouTube video id from any of KaraokeNerds' stored watch-URL forms
|
||||
# (youtu.be/<id>, /watch?v=<id>, /embed/<id>, /shorts/<id>) so we can emit the
|
||||
# canonical https://www.youtube.com/watch?v=<id> the old scrape produced.
|
||||
_YT_ID_RE = re.compile(
|
||||
r"(?:youtu\.be/|youtube\.com/(?:watch\?(?:[^&]*&)*v=|embed/|shorts/|v/))"
|
||||
r"([A-Za-z0-9_-]{11})"
|
||||
)
|
||||
|
||||
|
||||
def _cache_get(key: str) -> Any | None:
|
||||
"""Get a value from cache if it exists and hasn't expired."""
|
||||
if key in _cache:
|
||||
expiry, data = _cache[key]
|
||||
if time.monotonic() < expiry:
|
||||
return data
|
||||
del _cache[key]
|
||||
return None
|
||||
def _normalize_youtube_url(watch: str | None) -> str | None:
|
||||
"""Canonicalize a KaraokeNerds watch URL to youtube.com/watch?v=<id>.
|
||||
|
||||
Returns the canonical URL, or the stripped original if no 11-char id can be
|
||||
parsed (never fabricates), or None when empty.
|
||||
"""
|
||||
watch = (watch or "").strip()
|
||||
if not watch:
|
||||
return None
|
||||
m = _YT_ID_RE.search(watch)
|
||||
if m:
|
||||
return f"https://www.youtube.com/watch?v={m.group(1)}"
|
||||
return watch
|
||||
|
||||
# Every row in the community catalog is, by definition, a community/web track, so
|
||||
# entries surfaced from it are always flagged as community versions.
|
||||
_IS_COMMUNITY = True
|
||||
|
||||
# In-process index built from the community export, refreshed on a TTL. Structure:
|
||||
# { "<norm-artist>\x1f<norm-title>": {"title", "artist", "community_tracks": [...]} }
|
||||
_index: dict[str, dict[str, Any]] | None = None
|
||||
_index_expiry: float = 0.0
|
||||
_index_lock = asyncio.Lock()
|
||||
|
||||
# Separator for the (artist, title) match key — a control char that survives
|
||||
# normalization stripping so it can never appear inside a normalized value.
|
||||
_KEY_SEP = "\x1f"
|
||||
|
||||
|
||||
def _cache_set(key: str, data: Any, ttl: float = CACHE_TTL_SECONDS) -> None:
|
||||
"""Store a value in cache with TTL."""
|
||||
_cache[key] = (time.monotonic() + ttl, data)
|
||||
def _match_key(artist: str, title: str) -> str:
|
||||
return f"{normalize_for_match(artist)}{_KEY_SEP}{normalize_for_match(title)}"
|
||||
|
||||
|
||||
def _clean_youtube_url(url: str) -> str:
|
||||
"""Strip playlist params from YouTube URLs, keep just the video URL."""
|
||||
return re.sub(r"&list=[^&]*", "", url)
|
||||
def _build_index(items: list[dict[str, Any]]) -> dict[str, dict[str, Any]]:
|
||||
"""Build the (artist, title) -> song lookup from raw community rows.
|
||||
|
||||
Each raw row carries ``Artist, Title, Brand, Watch`` (YouTube URL). Rows for
|
||||
the same normalized (artist, title) are grouped; their community tracks are
|
||||
deduped by (brand, url).
|
||||
"""
|
||||
index: dict[str, dict[str, Any]] = {}
|
||||
for row in items:
|
||||
artist = (row.get("Artist") or "").strip()
|
||||
title = (row.get("Title") or "").strip()
|
||||
if not artist or not title:
|
||||
continue
|
||||
# The export stores the brand *code* (e.g. "NOMAD"); resolve the human
|
||||
# name for display and keep the code, matching the old scrape's output.
|
||||
brand_code = (row.get("Brand") or "").strip()
|
||||
youtube_url = _normalize_youtube_url(row.get("Watch"))
|
||||
|
||||
key = _match_key(artist, title)
|
||||
song = index.get(key)
|
||||
if song is None:
|
||||
# Keep the first-seen display casing for artist/title.
|
||||
song = {"title": title, "artist": artist, "community_tracks": [], "_seen": set()}
|
||||
index[key] = song
|
||||
|
||||
dedup = (brand_code, youtube_url)
|
||||
if dedup in song["_seen"]:
|
||||
continue
|
||||
song["_seen"].add(dedup)
|
||||
song["community_tracks"].append({
|
||||
"brand_name": brand_name_for(brand_code),
|
||||
"brand_code": brand_code,
|
||||
"youtube_url": youtube_url,
|
||||
"is_community": _IS_COMMUNITY,
|
||||
})
|
||||
|
||||
# Drop the internal dedup bookkeeping before returning.
|
||||
for song in index.values():
|
||||
song.pop("_seen", None)
|
||||
return index
|
||||
|
||||
|
||||
def _parse_single_track(li) -> dict | None:
|
||||
"""Parse a single track <li> element from karaokenerds search results."""
|
||||
# Brand name: first <a> in the li
|
||||
brand_link = li.find("a")
|
||||
brand_name = brand_link.get_text(strip=True) if brand_link else ""
|
||||
def _load_index() -> dict[str, dict[str, Any]]:
|
||||
"""Download and parse the community export gzip from GCS (blocking)."""
|
||||
client = storage.Client(project=settings.google_cloud_project)
|
||||
bucket = client.bucket(settings.kn_community_bucket)
|
||||
blob = bucket.blob(settings.kn_community_blob)
|
||||
raw = blob.download_as_bytes()
|
||||
data = json.loads(gzip.decompress(raw))
|
||||
if isinstance(data, dict) and "Items" in data:
|
||||
items = data["Items"]
|
||||
elif isinstance(data, list):
|
||||
items = data
|
||||
else:
|
||||
raise ValueError(f"Unexpected community export shape: {type(data).__name__}")
|
||||
index = _build_index(items)
|
||||
logger.info(
|
||||
"Loaded KaraokeNerds community index: %d songs from gs://%s/%s",
|
||||
len(index), settings.kn_community_bucket, settings.kn_community_blob,
|
||||
)
|
||||
return index
|
||||
|
||||
# Brand code: text inside .badge span
|
||||
badge = li.find("span", class_="badge")
|
||||
brand_code = ""
|
||||
if badge:
|
||||
brand_code = badge.get_text(strip=True)
|
||||
|
||||
# YouTube URL: link containing youtube.com
|
||||
youtube_url = None
|
||||
for a in li.find_all("a", href=True):
|
||||
href = a["href"]
|
||||
if "youtube.com" in href:
|
||||
youtube_url = _clean_youtube_url(href)
|
||||
async def _get_index() -> dict[str, dict[str, Any]]:
|
||||
"""Return the community index, refreshing from GCS when the TTL has expired.
|
||||
|
||||
Failures are non-fatal: a stale index keeps serving; if there is no index
|
||||
yet, an empty one is returned (every song reads as "no community version",
|
||||
which keeps tracks selectable — the same fail-open behaviour the scraper had).
|
||||
"""
|
||||
global _index, _index_expiry
|
||||
if _index is not None and time.monotonic() < _index_expiry:
|
||||
return _index
|
||||
|
||||
async with _index_lock:
|
||||
# Re-check after acquiring the lock — another coroutine may have loaded it.
|
||||
if _index is not None and time.monotonic() < _index_expiry:
|
||||
return _index
|
||||
try:
|
||||
fresh = await asyncio.to_thread(_load_index)
|
||||
_index = fresh
|
||||
_index_expiry = time.monotonic() + max(60, settings.kn_community_ttl_seconds)
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.warning("Failed to load KaraokeNerds community index: %s", e)
|
||||
if _index is None:
|
||||
# No prior data — serve empty until the short retry window elapses.
|
||||
_index = {}
|
||||
# Retry soon whether we're serving empty or a stale index, so an
|
||||
# outage doesn't make every request re-attempt the load immediately.
|
||||
_index_expiry = time.monotonic() + 60
|
||||
return _index
|
||||
|
||||
|
||||
def _lookup(index: dict[str, dict[str, Any]], artist: str, title: str) -> dict:
|
||||
"""Build a check result for one (artist, title) from the index."""
|
||||
song = index.get(_match_key(artist, title))
|
||||
if not song or not song.get("community_tracks"):
|
||||
return {"has_community": False, "songs": [], "best_youtube_url": None}
|
||||
|
||||
best_youtube_url = None
|
||||
for track in song["community_tracks"]:
|
||||
if track.get("youtube_url"):
|
||||
best_youtube_url = track["youtube_url"]
|
||||
break
|
||||
|
||||
# Community: presence of img.check
|
||||
is_community = bool(li.find("img", class_="check"))
|
||||
|
||||
if not youtube_url:
|
||||
return None
|
||||
|
||||
return {
|
||||
"brand_name": brand_name,
|
||||
"brand_code": brand_code,
|
||||
"youtube_url": youtube_url,
|
||||
"is_community": is_community,
|
||||
"has_community": True,
|
||||
"songs": [{
|
||||
"title": song["title"],
|
||||
"artist": song["artist"],
|
||||
"community_tracks": song["community_tracks"],
|
||||
}],
|
||||
"best_youtube_url": best_youtube_url,
|
||||
}
|
||||
|
||||
|
||||
def _parse_tracks(details_row) -> list[dict]:
|
||||
"""Parse track list items from a details row."""
|
||||
tracks = []
|
||||
for li in details_row.find_all("li", class_="track"):
|
||||
track = _parse_single_track(li)
|
||||
if track:
|
||||
tracks.append(track)
|
||||
return tracks
|
||||
|
||||
|
||||
def parse_results(html: str) -> list[dict]:
|
||||
"""Parse karaokenerds.com search results HTML into structured data."""
|
||||
soup = BeautifulSoup(html, "html.parser")
|
||||
table = soup.find("table")
|
||||
if not table:
|
||||
return []
|
||||
|
||||
tbody = table.find("tbody")
|
||||
if not tbody:
|
||||
return []
|
||||
|
||||
songs = []
|
||||
rows = tbody.find_all("tr", recursive=False)
|
||||
|
||||
i = 0
|
||||
while i < len(rows):
|
||||
row = rows[i]
|
||||
|
||||
# Song rows have class "group"
|
||||
if "group" not in row.get("class", []):
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# Extract title and artist from the song row
|
||||
cells = row.find_all("td")
|
||||
if len(cells) < 3:
|
||||
i += 1
|
||||
continue
|
||||
|
||||
title_link = cells[0].find("a")
|
||||
artist_link = cells[1].find("a")
|
||||
title = title_link.get_text(strip=True) if title_link else ""
|
||||
artist = artist_link.get_text(strip=True) if artist_link else ""
|
||||
|
||||
# The next row should be the details row with tracks
|
||||
tracks = []
|
||||
if i + 1 < len(rows):
|
||||
details_row = rows[i + 1]
|
||||
if "details" in details_row.get("class", []):
|
||||
tracks = _parse_tracks(details_row)
|
||||
i += 2
|
||||
else:
|
||||
i += 1
|
||||
else:
|
||||
i += 1
|
||||
|
||||
if title:
|
||||
songs.append({
|
||||
"title": title,
|
||||
"artist": artist,
|
||||
"tracks": tracks,
|
||||
})
|
||||
|
||||
return songs
|
||||
|
||||
|
||||
async def _search_songs(query: str) -> list[dict] | None:
|
||||
"""Run a single karaokenerds search and parse the results.
|
||||
|
||||
Returns the parsed song list, or ``None`` if the HTTP request failed (so the
|
||||
caller can distinguish "search errored" from "search returned nothing").
|
||||
"""
|
||||
params = urlencode({"query": query, "webFilter": "OnlyWeb"})
|
||||
url = f"{SEARCH_URL}?{params}"
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=REQUEST_TIMEOUT) as client:
|
||||
resp = await client.get(
|
||||
url,
|
||||
headers={"User-Agent": USER_AGENT},
|
||||
follow_redirects=True,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
except Exception as e:
|
||||
logger.warning(f"KaraokeNerds search failed for '{query}': {e}")
|
||||
return None
|
||||
return parse_results(resp.text)
|
||||
|
||||
|
||||
def _extract_community_songs(songs: list[dict]) -> tuple[list[dict], str | None]:
|
||||
"""Filter parsed songs to those with community tracks; return (songs, best_url)."""
|
||||
community_songs: list[dict] = []
|
||||
best_youtube_url: str | None = None
|
||||
for song in songs:
|
||||
community_tracks = [t for t in song["tracks"] if t["is_community"]]
|
||||
if community_tracks:
|
||||
community_songs.append({
|
||||
"title": song["title"],
|
||||
"artist": song["artist"],
|
||||
"community_tracks": community_tracks,
|
||||
})
|
||||
if best_youtube_url is None:
|
||||
best_youtube_url = community_tracks[0]["youtube_url"]
|
||||
return community_songs, best_youtube_url
|
||||
|
||||
|
||||
async def check_community_versions(artist: str, title: str) -> dict:
|
||||
"""
|
||||
Check if a song has community-approved karaoke versions on karaokenerds.
|
||||
Check if a song has community-approved karaoke versions.
|
||||
|
||||
Returns a dict with:
|
||||
Reads our own community catalog (never karaokenerds.com). Returns a dict with:
|
||||
- has_community: bool
|
||||
- songs: list of matched songs with community tracks
|
||||
- best_youtube_url: URL of the top community version (if any)
|
||||
"""
|
||||
query = f"{artist} {title}"
|
||||
cache_key = f"community:{query.lower().strip()}"
|
||||
cached = _cache_get(cache_key)
|
||||
if cached is not None:
|
||||
return cached
|
||||
|
||||
songs = await _search_songs(query)
|
||||
if songs is None:
|
||||
# Hard failure (network/HTTP) — cache a negative so we don't hammer the
|
||||
# site, matching prior behaviour.
|
||||
result = {"has_community": False, "songs": [], "best_youtube_url": None}
|
||||
_cache_set(cache_key, result)
|
||||
return result
|
||||
|
||||
# karaokenerds chokes on overlong queries and returns nothing. If the
|
||||
# combined "artist title" query was too long AND came back empty, retry with
|
||||
# the title alone, then keep only results whose artist matches (title-only is
|
||||
# broader, so this guards against same-titled songs by other artists).
|
||||
if (
|
||||
not songs
|
||||
and title.strip()
|
||||
and len(query.split()) > MAX_RELIABLE_QUERY_TERMS
|
||||
):
|
||||
fallback = await _search_songs(title)
|
||||
if fallback:
|
||||
key_artist = normalize_for_match(artist)
|
||||
songs = [
|
||||
s for s in fallback
|
||||
if normalize_for_match(s.get("artist") or "") == key_artist
|
||||
]
|
||||
|
||||
community_songs, best_youtube_url = _extract_community_songs(songs)
|
||||
|
||||
result = {
|
||||
"has_community": len(community_songs) > 0,
|
||||
"songs": community_songs,
|
||||
"best_youtube_url": best_youtube_url,
|
||||
}
|
||||
_cache_set(cache_key, result)
|
||||
return result
|
||||
artist = (artist or "").strip()
|
||||
title = (title or "").strip()
|
||||
if not artist or not title:
|
||||
return {"has_community": False, "songs": [], "best_youtube_url": None}
|
||||
index = await _get_index()
|
||||
return _lookup(index, artist, title)
|
||||
|
||||
|
||||
async def check_community_versions_batch(
|
||||
@@ -256,20 +215,20 @@ async def check_community_versions_batch(
|
||||
"brand_count": int, "versions": [{"brand": str, "url": str}]}``. ``versions`` is
|
||||
the per-community-version detail (deduped by brand, first YouTube URL kept) the UI
|
||||
uses to render clickable links; ``brands``/``brand_count`` are retained for
|
||||
back-compat. Bounded concurrency keeps us polite to karaokenerds.com; per-song
|
||||
results reuse the existing 1h cache. A failed lookup degrades to
|
||||
``available=False`` (the track simply stays selectable) — never raises.
|
||||
back-compat. Lookups hit our in-process community index (no network per song), so
|
||||
``concurrency`` is accepted for back-compat but no longer meaningful. A missing
|
||||
catalog degrades to ``available=False`` (the track simply stays selectable).
|
||||
"""
|
||||
sem = asyncio.Semaphore(max(1, concurrency))
|
||||
_ = concurrency # retained for call-site compatibility; lookups are in-memory now
|
||||
index = await _get_index()
|
||||
|
||||
async def _one(song: dict) -> dict:
|
||||
def _one(song: dict) -> dict:
|
||||
artist = (song.get("artist") or "").strip()
|
||||
title = (song.get("title") or "").strip()
|
||||
if not artist or not title:
|
||||
return {"artist": artist, "title": title, "available": False,
|
||||
"brands": [], "brand_count": 0, "versions": []}
|
||||
async with sem:
|
||||
res = await check_community_versions(artist, title)
|
||||
res = _lookup(index, artist, title)
|
||||
versions: list[dict] = []
|
||||
versioned_brands: set[str] = set()
|
||||
brands: list[str] = []
|
||||
@@ -294,4 +253,11 @@ async def check_community_versions_batch(
|
||||
"versions": versions,
|
||||
}
|
||||
|
||||
return await asyncio.gather(*[_one(s) for s in songs])
|
||||
return [_one(s) for s in songs]
|
||||
|
||||
|
||||
def _reset_index_for_tests() -> None:
|
||||
"""Clear the module-level cache (used by tests to isolate index state)."""
|
||||
global _index, _index_expiry
|
||||
_index = None
|
||||
_index_expiry = 0.0
|
||||
@@ -0,0 +1,54 @@
|
||||
"""KaraokeNerds brand code -> human display name.
|
||||
|
||||
Our own KaraokeNerds catalog (BigQuery `karaokenerds_community` + the GCS export)
|
||||
stores only the brand *code* (e.g. "NOMAD", "OBSK"). The old live scrape also
|
||||
surfaced the human name ("Nomad Karaoke", "ObsKure Karaoke") which the UI shows.
|
||||
KaraokeNerds exposes no authorized brand-name data source, so this static map
|
||||
(kept in sync with kjbox's version_priority registry, plus the highest-frequency
|
||||
community brands) reproduces those names. Unknown codes fall back to the code —
|
||||
the same graceful degradation the UI already applies.
|
||||
"""
|
||||
|
||||
KN_BRAND_NAMES: dict[str, str] = {
|
||||
# Community brands (mirrors kjbox version_priority.COMMUNITY_BRANDS display names)
|
||||
"CC": "CC Karaoke",
|
||||
"LC": "Lemmy Caution",
|
||||
"FBK": "Funbox Karaoke",
|
||||
"BELLY": "BellySings",
|
||||
"NOMAD": "Nomad Karaoke",
|
||||
"FAKEY": "FakeyOke",
|
||||
"PMK": "Punk Media Karaoke",
|
||||
"OBSK": "ObsKure Karaoke",
|
||||
"SDK": "SNDL Karaoke",
|
||||
"DBK": "Deep Bench Karaoke",
|
||||
# Commercial brands (mirrors version_priority.COMMERCIAL_BRANDS display names)
|
||||
"KV": "Karaoke Version",
|
||||
"SC": "Sound Choice",
|
||||
"SBI": "SBI Karaoke",
|
||||
"SF": "Sunfly",
|
||||
"CB": "Chart Buster",
|
||||
"ZM": "Zoom",
|
||||
"VS": "Vocal Star",
|
||||
"SK": "Sing King",
|
||||
"MR": "Mr. Entertainer",
|
||||
"PT": "Party Tyme",
|
||||
"EK": "Easy Karaoke",
|
||||
# Additional high-frequency community brands (harvested from KaraokeNerds).
|
||||
"IKV": "Imperfekt Karaoke",
|
||||
"ZP": "Zipper Karaoke",
|
||||
"JL311": "Rock Solid Karaoke",
|
||||
"CAR": "Caritas",
|
||||
"MKU": "Mobile Karaoke Unit",
|
||||
"VONAGAM": "Vonagam Karaoke",
|
||||
"GR": "ggnzla RECORDS",
|
||||
"HALJAM": "Hal Jam",
|
||||
"REEKIES": "Reekies Karaoke",
|
||||
"DJS": "DJ Sauly Karaoke",
|
||||
}
|
||||
|
||||
|
||||
def brand_name_for(code: str) -> str:
|
||||
"""Human display name for a KaraokeNerds brand code; the code itself if unknown."""
|
||||
if not code:
|
||||
return ""
|
||||
return KN_BRAND_NAMES.get(code.upper().strip(), code)
|
||||
@@ -170,6 +170,15 @@ class SongRequestService:
|
||||
return SongRequest(**doc.to_dict())
|
||||
return None
|
||||
|
||||
def list_all(self) -> list[SongRequest]:
|
||||
"""Every request across all statuses, newest first — the admin history view."""
|
||||
items = [
|
||||
SongRequest(**doc.to_dict())
|
||||
for doc in self.db.collection(REQUESTS_COLLECTION).stream()
|
||||
]
|
||||
items.sort(key=lambda r: r.created_at, reverse=True)
|
||||
return items
|
||||
|
||||
def list_active(self) -> list[SongRequest]:
|
||||
"""Open requests, ranked by net votes desc then oldest-first."""
|
||||
query = self.db.collection(REQUESTS_COLLECTION).where(
|
||||
@@ -388,6 +397,19 @@ class SongRequestService:
|
||||
).limit(ACTIVE_FETCH_LIMIT)
|
||||
return [SongRequest(**doc.to_dict()) for doc in query.stream()]
|
||||
|
||||
def list_published_unnotified(self) -> list[SongRequest]:
|
||||
"""Published picks whose voter fan-out never fully completed
|
||||
(``voters_notified == False``) — e.g. a send failed after the request was
|
||||
already marked published. The reconcile job retries these; the per-voter
|
||||
``notified_voters`` guard keeps it from re-emailing anyone already reached.
|
||||
"""
|
||||
query = self.db.collection(REQUESTS_COLLECTION).where(
|
||||
filter=FieldFilter("status", "==", "published")
|
||||
).where(
|
||||
filter=FieldFilter("voters_notified", "==", False)
|
||||
).limit(ACTIVE_FETCH_LIMIT)
|
||||
return [SongRequest(**doc.to_dict()) for doc in query.stream()]
|
||||
|
||||
def list_upvoters(self, request_id: str) -> list[str]:
|
||||
"""Emails that up-voted this request (value > 0), oldest vote first.
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
"""
|
||||
Google Cloud Storage operations for file management.
|
||||
"""
|
||||
import concurrent.futures
|
||||
import logging
|
||||
import os
|
||||
import json
|
||||
import threading
|
||||
from typing import Optional, BinaryIO, Any, Dict
|
||||
from pathlib import Path
|
||||
from google.cloud import storage
|
||||
@@ -16,6 +18,39 @@ from backend.config import settings
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# --- Signed-URL generation hardening (incident 2026-09-17) ---------------------
|
||||
# On Cloud Run we have no private key, so signing goes through the IAM signBlob API
|
||||
# over the network. google-cloud-storage gives that call a ~120s per-attempt
|
||||
# timeout PLUS retries, so a stalled IAM/metadata endpoint hangs the calling worker
|
||||
# thread for minutes. When enough review-page loads (each signs 2-3 audio URLs) hit
|
||||
# a stall at once, the request thread pool is exhausted and the whole service goes
|
||||
# unavailable — exactly what took gen down on 2026-09-17.
|
||||
#
|
||||
# Defense: run every sign on a DEDICATED, bounded thread pool and give it a short
|
||||
# wall-clock budget. A stall then (a) fails fast for the caller instead of hanging,
|
||||
# and (b) is confined to this pool so it can never starve GCS data-plane reads/writes
|
||||
# or the request handlers. Callers treat signing as best-effort (see the review
|
||||
# endpoint's fail-soft handling).
|
||||
SIGNED_URL_TIMEOUT_S = float(os.getenv("SIGNED_URL_TIMEOUT_S", "12"))
|
||||
_SIGNING_MAX_WORKERS = int(os.getenv("SIGNED_URL_MAX_WORKERS", "8"))
|
||||
_SIGNING_EXECUTOR = concurrent.futures.ThreadPoolExecutor(
|
||||
max_workers=_SIGNING_MAX_WORKERS,
|
||||
thread_name_prefix="gcs-sign",
|
||||
)
|
||||
# Bounded admission in front of the executor. If every worker is blocked on a stalled
|
||||
# signBlob, the executor's queue is unbounded — a burst of callers would each wait the
|
||||
# full SIGNED_URL_TIMEOUT_S then cancel a still-queued future. Cap total in-flight
|
||||
# (running + queued) so, once saturated, extra callers fail *immediately* instead of
|
||||
# waiting out the budget, and the queue can't grow without bound. Slack above the
|
||||
# worker count absorbs normal bursts (a job-detail load signs ~20 URLs concurrently).
|
||||
_SIGNING_MAX_INFLIGHT = int(os.getenv("SIGNED_URL_MAX_INFLIGHT", str(_SIGNING_MAX_WORKERS * 6)))
|
||||
_SIGNING_SLOTS = threading.BoundedSemaphore(_SIGNING_MAX_INFLIGHT)
|
||||
|
||||
|
||||
class SignedUrlTimeout(Exception):
|
||||
"""A signed-URL generation exceeded ``SIGNED_URL_TIMEOUT_S`` (IAM signBlob stall)."""
|
||||
|
||||
|
||||
class StorageService:
|
||||
"""Service for Google Cloud Storage operations."""
|
||||
|
||||
@@ -177,37 +212,69 @@ class StorageService:
|
||||
logger.info(f"Generated emulator {method} URL for {blob_path} (STORAGE_EMULATOR_HOST set)")
|
||||
return url
|
||||
|
||||
try:
|
||||
def _sign() -> str:
|
||||
"""The actual (blocking, network-bound) signing work.
|
||||
|
||||
Run on the dedicated signing pool with a wall-clock timeout so a stalled
|
||||
IAM signBlob can't hang the caller — see module docstring above.
|
||||
"""
|
||||
blob = self.bucket.blob(blob_path)
|
||||
|
||||
|
||||
# Get default credentials and refresh to ensure we have a valid token
|
||||
credentials, project = google.auth.default()
|
||||
|
||||
|
||||
# Common kwargs for signed URL generation
|
||||
kwargs = {
|
||||
"version": "v4",
|
||||
"expiration": timedelta(minutes=expiration_minutes),
|
||||
"method": method,
|
||||
}
|
||||
|
||||
|
||||
# For PUT requests, we need to specify the content type in headers
|
||||
if method == "PUT" and content_type:
|
||||
kwargs["headers"] = {"Content-Type": content_type}
|
||||
|
||||
|
||||
# Check if we're using compute credentials (Cloud Run/GCE)
|
||||
# These need to use IAM signBlob via service_account_email + access_token
|
||||
if hasattr(credentials, 'service_account_email'):
|
||||
# Refresh credentials to get a valid access token
|
||||
auth_request = requests.Request()
|
||||
credentials.refresh(auth_request)
|
||||
|
||||
|
||||
kwargs["service_account_email"] = credentials.service_account_email
|
||||
kwargs["access_token"] = credentials.token
|
||||
|
||||
url = blob.generate_signed_url(**kwargs)
|
||||
|
||||
|
||||
return blob.generate_signed_url(**kwargs)
|
||||
|
||||
# Bounded admission: refuse immediately when signing is saturated (all workers
|
||||
# stalled + queue full) instead of enqueuing work that would just time out.
|
||||
if not _SIGNING_SLOTS.acquire(blocking=False):
|
||||
logger.error(
|
||||
f"Signing saturated (>{_SIGNING_MAX_INFLIGHT} in flight) — refusing signed "
|
||||
f"{method} URL for {blob_path}; IAM signBlob likely stalled"
|
||||
)
|
||||
raise SignedUrlTimeout(f"Signing saturated for {blob_path}")
|
||||
|
||||
future = _SIGNING_EXECUTOR.submit(_sign)
|
||||
# Release the slot whenever the work settles — success, error, OR cancellation
|
||||
# (cancelling a still-queued future fires done callbacks, so queued-but-abandoned
|
||||
# work frees its slot; a running future frees it only when it actually returns).
|
||||
future.add_done_callback(lambda _f: _SIGNING_SLOTS.release())
|
||||
try:
|
||||
url = future.result(timeout=SIGNED_URL_TIMEOUT_S)
|
||||
logger.info(f"Generated signed {method} URL for {blob_path}")
|
||||
return url
|
||||
except concurrent.futures.TimeoutError:
|
||||
# Don't wait on the leaked thread — it caps itself at the library's own
|
||||
# ~120s timeout and frees its (bounded) pool slot on its own. We bail now.
|
||||
future.cancel()
|
||||
logger.error(
|
||||
f"Timed out (>{SIGNED_URL_TIMEOUT_S:g}s) generating signed {method} URL "
|
||||
f"for {blob_path} — IAM signBlob likely stalled"
|
||||
)
|
||||
raise SignedUrlTimeout(
|
||||
f"Signed URL generation timed out for {blob_path}"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Error generating signed {method} URL for {blob_path}: {e}")
|
||||
raise
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -158,19 +158,15 @@ class TestParallelProcessingCoordination:
|
||||
# Verify update_job was called to set the lyrics_complete flag
|
||||
job_manager.firestore.update_job.assert_called()
|
||||
|
||||
def test_both_complete_triggers_screens(self, job_manager, mock_firestore_service):
|
||||
"""Test that screens worker is triggered when both complete."""
|
||||
# First call: Job with audio already complete (for update_state_data)
|
||||
# Second call: Job with both complete (for check_parallel_processing_complete)
|
||||
job_audio_only = Job(
|
||||
job_id="test-parallel-003",
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
status=JobStatus.DOWNLOADING,
|
||||
created_at=datetime.now(UTC),
|
||||
updated_at=datetime.now(UTC),
|
||||
state_data={'audio_complete': True},
|
||||
)
|
||||
@pytest.mark.asyncio
|
||||
async def test_both_complete_triggers_screens(self, job_manager, mock_firestore_service):
|
||||
"""When lyrics is complete and the job is still DOWNLOADING, advancing
|
||||
triggers the screens worker via an AWAITED (durable) dispatch.
|
||||
|
||||
mark_lyrics_complete now only sets the flag; advance_to_screens_if_ready
|
||||
does the dispatch (the old fire-and-forget trigger was lost on Cloud Run
|
||||
Job loop teardown, orphaning jobs at `downloading`).
|
||||
"""
|
||||
job_both_complete = Job(
|
||||
job_id="test-parallel-003",
|
||||
artist="Test Artist",
|
||||
@@ -180,17 +176,17 @@ class TestParallelProcessingCoordination:
|
||||
updated_at=datetime.now(UTC),
|
||||
state_data={'audio_complete': True, 'lyrics_complete': True},
|
||||
)
|
||||
# Return different jobs on subsequent calls
|
||||
job_manager.firestore.get_job.side_effect = [job_audio_only, job_both_complete]
|
||||
job_manager.firestore.get_job.return_value = job_both_complete
|
||||
job_manager.firestore.update_job.return_value = True
|
||||
|
||||
# Mock the screens worker trigger
|
||||
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
|
||||
# Now lyrics completes
|
||||
mock_ws = MagicMock()
|
||||
mock_ws.trigger_screens_worker = AsyncMock(return_value=True)
|
||||
with patch("backend.services.worker_service.get_worker_service", return_value=mock_ws):
|
||||
job_manager.mark_lyrics_complete("test-parallel-003")
|
||||
result = await job_manager.advance_to_screens_if_ready("test-parallel-003")
|
||||
|
||||
# Verify screens worker was triggered (both complete)
|
||||
mock_trigger.assert_called_once_with("test-parallel-003")
|
||||
assert result is True
|
||||
mock_ws.trigger_screens_worker.assert_awaited_once_with("test-parallel-003")
|
||||
|
||||
|
||||
class TestStateTransitionValidation:
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Regression: admin endpoints that log the caller must not 500.
|
||||
|
||||
`require_admin` returns an `AuthResult` object (not a tuple). Three admin endpoints
|
||||
logged `auth_data[0]`, which raised `TypeError: 'AuthResult' object is not
|
||||
subscriptable` and returned 500 (prod: POST /jobs/{id}/reset-worker-state on
|
||||
2026-09-15). These endpoints had no test coverage, so the bug shipped. This test
|
||||
locks in the fix (`auth_data.user_email`).
|
||||
"""
|
||||
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, AuthResult, UserType
|
||||
|
||||
app = FastAPI()
|
||||
app.include_router(router, prefix="/api")
|
||||
|
||||
|
||||
def _mock_admin():
|
||||
return AuthResult(
|
||||
is_valid=True,
|
||||
user_type=UserType.ADMIN,
|
||||
remaining_uses=999,
|
||||
message="Admin authenticated",
|
||||
user_email="admin@example.com",
|
||||
is_admin=True,
|
||||
)
|
||||
|
||||
|
||||
app.dependency_overrides[require_admin] = _mock_admin
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def test_reset_worker_state_does_not_500(client):
|
||||
"""POST /jobs/{id}/reset-worker-state must succeed — previously raised
|
||||
TypeError on `auth_data[0]` because require_admin returns an AuthResult."""
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = Mock() # truthy job
|
||||
|
||||
with patch("backend.services.job_manager.JobManager", return_value=mock_jm):
|
||||
resp = client.post("/api/admin/jobs/test-123/reset-worker-state")
|
||||
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert resp.json()["status"] == "success"
|
||||
# video/render/screens progress states reset
|
||||
assert mock_jm.update_state_data.call_count == 3
|
||||
|
||||
|
||||
def test_clear_all_flacfetch_cache_does_not_500(client):
|
||||
"""DELETE /cache must succeed — same `auth_data[0]` bug on the admin log line."""
|
||||
mock_client = Mock()
|
||||
|
||||
async def _clear():
|
||||
return 7
|
||||
|
||||
mock_client.clear_all_cache = _clear
|
||||
|
||||
with patch("backend.api.routes.admin.get_flacfetch_client", return_value=mock_client):
|
||||
resp = client.delete("/api/admin/cache")
|
||||
|
||||
assert resp.status_code == 200, resp.text
|
||||
assert resp.json()["deleted_count"] == 7
|
||||
@@ -439,3 +439,40 @@ class TestUpdateJobUserEmailAutoCreate:
|
||||
assert response.status_code == 400
|
||||
assert "valid email" in response.json()["detail"]
|
||||
mock_jm.update_job.assert_not_called()
|
||||
|
||||
|
||||
class TestUpdateJobMadeForYou:
|
||||
"""made_for_you is editable so admin batches can opt jobs out of the
|
||||
stale-review auto-expiry (stale_review_processor skips MFY jobs)."""
|
||||
|
||||
def test_made_for_you_is_editable(self, client, mock_job):
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm.update_job.return_value = True
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.patch(
|
||||
"/api/admin/jobs/test-job-123",
|
||||
json={"made_for_you": True},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert "made_for_you" in response.json()["updated_fields"]
|
||||
call_args = mock_jm.update_job.call_args
|
||||
assert call_args[0][1]["made_for_you"] is True
|
||||
|
||||
def test_made_for_you_rejects_non_bool(self, client, mock_job):
|
||||
with patch('backend.api.routes.admin.JobManager') as mock_jm_class:
|
||||
mock_jm = Mock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
mock_jm_class.return_value = mock_jm
|
||||
|
||||
response = client.patch(
|
||||
"/api/admin/jobs/test-job-123",
|
||||
json={"made_for_you": "yes"},
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "boolean" in response.json()["detail"]
|
||||
mock_jm.update_job.assert_not_called()
|
||||
@@ -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
|
||||
@@ -411,3 +411,250 @@ class TestLoadCachedWaveform:
|
||||
|
||||
assert result is None
|
||||
|
||||
|
||||
|
||||
class TestGetReviewWaveform:
|
||||
"""Persistent GCS cache for the review-page waveform (concurrent-load fix)."""
|
||||
|
||||
def _service(self, mock_storage_class, mock_waveform_class):
|
||||
from backend.services.audio_analysis_service import AudioAnalysisService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage_class.return_value = mock_storage
|
||||
mock_waveform = Mock()
|
||||
mock_waveform.generate_data_only.return_value = ([0.1, 0.9], 200.0)
|
||||
mock_waveform_class.return_value = mock_waveform
|
||||
return AudioAnalysisService(), mock_storage, mock_waveform
|
||||
|
||||
@patch("backend.services.audio_analysis_service.StorageService")
|
||||
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
|
||||
@patch("backend.services.audio_analysis_service.WaveformGenerator")
|
||||
def test_cache_hit_skips_decode(
|
||||
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
|
||||
):
|
||||
service, storage, waveform = self._service(mock_storage_class, mock_waveform_class)
|
||||
storage.file_exists.return_value = True
|
||||
storage.download_json.return_value = {
|
||||
"amplitudes": [0.3, 0.7],
|
||||
"duration_seconds": 123.0,
|
||||
"num_points": 1000,
|
||||
"source_gcs_path": "jobs/j1/stems/backing_vocals.flac",
|
||||
}
|
||||
|
||||
amps, duration = service.get_review_waveform(
|
||||
"jobs/j1/stems/backing_vocals.flac", "j1", 1000
|
||||
)
|
||||
|
||||
assert amps == [0.3, 0.7]
|
||||
assert duration == 123.0
|
||||
waveform.generate_data_only.assert_not_called()
|
||||
storage.upload_json.assert_not_called()
|
||||
|
||||
@patch("backend.services.audio_analysis_service.StorageService")
|
||||
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
|
||||
@patch("backend.services.audio_analysis_service.WaveformGenerator")
|
||||
def test_cache_miss_computes_and_uploads(
|
||||
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
|
||||
):
|
||||
service, storage, waveform = self._service(mock_storage_class, mock_waveform_class)
|
||||
storage.file_exists.return_value = False
|
||||
|
||||
amps, duration = service.get_review_waveform(
|
||||
"jobs/j1/stems/backing_vocals.flac", "j1", 1000
|
||||
)
|
||||
|
||||
assert amps == [0.1, 0.9]
|
||||
assert duration == 200.0
|
||||
waveform.generate_data_only.assert_called_once()
|
||||
storage.upload_json.assert_called_once()
|
||||
cache_path, payload = storage.upload_json.call_args[0]
|
||||
assert cache_path == "jobs/j1/review-audio/waveform_review_1000.json"
|
||||
assert payload["source_gcs_path"] == "jobs/j1/stems/backing_vocals.flac"
|
||||
assert payload["num_points"] == 1000
|
||||
|
||||
@patch("backend.services.audio_analysis_service.StorageService")
|
||||
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
|
||||
@patch("backend.services.audio_analysis_service.WaveformGenerator")
|
||||
def test_stale_source_recomputes(
|
||||
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
|
||||
):
|
||||
"""A cache written for an old/replaced stem path must not be served."""
|
||||
service, storage, waveform = self._service(mock_storage_class, mock_waveform_class)
|
||||
storage.file_exists.return_value = True
|
||||
storage.download_json.return_value = {
|
||||
"amplitudes": [0.3, 0.7],
|
||||
"duration_seconds": 123.0,
|
||||
"num_points": 1000,
|
||||
"source_gcs_path": "jobs/j1/stems/OLD_backing_vocals.flac",
|
||||
}
|
||||
|
||||
amps, _ = service.get_review_waveform(
|
||||
"jobs/j1/stems/backing_vocals.flac", "j1", 1000
|
||||
)
|
||||
|
||||
assert amps == [0.1, 0.9] # freshly computed, not the stale cache
|
||||
waveform.generate_data_only.assert_called_once()
|
||||
|
||||
@patch("backend.services.audio_analysis_service.StorageService")
|
||||
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
|
||||
@patch("backend.services.audio_analysis_service.WaveformGenerator")
|
||||
def test_num_points_mismatch_recomputes(
|
||||
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
|
||||
):
|
||||
service, storage, waveform = self._service(mock_storage_class, mock_waveform_class)
|
||||
storage.file_exists.return_value = True
|
||||
storage.download_json.return_value = {
|
||||
"amplitudes": [0.3, 0.7],
|
||||
"duration_seconds": 123.0,
|
||||
"num_points": 500,
|
||||
"source_gcs_path": "jobs/j1/stems/backing_vocals.flac",
|
||||
}
|
||||
|
||||
_, _ = service.get_review_waveform(
|
||||
"jobs/j1/stems/backing_vocals.flac", "j1", 1000
|
||||
)
|
||||
waveform.generate_data_only.assert_called_once()
|
||||
|
||||
@patch("backend.services.audio_analysis_service.StorageService")
|
||||
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
|
||||
@patch("backend.services.audio_analysis_service.WaveformGenerator")
|
||||
def test_prefers_transcoded_ogg_on_miss(
|
||||
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
|
||||
):
|
||||
"""On a cache miss, decode the small review OGG when it exists."""
|
||||
service, storage, waveform = self._service(mock_storage_class, mock_waveform_class)
|
||||
# Cache JSON absent, transcoded OGG present.
|
||||
storage.file_exists.side_effect = lambda p: p.endswith(".ogg")
|
||||
|
||||
transcoding = Mock()
|
||||
transcoding.get_transcoded_cache_path.return_value = (
|
||||
"jobs/j1/review-audio/backing_vocals.ogg"
|
||||
)
|
||||
|
||||
with patch.object(service, "get_waveform_data", wraps=None) as mock_get:
|
||||
mock_get.return_value = ([0.5], 90.0)
|
||||
service.get_review_waveform(
|
||||
"jobs/j1/stems/backing_vocals.flac", "j1", 1000, transcoding
|
||||
)
|
||||
assert (
|
||||
mock_get.call_args.kwargs["gcs_audio_path"]
|
||||
== "jobs/j1/review-audio/backing_vocals.ogg"
|
||||
)
|
||||
|
||||
@patch("backend.services.audio_analysis_service.StorageService")
|
||||
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
|
||||
@patch("backend.services.audio_analysis_service.WaveformGenerator")
|
||||
def test_cache_upload_failure_still_returns_data(
|
||||
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
|
||||
):
|
||||
service, storage, waveform = self._service(mock_storage_class, mock_waveform_class)
|
||||
storage.file_exists.return_value = False
|
||||
storage.upload_json.side_effect = Exception("GCS write denied")
|
||||
|
||||
amps, duration = service.get_review_waveform(
|
||||
"jobs/j1/stems/backing_vocals.flac", "j1", 1000
|
||||
)
|
||||
assert amps == [0.1, 0.9]
|
||||
assert duration == 200.0
|
||||
|
||||
|
||||
class TestGetVocalsPeaks:
|
||||
"""Persistent GCS cache of the vocals peak envelope (sub-second strips)."""
|
||||
|
||||
def _service(self, mock_storage_class, mock_waveform_class):
|
||||
import numpy as np
|
||||
from backend.services.audio_analysis_service import AudioAnalysisService
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage_class.return_value = mock_storage
|
||||
mock_waveform = Mock()
|
||||
mock_waveform.generate_peaks.return_value = (
|
||||
np.array([0.0, 0.5, 1.0], dtype=np.float32), 3.0
|
||||
)
|
||||
mock_waveform_class.return_value = mock_waveform
|
||||
return AudioAnalysisService(), mock_storage, mock_waveform
|
||||
|
||||
@patch("backend.services.audio_analysis_service.StorageService")
|
||||
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
|
||||
@patch("backend.services.audio_analysis_service.WaveformGenerator")
|
||||
def test_cache_hit_skips_decode(
|
||||
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
|
||||
):
|
||||
service, storage, waveform = self._service(mock_storage_class, mock_waveform_class)
|
||||
cached = {
|
||||
"peaks_b64": "AAA=",
|
||||
"encoding": "u8",
|
||||
"peaks_per_second": 400,
|
||||
"duration_seconds": 3.0,
|
||||
"source_gcs_path": "jobs/j1/stems/vocals_clean.flac",
|
||||
}
|
||||
storage.file_exists.return_value = True
|
||||
storage.download_json.return_value = cached
|
||||
|
||||
result = service.get_vocals_peaks("jobs/j1/stems/vocals_clean.flac", "j1", 400)
|
||||
|
||||
assert result == cached
|
||||
waveform.generate_peaks.assert_not_called()
|
||||
storage.upload_json.assert_not_called()
|
||||
|
||||
@patch("backend.services.audio_analysis_service.StorageService")
|
||||
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
|
||||
@patch("backend.services.audio_analysis_service.WaveformGenerator")
|
||||
def test_cache_miss_computes_quantizes_and_uploads(
|
||||
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
|
||||
):
|
||||
import base64
|
||||
|
||||
service, storage, waveform = self._service(mock_storage_class, mock_waveform_class)
|
||||
storage.file_exists.return_value = False
|
||||
|
||||
result = service.get_vocals_peaks("jobs/j1/stems/vocals_clean.flac", "j1", 400)
|
||||
|
||||
assert result["encoding"] == "u8"
|
||||
assert result["peaks_per_second"] == 400
|
||||
assert result["duration_seconds"] == 3.0
|
||||
# [0.0, 0.5, 1.0] -> uint8 [0, 128, 255]
|
||||
assert list(base64.b64decode(result["peaks_b64"])) == [0, 128, 255]
|
||||
cache_path, payload = storage.upload_json.call_args[0]
|
||||
assert cache_path == "jobs/j1/review-audio/vocals_peaks_400.json"
|
||||
assert payload == result
|
||||
|
||||
@patch("backend.services.audio_analysis_service.StorageService")
|
||||
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
|
||||
@patch("backend.services.audio_analysis_service.WaveformGenerator")
|
||||
def test_stale_source_recomputes(
|
||||
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
|
||||
):
|
||||
service, storage, waveform = self._service(mock_storage_class, mock_waveform_class)
|
||||
storage.file_exists.return_value = True
|
||||
storage.download_json.return_value = {
|
||||
"peaks_b64": "AAA=",
|
||||
"peaks_per_second": 400,
|
||||
"duration_seconds": 3.0,
|
||||
"source_gcs_path": "jobs/j1/stems/OLD.flac",
|
||||
}
|
||||
|
||||
service.get_vocals_peaks("jobs/j1/stems/vocals_clean.flac", "j1", 400)
|
||||
waveform.generate_peaks.assert_called_once()
|
||||
|
||||
@patch("backend.services.audio_analysis_service.StorageService")
|
||||
@patch("backend.services.audio_analysis_service.AudioAnalyzer")
|
||||
@patch("backend.services.audio_analysis_service.WaveformGenerator")
|
||||
def test_prefers_transcoded_ogg_and_survives_upload_failure(
|
||||
self, mock_waveform_class, mock_analyzer_class, mock_storage_class
|
||||
):
|
||||
service, storage, waveform = self._service(mock_storage_class, mock_waveform_class)
|
||||
storage.file_exists.side_effect = lambda p: p.endswith(".ogg")
|
||||
storage.upload_json.side_effect = Exception("GCS write denied")
|
||||
|
||||
transcoding = Mock()
|
||||
transcoding.get_transcoded_cache_path.return_value = "jobs/j1/review-audio/vocals_clean.ogg"
|
||||
|
||||
result = service.get_vocals_peaks(
|
||||
"jobs/j1/stems/vocals_clean.flac", "j1", 400, transcoding
|
||||
)
|
||||
|
||||
# Decoded from the small OGG, and data still returned despite upload failure
|
||||
downloaded_path = storage.download_file.call_args[0][0]
|
||||
assert downloaded_path == "jobs/j1/review-audio/vocals_clean.ogg"
|
||||
assert result["source_gcs_path"] == "jobs/j1/stems/vocals_clean.flac"
|
||||
@@ -136,6 +136,26 @@ class TestGetReviewAudioUrl:
|
||||
"jobs/abc/review-audio/song.ogg", 120
|
||||
)
|
||||
|
||||
def test_signed_url_timeout_short_circuits_fallbacks(self):
|
||||
"""A signing stall must NOT trigger the FLAC/cache fallbacks (they'd stall too).
|
||||
|
||||
On a cache hit the first sign is the only sign attempted; a SignedUrlTimeout
|
||||
propagates immediately so the caller degrades fast.
|
||||
"""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
from backend.services.storage_service import SignedUrlTimeout
|
||||
|
||||
mock_storage = Mock()
|
||||
mock_storage.file_exists.return_value = True # cache hit
|
||||
mock_storage.generate_signed_url.side_effect = SignedUrlTimeout("stalled")
|
||||
service = AudioTranscodingService(storage_service=mock_storage)
|
||||
|
||||
with pytest.raises(SignedUrlTimeout):
|
||||
service.get_review_audio_url("jobs/abc/input/song.flac")
|
||||
|
||||
# Exactly one sign attempt — no fallback re-signing.
|
||||
assert mock_storage.generate_signed_url.call_count == 1
|
||||
|
||||
def test_falls_back_to_flac_on_error(self):
|
||||
"""On transcoding error with no cache, fall back to original FLAC signed URL."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
@@ -30,24 +30,24 @@ class TestBatchHelper:
|
||||
async def test_batch_maps_community_results(self, monkeypatch):
|
||||
from backend.services import karaokenerds_service as kn
|
||||
|
||||
async def fake_single(artist, title):
|
||||
if title == "One More Time":
|
||||
return {
|
||||
"has_community": True,
|
||||
"songs": [{"community_tracks": [{"brand_name": "KV"}, {"brand_name": "KaraFun"}]}],
|
||||
"best_youtube_url": None,
|
||||
}
|
||||
return {"has_community": False, "songs": [], "best_youtube_url": None}
|
||||
# Seed the in-process community index (the batch helper reads it directly).
|
||||
# Brand is a CODE in the catalog; brand names resolve for display.
|
||||
rows = [
|
||||
{"Artist": "Daft Punk", "Title": "One More Time", "Brand": "KV", "Watch": ""},
|
||||
{"Artist": "Daft Punk", "Title": "One More Time", "Brand": "OBSK", "Watch": ""},
|
||||
]
|
||||
kn._reset_index_for_tests()
|
||||
monkeypatch.setattr(kn, "_load_index", lambda: kn._build_index(rows))
|
||||
|
||||
monkeypatch.setattr(kn, "check_community_versions", fake_single)
|
||||
out = await kn.check_community_versions_batch(
|
||||
[{"artist": "Daft Punk", "title": "One More Time"},
|
||||
{"artist": "Daft Punk", "title": "Aerodynamic"}]
|
||||
)
|
||||
assert out[0]["available"] is True
|
||||
assert out[0]["brands"] == ["KV", "KaraFun"]
|
||||
assert out[0]["brands"] == ["Karaoke Version", "ObsKure Karaoke"]
|
||||
assert out[1]["available"] is False
|
||||
assert out[1]["brand_count"] == 0
|
||||
kn._reset_index_for_tests()
|
||||
|
||||
|
||||
class TestAvailabilityRoute:
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Tests for POST /api/client-events (degradation telemetry)."""
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from backend.api.routes import client_events
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
app = FastAPI()
|
||||
app.include_router(client_events.router, prefix="/api")
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def fresh_limiter_and_db(monkeypatch):
|
||||
monkeypatch.setattr(client_events, "_limiter", client_events.RateLimiter(max_per_minute=30))
|
||||
db = MagicMock()
|
||||
monkeypatch.setattr(client_events, "_db_singleton", db)
|
||||
return db
|
||||
|
||||
|
||||
def _event(**overrides):
|
||||
payload = {
|
||||
"type": "banner_unavailable",
|
||||
"url": "https://gen.nomadkaraoke.com/app/jobs?token=SECRET#/abc123/review",
|
||||
"job_id": "abc123",
|
||||
"locale": "en",
|
||||
"release": "deadbeef",
|
||||
"detail": {"stall_ms": 21000, "probe_ok": False},
|
||||
}
|
||||
payload.update(overrides)
|
||||
return payload
|
||||
|
||||
|
||||
class TestReportClientEvent:
|
||||
def test_valid_event_persists_to_firestore(self, client, fresh_limiter_and_db):
|
||||
resp = client.post("/api/client-events", json=_event())
|
||||
|
||||
assert resp.status_code == 202
|
||||
assert resp.json() == {"status": "recorded"}
|
||||
fresh_limiter_and_db.collection.assert_called_once_with("client_events")
|
||||
(doc,) = fresh_limiter_and_db.collection.return_value.add.call_args[0]
|
||||
assert doc["type"] == "banner_unavailable"
|
||||
assert doc["job_id"] == "abc123"
|
||||
assert doc["detail"] == {"stall_ms": 21000, "probe_ok": False}
|
||||
# Query string (may carry tokens) must be stripped before persisting.
|
||||
assert "SECRET" not in doc["url"]
|
||||
|
||||
def test_unknown_event_type_rejected(self, client):
|
||||
resp = client.post("/api/client-events", json=_event(type="something_else"))
|
||||
assert resp.status_code == 422
|
||||
|
||||
def test_rate_limited(self, client, monkeypatch):
|
||||
monkeypatch.setattr(client_events, "_limiter", client_events.RateLimiter(max_per_minute=2))
|
||||
assert client.post("/api/client-events", json=_event()).status_code == 202
|
||||
assert client.post("/api/client-events", json=_event()).status_code == 202
|
||||
assert client.post("/api/client-events", json=_event()).status_code == 429
|
||||
|
||||
def test_bot_user_agent_ignored(self, client, fresh_limiter_and_db):
|
||||
resp = client.post(
|
||||
"/api/client-events",
|
||||
json=_event(),
|
||||
headers={"User-Agent": "Googlebot/2.1 (+http://www.google.com/bot.html)"},
|
||||
)
|
||||
assert resp.status_code == 202
|
||||
assert resp.json() == {"status": "ignored"}
|
||||
fresh_limiter_and_db.collection.assert_not_called()
|
||||
|
||||
def test_firestore_failure_still_returns_202(self, client, fresh_limiter_and_db):
|
||||
fresh_limiter_and_db.collection.return_value.add.side_effect = Exception("firestore down")
|
||||
resp = client.post("/api/client-events", json=_event())
|
||||
assert resp.status_code == 202 # telemetry must never error back to users
|
||||
|
||||
def test_detail_is_capped(self):
|
||||
big = {f"key{i}": "x" * 500 for i in range(30)}
|
||||
capped = client_events._capped_detail(big)
|
||||
assert len(capped) == 12
|
||||
assert all(len(v) <= 200 for v in capped.values())
|
||||
assert client_events._capped_detail(None) == {}
|
||||
assert client_events._capped_detail("not a dict") == {}
|
||||
@@ -148,6 +148,56 @@ class TestGetCorrectionDataReturnsUpdatedCorrections:
|
||||
# Verify the returned data is the original
|
||||
assert result["corrected_segments"][0]["text"] == "Hello world"
|
||||
|
||||
def test_returns_proxy_audio_urls_and_omits_waveform_without_signing(
|
||||
self, mock_job, original_corrections
|
||||
):
|
||||
"""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
|
||||
|
||||
# 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"
|
||||
}
|
||||
mock_job.file_urls["stems"] = {
|
||||
"instrumental_clean": "jobs/test-job-123/stems/instrumental_clean.flac",
|
||||
"instrumental_with_backing": "jobs/test-job-123/stems/instrumental_with_backing.flac",
|
||||
}
|
||||
|
||||
with patch("backend.api.routes.review.JobManager") as MockJobManager, \
|
||||
patch("backend.api.routes.review.StorageService") as MockStorageService, \
|
||||
patch("backend.api.routes.review._dev_audio_proxy_enabled", return_value=False):
|
||||
|
||||
job_manager = MockJobManager.return_value
|
||||
job_manager.get_job.return_value = mock_job
|
||||
|
||||
storage = MockStorageService.return_value
|
||||
storage.file_exists.side_effect = lambda path: "corrections_updated" not in path
|
||||
storage.download_json.return_value = original_corrections.copy()
|
||||
|
||||
import asyncio
|
||||
result = asyncio.run(
|
||||
get_correction_data("test-job-123", ("user@test.com", "job_owner"))
|
||||
)
|
||||
|
||||
# Endpoint succeeded with the lyrics payload.
|
||||
assert result["corrected_segments"][0]["text"] == "Hello world"
|
||||
# Waveform URL is not emitted at all (dead field, no consumer).
|
||||
assert "backing_vocals_waveform_url" not in result
|
||||
# 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": "/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
|
||||
):
|
||||
|
||||
@@ -8,6 +8,7 @@ from fastapi import HTTPException
|
||||
from backend.api.routes.admin import (
|
||||
CommunityReviewActionBody,
|
||||
action_community_review,
|
||||
list_community_requests,
|
||||
)
|
||||
from backend.models.song_request import SongRequest
|
||||
|
||||
@@ -105,3 +106,26 @@ async def test_make_failure_raises_500():
|
||||
with pytest.raises(HTTPException) as exc:
|
||||
await _call(_patches(svc, provision=provision), "req1", "make")
|
||||
assert exc.value.status_code == 500
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_community_requests_maps_all_statuses():
|
||||
svc = MagicMock()
|
||||
published = _req(
|
||||
id="pub", status="published", review_state=None,
|
||||
job_id="j-abc12345", youtube_url="https://youtu.be/pub",
|
||||
owner_email="voter@x.com",
|
||||
)
|
||||
open_req = _req(id="op", status="open", review_state=None, job_id=None, youtube_url=None)
|
||||
svc.list_all.return_value = [published, open_req]
|
||||
with patch("backend.services.song_request_service.get_song_request_service",
|
||||
MagicMock(return_value=svc)):
|
||||
res = await list_community_requests(auth_data=("admin", None, 0))
|
||||
assert [r.id for r in res.requests] == ["pub", "op"]
|
||||
pub = res.requests[0]
|
||||
assert pub.status == "published"
|
||||
assert pub.youtube_url == "https://youtu.be/pub"
|
||||
assert pub.owner_email == "voter@x.com"
|
||||
assert pub.created_at is not None # datetime serialized to iso string
|
||||
# Open request carries no job/video links.
|
||||
assert res.requests[1].job_id is None and res.requests[1].youtube_url is None
|
||||
@@ -1,10 +1,14 @@
|
||||
"""Unit tests for the requests-board publish fan-out in the YouTube queue processor."""
|
||||
"""Unit tests for the requests-board publish fan-out (backend.services.community_publish).
|
||||
|
||||
The fan-out fires from BOTH publish paths (youtube_queue_processor and the direct
|
||||
video_worker distribution), so it lives in a shared module and is tested here once.
|
||||
"""
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.models.song_request import SongRequest
|
||||
from backend.workers import youtube_queue_processor as yqp
|
||||
from backend.services import community_publish as cp
|
||||
|
||||
|
||||
def _req(**over):
|
||||
@@ -34,7 +38,8 @@ async def test_non_community_job_is_ignored():
|
||||
notifier = MagicMock()
|
||||
p1, p2 = _ctx(svc, notifier)
|
||||
with p1, p2:
|
||||
await yqp._notify_community_voters("j1", {}, "https://youtu.be/x")
|
||||
result = await cp.notify_community_publish("j1", "https://youtu.be/x")
|
||||
assert result is None
|
||||
svc.mark_published.assert_not_called()
|
||||
|
||||
|
||||
@@ -47,7 +52,8 @@ async def test_publishes_and_fans_out_excluding_owner():
|
||||
notifier.send_community_track_live_email = AsyncMock(return_value=True)
|
||||
p1, p2 = _ctx(svc, notifier)
|
||||
with p1, p2:
|
||||
await yqp._notify_community_voters("j1", {}, "https://youtu.be/x")
|
||||
result = await cp.notify_community_publish("j1", "https://youtu.be/x")
|
||||
assert result == "req1"
|
||||
svc.mark_published.assert_called_once_with("req1", "https://youtu.be/x")
|
||||
# Owner excluded (already got the completion email); two voters emailed.
|
||||
emailed = {c.kwargs["to_email"] for c in notifier.send_community_track_live_email.call_args_list}
|
||||
@@ -69,7 +75,7 @@ async def test_skips_already_notified_voters_and_retries_failures():
|
||||
notifier.send_community_track_live_email = AsyncMock(return_value=False) # v3 send fails
|
||||
p1, p2 = _ctx(svc, notifier)
|
||||
with p1, p2:
|
||||
await yqp._notify_community_voters("j1", {}, "https://youtu.be/x")
|
||||
await cp.notify_community_publish("j1", "https://youtu.be/x")
|
||||
# Only the un-notified voter (v3) is attempted; v2 skipped.
|
||||
emailed = {c.kwargs["to_email"] for c in notifier.send_community_track_live_email.call_args_list}
|
||||
assert emailed == {"v3@x.com"}
|
||||
@@ -85,7 +91,97 @@ async def test_already_notified_does_not_resend():
|
||||
notifier.send_community_track_live_email = AsyncMock(return_value=True)
|
||||
p1, p2 = _ctx(svc, notifier)
|
||||
with p1, p2:
|
||||
await yqp._notify_community_voters("j1", {}, "https://youtu.be/x")
|
||||
await cp.notify_community_publish("j1", "https://youtu.be/x")
|
||||
svc.mark_published.assert_called_once() # republish (mark) is safe/idempotent
|
||||
notifier.send_community_track_live_email.assert_not_called()
|
||||
svc.mark_voters_notified.assert_not_called()
|
||||
|
||||
|
||||
# --- youtube-url resolution ---------------------------------------------------
|
||||
|
||||
def test_youtube_url_prefers_state_data():
|
||||
job = MagicMock()
|
||||
job.state_data = {"youtube_url": "https://youtu.be/state"}
|
||||
job.processing_metadata = {"distribution": {"youtube_video_url": "https://youtu.be/dist"}}
|
||||
assert cp._youtube_url_for_job(job) == "https://youtu.be/state"
|
||||
|
||||
|
||||
def test_youtube_url_falls_back_to_distribution_metadata():
|
||||
job = MagicMock()
|
||||
job.state_data = {}
|
||||
job.processing_metadata = {"distribution": {"youtube_video_url": "https://youtu.be/dist"}}
|
||||
assert cp._youtube_url_for_job(job) == "https://youtu.be/dist"
|
||||
|
||||
|
||||
def test_youtube_url_none_when_unpublished():
|
||||
job = MagicMock()
|
||||
job.state_data = {}
|
||||
job.processing_metadata = {"distribution": {}}
|
||||
assert cp._youtube_url_for_job(job) is None
|
||||
assert cp._youtube_url_for_job(None) is None
|
||||
|
||||
|
||||
# --- reconcile / backfill -----------------------------------------------------
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reconcile_publishes_live_in_progress_requests():
|
||||
svc = MagicMock()
|
||||
live = _req(id="r-live", job_id="j-live", voters_notified=True)
|
||||
unpub = _req(id="r-unpub", job_id="j-unpub", voters_notified=True)
|
||||
nojob = _req(id="r-nojob", job_id=None)
|
||||
svc.list_in_progress.return_value = [live, unpub, nojob]
|
||||
svc.list_published_unnotified.return_value = []
|
||||
# get_by_job_id (used inside notify_community_publish) resolves the live request.
|
||||
svc.get_by_job_id.side_effect = lambda jid: {"j-live": live}.get(jid)
|
||||
|
||||
live_job = MagicMock(state_data={"youtube_url": "https://youtu.be/live"}, processing_metadata={})
|
||||
unpub_job = MagicMock(state_data={}, processing_metadata={"distribution": {}})
|
||||
|
||||
jm = MagicMock()
|
||||
jm.get_job.side_effect = lambda jid: {"j-live": live_job, "j-unpub": unpub_job}.get(jid)
|
||||
|
||||
with patch.multiple(
|
||||
"backend.services.song_request_service",
|
||||
get_song_request_service=MagicMock(return_value=svc),
|
||||
), patch("backend.services.job_manager.JobManager", MagicMock(return_value=jm)):
|
||||
result = await cp.reconcile_community_publishes()
|
||||
|
||||
assert result["scanned"] == 3
|
||||
published_ids = {p["request_id"] for p in result["published"]}
|
||||
assert published_ids == {"r-live"}
|
||||
assert result["retried_fanout"] == 0
|
||||
svc.mark_published.assert_called_once_with("r-live", "https://youtu.be/live")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reconcile_retries_published_but_unnotified_fanout():
|
||||
# A published pick whose voter fan-out never completed is retried using the
|
||||
# URL already on the request (no job lookup needed).
|
||||
svc = MagicMock()
|
||||
svc.list_in_progress.return_value = []
|
||||
stuck = _req(
|
||||
id="r-stuck", job_id="j-stuck", status="published",
|
||||
youtube_url="https://youtu.be/stuck", voters_notified=False,
|
||||
)
|
||||
svc.list_published_unnotified.return_value = [stuck]
|
||||
svc.get_by_job_id.side_effect = lambda jid: {"j-stuck": stuck}.get(jid)
|
||||
svc.list_upvoters.return_value = ["owner@x.com", "v2@x.com"]
|
||||
notifier = MagicMock()
|
||||
notifier.send_community_track_live_email = AsyncMock(return_value=True)
|
||||
|
||||
jm = MagicMock()
|
||||
jm.get_job.return_value = None # not needed — request already carries the URL
|
||||
|
||||
with patch.multiple(
|
||||
"backend.services.song_request_service",
|
||||
get_song_request_service=MagicMock(return_value=svc),
|
||||
), patch(
|
||||
"backend.services.job_notification_service.get_job_notification_service",
|
||||
MagicMock(return_value=notifier),
|
||||
), patch("backend.services.job_manager.JobManager", MagicMock(return_value=jm)):
|
||||
result = await cp.reconcile_community_publishes()
|
||||
|
||||
assert result["retried_fanout"] == 1
|
||||
# The un-notified voter (not the owner) gets emailed on the retry.
|
||||
emailed = {c.kwargs["to_email"] for c in notifier.send_community_track_live_email.call_args_list}
|
||||
assert emailed == {"v2@x.com"}
|
||||
@@ -155,6 +155,92 @@ class TestPostmarkEmailProvider:
|
||||
|
||||
assert result is False
|
||||
|
||||
def test_suppressed_recipient_flagged_and_not_error(self):
|
||||
"""422 ErrorCode 406 (InactiveRecipient) is benign: SendResult.suppressed
|
||||
is True, provider.last_suppressed is True, and it's logged at INFO not ERROR."""
|
||||
import logging
|
||||
provider = PostmarkEmailProvider(server_token="t", from_email="f@e.com")
|
||||
|
||||
with patch("backend.services.email_service.requests.post") as mock_post:
|
||||
mock_post.return_value = self._mock_response(
|
||||
422, body={"ErrorCode": 406, "Message": "Inactive recipient"}
|
||||
)
|
||||
with self._capture_logs(logging.ERROR) as errors:
|
||||
result = provider.send_email_detailed(
|
||||
to_email="whatever@example.com",
|
||||
subject="Test",
|
||||
html_content="<p>x</p>",
|
||||
)
|
||||
|
||||
assert result.success is False
|
||||
assert result.suppressed is True
|
||||
assert provider.last_suppressed is True
|
||||
# No ERROR-level log for a suppressed recipient (it must not page).
|
||||
assert not errors
|
||||
|
||||
def test_non_suppression_422_is_not_flagged_suppressed(self):
|
||||
"""A 422 with a different ErrorCode (e.g. bad signature) is a real error:
|
||||
suppressed stays False and last_suppressed stays False."""
|
||||
provider = PostmarkEmailProvider(server_token="t", from_email="f@e.com")
|
||||
|
||||
with patch("backend.services.email_service.requests.post") as mock_post:
|
||||
mock_post.return_value = self._mock_response(
|
||||
422, body={"ErrorCode": 10, "Message": "Invalid API token"}
|
||||
)
|
||||
result = provider.send_email_detailed(
|
||||
to_email="user@example.com",
|
||||
subject="Test",
|
||||
html_content="<p>x</p>",
|
||||
)
|
||||
|
||||
assert result.success is False
|
||||
assert result.suppressed is False
|
||||
assert provider.last_suppressed is False
|
||||
|
||||
def test_last_suppressed_reset_on_success(self):
|
||||
"""last_suppressed is cleared on a subsequent successful send."""
|
||||
provider = PostmarkEmailProvider(server_token="t", from_email="f@e.com")
|
||||
|
||||
with patch("backend.services.email_service.requests.post") as mock_post:
|
||||
mock_post.return_value = self._mock_response(
|
||||
422, body={"ErrorCode": 406, "Message": "Inactive recipient"}
|
||||
)
|
||||
provider.send_email_detailed(
|
||||
to_email="whatever@example.com", subject="s", html_content="<p>x</p>"
|
||||
)
|
||||
assert provider.last_suppressed is True
|
||||
|
||||
mock_post.return_value = self._mock_response(200)
|
||||
provider.send_email_detailed(
|
||||
to_email="ok@example.com", subject="s", html_content="<p>x</p>"
|
||||
)
|
||||
assert provider.last_suppressed is False
|
||||
|
||||
@staticmethod
|
||||
def _capture_logs(level):
|
||||
"""Context manager capturing records at >= level from the email_service logger."""
|
||||
import contextlib
|
||||
import logging
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _cm():
|
||||
logger = logging.getLogger("backend.services.email_service")
|
||||
records: list = []
|
||||
|
||||
class _H(logging.Handler):
|
||||
def emit(self, record):
|
||||
if record.levelno >= level:
|
||||
records.append(record)
|
||||
|
||||
h = _H()
|
||||
logger.addHandler(h)
|
||||
try:
|
||||
yield records
|
||||
finally:
|
||||
logger.removeHandler(h)
|
||||
|
||||
return _cm()
|
||||
|
||||
def test_send_email_request_exception(self):
|
||||
import requests as _requests
|
||||
provider = PostmarkEmailProvider(server_token="t", from_email="f@e.com")
|
||||
@@ -189,6 +275,25 @@ class TestEmailServiceProviderSelection:
|
||||
assert isinstance(svc.provider, ConsoleEmailProvider)
|
||||
assert svc.is_configured() is False
|
||||
|
||||
def test_last_send_suppressed_wired_through_send_magic_link(self, monkeypatch):
|
||||
"""A suppressed recipient surfaces on EmailService.last_send_suppressed so
|
||||
route handlers can log it at INFO instead of a scary ERROR."""
|
||||
monkeypatch.setenv("POSTMARK_SERVER_TOKEN", "pm-token")
|
||||
svc = EmailService()
|
||||
|
||||
def _suppressed_response(*args, **kwargs):
|
||||
resp = Mock()
|
||||
resp.status_code = 422
|
||||
resp.json.return_value = {"ErrorCode": 406, "Message": "Inactive recipient"}
|
||||
resp.text = ""
|
||||
return resp
|
||||
|
||||
with patch("backend.services.email_service.requests.post", side_effect=_suppressed_response):
|
||||
sent = svc.send_magic_link("whatever@example.com", "tok123")
|
||||
|
||||
assert sent is False
|
||||
assert svc.last_send_suppressed is True
|
||||
|
||||
|
||||
class TestEmailServiceJobCompletion:
|
||||
"""Tests for job completion email method."""
|
||||
|
||||
@@ -1,219 +1,72 @@
|
||||
"""Route tests for the encoding-worker warmup/heartbeat endpoints.
|
||||
|
||||
Regression context (2026-09-19): these handlers called sync manager methods
|
||||
(Firestore + GCE compute API, 10s+) directly in async handlers, freezing the
|
||||
single event loop — every other request on the instance (the same review
|
||||
page's audio/lyrics loads!) stalled behind a cold-VM warmup. They must run
|
||||
their manager work via asyncio.to_thread.
|
||||
"""
|
||||
Unit tests for encoding worker lifecycle endpoints.
|
||||
|
||||
Tests the warmup and heartbeat API endpoints.
|
||||
|
||||
These endpoints are called from the customer-facing lyrics-review page to
|
||||
pre-warm the encoding VM. They are therefore gated on ``require_review_auth``
|
||||
(review access to a specific job), NOT ``require_admin`` — otherwise every
|
||||
non-admin customer 403s and the pre-warm silently never happens (the bug this
|
||||
suite guards against).
|
||||
"""
|
||||
import logging
|
||||
|
||||
import pytest
|
||||
import asyncio
|
||||
import time
|
||||
from unittest.mock import MagicMock
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
from backend.api.routes.encoding_worker import router, get_worker_manager
|
||||
from backend.api.dependencies import require_admin, require_review_auth
|
||||
from backend.services.encoding_errors import (
|
||||
EncodingWorkerCapacityError,
|
||||
EncodingWorkerStartError,
|
||||
)
|
||||
|
||||
JOB_ID = "test-job-123"
|
||||
WARMUP_URL = f"/api/internal/encoding-worker/warmup/{JOB_ID}"
|
||||
HEARTBEAT_URL = f"/api/internal/encoding-worker/heartbeat/{JOB_ID}"
|
||||
from backend.api.routes import encoding_worker
|
||||
from backend.services.encoding_errors import EncodingWorkerStartError
|
||||
|
||||
|
||||
async def fake_review_auth():
|
||||
"""Override for require_review_auth — stands in for a review user.
|
||||
|
||||
Deliberately returns a *non-admin* auth result (auth_type="full") so the
|
||||
tests exercise the review-scoped path, not admin access.
|
||||
"""
|
||||
return (JOB_ID, "full")
|
||||
|
||||
|
||||
class TestWarmupEndpoint:
|
||||
def setup_method(self):
|
||||
self.mock_manager = MagicMock()
|
||||
self.app = FastAPI()
|
||||
self.app.include_router(router, prefix="/api")
|
||||
self.app.dependency_overrides[require_review_auth] = fake_review_auth
|
||||
self.app.dependency_overrides[get_worker_manager] = lambda: self.mock_manager
|
||||
self.client = TestClient(self.app)
|
||||
|
||||
def test_warmup_starts_stopped_vm(self):
|
||||
self.mock_manager.ensure_primary_running.return_value = {
|
||||
"started": True,
|
||||
"vm_name": "encoding-worker-a",
|
||||
"primary_url": "http://34.1.2.3:8080",
|
||||
}
|
||||
response = self.client.post(WARMUP_URL)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["started"] is True
|
||||
assert data["vm_name"] == "encoding-worker-a"
|
||||
|
||||
def test_warmup_already_running(self):
|
||||
self.mock_manager.ensure_primary_running.return_value = {
|
||||
"started": False,
|
||||
"vm_name": "encoding-worker-a",
|
||||
"primary_url": "http://34.1.2.3:8080",
|
||||
}
|
||||
response = self.client.post(WARMUP_URL)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["started"] is False
|
||||
|
||||
def test_warmup_handles_error(self):
|
||||
self.mock_manager.ensure_primary_running.side_effect = RuntimeError(
|
||||
"VM not found"
|
||||
)
|
||||
response = self.client.post(WARMUP_URL)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["started"] is False
|
||||
assert "error" in response.json()
|
||||
|
||||
def test_warmup_503_start_failure_logged_as_warning(self, caplog):
|
||||
"""A transient 503/start failure must NOT log at ERROR.
|
||||
|
||||
The encoding flow falls back to alternate-zone workers, so this is a
|
||||
self-healing event. Logging it at ERROR trips the production error
|
||||
monitor (severity>=ERROR) and pages us for a non-incident.
|
||||
"""
|
||||
self.mock_manager.ensure_primary_running.side_effect = (
|
||||
EncodingWorkerStartError(
|
||||
"VM encoding-worker-b start failed in us-central1-c: "
|
||||
"503 — SERVICE UNAVAILABLE",
|
||||
vm_name="encoding-worker-b",
|
||||
zone="us-central1-c",
|
||||
)
|
||||
)
|
||||
with caplog.at_level(logging.WARNING):
|
||||
response = self.client.post(WARMUP_URL)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["started"] is False
|
||||
warmup_records = [
|
||||
r for r in caplog.records if "warmup failed" in r.getMessage()
|
||||
]
|
||||
assert warmup_records, "expected a warmup-failure log record"
|
||||
assert all(r.levelno == logging.WARNING for r in warmup_records)
|
||||
# And nothing from this endpoint should be at ERROR.
|
||||
assert not [
|
||||
r
|
||||
for r in caplog.records
|
||||
if r.levelno >= logging.ERROR
|
||||
and r.name == "backend.api.routes.encoding_worker"
|
||||
]
|
||||
|
||||
def test_warmup_capacity_error_logged_as_warning(self, caplog):
|
||||
"""Capacity exhaustion is also self-healing → WARNING, not ERROR."""
|
||||
self.mock_manager.ensure_primary_running.side_effect = (
|
||||
EncodingWorkerCapacityError(
|
||||
"VM encoding-worker-b could not be started in us-central1-c: "
|
||||
"ZONE_RESOURCE_POOL_EXHAUSTED",
|
||||
vm_name="encoding-worker-b",
|
||||
zone="us-central1-c",
|
||||
code="ZONE_RESOURCE_POOL_EXHAUSTED",
|
||||
)
|
||||
)
|
||||
with caplog.at_level(logging.WARNING):
|
||||
response = self.client.post(WARMUP_URL)
|
||||
assert response.status_code == 200
|
||||
assert not [
|
||||
r
|
||||
for r in caplog.records
|
||||
if r.levelno >= logging.ERROR
|
||||
and r.name == "backend.api.routes.encoding_worker"
|
||||
]
|
||||
|
||||
def test_warmup_unexpected_error_still_logged_as_error(self, caplog):
|
||||
"""Genuinely unexpected failures must still surface at ERROR."""
|
||||
self.mock_manager.ensure_primary_running.side_effect = RuntimeError(
|
||||
"misconfigured service account"
|
||||
)
|
||||
with caplog.at_level(logging.WARNING):
|
||||
response = self.client.post(WARMUP_URL)
|
||||
assert response.status_code == 200
|
||||
error_records = [
|
||||
r
|
||||
for r in caplog.records
|
||||
if r.levelno >= logging.ERROR
|
||||
and r.name == "backend.api.routes.encoding_worker"
|
||||
]
|
||||
assert error_records, "unexpected errors must remain at ERROR severity"
|
||||
|
||||
|
||||
class TestHeartbeatEndpoint:
|
||||
def setup_method(self):
|
||||
self.mock_manager = MagicMock()
|
||||
self.app = FastAPI()
|
||||
self.app.include_router(router, prefix="/api")
|
||||
self.app.dependency_overrides[require_review_auth] = fake_review_auth
|
||||
self.app.dependency_overrides[get_worker_manager] = lambda: self.mock_manager
|
||||
self.client = TestClient(self.app)
|
||||
|
||||
def test_heartbeat_updates_activity(self):
|
||||
response = self.client.post(HEARTBEAT_URL)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "ok"
|
||||
self.mock_manager.update_activity.assert_called_once()
|
||||
|
||||
def test_heartbeat_handles_error(self):
|
||||
self.mock_manager.update_activity.side_effect = RuntimeError(
|
||||
"Firestore error"
|
||||
)
|
||||
response = self.client.post(HEARTBEAT_URL)
|
||||
assert response.status_code == 200
|
||||
assert response.json()["status"] == "error"
|
||||
|
||||
|
||||
class TestReviewAuthGating:
|
||||
"""Regression guard: these endpoints must be review-auth gated, not admin.
|
||||
|
||||
Before this fix they used ``require_admin``, so every non-admin customer on
|
||||
the lyrics-review page got a 403 and the JIT pre-warm never happened.
|
||||
"""
|
||||
|
||||
def test_routes_depend_on_review_auth_not_admin(self):
|
||||
"""The route dependencies reference require_review_auth, never require_admin."""
|
||||
deps = set()
|
||||
for route in router.routes:
|
||||
dependant = getattr(route, "dependant", None)
|
||||
if dependant is None:
|
||||
continue
|
||||
# Flatten the whole dependency tree for the route.
|
||||
stack = list(dependant.dependencies)
|
||||
while stack:
|
||||
d = stack.pop()
|
||||
deps.add(d.call)
|
||||
stack.extend(d.dependencies)
|
||||
assert require_review_auth in deps, (
|
||||
"warmup/heartbeat must be gated on require_review_auth"
|
||||
)
|
||||
assert require_admin not in deps, (
|
||||
"warmup/heartbeat must NOT require admin (regresses pre-warm for "
|
||||
"all non-admin customers)"
|
||||
class TestWarmupHandler:
|
||||
def _run(self, manager):
|
||||
return asyncio.run(
|
||||
encoding_worker.warmup_encoding_worker("job-1", ("admin", "full"), manager)
|
||||
)
|
||||
|
||||
def test_unauthenticated_request_is_rejected(self):
|
||||
"""With real auth (no override, no token), warmup is rejected — not 200/500."""
|
||||
app = FastAPI()
|
||||
app.include_router(router, prefix="/api")
|
||||
app.dependency_overrides[get_worker_manager] = lambda: MagicMock()
|
||||
client = TestClient(app, raise_server_exceptions=False)
|
||||
response = client.post(WARMUP_URL)
|
||||
# require_review_auth with no credentials raises 401.
|
||||
assert response.status_code == 401
|
||||
def test_success_passthrough(self):
|
||||
manager = MagicMock()
|
||||
manager.ensure_primary_running.return_value = {"started": True, "vm_name": "encoding-worker-a"}
|
||||
assert self._run(manager)["started"] is True
|
||||
|
||||
def test_job_id_is_required_in_path(self):
|
||||
"""The old job-less path no longer exists (404), forcing job scoping."""
|
||||
app = FastAPI()
|
||||
app.include_router(router, prefix="/api")
|
||||
app.dependency_overrides[require_review_auth] = fake_review_auth
|
||||
app.dependency_overrides[get_worker_manager] = lambda: MagicMock()
|
||||
client = TestClient(app)
|
||||
response = client.post("/api/internal/encoding-worker/warmup")
|
||||
assert response.status_code == 404
|
||||
def test_start_error_is_soft(self):
|
||||
manager = MagicMock()
|
||||
manager.ensure_primary_running.side_effect = EncodingWorkerStartError("zone exhausted")
|
||||
result = self._run(manager)
|
||||
assert result["started"] is False
|
||||
assert "zone exhausted" in result["error"]
|
||||
|
||||
def test_slow_manager_does_not_block_event_loop(self):
|
||||
"""The whole point of the fix: a slow warmup must not freeze the loop."""
|
||||
manager = MagicMock()
|
||||
|
||||
def slow_warmup():
|
||||
time.sleep(0.5)
|
||||
return {"started": False}
|
||||
|
||||
manager.ensure_primary_running.side_effect = slow_warmup
|
||||
|
||||
async def scenario():
|
||||
ticks = 0
|
||||
|
||||
async def ticker():
|
||||
nonlocal ticks
|
||||
while True:
|
||||
ticks += 1
|
||||
await asyncio.sleep(0.05)
|
||||
|
||||
t = asyncio.create_task(ticker())
|
||||
await encoding_worker.warmup_encoding_worker("job-1", ("admin", "full"), manager)
|
||||
t.cancel()
|
||||
return ticks
|
||||
|
||||
# With the sync-on-loop bug, the ticker would run ~0 times during the
|
||||
# 0.5s warmup; off-loop it keeps ticking throughout.
|
||||
assert asyncio.run(scenario()) >= 5
|
||||
|
||||
|
||||
class TestHeartbeatHandler:
|
||||
def test_ok(self):
|
||||
manager = MagicMock()
|
||||
result = asyncio.run(
|
||||
encoding_worker.heartbeat_encoding_worker("job-1", ("admin", "full"), manager)
|
||||
)
|
||||
assert result == {"status": "ok"}
|
||||
manager.update_activity.assert_called_once()
|
||||
@@ -829,6 +829,150 @@ class TestFlacfetchRetryLogic:
|
||||
assert mock_client.post.call_count == 3
|
||||
|
||||
|
||||
class TestFlacfetchSearchRetryLogic:
|
||||
"""Test retry logic for flacfetch search (lighter profile than downloads)."""
|
||||
|
||||
@staticmethod
|
||||
def _mock_settings():
|
||||
mock_settings = Mock()
|
||||
# Heavy download retry settings - search must NOT use these
|
||||
mock_settings.flacfetch_retry_max_attempts = 9
|
||||
mock_settings.flacfetch_retry_min_wait = 10.0
|
||||
mock_settings.flacfetch_retry_max_wait = 60.0
|
||||
# Light search retry settings
|
||||
mock_settings.flacfetch_search_retry_max_attempts = 2
|
||||
mock_settings.flacfetch_search_retry_wait = 0.01 # Fast for testing
|
||||
mock_settings.flacfetch_search_total_timeout = 5.0
|
||||
return mock_settings
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_retries_on_read_timeout(self):
|
||||
"""Test search retries on ReadTimeout and succeeds on second attempt."""
|
||||
with patch("backend.services.flacfetch_client.get_settings", return_value=self._mock_settings()):
|
||||
client = FlacfetchClient(
|
||||
base_url="http://test:8080",
|
||||
api_key="test-key",
|
||||
)
|
||||
|
||||
with patch("httpx.AsyncClient") as mock_client_cls:
|
||||
mock_client = AsyncMock()
|
||||
mock_client_cls.return_value.__aenter__.return_value = mock_client
|
||||
|
||||
mock_response = Mock()
|
||||
mock_response.status_code = 200
|
||||
mock_response.json.return_value = {"search_id": "s1", "results": [{"index": 0}]}
|
||||
mock_response.raise_for_status = Mock()
|
||||
|
||||
mock_client.post.side_effect = [
|
||||
httpx.ReadTimeout("timed out"),
|
||||
mock_response,
|
||||
]
|
||||
|
||||
result = await client.search("ABBA", "Waterloo")
|
||||
|
||||
assert result["search_id"] == "s1"
|
||||
assert mock_client.post.call_count == 2
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_fails_after_max_attempts(self):
|
||||
"""Test search raises FlacfetchServiceError after exhausting its 2 attempts.
|
||||
|
||||
Also verifies search uses the light search retry settings (2 attempts),
|
||||
not the heavy download settings (9 attempts).
|
||||
"""
|
||||
with patch("backend.services.flacfetch_client.get_settings", return_value=self._mock_settings()):
|
||||
client = FlacfetchClient(
|
||||
base_url="http://test:8080",
|
||||
api_key="test-key",
|
||||
)
|
||||
|
||||
with patch("httpx.AsyncClient") as mock_client_cls:
|
||||
mock_client = AsyncMock()
|
||||
mock_client_cls.return_value.__aenter__.return_value = mock_client
|
||||
|
||||
mock_client.post.side_effect = httpx.ReadTimeout("timed out")
|
||||
|
||||
with pytest.raises(FlacfetchServiceError, match="Search request failed"):
|
||||
await client.search("ABBA", "Waterloo")
|
||||
|
||||
assert mock_client.post.call_count == 2
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_no_retry_on_4xx(self):
|
||||
"""Test search does NOT retry on 4xx client errors (other than 404)."""
|
||||
with patch("backend.services.flacfetch_client.get_settings", return_value=self._mock_settings()):
|
||||
client = FlacfetchClient(
|
||||
base_url="http://test:8080",
|
||||
api_key="test-key",
|
||||
)
|
||||
|
||||
with patch("httpx.AsyncClient") as mock_client_cls:
|
||||
mock_client = AsyncMock()
|
||||
mock_client_cls.return_value.__aenter__.return_value = mock_client
|
||||
|
||||
mock_response = Mock()
|
||||
mock_response.status_code = 400
|
||||
mock_response.text = "Bad request"
|
||||
mock_response.raise_for_status.side_effect = httpx.HTTPStatusError(
|
||||
"Bad request",
|
||||
request=Mock(),
|
||||
response=mock_response,
|
||||
)
|
||||
mock_client.post.return_value = mock_response
|
||||
|
||||
with pytest.raises(FlacfetchServiceError, match="400"):
|
||||
await client.search("ABBA", "Waterloo")
|
||||
|
||||
assert mock_client.post.call_count == 1
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_total_timeout_enforced(self):
|
||||
"""Test the total search budget caps retries below the Cloudflare edge
|
||||
deadline, surfacing a clean FlacfetchServiceError instead of hanging."""
|
||||
mock_settings = self._mock_settings()
|
||||
mock_settings.flacfetch_search_total_timeout = 0.05
|
||||
|
||||
with patch("backend.services.flacfetch_client.get_settings", return_value=mock_settings):
|
||||
client = FlacfetchClient(
|
||||
base_url="http://test:8080",
|
||||
api_key="test-key",
|
||||
)
|
||||
|
||||
async def hang(*args, **kwargs):
|
||||
await asyncio.sleep(10)
|
||||
|
||||
with patch("httpx.AsyncClient") as mock_client_cls:
|
||||
mock_client = AsyncMock()
|
||||
mock_client_cls.return_value.__aenter__.return_value = mock_client
|
||||
mock_client.post.side_effect = hang
|
||||
|
||||
with pytest.raises(FlacfetchServiceError, match="timed out.*total"):
|
||||
await asyncio.wait_for(client.search("ABBA", "Waterloo"), timeout=2)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_search_404_returns_empty_without_retry(self):
|
||||
"""Test 404 (no results) still returns empty results, without retrying."""
|
||||
with patch("backend.services.flacfetch_client.get_settings", return_value=self._mock_settings()):
|
||||
client = FlacfetchClient(
|
||||
base_url="http://test:8080",
|
||||
api_key="test-key",
|
||||
)
|
||||
|
||||
with patch("httpx.AsyncClient") as mock_client_cls:
|
||||
mock_client = AsyncMock()
|
||||
mock_client_cls.return_value.__aenter__.return_value = mock_client
|
||||
|
||||
mock_response = Mock()
|
||||
mock_response.status_code = 404
|
||||
mock_client.post.return_value = mock_response
|
||||
|
||||
result = await client.search("Unknown", "Nothing")
|
||||
|
||||
assert result["results"] == []
|
||||
assert result["search_id"] is None
|
||||
assert mock_client.post.call_count == 1
|
||||
|
||||
|
||||
class TestFormatHttpxError:
|
||||
"""Test _format_httpx_error helper for descriptive error messages."""
|
||||
|
||||
|
||||
@@ -341,3 +341,26 @@ class TestWorkerIdempotency:
|
||||
data = response.json()
|
||||
assert data["status"] == "not_found"
|
||||
|
||||
|
||||
|
||||
class TestAutoApprovalEval:
|
||||
"""POST /api/internal/jobs/{job_id}/auto-approval-eval — admin re-evaluation."""
|
||||
|
||||
def test_eval_calls_executor_and_returns_outcome(self, client):
|
||||
with patch(
|
||||
'backend.services.auto_approval.executor.maybe_auto_complete_review',
|
||||
new=AsyncMock(return_value={"outcome": "auto_completed"}),
|
||||
) as mock_eval:
|
||||
response = client.post(
|
||||
"/api/internal/jobs/test123/auto-approval-eval",
|
||||
headers={"Authorization": "Bearer test-admin-token"},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["job_id"] == "test123"
|
||||
assert data["outcome"] == "auto_completed"
|
||||
mock_eval.assert_awaited_once_with("test123", trigger="admin_eval")
|
||||
|
||||
def test_eval_requires_admin(self, client):
|
||||
response = client.post("/api/internal/jobs/test123/auto-approval-eval")
|
||||
assert response.status_code == 401
|
||||
@@ -1,263 +1,169 @@
|
||||
"""
|
||||
Tests for the karaokenerds service — HTML parsing, community detection, YouTube URL cleanup.
|
||||
Tests for the karaokenerds service.
|
||||
|
||||
Ported from kjbox/kj-controller/tests/unit/test_karaoke_nerds.py.
|
||||
The service reads our OWN daily-refreshed copy of the KaraokeNerds community
|
||||
catalog (a gzipped-JSON export in GCS, populated by the authorized `kn-data-sync`
|
||||
job) into an in-process index — it never scrapes or live-queries karaokenerds.com.
|
||||
"""
|
||||
|
||||
import gzip
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.services import karaokenerds_service as svc
|
||||
from backend.services.karaokenerds_service import (
|
||||
parse_results,
|
||||
_clean_youtube_url,
|
||||
_parse_single_track,
|
||||
_build_index,
|
||||
_normalize_youtube_url,
|
||||
check_community_versions,
|
||||
check_community_versions_batch,
|
||||
)
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
|
||||
# --- YouTube URL cleanup ---
|
||||
# Rows mirror the community export shape: Artist, Title, Brand (a CODE), Watch.
|
||||
ROWS = [
|
||||
{"Artist": "Fleetwood Mac", "Title": "Dreams", "Brand": "NOMAD",
|
||||
"Watch": "https://youtu.be/aaaaaaaaaaa"},
|
||||
{"Artist": "Fleetwood Mac", "Title": "Dreams", "Brand": "OBSK",
|
||||
"Watch": "https://youtu.be/bbbbbbbbbbb"},
|
||||
# Exact duplicate (brand + url) — must collapse.
|
||||
{"Artist": "Fleetwood Mac", "Title": "Dreams", "Brand": "NOMAD",
|
||||
"Watch": "https://youtu.be/aaaaaaaaaaa"},
|
||||
{"Artist": "ABBA", "Title": "Dancing Queen", "Brand": "SDK",
|
||||
"Watch": "https://youtu.be/ddddddddddd"},
|
||||
# Accents + ampersand exercise the normalized match key.
|
||||
{"Artist": "Beyoncé", "Title": "Crazy in Love", "Brand": "NOMAD",
|
||||
"Watch": "https://youtu.be/ccccccccccc"},
|
||||
{"Artist": "Hall & Oates", "Title": "Rich Girl", "Brand": "NOMAD",
|
||||
"Watch": "https://youtu.be/rrrrrrrrrrr"},
|
||||
# Unknown brand code -> name falls back to the code.
|
||||
{"Artist": "Some Band", "Title": "Obscure", "Brand": "ZZTOP7",
|
||||
"Watch": "https://youtu.be/eeeeeeeeeee"},
|
||||
# Missing artist/title rows are skipped.
|
||||
{"Artist": "", "Title": "No Artist", "Brand": "X", "Watch": "https://youtu.be/fffffffffff"},
|
||||
]
|
||||
|
||||
|
||||
def test_clean_youtube_url_strips_list_param():
|
||||
url = "https://www.youtube.com/watch?v=abc123&list=PLtest123&index=1"
|
||||
assert _clean_youtube_url(url) == "https://www.youtube.com/watch?v=abc123&index=1"
|
||||
@pytest.fixture(autouse=True)
|
||||
def _seed_index(monkeypatch):
|
||||
"""Isolate the module cache and back `_get_index` with the sample catalog."""
|
||||
svc._reset_index_for_tests()
|
||||
monkeypatch.setattr(svc, "_load_index", lambda: _build_index(ROWS))
|
||||
yield
|
||||
svc._reset_index_for_tests()
|
||||
|
||||
|
||||
def test_clean_youtube_url_no_list_param():
|
||||
url = "https://www.youtube.com/watch?v=abc123"
|
||||
assert _clean_youtube_url(url) == "https://www.youtube.com/watch?v=abc123"
|
||||
# --- YouTube URL normalization ---
|
||||
|
||||
|
||||
def test_clean_youtube_url_list_at_end():
|
||||
url = "https://www.youtube.com/watch?v=abc123&list=PLtest"
|
||||
assert _clean_youtube_url(url) == "https://www.youtube.com/watch?v=abc123"
|
||||
@pytest.mark.parametrize("raw,expected", [
|
||||
("https://youtu.be/dQw4w9WgXcQ", "https://www.youtube.com/watch?v=dQw4w9WgXcQ"),
|
||||
("https://www.youtube.com/watch?v=dQw4w9WgXcQ&list=PLx", "https://www.youtube.com/watch?v=dQw4w9WgXcQ"),
|
||||
("https://www.youtube.com/embed/dQw4w9WgXcQ", "https://www.youtube.com/watch?v=dQw4w9WgXcQ"),
|
||||
("", None),
|
||||
("not a url", "not a url"), # unparseable -> returned as-is, never fabricated
|
||||
])
|
||||
def test_normalize_youtube_url(raw, expected):
|
||||
assert _normalize_youtube_url(raw) == expected
|
||||
|
||||
|
||||
# --- Single track parsing ---
|
||||
# --- Index building ---
|
||||
|
||||
|
||||
TRACK_HTML_COMMUNITY = """
|
||||
<li class="track list-group-item d-flex p-0">
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/KV/">Karaoke Version</a>
|
||||
<div class="ml-auto">
|
||||
<a href="https://www.youtube.com/watch?v=mrZRURcb1cM&list=PLtest" target="_blank">
|
||||
<img class="web" src="/Content/Images/globe.svg">
|
||||
</a>
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/KV/">
|
||||
<span class="badge badge-primary badge-pill">
|
||||
KV<img class="check" src="/Content/Images/check.svg" title="Global Karaoke Community">
|
||||
</span>
|
||||
</a>
|
||||
</div>
|
||||
</li>
|
||||
"""
|
||||
|
||||
TRACK_HTML_NO_COMMUNITY = """
|
||||
<li class="track list-group-item d-flex p-0">
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/SF/">Sunfly</a>
|
||||
<div class="ml-auto">
|
||||
<a href="https://www.youtube.com/watch?v=xyz789" target="_blank">
|
||||
<img class="web" src="/Content/Images/globe.svg">
|
||||
</a>
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/SF/">
|
||||
<span class="badge badge-primary badge-pill">SF</span>
|
||||
</a>
|
||||
</div>
|
||||
</li>
|
||||
"""
|
||||
|
||||
TRACK_HTML_NO_YOUTUBE = """
|
||||
<li class="track list-group-item d-flex p-0">
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/AB/">Some Brand</a>
|
||||
<div class="ml-auto">
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/AB/">
|
||||
<span class="badge badge-primary badge-pill">AB</span>
|
||||
</a>
|
||||
</div>
|
||||
</li>
|
||||
"""
|
||||
def test_build_index_groups_and_dedupes():
|
||||
index = _build_index(ROWS)
|
||||
dreams = index[svc._match_key("Fleetwood Mac", "Dreams")]
|
||||
# Two distinct brands; the exact-duplicate row is collapsed.
|
||||
assert len(dreams["community_tracks"]) == 2
|
||||
codes = {t["brand_code"] for t in dreams["community_tracks"]}
|
||||
names = {t["brand_name"] for t in dreams["community_tracks"]}
|
||||
assert codes == {"NOMAD", "OBSK"}
|
||||
assert names == {"Nomad Karaoke", "ObsKure Karaoke"}
|
||||
assert all(t["is_community"] is True for t in dreams["community_tracks"])
|
||||
# youtu.be URLs are canonicalized to watch?v=.
|
||||
assert all(t["youtube_url"].startswith("https://www.youtube.com/watch?v=")
|
||||
for t in dreams["community_tracks"])
|
||||
|
||||
|
||||
def test_parse_single_track_community():
|
||||
soup = BeautifulSoup(TRACK_HTML_COMMUNITY, "html.parser")
|
||||
li = soup.find("li", class_="track")
|
||||
track = _parse_single_track(li)
|
||||
assert track is not None
|
||||
assert track["brand_name"] == "Karaoke Version"
|
||||
assert track["brand_code"] == "KV"
|
||||
assert track["is_community"] is True
|
||||
assert "youtube.com" in track["youtube_url"]
|
||||
# List param should be stripped
|
||||
assert "&list=" not in track["youtube_url"]
|
||||
def test_build_index_unknown_brand_name_falls_back_to_code():
|
||||
index = _build_index(ROWS)
|
||||
song = index[svc._match_key("Some Band", "Obscure")]
|
||||
tr = song["community_tracks"][0]
|
||||
assert tr["brand_code"] == "ZZTOP7"
|
||||
assert tr["brand_name"] == "ZZTOP7"
|
||||
|
||||
|
||||
def test_parse_single_track_no_community():
|
||||
soup = BeautifulSoup(TRACK_HTML_NO_COMMUNITY, "html.parser")
|
||||
li = soup.find("li", class_="track")
|
||||
track = _parse_single_track(li)
|
||||
assert track is not None
|
||||
assert track["brand_name"] == "Sunfly"
|
||||
assert track["brand_code"] == "SF"
|
||||
assert track["is_community"] is False
|
||||
assert "youtube.com" in track["youtube_url"]
|
||||
def test_build_index_skips_rows_without_artist_or_title():
|
||||
index = _build_index(ROWS)
|
||||
assert svc._match_key("", "No Artist") not in index
|
||||
|
||||
|
||||
def test_parse_single_track_no_youtube_returns_none():
|
||||
soup = BeautifulSoup(TRACK_HTML_NO_YOUTUBE, "html.parser")
|
||||
li = soup.find("li", class_="track")
|
||||
track = _parse_single_track(li)
|
||||
assert track is None
|
||||
|
||||
|
||||
# --- Full results parsing ---
|
||||
|
||||
|
||||
FULL_RESULTS_HTML = """
|
||||
<table>
|
||||
<tbody>
|
||||
<tr class="group">
|
||||
<td><a href="/Song/Dreams/Fleetwood-Mac/">Dreams</a></td>
|
||||
<td><a href="/Artist/Fleetwood-Mac/">Fleetwood Mac</a></td>
|
||||
<td><a class="details-link">2 Brands >></a></td>
|
||||
</tr>
|
||||
<tr class="details">
|
||||
<td colspan="30">
|
||||
<ul class="list-group">
|
||||
<li class="track list-group-item d-flex p-0">
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/KV/">Karaoke Version</a>
|
||||
<div class="ml-auto">
|
||||
<a href="https://www.youtube.com/watch?v=community1" target="_blank">
|
||||
<img class="web" src="/Content/Images/globe.svg">
|
||||
</a>
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/KV/">
|
||||
<span class="badge badge-primary badge-pill">
|
||||
KV<img class="check" src="/Content/Images/check.svg" title="Global Karaoke Community">
|
||||
</span>
|
||||
</a>
|
||||
</div>
|
||||
</li>
|
||||
<li class="track list-group-item d-flex p-0">
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/SF/">Sunfly</a>
|
||||
<div class="ml-auto">
|
||||
<a href="https://www.youtube.com/watch?v=noncommunity1" target="_blank">
|
||||
<img class="web" src="/Content/Images/globe.svg">
|
||||
</a>
|
||||
<a href="/Song/Dreams/Fleetwood-Mac/SF/">
|
||||
<span class="badge badge-primary badge-pill">SF</span>
|
||||
</a>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</td>
|
||||
</tr>
|
||||
<tr class="group">
|
||||
<td><a href="/Song/The-Chain/Fleetwood-Mac/">The Chain</a></td>
|
||||
<td><a href="/Artist/Fleetwood-Mac/">Fleetwood Mac</a></td>
|
||||
<td><a class="details-link">1 Brand >></a></td>
|
||||
</tr>
|
||||
<tr class="details">
|
||||
<td colspan="30">
|
||||
<ul class="list-group">
|
||||
<li class="track list-group-item d-flex p-0">
|
||||
<a href="/Song/The-Chain/Fleetwood-Mac/KFN/">Karafun</a>
|
||||
<div class="ml-auto">
|
||||
<a href="https://www.youtube.com/watch?v=chain1" target="_blank">
|
||||
<img class="web" src="/Content/Images/globe.svg">
|
||||
</a>
|
||||
<a href="/Song/The-Chain/Fleetwood-Mac/KFN/">
|
||||
<span class="badge badge-primary badge-pill">KFN</span>
|
||||
</a>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
"""
|
||||
|
||||
|
||||
def test_parse_results_full():
|
||||
songs = parse_results(FULL_RESULTS_HTML)
|
||||
assert len(songs) == 2
|
||||
|
||||
# First song: Dreams
|
||||
assert songs[0]["title"] == "Dreams"
|
||||
assert songs[0]["artist"] == "Fleetwood Mac"
|
||||
assert len(songs[0]["tracks"]) == 2
|
||||
|
||||
# First track is community
|
||||
assert songs[0]["tracks"][0]["is_community"] is True
|
||||
assert songs[0]["tracks"][0]["brand_code"] == "KV"
|
||||
|
||||
# Second track is not community
|
||||
assert songs[0]["tracks"][1]["is_community"] is False
|
||||
assert songs[0]["tracks"][1]["brand_code"] == "SF"
|
||||
|
||||
# Second song: The Chain
|
||||
assert songs[1]["title"] == "The Chain"
|
||||
assert songs[1]["artist"] == "Fleetwood Mac"
|
||||
assert len(songs[1]["tracks"]) == 1
|
||||
assert songs[1]["tracks"][0]["is_community"] is False
|
||||
|
||||
|
||||
def test_parse_results_empty_html():
|
||||
assert parse_results("") == []
|
||||
assert parse_results("<html></html>") == []
|
||||
assert parse_results("<table></table>") == []
|
||||
|
||||
|
||||
def test_parse_results_no_table():
|
||||
assert parse_results("<div>No results</div>") == []
|
||||
|
||||
|
||||
# --- Batch availability: per-version data with YouTube URLs (Bulk Mode) ---
|
||||
# --- check_community_versions ---
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_batch_returns_versions_with_urls_deduped_by_brand(monkeypatch):
|
||||
"""Each result carries `versions: [{brand, url}]` (community only), deduped by
|
||||
brand keeping the first URL, alongside the existing brands/brand_count."""
|
||||
async def test_match_returns_community_with_best_url():
|
||||
result = await check_community_versions("Fleetwood Mac", "Dreams")
|
||||
assert result["has_community"] is True
|
||||
assert result["best_youtube_url"] == "https://www.youtube.com/watch?v=aaaaaaaaaaa"
|
||||
assert len(result["songs"]) == 1
|
||||
assert result["songs"][0]["title"] == "Dreams"
|
||||
assert result["songs"][0]["artist"] == "Fleetwood Mac"
|
||||
|
||||
async def fake_check(artist, title):
|
||||
return {
|
||||
"has_community": True,
|
||||
"songs": [
|
||||
{
|
||||
"title": title,
|
||||
"artist": artist,
|
||||
"community_tracks": [
|
||||
{"brand_name": "SNDL Karaoke", "brand_code": "SNDL",
|
||||
"youtube_url": "https://www.youtube.com/watch?v=aaa", "is_community": True},
|
||||
{"brand_name": "Nomad Karaoke", "brand_code": "NK",
|
||||
"youtube_url": "https://www.youtube.com/watch?v=bbb", "is_community": True},
|
||||
# Duplicate brand — should be collapsed, keeping the first URL.
|
||||
{"brand_name": "SNDL Karaoke", "brand_code": "SNDL",
|
||||
"youtube_url": "https://www.youtube.com/watch?v=ccc", "is_community": True},
|
||||
],
|
||||
}
|
||||
],
|
||||
"best_youtube_url": "https://www.youtube.com/watch?v=aaa",
|
||||
}
|
||||
|
||||
monkeypatch.setattr(
|
||||
"backend.services.karaokenerds_service.check_community_versions", fake_check
|
||||
)
|
||||
@pytest.mark.asyncio
|
||||
async def test_match_is_case_and_whitespace_insensitive():
|
||||
result = await check_community_versions(" fleetwood MAC ", "dreams")
|
||||
assert result["has_community"] is True
|
||||
|
||||
results = await check_community_versions_batch(
|
||||
[{"artist": "ABBA", "title": "Dancing Queen"}]
|
||||
)
|
||||
|
||||
assert len(results) == 1
|
||||
r = results[0]
|
||||
assert r["available"] is True
|
||||
assert r["versions"] == [
|
||||
{"brand": "SNDL Karaoke", "url": "https://www.youtube.com/watch?v=aaa"},
|
||||
{"brand": "Nomad Karaoke", "url": "https://www.youtube.com/watch?v=bbb"},
|
||||
@pytest.mark.asyncio
|
||||
async def test_match_folds_accents():
|
||||
result = await check_community_versions("Beyonce", "Crazy in Love")
|
||||
assert result["has_community"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_match_treats_ampersand_as_and():
|
||||
# "&" folds to "and", so "Hall and Oates" matches "Hall & Oates".
|
||||
result = await check_community_versions("Hall and Oates", "Rich Girl")
|
||||
assert result["has_community"] is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_match_returns_false():
|
||||
result = await check_community_versions("Nonexistent Artist", "No Such Song")
|
||||
assert result == {"has_community": False, "songs": [], "best_youtube_url": None}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_blank_input_returns_false_without_lookup():
|
||||
assert (await check_community_versions("", "Dreams"))["has_community"] is False
|
||||
assert (await check_community_versions("ABBA", ""))["has_community"] is False
|
||||
|
||||
|
||||
# --- Batch (Bulk Mode) ---
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_batch_returns_versions_deduped_by_brand():
|
||||
results = await check_community_versions_batch([
|
||||
{"artist": "Fleetwood Mac", "title": "Dreams"},
|
||||
{"artist": "Nope", "title": "Missing"},
|
||||
])
|
||||
assert len(results) == 2
|
||||
|
||||
dreams = results[0]
|
||||
assert dreams["available"] is True
|
||||
assert dreams["brands"] == ["Nomad Karaoke", "ObsKure Karaoke"]
|
||||
assert dreams["brand_count"] == 2
|
||||
assert dreams["versions"] == [
|
||||
{"brand": "Nomad Karaoke", "url": "https://www.youtube.com/watch?v=aaaaaaaaaaa"},
|
||||
{"brand": "ObsKure Karaoke", "url": "https://www.youtube.com/watch?v=bbbbbbbbbbb"},
|
||||
]
|
||||
# Back-compat retained.
|
||||
assert r["brands"] == ["SNDL Karaoke", "Nomad Karaoke"]
|
||||
assert r["brand_count"] == 2
|
||||
|
||||
assert results[1]["available"] is False
|
||||
assert results[1]["versions"] == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -267,110 +173,63 @@ async def test_batch_empty_song_has_empty_versions():
|
||||
assert results[0]["versions"] == []
|
||||
|
||||
|
||||
# --- check_community_versions: overlong-query fallback (KaraokeNerds term cap) ---
|
||||
@pytest.mark.asyncio
|
||||
async def test_batch_preserves_input_order():
|
||||
order = [
|
||||
{"artist": "ABBA", "title": "Dancing Queen"},
|
||||
{"artist": "Fleetwood Mac", "title": "Dreams"},
|
||||
{"artist": "Beyonce", "title": "Crazy in Love"},
|
||||
]
|
||||
results = await check_community_versions_batch(order)
|
||||
assert [r["title"] for r in results] == ["Dancing Queen", "Dreams", "Crazy in Love"]
|
||||
assert all(r["available"] for r in results)
|
||||
|
||||
|
||||
def _community_song(title, artist, brand="Nomad Karaoke", url="https://youtu.be/x"):
|
||||
return {
|
||||
"title": title,
|
||||
"artist": artist,
|
||||
"tracks": [
|
||||
{"brand_name": brand, "brand_code": "NK", "youtube_url": url, "is_community": True}
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clear_community_cache():
|
||||
"""check_community_versions caches in-process; isolate each test."""
|
||||
from backend.services import karaokenerds_service as svc
|
||||
svc._cache.clear()
|
||||
yield
|
||||
svc._cache.clear()
|
||||
# --- Loading + resilience ---
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_overlong_query_falls_back_to_title_only(monkeypatch):
|
||||
"""An overlong "artist title" query that returns nothing retries title-only
|
||||
and matches by artist (the ABBA 'I Do, I Do, I Do, I Do, I Do' bug)."""
|
||||
title = "I Do, I Do, I Do, I Do, I Do"
|
||||
calls = []
|
||||
async def test_load_index_parses_gzipped_items(monkeypatch):
|
||||
"""`_load_index` decompresses the GCS gzip and reads the `Items` array."""
|
||||
payload = gzip.compress(json.dumps({"Items": ROWS}).encode())
|
||||
|
||||
async def fake_search(query):
|
||||
calls.append(query)
|
||||
if query == f"ABBA {title}":
|
||||
return [] # combined query is too long -> KaraokeNerds returns nothing
|
||||
if query == title:
|
||||
return [_community_song("I Do I Do I Do I Do I Do", "ABBA")]
|
||||
return []
|
||||
class _Blob:
|
||||
def download_as_bytes(self):
|
||||
return payload
|
||||
|
||||
monkeypatch.setattr(
|
||||
"backend.services.karaokenerds_service._search_songs", fake_search
|
||||
)
|
||||
class _Bucket:
|
||||
def blob(self, _name):
|
||||
return _Blob()
|
||||
|
||||
result = await check_community_versions("ABBA", title)
|
||||
class _Client:
|
||||
def __init__(self, *a, **k):
|
||||
pass
|
||||
|
||||
def bucket(self, _name):
|
||||
return _Bucket()
|
||||
|
||||
monkeypatch.setattr(svc.storage, "Client", _Client)
|
||||
# Restore the real loader (the autouse fixture stubbed it) so it runs against
|
||||
# the mocked GCS client above.
|
||||
monkeypatch.setattr(svc, "_load_index", _real_load_index)
|
||||
svc._reset_index_for_tests()
|
||||
|
||||
result = await check_community_versions("Fleetwood Mac", "Dreams")
|
||||
assert result["has_community"] is True
|
||||
assert result["songs"][0]["artist"] == "ABBA"
|
||||
assert calls == [f"ABBA {title}", title] # combined first, then title-only fallback
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_fallback_filters_out_wrong_artist(monkeypatch):
|
||||
"""Title-only fallback is broader, so same-titled songs by other artists
|
||||
must be discarded — no false positive."""
|
||||
title = "I Do, I Do, I Do, I Do, I Do"
|
||||
|
||||
async def fake_search(query):
|
||||
if query == title:
|
||||
return [_community_song("I Do I Do I Do I Do I Do", "Some Other Band")]
|
||||
return []
|
||||
|
||||
monkeypatch.setattr(
|
||||
"backend.services.karaokenerds_service._search_songs", fake_search
|
||||
)
|
||||
|
||||
result = await check_community_versions("ABBA", title)
|
||||
async def test_load_failure_is_fail_open(monkeypatch):
|
||||
"""If the export can't be loaded, every song reads as no-community (fail-open)."""
|
||||
def _boom():
|
||||
raise RuntimeError("GCS unavailable")
|
||||
|
||||
svc._reset_index_for_tests()
|
||||
monkeypatch.setattr(svc, "_load_index", _boom)
|
||||
result = await check_community_versions("Fleetwood Mac", "Dreams")
|
||||
assert result["has_community"] is False
|
||||
assert result["songs"] == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_short_empty_query_does_not_fall_back(monkeypatch):
|
||||
"""A short query that legitimately returns nothing must NOT trigger a second
|
||||
request (avoids doubling load for songs with no community version)."""
|
||||
calls = []
|
||||
|
||||
async def fake_search(query):
|
||||
calls.append(query)
|
||||
return []
|
||||
|
||||
monkeypatch.setattr(
|
||||
"backend.services.karaokenerds_service._search_songs", fake_search
|
||||
)
|
||||
|
||||
result = await check_community_versions("ABBA", "Dancing Queen")
|
||||
|
||||
assert result["has_community"] is False
|
||||
assert calls == ["ABBA Dancing Queen"] # no fallback request
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_nonempty_combined_result_skips_fallback(monkeypatch):
|
||||
"""If the combined query returns results, never fall back even when long."""
|
||||
title = "I Do, I Do, I Do, I Do, I Do"
|
||||
calls = []
|
||||
|
||||
async def fake_search(query):
|
||||
calls.append(query)
|
||||
return [_community_song("I Do I Do I Do I Do I Do", "ABBA")]
|
||||
|
||||
monkeypatch.setattr(
|
||||
"backend.services.karaokenerds_service._search_songs", fake_search
|
||||
)
|
||||
|
||||
result = await check_community_versions("ABBA", title)
|
||||
|
||||
assert result["has_community"] is True
|
||||
assert calls == [f"ABBA {title}"] # only the combined query ran
|
||||
# `_real_load_index` is the unpatched module function, captured at import time so
|
||||
# the gzip-parsing test can call it after the autouse fixture stubs `_load_index`.
|
||||
_real_load_index = svc._load_index
|
||||
@@ -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
|
||||
@@ -11,7 +11,7 @@ Covers:
|
||||
import os
|
||||
import tempfile
|
||||
from datetime import datetime, timezone
|
||||
from unittest.mock import Mock, patch, MagicMock
|
||||
from unittest.mock import Mock, patch, MagicMock, AsyncMock
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -58,8 +58,10 @@ class TestPipelineDecoupling:
|
||||
|
||||
New behavior:
|
||||
- check_parallel_processing_complete() only checks lyrics_complete
|
||||
- mark_audio_complete() sets flag but does NOT trigger screens
|
||||
- mark_lyrics_complete() triggers screens on its own (no audio gate)
|
||||
- mark_audio_complete() / mark_lyrics_complete() only set their flag
|
||||
- advance_to_screens_if_ready() does the AWAITED, idempotent screens dispatch,
|
||||
gated on lyrics_complete + status==DOWNLOADING (durability fix: the old
|
||||
fire-and-forget trigger was lost on Cloud Run Job loop teardown).
|
||||
"""
|
||||
|
||||
def test_check_parallel_only_requires_lyrics(self, job_manager, mock_firestore_service):
|
||||
@@ -83,76 +85,86 @@ class TestPipelineDecoupling:
|
||||
|
||||
assert job_manager.check_parallel_processing_complete("test-001") is False
|
||||
|
||||
def test_mark_audio_complete_does_not_trigger_screens(self, job_manager, mock_firestore_service):
|
||||
"""Critical: audio completion must NOT trigger screens worker."""
|
||||
def test_mark_audio_complete_only_sets_flag(self, job_manager, mock_firestore_service):
|
||||
"""mark_audio_complete only persists the flag; it never triggers screens
|
||||
itself (the audio worker calls advance_to_screens_if_ready as a fallback)."""
|
||||
job = _make_job(state_data={"lyrics_complete": True})
|
||||
mock_firestore_service.get_job.return_value = job
|
||||
mock_firestore_service.update_job.return_value = True
|
||||
|
||||
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
|
||||
job_manager.mark_audio_complete("test-001")
|
||||
mock_trigger.assert_not_called()
|
||||
job_manager.mark_audio_complete("test-001")
|
||||
# Flag persisted via a dot-path state_data write.
|
||||
assert mock_firestore_service.update_job.called
|
||||
|
||||
def test_mark_lyrics_complete_triggers_screens_without_audio(self, job_manager, mock_firestore_service):
|
||||
"""Critical: lyrics completion triggers screens even if audio isn't done."""
|
||||
# After update_state_data sets lyrics_complete, get_job returns updated state
|
||||
job_after_update = _make_job(state_data={"audio_complete": False, "lyrics_complete": True})
|
||||
mock_firestore_service.get_job.return_value = job_after_update
|
||||
def test_mark_lyrics_complete_only_sets_flag(self, job_manager, mock_firestore_service):
|
||||
"""mark_lyrics_complete only persists the flag; the durable AWAITED dispatch
|
||||
is advance_to_screens_if_ready (called by the worker)."""
|
||||
job = _make_job(state_data={"lyrics_complete": True})
|
||||
mock_firestore_service.get_job.return_value = job
|
||||
mock_firestore_service.update_job.return_value = True
|
||||
|
||||
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
|
||||
job_manager.mark_lyrics_complete("test-001")
|
||||
mock_trigger.assert_called_once_with("test-001")
|
||||
job_manager.mark_lyrics_complete("test-001")
|
||||
assert mock_firestore_service.update_job.called
|
||||
|
||||
def test_mark_lyrics_complete_triggers_screens_with_audio(self, job_manager, mock_firestore_service):
|
||||
"""Lyrics completion triggers screens when audio is already done too."""
|
||||
job_after_update = _make_job(state_data={"audio_complete": True, "lyrics_complete": True})
|
||||
mock_firestore_service.get_job.return_value = job_after_update
|
||||
mock_firestore_service.update_job.return_value = True
|
||||
@pytest.mark.asyncio
|
||||
async def test_advance_triggers_screens_when_lyrics_done(self, job_manager, mock_firestore_service):
|
||||
"""lyrics_complete + status DOWNLOADING → screens dispatched (awaited)."""
|
||||
job = _make_job(state_data={"lyrics_complete": True, "audio_complete": False})
|
||||
mock_firestore_service.get_job.return_value = job
|
||||
mock_ws = MagicMock()
|
||||
mock_ws.trigger_screens_worker = AsyncMock(return_value=True)
|
||||
|
||||
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
|
||||
job_manager.mark_lyrics_complete("test-001")
|
||||
mock_trigger.assert_called_once_with("test-001")
|
||||
with patch("backend.services.worker_service.get_worker_service", return_value=mock_ws):
|
||||
result = await job_manager.advance_to_screens_if_ready("test-001")
|
||||
|
||||
def test_ordering_audio_first_then_lyrics(self, job_manager, mock_firestore_service):
|
||||
"""Typical flow: audio finishes first, then lyrics triggers screens."""
|
||||
mock_firestore_service.update_job.return_value = True
|
||||
assert result is True
|
||||
mock_ws.trigger_screens_worker.assert_awaited_once_with("test-001")
|
||||
|
||||
# Audio completes first — get_job returns state without lyrics_complete
|
||||
job_audio_only = _make_job(state_data={"audio_complete": True})
|
||||
mock_firestore_service.get_job.return_value = job_audio_only
|
||||
@pytest.mark.asyncio
|
||||
async def test_advance_noop_when_lyrics_not_done(self, job_manager, mock_firestore_service):
|
||||
"""No screens trigger until lyrics complete, even if audio is done."""
|
||||
job = _make_job(state_data={"lyrics_complete": False, "audio_complete": True})
|
||||
mock_firestore_service.get_job.return_value = job
|
||||
mock_ws = MagicMock()
|
||||
mock_ws.trigger_screens_worker = AsyncMock(return_value=True)
|
||||
|
||||
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
|
||||
job_manager.mark_audio_complete("test-001")
|
||||
mock_trigger.assert_not_called()
|
||||
with patch("backend.services.worker_service.get_worker_service", return_value=mock_ws):
|
||||
result = await job_manager.advance_to_screens_if_ready("test-001")
|
||||
|
||||
# Now lyrics completes — get_job returns state with both flags
|
||||
job_both = _make_job(state_data={"audio_complete": True, "lyrics_complete": True})
|
||||
mock_firestore_service.get_job.return_value = job_both
|
||||
assert result is False
|
||||
mock_ws.trigger_screens_worker.assert_not_called()
|
||||
|
||||
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
|
||||
job_manager.mark_lyrics_complete("test-001")
|
||||
mock_trigger.assert_called_once()
|
||||
@pytest.mark.asyncio
|
||||
async def test_advance_is_idempotent_when_already_advanced(self, job_manager, mock_firestore_service):
|
||||
"""Idempotency: once the job has advanced past DOWNLOADING, a second call
|
||||
(e.g. the audio-worker fallback) must NOT re-dispatch screens."""
|
||||
job = _make_job(state_data={"lyrics_complete": True}, status=JobStatus.AWAITING_REVIEW)
|
||||
mock_firestore_service.get_job.return_value = job
|
||||
mock_ws = MagicMock()
|
||||
mock_ws.trigger_screens_worker = AsyncMock(return_value=True)
|
||||
|
||||
def test_ordering_lyrics_first_then_audio(self, job_manager, mock_firestore_service):
|
||||
"""Less common: lyrics finishes first, triggers screens immediately."""
|
||||
mock_firestore_service.update_job.return_value = True
|
||||
with patch("backend.services.worker_service.get_worker_service", return_value=mock_ws):
|
||||
result = await job_manager.advance_to_screens_if_ready("test-001")
|
||||
|
||||
# Lyrics completes first — get_job returns state with lyrics_complete
|
||||
job_lyrics_only = _make_job(state_data={"lyrics_complete": True})
|
||||
mock_firestore_service.get_job.return_value = job_lyrics_only
|
||||
assert result is False
|
||||
mock_ws.trigger_screens_worker.assert_not_called()
|
||||
|
||||
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
|
||||
job_manager.mark_lyrics_complete("test-001")
|
||||
mock_trigger.assert_called_once()
|
||||
@pytest.mark.asyncio
|
||||
async def test_audio_fallback_recovers_lost_lyrics_trigger(self, job_manager, mock_firestore_service):
|
||||
"""The exact incident: lyrics finished (flag set) but its screens dispatch
|
||||
was lost, leaving the job at DOWNLOADING. The audio worker finishing later
|
||||
calls advance_to_screens_if_ready and rescues it."""
|
||||
job = _make_job(state_data={"lyrics_complete": True, "audio_complete": True},
|
||||
status=JobStatus.DOWNLOADING)
|
||||
mock_firestore_service.get_job.return_value = job
|
||||
mock_ws = MagicMock()
|
||||
mock_ws.trigger_screens_worker = AsyncMock(return_value=True)
|
||||
|
||||
# Audio completes later — should NOT trigger screens again
|
||||
job_both = _make_job(state_data={"lyrics_complete": True, "audio_complete": True})
|
||||
mock_firestore_service.get_job.return_value = job_both
|
||||
with patch("backend.services.worker_service.get_worker_service", return_value=mock_ws):
|
||||
result = await job_manager.advance_to_screens_if_ready("test-001")
|
||||
|
||||
with patch.object(job_manager, '_trigger_screens_worker') as mock_trigger:
|
||||
job_manager.mark_audio_complete("test-001")
|
||||
mock_trigger.assert_not_called()
|
||||
assert result is True
|
||||
mock_ws.trigger_screens_worker.assert_awaited_once_with("test-001")
|
||||
|
||||
|
||||
# ==================== P0: Preset Configuration ====================
|
||||
|
||||
@@ -55,7 +55,8 @@ def _job(job_id, status, *, minutes_stale=0, source_name=None, download_retry=No
|
||||
)
|
||||
|
||||
|
||||
def _mock_jm(*, downloading=None, pending=None, rendering=None, review_complete=None, jobs=None):
|
||||
def _mock_jm(*, downloading=None, pending=None, rendering=None, review_complete=None,
|
||||
downloading_prep=None, jobs=None):
|
||||
"""Wire a JobManager mock for the endpoint's 4 status queries.
|
||||
|
||||
downloading/rendering/review_complete use .where().stream(); pending uses
|
||||
@@ -68,8 +69,11 @@ def _mock_jm(*, downloading=None, pending=None, rendering=None, review_complete=
|
||||
where.stream.side_effect = [
|
||||
iter(downloading or []), iter(rendering or []), iter(review_complete or []),
|
||||
]
|
||||
# One .limit().stream() call: download_pending_retry
|
||||
where.limit.return_value.stream.return_value = iter(pending or [])
|
||||
# Two .limit().stream() calls in order: download_pending_retry, then downloading
|
||||
# (lost-screens-trigger sweep, bounded by SCREENS_RECOVERY_SCAN_LIMIT)
|
||||
where.limit.return_value.stream.side_effect = [
|
||||
iter(pending or []), iter(downloading_prep or []),
|
||||
]
|
||||
mock_jm.get_job.side_effect = lambda jid: (jobs or {}).get(jid)
|
||||
mock_jm.transition_to_state.return_value = True
|
||||
return mock_jm
|
||||
@@ -177,6 +181,41 @@ def test_fresh_render_not_reparked(client):
|
||||
mock_jm = _mock_jm(rendering=[_doc("r2", JobStatus.RENDERING_VIDEO)], jobs={"r2": job})
|
||||
resp, _ = _run(client, mock_jm)
|
||||
assert resp.json()["reparked_render_count"] == 0
|
||||
|
||||
|
||||
def test_stuck_downloading_with_lyrics_done_retriggers_screens(client):
|
||||
"""A job stuck at DOWNLOADING >10 min with lyrics_complete=True (a lost screens
|
||||
trigger) is re-advanced to screen generation."""
|
||||
job = _job("s1", JobStatus.DOWNLOADING, minutes_stale=15)
|
||||
job.state_data["lyrics_complete"] = True
|
||||
mock_jm = _mock_jm(downloading_prep=[_doc("s1", JobStatus.DOWNLOADING)], jobs={"s1": job})
|
||||
mock_jm.advance_to_screens_if_ready = AsyncMock(return_value=True)
|
||||
resp, _ = _run(client, mock_jm)
|
||||
data = resp.json()
|
||||
assert data["screens_retriggered_jobs"] == ["s1"]
|
||||
mock_jm.advance_to_screens_if_ready.assert_awaited_once_with("s1")
|
||||
|
||||
|
||||
def test_fresh_downloading_not_retriggered(client):
|
||||
"""A DOWNLOADING job updated 2 min ago (audio still separating) is NOT re-triggered."""
|
||||
job = _job("s2", JobStatus.DOWNLOADING, minutes_stale=2)
|
||||
job.state_data["lyrics_complete"] = True
|
||||
mock_jm = _mock_jm(downloading_prep=[_doc("s2", JobStatus.DOWNLOADING)], jobs={"s2": job})
|
||||
mock_jm.advance_to_screens_if_ready = AsyncMock(return_value=True)
|
||||
resp, _ = _run(client, mock_jm)
|
||||
assert resp.json()["screens_retriggered_count"] == 0
|
||||
mock_jm.advance_to_screens_if_ready.assert_not_awaited()
|
||||
|
||||
|
||||
def test_downloading_without_lyrics_not_retriggered(client):
|
||||
"""A DOWNLOADING job stale >10 min but WITHOUT lyrics_complete is still
|
||||
legitimately processing (download/separate/transcribe) — not re-triggered."""
|
||||
job = _job("s3", JobStatus.DOWNLOADING, minutes_stale=15) # no lyrics_complete
|
||||
mock_jm = _mock_jm(downloading_prep=[_doc("s3", JobStatus.DOWNLOADING)], jobs={"s3": job})
|
||||
mock_jm.advance_to_screens_if_ready = AsyncMock(return_value=True)
|
||||
resp, _ = _run(client, mock_jm)
|
||||
assert resp.json()["screens_retriggered_count"] == 0
|
||||
mock_jm.advance_to_screens_if_ready.assert_not_awaited()
|
||||
mock_jm.transition_to_state.assert_not_called()
|
||||
|
||||
|
||||
|
||||
@@ -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 "")]
|
||||
|
||||
@@ -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,6 +373,29 @@ class TestInstrumentalUrlsRefresh:
|
||||
options = response.json()["instrumental_options"]
|
||||
assert [o["id"] for o in options] == ["clean"]
|
||||
|
||||
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 = {
|
||||
"stems": {
|
||||
"instrumental_clean": "jobs/job1/stems/instrumental_clean.flac",
|
||||
"instrumental_with_backing": "jobs/job1/stems/instrumental_with_backing.flac",
|
||||
}
|
||||
}
|
||||
|
||||
with patch("backend.api.routes.review.JobManager") as mock_jm, \
|
||||
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") 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
|
||||
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, \
|
||||
patch("backend.api.routes.review.StorageService"):
|
||||
@@ -391,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.
|
||||
|
||||
@@ -1318,7 +1447,11 @@ class TestGetVocalsAudio:
|
||||
|
||||
def _call(self, stems, audio_complete=True):
|
||||
import asyncio
|
||||
from backend.api.routes.review import _stream_audio
|
||||
from backend.api.routes.review import _stream_audio, _review_audio_cache
|
||||
|
||||
# Vocals bytes are LRU-cached module-wide; clear so each test asserts a
|
||||
# fresh fetch rather than a hit on a previous test's identical path.
|
||||
_review_audio_cache.clear()
|
||||
|
||||
job = MagicMock()
|
||||
job.input_media_gcs_path = "jobs/j/input.flac"
|
||||
@@ -1692,7 +1825,7 @@ class TestEncodePreviewInBackground:
|
||||
encoding_service = MagicMock()
|
||||
encoding_service.encode_preview_video = AsyncMock(side_effect=RuntimeError("stockout"))
|
||||
storage = MagicMock()
|
||||
local_render = MagicMock(return_value="h1")
|
||||
local_render = AsyncMock(return_value="h1")
|
||||
self._run(mock_job, encoding_service, storage, local_render)
|
||||
local_render.assert_called_once()
|
||||
storage.upload_json.assert_not_called()
|
||||
@@ -1703,9 +1836,378 @@ class TestEncodePreviewInBackground:
|
||||
encoding_service = MagicMock()
|
||||
encoding_service.encode_preview_video = AsyncMock(side_effect=RuntimeError("stockout"))
|
||||
storage = MagicMock()
|
||||
local_render = MagicMock(side_effect=RuntimeError("ffmpeg died"))
|
||||
local_render = AsyncMock(side_effect=RuntimeError("ffmpeg died"))
|
||||
self._run(mock_job, encoding_service, storage, local_render)
|
||||
storage.upload_json.assert_called_once_with(
|
||||
"jobs/job-bg/previews/h1.error.json",
|
||||
{"error": "ffmpeg died"},
|
||||
)
|
||||
|
||||
|
||||
class TestVocalsCacheRangeAndHeaders:
|
||||
"""Concurrent-load fixes on the vocals byte proxy: LRU cache, Range, Cache-Control."""
|
||||
|
||||
def _make_request(self, headers=None):
|
||||
req = MagicMock()
|
||||
req.headers = headers or {}
|
||||
return req
|
||||
|
||||
def _run(self, request=None, path="jobs/j/stems/vocals_clean.flac", clear_cache=True):
|
||||
import asyncio
|
||||
from backend.api.routes.review import _stream_audio, _review_audio_cache
|
||||
|
||||
if clear_cache:
|
||||
_review_audio_cache.clear()
|
||||
|
||||
job = MagicMock()
|
||||
job.input_media_gcs_path = "jobs/j/input.flac"
|
||||
job.file_urls = {"stems": {"vocals_clean": path}}
|
||||
job.state_data = {"audio_complete": True}
|
||||
|
||||
job_manager = MagicMock()
|
||||
job_manager.get_job.return_value = job
|
||||
|
||||
transcoding = MagicMock()
|
||||
transcoding.get_review_audio_bytes_async = AsyncMock(
|
||||
return_value=(b"0123456789", "audio/ogg")
|
||||
)
|
||||
|
||||
with patch("backend.api.routes.review.JobManager", return_value=job_manager), patch(
|
||||
"backend.services.audio_transcoding_service.AudioTranscodingService",
|
||||
return_value=transcoding,
|
||||
):
|
||||
resp = asyncio.run(_stream_audio("j", request, stem="vocals"))
|
||||
return resp, transcoding
|
||||
|
||||
def test_second_fetch_served_from_lru_cache(self):
|
||||
"""Ten tabs of one job must not each re-download the stem from GCS."""
|
||||
_, first = self._run()
|
||||
first.get_review_audio_bytes_async.assert_awaited_once()
|
||||
|
||||
resp, second = self._run(clear_cache=False)
|
||||
second.get_review_audio_bytes_async.assert_not_awaited()
|
||||
assert resp.body == b"0123456789"
|
||||
|
||||
def test_range_request_returns_206_partial(self):
|
||||
req = self._make_request({"range": "bytes=2-5"})
|
||||
resp, _ = self._run(request=req)
|
||||
|
||||
assert resp.status_code == 206
|
||||
assert resp.body == b"2345"
|
||||
assert resp.headers["Content-Range"] == "bytes 2-5/10"
|
||||
assert resp.headers["Accept-Ranges"] == "bytes"
|
||||
|
||||
def test_full_response_has_cache_control(self):
|
||||
req = self._make_request({})
|
||||
resp, _ = self._run(request=req)
|
||||
|
||||
assert resp.status_code == 200
|
||||
assert "max-age" in resp.headers.get("Cache-Control", "")
|
||||
|
||||
def test_no_request_still_returns_full_body(self):
|
||||
"""Callers without a Request object (legacy path) keep working."""
|
||||
resp, _ = self._run(request=None)
|
||||
assert resp.status_code == 200
|
||||
assert resp.body == b"0123456789"
|
||||
|
||||
|
||||
class TestWaveformDataEndpointCache:
|
||||
"""/waveform-data must serve via the persistent cache path, off the event loop."""
|
||||
|
||||
def _run(self, stems=None):
|
||||
import asyncio
|
||||
from backend.api.routes.review import get_waveform_data
|
||||
|
||||
job = MagicMock()
|
||||
job.input_media_gcs_path = "jobs/j/input.flac"
|
||||
if stems is None:
|
||||
stems = {"backing_vocals": "jobs/j/stems/backing_vocals.flac"}
|
||||
job.file_urls = {"stems": stems}
|
||||
|
||||
job_manager = MagicMock()
|
||||
job_manager.get_job.return_value = job
|
||||
|
||||
analysis = MagicMock()
|
||||
analysis.get_review_waveform.return_value = ([0.4, 0.8], 150.0)
|
||||
|
||||
with patch("backend.api.routes.review.JobManager", return_value=job_manager), patch(
|
||||
"backend.services.audio_analysis_service.AudioAnalysisService",
|
||||
return_value=analysis,
|
||||
), patch(
|
||||
"backend.services.audio_transcoding_service.AudioTranscodingService",
|
||||
return_value=MagicMock(),
|
||||
):
|
||||
result = asyncio.run(
|
||||
get_waveform_data("j", num_points=1000, auth_info=("admin", "full"))
|
||||
)
|
||||
return result, analysis
|
||||
|
||||
def test_serves_cached_review_waveform(self):
|
||||
result, analysis = self._run()
|
||||
|
||||
analysis.get_review_waveform.assert_called_once()
|
||||
args = analysis.get_review_waveform.call_args[0]
|
||||
assert args[0] == "jobs/j/stems/backing_vocals.flac"
|
||||
assert args[1] == "j"
|
||||
assert args[2] == 1000
|
||||
assert result["amplitudes"] == [0.4, 0.8]
|
||||
assert result["duration_seconds"] == 150.0
|
||||
assert result["duration"] == 150.0
|
||||
|
||||
def test_falls_back_to_input_audio_without_backing_stem(self):
|
||||
_, analysis = self._run(stems={})
|
||||
assert analysis.get_review_waveform.call_args[0][0] == "jobs/j/input.flac"
|
||||
|
||||
|
||||
class TestReviewAudioSingleFlightAndByteCap:
|
||||
"""CodeRabbit follow-ups on #1024: coalesce concurrent misses; bound cache bytes."""
|
||||
|
||||
def test_concurrent_misses_share_one_fetch(self):
|
||||
import asyncio
|
||||
from backend.api.routes import review as review_module
|
||||
|
||||
review_module._review_audio_cache.clear()
|
||||
|
||||
calls = {"n": 0}
|
||||
|
||||
class SlowTranscoding:
|
||||
async def get_review_audio_bytes_async(self, path):
|
||||
calls["n"] += 1
|
||||
await asyncio.sleep(0.05)
|
||||
return (b"shared-bytes", "audio/ogg")
|
||||
|
||||
async def scenario():
|
||||
t = SlowTranscoding()
|
||||
results = await asyncio.gather(
|
||||
*[review_module._get_review_audio("jobs/j/stems/v.flac", t) for _ in range(5)]
|
||||
)
|
||||
return results
|
||||
|
||||
results = asyncio.run(scenario())
|
||||
assert calls["n"] == 1 # five concurrent callers, one fetch
|
||||
assert all(r == (b"shared-bytes", "audio/ogg") for r in results)
|
||||
|
||||
def test_failure_is_shared_and_next_call_retries(self):
|
||||
import asyncio
|
||||
from backend.api.routes import review as review_module
|
||||
|
||||
review_module._review_audio_cache.clear()
|
||||
|
||||
calls = {"n": 0}
|
||||
|
||||
class FlakyTranscoding:
|
||||
async def get_review_audio_bytes_async(self, path):
|
||||
calls["n"] += 1
|
||||
await asyncio.sleep(0.02)
|
||||
if calls["n"] == 1:
|
||||
raise RuntimeError("GCS blip")
|
||||
return (b"ok", "audio/ogg")
|
||||
|
||||
async def scenario():
|
||||
t = FlakyTranscoding()
|
||||
first = await asyncio.gather(
|
||||
*[review_module._get_review_audio("jobs/j/stems/v.flac", t) for _ in range(3)],
|
||||
return_exceptions=True,
|
||||
)
|
||||
assert all(isinstance(r, RuntimeError) for r in first)
|
||||
# In-flight entry must be gone — a fresh call retries and succeeds.
|
||||
return await review_module._get_review_audio("jobs/j/stems/v.flac", t)
|
||||
|
||||
result = asyncio.run(scenario())
|
||||
assert result == (b"ok", "audio/ogg")
|
||||
assert calls["n"] == 2
|
||||
|
||||
def test_oversized_entry_not_cached(self, monkeypatch):
|
||||
from backend.api.routes import review as review_module
|
||||
|
||||
review_module._review_audio_cache.clear()
|
||||
monkeypatch.setattr(review_module, "_REVIEW_AUDIO_CACHE_MAX_BYTES", 100)
|
||||
|
||||
# > max_bytes // 4 → skipped (one giant fallback FLAC must not evict all)
|
||||
review_module._review_audio_cache_put("big", (b"x" * 50, "audio/flac"))
|
||||
assert "big" not in review_module._review_audio_cache
|
||||
|
||||
def test_byte_cap_evicts_lru(self, monkeypatch):
|
||||
from backend.api.routes import review as review_module
|
||||
|
||||
review_module._review_audio_cache.clear()
|
||||
review_module._review_audio_cache_bytes = 0
|
||||
monkeypatch.setattr(review_module, "_REVIEW_AUDIO_CACHE_MAX_BYTES", 100)
|
||||
|
||||
for key in ("a", "b", "c", "d", "e"):
|
||||
review_module._review_audio_cache_put(key, (b"x" * 25, "audio/ogg"))
|
||||
|
||||
# 5 × 25B = 125B > 100B cap → oldest evicted, total back under the cap.
|
||||
assert "a" not in review_module._review_audio_cache
|
||||
assert review_module._review_audio_cache_bytes <= 100
|
||||
assert set(review_module._review_audio_cache) == {"b", "c", "d", "e"}
|
||||
|
||||
|
||||
class TestLocalPreviewRenderBound:
|
||||
"""The local preview ffmpeg fallback must be bounded so a GCE outage plus a
|
||||
few concurrent Preview clicks can't saturate the API instance's CPU.
|
||||
Admission is an async semaphore on the event loop (waiters are cheap
|
||||
coroutines, not parked executor threads)."""
|
||||
|
||||
def test_serializes_and_times_out_admission(self, monkeypatch):
|
||||
import asyncio
|
||||
import threading
|
||||
from backend.api.routes import review as review_module
|
||||
|
||||
monkeypatch.setattr(review_module, "_LOCAL_PREVIEW_QUEUE_TIMEOUT_S", 0.2)
|
||||
monkeypatch.setattr(review_module, "_local_preview_slots", asyncio.Semaphore(1))
|
||||
|
||||
started = threading.Event()
|
||||
release = threading.Event()
|
||||
|
||||
def slow_render(job, updated_data, is_duet):
|
||||
started.set()
|
||||
release.wait(timeout=5)
|
||||
return "hash"
|
||||
|
||||
monkeypatch.setattr(review_module, "_render_preview_locally_unbounded", slow_render)
|
||||
|
||||
async def scenario():
|
||||
first = asyncio.create_task(
|
||||
review_module._render_preview_locally(MagicMock(), {}, False)
|
||||
)
|
||||
await asyncio.to_thread(started.wait, 5)
|
||||
|
||||
# Slot held by the first render — the second caller's admission wait
|
||||
# times out fast instead of piling more ffmpeg onto the instance.
|
||||
with pytest.raises(RuntimeError, match="busy"):
|
||||
await review_module._render_preview_locally(MagicMock(), {}, False)
|
||||
|
||||
release.set()
|
||||
assert await first == "hash"
|
||||
|
||||
# Slot released — a fresh render is admitted immediately.
|
||||
monkeypatch.setattr(
|
||||
review_module, "_render_preview_locally_unbounded",
|
||||
lambda job, updated_data, is_duet: "hash2",
|
||||
)
|
||||
assert await review_module._render_preview_locally(MagicMock(), {}, False) == "hash2"
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
def test_cancelled_caller_does_not_free_slot_while_render_runs(self, monkeypatch):
|
||||
"""Cancelling the awaiting request must NOT release the slot while the
|
||||
ffmpeg worker thread is still running — otherwise a second render can
|
||||
start and defeat the concurrency bound."""
|
||||
import asyncio
|
||||
import threading
|
||||
from backend.api.routes import review as review_module
|
||||
|
||||
monkeypatch.setattr(review_module, "_LOCAL_PREVIEW_QUEUE_TIMEOUT_S", 0.2)
|
||||
monkeypatch.setattr(review_module, "_local_preview_slots", asyncio.Semaphore(1))
|
||||
|
||||
started = threading.Event()
|
||||
release = threading.Event()
|
||||
|
||||
def slow_render(job, updated_data, is_duet):
|
||||
started.set()
|
||||
release.wait(timeout=5)
|
||||
return "hash"
|
||||
|
||||
monkeypatch.setattr(review_module, "_render_preview_locally_unbounded", slow_render)
|
||||
|
||||
async def scenario():
|
||||
first = asyncio.create_task(
|
||||
review_module._render_preview_locally(MagicMock(), {}, False)
|
||||
)
|
||||
await asyncio.to_thread(started.wait, 5)
|
||||
|
||||
first.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await first
|
||||
|
||||
# Worker thread is still rendering — the slot must still be held.
|
||||
with pytest.raises(RuntimeError, match="busy"):
|
||||
await review_module._render_preview_locally(MagicMock(), {}, False)
|
||||
|
||||
# Worker finishes → done-callback releases the slot.
|
||||
release.set()
|
||||
for _ in range(50):
|
||||
if not review_module._local_preview_slots.locked():
|
||||
break
|
||||
await asyncio.sleep(0.05)
|
||||
|
||||
monkeypatch.setattr(
|
||||
review_module, "_render_preview_locally_unbounded",
|
||||
lambda job, updated_data, is_duet: "hash2",
|
||||
)
|
||||
assert await review_module._render_preview_locally(MagicMock(), {}, False) == "hash2"
|
||||
|
||||
asyncio.run(scenario())
|
||||
|
||||
|
||||
class TestVocalsPeaksEndpoint:
|
||||
"""/vocals-peaks serves the precomputed envelope (sub-second strips)."""
|
||||
|
||||
def _run(self, stems=None, audio_complete=True, pps=400):
|
||||
import asyncio
|
||||
from backend.api.routes.review import get_vocals_peaks
|
||||
|
||||
job = MagicMock()
|
||||
job.input_media_gcs_path = "jobs/j/input.flac"
|
||||
if stems is None:
|
||||
stems = {"vocals_clean": "jobs/j/stems/vocals_clean.flac"}
|
||||
job.file_urls = {"stems": stems}
|
||||
job.state_data = {"audio_complete": audio_complete}
|
||||
|
||||
job_manager = MagicMock()
|
||||
job_manager.get_job.return_value = job
|
||||
|
||||
analysis = MagicMock()
|
||||
analysis.get_vocals_peaks.return_value = {
|
||||
"peaks_b64": "AAECAw==",
|
||||
"encoding": "u8",
|
||||
"peaks_per_second": 400,
|
||||
"duration_seconds": 12.5,
|
||||
"source_gcs_path": "jobs/j/stems/vocals_clean.flac",
|
||||
}
|
||||
|
||||
with patch("backend.api.routes.review.JobManager", return_value=job_manager), patch(
|
||||
"backend.services.audio_analysis_service.AudioAnalysisService",
|
||||
return_value=analysis,
|
||||
), patch(
|
||||
"backend.services.audio_transcoding_service.AudioTranscodingService",
|
||||
return_value=MagicMock(),
|
||||
):
|
||||
resp = asyncio.run(
|
||||
get_vocals_peaks("j", peaks_per_second=pps, auth_info=("admin", "full"))
|
||||
)
|
||||
return resp, analysis
|
||||
|
||||
def test_serves_payload_with_cache_headers(self):
|
||||
import json as jsonlib
|
||||
|
||||
resp, analysis = self._run()
|
||||
|
||||
assert resp.status_code == 200
|
||||
body = jsonlib.loads(resp.body)
|
||||
assert body["peaks_b64"] == "AAECAw=="
|
||||
assert body["encoding"] == "u8"
|
||||
assert body["duration_seconds"] == 12.5
|
||||
assert "max-age" in resp.headers.get("Cache-Control", "")
|
||||
args = analysis.get_vocals_peaks.call_args[0]
|
||||
assert args[0] == "jobs/j/stems/vocals_clean.flac"
|
||||
assert args[1] == "j"
|
||||
assert args[2] == 400
|
||||
|
||||
def test_clamps_peaks_per_second(self):
|
||||
_, analysis = self._run(pps=999999)
|
||||
assert analysis.get_vocals_peaks.call_args[0][2] == 1000
|
||||
|
||||
def test_202_while_separation_running(self):
|
||||
resp, analysis = self._run(stems={}, audio_complete=False)
|
||||
assert resp.status_code == 202
|
||||
assert resp.headers.get("Retry-After") == "15"
|
||||
analysis.get_vocals_peaks.assert_not_called()
|
||||
|
||||
def test_404_when_stem_will_never_exist(self):
|
||||
from fastapi import HTTPException
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
self._run(stems={}, audio_complete=True)
|
||||
assert exc_info.value.status_code == 404
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Screens worker idempotency.
|
||||
|
||||
The screens worker can be dispatched more than once — the lyrics worker (primary
|
||||
trigger) and the audio worker (fallback trigger) may both fire it, and Cloud Tasks
|
||||
can redeliver. A duplicate dispatch that arrives once the job has advanced past the
|
||||
pre-screens stage must no-op rather than re-run the (now invalid)
|
||||
GENERATING_SCREENS transition and regenerate screens.
|
||||
"""
|
||||
from datetime import datetime, timezone
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.models.job import Job, JobStatus
|
||||
|
||||
|
||||
def _job(status):
|
||||
return Job(
|
||||
job_id="dup-1", artist="A", title="B", status=status,
|
||||
created_at=datetime.now(timezone.utc), updated_at=datetime.now(timezone.utc),
|
||||
state_data={"lyrics_complete": True, "audio_complete": True},
|
||||
)
|
||||
|
||||
|
||||
def _patched(screens_worker, mock_jm):
|
||||
return (
|
||||
patch.object(screens_worker, "JobManager", return_value=mock_jm),
|
||||
patch.object(screens_worker, "StorageService"),
|
||||
patch.object(screens_worker, "get_settings"),
|
||||
patch.object(screens_worker, "create_job_logger"),
|
||||
patch.object(screens_worker, "setup_job_logging"),
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("status", [
|
||||
JobStatus.GENERATING_SCREENS,
|
||||
JobStatus.AWAITING_REVIEW,
|
||||
JobStatus.REVIEW_COMPLETE,
|
||||
JobStatus.COMPLETE,
|
||||
])
|
||||
async def test_generate_screens_noops_when_already_advanced(status):
|
||||
from backend.workers import screens_worker
|
||||
mock_jm = MagicMock()
|
||||
mock_jm.get_job.return_value = _job(status)
|
||||
|
||||
p1, p2, p3, p4, p5 = _patched(screens_worker, mock_jm)
|
||||
with p1, p2, p3, p4, p5:
|
||||
result = await screens_worker.generate_screens("dup-1")
|
||||
|
||||
assert result is True
|
||||
# Duplicate dispatch must NOT perform the (invalid) GENERATING_SCREENS transition.
|
||||
mock_jm.transition_to_state.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_generate_screens_proceeds_from_downloading():
|
||||
"""A first, legitimate dispatch (status DOWNLOADING) passes the idempotency
|
||||
guard and proceeds to validate prerequisites."""
|
||||
from backend.workers import screens_worker
|
||||
mock_jm = MagicMock()
|
||||
mock_jm.get_job.return_value = _job(JobStatus.DOWNLOADING)
|
||||
|
||||
p1, p2, p3, p4, p5 = _patched(screens_worker, mock_jm)
|
||||
with p1, p2, p3, p4, p5, \
|
||||
patch.object(screens_worker, "_validate_prerequisites", return_value=False) as mock_val:
|
||||
result = await screens_worker.generate_screens("dup-1")
|
||||
|
||||
# Guard passed → prerequisites were checked (stubbed False to stop early before work).
|
||||
mock_val.assert_called_once()
|
||||
assert result is False
|
||||
@@ -550,6 +550,108 @@ class TestStorageServiceSignedUrls:
|
||||
|
||||
|
||||
|
||||
class TestStorageServiceSigningTimeout:
|
||||
"""A stalled IAM signBlob must fail fast, not hang the caller (incident 2026-09-17)."""
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_emulator_env(self, monkeypatch):
|
||||
# In CI STORAGE_EMULATOR_HOST is set, which would divert signing into the
|
||||
# emulator URL fallback and never exercise the timeout/executor path.
|
||||
monkeypatch.delenv("STORAGE_EMULATOR_HOST", raising=False)
|
||||
|
||||
@patch("backend.services.storage_service.storage.Client")
|
||||
@patch("backend.services.storage_service.settings")
|
||||
def test_signing_raises_signed_url_timeout_when_stalled(
|
||||
self, mock_settings, mock_client_class, monkeypatch
|
||||
):
|
||||
import threading
|
||||
import time
|
||||
|
||||
from backend.services.storage_service import SignedUrlTimeout, StorageService
|
||||
|
||||
mock_settings.google_cloud_project = "test-project"
|
||||
mock_settings.gcs_bucket_name = "test-bucket"
|
||||
|
||||
# Simulate a stalled signBlob: block until released, well past the timeout.
|
||||
release = threading.Event()
|
||||
|
||||
def _hang(*_args, **_kwargs):
|
||||
release.wait(timeout=5)
|
||||
return "https://storage.googleapis.com/never-returned-in-time"
|
||||
|
||||
mock_blob = Mock()
|
||||
mock_blob.generate_signed_url.side_effect = _hang
|
||||
mock_bucket = Mock()
|
||||
mock_bucket.blob.return_value = mock_blob
|
||||
mock_client_class.return_value.bucket.return_value = mock_bucket
|
||||
|
||||
# Tiny budget so the test is fast.
|
||||
monkeypatch.setattr("backend.services.storage_service.SIGNED_URL_TIMEOUT_S", 0.2)
|
||||
|
||||
try:
|
||||
with patch("google.auth.default") as mock_auth_default:
|
||||
mock_auth_default.return_value = (Mock(spec=[]), "test-project")
|
||||
started = time.monotonic()
|
||||
with pytest.raises(SignedUrlTimeout):
|
||||
StorageService().generate_signed_url("jobs/abc/review-audio/song.ogg")
|
||||
elapsed = time.monotonic() - started
|
||||
finally:
|
||||
release.set() # let the leaked signing thread finish cleanly
|
||||
|
||||
# Must bail near the budget, not wait for the underlying stall.
|
||||
assert elapsed < 2.0, f"signing did not fail fast (took {elapsed:.2f}s)"
|
||||
|
||||
@patch("backend.services.storage_service.storage.Client")
|
||||
@patch("backend.services.storage_service.settings")
|
||||
def test_signing_refuses_immediately_when_saturated(
|
||||
self, mock_settings, mock_client_class, monkeypatch
|
||||
):
|
||||
"""When admission is saturated, refuse at submit time — don't enqueue/wait."""
|
||||
import threading
|
||||
|
||||
from backend.services.storage_service import SignedUrlTimeout, StorageService
|
||||
|
||||
mock_settings.google_cloud_project = "test-project"
|
||||
mock_settings.gcs_bucket_name = "test-bucket"
|
||||
mock_blob = Mock()
|
||||
mock_bucket = Mock()
|
||||
mock_bucket.blob.return_value = mock_blob
|
||||
mock_client_class.return_value.bucket.return_value = mock_bucket
|
||||
|
||||
# Fully-acquired semaphore = no free admission slots.
|
||||
full = threading.BoundedSemaphore(1)
|
||||
assert full.acquire(blocking=False)
|
||||
monkeypatch.setattr("backend.services.storage_service._SIGNING_SLOTS", full)
|
||||
|
||||
with patch("google.auth.default") as mock_auth_default:
|
||||
mock_auth_default.return_value = (Mock(spec=[]), "test-project")
|
||||
with pytest.raises(SignedUrlTimeout):
|
||||
StorageService().generate_signed_url("jobs/abc/review-audio/song.ogg")
|
||||
|
||||
# Refused before any signing work was attempted.
|
||||
mock_blob.generate_signed_url.assert_not_called()
|
||||
|
||||
@patch("backend.services.storage_service.storage.Client")
|
||||
@patch("backend.services.storage_service.settings")
|
||||
def test_signing_returns_url_normally(self, mock_settings, mock_client_class):
|
||||
"""Sanity: the executor path still returns a normal (fast) signed URL."""
|
||||
from backend.services.storage_service import StorageService
|
||||
|
||||
mock_settings.google_cloud_project = "test-project"
|
||||
mock_settings.gcs_bucket_name = "test-bucket"
|
||||
mock_blob = Mock()
|
||||
mock_blob.generate_signed_url.return_value = "https://storage.googleapis.com/ok"
|
||||
mock_bucket = Mock()
|
||||
mock_bucket.blob.return_value = mock_blob
|
||||
mock_client_class.return_value.bucket.return_value = mock_bucket
|
||||
|
||||
with patch("google.auth.default") as mock_auth_default:
|
||||
mock_auth_default.return_value = (Mock(spec=[]), "test-project")
|
||||
url = StorageService().generate_signed_url("jobs/abc/review-audio/song.ogg")
|
||||
|
||||
assert url == "https://storage.googleapis.com/ok"
|
||||
|
||||
|
||||
class TestStorageServiceEmulatorUrls:
|
||||
"""Test emulator URL fallback when STORAGE_EMULATOR_HOST is set (local dev)."""
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -507,3 +507,130 @@ class TestWorkerLogEntryEdgeCases:
|
||||
# Should be ~30 days from now
|
||||
expected = datetime.now(timezone.utc) + timedelta(days=30)
|
||||
assert abs((entry.ttl_expiry - expected).total_seconds()) < 10
|
||||
|
||||
|
||||
class TestDocSizeRecovery:
|
||||
"""Self-healing when a job document hits Firestore's 1MB size limit.
|
||||
|
||||
A large legacy embedded ``worker_logs`` array (superseded by the logs
|
||||
subcollection) can push an old job document to ~1MB, after which EVERY
|
||||
write — including a customer submitting lyrics corrections — fails with
|
||||
Firestore's "exceeds the maximum allowed size" 400. update_job /
|
||||
update_job_status drop the deprecated array and retry once.
|
||||
"""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_db(self):
|
||||
return MagicMock()
|
||||
|
||||
@pytest.fixture
|
||||
def firestore_service(self, mock_db):
|
||||
with patch('backend.services.firestore_service.firestore') as mock_firestore:
|
||||
mock_firestore.Client.return_value = mock_db
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
service = FirestoreService()
|
||||
service.db = mock_db
|
||||
return service
|
||||
|
||||
@staticmethod
|
||||
def _size_error():
|
||||
return Exception(
|
||||
"400 Document 'projects/nomadkaraoke/databases/(default)/documents/"
|
||||
"jobs/d93747cd' cannot be written because its size (1,048,592 bytes) "
|
||||
"exceeds the maximum allowed size of 1,048,576 bytes."
|
||||
)
|
||||
|
||||
def test_update_job_recovers_by_clearing_worker_logs(self, firestore_service, mock_db):
|
||||
doc_ref = MagicMock()
|
||||
mock_db.collection.return_value.document.return_value = doc_ref
|
||||
# payload write fails (too big), worker_logs delete succeeds, retry succeeds
|
||||
doc_ref.update.side_effect = [self._size_error(), None, None]
|
||||
|
||||
firestore_service.update_job(
|
||||
"d93747cd", {"state_data.corrected_lyrics": {"corrected_segment_count": 5}}
|
||||
)
|
||||
|
||||
assert doc_ref.update.call_count == 3
|
||||
# Second write clears the legacy embedded worker_logs array
|
||||
delete_payload = doc_ref.update.call_args_list[1][0][0]
|
||||
assert "worker_logs" in delete_payload
|
||||
# Third write re-applies the caller's original field
|
||||
retry_payload = doc_ref.update.call_args_list[2][0][0]
|
||||
assert "state_data.corrected_lyrics" in retry_payload
|
||||
|
||||
def test_update_job_reraises_non_size_errors(self, firestore_service, mock_db):
|
||||
doc_ref = MagicMock()
|
||||
mock_db.collection.return_value.document.return_value = doc_ref
|
||||
doc_ref.update.side_effect = Exception("PERMISSION_DENIED")
|
||||
|
||||
with pytest.raises(Exception, match="PERMISSION_DENIED"):
|
||||
firestore_service.update_job("j", {"foo": "bar"})
|
||||
# No recovery attempt for unrelated errors
|
||||
assert doc_ref.update.call_count == 1
|
||||
|
||||
def test_worker_logs_write_does_not_recurse(self, firestore_service, mock_db):
|
||||
"""A write that is itself setting worker_logs must not self-clear+retry."""
|
||||
doc_ref = MagicMock()
|
||||
mock_db.collection.return_value.document.return_value = doc_ref
|
||||
doc_ref.update.side_effect = self._size_error()
|
||||
|
||||
with pytest.raises(Exception, match="maximum allowed size"):
|
||||
firestore_service.update_job("j", {"worker_logs": ["x"]})
|
||||
assert doc_ref.update.call_count == 1
|
||||
|
||||
def test_update_job_status_recovers_by_clearing_worker_logs(self, firestore_service, mock_db):
|
||||
doc_ref = MagicMock()
|
||||
mock_db.collection.return_value.document.return_value = doc_ref
|
||||
doc_ref.update.side_effect = [self._size_error(), None, None]
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
firestore_service.update_job_status("d93747cd", JobStatus.IN_REVIEW)
|
||||
|
||||
assert doc_ref.update.call_count == 3
|
||||
delete_payload = doc_ref.update.call_args_list[1][0][0]
|
||||
assert "worker_logs" in delete_payload
|
||||
|
||||
|
||||
class TestAppendWorkerLogRouting:
|
||||
"""Legacy dict-based append_worker_log must respect the subcollection flag
|
||||
so it stops bloating the embedded worker_logs array."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_db(self):
|
||||
return MagicMock()
|
||||
|
||||
@pytest.fixture
|
||||
def firestore_service(self, mock_db):
|
||||
with patch('backend.services.firestore_service.firestore') as mock_firestore:
|
||||
mock_firestore.Client.return_value = mock_db
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
service = FirestoreService()
|
||||
service.db = mock_db
|
||||
return service
|
||||
|
||||
def test_routes_to_subcollection_when_flag_on(self, firestore_service):
|
||||
with patch('backend.services.firestore_service.settings') as mock_settings:
|
||||
mock_settings.use_log_subcollection = True
|
||||
with patch.object(firestore_service, 'append_log_to_subcollection') as mock_sub:
|
||||
firestore_service.append_worker_log(
|
||||
"job123",
|
||||
{"timestamp": "t", "worker": "review", "level": "INFO", "message": "hi"},
|
||||
)
|
||||
mock_sub.assert_called_once()
|
||||
entry = mock_sub.call_args[0][1]
|
||||
assert entry.worker == "review"
|
||||
assert entry.level == "INFO"
|
||||
assert entry.message == "hi"
|
||||
|
||||
def test_uses_embedded_array_when_flag_off(self, firestore_service, mock_db):
|
||||
doc_ref = MagicMock()
|
||||
mock_db.collection.return_value.document.return_value = doc_ref
|
||||
with patch('backend.services.firestore_service.settings') as mock_settings:
|
||||
mock_settings.use_log_subcollection = False
|
||||
with patch.object(firestore_service, 'append_log_to_subcollection') as mock_sub:
|
||||
firestore_service.append_worker_log(
|
||||
"job123",
|
||||
{"timestamp": "t", "worker": "review", "level": "INFO", "message": "hi"},
|
||||
)
|
||||
mock_sub.assert_not_called()
|
||||
doc_ref.update.assert_called_once()
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Helpers for naming local temp copies of audio files downloaded from GCS.
|
||||
|
||||
ffmpeg falls back to extension-based format guessing when content probing is
|
||||
inconclusive (e.g. an MP3 whose multi-megabyte ID3 tag fills the probe
|
||||
buffer). Downloading a `.mp3` GCS object to a temp file named `foo.flac`
|
||||
makes ffmpeg commit to the flac demuxer and fail with "Could not find codec
|
||||
parameters ... 0 channels". Always name local copies with the source
|
||||
object's real extension.
|
||||
"""
|
||||
|
||||
from pathlib import PurePosixPath
|
||||
|
||||
# Extensions we recognise as audio containers. Anything else (or no
|
||||
# extension) falls back to no suffix, which forces pure content probing.
|
||||
_AUDIO_SUFFIXES = {
|
||||
".flac", ".mp3", ".wav", ".ogg", ".opus", ".m4a", ".aac",
|
||||
".mp4", ".wma", ".aiff", ".aif", ".webm", ".mka", ".mkv",
|
||||
}
|
||||
|
||||
|
||||
_AUDIO_CONTENT_TYPES = {
|
||||
".flac": "audio/flac",
|
||||
".mp3": "audio/mpeg",
|
||||
".wav": "audio/wav",
|
||||
".ogg": "audio/ogg",
|
||||
".opus": "audio/opus",
|
||||
".m4a": "audio/mp4",
|
||||
".aac": "audio/aac",
|
||||
".mp4": "audio/mp4",
|
||||
".wma": "audio/x-ms-wma",
|
||||
".aiff": "audio/aiff",
|
||||
".aif": "audio/aiff",
|
||||
".webm": "audio/webm",
|
||||
".mka": "audio/x-matroska",
|
||||
".mkv": "audio/x-matroska",
|
||||
}
|
||||
|
||||
|
||||
def audio_content_type(gcs_path: str) -> str:
|
||||
"""Return the MIME type for an audio object based on its extension.
|
||||
|
||||
Unknown extensions get application/octet-stream rather than a wrong
|
||||
audio/* type.
|
||||
"""
|
||||
suffix = PurePosixPath(gcs_path).suffix.lower()
|
||||
return _AUDIO_CONTENT_TYPES.get(suffix, "application/octet-stream")
|
||||
|
||||
|
||||
def local_audio_filename(gcs_path: str, stem: str = "audio") -> str:
|
||||
"""Return a local filename for a downloaded audio object.
|
||||
|
||||
Keeps the source object's extension (lowercased) so ffmpeg's
|
||||
extension-based fallback never mismatches the content. Unknown or
|
||||
missing extensions yield a bare name, which makes ffmpeg rely solely
|
||||
on content probing.
|
||||
|
||||
>>> local_audio_filename("jobs/x/input/Song (192 Kbps).mp3", "audio")
|
||||
'audio.mp3'
|
||||
>>> local_audio_filename("jobs/x/stems/backing_vocals.flac", "backing_vocals")
|
||||
'backing_vocals.flac'
|
||||
"""
|
||||
suffix = PurePosixPath(gcs_path).suffix.lower()
|
||||
if suffix in _AUDIO_SUFFIXES:
|
||||
return f"{stem}{suffix}"
|
||||
return stem
|
||||
@@ -0,0 +1,20 @@
|
||||
"""Stem-selection helpers shared by review routes and workers."""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
|
||||
def vocals_stem_path(job) -> Optional[str]:
|
||||
"""The full-vocal-mix stem for the review waveform, or None if absent.
|
||||
|
||||
Stem keys vary by separation model. We want the full vocal mix
|
||||
(lead + backing) so every word can be lined up against the waveform:
|
||||
- "vocals" : full vocal from a 2-stem split (rare)
|
||||
- "vocals_clean" : full vocal from the primary vocal/instrumental
|
||||
split (present on essentially all cloud jobs)
|
||||
- "lead_vocals" : last-resort fallback (misses backing lines)
|
||||
"""
|
||||
stems = job.file_urls.get("stems", {}) if job.file_urls else {}
|
||||
for key in ("vocals", "vocals_clean", "lead_vocals"):
|
||||
if stems.get(key):
|
||||
return stems[key]
|
||||
return None
|
||||
@@ -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)
|
||||
|
||||
|
||||
|
||||
+17
-10
@@ -354,17 +354,24 @@ background_tasks.add_task(worker_service.trigger_lyrics_worker, job_id)
|
||||
Coordination via job state:
|
||||
|
||||
```python
|
||||
# Audio worker completes
|
||||
job_manager.mark_audio_complete(job_id)
|
||||
→ Sets audio_complete flag
|
||||
→ Checks if lyrics also complete
|
||||
→ If both: triggers screens worker
|
||||
# Screen generation is gated on LYRICS ONLY — audio separation is decoupled so
|
||||
# reviewers can start while it finishes. mark_*_complete only persist a flag; the
|
||||
# screens dispatch is an AWAITED, idempotent call (advance_to_screens_if_ready).
|
||||
# A previous fire-and-forget asyncio trigger was cancelled on Cloud Run Job loop
|
||||
# teardown, orphaning jobs at `downloading` (E2E job-orchestration stall, 2026-09).
|
||||
|
||||
# Lyrics worker completes
|
||||
job_manager.mark_lyrics_complete(job_id)
|
||||
→ Sets lyrics_complete flag
|
||||
→ Checks if audio also complete
|
||||
→ If both: triggers screens worker
|
||||
# Lyrics worker completes (PRIMARY trigger)
|
||||
job_manager.mark_lyrics_complete(job_id) # sets lyrics_complete flag
|
||||
await job_manager.advance_to_screens_if_ready(job_id)
|
||||
→ if lyrics_complete and status == DOWNLOADING: await trigger_screens_worker()
|
||||
|
||||
# Audio worker completes (FALLBACK trigger — rescues a lost lyrics dispatch)
|
||||
job_manager.mark_audio_complete(job_id) # sets audio_complete flag
|
||||
await job_manager.advance_to_screens_if_ready(job_id)
|
||||
→ no-op unless lyrics already done AND still at DOWNLOADING (status guard)
|
||||
|
||||
# Defense-in-depth: recover-stuck-jobs (every 5 min) re-triggers any job left at
|
||||
# DOWNLOADING with lyrics_complete but no screens (a lost/failed dispatch).
|
||||
```
|
||||
|
||||
Benefits:
|
||||
|
||||
@@ -26,6 +26,7 @@ from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.audio_search_service import DownloadError
|
||||
from backend.services.job_health_service import validate_worker_can_run
|
||||
from backend.utils.audio_filenames import local_audio_filename
|
||||
from backend.config import get_settings
|
||||
from backend.workers.worker_logging import create_job_logger, setup_job_logging, job_logging_context
|
||||
from backend.workers.registry import worker_registry
|
||||
@@ -357,9 +358,15 @@ async def process_audio_separation(job_id: str) -> bool:
|
||||
logger.warning(f"[job:{job_id}] Backing vocals analysis failed (non-fatal): {e}")
|
||||
|
||||
# Mark audio processing complete
|
||||
# This will check if lyrics are also complete and transition to next stage if so
|
||||
job_manager.mark_audio_complete(job_id)
|
||||
|
||||
# Fallback screens trigger: if lyrics already finished but its
|
||||
# (primary) screens dispatch was lost, advancing here rescues the
|
||||
# job. No-op unless lyrics are done AND the job is still at
|
||||
# `downloading`, so the audio/review decoupling is preserved and a
|
||||
# normal run never double-triggers.
|
||||
await job_manager.advance_to_screens_if_ready(job_id)
|
||||
|
||||
# Auto-approval second chance: when lyrics/screens finished BEFORE
|
||||
# audio, the job is already parked in AWAITING_REVIEW and the
|
||||
# screens-worker scoring ran without backing analysis. Now that
|
||||
@@ -477,7 +484,7 @@ async def download_audio(
|
||||
if job.file_urls and job.file_urls.get('input'):
|
||||
# Already downloaded and stored in GCS
|
||||
input_url = job.file_urls.get('input')
|
||||
local_path = os.path.join(temp_dir, "input.flac")
|
||||
local_path = os.path.join(temp_dir, local_audio_filename(str(input_url), "input"))
|
||||
storage.download_file(input_url, local_path)
|
||||
logger.info(f"Job {job_id}: Downloaded audio from GCS: {input_url}")
|
||||
return local_path
|
||||
|
||||
@@ -34,6 +34,7 @@ from backend.services.storage_service import StorageService
|
||||
from backend.services.audio_search_service import DownloadError
|
||||
from backend.services.job_health_service import validate_worker_can_run
|
||||
from backend.services.lyrics_cache_service import LyricsCacheService
|
||||
from backend.utils.audio_filenames import local_audio_filename
|
||||
from backend.workers.worker_logging import create_job_logger, setup_job_logging, job_logging_context
|
||||
from backend.workers.style_helper import load_style_config
|
||||
from backend.workers.registry import worker_registry
|
||||
@@ -533,10 +534,14 @@ async def process_lyrics_transcription(job_id: str) -> bool:
|
||||
'message': 'Lyrics transcription complete'
|
||||
})
|
||||
|
||||
# Mark lyrics processing complete
|
||||
# This will check if audio is also complete and transition to next stage if so
|
||||
job_log.info("Lyrics worker complete, checking if audio is also done...")
|
||||
# Mark lyrics processing complete, then durably (AWAITED) trigger
|
||||
# the screens worker. The old fire-and-forget trigger was being
|
||||
# cancelled on Cloud Run Job event-loop teardown, orphaning jobs at
|
||||
# `downloading`; awaiting guarantees the screens Cloud Task is
|
||||
# enqueued before this worker returns.
|
||||
job_log.info("Lyrics worker complete, advancing to screen generation...")
|
||||
job_manager.mark_lyrics_complete(job_id)
|
||||
await job_manager.advance_to_screens_if_ready(job_id)
|
||||
|
||||
# Proactively pre-generate + cache AI auto-correct suggestions so
|
||||
# they're ready when the reviewer opens the lyrics UI. The work
|
||||
@@ -628,7 +633,7 @@ async def download_audio(
|
||||
try:
|
||||
# If input_media_gcs_path is already set, download directly
|
||||
if job.input_media_gcs_path:
|
||||
local_path = os.path.join(temp_dir, job.filename or "input.flac")
|
||||
local_path = os.path.join(temp_dir, job.filename or local_audio_filename(job.input_media_gcs_path, "input"))
|
||||
storage.download_file(job.input_media_gcs_path, local_path)
|
||||
logger.info(f"Job {job_id}: Downloaded audio from {job.input_media_gcs_path} to {local_path}")
|
||||
return local_path
|
||||
@@ -646,7 +651,7 @@ async def download_audio(
|
||||
|
||||
if updated_job and updated_job.input_media_gcs_path:
|
||||
# Audio worker has uploaded the file
|
||||
local_path = os.path.join(temp_dir, "input.flac")
|
||||
local_path = os.path.join(temp_dir, local_audio_filename(updated_job.input_media_gcs_path, "input"))
|
||||
storage.download_file(updated_job.input_media_gcs_path, local_path)
|
||||
logger.info(f"Job {job_id}: Downloaded audio from {updated_job.input_media_gcs_path}")
|
||||
return local_path
|
||||
|
||||
@@ -36,6 +36,7 @@ from dataclasses import dataclass
|
||||
|
||||
from backend.models.job import JobStatus
|
||||
from backend.exceptions import InvalidStateTransitionError
|
||||
from backend.utils.audio_filenames import local_audio_filename
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.job_health_service import validate_worker_can_run
|
||||
@@ -486,8 +487,8 @@ async def process_render_video(job_id: str) -> bool:
|
||||
raise ValueError(str(timing_err)) from timing_err
|
||||
|
||||
# 5. Download audio file
|
||||
audio_path = os.path.join(temp_dir, "audio.flac")
|
||||
audio_gcs_path = job.input_media_gcs_path
|
||||
audio_path = os.path.join(temp_dir, local_audio_filename(audio_gcs_path or "", "audio"))
|
||||
|
||||
if not audio_gcs_path:
|
||||
raise FileNotFoundError(f"No input audio path for job {job_id}")
|
||||
|
||||
@@ -22,6 +22,7 @@ Observability:
|
||||
- Logs include [job:ID] prefix for easy filtering in Cloud Logging
|
||||
- Worker start/end timing logged with WORKER_START/WORKER_END markers
|
||||
"""
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
@@ -53,6 +54,18 @@ SCREENS_WORKER_LOGGERS = [
|
||||
"backend.workers.style_helper",
|
||||
]
|
||||
|
||||
# Statuses from which screen generation may legitimately start. The screens
|
||||
# worker can be dispatched more than once — the lyrics worker (primary) and the
|
||||
# audio worker (fallback) may both trigger it, and Cloud Tasks may redeliver — so
|
||||
# a dispatch that arrives when the job has already advanced past these states is a
|
||||
# duplicate and must no-op (see generate_screens).
|
||||
_SCREENS_ENTRY_STATUSES = frozenset({
|
||||
JobStatus.DOWNLOADING,
|
||||
JobStatus.AUDIO_EDIT_COMPLETE,
|
||||
JobStatus.AUDIO_COMPLETE,
|
||||
JobStatus.LYRICS_COMPLETE,
|
||||
})
|
||||
|
||||
|
||||
async def generate_screens(job_id: str) -> bool:
|
||||
"""
|
||||
@@ -78,19 +91,36 @@ async def generate_screens(job_id: str) -> bool:
|
||||
# Log with structured markers for easy Cloud Logging queries
|
||||
logger.info(f"[job:{job_id}] WORKER_START worker=screens")
|
||||
|
||||
# Set up log capture for VideoGenerator and style_helper
|
||||
log_handler = setup_job_logging(job_id, "screens", *SCREENS_WORKER_LOGGERS)
|
||||
|
||||
# Resolve the job and run the cheap guards BEFORE attaching the job-log handler,
|
||||
# so an early return (not-found / duplicate dispatch / prerequisites) cannot leak
|
||||
# a JobLogHandler — each leaked handler re-appends log records to Firestore and
|
||||
# retains memory.
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
logger.error(f"[job:{job_id}] Job not found")
|
||||
return False
|
||||
|
||||
|
||||
# Idempotency guard: this worker may be dispatched twice (lyrics primary +
|
||||
# audio fallback triggers, or a Cloud Tasks redelivery). Once the job has
|
||||
# advanced past the pre-screens stage, a second dispatch is a duplicate — no-op
|
||||
# rather than re-running the (invalid) GENERATING_SCREENS transition and
|
||||
# regenerating screens.
|
||||
if job.status not in _SCREENS_ENTRY_STATUSES:
|
||||
logger.info(
|
||||
f"[job:{job_id}] Screens already triggered/advanced "
|
||||
f"(status={job.status}); skipping duplicate dispatch"
|
||||
)
|
||||
return True
|
||||
|
||||
# Validate both audio and lyrics are complete
|
||||
if not _validate_prerequisites(job):
|
||||
logger.error(f"[job:{job_id}] Prerequisites not met for screen generation")
|
||||
return False
|
||||
|
||||
|
||||
# Set up log capture for VideoGenerator and style_helper (after the guards above
|
||||
# so their early returns don't leak handlers).
|
||||
log_handler = setup_job_logging(job_id, "screens", *SCREENS_WORKER_LOGGERS)
|
||||
|
||||
# Create temporary working directory
|
||||
temp_dir = tempfile.mkdtemp(prefix=f"karaoke_screens_{job_id}_")
|
||||
|
||||
@@ -102,13 +132,29 @@ async def generate_screens(job_id: str) -> bool:
|
||||
job_log.info(f"Starting screen generation for {job.artist} - {job.title}")
|
||||
logger.info(f"[job:{job_id}] Starting screen generation for {job.artist} - {job.title}")
|
||||
|
||||
# Transition to GENERATING_SCREENS state
|
||||
job_manager.transition_to_state(
|
||||
# Claim the job for screen generation via the status transition
|
||||
# itself. If a concurrent duplicate dispatch already advanced it,
|
||||
# the transition is invalid and (raise_on_invalid=False) returns
|
||||
# False — bail out cleanly instead of regenerating screens. Together
|
||||
# with the entry-status guard above this narrows the concurrent
|
||||
# lyrics+audio double-trigger window to near zero. (A fully
|
||||
# transactional compare-and-set on the status field would close the
|
||||
# residual sub-millisecond window; deferred as the worker is
|
||||
# otherwise idempotent — worst case is duplicated work, not
|
||||
# corruption.)
|
||||
claimed = job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.GENERATING_SCREENS,
|
||||
progress=50,
|
||||
message="Generating title and end screens"
|
||||
message="Generating title and end screens",
|
||||
raise_on_invalid=False,
|
||||
)
|
||||
if not claimed:
|
||||
logger.info(
|
||||
f"[job:{job_id}] Screens already claimed by another dispatch "
|
||||
"(transition rejected); skipping duplicate"
|
||||
)
|
||||
return True
|
||||
|
||||
# Log style assets info
|
||||
style_assets = getattr(job, 'style_assets', {}) or {}
|
||||
@@ -721,6 +767,42 @@ async def _transcode_review_audio(
|
||||
|
||||
job_log.info(f"Review audio transcoding complete: {len(transcoded)} files")
|
||||
|
||||
# Pre-compute the review-page waveform JSON while we're here, so the
|
||||
# /waveform-data endpoint is a pure GCS-cache read when the user opens
|
||||
# review (a miss there decodes a whole stem — seconds of CPU on the
|
||||
# API instance, which is what wedged it under concurrent load).
|
||||
from backend.services.audio_analysis_service import AudioAnalysisService
|
||||
|
||||
stems = job.file_urls.get("stems", {}) if job.file_urls else {}
|
||||
waveform_source = stems.get("backing_vocals") or job.input_media_gcs_path
|
||||
if waveform_source:
|
||||
try:
|
||||
await asyncio.to_thread(
|
||||
AudioAnalysisService().get_review_waveform,
|
||||
waveform_source, job_id, 1000, transcoding,
|
||||
)
|
||||
job_log.info("Review waveform data pre-computed")
|
||||
except Exception as e:
|
||||
# Non-fatal: /waveform-data computes + caches lazily on first open
|
||||
job_log.warning(f"Review waveform pre-compute failed (non-fatal): {e}")
|
||||
|
||||
# Pre-compute the vocals peak envelope too (Waveforms review mode) so
|
||||
# /vocals-peaks is a pure cache read and the per-segment strips paint
|
||||
# sub-second on first open.
|
||||
from backend.utils.stems import vocals_stem_path
|
||||
|
||||
vocals_source = vocals_stem_path(job)
|
||||
if vocals_source:
|
||||
try:
|
||||
await asyncio.to_thread(
|
||||
AudioAnalysisService().get_vocals_peaks,
|
||||
vocals_source, job_id, 400, transcoding,
|
||||
)
|
||||
job_log.info("Vocals peak envelope pre-computed")
|
||||
except Exception as e:
|
||||
# Non-fatal: /vocals-peaks computes + caches lazily on first open
|
||||
job_log.warning(f"Vocals peaks pre-compute failed (non-fatal): {e}")
|
||||
|
||||
except Exception as e:
|
||||
# Non-fatal: review UI will fall back to FLAC signed URLs
|
||||
job_log.warning(f"Review audio transcoding failed (non-fatal): {e}")
|
||||
|
||||
@@ -432,6 +432,18 @@ async def generate_video_orchestrated(job_id: str) -> bool:
|
||||
timeline_metadata=completion_metadata,
|
||||
)
|
||||
|
||||
# If this was a requests-board community pick published directly here
|
||||
# (i.e. not deferred to the youtube_upload_queue), advance its request
|
||||
# to `published` and fan out "your track is live" voter emails. The
|
||||
# queue path fires the same helper; jobs deferred to the queue are
|
||||
# handled there instead, so we skip them to avoid a premature publish.
|
||||
if result.youtube_url and not result.youtube_upload_queued:
|
||||
try:
|
||||
from backend.services.community_publish import notify_community_publish
|
||||
await notify_community_publish(job_id, result.youtube_url)
|
||||
except Exception:
|
||||
logger.exception(f"[job:{job_id}] Community publish fan-out failed (non-fatal)")
|
||||
|
||||
root_span.set_attribute("duration_seconds", duration)
|
||||
root_span.set_attribute("brand_code", result.brand_code or '')
|
||||
logger.info(f"[job:{job_id}] WORKER_END worker=video orchestrator=true status=success duration={duration:.1f}s")
|
||||
@@ -1024,6 +1036,15 @@ async def generate_video_legacy(job_id: str) -> bool:
|
||||
timeline_metadata=completion_metadata,
|
||||
)
|
||||
|
||||
# Advance a requests-board community pick to `published` + fan out
|
||||
# voter emails (legacy path always publishes directly here).
|
||||
if result.get('youtube_url'):
|
||||
try:
|
||||
from backend.services.community_publish import notify_community_publish
|
||||
await notify_community_publish(job_id, result.get('youtube_url'))
|
||||
except Exception:
|
||||
logger.exception(f"[job:{job_id}] Community publish fan-out failed (non-fatal)")
|
||||
|
||||
root_span.set_attribute("duration_seconds", duration)
|
||||
root_span.set_attribute("brand_code", result.get('brand_code', ''))
|
||||
logger.info(f"[job:{job_id}] WORKER_END worker=video status=success duration={duration:.1f}s")
|
||||
|
||||
@@ -11,6 +11,7 @@ import tempfile
|
||||
from typing import Dict, Any, Optional
|
||||
|
||||
from backend.config import get_settings
|
||||
from backend.services.community_publish import notify_community_publish
|
||||
from backend.services.job_manager import JobManager
|
||||
from backend.services.storage_service import StorageService
|
||||
from backend.services.youtube_quota_service import get_youtube_quota_service
|
||||
@@ -91,7 +92,7 @@ async def process_youtube_upload_queue() -> Dict[str, Any]:
|
||||
|
||||
# If this was a requests-board community pick, mark it published
|
||||
# and fan out "your track is live" emails to everyone who voted.
|
||||
await _notify_community_voters(job_id, entry, youtube_url)
|
||||
await notify_community_publish(job_id, youtube_url)
|
||||
|
||||
processed += 1
|
||||
else:
|
||||
@@ -304,68 +305,6 @@ def _update_job_youtube_url(job_id: str, youtube_url: str) -> None:
|
||||
logger.error(f"Failed to update job {job_id} with YouTube URL: {e}")
|
||||
|
||||
|
||||
async def _notify_community_voters(
|
||||
job_id: str, entry: Dict[str, Any], youtube_url: str
|
||||
) -> None:
|
||||
"""Publish fan-out for requests-board picks: mark the request published and
|
||||
email every up-voter (except the owner, who already got the completion email).
|
||||
|
||||
Idempotent via the request's ``voters_notified`` flag. Best-effort — never
|
||||
fails the upload over a notification error.
|
||||
"""
|
||||
try:
|
||||
from backend.services.song_request_service import get_song_request_service
|
||||
service = get_song_request_service()
|
||||
request = service.get_by_job_id(job_id)
|
||||
if request is None:
|
||||
return # Not a community pick — normal job.
|
||||
|
||||
service.mark_published(request.id, youtube_url)
|
||||
|
||||
if request.voters_notified:
|
||||
return
|
||||
|
||||
# Email up-voters we haven't already reached (retry-safe): exclude the
|
||||
# owner (already got the completion email) and anyone previously notified.
|
||||
owner = (request.owner_email or request.submitted_by or "").lower()
|
||||
already = {v.lower() for v in (request.notified_voters or [])}
|
||||
pending = [
|
||||
v for v in service.list_upvoters(request.id)
|
||||
if v != owner and v not in already
|
||||
]
|
||||
|
||||
from backend.services.job_notification_service import get_job_notification_service
|
||||
notification_service = get_job_notification_service()
|
||||
succeeded = 0
|
||||
for voter in pending:
|
||||
try:
|
||||
ok = await notification_service.send_community_track_live_email(
|
||||
to_email=voter,
|
||||
artist=request.artist,
|
||||
title=request.title,
|
||||
youtube_url=youtube_url,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Failed community voter email for job %s / %s", job_id, voter)
|
||||
continue
|
||||
if ok:
|
||||
# Record each success immediately so a crash mid-loop never
|
||||
# re-emails an already-notified voter on the retry.
|
||||
service.add_notified_voters(request.id, [voter])
|
||||
succeeded += 1
|
||||
|
||||
# Only flag "fully notified" when every pending voter was reached — a
|
||||
# partial failure leaves the flag unset so a re-run retries just the misses.
|
||||
if succeeded == len(pending):
|
||||
service.mark_voters_notified(request.id)
|
||||
logger.info(
|
||||
"community pick %s published (job %s): notified %d/%d pending voters",
|
||||
request.id, job_id, len(succeeded), len(pending),
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed community voter fan-out for job {job_id}: {e}")
|
||||
|
||||
|
||||
async def _send_youtube_upload_notification(
|
||||
job_id: str, entry: Dict[str, Any], youtube_url: str
|
||||
) -> None:
|
||||
|
||||
+97
-1
@@ -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,36 @@ 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).
|
||||
|
||||
#### Waveform Data (review page)
|
||||
|
||||
```http
|
||||
GET /api/review/{job_id}/waveform-data?num_points=1000
|
||||
```
|
||||
|
||||
Returns `{amplitudes, duration_seconds, duration, sample_rate}` for canvas rendering of the
|
||||
backing-vocals waveform. Served from a **persistent GCS cache**
|
||||
(`jobs/{job_id}/review-audio/waveform_review_{num_points}.json`, validated against the source
|
||||
stem path + `num_points`), pre-computed by `screens_worker` before the job reaches review. A
|
||||
cache miss decodes the transcoded review OGG off the event loop, bounded by
|
||||
`REVIEW_WAVEFORM_MAX_CONCURRENCY` (default 4) — added in v0.230.0 after uncached in-request
|
||||
decoding wedged the service under concurrent review-page loads.
|
||||
|
||||
Note: `/audio/vocals` (and the instrumental proxy above) serve from a bounded in-memory LRU,
|
||||
honor HTTP Range (`206`), and set `Cache-Control: private, max-age=600`.
|
||||
|
||||
#### Create Custom Instrumental
|
||||
|
||||
```http
|
||||
@@ -1448,6 +1482,24 @@ X-Admin-Token: ADMIN_TOKEN
|
||||
|
||||
Internal (admin/OIDC). Called hourly by Cloud Scheduler. For each in-progress community pick whose owner hasn't completed their review within 24h (and whose job is blocked waiting on the owner), reassigns the job to the next up-voter (oldest-first, skipping those already tried) and emails them — up to 5 voters, then parks the track (`stalled`). Returns `{status, checked, handed_off, parked, errors}`.
|
||||
|
||||
### Community Publish Reconcile (internal)
|
||||
|
||||
```http
|
||||
POST /api/internal/community-requests/reconcile
|
||||
X-Admin-Token: ADMIN_TOKEN
|
||||
```
|
||||
|
||||
Internal (admin/OIDC). Idempotent safety net / backfill. A community pick advances to `published` (and fans out "your track is live" emails to up-voters) when its job goes live on YouTube — this now fires from both publish paths (the `youtube_upload_queue` processor and the direct video-worker distribution). This endpoint reconciles any pick still stuck at `in_progress` whose job actually has a YouTube URL, running the publish transition for each. Returns `{scanned, published: [{request_id, job_id, youtube_url}]}`.
|
||||
|
||||
### Community Requests History (admin)
|
||||
|
||||
```http
|
||||
GET /api/admin/community-requests
|
||||
X-Admin-Token: ADMIN_TOKEN
|
||||
```
|
||||
|
||||
Admin. Full history of requests-board submissions across every status (newest first), surfaced at `/admin/community-requests`. Each item: `{id, artist, title, status, submitted_by, owner_email, vote_count, job_id, youtube_url, review_state, created_at, picked_at}` — who asked, how it was voted, which job made it, and where it landed on YouTube.
|
||||
|
||||
### Community Review Queue (existing-version, admin)
|
||||
|
||||
```http
|
||||
@@ -2617,3 +2669,47 @@ search returned nothing usable.
|
||||
|
||||
Stripe webhooks implemented at `/api/users/webhooks/stripe`.
|
||||
Job status webhooks not yet implemented.
|
||||
|
||||
## Client Telemetry
|
||||
|
||||
### Degradation Events
|
||||
|
||||
```http
|
||||
POST /api/client-events
|
||||
```
|
||||
|
||||
Unauthenticated, rate-limited (120/min/IP — sized so a many-tab burst from one IP is fully recorded), bot-filtered. The frontend reports every
|
||||
user-visible degraded-service surface: `banner_reconnecting`, `banner_unavailable`
|
||||
(the connectivity banner — reported by `BackendStatusBanner`), `lyrics_load_failed`
|
||||
(review page "temporarily unavailable"), `waveform_slow` / `waveform_failed`
|
||||
(Waveforms-mode strips late or missing). Body: `{type, url, job_id?, user_email?,
|
||||
locale, release, detail?}` — `detail` is size-capped server-side (≤12 keys, ≤200
|
||||
chars per value); URLs are stored query-stripped.
|
||||
|
||||
Each event emits a structured `client_event type=…` INFO log line and is
|
||||
best-effort persisted to the Firestore `client_events` collection (a Firestore
|
||||
write failure is logged but still returns `202` — telemetry never errors back to
|
||||
the client), so frequency can be reviewed later
|
||||
(Firestore aggregation, or Cloud Logging correlated with backend symptoms from the
|
||||
same window). Reporter: `frontend/lib/degradation-events.ts` (60s per-type throttle,
|
||||
localhost no-op). Added in v0.231.0 — see
|
||||
`docs/archive/2026-09-18-concurrent-review-reliability-investigation-and-plan.md`.
|
||||
|
||||
Crash reports are the separate `POST /api/client-errors` (error-monitor pipeline).
|
||||
|
||||
### Vocals Peaks (Waveforms review mode)
|
||||
|
||||
```http
|
||||
GET /api/review/{job_id}/vocals-peaks?peaks_per_second=400
|
||||
```
|
||||
|
||||
Pre-computed max-abs peak envelope of the vocal stem:
|
||||
`{peaks_b64, encoding: "u8", peaks_per_second, duration_seconds}` — base64 of one
|
||||
uint8 per 1/400s bucket (~150 KB for a 5-minute track). Replaces the frontend's
|
||||
download+decode of the whole vocals OGG so Waveforms-mode strips paint sub-second.
|
||||
Served from a persistent GCS cache (`review-audio/vocals_peaks_{pps}.json`,
|
||||
validated against the stem path), pre-computed by `screens_worker`; a miss computes
|
||||
off the event loop under the shared waveform semaphore. Returns `202 Retry-After: 15`
|
||||
while audio separation is still producing the stem. Auth like `/audio/vocals`
|
||||
(`?token=` / `?review_token=`). The frontend falls back to the full audio decode if
|
||||
this endpoint fails (`VocalsAudioDataLoader`). Added in v0.232.0.
|
||||
@@ -516,6 +516,9 @@ When a document's payload can exceed Firestore's 1MB limit (e.g., CorrectionData
|
||||
### Strip Whole Categories, Not Single Fields, From Firestore Saves (Jun 2026)
|
||||
`submit_corrections` originally stripped only `reference_lyrics` before writing corrections to `state_data`. A 32-minute mashup (prod job 9a12cf0f, 422 segments) then hit the 1MB limit anyway — the real bulk was the segment arrays (`corrected_segments`/`original_segments`/`resized_segments`, ~600KB each), not reference_lyrics. **Lesson:** when guarding against the doc-size limit, persist a small *allowlisted summary* to Firestore (here: `{'corrected_segment_count': N}`) rather than denylisting known-big fields one at a time — the next big field will silently reappear. The full payload already lives in GCS (`corrections_updated.json`); the render worker reads from there. The only in-Firestore consumer was the complete-review 0-segment guard, which just needs the count.
|
||||
|
||||
### The Blocker Can Be a *Different* Field Than the One Being Written (Sep 2026)
|
||||
A customer couldn't submit their review — `POST /jobs/{id}/corrections` failed with Firestore's "size (1,048,592 bytes) exceeds the maximum allowed size of 1,048,576 bytes". The corrections endpoint was innocent: it already persists only a tiny `{'corrected_segment_count': N}` summary (see above). The bloat was an unrelated field — a **1.19MB embedded `worker_logs` array** on the job doc. Once any field pushes a document to ~1MB, *every* subsequent write to that doc fails, so the symptom surfaces on whatever the user happens to click next. Two causes: (1) `worker_logs` is deprecated (logs now live in the `jobs/{id}/logs` subcollection) but the legacy dict-based `FirestoreService.append_worker_log` ignored `USE_LOG_SUBCOLLECTION` and kept appending to the embedded array — the review-flow `JobLogger`/`FirestoreJobLogHandler` in `job_logging.py` used exactly that path; (2) old docs already carrying the bloat can't be written at all. **Fixes:** route `append_worker_log` through the subcollection when the flag is on (stops new bloat), and make `update_job`/`update_job_status` self-heal — on a size-limit error, drop the deprecated `worker_logs` field and retry once (unblocks already-bloated docs on their next write, since ADC is read-only and can't be cleared out-of-band). **Lesson:** when a write fails on doc size, don't assume the payload you're writing is the culprit — measure per-field sizes (`len(json.dumps(v))`) of the *existing* document first.
|
||||
|
||||
### Scale Worker Timeouts by Input Size (Jun 2026)
|
||||
The lyrics worker used a fixed 1200s transcription timeout. The same 32-min mashup flapped to `failed` when AudioShake was slow, even though a healthy run transcribes it in ~438s. Fix: `compute_transcription_timeout()` scales the safety-net timeout by ffprobe-measured audio duration, clamped to `[floor, cap]` where the cap stays under the Cloud Run Job task timeout (raised 1800→3000s; app cap 2700s via env). Fixed timeouts that work for the median input will fail outliers — scale by the dimension that drives the cost.
|
||||
|
||||
@@ -1940,3 +1943,28 @@ too instead of regressing to the vulnerable path.
|
||||
its own failures (park/fail/supersede), so the CLI exits 0 on any clean return and
|
||||
1 only on an escaped crash — otherwise `max_retries=2` would re-enter jobs that
|
||||
already moved to a non-render state.
|
||||
|
||||
## Lyrics-review "Waveforms" mode — two React/CSS gotchas (Sep 2026, v0.227.0)
|
||||
|
||||
Added a third Synced Lyrics view ("Waveforms") that renders a compact inline copy of
|
||||
the Edit Segment timeline (`TimelineEditor`) per segment. Full write-up:
|
||||
`docs/archive/2026-09-17-waveforms-review-mode-plan.md`. Two bugs worth remembering:
|
||||
|
||||
- **Never call a parent's setState from inside a `setState` updater.** The per-row
|
||||
`WaveformSegmentRow` committed its dragged timing on mouse-up via
|
||||
`setWords(cur => { onCommit(recompute(cur)); return cur })` — reading the latest words
|
||||
through the updater. React runs updater functions *during render*, so `onCommit`
|
||||
(which calls the parent's `updateDataWithHistory` → `setHistory`) fired a parent
|
||||
update mid-render: *"Cannot update a component while rendering a different component."*
|
||||
Fix: keep a `wordsRef` synced alongside the `words` state and read `wordsRef.current`
|
||||
from the event handler — never call outward-facing callbacks from inside an updater.
|
||||
- **`overflow-hidden` on a bar clips anything positioned *above* it.** The
|
||||
AI-correction "ghost" (original text, struck-through) floats above its word bar via
|
||||
`absolute bottom-full`, so it's a visual child that lives outside the bar's box.
|
||||
Adding `overflow-hidden` to the bar (to truncate long word text) silently hid the
|
||||
ghost. Truncate the inner text span (`truncate min-w-0`) instead of clipping the bar.
|
||||
|
||||
Also: colour-code the bars with the **exact** `HIGHLIGHT_CLASSES` tints the Advanced
|
||||
pills use (not hand-picked solids) so the two views read identically, and persist the
|
||||
view mode under a new `lyricsReviewViewMode` enum that migrates the old
|
||||
`lyricsReviewAdvancedMode` boolean.
|
||||
@@ -456,6 +456,25 @@ The production tests cover:
|
||||
- Final encoding and download
|
||||
- Admin dashboard functionality
|
||||
|
||||
## Concurrent-Load Regression Test (review pages)
|
||||
|
||||
`scripts/load-test-review.py` replays the 2026-09-18 "10 tabs melt the backend"
|
||||
incident: N simultaneous review-tab loads, each firing the page's real GET trio
|
||||
(correction-data, waveform-data, ranged audio/vocals), authenticated with per-job
|
||||
review tokens read from Firestore via ADC (no admin secret needed).
|
||||
|
||||
```bash
|
||||
python scripts/load-test-review.py # 10 tabs vs prod, warm thresholds
|
||||
python scripts/load-test-review.py --tabs 20
|
||||
python scripts/load-test-review.py --max-tab-seconds 45 # cold caches (first-ever waveforms)
|
||||
```
|
||||
|
||||
Pass = every request 2xx and every tab under the threshold; exit 1 otherwise.
|
||||
Run it after changes to the review hot path (`backend/api/routes/review.py`,
|
||||
`audio_transcoding_service`, `audio_analysis_service`) or Cloud Run deploy flags.
|
||||
Background + before/after numbers:
|
||||
`docs/archive/2026-09-18-concurrent-review-reliability-investigation-and-plan.md`.
|
||||
|
||||
## Ad-Hoc Production Debugging (for Agents)
|
||||
|
||||
When asked to "test it yourself in prod" or debug a specific production issue, use the debug script template:
|
||||
|
||||
@@ -4,6 +4,62 @@ Operational runbooks for known production issues.
|
||||
|
||||
---
|
||||
|
||||
## Review pages hang on "Loading lyrics data…" / uptime alert "Service Unavailable"
|
||||
|
||||
**Symptom:** `/app/jobs/#/{id}/review` spins forever; the browser is stuck fetching
|
||||
`GET /api/review/{id}/correction-data`, which eventually returns "server temporarily
|
||||
unavailable". A GCP uptime alert ("Karaoke Backend - Service Unavailable") may fire.
|
||||
`/api/health` and `/api/jobs` still respond fast.
|
||||
|
||||
**Root cause (incident 2026-09-17):** GCS **signed-URL generation** stalls. On Cloud
|
||||
Run we have no private key, so signing goes through the IAM `signBlob` API over the
|
||||
network. `correction-data` signs 2-3 audio/waveform URLs per load; when signBlob
|
||||
stalls (transient IAM/metadata networking; **no GCP incident is necessarily declared**),
|
||||
those calls hang and pile up worker threads until the service looks down. Tell-tale
|
||||
in logs: `"Generated signed … URL"` lines **stop appearing** while everything else
|
||||
keeps logging, and there are **no** `"Error generating signed"` lines (a hang, not a
|
||||
failure). Confirm it's not job-specific: `correction-data` hangs for *every* in-review
|
||||
job, not just one.
|
||||
|
||||
**Immediate fix — restart to get fresh instances / connection pools:**
|
||||
```bash
|
||||
gcloud run services update karaoke-backend --region=us-central1 --project=nomadkaraoke \
|
||||
--update-labels=forcerestart=$(date +%s)
|
||||
```
|
||||
Non-destructive (config unchanged, new revision). Then verify signing resumed
|
||||
(replace `JOB_ID` with any in-review job id — the URL is quoted so no placeholder
|
||||
angle-brackets reach the shell):
|
||||
```bash
|
||||
# should return 200 fast, not hang
|
||||
JOB_ID="d93747cd" # any in-review job
|
||||
curl -s -m 30 -o /dev/null -w "%{http_code} %{time_total}s\n" \
|
||||
-H "Authorization: Bearer $(gcloud secrets versions access latest --secret=admin-tokens --project=nomadkaraoke | cut -d, -f1)" \
|
||||
"https://api.nomadkaraoke.com/api/review/${JOB_ID}/correction-data"
|
||||
# and check signing is logging again
|
||||
gcloud logging read 'resource.type="cloud_run_revision" AND resource.labels.service_name="karaoke-backend" AND jsonPayload.message:"Generated signed"' \
|
||||
--project=nomadkaraoke --freshness=3m --limit=3 --format="value(timestamp,jsonPayload.message)"
|
||||
```
|
||||
If a restart doesn't clear it, the IAM Credentials API is genuinely degraded in the
|
||||
region — wait it out / open a GCP ticket.
|
||||
|
||||
**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.
|
||||
|
||||
---
|
||||
|
||||
## Fast rollback (bad backend deploy)
|
||||
|
||||
**When to use:** a merge-to-main deploy shipped a bad backend revision — the
|
||||
@@ -273,6 +329,18 @@ python scripts/backfill_gdrive_uploads.py --job-ids JOB1,JOB2
|
||||
|
||||
---
|
||||
|
||||
## Review waveform 500 / preview encode fails: "Could not find codec parameters for stream 0 (Audio: flac, 0 channels)"
|
||||
|
||||
**Symptoms (all at once, for one job):** `waveform-data` returns 500 ("Decoding failed. ffmpeg returned error code: 8"), review OGG transcode falls back to FLAC ("Cannot determine format of input 0:0 after EOF"), preview video fails on both GCE and local fallback ("Invalid data found when processing input"), and "Failed to get audio duration: 'duration'" appears in logs. The pipeline itself completed fine (stems/lyrics exist).
|
||||
|
||||
**Cause:** The uploaded input audio is a valid MP3 with a very large ID3 tag (megabytes of embedded cover art — common in ytmp3-site rips; a `majorbrand: dash` ID3 tag is a telltale, but it's just copied metadata, not a mislabeled MP4). The backend downloaded job audio to temp files hardcoded as `*.flac`; ffmpeg's content probe is inconclusive inside the huge tag, so it falls back to the file extension, commits to the flac demuxer, and fails. The file itself is fine — `ffprobe` succeeds when the local copy keeps its real extension.
|
||||
|
||||
**Fix (v0.229.4+):** All temp downloads of job audio now preserve the source object's extension (`backend/utils/audio_filenames.local_audio_filename`). No job data repair is needed — once deployed, the same job's review page works as-is.
|
||||
|
||||
**Diagnosis tip:** Download the input object and run `ffprobe` on it twice — once named `.mp3`/no extension, once named `.flac`. If only the `.flac`-named copy fails, it's this extension-fallback class, not a corrupt upload.
|
||||
|
||||
---
|
||||
|
||||
## Job failed: "Audio separation failed: expected str, bytes or os.PathLike object, not NoneType"
|
||||
|
||||
**Cause (historical):** Modal API intermittently returned fewer stems than expected from stage 2 (backing vocals) separation. Missing stems caused NoneType crashes in downstream processing. This was resolved by migrating to Cloud Run GPU (see `docs/archive/2026-03-22-modal-to-gcp-migration-plan.md`).
|
||||
|
||||
@@ -0,0 +1,323 @@
|
||||
# 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,
|
||||
> excluded 2 test requesters. Corrected names unlocked big torrents (Early Mornin' 189
|
||||
> seeders, KAYTRANADA 10% 209, BOOMPALA, Luther Vandross). **FINAL BUCKETS
|
||||
> (`review_summary_v3.md` / `actions_v3.json`): 87 requesters · 27 community (searched
|
||||
> songs; +20 phase-1 links) · 65 torrent-submit · 29 spotify/youtube-make · 7 no-match ·
|
||||
> 10 dropped.**
|
||||
> **SESSION 3b (2026-09-15)**: the KN 429 bug was fixed by Andrew's dedicated session —
|
||||
> see workspace `docs/KARAOKENERDS-DATA-ACCESS.md`; **HARD RULE: never scrape
|
||||
> karaokenerds.com** — use the nightly exports (BigQuery / GCS / divebar-lookup CF /
|
||||
> the now-fixed `/api/bulk/availability`). All outreach community verdicts were
|
||||
> re-verified against the authoritative export + fuzzy divebar-lookup (3 more community
|
||||
> found via title variants incl. Little Simz "Selfish" = our own NOMAD track; Youngblood
|
||||
> community hit is an Acoustic variant so we generate the original).
|
||||
> **DECIDED (Andrew)**: brand-only karaoke versions → GENERATE ANYWAY (annotations
|
||||
> informational). **FINAL: 87 requesters · 29 community (searched; +20 phase-1) ·
|
||||
> 64 torrent-submit · 28 spotify/youtube-make · 7 no-match · 10 dropped.**
|
||||
|
||||
> **SESSION 2 UPDATE (2026-09-13, later the same day)** — the §4 Segment-A pipeline is
|
||||
> BUILT and the full run is DONE (searched 2026-09-13 ~07:00 UTC — sessions expire in
|
||||
> 7 days). **RESULTS: 89 requesters · 20 community (14 + 6 found after typo-fix, 51/139
|
||||
> titles canonicalized) · 28 CONFIDENT auto-submit · 105 no-match (55 of them NEAR
|
||||
> MISSES) · 0 errors.** NEXT STEP: **Andrew reviews `outreach_out/review_packet_v2.md`**,
|
||||
> flips `"approved": true` rows (+ optional `"manual_approve": true` on near-miss songs)
|
||||
> in `actions_v2.json`, then `phase2_execute.py --execute`; emails go out afterwards as
|
||||
> Gmail drafts in ~10-batches (see EMAIL POLICY below).
|
||||
> - `scripts/karaokehunt_outreach/phase1b_audio_search.py` — match-judge canonicalization
|
||||
> → community re-check → search-standalone per song → ported `pick_auto_selection`
|
||||
> tier-1 gate → buckets CONFIDENT / NEAR-MISS / no-match. Resumable via
|
||||
> `outreach_out/audio_search_cache.json`; outputs `actions_v2.json` + `review_packet_v2.md`.
|
||||
> NEAR MISS = lossless non-vinyl torrent, filename matches, <50 seeders — surfaced with
|
||||
> saved session id + best index so Andrew can hand-approve (seeders≥50 proved strict:
|
||||
> even Bohemian Rhapsody's best FLAC had 44).
|
||||
> - `scripts/karaokehunt_outreach/phase2_execute.py` — Phase 2 executor (dry-run by
|
||||
> default, `--execute` to act; idempotent via `phase2_state.json`). KEY LEARNINGS baked
|
||||
> in: (1) admin-created search sessions 403 on create-from-search under an impersonated
|
||||
> user → phase 2 re-searches AS the user and exact-matches the reviewed pick
|
||||
> (provider+target_file), skips (never substitutes) if gone; (2)
|
||||
> `POST /api/users/admin/credits` EMAILS the user — existing gen users (3 of 89,
|
||||
> all 0 credits — listed in the LOCAL PII file `outreach_out/existing_gen_users.txt`,
|
||||
> never committed) are reported not silently granted;
|
||||
> (3) match-judge does NOT reliably fix typos ("Bohemian Rapsody" came back cosmetic
|
||||
> with typo intact) — the filename gate correctly blocks those; (4) create-from-search
|
||||
> deducts 1 credit, so job-submitted users end with 2/3 — OPEN QUESTION for Andrew.
|
||||
> - **EMAIL POLICY (Andrew, verbatim intent)**: he reviews ALL emails before send; send in
|
||||
> batches of ~10 via his Gmail andrew@nomadkaraoke.com. Nothing in phase1b/phase2 sends
|
||||
> email; the send step should create Gmail DRAFTS for him.
|
||||
> - **RELAXED TORRENT RULE (Andrew)**: any FLAC torrent ≥2 seeders is acceptable if the
|
||||
> torrent filename roughly matches — he eyeballs. Review surface = Google Sheet
|
||||
> "KaraokeHunt Outreach — Torrent Review v2 (2026-09-13)" (his Drive; created via
|
||||
> Drive MCP; `scripts/karaokehunt_outreach/torrent_review.py` regenerates the CSV).
|
||||
> Groups: CONFIDENT 28 / A filename-matches 53 / B filename-differs 4 / C no-torrent 45.
|
||||
> He fills the "Review notes" column; map notes back via the `key` column.
|
||||
> - **LOCALIZATION**: no direct country/language data exists anywhere (Firestore/Auth/
|
||||
> Pushbullet empty; Kit geo 23/348 with 1 overlap). Inference from song language +
|
||||
> domains → `outreach_out/language_inference.{json,csv}` (28 non-en of 89; high-conf:
|
||||
> vi ar he ko hi id it fr es pt tl). Plan: bilingual emails for high-confidence rows;
|
||||
> for everyone, footer links to a HOSTED LOCALIZED LETTER page (33 locales via existing
|
||||
> translate.py) = true one-click "read this in your language" (Andrew approved) — build
|
||||
> AFTER email wording is final. NOTE: fj/mr/ne/lt/ka NOT in the 33 locales.
|
||||
|
||||
**Purpose:** hand a fresh Claude session everything needed to finish the KaraokeHunt
|
||||
requester-outreach work. Most of the decommission is DONE; the remaining build is the
|
||||
**Segment A generation pipeline** (find real audio for each requested song, only
|
||||
auto-generate confident FLAC-from-torrent matches, email everyone appropriately).
|
||||
|
||||
Branch / worktree for this work:
|
||||
- Worktree: `/Users/andrew/Projects/nomadkaraoke/karaoke-gen-karaokehunt-outreach`
|
||||
- Branch: `feat/sess-20260913-0106-karaokehunt-outreach`
|
||||
- Resume the original session if useful: `cld --resume e53abc1d-28be-4ae0-9c97-965f2b533470`
|
||||
|
||||
Backlog item: FROG #2 "KaraokeHunt order-email recovery + app redirect" (WIP).
|
||||
Related memory: `project_karaokehunt_gcp_decommission`, `reference_karaokehunt_old_project`.
|
||||
|
||||
---
|
||||
|
||||
## 1. Background (what KaraokeHunt was)
|
||||
|
||||
`KaraokeHunt` was Andrew's earlier mobile app (FlutterFlow + Firebase, GCP project
|
||||
`projectbread-karaokay`). Users could search a karaoke-song catalog and **request** a
|
||||
track to be made. Requesting did essentially nothing except fire a Pushbullet
|
||||
notification to Andrew — **no payment, no datastore, no fulfilment.** It's being fully
|
||||
retired in favour of **Nomad Karaoke / gen.nomadkaraoke.com**, which actually generates
|
||||
karaoke videos. This session drew a line under the KaraokeHunt era and set up outreach to
|
||||
convert its users into gen users.
|
||||
|
||||
---
|
||||
|
||||
## 2. DONE this session
|
||||
|
||||
### Cost / security (old GCP project `projectbread-karaokay`)
|
||||
- **Billing unlinked** (`gcloud billing projects unlink projectbread-karaokay`) → all
|
||||
billing-gated services dead. Root cause of the spend: an unrestricted 2018 API key
|
||||
(Places/Maps) hit by a scraper + 5 `allUsers`-invoker Cloud Functions. **Deleted** the
|
||||
leaked key.
|
||||
- ⚠️ After billing-unlink, GCS object reads + Cloud Functions describe return 403; only
|
||||
Firestore/Auth free-tier + bucket listing survive.
|
||||
|
||||
### Data recovered (all saved to `old-or-other/karaokehunt-users-export-2026-09-09/`)
|
||||
- **User emails**: Firestore `users` (352) ∪ Firebase Auth (351) = **357 deduped**
|
||||
(`all_emails_deduped.csv`, `firestore_users.json`, `firebase_auth_users.json`).
|
||||
(firebase CLI broken on Node v26 → used Identity Toolkit REST `downloadAccount`.)
|
||||
- **Order/request history** = Pushbullet push history (the ONLY record; no datastore).
|
||||
Pulled the full account history (11,599 pushes back to 2016). KaraokeHunt titles:
|
||||
**"KaraokeHunt Order"** (265 pushes 2024-07→2026-09; body = `KaraokeHunt App Request
|
||||
Success! Email: X | Artist: A | Title: T | InputURL: U | Backing Vocals: bool`) and
|
||||
**"KaraokeHunt Registration"** (350, 2023-03→2026-09). Parsed to
|
||||
`karaokehunt_track_requests.csv` (**241 requests / 96 distinct emails**),
|
||||
`karaokehunt_registrations.csv`, `karaokehunt_account_deletions.csv`, raw in
|
||||
`pushbullet_pushes_raw.json`. Pushbullet token is in repo `.envrc` as
|
||||
`PUSHBULLET_TOKEN` (account andrew.d.beveridge@gmail.com). RATE LIMIT is brutal
|
||||
(16384-unit bucket, ~4 units/push, `x-ratelimit-remaining`/`-reset` headers) — pull
|
||||
slowly, foreground; `/tmp/pb_pull4.py` was a cursor-persisting resumable version.
|
||||
- **Play Console reports**: full GCS mirror `gs://pubsite_prod_rev_04078640156148783055/`
|
||||
copied to `play-console-reports/` (4,621 CSVs incl. 528 KaraokeHunt; acquisition,
|
||||
reviews, stats — spans all Andrew's Play apps 2012→2026). Reviews/financials were
|
||||
essentially empty (0 ratings, free app).
|
||||
- **Kit subscribers**: `NomadKaraoke-Kit-Subscribers-All-2026-09-13-6647674.csv`
|
||||
(348 active subs; email/name/created_at/geo/referrer/utm).
|
||||
|
||||
### Stores — both apps REMOVED (Andrew authorized; reversible, NOT deleted)
|
||||
- **iOS** (App Store Connect app `6445938099`, was v1.10.0): Pricing & Availability →
|
||||
**Remove App From Sale** (gone within 24h).
|
||||
- **Android** (Play `com.karaokehunt.karaokehunt`, app id 4974846911887103500, was
|
||||
Production): Test and release → Advanced settings → App availability → **Unpublished**
|
||||
(gone within ~1h). Did NOT click "Delete app" (that's a 7-day permanent delete that
|
||||
loses console data — leave it so analytics stay accessible).
|
||||
- `karaokehunt.com` already 301-redirects (Andrew) and is also the iOS Support/Marketing
|
||||
URL, so it covers both listings' website links.
|
||||
- **Learnings from Play analytics** (tiny scale, directional): US #1 + **Philippines #2**
|
||||
(big karaoke market); steady ~1k organic Play-search impressions/mo at ~22% install
|
||||
conversion but ~5 MAU → *discovery was fine, retention/product was the problem*; the
|
||||
#1 engaged action was **requesting a specific song** — validates gen's value prop.
|
||||
|
||||
### Backlog / memory
|
||||
- Added PRODUCT item **"Native Nomad Karaoke mobile app (iOS + Android)"** (successor to
|
||||
the retired apps; `nomad-mobile` Expo repo is scaffolding only).
|
||||
- **Phase E of the GCP decommission is now UNGATED** — apps are down, so
|
||||
`gcloud projects delete projectbread-karaokay` + close billing acct
|
||||
`0123B3-AAC0D8-4344D3` can happen whenever Andrew wants.
|
||||
|
||||
### Outreach tool built (Phase 1 = analyze/draft only, ZERO spend)
|
||||
Location: `scripts/karaokehunt_outreach/` in this worktree.
|
||||
- `phase1_analyze.py` — **Segment A** (requesters): cleans + dedupes requests, drops
|
||||
Andrew's own email + junk, checks each unique song for an existing community karaoke
|
||||
version via `POST /api/bulk/availability`, buckets (community-link vs generate), and
|
||||
drafts a personalized per-requester email. Output → `outreach_out/review_packet.md` +
|
||||
`outreach_out/actions.json`.
|
||||
- `segment_bc.py` — **Segments B & C** (account + 3 credits + "we've moved" email, NO
|
||||
generation). Output → `outreach_out/review_packet_bc.md` + `outreach_out/actions_bc.json`.
|
||||
|
||||
---
|
||||
|
||||
## 3. The three audience segments (397 people, none double-messaged; priority A>B>C)
|
||||
|
||||
| Seg | Who | Count | Message | Account + 3 credits | Generate a track? |
|
||||
|-----|-----|------:|---------|:---:|:---:|
|
||||
| **A** | KaraokeHunt **requesters** | 94 | Personalized per requested song | ✅ | ✅ (only confident matches — see §4) |
|
||||
| **B** | KaraokeHunt app users, never requested | 266 | "Your KaraokeHunt app is retired → Nomad Karaoke" | ✅ | ❌ |
|
||||
| **C** | Kit-only (brochure/sticker/GitHub/YouTube) | 37 | "You found us online → it's now Nomad Karaoke" | ✅ | ❌ |
|
||||
|
||||
**Decisions locked by Andrew:** 3 free credits to everyone (apology for the delay);
|
||||
Segment-A jobs are **public** (YouTube + community catalog) and **user-owned** (so the
|
||||
requester gets the lyrics-review email); draft everything, **zero spend until Andrew
|
||||
approves each row**; Andrew reviews **every** email before send.
|
||||
|
||||
⚠️ **Segment C overlaps the approved Frog #1 "Launch email to old mailing list"**
|
||||
(discount-code campaign). Reconcile to ONE coordinated offer before sending — don't hit
|
||||
these 37 with two competing emails.
|
||||
|
||||
---
|
||||
|
||||
## 4. WHAT REMAINS — Segment A generation pipeline (the main build)
|
||||
|
||||
Andrew's refined spec (verbatim intent): **dedupe → skip obvious junk → search for
|
||||
existing community versions first → for unique requests that get through, run a
|
||||
flacfetch-remote search (same as karaoke-gen audio search) per song and review results →
|
||||
only auto-submit a job for requests with a CONFIDENT FLAC match from a TORRENT source →
|
||||
for the rest, send an email variant: "we saw you requested '<title>' by '<artist>' but
|
||||
couldn't find a clear match" (still gave you credits, try it yourself here).**
|
||||
|
||||
Current Phase-1 state: dedupe + junk-skip + community check are DONE. Of 153 unique
|
||||
requester songs, **14 have a community version** (link them), **139 don't** (candidates
|
||||
for generation). Many of the 139 are niche or typo'd.
|
||||
|
||||
Steps to build next:
|
||||
1. **(Recommended) match-judge canonicalization pass** on the 139 first — fixes typos
|
||||
(e.g. "bohemian rapsody"→"Bohemian Rhapsody", "Olivia Newton"→"Olivia Newton-John")
|
||||
and will re-classify some as "community version exists," cutting the generate count
|
||||
and cost. Endpoint `POST /catalog/match-judge` / service `backend/services/match_judge/`.
|
||||
2. **flacfetch-remote audio search per song** (the new step). For each of the remaining
|
||||
unique songs, run the same search karaoke-gen uses and capture the verdict:
|
||||
is there a **confident lossless/FLAC match from a torrent source**? Collect results
|
||||
into the review packet so Andrew can eyeball. → SEE §6 for the concrete API/functions.
|
||||
- NOTE: the captured `InputURL` in most requests is NOT a usable YouTube link (users
|
||||
pasted the song title), so direct-URL jobs mostly won't work — audio SEARCH is the
|
||||
right path, which is exactly why Andrew wants this step.
|
||||
3. **Bucket the 139 into**: (a) confident FLAC-from-torrent → auto-submit job; (b) no
|
||||
confident match → "couldn't find a clear match" email variant (no job).
|
||||
4. **Phase 2 — execute (spend happens here), gated on Andrew's per-row approval:**
|
||||
- Create account + grant 3 credits: `POST /api/users/admin/users {email,
|
||||
display_name?, initial_credits:3}` (idempotent; 409 if exists; sends no email).
|
||||
- Submit user-owned job for bucket-(a) songs: `POST /api/admin/users/{email}/impersonate`
|
||||
(admin token) → returns the user's session token → `POST /api/jobs/create-from-url`
|
||||
(or the search-based path) **with that session token** so the job is owned by the
|
||||
requester and THEY get the lyrics-review email. `is_private:false` (public),
|
||||
`backing_preference` = `auto` if captured "Backing Vocals: true" else `clean`.
|
||||
⚠️ With an ADMIN token, `create-from-url` ignores `body.user_email` and owns the job
|
||||
as admin — you MUST impersonate for user-owned jobs.
|
||||
- Send the approved outreach emails (Andrew reviews each first). For Segment A there
|
||||
are now THREE email variants: community-link / job-submitted / couldn't-find-match.
|
||||
5. **Reconcile Segment C** with Frog #1 before sending C.
|
||||
|
||||
---
|
||||
|
||||
## 5. Concrete API reference (verified this session)
|
||||
|
||||
- **Admin token**: `gcloud secrets versions access latest --secret=admin-tokens
|
||||
--project=nomadkaraoke | cut -d',' -f1`. Send as `Authorization: Bearer <t>` or
|
||||
`X-Admin-Token`.
|
||||
- **Prod API base**: `https://api.nomadkaraoke.com` (all routes under `/api`).
|
||||
⚠️ **Cloudflare WAF** bans non-browser User-Agents (error 1010) — send a browser UA
|
||||
header on every request (see `phase1_analyze.py` `BROWSER_UA`).
|
||||
- **Community check**: `POST /api/bulk/availability` `{tracks:[{artist,title}]}` (max 100)
|
||||
→ `{results:[{artist,title,available,brands,brand_count,versions:[{brand,url}]}]}`.
|
||||
Service: `backend/services/karaokenerds_service.py::check_community_versions_batch`.
|
||||
- **Account + credits**: `POST /api/users/admin/users` `{email, initial_credits:3}`
|
||||
(`backend/api/routes/users.py:2060`). Users are in Firestore `gen_users`. Pure credit
|
||||
grant: `POST /api/users/admin/credits`.
|
||||
- **Magic-link login** (users self-serve after we make accounts): public
|
||||
`POST /api/users/auth/magic-link {email}`. Just tell people to sign in at
|
||||
gen.nomadkaraoke.com with their email.
|
||||
- **Impersonate**: `POST /api/admin/users/{email}/impersonate` (`admin.py:2176`) → session
|
||||
token for that user.
|
||||
- **Job submit (URL)**: `POST /api/jobs/create-from-url` (`file_upload.py:1781`), model
|
||||
`CreateJobFromUrlRequest`. Fields: `url` (required), `artist`, `title`, `is_private`,
|
||||
`backing_preference` (`auto`|`clean`|`review`), `review_mode`, `enable_youtube_upload`,
|
||||
`theme_id`, …
|
||||
- **Job submit (search)**: `POST /api/jobs/create-from-search` (`jobs.py:2443`); bulk
|
||||
`POST /api/bulk/submit` (max 100, `bulk.py:277`, has `auto_select_if_lossless`).
|
||||
|
||||
## 6. flacfetch audio search — the "confident FLAC-from-torrent" step (verified)
|
||||
|
||||
This is the new middle step for Segment A. karaoke-gen proxies flacfetch (torrent
|
||||
trackers RED/OPS + YouTube + Spotify).
|
||||
|
||||
**Read-only preview per song (no job, no credit charge):**
|
||||
`POST /api/audio-search/search-standalone` `{artist, title}`
|
||||
(`backend/api/routes/audio_search.py:1015`). Returns `{search_session_id, results[],
|
||||
results_count}`; each result has `is_lossless`, `provider` (RED/OPS/YouTube/Spotify),
|
||||
`seeders`, `quality_data{format,bit_depth,…}`, `target_file`, `match_score`, `release_type`.
|
||||
It only writes a small 7-day-TTL Firestore search-session doc (no job, no charge; use an
|
||||
admin token to bypass the non-admin credit *check*). This is the endpoint to loop over the
|
||||
~139 songs to collect verdicts. ⚠️ Same Cloudflare browser-UA requirement.
|
||||
|
||||
**Confident-FLAC-from-torrent verdict = reuse `pick_auto_selection(results, title)`**
|
||||
(`backend/services/audio_search_service.py:172`). It returns an index to auto-select or
|
||||
`None` to defer. A non-`None` result means the best candidate is category `BEST CHOICE`:
|
||||
`is_lossless == True` **AND** `seeders >= 50` **AND** media != vinyl **AND** filename
|
||||
matches the title (`_check_filename_mismatch`). Because flacfetch computes `is_lossless`
|
||||
as *true* lossless (Spotify-FLAC and YouTube are `False`), `is_lossless==True` already
|
||||
implies a real FLAC torrent source (RED/OPS). Import that function directly, or port the
|
||||
tier-1 rule (it's ~20 lines). **Use `pick_auto_selection`, NOT `select_best`** — the
|
||||
single-job `auto_download` path uses the looser `select_best` quality ranking, which does
|
||||
NOT enforce the confident-torrent-FLAC gate Andrew wants.
|
||||
|
||||
**Then submit (only for confident ones):** `POST /api/jobs/create-from-search` with the
|
||||
`search_session_id` from the preview + the chosen `selection_index` — the preview session
|
||||
is reusable within its 7-day TTL, so preview-now/submit-after-approval works. Do this
|
||||
under the requester's impersonated session token (§4/§5) so the job is user-owned.
|
||||
|
||||
**Direct flacfetch alternative:** `POST {FLACFETCH_API_URL}/search` header `X-API-Key:
|
||||
{FLACFETCH_API_KEY}`, body `{artist, title, exhaustive?}` → `SearchResponse`
|
||||
(`flacfetch/flacfetch/api/routes/search.py:20`, models `flacfetch/flacfetch/api/models.py`).
|
||||
Same fields; but the karaoke-gen `search-standalone` path is less code (gives you the
|
||||
ready `search_session_id`). flacfetch env: `FLACFETCH_API_URL`, `FLACFETCH_API_KEY`
|
||||
(`backend/config.py:239`); flacfetch key is retrievable via `ssh flacup` per memory.
|
||||
|
||||
**Bucketing outcome for the 139:** `pick_auto_selection` returns a pick → bucket (a)
|
||||
auto-submit; returns `None` → bucket (b) "couldn't find a clear match" email variant
|
||||
(no job, but the user still got 3 credits and can try it themselves).
|
||||
|
||||
---
|
||||
|
||||
## 7. File inventory (`old-or-other/karaokehunt-users-export-2026-09-09/`)
|
||||
|
||||
- `all_emails_deduped.csv` (357), `firestore_users.json`, `firebase_auth_users.json`
|
||||
- `karaokehunt_track_requests.csv` (241), `karaokehunt_registrations.csv` (350),
|
||||
`karaokehunt_account_deletions.csv` (20), `pushbullet_pushes_raw.json`
|
||||
- `NomadKaraoke-Kit-Subscribers-All-2026-09-13-6647674.csv` (348)
|
||||
- `play-console-reports/` (4,621 Play report CSVs)
|
||||
- `outreach_out/` — `review_packet.md` + `actions.json` (Segment A);
|
||||
`review_packet_bc.md` + `actions_bc.json` (Segments B & C)
|
||||
|
||||
Tool code: `scripts/karaokehunt_outreach/{phase1_analyze.py, segment_bc.py}` in this worktree.
|
||||
|
||||
> NOTE: the export dir holds real user PII and is under `old-or-other/` (local only —
|
||||
> not committed). Keep it out of git.
|
||||
@@ -0,0 +1,62 @@
|
||||
# Concurrent-load reliability initiative — Andrew's verbatim request (2026-09-17)
|
||||
|
||||
This is the canonical record of Andrew's original prompt for this initiative. Treat it as the
|
||||
spec; refer back to it over time. Do not paraphrase or edit the blockquote.
|
||||
|
||||
> i'd like to make sure karaoke-gen works reliably and quickly even when there are multiple users
|
||||
> using it at the same time. unfortunately right now my confidence in that is pretty low, as i can
|
||||
> reliably cause it to start showing errors such as the general purpose "We're having trouble
|
||||
> reaching our servers
|
||||
>
|
||||
> This is usually temporary — please try again in a couple of minutes.
|
||||
>
|
||||
> Any karaoke videos currently being created are unaffected and will keep processing." or the more
|
||||
> specific "Failed to load lyrics - The server is temporarily unavailable. Please try again in a
|
||||
> moment." when loading a lyrics review page, just by opening 10 separate karaoke jobs' lyrics
|
||||
> review URLs simultaneously in 10 separate browser tabs. usually 1 or 2 load then the other 8 fail
|
||||
> with one of those errors.
|
||||
> Please review our architecture and perhaps try reproducing this (you can open a playwright
|
||||
> browser, make sure i'm logged into karaoke-gen as admin, then open the lyrics review pages for 10
|
||||
> jobs currently in-review (there's plenty right now due to another initiative) in separate tabs -
|
||||
> you should see some of them load fine, others show the reconnecting error, likely some
|
||||
> timeout/fail to load completely.
|
||||
> Also I see the "reconnecting" warning message a bit too frequently still, e.g. when the preview
|
||||
> video is loading: [Image #2] so I think we need to tune that and probably log (server side,
|
||||
> persistently, with useful metadata) any time that orange warning banner or the more serious
|
||||
> "server is temporarily unavailable" version is shown to any user, so later on we can review those
|
||||
> logs to understand how frequently users are experiencing that and make efforts to improve the
|
||||
> underlying architecture and/or tune the warning banner notifications to prevent users from having
|
||||
> a poor user experience.
|
||||
> Also I have my default lyrics review mode set to waveforms and i usually find when i first load
|
||||
> the lyrics review page the waveforms don't load yet: [Image #3], i have to wait a while (eg. 1+
|
||||
> minutes) for them to eventually load: [Image #4]
|
||||
> I'm not sure if all of these are same class of problem but i definitely want all of them to be
|
||||
> addressed systematically and thoroughly after brainstorming and investigation, so please record
|
||||
> this verbatim first as a record and refer back to it over time
|
||||
|
||||
**Image references** (attached to the original message):
|
||||
- **Image #2** — the orange "We're having trouble reaching our servers" banner shown overlapping
|
||||
the review page while the Preview Video modal shows "Encoding preview video…" spinner.
|
||||
- **Image #3** — Synced Lyrics panel in **Waveforms** mode right after page load: word bars render
|
||||
but the waveform strips under them are missing/empty.
|
||||
- **Image #4** — the same panel after waiting (~1+ min): waveform strips now rendered under every
|
||||
segment row.
|
||||
|
||||
## Distilled problem statements (agent summary — the blockquote above is the spec)
|
||||
|
||||
1. **Concurrent review-page loads fail** — opening ~10 in-review lyrics review URLs in parallel
|
||||
tabs as admin: 1–2 load, the rest show the generic "trouble reaching our servers" banner or
|
||||
"Failed to load lyrics - The server is temporarily unavailable."
|
||||
2. **Orange "reconnecting" banner shows too often** — e.g. during preview-video encoding; needs
|
||||
tuning so it reflects genuine outage, not slow/heavy in-flight requests.
|
||||
3. **No persistent telemetry for user-visible degradation** — want server-side, persistent,
|
||||
metadata-rich logging every time the orange banner or the more serious "temporarily
|
||||
unavailable" state is shown to any user, so frequency can be reviewed later.
|
||||
4. **Waveforms review mode loads without waveforms** — first paint has no waveform strips; they
|
||||
appear only after ~1+ minutes.
|
||||
|
||||
## Session trail
|
||||
|
||||
- 2026-09-17: initiative started; worktree `karaoke-gen-concurrent-review-reliability`
|
||||
(branch `feat/sess-20260917-2329-concurrent-review-reliability`). Investigation + repro attempt
|
||||
this session; findings and plan to follow in this doc's siblings.
|
||||
@@ -0,0 +1,81 @@
|
||||
# Requests Board — Admin History View, Public "Recently Made" List, & Publish-Transition Fix
|
||||
|
||||
Date: 2026-09-17
|
||||
Branch: `feat/sess-20260916-2353-requests-board-history`
|
||||
|
||||
## Context / discovery
|
||||
|
||||
Andrew asked whether we can see past community requests and whether our first real user
|
||||
successfully got a video. Investigation (Firestore + `email_log`):
|
||||
|
||||
- **Only 2 requests ever.** Both stuck at `status == "in_progress"`:
|
||||
- Admin go-live test request — Sep 3 (submitted by `admin@`, job since deleted).
|
||||
- A real community user's request — **Sep 15** (first genuine board user; PII kept out of this
|
||||
public repo — see the private session record / Firestore for specifics).
|
||||
- **First real user was fully served.** The job completed, rendered all finals, and published to
|
||||
YouTube (brand assigned, GDrive + Dropbox). `email_log` confirms magic-link → `action_reminder`
|
||||
(lyrics review) → `job_completion` emails all sent to the requester; he emailed a thank-you. ✅
|
||||
(He was notified via the **standard job-owner** path, not the community fan-out.)
|
||||
|
||||
### Root-cause bug found
|
||||
The community publish transition (`song_request_service.mark_published` + voter fan-out in
|
||||
`_notify_community_voters`) is invoked **only** inside `backend/workers/youtube_queue_processor.py`
|
||||
(the quota-managed `youtube_upload_queue` path). The first real user's job got its YouTube URL via
|
||||
the **direct distribution path** during finalization (`processing_metadata.distribution.youtube_video_url`),
|
||||
which never enqueues to `youtube_upload_queue`. Result: `_notify_community_voters` never ran, so the
|
||||
request stayed `in_progress`, `youtube_url` stayed empty, `voters_notified` stayed `False`.
|
||||
|
||||
Impact today is minor (he was the only voter, and got the standard completion email anyway), but:
|
||||
- The board's public **"Recently made"** section (`frontend/app/[locale]/requests/client.tsx:317`,
|
||||
driven by `list_published()` = `status == "published"`) will **never populate** while this bug
|
||||
exists — so it looks empty/broken.
|
||||
- Any request with *other* up-voters would silently fail to send the "your track is live" fan-out.
|
||||
|
||||
## Scope (agreed with Andrew)
|
||||
|
||||
1. **Admin history view** of ALL community requests (his explicit ask).
|
||||
2. **Public "recently made" list** on the board — already coded, needs the publish transition fixed
|
||||
+ a backfill to light up.
|
||||
3. **Fix the publish-transition bug** (prerequisite for #2; correctness for all future picks).
|
||||
|
||||
## Plan
|
||||
|
||||
### Part A — Publish transition fix (backend)
|
||||
- Extract the "job just got a YouTube URL → advance its community request" logic into a single
|
||||
reusable helper (e.g. `song_request_service.on_job_published(job_id, youtube_url)` or a shared
|
||||
`_notify_community_voters` callable) that: looks up the request by `state_data.community_request_id`,
|
||||
calls `mark_published`, and fans out voter emails (retry-safe via existing `notified_voters` /
|
||||
`voters_notified` flags).
|
||||
- Call it from **both** publish paths:
|
||||
- existing `youtube_queue_processor` site (line ~94) — unchanged behavior;
|
||||
- the **direct distribution finalize path** — add the hook where `distribution.youtube_video_url`
|
||||
is set. Locate that write and call the shared helper there (idempotent, so double-firing is safe).
|
||||
- Keep it idempotent so re-runs / both-paths-firing don't double-email.
|
||||
|
||||
### Part B — Backfill the first real request
|
||||
- Run the reconcile endpoint (Part below) in prod to mark the stuck request `published` with its
|
||||
YouTube URL, making it appear in the board's "Recently made" list. In general, reconcile also
|
||||
retries missing community "track is live" emails for any un-notified **non-owner** up-voters via
|
||||
`notify_community_publish()`. For *this specific* request no extra email is sent — its sole voter
|
||||
is the owner, who was already notified via the standard job-completion email.
|
||||
|
||||
### Part C — Admin history view (backend + frontend)
|
||||
- **Backend:** `GET /api/admin/community-requests` (admin-auth) returning ALL `song_requests`,
|
||||
every status, with: artist/title, status, `submitted_by`, `owner_email`, `vote_count`, `job_id`,
|
||||
`youtube_url`, `created_at`, `picked_at`, `review_state`. Reuse existing admin auth + response
|
||||
model patterns from `admin.py` (see `community-reviews`).
|
||||
- **Frontend:** new admin page `frontend/app/admin/community-requests/` (English-only admin surface;
|
||||
no `[locale]` counterpart) — a table with status badges, requester, link to the job review page
|
||||
(`/app/jobs#/{job_id}/review`), and YouTube link. Add nav entry alongside `community-reviews`.
|
||||
|
||||
### Testing
|
||||
- Backend unit: shared helper fires from the distribution path; idempotency; request lookup by
|
||||
`state_data.community_request_id`; admin endpoint returns all statuses + is admin-gated.
|
||||
- Frontend: admin page renders rows, links resolve.
|
||||
- Follow `docs/TESTING.md`; run `make test`.
|
||||
|
||||
## Open questions
|
||||
- Exact location of the direct-distribution YouTube-URL write (need to grep the finalize/distribute
|
||||
worker) — confirm during implementation.
|
||||
- Whether to also surface the admin history inside the existing `/admin/community-reviews` page vs a
|
||||
new page. Leaning new page for clarity.
|
||||
@@ -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,186 @@
|
||||
# Lyrics Review "Waveforms" mode — implementation plan
|
||||
|
||||
**Date:** 2026-09-17
|
||||
**Repo:** karaoke-gen (frontend)
|
||||
**Branch:** feat/sess-20260917-0028-waveforms-review-mode
|
||||
|
||||
## Problem
|
||||
|
||||
In the lyrics review UI, the `Synced Lyrics` panel has a `Simple` / `Advanced` toggle.
|
||||
Advanced draws each line's words as flex-weighted pills (widths ∝ duration) but shows **no
|
||||
vocal waveform**. To actually tell whether a word's timing is well-aligned, the reviewer has
|
||||
to open the **Edit Segment** modal for nearly every line — the only place the vocal waveform is
|
||||
visible. That's the friction.
|
||||
|
||||
**Motivating case** (from the modal): a segment `No looking back` where the `looking` bar runs
|
||||
to ~142.4s but the vocal energy clearly dies at ~142.3s with a visible gap after — an over-long
|
||||
trailing word only catchable with the waveform. The goal: spot that at a glance for **every**
|
||||
segment, without opening a modal per line.
|
||||
|
||||
## Solution
|
||||
|
||||
Add a third view mode, **Waveforms**, to the `Synced Lyrics` toggle. It renders a compact copy
|
||||
of the Edit Segment timeline **inline for every segment** — resizable/draggable word bars over
|
||||
the segment's vocal waveform, with the 1s buffer padding + start/end boundary lines + greyed
|
||||
neighbouring-segment words, exactly as the modal does — minus the per-row time ruler.
|
||||
|
||||
### Decisions (confirmed with Andrew)
|
||||
|
||||
1. **Edit scope:** drag/resize word bars inline → persists **timing** directly. Text edits and
|
||||
add/split/merge/delete-word still open the existing Edit modal (via the segment number or an
|
||||
edit affordance on the row). Reuses `TimelineEditor` + the segment-commit path as-is.
|
||||
2. **Time scale:** fit-to-width per segment — each row maps `[start-1s .. end+1s]` to full
|
||||
container width, identical to the modal. No horizontal scroll.
|
||||
3. **Row detail:** reproduce the modal timeline exactly — buffer padding + dashed boundary
|
||||
lines + greyed read-only neighbour words. **Omit** the per-row ruler (too tall for a dense
|
||||
list; the whole point is compact scannability).
|
||||
|
||||
## Why this is low-risk
|
||||
|
||||
- The waveform component already renders from a **compact peak envelope loaded once for the
|
||||
whole track** (`AudioData`, ~hundreds of KB) and shared via `VocalsAudioDataLoaderContext`.
|
||||
Each segment waveform is just a time-slice into that shared array — cheap to render N of them.
|
||||
- `TimelineEditor.tsx` already implements everything visual: word bars, resize handles, drag,
|
||||
collision checks, `TIMELINE_PAD_SECONDS` padding, boundary lines, greyed `contextWords`,
|
||||
playback cursor, click-to-play scrub. We reuse it, not rebuild it.
|
||||
- `TranscriptionView` already lives **inside** `<VocalsAudioDataLoader>` in `LyricsAnalyzer`,
|
||||
so the audio context is in scope for inline waveforms with no plumbing changes.
|
||||
|
||||
## Key components (current)
|
||||
|
||||
- `components/lyrics-review/TranscriptionView.tsx` — renders the segment list; owns the
|
||||
`Simple`/`Advanced` `ToggleGroup`. **← add Waveforms branch + 3rd toggle item.**
|
||||
- `components/lyrics-review/TimelineEditor.tsx` — the reusable timeline (bars + waveform +
|
||||
padding + context). **← add `showRuler?` + `onCommit?` props.**
|
||||
- `components/lyrics-review/WaveformVisualizer.tsx` — canvas renderer, unchanged.
|
||||
- `components/lyrics-review/VocalsAudioDataLoader.tsx` — shared audio context, unchanged.
|
||||
- `components/lyrics-review/LyricsAnalyzer.tsx` — container. Holds `advancedMode` (localStorage),
|
||||
`handleUpdateSegment`, `handlePlaySegment`, `editContextWords`, opens `EditModal`.
|
||||
**← migrate view-mode state; add inline-commit + per-segment context; wire new props.**
|
||||
- `components/lyrics-review/modals/EditModal.tsx` — reference for the local-copy → commit
|
||||
pattern (its `updateSegment` recomputes seg `start_time`/`end_time` from words).
|
||||
|
||||
## Implementation
|
||||
|
||||
### 1. New component: `WaveformSegmentRow.tsx`
|
||||
|
||||
Per-segment inline editor. Wraps `TimelineEditor`, owns the drag-in-progress local state, and
|
||||
commits to history **only on drag end** (never per-mousemove — that would flood undo history and
|
||||
re-render the whole list).
|
||||
|
||||
Props:
|
||||
```
|
||||
segment: LyricsSegment
|
||||
segmentIndex: number
|
||||
contextWords: Word[] // neighbours within the padded window (see §4)
|
||||
currentTime?: number
|
||||
onCommit: (index, updatedSegment) => void // fires on drag end
|
||||
onPlaySegment?: (time) => void
|
||||
onOpenEditModal: (index) => void // segment #/✎ → existing modal
|
||||
audioReady: boolean
|
||||
```
|
||||
|
||||
Behaviour:
|
||||
- Local `words` state, seeded from `segment.words`; re-synced via `useEffect` when the segment's
|
||||
words/timings change externally (undo/redo, modal save, auto-correct).
|
||||
- `handleWordUpdate(i, updates)` → update local `words` only (this row re-renders, not the list).
|
||||
- `handleCommit()` (drag end) → recompute segment `start_time`/`end_time` from `words`
|
||||
(mirror `EditModal.updateSegment`), call `onCommit(segmentIndex, updatedSegment)`.
|
||||
- Row chrome: segment index (click → `onOpenEditModal`) + play button + edit ✎ icon, matching
|
||||
the density of the current Advanced row's left controls.
|
||||
- Renders `<TimelineEditor words={words} contextWords={contextWords} showRuler={false}
|
||||
onWordUpdate={handleWordUpdate} onCommit={handleCommit} onPlaySegment={...}
|
||||
currentTime={currentTime} />`.
|
||||
|
||||
### 2. `TimelineEditor.tsx` changes (additive, backward-compatible)
|
||||
|
||||
- Add `showRuler?: boolean` (default `true`). When `false`: skip the 40px ruler band; keep a
|
||||
thin click-to-play strip (or move `handleTimelineClick` onto the waveform wrapper) so
|
||||
click-to-scrub still works. Total row height shrinks to ~bars(30) + waveform(35).
|
||||
- Add `onCommit?: () => void`. Call it in `handleMouseUp` **iff a drag was active**
|
||||
(`dragState != null`) so the row can persist on release. Modal usage omits it → no change.
|
||||
- Everything else (padding overlays, boundary lines, contextWords, collision, cursor) unchanged
|
||||
→ "exactly as the modal works."
|
||||
|
||||
### 3. View-mode state migration (`LyricsAnalyzer.tsx`)
|
||||
|
||||
- Replace the `advancedMode: boolean` (localStorage `lyricsReviewAdvancedMode`) with
|
||||
`transcriptionViewMode: 'simple' | 'advanced' | 'waveforms'` (localStorage
|
||||
`lyricsReviewViewMode`).
|
||||
- Migration: if new key absent, read old boolean (`'true'` → `'advanced'`, else `'simple'`).
|
||||
- Pass `viewMode` + `onViewModeChange` down to `TranscriptionView` (keep deriving
|
||||
`advancedMode = viewMode === 'advanced'` internally where the flex-pill layout is used, to
|
||||
minimise churn in `HighlightedText` wiring).
|
||||
|
||||
### 4. Per-segment context words
|
||||
|
||||
The modal computes `editContextWords` for the single open segment (±2s neighbours). Waveforms
|
||||
mode needs this for **every** row. Precompute once per data change to stay O(n):
|
||||
- Segments are time-ordered; for row `i`, gather timed words from the neighbouring segments
|
||||
whose `[start,end]` intersect `[seg.start-1s, seg.end+1s]` (just prev/next segment in
|
||||
practice). Return a `Map<segmentIndex, Word[]>` or a small helper called per row.
|
||||
- Apply `timingOffsetMs` the same way `editContextWords` does.
|
||||
|
||||
### 5. Inline commit handler (`LyricsAnalyzer.tsx`)
|
||||
|
||||
Add `handleCommitSegmentTiming(index, updatedSegment)`:
|
||||
- Replace `corrected_segments[index]` and `updateDataWithHistory(newData, 'adjust word timing')`.
|
||||
- Does **not** depend on `editModalSegment` (unlike `handleUpdateSegment`).
|
||||
- No edit-log entry needed for pure timing (the modal path only logs text changes today — keep
|
||||
parity).
|
||||
|
||||
### 6. `TranscriptionView.tsx` changes
|
||||
|
||||
- Add third `ToggleGroupItem value="waveforms"` (icon: `AudioWaveform`/`Activity` from lucide)
|
||||
with label `t('waveforms')`.
|
||||
- When `viewMode === 'waveforms'`: map segments → `<WaveformSegmentRow>` instead of
|
||||
`HighlightedText` rows. Pass `onCommit`, `onOpenEditModal` (→ parent opens `EditModal`),
|
||||
`onPlaySegment`, `currentTime`, and the per-segment `contextWords`.
|
||||
- Simple/Advanced branches unchanged.
|
||||
|
||||
### 7. i18n
|
||||
|
||||
- Add `lyricsReview.transcription.waveforms` (+ any row tooltips, e.g. edit ✎) to
|
||||
`frontend/messages/en.json`, then:
|
||||
`python frontend/scripts/translate.py --messages-dir frontend/messages --target all`
|
||||
- CI fails if any of the 33 locales are missing keys.
|
||||
|
||||
## Performance notes
|
||||
|
||||
- N canvases (one per segment; typically 40–90). Each `WaveformVisualizer` uses a
|
||||
`ResizeObserver` and slices only its own time window — bounded work. Expected fine.
|
||||
- Only the actively-dragged row re-renders during a drag (local state), so dragging is smooth
|
||||
regardless of list length.
|
||||
- **If** long lists lag on lower-end devices, add windowing (render waveforms only for rows near
|
||||
the viewport) as a follow-up — not in scope for v1.
|
||||
- Mobile: touch drag on small bars is fiddly; mode remains functional (grid collapses to 1 col).
|
||||
Primary use is desktop review. No blocker.
|
||||
|
||||
## Testing strategy (per docs/TESTING.md)
|
||||
|
||||
- **Unit (Jest):**
|
||||
- `WaveformSegmentRow`: local-state seeding + re-sync on external segment change; commit on
|
||||
drag end recomputes segment `start_time`/`end_time` from words; does not commit mid-drag.
|
||||
- Per-segment context-words helper: returns neighbours intersecting the padded window; honours
|
||||
`timingOffsetMs`.
|
||||
- View-mode localStorage migration (old boolean → new enum).
|
||||
- **Component:** `TranscriptionView` renders N waveform rows in `waveforms` mode; clicking the
|
||||
segment number invokes `onOpenEditModal`; Simple/Advanced unaffected.
|
||||
- **`TimelineEditor`:** existing tests still pass with default `showRuler`; new test for
|
||||
`showRuler={false}` (no ruler, click-to-play still fires) and `onCommit` firing once on
|
||||
mouseup after a drag.
|
||||
- **E2E (`frontend/e2e/regression/lyrics-review.spec.ts` or a new spec):** switch to Waveforms
|
||||
mode → assert ≥1 `<canvas>` waveform present per segment; drag a word bar → assert timing
|
||||
persisted (data change / undo enabled); open Edit modal from a row.
|
||||
- **Production E2E:** extend an existing review prod spec to toggle Waveforms and assert render.
|
||||
|
||||
## Rollout
|
||||
|
||||
- Version bump `pyproject.toml` (frontend-affecting change ships via the wheel-packaged frontend).
|
||||
- No backend / infra changes. No new API surface.
|
||||
|
||||
## Out of scope (v1)
|
||||
|
||||
- Tap-To-Sync inline (stays in modal).
|
||||
- Inline add/split/merge/delete-word and text editing (stays in modal).
|
||||
- Global fixed px/second scale + row virtualization (possible follow-ups).
|
||||
@@ -0,0 +1,126 @@
|
||||
# Concurrent-load reliability: investigation findings + systematic plan — 2026-09-18
|
||||
|
||||
Spec: `docs/archive/2026-09-17-concurrent-review-reliability-verbatim-record.md` (Andrew's
|
||||
verbatim prompt — the four problem statements below map 1:1 to it).
|
||||
|
||||
## Reproduction (prod, 2026-09-18 ~03:35Z) — CONFIRMED
|
||||
|
||||
Method: `frontend/test-concurrency.local.sh` (gitignored) — 10 simulated review tabs, each
|
||||
firing the page's real GET trio (`correction-data`, `waveform-data`, `audio/vocals`) with
|
||||
per-job `review_token`s pulled from Firestore via ADC.
|
||||
|
||||
**Baseline (sequential, one job):** ping 0.31s · correction-data 0.83s · waveform-data 1.35s ·
|
||||
instrumental-urls 0.47s · instrumental-analysis **13.7s** · audio/vocals **27.7s** (full 4.3MB
|
||||
body; Range header ignored — 200 not 206).
|
||||
|
||||
**Burst (10 tabs in parallel):**
|
||||
- 9 of 30 requests → **HTTP 500** (7× audio/vocals + 2× correction-data), hitting 8 of the 10 tabs
|
||||
- surviving requests took **44–72s** (correction-data up to 70.6s vs 0.83s baseline)
|
||||
- Cloud Run logged **9× "The request was aborted because there was no available instance"**
|
||||
at 03:35:32Z — the instance was so wedged that Cloud Run couldn't dispatch to it, despite
|
||||
only ~30 in-flight requests vs `--concurrency 80`.
|
||||
- Frontend consequences (from code, `frontend/lib/api.ts`): GETs have a 45s hard timeout + 3
|
||||
attempts, then throw `BackendUnavailableError` → **"The server is temporarily unavailable.
|
||||
Please try again in a moment."** under "Failed to load lyrics". Tracked GETs stalled ≥10s /
|
||||
≥20s + a failed 4s `/api/health` probe → the orange **"We're having trouble reaching our
|
||||
servers"** banner. Both exactly match Andrew's 1–2-tabs-load-8-fail observation.
|
||||
|
||||
**Ruled out:** Cloudflare edge rate limiting (50 req/10s/IP is live in prod — `edge:enabled`,
|
||||
`proxyProdApi=true` — but 60 parallel cheap pings all returned 200 fast; the rule never
|
||||
tripped, and cheap-endpoint concurrency is fine). The meltdown is entirely origin-side and
|
||||
entirely caused by the *heavy* endpoints.
|
||||
|
||||
## Root causes (evidence-backed)
|
||||
|
||||
**RC1 — `/waveform-data` does CPU-bound audio decoding ON the event loop, uncached.**
|
||||
`backend/api/routes/review.py:2107` calls `AudioAnalysisService().get_waveform_data()`
|
||||
synchronously in the async handler: downloads the **raw backing-vocals FLAC** (tens of MB) from
|
||||
GCS, decodes it fully via pydub→ffmpeg, then runs a 1000-iteration pure-Python RMS loop
|
||||
(`karaoke_gen/instrumental_review/waveform.py:163-210`). A GCS waveform cache EXISTS
|
||||
(`audio_analysis_service.py:246-315`) but is only wired to the audio-editor `input-audio-info`
|
||||
path — NOT to `/waveform-data`. Every review load recomputes from scratch, and while it runs,
|
||||
**every other request on that instance is frozen** (single uvicorn process, single event loop,
|
||||
no `--workers` — `backend/Dockerfile:50`).
|
||||
|
||||
**RC2 — blocking Firestore/GCS calls on the event loop in every review endpoint.**
|
||||
`get_job()` (sync Firestore read) is called directly in async handlers; `correction-data` also
|
||||
does sync `file_exists` + `download_json` (large corrections JSON) + a Firestore write
|
||||
(`transition_to_state`). Under contention these serialize behind RC1.
|
||||
|
||||
**RC3 — multi-MB audio byte-serving through the Python proxy, slow and uncached.**
|
||||
`/audio/vocals` streams 3–8MB per tab at ~700KB/s observed (5–28s each), re-downloading from
|
||||
GCS every request (the LRU byte cache `_review_audio_cache` cap 16 covers only
|
||||
`/instrumental-audio/{option}`). No Range support (ignores the header, returns 200 full-body).
|
||||
Ten tabs = 30–80MB pushed through one 2-vCPU throttled container.
|
||||
|
||||
**RC4 — Cloud Run shape concentrates the burst on one instance.**
|
||||
`--concurrency 80 --min-instances 1 --max-instances 20 --cpu 2 --cpu-throttling` (ci.yml
|
||||
~:1979-1998; service is deployed via gcloud in CI, NOT Pulumi). 10 tabs ≈ 30–50 requests ≪ 80,
|
||||
so the autoscaler sees no reason to scale out; everything lands on the one warm instance until
|
||||
it's wedged enough to abort dispatches ("no available instance").
|
||||
|
||||
**RC5 — Waveforms-mode strips: client decodes the whole vocals stem, with silent give-up.**
|
||||
The per-segment strips do NOT use `/waveform-data`; `VocalsAudioDataLoader.tsx` raw-fetches the
|
||||
full `/audio/vocals` OGG, decodes with WebAudio, computes peaks client-side
|
||||
(`lib/audio-data.ts`, 400 peaks/s). On HTTP 202 (stem not ready) it polls every **15s up to 40
|
||||
tries**; on ANY other error (e.g. the burst 500s, or a timeout) it **gives up silently** —
|
||||
strips never appear until a manual reload. No loading indicator exists (TimelineEditor renders
|
||||
blank space). First-paint delay = slow 3–8MB proxy download + decode, or a swallowed error →
|
||||
matches "wait 1+ minutes" (Image #3/#4).
|
||||
|
||||
**RC6 — the orange banner fires "correctly" but the origin is too easy to stall, and there's
|
||||
ZERO telemetry.** Banner logic (`lib/backend-status.ts`): oldest tracked in-flight GET ≥10s →
|
||||
reconnecting, ≥20s → unavailable, gated on a 4s `/api/health` probe failing. During preview
|
||||
encoding (Image #2) the GCE-worker-with-LOCAL-FALLBACK path can run ffmpeg on the API instance
|
||||
itself; on a 2-vCPU CPU-throttled container that stalls the status polls AND the health probe →
|
||||
banner, with no real outage. Nothing is logged anywhere when the banner or the
|
||||
"temporarily unavailable" error is shown (confirmed: no gtag events, crash-reporter never
|
||||
invoked for caught errors) — Andrew has no visibility into user-experienced frequency.
|
||||
|
||||
## Plan (phased; each phase independently shippable)
|
||||
|
||||
### Phase 1 — stop the bleeding server-side (highest leverage, code-only) — ✅ IMPLEMENTED (this branch, v0.230.0), plus the Phase-4 waveform silent-give-up retry fix
|
||||
1. `/waveform-data`: wire the EXISTING GCS waveform cache; compute via `asyncio.to_thread`;
|
||||
precompute in `screens_worker` alongside `prepare_review_audio_for_job` (OGG pre-warm
|
||||
already happens there); decode from the small transcoded OGG, not the raw FLAC.
|
||||
2. Wrap blocking Firestore/GCS calls in review-path handlers with `to_thread` (helper:
|
||||
`run_sync()`), starting with `get_job`, `download_json`, `file_exists`,
|
||||
`transition_to_state`.
|
||||
3. Audio byte-serving: honor Range (206) so browsers/audio elements fetch incrementally;
|
||||
extend the LRU byte cache to vocals + input audio; add `Cache-Control: private, immutable,
|
||||
max-age=…` so repeat loads hit browser cache.
|
||||
4. Admission control for CPU-heavy review endpoints (small semaphore + fast 503-with-Retry-After
|
||||
rather than wedging the loop) — mirrors the v0.228.1 signing-pool pattern.
|
||||
|
||||
### Phase 2 — Cloud Run shape (deploy-config)
|
||||
5. Lower `--concurrency` for karaoke-backend (e.g. 12–16) so bursts trigger scale-out; consider
|
||||
`--no-cpu-throttling`; consider `--workers 2` (check in-memory cache/locks assumptions);
|
||||
evaluate uvloop. Revisit preview-video LOCAL fallback running ffmpeg on the API instance —
|
||||
route to the encoding pool or cap it.
|
||||
|
||||
### Phase 3 — degradation telemetry (Andrew's explicit ask)
|
||||
6. `POST /api/client-events` (batched, lightweight, auth-optional): frontend reports
|
||||
`banner_reconnecting`, `banner_unavailable`, `lyrics_load_failed`, `waveform_slow` (>Xs),
|
||||
with metadata (job_id, user/session, page, oldest-stall age, probe result, http status,
|
||||
locale, UA). Backend emits structured Cloud Logging events (`jsonPayload.event=...`) —
|
||||
persistent, queryable via Log Analytics, zero new infra; optional log-based metric + alert.
|
||||
|
||||
### Phase 4 — banner tuning + Waveforms UX (frontend)
|
||||
7. Banner: require 2 consecutive probe failures (or longer probe timeout) before `unavailable`;
|
||||
exempt/raise thresholds for known-slow byte GETs; show `reconnecting` pill only after a
|
||||
probe failure too.
|
||||
8. Waveforms mode: loading indicator on the strip area; retry-with-backoff on transient errors
|
||||
instead of silent give-up; consider serving a precomputed vocals peak JSON (from Phase 1's
|
||||
cached waveform work) so strips paint instantly without a client-side full decode.
|
||||
|
||||
### Phase 5 — regression guard
|
||||
9. Formalize `test-concurrency.local.sh` into a repeatable load-test script (checked in) + a
|
||||
Playwright multi-tab prod E2E; record before/after numbers in this doc.
|
||||
|
||||
## Open questions for Andrew
|
||||
- OK to lower Cloud Run concurrency (cost: more instances under load)? min-instances stays 1.
|
||||
- Telemetry sink: structured Cloud Logging (proposed, free-ish) vs Firestore collection?
|
||||
|
||||
## Verification numbers to beat (from this session's repro)
|
||||
- Burst 10-tab: 0 failed requests (was 9/30); worst correction-data < 5s (was 70.6s);
|
||||
no "no available instance" aborts; waveform strips present on first paint for a warm job.
|
||||
@@ -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,83 @@
|
||||
# Lyrics Review "Waveforms" mode + preview backing-vocals visibility — 2026-09-17
|
||||
|
||||
**Project:** karaoke-gen (frontend) **Branch/commit:** merged to `main` via PR #1010 (squash `912ca37a`), v0.227.0 **Status:** done / shipped + prod-verified
|
||||
|
||||
## Summary
|
||||
Added a third Synced Lyrics review view, **Waveforms**, that renders a compact inline copy of the
|
||||
Edit Segment timeline for every segment — so a reviewer can spot mis-timed words (e.g. an over-long
|
||||
trailing word whose vocal energy died earlier) at a glance without opening a modal per line. Also
|
||||
changed the preview modal so the **backing-vocals waveform is always shown** (even when "Clean
|
||||
instrumental" is selected), so backing vocals are never discarded sight-unseen. Shipped to prod and
|
||||
verified live on a real in-review job.
|
||||
|
||||
## What changed
|
||||
Frontend only (`karaoke-gen/frontend`). Key files:
|
||||
- **New `components/lyrics-review/WaveformSegmentRow.tsx`** — per-segment inline editor wrapping the
|
||||
existing `TimelineEditor`. Holds a local `words` copy during a drag; commits on drag release.
|
||||
- **`TimelineEditor.tsx`** — new opt-in props: `showRuler`, `compact`, `onCommit`, `onWordClick`,
|
||||
`wordDecorations`. Compact mode: no card chrome, tight heights (20px bars + 14px waveform, no gap),
|
||||
waveform doubles as the click-to-play target. Click-vs-drag via a 4px threshold (`DRAG_THRESHOLD_PX`).
|
||||
- **`TranscriptionView.tsx`** — 3-value view toggle (Simple/Advanced/**Waveforms**); renders
|
||||
`WaveformSegmentRow`s; builds per-segment context words + colour decorations (memoised).
|
||||
- **`LyricsAnalyzer.tsx`** — view-mode state migrated from boolean `advancedMode` →
|
||||
`transcriptionViewMode` enum (localStorage `lyricsReviewViewMode`, migrating old
|
||||
`lyricsReviewAdvancedMode`); added `handleCommitSegmentTiming` (un-applies timing offset before
|
||||
storing) + `handleEditSegmentFromWaveforms`; Advanced/Waveforms now size the Reference column to its
|
||||
longest line (`flex-none w-max max-w-[46%]`) so Synced gets the freed width.
|
||||
- **New utils** (all unit-tested): `lib/lyrics-review/utils/contextWords.ts`, `segmentTiming.ts`
|
||||
(`recomputeSegmentFromWords`, `resolveInitialViewMode`), `wordDecorations.ts` (`classifyWord`,
|
||||
`barClassForWord` using the **exact `HIGHLIGHT_CLASSES` tints**, `buildSegmentDecorations`).
|
||||
- **`BackingVocalsWaveform.tsx` + `modals/ReviewChangesModal.tsx`** — waveform always shown when a
|
||||
playable backing stem exists; selection-aware `kept` prop drives wording.
|
||||
- **`Header.tsx`** — fixed pre-existing `FORMATTING_ERROR`: `autoCorrectedDesc` rendered without its
|
||||
`count` param (surfaced on jobs with ≥1 auto-correction).
|
||||
- **i18n** — new keys (`waveforms`, `editSegment`, `untimedSegment`, `backingVocalsWaveformKept/Removed`),
|
||||
reworded `autoInstrumentalClean/CleanChosen`, removed `backingVocalsWaveformHint`; translated all 33
|
||||
locales; pruned the stale key from every locale; parity validated.
|
||||
- **New tests** — `WaveformSegmentRow`, `contextWords`, `segmentTiming`, `wordDecorations`; updated
|
||||
`ReviewChangesModal`. Full frontend suite: 104 suites / 1283 tests green.
|
||||
- **`scripts/list-review-jobs.py`** — lists in-review jobs (Firestore) with ready-to-open local review URLs.
|
||||
- Docs: `docs/archive/2026-09-17-waveforms-review-mode-plan.md`; LESSONS-LEARNED entry.
|
||||
|
||||
## Decisions & rationale
|
||||
- **Reuse `TimelineEditor` verbatim** (not a rebuild): the modal timeline already had bars + waveform +
|
||||
padding + boundary lines + greyed context, and the vocal peak envelope is loaded once per track and
|
||||
shared via context — so N inline waveforms are cheap time-slices.
|
||||
- **Inline edits = timing only; structural stays in the modal** (Andrew's call) — lowest-risk surface.
|
||||
- **Fit-to-width per segment** (matches the modal), ruler omitted for density.
|
||||
- **Colours = exact `HIGHLIGHT_CLASSES` tints** so Waveforms and Advanced read identically (first
|
||||
attempt used saturated solids — Andrew rejected as too bright).
|
||||
- **Always show backing-vocals waveform** so the "Clean recommended" default can't be accepted without
|
||||
seeing/hearing what's discarded.
|
||||
- Merged with only "CI Gate" required (CodeRabbit is advisory, and was stalled ~10 min at merge; PR left
|
||||
without the `@coderabbitai ignore` line so its review still posts).
|
||||
|
||||
## Learnings / gotchas
|
||||
- **Never call a parent's setState from inside a `setState` updater.** Committing dragged timing via
|
||||
`setWords(cur => { onCommit(...); return cur })` fired the parent's `setHistory` during render →
|
||||
"Cannot update a component while rendering a different component." Fix: keep a `wordsRef` synced with
|
||||
the state and read it from the event handler.
|
||||
- **`overflow-hidden` on a bar clips the ghost text above it.** The AI-correction ghost floats above the
|
||||
bar via `absolute bottom-full` (a visual child outside the box); adding `overflow-hidden` to truncate
|
||||
long words silently hid it. Truncate the inner text span (`truncate min-w-0`) instead.
|
||||
- **Structural JSX edits to the big `LyricsAnalyzer.tsx` don't hot-swap via Fast Refresh** — needed a full
|
||||
page reload to take effect during dev.
|
||||
- **`translate.py` adds/updates keys but does NOT prune removed ones**; CI (`validate-translations.py`)
|
||||
requires exact parity, so a removed en key must be manually deleted from all 33 locales.
|
||||
- **Local review against prod:** `cd frontend && npm run dev` proxies `/api/*` → prod backend by default
|
||||
(`BACKEND_URL`); set `localStorage.karaoke_access_token` to the admin-tokens secret + open
|
||||
`/app/jobs#/<id>/review`. `scripts/list-review-jobs.py` prints the URLs.
|
||||
|
||||
## Open threads & next steps
|
||||
- **CodeRabbit review on PR #1010** was still "in progress" at merge — glance later; follow-up if it
|
||||
flags anything real.
|
||||
- **Short-word truncation:** timing-accurate bars mean short words truncate to an ellipsis; mitigated
|
||||
with a hover tooltip. Andrew hasn't asked for more, but a different treatment (visible overflow) is an
|
||||
option if it annoys.
|
||||
- Row **virtualization** is a possible follow-up if very long lyric lists lag (not needed so far).
|
||||
- Dev server + Playwright browser were left running at session end (to be stopped on cleanup).
|
||||
|
||||
## Related docs
|
||||
- Plan: `docs/archive/2026-09-17-waveforms-review-mode-plan.md`
|
||||
- `docs/LESSONS-LEARNED.md` → "Lyrics-review 'Waveforms' mode — two React/CSS gotchas (Sep 2026, v0.227.0)"
|
||||
- PR: https://github.com/nomadkaraoke/karaoke-gen/pull/1010
|
||||
@@ -0,0 +1,60 @@
|
||||
# Review fast-full-load + E2E canary regression fix — 2026-09-17
|
||||
|
||||
**Project:** karaoke-gen **Branch/commit:** main @ `303ff7e7` **Status:** done (shipped + deployed + canary-verified)
|
||||
|
||||
## Summary
|
||||
|
||||
Two pieces of work, back to back:
|
||||
|
||||
1. **Review page fast-full-load re-architecture (PR #1018, v0.229.0).** Picked up from a prior-session handoff. Root-cause fix for the 2026-09-17 signing-hang incident: removed the IAM `signBlob` network round-trip from the `/api/review/{id}/correction-data` hot path entirely, so the review page always loads fast with audio present on first paint (not the degraded fail-soft path v0.228.1 fell back to).
|
||||
|
||||
2. **Post-deploy canary regression diagnosis + verification.** v0.229.0's post-deploy canary went red. Diagnosed it as a regression from **#1019** (not #1018): the happy-path canary's admin `e2e-test-runner` account got added to the test-email allowlist, and `exclude_test` then hid its own just-created job from its own list → STEP 5 "job card visible" timed out. Andrew had already shipped the identical fix (#1020) in parallel; my duplicate (#1021) was closed. Watched the deploy through and confirmed **both** the deploy canary and the daily E2E happy-path are green again.
|
||||
|
||||
## What changed
|
||||
|
||||
### PR #1018 — review fast-full-load (Option B: same-origin byte proxy), v0.229.0
|
||||
- **`backend/api/routes/review.py`:**
|
||||
- New endpoint `GET /{job_id}/instrumental-audio/{option_id}` — streams the transcoded OGG bytes with HTTP Range (206) support, `require_review_auth` (token via query for raw `<audio>` src, like `/audio/vocals`), stem path resolved server-side from the option id. Bounded LRU byte cache (`_review_audio_cache`, cap `REVIEW_AUDIO_CACHE_MAX`=16) — prod-safe, unlike the unbounded dev cache. Catches `NotFound` → 404 (CodeRabbit follow-up).
|
||||
- `_build_instrumental_options` now returns **relative same-origin proxy paths** as `audio_url` (no signing). Dropped the now-unused `storage` param.
|
||||
- `get_correction_data` — removed the `backing_vocals_waveform_url` signing block (dead field, zero consumers; waveform comes from the JSON `/waveform-data` endpoint). Net: `correction-data` performs **zero** `signBlob` calls.
|
||||
- **`frontend/lib/api.ts`:** `resolveInstrumentalAudioUrls()` rewrites the relative proxy path → absolute `?token=` URL in the API layer (`getCorrectionData` + `refreshInstrumentalUrls`) — zero component churn, mirrors `getVocalsAudioUrl`. Also fixes the CORS `Origin: null` issue and kills the signed-URL expiry/refresh dance.
|
||||
- Tests: backend endpoint (bytes/Range/auth/404), no-signing assertions on the hot path; frontend URL-resolution units; prod E2E `frontend/e2e/production/review-fast-load.spec.ts`. Docs: `TROUBLESHOOTING.md`, `API.md`, plan in `docs/archive/2026-09-17-review-fast-full-load-plan.md`.
|
||||
- The v0.228.1 signing timeout + bounded admission stays as defense-in-depth for non-hot-path signing (e.g. preview-video).
|
||||
|
||||
### PR #1020 (Andrew's, identical to my closed #1021) — canary regression fix
|
||||
- **`backend/api/routes/jobs.py`:** the admin-only `exclude_test` filter (both summary + full list modes) now **exempts the caller's own jobs** (`user_email == auth_result.user_email`). #1019's intent preserved (Andrew's admin dashboard still hides e2e-test-runner jobs), but a test account always sees its own.
|
||||
|
||||
### Ops / verification actions (external state)
|
||||
- Merged #1018 (admin auto-merge after CI); deployed to prod. Verified live: `correction-data` 200 in 0.81s with proxy paths; proxy endpoint serves `audio/ogg` + Range 206; 401 without token; 404 bad option.
|
||||
- Diagnosed the canary failure empirically: minted an `e2e-test-runner` impersonation token → `GET /api/jobs` returned 7 different users' jobs, proving the token is **admin**.
|
||||
- Closed PR #1021 (redundant with #1020). Cleaned up both worktrees.
|
||||
- Watched the `303ff7e7` deploy to completion: prod moved to revision **`karaoke-backend-01015-dav`**.
|
||||
- Confirmed fix live: `e2e-test-runner` (admin) again sees its own jobs with default `exclude_test`.
|
||||
- **Deploy canary run `35263676868` = ✅ success** (full happy-path incl. STEP 5 + generation + distribution + cleanup).
|
||||
- **Daily E2E run `35266877382` = ✅ success** — dispatched via `workflow_dispatch` with `use_test_token=true` (impersonates `e2e-test-runner` = the exact broken admin path; skips Stage 1 real-Stripe purchase). Job drove the full pipeline to `complete`.
|
||||
|
||||
## Decisions & rationale
|
||||
- **Option B (same-origin byte proxy) over Option A (local SA-key V4 signing).** Andrew chose B. Org policy `iam.disableServiceAccountKeyCreation` is NOT enforced (A was viable), but B is fully shippable in code (no infra/key provisioning, no long-lived-key liability), reuses the proven dev proxy, and also fixes CORS.
|
||||
- **Frontend builds the absolute proxy URL, not the backend.** `request.base_url` is unreliable behind Cloudflare (wrong scheme/host); the frontend already knows `API_BASE_URL`. Backend returns a relative path; frontend resolves + appends token — one place, matches `getVocalsAudioUrl`.
|
||||
- **exclude_test fix exempts the caller's own jobs** (rather than reverting #1019 or making e2e-test-runner non-admin). Surgical, preserves #1019's admin-dashboard hiding, protects any future test account from being invisible to itself.
|
||||
- **Verified the daily via `use_test_token=true`** — skips the real Stripe charge (unrelated to this fix) while still exercising the broken admin path. Full payment run happens on the next 6am cron.
|
||||
|
||||
## Learnings / gotchas
|
||||
- **`e2e-test-runner@nomadkaraoke.com` impersonation tokens are ADMIN** (internal domain). So the happy-path canary runs the consumer `/app` as an admin, and `list_jobs` returns all-jobs-minus-`exclude_test`. That interaction is what made #1019 break the canary.
|
||||
- **A red deploy run with backend+frontend deploy = success but Post-Deploy Canary = failure** may be a canary/test-visibility issue, not the shipped change. Check *which STEP* failed: STEP 5 (job card) = list/visibility; STEP 6/8 = the orchestration stalls documented in the e2e-stall memory.
|
||||
- **Before building a fix for a failing canary, `git fetch origin main`** — Andrew (or a parallel session) may already have an in-flight fix. I independently diagnosed + wrote #1021 only to find #1020 already merged. (Good cross-check, wasted a PR.)
|
||||
- **GHA deploy concurrency cancels older in-progress deploys.** Three PRs (#1018, #1020, #1017) merged in quick succession; intermediate deploys show "cancelled" — the final main-HEAD deploy carries everything. Don't mistake a cancelled deploy for a failure.
|
||||
- **`gh run list --branch main` returned stale results** this session; `gh api .../actions/runs` + filtering by `head_sha` / `gcloud run revisions list` were more reliable for tracking the live deploy.
|
||||
- Frontend `tsc --noEmit` surfaces many pre-existing errors in unrelated files (admin pages, e2e specs, functions) — filter to your touched file to check your own work.
|
||||
|
||||
## Open threads & next steps
|
||||
- **Nothing blocking.** All three PRs (#1018, #1019, #1020 — plus #1017 lyrics-cache) are live on `karaoke-backend-01015-dav` and canary-verified.
|
||||
- The daily E2E's **Stage 1 (real Stripe credit purchase)** was skipped in my dispatched verification; it runs on the next 6am cron. If it ever fails, that's a payment-flow issue unrelated to today's work.
|
||||
- The older, separate **job-orchestration stalls** (prep→advance, in_review→finalize) were fixed 2026-09-15 (#1002/#1003) and are documented in agent memory `project_gen_e2e_job_orchestration_stalls` — not seen this session.
|
||||
|
||||
## Related docs
|
||||
- `docs/archive/2026-09-17-review-fast-full-load-plan.md` — Option A/B/C design + rationale
|
||||
- `docs/archive/2026-09-17-lyrics-review-fast-full-load-rearchitecture-handoff.md` — the prior-session handoff this work started from
|
||||
- `docs/TROUBLESHOOTING.md` — updated review-signing runbook (root-cause fix section)
|
||||
- `docs/sessions/2026-Q3/2026-09-17-gen-review-page-signing-hang-incident.md` — the incident that motivated #1018
|
||||
- Agent memory: `project_gen_signed_url_signing_hang`, `project_gen_e2e_job_orchestration_stalls`
|
||||
@@ -131,10 +131,16 @@ describe('apiFetch', () => {
|
||||
// stays hidden (a slow endpoint must not alarm the user without evidence).
|
||||
await jest.advanceTimersByTimeAsync(STALL_RECONNECTING_MS)
|
||||
expect(getBackendStatus()).toBe('online')
|
||||
// Probe times out (~4s) → outage confirmed → the hint appears.
|
||||
// Probe times out (~4s) → outage suspected → the hint appears.
|
||||
await jest.advanceTimersByTimeAsync(5_000)
|
||||
expect(getBackendStatus()).toBe('reconnecting')
|
||||
// The stall alone now qualifies for "unavailable", but escalation needs a
|
||||
// SECOND consecutive probe failure (one failed probe can just be a briefly
|
||||
// pegged instance) — until then the calm pill is all the user sees.
|
||||
await jest.advanceTimersByTimeAsync(STALL_UNAVAILABLE_MS - STALL_RECONNECTING_MS - 5_000)
|
||||
expect(getBackendStatus()).toBe('reconnecting')
|
||||
// Verdict goes stale (~24s) → probe #2 fires → times out (~28s) → confirmed.
|
||||
await jest.advanceTimersByTimeAsync(9_000)
|
||||
expect(getBackendStatus()).toBe('unavailable')
|
||||
|
||||
settleGet(mockResponse(200, { ok: true }))
|
||||
|
||||
@@ -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,6 +8,7 @@
|
||||
|
||||
import {
|
||||
getBackendStatus,
|
||||
getBackendStatusDebug,
|
||||
beginRequest,
|
||||
endRequest,
|
||||
configureHealthProbe,
|
||||
@@ -158,4 +159,53 @@ describe('backend-status store (health-probe confirmation)', () => {
|
||||
await jest.advanceTimersByTimeAsync(3000) // verdict lands
|
||||
expect(getBackendStatus()).toBe('reconnecting')
|
||||
})
|
||||
|
||||
it('needs TWO consecutive failed probes before escalating to unavailable', async () => {
|
||||
// Each probe takes 3s to fail — realistic for a probe racing its own
|
||||
// timeout against a briefly-pegged (not down) instance.
|
||||
const probe = jest.fn(
|
||||
() => new Promise<boolean>((res) => setTimeout(() => res(false), 3000)),
|
||||
)
|
||||
configureHealthProbe(probe)
|
||||
|
||||
open.push(beginRequest())
|
||||
// t=10s: probe #1 starts. t=13s: failure #1 recorded.
|
||||
// t=20s: the stall alone now qualifies for "unavailable", but only one
|
||||
// probe failure has been recorded (verdict fresh until t=23s) —
|
||||
// the calm reconnecting pill must be all the user sees.
|
||||
await jest.advanceTimersByTimeAsync(STALL_UNAVAILABLE_MS + 1000) // t=21s
|
||||
expect(getBackendStatus()).toBe('reconnecting')
|
||||
expect(getBackendStatusDebug().consecutiveProbeFailures).toBe(1)
|
||||
|
||||
// t=23s: verdict stale → probe #2 starts. t=26s: failure #2 → escalate.
|
||||
await jest.advanceTimersByTimeAsync(6000) // t=27s
|
||||
expect(getBackendStatus()).toBe('unavailable')
|
||||
expect(getBackendStatusDebug().consecutiveProbeFailures).toBe(2)
|
||||
})
|
||||
|
||||
it('a probe success resets the consecutive-failure count', async () => {
|
||||
let reachable = false
|
||||
const probe = jest.fn(() => Promise.resolve(reachable))
|
||||
configureHealthProbe(probe)
|
||||
|
||||
open.push(beginRequest())
|
||||
await jest.advanceTimersByTimeAsync(STALL_UNAVAILABLE_MS + PROBE_FRESH_MS)
|
||||
expect(getBackendStatusDebug().consecutiveProbeFailures).toBeGreaterThanOrEqual(2)
|
||||
|
||||
reachable = true
|
||||
await jest.advanceTimersByTimeAsync(PROBE_FRESH_MS + 2000)
|
||||
expect(getBackendStatus()).toBe('online')
|
||||
expect(getBackendStatusDebug().consecutiveProbeFailures).toBe(0)
|
||||
})
|
||||
|
||||
it('exposes a diagnostic snapshot for telemetry', async () => {
|
||||
configureHealthProbe(() => Promise.resolve(false))
|
||||
open.push(beginRequest())
|
||||
await jest.advanceTimersByTimeAsync(STALL_RECONNECTING_MS + 1000)
|
||||
|
||||
const debug = getBackendStatusDebug()
|
||||
expect(debug.inFlightCount).toBe(1)
|
||||
expect(debug.oldestStallMs).toBeGreaterThanOrEqual(STALL_RECONNECTING_MS)
|
||||
expect(debug.lastProbeOk).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client"
|
||||
|
||||
import { useEffect, useState, useCallback, useRef } from "react"
|
||||
import { reportDegradationEvent } from "@/lib/degradation-events"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
import { api, Job, createLyricsReviewApiClient, lyricsReviewApi } from "@/lib/api"
|
||||
import { Spinner } from "@/components/ui/spinner"
|
||||
@@ -334,6 +335,10 @@ function LyricsReviewWrapper({ job, isLocalMode = false, isReplay = false }: { j
|
||||
setCorrectionData(data)
|
||||
} catch (err) {
|
||||
console.error("Failed to load correction data:", err)
|
||||
reportDegradationEvent("lyrics_load_failed", {
|
||||
message: err instanceof Error ? err.message : String(err),
|
||||
status: (err as { status?: number })?.status ?? null,
|
||||
})
|
||||
setError(err instanceof Error ? err.message : "Failed to load lyrics data")
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
"use client"
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState } from "react"
|
||||
import { adminApi } from "@/lib/api"
|
||||
import type { CommunityRequestItem } from "@/lib/api"
|
||||
import { Card, CardContent } from "@/components/ui/card"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Skeleton } from "@/components/ui/skeleton"
|
||||
import {
|
||||
Table, TableHeader, TableBody, TableHead, TableRow, TableCell,
|
||||
} from "@/components/ui/table"
|
||||
import { History, Youtube, ExternalLink, RefreshCw } from "lucide-react"
|
||||
|
||||
// Status → badge styling. Mirrors the request lifecycle in backend/models/song_request.py.
|
||||
const STATUS_VARIANT: Record<string, "default" | "secondary" | "outline" | "destructive"> = {
|
||||
open: "secondary",
|
||||
queued: "outline",
|
||||
in_progress: "outline",
|
||||
published: "default",
|
||||
rejected: "destructive",
|
||||
stalled: "destructive",
|
||||
}
|
||||
|
||||
function fmtDate(iso?: string | null): string {
|
||||
if (!iso) return "—"
|
||||
const d = new Date(iso)
|
||||
return isNaN(d.getTime()) ? "—" : d.toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric" })
|
||||
}
|
||||
|
||||
export default function CommunityRequestsPage() {
|
||||
const [requests, setRequests] = useState<CommunityRequestItem[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
try {
|
||||
const res = await adminApi.listCommunityRequests()
|
||||
setRequests(res.requests)
|
||||
} catch {
|
||||
setError("Failed to load community requests.")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
load()
|
||||
}, [load])
|
||||
|
||||
const counts = useMemo(() => {
|
||||
const c: Record<string, number> = {}
|
||||
for (const r of requests) c[r.status] = (c[r.status] ?? 0) + 1
|
||||
return c
|
||||
}, [requests])
|
||||
|
||||
return (
|
||||
<div className="space-y-6 max-w-6xl">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold flex items-center gap-2">
|
||||
<History className="w-6 h-6" /> Community Requests
|
||||
</h1>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
Every song requested via the public voting board
|
||||
(<a href="https://requests.nomadkaraoke.com" target="_blank" rel="noopener noreferrer"
|
||||
className="text-blue-500 hover:underline">requests.nomadkaraoke.com</a>) —
|
||||
who asked, how it was voted, which job made it, and where it landed on YouTube.
|
||||
</p>
|
||||
</div>
|
||||
<Button variant="outline" size="sm" onClick={load} disabled={loading}>
|
||||
<RefreshCw className={`w-4 h-4 mr-1 ${loading ? "animate-spin" : ""}`} /> Refresh
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="rounded-lg px-3 py-2 text-sm bg-red-500/10 text-red-500 border border-red-500/30">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && requests.length > 0 && (
|
||||
<div className="flex flex-wrap gap-2 text-xs">
|
||||
<Badge variant="outline">{requests.length} total</Badge>
|
||||
{Object.entries(counts).map(([status, n]) => (
|
||||
<Badge key={status} variant={STATUS_VARIANT[status] ?? "outline"}>
|
||||
{n} {status.replace("_", " ")}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{loading ? (
|
||||
<div className="space-y-3">
|
||||
{[0, 1, 2].map((i) => <Skeleton key={i} className="h-12 w-full" />)}
|
||||
</div>
|
||||
) : requests.length === 0 ? (
|
||||
<Card>
|
||||
<CardContent className="py-10 text-center text-muted-foreground">
|
||||
No community requests yet.
|
||||
</CardContent>
|
||||
</Card>
|
||||
) : (
|
||||
<Card>
|
||||
<CardContent className="p-0">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Song</TableHead>
|
||||
<TableHead>Status</TableHead>
|
||||
<TableHead>Requester</TableHead>
|
||||
<TableHead className="text-right">Votes</TableHead>
|
||||
<TableHead>Requested</TableHead>
|
||||
<TableHead>Job</TableHead>
|
||||
<TableHead>Video</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{requests.map((r) => (
|
||||
<TableRow key={r.id}>
|
||||
<TableCell className="font-medium">
|
||||
{r.artist} — {r.title}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant={STATUS_VARIANT[r.status] ?? "outline"}>
|
||||
{r.status.replace("_", " ")}
|
||||
</Badge>
|
||||
{r.review_state ? (
|
||||
<Badge variant="outline" className="ml-1">{r.review_state}</Badge>
|
||||
) : null}
|
||||
</TableCell>
|
||||
<TableCell className="text-sm">
|
||||
<span className="truncate">{r.submitted_by}</span>
|
||||
{r.owner_email && r.owner_email !== r.submitted_by ? (
|
||||
<span className="block text-xs text-muted-foreground">owner: {r.owner_email}</span>
|
||||
) : null}
|
||||
</TableCell>
|
||||
<TableCell className="text-right">{r.vote_count}</TableCell>
|
||||
<TableCell className="text-sm text-muted-foreground">{fmtDate(r.created_at)}</TableCell>
|
||||
<TableCell>
|
||||
{r.job_id ? (
|
||||
<a
|
||||
href={`/app/jobs#/${r.job_id}`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1 text-sm text-blue-500 hover:underline"
|
||||
>
|
||||
{r.job_id.slice(0, 8)} <ExternalLink className="w-3 h-3" />
|
||||
</a>
|
||||
) : (
|
||||
<span className="text-muted-foreground text-sm">—</span>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{r.youtube_url ? (
|
||||
<a
|
||||
href={r.youtube_url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1 text-sm text-blue-500 hover:underline"
|
||||
>
|
||||
<Youtube className="w-4 h-4 text-red-500" /> Watch
|
||||
</a>
|
||||
) : (
|
||||
<span className="text-muted-foreground text-sm">—</span>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
Share2,
|
||||
Building2,
|
||||
ListChecks,
|
||||
History,
|
||||
} from "lucide-react"
|
||||
|
||||
import {
|
||||
@@ -60,6 +61,11 @@ const navItems = [
|
||||
href: "/admin/referrals",
|
||||
icon: Share2,
|
||||
},
|
||||
{
|
||||
title: "Community Requests",
|
||||
href: "/admin/community-requests",
|
||||
icon: History,
|
||||
},
|
||||
{
|
||||
title: "Community Reviews",
|
||||
href: "/admin/community-reviews",
|
||||
|
||||
@@ -5,8 +5,10 @@ import { useTranslations } from "next-intl"
|
||||
import { Loader2, CloudOff, X } from "lucide-react"
|
||||
import {
|
||||
useBackendStatus,
|
||||
getBackendStatusDebug,
|
||||
__installBackendStatusDevHook,
|
||||
} from "@/lib/backend-status"
|
||||
import { reportDegradationEvent } from "@/lib/degradation-events"
|
||||
|
||||
/**
|
||||
* App-wide, non-blocking banner that reacts to backend connectivity (see
|
||||
@@ -37,6 +39,26 @@ export function BackendStatusBanner() {
|
||||
if (status === "online") setDismissed(false)
|
||||
}, [status])
|
||||
|
||||
// Persist every banner display server-side (Andrew's telemetry ask): this is
|
||||
// the single global banner instance, so reporting here == "shown to a user".
|
||||
// The reporter throttles per type, so a flapping status can't spam.
|
||||
useEffect(() => {
|
||||
if (status === "online") return
|
||||
// A dismissed unavailable card renders nothing — reporting it would count a
|
||||
// banner the user never saw. (dismiss only re-arms after passing online.)
|
||||
if (status === "unavailable" && dismissed) return
|
||||
const debug = getBackendStatusDebug()
|
||||
reportDegradationEvent(
|
||||
status === "unavailable" ? "banner_unavailable" : "banner_reconnecting",
|
||||
{
|
||||
stall_ms: debug.oldestStallMs,
|
||||
in_flight: debug.inFlightCount,
|
||||
probe_ok: debug.lastProbeOk,
|
||||
probe_failures: debug.consecutiveProbeFailures,
|
||||
},
|
||||
)
|
||||
}, [status, dismissed])
|
||||
|
||||
if (status === "online") return null
|
||||
|
||||
if (status === "reconnecting") {
|
||||
|
||||
@@ -17,21 +17,26 @@ interface BackingVocalsWaveformProps {
|
||||
currentTime: number
|
||||
/** Seek the preview to this time and switch audio to the instrumental. */
|
||||
onSeek: (time: number) => void
|
||||
/** Whether these backing vocals will be kept (with_backing) or removed (clean) in the
|
||||
final video — drives the hint wording. Defaults to kept. */
|
||||
kept?: boolean
|
||||
}
|
||||
|
||||
const WAVEFORM_HEIGHT = 35
|
||||
const NUM_POINTS = 600
|
||||
|
||||
/**
|
||||
* Thin waveform of the whole backing-vocals stem, shown when the instrumental
|
||||
* auto-selector chose to keep the backing vocals. Clicking seeks the preview
|
||||
* video to that point and switches its audio to the instrumental+backing track,
|
||||
* so the reviewer can quickly sanity-check the automatic choice.
|
||||
* Thin waveform of the whole backing-vocals stem, shown whenever a playable backing stem
|
||||
* exists — whether the reviewer is keeping them or has the clean instrumental selected — so
|
||||
* the backing vocals are never discarded sight-unseen. Clicking seeks the preview video to
|
||||
* that point and switches its audio to the instrumental+backing track, so the reviewer can
|
||||
* hear the backing vocals before deciding.
|
||||
*/
|
||||
export default function BackingVocalsWaveform({
|
||||
getWaveformData,
|
||||
currentTime,
|
||||
onSeek,
|
||||
kept = true,
|
||||
}: BackingVocalsWaveformProps) {
|
||||
const t = useTranslations('lyricsReview.previewVideo')
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null)
|
||||
@@ -119,7 +124,9 @@ export default function BackingVocalsWaveform({
|
||||
|
||||
return (
|
||||
<div className="mt-2">
|
||||
<p className="text-xs text-muted-foreground mb-1">{t('backingVocalsWaveformHint')}</p>
|
||||
<p className="text-xs text-muted-foreground mb-1">
|
||||
{kept ? t('backingVocalsWaveformKept') : t('backingVocalsWaveformRemoved')}
|
||||
</p>
|
||||
<div
|
||||
ref={containerRef}
|
||||
className="w-full rounded-md overflow-hidden bg-[#0d1117]"
|
||||
|
||||
@@ -317,7 +317,9 @@ export default function Header({
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent className="max-w-xs">
|
||||
{autoCorrectedCount > 0 ? t('autoCorrectedDesc') : t('autoCorrectDesc')}
|
||||
{autoCorrectedCount > 0
|
||||
? t('autoCorrectedDesc', { count: autoCorrectedCount })
|
||||
: t('autoCorrectDesc')}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
GapSequence,
|
||||
HighlightInfo,
|
||||
InteractionMode,
|
||||
TranscriptionViewMode,
|
||||
LyricsSegment,
|
||||
ReferenceSource,
|
||||
WordCorrection,
|
||||
@@ -65,6 +66,7 @@ import type { AiSuggestion } from '@/lib/api/autoCorrect'
|
||||
import type { ServerSuggestionUndoInfo } from '@/lib/lyrics-review/utils/autoCorrectApply'
|
||||
import { getWordsFromIds } from '@/lib/lyrics-review/utils/wordUtils'
|
||||
import { applyOffsetToCorrectionData, applyOffsetToSegment, applyOffsetToWord } from '@/lib/lyrics-review/utils/timingUtils'
|
||||
import { resolveInitialViewMode } from '@/lib/lyrics-review/utils/segmentTiming'
|
||||
import { VocalsAudioDataLoader } from './VocalsAudioDataLoader'
|
||||
|
||||
// Add type for window augmentation
|
||||
@@ -86,6 +88,9 @@ interface ApiClient {
|
||||
searchLyrics?: (artist: string, title: string, forceSources?: string[]) => Promise<SearchLyricsResponse>
|
||||
getAudioUrl: (hash: string) => string
|
||||
getVocalsAudioUrl: () => string
|
||||
// Optional: pre-computed peaks endpoint (cloud mode); absent → loader falls
|
||||
// back to downloading + decoding the full stem.
|
||||
getVocalsPeaksUrl?: () => string
|
||||
generatePreviewVideo: (data: CorrectionData, isDuet?: boolean) => Promise<{
|
||||
status: string
|
||||
message?: string
|
||||
@@ -175,6 +180,7 @@ export default function LyricsAnalyzer({
|
||||
const [instrumentalChoice, setInstrumentalChoice] = useState<'clean' | 'with_backing' | null>(null)
|
||||
|
||||
const [vocalsAudioUrl, setVocalsAudioUrl] = useState<string | null>(null)
|
||||
const [vocalsPeaksUrl, setVocalsPeaksUrl] = useState<string | null>(null)
|
||||
|
||||
// Success screen state (for auto-close after submission)
|
||||
const [showSuccess, setShowSuccess] = useState(false)
|
||||
@@ -207,10 +213,11 @@ export default function LyricsAnalyzer({
|
||||
|
||||
const [focusedSegmentIndex, setFocusedSegmentIndex] = useState<number | null>(null)
|
||||
|
||||
const [advancedMode, setAdvancedMode] = useState(() => {
|
||||
if (typeof window === 'undefined') return false
|
||||
return localStorage.getItem('lyricsReviewAdvancedMode') === 'true'
|
||||
})
|
||||
// Synced Lyrics view mode: Simple text / Advanced flex-pills / Waveforms inline timelines.
|
||||
// Migrates the old boolean `lyricsReviewAdvancedMode` localStorage key to the new enum.
|
||||
const [transcriptionViewMode, setTranscriptionViewMode] = useState<TranscriptionViewMode>(() =>
|
||||
resolveInitialViewMode(typeof window === 'undefined' ? null : window.localStorage)
|
||||
)
|
||||
|
||||
// Gap navigation state
|
||||
const [currentGapIndex, setCurrentGapIndex] = useState<number | null>(null)
|
||||
@@ -654,6 +661,7 @@ export default function LyricsAnalyzer({
|
||||
if (!apiClient) return
|
||||
|
||||
setVocalsAudioUrl(apiClient.getVocalsAudioUrl())
|
||||
setVocalsPeaksUrl(apiClient.getVocalsPeaksUrl ? apiClient.getVocalsPeaksUrl() : null)
|
||||
}, [apiClient])
|
||||
|
||||
// Countdown effect for success screen (auto-close/redirect after submission)
|
||||
@@ -691,10 +699,10 @@ export default function LyricsAnalyzer({
|
||||
[editLog]
|
||||
)
|
||||
|
||||
const handleAdvancedModeToggle = useCallback((enabled: boolean) => {
|
||||
setAdvancedMode(enabled)
|
||||
const handleViewModeChange = useCallback((mode: TranscriptionViewMode) => {
|
||||
setTranscriptionViewMode(mode)
|
||||
if (typeof window !== 'undefined') {
|
||||
localStorage.setItem('lyricsReviewAdvancedMode', String(enabled))
|
||||
localStorage.setItem('lyricsReviewViewMode', mode)
|
||||
}
|
||||
}, [])
|
||||
|
||||
@@ -906,6 +914,36 @@ export default function LyricsAnalyzer({
|
||||
[history, historyIndex, editModalSegment, updateDataWithHistory, editLog, showFeedbackForEntry]
|
||||
)
|
||||
|
||||
// Waveforms mode: persist a segment's inline timing edit (fires on drag release). The
|
||||
// incoming segment is in display coordinates (offset-applied, like the modal); un-apply
|
||||
// the offset before storing so the manual nudge never gets baked into the saved timings.
|
||||
const handleCommitSegmentTiming = useCallback(
|
||||
(index: number, updatedSegment: LyricsSegment) => {
|
||||
const currentData = history[historyIndex]
|
||||
const segmentToStore =
|
||||
timingOffsetMs !== 0 ? applyOffsetToSegment(updatedSegment, -timingOffsetMs) : updatedSegment
|
||||
const newSegments = currentData.corrected_segments.map((segment, i) =>
|
||||
i === index ? segmentToStore : segment
|
||||
)
|
||||
updateDataWithHistory(
|
||||
{ ...currentData, corrected_segments: newSegments },
|
||||
'adjust word timing'
|
||||
)
|
||||
},
|
||||
[history, historyIndex, timingOffsetMs, updateDataWithHistory]
|
||||
)
|
||||
|
||||
// Waveforms mode: open the full Edit modal for structural edits (text / split / merge /
|
||||
// add / delete). Uses the raw (non-offset) segment; the modal applies the offset itself.
|
||||
const handleEditSegmentFromWaveforms = useCallback(
|
||||
(segmentIndex: number) => {
|
||||
const segment = data.corrected_segments[segmentIndex]
|
||||
if (!segment) return
|
||||
setEditModalSegment({ segment, index: segmentIndex, originalSegment: segment })
|
||||
},
|
||||
[data.corrected_segments]
|
||||
)
|
||||
|
||||
// Delete segment handler
|
||||
const handleDeleteSegment = useCallback(
|
||||
(segmentIndex: number) => {
|
||||
@@ -1499,7 +1537,7 @@ export default function LyricsAnalyzer({
|
||||
}
|
||||
|
||||
return (
|
||||
<VocalsAudioDataLoader audioUrl={vocalsAudioUrl}>
|
||||
<VocalsAudioDataLoader audioUrl={vocalsAudioUrl} peaksUrl={vocalsPeaksUrl}>
|
||||
<div className="max-w-full overflow-x-hidden">
|
||||
<Header
|
||||
isReadOnly={isReadOnly}
|
||||
@@ -1554,7 +1592,11 @@ export default function LyricsAnalyzer({
|
||||
}}
|
||||
/>
|
||||
|
||||
<div className={cn('grid gap-2', isMobile ? 'grid-cols-1' : 'grid-cols-2')}>
|
||||
{/* In Advanced/Waveforms the Synced side benefits from extra width, so the Reference
|
||||
column shrinks to its longest line (capped) and Synced takes the rest — no wasted
|
||||
space. Simple mode keeps the even 50/50 split. */}
|
||||
<div className={cn('gap-2', isMobile ? 'flex flex-col' : 'flex flex-row items-start')}>
|
||||
<div className={cn(isMobile ? 'w-full' : 'flex-1 min-w-0')}>
|
||||
<TranscriptionView
|
||||
data={displayData}
|
||||
mode={effectiveMode}
|
||||
@@ -1575,8 +1617,10 @@ export default function LyricsAnalyzer({
|
||||
onAcceptCorrection={handleAcceptCorrection}
|
||||
onShowCorrectionDetail={handleShowCorrectionDetail}
|
||||
activeGapWordIds={activeGapWordIds}
|
||||
advancedMode={advancedMode}
|
||||
onAdvancedModeToggle={handleAdvancedModeToggle}
|
||||
viewMode={transcriptionViewMode}
|
||||
onViewModeChange={handleViewModeChange}
|
||||
onCommitSegment={handleCommitSegmentTiming}
|
||||
onEditSegment={handleEditSegmentFromWaveforms}
|
||||
editedWordIds={editedWordIds}
|
||||
aiCorrectedWordIds={aiCorrectedWordIds}
|
||||
aiOriginalTextByWordId={aiOriginalTextByWordId}
|
||||
@@ -1589,6 +1633,16 @@ export default function LyricsAnalyzer({
|
||||
}}
|
||||
onSegmentFocus={setFocusedSegmentIndex}
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
className={cn(
|
||||
isMobile
|
||||
? 'w-full'
|
||||
: transcriptionViewMode === 'simple'
|
||||
? 'flex-1 min-w-0'
|
||||
: 'flex-none w-max max-w-[46%]'
|
||||
)}
|
||||
>
|
||||
<ReferenceView
|
||||
referenceSources={data.reference_lyrics}
|
||||
anchors={data.anchor_sequences}
|
||||
@@ -1608,6 +1662,7 @@ export default function LyricsAnalyzer({
|
||||
defaultArtist={data.metadata?.artist || ''}
|
||||
defaultTitle={data.metadata?.title || ''}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Spacer for sticky footer */}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { useRef, useState } from 'react'
|
||||
import { Word } from '@/lib/lyrics-review/types'
|
||||
import { WordDecoration } from '@/lib/lyrics-review/utils/wordDecorations'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { WaveformVisualizer } from './WaveformVisualizer'
|
||||
import { VocalsAudioDataLoaderContext } from './VocalsAudioDataLoader'
|
||||
@@ -21,8 +22,25 @@ interface TimelineEditorProps {
|
||||
currentTime?: number
|
||||
onPlaySegment?: (time: number) => void
|
||||
showPlaybackIndicator?: boolean
|
||||
/** Show the second-marker ruler band. Hidden in the compact Waveforms review rows. */
|
||||
showRuler?: boolean
|
||||
/** Fires once on drag release (mouse up after a move/resize). Lets inline callers
|
||||
persist the final timing to history without committing on every mousemove. */
|
||||
onCommit?: () => void
|
||||
/** Per-word bar colour + AI-correction ghost text, keyed by word id (Waveforms mode).
|
||||
When present, bars colour-code like the Advanced pills (anchor/gap/correction). */
|
||||
wordDecorations?: Map<string, WordDecoration>
|
||||
/** Compact layout for the inline Waveforms rows: no card chrome, tight heights, the
|
||||
waveform doubles as the click-to-play target (no separate strip). */
|
||||
compact?: boolean
|
||||
/** Fires when a word bar is clicked (pressed and released without dragging). Used by the
|
||||
Waveforms rows to open the Edit Segment modal, distinct from a drag which moves/resizes. */
|
||||
onWordClick?: (index: number) => void
|
||||
}
|
||||
|
||||
// Pointer travel (px) beyond which a press counts as a drag rather than a click.
|
||||
const DRAG_THRESHOLD_PX = 4
|
||||
|
||||
export default function TimelineEditor({
|
||||
words,
|
||||
contextWords,
|
||||
@@ -33,8 +51,16 @@ export default function TimelineEditor({
|
||||
currentTime = 0,
|
||||
onPlaySegment,
|
||||
showPlaybackIndicator = true,
|
||||
showRuler = true,
|
||||
onCommit,
|
||||
wordDecorations,
|
||||
compact = false,
|
||||
onWordClick,
|
||||
}: TimelineEditorProps) {
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
// Whether the current press has moved past the drag threshold. Distinguishes a click
|
||||
// (open the modal) from a drag (move/resize the word timing).
|
||||
const hasDraggedRef = useRef(false)
|
||||
const [dragState, setDragState] = useState<{
|
||||
wordIndex: number
|
||||
type: 'move' | 'resize-left' | 'resize-right'
|
||||
@@ -139,6 +165,7 @@ export default function TimelineEditor({
|
||||
const initialX = e.clientX - rect.left
|
||||
const initialTime = (initialX / rect.width) * viewDuration
|
||||
|
||||
hasDraggedRef.current = false
|
||||
setDragState({
|
||||
wordIndex,
|
||||
type,
|
||||
@@ -155,6 +182,13 @@ export default function TimelineEditor({
|
||||
const x = e.clientX - rect.left
|
||||
const width = rect.width
|
||||
|
||||
// Ignore sub-threshold jitter so a click (which opens the modal) doesn't nudge the
|
||||
// timing; once the threshold is crossed the press is a drag for the rest of its life.
|
||||
if (!hasDraggedRef.current) {
|
||||
if (Math.abs(x - dragState.initialX) <= DRAG_THRESHOLD_PX) return
|
||||
hasDraggedRef.current = true
|
||||
}
|
||||
|
||||
const currentWord = words[dragState.wordIndex]
|
||||
if (
|
||||
currentWord.start_time === null ||
|
||||
@@ -221,7 +255,18 @@ export default function TimelineEditor({
|
||||
}
|
||||
}
|
||||
|
||||
const handleMouseUp = () => {
|
||||
const handleMouseUp = (fromLeave = false) => {
|
||||
if (dragState) {
|
||||
if (hasDraggedRef.current) {
|
||||
// A real drag: persist the new timing.
|
||||
onCommit?.()
|
||||
} else if (!fromLeave) {
|
||||
// A click (no drag): open the Edit Segment modal. Skipped when the pointer merely
|
||||
// left the row, so leaving without releasing doesn't spuriously open the modal.
|
||||
onWordClick?.(dragState.wordIndex)
|
||||
}
|
||||
}
|
||||
hasDraggedRef.current = false
|
||||
setDragState(null)
|
||||
}
|
||||
|
||||
@@ -256,13 +301,24 @@ export default function TimelineEditor({
|
||||
onPlaySegment(clickedPosition)
|
||||
}
|
||||
|
||||
// Only reserve headroom for the ghost text on rows that actually have an AI correction,
|
||||
// so uncorrected rows stay as tight as the Advanced view.
|
||||
const hasGhostText = Boolean(
|
||||
wordDecorations && Array.from(wordDecorations.values()).some((d) => d.originalText)
|
||||
)
|
||||
// Compact rows tuck the waveform directly under the word bars and use it as the click
|
||||
// target; the modal keeps the roomier card + ruler layout.
|
||||
const wordBandHeight = compact ? 'h-[20px]' : 'h-[30px]'
|
||||
const barPadding = compact ? 'px-1.5 py-0' : 'px-2 py-1'
|
||||
const barFont = 'text-[0.85rem] leading-[1.2]'
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
className="relative bg-card rounded border border-border"
|
||||
className={cn(compact ? 'relative' : 'relative bg-card rounded border border-border')}
|
||||
onMouseMove={handleMouseMove}
|
||||
onMouseUp={handleMouseUp}
|
||||
onMouseLeave={handleMouseUp}
|
||||
onMouseUp={() => handleMouseUp(false)}
|
||||
onMouseLeave={() => handleMouseUp(true)}
|
||||
>
|
||||
{/* Out-of-segment padding: greyed bands on each side of the real segment. These sit above
|
||||
the waveform but below the word bars and are click-through so playback scrubbing still
|
||||
@@ -276,13 +332,22 @@ export default function TimelineEditor({
|
||||
style={{ width: `${100 - timeToPosition(endTime)}%` }}
|
||||
/>
|
||||
|
||||
{/* Timeline ruler */}
|
||||
<div
|
||||
className="h-10 border-b border-border cursor-pointer"
|
||||
onClick={handleTimelineClick}
|
||||
>
|
||||
{generateTimelineMarks()}
|
||||
</div>
|
||||
{/* Timeline ruler. Compact rows drop it entirely (the waveform below is the click
|
||||
target); non-compact rows without a ruler keep a thin click-to-play strip. */}
|
||||
{showRuler ? (
|
||||
<div
|
||||
className="h-10 border-b border-border cursor-pointer"
|
||||
onClick={handleTimelineClick}
|
||||
>
|
||||
{generateTimelineMarks()}
|
||||
</div>
|
||||
) : compact ? null : (
|
||||
<div
|
||||
className="h-2 cursor-pointer"
|
||||
onClick={handleTimelineClick}
|
||||
title="Click to play from here"
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Playback cursor — visible across the padded view (incl. lead-in/out) */}
|
||||
{showPlaybackIndicator && currentTime >= viewStart && currentTime <= viewEnd && (
|
||||
@@ -292,8 +357,9 @@ export default function TimelineEditor({
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Word blocks */}
|
||||
<div className="relative h-[30px]">
|
||||
{/* Word blocks. Reserve headroom only on rows that carry an AI-correction ghost above
|
||||
a bar, so uncorrected rows stay tight. */}
|
||||
<div className={cn('relative', wordBandHeight, hasGhostText && 'mt-4')}>
|
||||
{/* Neighbouring segments' words that fall in the padded view — greyed, read-only context. */}
|
||||
{(contextWords ?? []).map((word, index) => {
|
||||
if (word.start_time === null || word.end_time === null) return null
|
||||
@@ -307,8 +373,10 @@ export default function TimelineEditor({
|
||||
<div
|
||||
key={`ctx-${word.id ?? index}`}
|
||||
className={cn(
|
||||
'absolute bg-muted-foreground/25 text-muted-foreground rounded px-2 py-1',
|
||||
'select-none flex items-center text-sm font-sans pointer-events-none',
|
||||
'absolute bg-muted-foreground/25 text-muted-foreground rounded',
|
||||
barPadding,
|
||||
barFont,
|
||||
'select-none flex items-center pointer-events-none',
|
||||
'border border-dashed border-muted-foreground/40 overflow-hidden whitespace-nowrap'
|
||||
)}
|
||||
style={{
|
||||
@@ -328,26 +396,44 @@ export default function TimelineEditor({
|
||||
const leftPosition = timeToPosition(word.start_time)
|
||||
const rightPosition = timeToPosition(word.end_time)
|
||||
const width = rightPosition - leftPosition
|
||||
const decoration = word.id ? wordDecorations?.get(word.id) : undefined
|
||||
const playing = isWordHighlighted(word)
|
||||
|
||||
return (
|
||||
<div
|
||||
key={index}
|
||||
className={cn(
|
||||
'absolute bg-primary rounded text-primary-foreground px-2 py-1',
|
||||
'cursor-move select-none flex items-center text-sm font-sans transition-colors',
|
||||
isWordHighlighted(word) && 'bg-purple-500 dark:bg-purple-600'
|
||||
'absolute rounded',
|
||||
barPadding,
|
||||
barFont,
|
||||
compact && 'top-0 h-full',
|
||||
'cursor-move select-none flex items-center transition-colors',
|
||||
// Semantic colour (anchor/gap/correction) when decorated, else the plain bar.
|
||||
decoration?.barClassName ?? 'bg-primary text-primary-foreground',
|
||||
// Currently-playing: a bright ring over the semantic colour (decorated), or the
|
||||
// original purple fill (undecorated, e.g. the Edit Segment modal).
|
||||
playing && (decoration ? 'ring-2 ring-inset ring-white' : 'bg-purple-500 dark:bg-purple-600')
|
||||
)}
|
||||
style={{
|
||||
left: `${leftPosition}%`,
|
||||
width: `${width}%`,
|
||||
maxWidth: `calc(${100 - leftPosition}%)`,
|
||||
}}
|
||||
// Timing-accurate bars mean short words get narrow bars whose text truncates;
|
||||
// a tooltip keeps the full word readable without distorting the width.
|
||||
title={compact ? word.text : undefined}
|
||||
onMouseDown={(e) => {
|
||||
e.stopPropagation()
|
||||
handleMouseDown(e, index, 'move')
|
||||
}}
|
||||
onContextMenu={(e) => handleContextMenu(e, index)}
|
||||
>
|
||||
{/* AI-correction ghost: the original transcription, struck through, above the bar. */}
|
||||
{decoration?.originalText && (
|
||||
<span className="absolute left-0 bottom-full mb-[1px] z-10 whitespace-nowrap rounded border border-dashed border-muted-foreground/50 bg-background/90 px-1 text-[0.6rem] leading-tight text-muted-foreground line-through pointer-events-none">
|
||||
{decoration.originalText}
|
||||
</span>
|
||||
)}
|
||||
{/* Left resize handle */}
|
||||
<div
|
||||
className="absolute top-0 left-0 w-2.5 h-full cursor-col-resize hover:bg-primary-foreground/20 rounded-l"
|
||||
@@ -356,7 +442,7 @@ export default function TimelineEditor({
|
||||
handleMouseDown(e, index, 'resize-left')
|
||||
}}
|
||||
/>
|
||||
{word.text}
|
||||
<span className="truncate min-w-0">{word.text}</span>
|
||||
{/* Right resize handle */}
|
||||
<div
|
||||
className="absolute top-0 right-0 w-2.5 h-full cursor-col-resize hover:bg-primary-foreground/20 rounded-r"
|
||||
@@ -370,18 +456,25 @@ export default function TimelineEditor({
|
||||
})}
|
||||
</div>
|
||||
|
||||
<VocalsAudioDataLoaderContext.Consumer>
|
||||
{({ audioData: vocalsAudioData }) => (
|
||||
vocalsAudioData && <WaveformVisualizer
|
||||
startTime={viewStart}
|
||||
endTime={viewEnd}
|
||||
fadeBeforeTime={startTime}
|
||||
fadeAfterTime={endTime}
|
||||
audioData={vocalsAudioData}
|
||||
className="w-[100%] h-[35px]"
|
||||
/>
|
||||
)}
|
||||
</VocalsAudioDataLoaderContext.Consumer>
|
||||
{/* In compact rows the waveform sits directly under the bars and doubles as the
|
||||
click-to-play target (there's no ruler strip). */}
|
||||
<div
|
||||
className={cn(compact && 'cursor-pointer')}
|
||||
onClick={compact ? handleTimelineClick : undefined}
|
||||
>
|
||||
<VocalsAudioDataLoaderContext.Consumer>
|
||||
{({ audioData: vocalsAudioData }) => (
|
||||
vocalsAudioData && <WaveformVisualizer
|
||||
startTime={viewStart}
|
||||
endTime={viewEnd}
|
||||
fadeBeforeTime={startTime}
|
||||
fadeAfterTime={endTime}
|
||||
audioData={vocalsAudioData}
|
||||
className={compact ? 'w-full h-[14px] block' : 'w-[100%] h-[35px]'}
|
||||
/>
|
||||
)}
|
||||
</VocalsAudioDataLoaderContext.Consumer>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -5,10 +5,14 @@ import { useState, useMemo } from 'react'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group'
|
||||
import { Play, Trash2, Type, Clock } from 'lucide-react'
|
||||
import { Play, Trash2, Type, Clock, AudioWaveform } from 'lucide-react'
|
||||
import { HighlightedText } from './shared/HighlightedText'
|
||||
import { TranscriptionViewProps, TranscriptionWordPosition } from '@/lib/lyrics-review/types'
|
||||
import { deleteSegment } from '@/lib/lyrics-review/utils/segmentOperations'
|
||||
import { computeContextWordsBySegment } from '@/lib/lyrics-review/utils/contextWords'
|
||||
import { buildSegmentDecorations } from '@/lib/lyrics-review/utils/wordDecorations'
|
||||
import { TIMELINE_PAD_SECONDS } from './TimelineEditor'
|
||||
import WaveformSegmentRow from './WaveformSegmentRow'
|
||||
import SegmentDetailsModal from './modals/SegmentDetailsModal'
|
||||
import SingerChip from './SingerChip'
|
||||
import { resolveSegmentSinger, hasWordOverrides } from '@/lib/lyrics-review/duet'
|
||||
@@ -34,8 +38,10 @@ export default function TranscriptionView({
|
||||
onAcceptCorrection,
|
||||
onShowCorrectionDetail,
|
||||
activeGapWordIds,
|
||||
advancedMode = false,
|
||||
onAdvancedModeToggle,
|
||||
viewMode = 'simple',
|
||||
onViewModeChange,
|
||||
onCommitSegment,
|
||||
onEditSegment,
|
||||
editedWordIds,
|
||||
aiCorrectedWordIds,
|
||||
aiOriginalTextByWordId,
|
||||
@@ -49,6 +55,41 @@ export default function TranscriptionView({
|
||||
const { ready: audioReady } = useAudioReady()
|
||||
const [selectedSegmentIndex, setSelectedSegmentIndex] = useState<number | null>(null)
|
||||
|
||||
// Advanced (flex-pill) layout is used by both the Advanced and Waveforms modes for the
|
||||
// left-hand controls / spacing; Waveforms additionally swaps the row body for an inline
|
||||
// timeline. Keeping `advancedMode` derived avoids churning the HighlightedText wiring.
|
||||
const advancedMode = viewMode === 'advanced'
|
||||
const waveformsMode = viewMode === 'waveforms'
|
||||
|
||||
// Greyed read-only neighbour words per segment, for the Waveforms inline timeline padding.
|
||||
// Only computed in Waveforms mode. `data.corrected_segments` here is already offset-applied
|
||||
// (the parent passes displayData), so the context words align with the drawn bars.
|
||||
const contextWordsBySegment = useMemo(
|
||||
() =>
|
||||
waveformsMode
|
||||
? computeContextWordsBySegment(data.corrected_segments, TIMELINE_PAD_SECONDS)
|
||||
: null,
|
||||
[waveformsMode, data.corrected_segments]
|
||||
)
|
||||
|
||||
// Per-segment bar colours + AI ghost text for Waveforms mode. Memoised so a playback tick
|
||||
// (currentTime changing every ~100ms) doesn't reclassify every word each frame.
|
||||
const decorationsBySegment = useMemo(() => {
|
||||
if (!waveformsMode) return null
|
||||
const map = new Map<string, ReturnType<typeof buildSegmentDecorations>>()
|
||||
for (const segment of data.corrected_segments) {
|
||||
map.set(
|
||||
segment.id,
|
||||
buildSegmentDecorations(data, segment, {
|
||||
editedWordIds,
|
||||
aiCorrectedWordIds,
|
||||
aiOriginalTextByWordId,
|
||||
})
|
||||
)
|
||||
}
|
||||
return map
|
||||
}, [waveformsMode, data, editedWordIds, aiCorrectedWordIds, aiOriginalTextByWordId])
|
||||
|
||||
// With no reference lyrics, nothing classifies words as anchor/gap/corrected,
|
||||
// so every pill would render uncoloured and the line loses the colour-scanning
|
||||
// we rely on. Fall back to the gap-orange highlight for plain words in that
|
||||
@@ -111,8 +152,8 @@ export default function TranscriptionView({
|
||||
<h3 className="text-sm font-semibold">{t('syncedLyrics')}</h3>
|
||||
<ToggleGroup
|
||||
type="single"
|
||||
value={advancedMode ? 'advanced' : 'simple'}
|
||||
onValueChange={(value) => value && onAdvancedModeToggle?.(value === 'advanced')}
|
||||
value={viewMode}
|
||||
onValueChange={(value) => value && onViewModeChange?.(value as typeof viewMode)}
|
||||
className="h-7"
|
||||
>
|
||||
<ToggleGroupItem value="simple" aria-label="simple view" className="h-7 px-2.5 text-[0.75rem]">
|
||||
@@ -123,10 +164,35 @@ export default function TranscriptionView({
|
||||
<Clock className="h-3.5 w-3.5 mr-1.5" />
|
||||
{t('advanced')}
|
||||
</ToggleGroupItem>
|
||||
<ToggleGroupItem value="waveforms" aria-label="waveforms view" className="h-7 px-2.5 text-[0.75rem]">
|
||||
<AudioWaveform className="h-3.5 w-3.5 mr-1.5" />
|
||||
{t('waveforms')}
|
||||
</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
</div>
|
||||
|
||||
{(
|
||||
{waveformsMode ? (
|
||||
// Waveforms mode: an inline, compact copy of the Edit Segment timeline for every
|
||||
// segment — resizable word bars over the vocal waveform, with buffer padding +
|
||||
// boundary lines + greyed neighbour words. Lets the reviewer spot mis-timed words
|
||||
// (e.g. an over-long trailing word) at a glance without opening a modal per line.
|
||||
<div className="flex flex-col gap-[5px]">
|
||||
{data.corrected_segments.map((segment, segmentIndex) => (
|
||||
<WaveformSegmentRow
|
||||
key={segment.id}
|
||||
segment={segment}
|
||||
segmentIndex={segmentIndex}
|
||||
contextWords={contextWordsBySegment?.get(segmentIndex) ?? []}
|
||||
currentTime={currentTime}
|
||||
wordDecorations={decorationsBySegment?.get(segment.id) ?? new Map()}
|
||||
onCommit={(idx, updated) => onCommitSegment?.(idx, updated)}
|
||||
onPlaySegment={onPlaySegment}
|
||||
onEditSegment={(idx) => onEditSegment?.(idx)}
|
||||
onDeleteSegment={handleDeleteSegment}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
// Advanced rows are full-width pill timelines, so give them a bit
|
||||
// more breathing room between lines to match Simple's rhythm.
|
||||
<div className={cn('flex flex-col', advancedMode ? 'gap-2' : 'gap-0.5')}>
|
||||
|
||||
@@ -1,10 +1,20 @@
|
||||
import { AudioData, AudioNotReadyError, fetchAudioData } from '@/lib/audio-data'
|
||||
import { AudioData, AudioNotReadyError, fetchAudioData, fetchVocalsPeaks, isTransientAudioError } from '@/lib/audio-data'
|
||||
import { reportDegradationEvent } from '@/lib/degradation-events'
|
||||
import { createContext, PropsWithChildren, useEffect, useState } from 'react'
|
||||
|
||||
// A first paint whose waveform strips took longer than this to appear counts as
|
||||
// a degraded experience worth recording (Andrew's "wait 1+ minutes" complaint).
|
||||
// Excludes legitimate separation-in-progress waits shorter than one 202 poll.
|
||||
const SLOW_LOAD_REPORT_MS = 20_000
|
||||
|
||||
export const VocalsAudioDataLoaderContext = createContext<{ audioData: AudioData | null }>({ audioData: null })
|
||||
|
||||
export interface AudioDataLoaderProps extends PropsWithChildren {
|
||||
audioUrl: string | null
|
||||
/** Pre-computed peak-envelope endpoint (~150 KB JSON). Preferred over
|
||||
* downloading + decoding the whole stem from audioUrl; when it fails
|
||||
* terminally the loader falls back to the full audio decode. */
|
||||
peaksUrl?: string | null
|
||||
}
|
||||
|
||||
// Audio separation runs in the background while the user reviews lyrics, so the
|
||||
@@ -14,42 +24,84 @@ export interface AudioDataLoaderProps extends PropsWithChildren {
|
||||
const NOT_READY_RETRY_MS = 15_000
|
||||
const NOT_READY_MAX_RETRIES = 40 // 40 × 15s = 10 minutes
|
||||
|
||||
export const VocalsAudioDataLoader = ({ audioUrl, children }: AudioDataLoaderProps) => {
|
||||
// Transient failures (a 500/timeout while the backend is briefly overloaded —
|
||||
// e.g. many review tabs opened at once) previously gave up silently, leaving the
|
||||
// Waveforms view stripless until a manual reload. Retry a few times with backoff.
|
||||
const TRANSIENT_RETRY_DELAYS_MS = [5_000, 15_000, 30_000, 60_000]
|
||||
|
||||
export const VocalsAudioDataLoader = ({ audioUrl, peaksUrl, children }: AudioDataLoaderProps) => {
|
||||
const [audioData, setAudioData] = useState<AudioData | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (!audioUrl) return
|
||||
if (!audioUrl && !peaksUrl) return
|
||||
|
||||
// Guard against (a) an unhandled rejection when the endpoint 404s (no vocal
|
||||
// stem for this job) and (b) a stale in-flight fetch resolving after a newer
|
||||
// audioUrl has already been set.
|
||||
let cancelled = false
|
||||
let retryTimer: ReturnType<typeof setTimeout> | undefined
|
||||
const startedAt = Date.now()
|
||||
|
||||
const load = (attempt: number) => {
|
||||
fetchAudioData(audioUrl)
|
||||
const load = (attempt: number, transientAttempt: number, usePeaks: boolean) => {
|
||||
const source =
|
||||
usePeaks && peaksUrl ? fetchVocalsPeaks(peaksUrl) : fetchAudioData(audioUrl!)
|
||||
source
|
||||
.then((audioData) => {
|
||||
if (!cancelled) setAudioData(audioData)
|
||||
if (cancelled) return
|
||||
const elapsedMs = Date.now() - startedAt
|
||||
if (elapsedMs >= SLOW_LOAD_REPORT_MS) {
|
||||
reportDegradationEvent('waveform_slow', {
|
||||
elapsed_ms: elapsedMs,
|
||||
not_ready_polls: attempt,
|
||||
transient_retries: transientAttempt,
|
||||
used_peaks: usePeaks,
|
||||
})
|
||||
}
|
||||
setAudioData(audioData)
|
||||
})
|
||||
.catch((error) => {
|
||||
if (cancelled) return
|
||||
if (error instanceof AudioNotReadyError && attempt < NOT_READY_MAX_RETRIES) {
|
||||
retryTimer = setTimeout(() => load(attempt + 1), NOT_READY_RETRY_MS)
|
||||
retryTimer = setTimeout(() => load(attempt + 1, transientAttempt, usePeaks), NOT_READY_RETRY_MS)
|
||||
return
|
||||
}
|
||||
// Peaks get ONE quick retry, then we fall back to the audio path
|
||||
// (which has the full backoff ladder) — a flaky peaks endpoint
|
||||
// must not delay strips by the whole retry ladder first.
|
||||
const maxTransientRetries = usePeaks ? 1 : TRANSIENT_RETRY_DELAYS_MS.length
|
||||
if (isTransientAudioError(error) && transientAttempt < maxTransientRetries) {
|
||||
const delay = TRANSIENT_RETRY_DELAYS_MS[transientAttempt]
|
||||
console.warn(`Vocals ${usePeaks ? 'peaks' : 'audio'} load failed, retrying in ${delay / 1000}s`, error)
|
||||
retryTimer = setTimeout(() => load(attempt, transientAttempt + 1, usePeaks), delay)
|
||||
return
|
||||
}
|
||||
if (usePeaks && audioUrl) {
|
||||
// Peaks endpoint terminally failed (or exhausted retries) —
|
||||
// fall back to the original full-download-and-decode path so a
|
||||
// peaks-side problem never costs the user their waveforms.
|
||||
console.warn('Vocals peaks unavailable, falling back to full audio decode', error)
|
||||
load(attempt, 0, false)
|
||||
return
|
||||
}
|
||||
console.error('Failed to load vocals audio data', error)
|
||||
reportDegradationEvent('waveform_failed', {
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
elapsed_ms: Date.now() - startedAt,
|
||||
not_ready_polls: attempt,
|
||||
transient_retries: transientAttempt,
|
||||
})
|
||||
setAudioData(null)
|
||||
})
|
||||
}
|
||||
|
||||
load(0)
|
||||
load(0, 0, Boolean(peaksUrl))
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
if (retryTimer) clearTimeout(retryTimer)
|
||||
setAudioData(null)
|
||||
}
|
||||
}, [audioUrl])
|
||||
}, [audioUrl, peaksUrl])
|
||||
|
||||
return (
|
||||
<VocalsAudioDataLoaderContext.Provider value={{ audioData }}>
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
'use client'
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Play, Trash2 } from 'lucide-react'
|
||||
import { LyricsSegment, Word } from '@/lib/lyrics-review/types'
|
||||
import TimelineEditor from './TimelineEditor'
|
||||
import { recomputeSegmentFromWords } from '@/lib/lyrics-review/utils/segmentTiming'
|
||||
import { WordDecoration } from '@/lib/lyrics-review/utils/wordDecorations'
|
||||
import { useAudioReady } from '@/lib/lyrics-review/hooks/useAudioReady'
|
||||
|
||||
interface WaveformSegmentRowProps {
|
||||
segment: LyricsSegment
|
||||
segmentIndex: number
|
||||
/** Neighbouring segments' words within the padded window, greyed/read-only for context. */
|
||||
contextWords: Word[]
|
||||
/** Per-word bar colour + AI-correction ghost text, keyed by word id. */
|
||||
wordDecorations: Map<string, WordDecoration>
|
||||
currentTime?: number
|
||||
/** Fires on drag release with the segment's recomputed word timings + bounds. */
|
||||
onCommit: (segmentIndex: number, updatedSegment: LyricsSegment) => void
|
||||
onPlaySegment?: (time: number) => void
|
||||
/** Open the full Edit modal for structural edits (text / split / merge / add / delete). */
|
||||
onEditSegment: (segmentIndex: number) => void
|
||||
/** Delete the whole segment (matches the Advanced view's trash control). */
|
||||
onDeleteSegment: (segmentIndex: number) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* A single row of the Waveforms review mode: a compact, inline copy of the Edit Segment
|
||||
* timeline (resizable word bars over the vocal waveform, with buffer padding + boundary
|
||||
* lines + greyed neighbour words). Drag/resize edits the word timing and persists on
|
||||
* release; the segment number / pencil open the modal for everything else.
|
||||
*
|
||||
* Word edits are held in local state during a drag so only this row re-renders (not the
|
||||
* whole list) and so a mousemove-per-pixel doesn't flood the undo history — we commit once
|
||||
* on drag end.
|
||||
*/
|
||||
export default function WaveformSegmentRow({
|
||||
segment,
|
||||
segmentIndex,
|
||||
contextWords,
|
||||
wordDecorations,
|
||||
currentTime,
|
||||
onCommit,
|
||||
onPlaySegment,
|
||||
onEditSegment,
|
||||
onDeleteSegment,
|
||||
}: WaveformSegmentRowProps) {
|
||||
const t = useTranslations('lyricsReview.transcription')
|
||||
const tHeader = useTranslations('lyricsReview.header')
|
||||
const { ready: audioReady } = useAudioReady()
|
||||
|
||||
// Local working copy of the words, re-seeded whenever the segment changes upstream
|
||||
// (undo/redo, modal save, auto-correct). `segment` is referentially stable between
|
||||
// unrelated re-renders (e.g. playback time ticks), so this does not clobber an
|
||||
// in-progress drag — commits only happen on drag release, when no drag is active.
|
||||
const [words, setWords] = useState<Word[]>(segment.words)
|
||||
// Mirror of `words` that is always current, so handleCommit (fired from a mouse-up event
|
||||
// handler) can read the latest timings without listing `words` as a dep — and, crucially,
|
||||
// without calling the parent's setState from inside a setWords updater (which React runs
|
||||
// during render, triggering the "setState while rendering another component" warning).
|
||||
const wordsRef = useRef(words)
|
||||
useEffect(() => {
|
||||
setWords(segment.words)
|
||||
wordsRef.current = segment.words
|
||||
}, [segment])
|
||||
|
||||
const handleWordUpdate = useCallback((index: number, updates: Partial<Word>) => {
|
||||
const next = wordsRef.current.map((w, i) => (i === index ? { ...w, ...updates } : w))
|
||||
wordsRef.current = next
|
||||
setWords(next)
|
||||
}, [])
|
||||
|
||||
const handleCommit = useCallback(() => {
|
||||
onCommit(segmentIndex, recomputeSegmentFromWords(segment, wordsRef.current))
|
||||
}, [segment, segmentIndex, onCommit])
|
||||
|
||||
const startTime = segment.start_time ?? 0
|
||||
const endTime = segment.end_time ?? startTime + 1
|
||||
const hasTimedWords = words.some((w) => w.start_time !== null && w.end_time !== null)
|
||||
|
||||
return (
|
||||
<div className="flex items-start w-full gap-1">
|
||||
{/* Left controls: index (opens modal), play, edit */}
|
||||
{/* Left controls match the Advanced view: index, delete, play. */}
|
||||
<div className="flex items-center gap-0.5 pr-1 h-[20px]" style={{ minWidth: '2.5em' }}>
|
||||
<span
|
||||
className="text-muted-foreground w-[1.8em] text-right mr-1 select-none font-mono text-[0.8rem] leading-tight cursor-pointer hover:underline"
|
||||
onClick={() => onEditSegment(segmentIndex)}
|
||||
title={t('editSegment', { index: segmentIndex })}
|
||||
>
|
||||
{segmentIndex}
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-[18px] w-[18px] min-h-0 min-w-0 p-[1px] text-destructive hover:text-destructive"
|
||||
onClick={() => onDeleteSegment(segmentIndex)}
|
||||
title={t('deleteSegment')}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
{segment.start_time !== null && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-[18px] w-[18px] min-h-0 min-w-0 p-[1px]"
|
||||
onClick={() => onPlaySegment?.(segment.start_time!)}
|
||||
disabled={!audioReady}
|
||||
title={audioReady ? t('playSegment') : tHeader('audioStillLoading')}
|
||||
>
|
||||
<Play className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Inline timeline (waveform + resizable word bars), ruler hidden for compactness */}
|
||||
<div className="flex-1 min-w-0">
|
||||
{hasTimedWords ? (
|
||||
<TimelineEditor
|
||||
words={words}
|
||||
contextWords={contextWords}
|
||||
startTime={startTime}
|
||||
endTime={endTime}
|
||||
onWordUpdate={handleWordUpdate}
|
||||
onCommit={handleCommit}
|
||||
onWordClick={() => onEditSegment(segmentIndex)}
|
||||
currentTime={currentTime}
|
||||
onPlaySegment={onPlaySegment}
|
||||
showRuler={false}
|
||||
compact
|
||||
wordDecorations={wordDecorations}
|
||||
/>
|
||||
) : (
|
||||
<div
|
||||
className="text-sm text-muted-foreground italic px-2 py-2 cursor-pointer hover:underline"
|
||||
onClick={() => onEditSegment(segmentIndex)}
|
||||
>
|
||||
{segment.text || t('untimedSegment')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -153,7 +153,7 @@ describe('ReviewChangesModal', () => {
|
||||
data={makeData({ corrected_segments: segments as any, instrumental_options: bothStems as any })}
|
||||
/>
|
||||
)
|
||||
expect(screen.getByText(/click to hear this part/i)).toBeInTheDocument()
|
||||
expect(screen.getByText(/kept in the instrumental — click to hear them/i)).toBeInTheDocument()
|
||||
expect(apiClient.getWaveformData).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@@ -174,11 +174,11 @@ describe('ReviewChangesModal', () => {
|
||||
})}
|
||||
/>
|
||||
)
|
||||
expect(screen.queryByText(/click to hear this part/i)).not.toBeInTheDocument()
|
||||
expect(screen.queryByText(/click to hear/i)).not.toBeInTheDocument()
|
||||
expect(apiClient.getWaveformData).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not render the backing-vocals waveform when clean is the current selection', () => {
|
||||
it('still renders the backing-vocals waveform when clean is selected (so it is not discarded unseen)', () => {
|
||||
const segments = [{ text: 'Hello', words: [], start_time: 0, end_time: 1 }]
|
||||
const apiClient = waveformApiClient()
|
||||
render(
|
||||
@@ -192,7 +192,9 @@ describe('ReviewChangesModal', () => {
|
||||
data={makeData({ corrected_segments: segments as any, instrumental_options: bothStems as any })}
|
||||
/>
|
||||
)
|
||||
expect(screen.queryByText(/click to hear this part/i)).not.toBeInTheDocument()
|
||||
// With clean selected the waveform shows the backing vocals the clean stem removes.
|
||||
expect(screen.getByText(/removes — click to hear what you'd be leaving out/i)).toBeInTheDocument()
|
||||
expect(apiClient.getWaveformData).toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('calls onSubmit when button clicked with valid segments', async () => {
|
||||
@@ -342,7 +344,7 @@ describe('ReviewChangesModal', () => {
|
||||
expect(
|
||||
screen.getByRole('radio', { name: /advanced mode \(review or upload a custom instrumental\)/i })
|
||||
).toBeInTheDocument()
|
||||
expect(screen.getByText(/we'll use the clean instrumental/i)).toBeInTheDocument()
|
||||
expect(screen.getByText(/the clean instrumental removes the backing vocals shown below/i)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('selecting Advanced mode calls onToggleReviewInstrumental', async () => {
|
||||
|
||||
@@ -38,6 +38,9 @@ function makeMockApiClient(): LyricsReviewApiClient {
|
||||
searchLyrics: jest.fn(),
|
||||
getAudioUrl: jest.fn(),
|
||||
getVocalsAudioUrl: jest.fn(),
|
||||
getVocalsPeaksUrl: jest.fn(),
|
||||
getWaveformData: jest.fn(),
|
||||
refreshInstrumentalUrls: jest.fn(),
|
||||
generatePreviewVideo: jest.fn(),
|
||||
getPreviewVideoStatus: jest.fn(),
|
||||
getPreviewVideoUrl: jest.fn(),
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { act, render, screen } from '@testing-library/react'
|
||||
import { useContext } from 'react'
|
||||
import { AudioData, AudioNotReadyError, fetchAudioData as fetchAudioDataImport } from '@/lib/audio-data'
|
||||
import { AudioData, AudioFetchError, AudioNotReadyError, fetchAudioData as fetchAudioDataImport } from '@/lib/audio-data'
|
||||
import { VocalsAudioDataLoader, VocalsAudioDataLoaderContext } from '../VocalsAudioDataLoader'
|
||||
|
||||
jest.mock('@/lib/audio-data', () => {
|
||||
const actual = jest.requireActual('@/lib/audio-data')
|
||||
return { ...actual, fetchAudioData: jest.fn() }
|
||||
return { ...actual, fetchAudioData: jest.fn(), fetchVocalsPeaks: jest.fn() }
|
||||
})
|
||||
|
||||
const fetchAudioData = fetchAudioDataImport as jest.Mock
|
||||
@@ -97,6 +97,77 @@ describe('VocalsAudioDataLoader', () => {
|
||||
consoleError.mockRestore()
|
||||
})
|
||||
|
||||
it('retries a transient failure (500 under load) with backoff, then loads', async () => {
|
||||
// Ten review tabs at once can briefly 500 this endpoint; giving up silently
|
||||
// left the Waveforms view stripless until a manual reload.
|
||||
fetchAudioData
|
||||
.mockRejectedValueOnce(new AudioFetchError(500))
|
||||
.mockResolvedValue(AUDIO_DATA)
|
||||
const consoleWarn = jest.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
|
||||
render(
|
||||
<VocalsAudioDataLoader audioUrl="https://api/audio/vocals">
|
||||
<Probe />
|
||||
</VocalsAudioDataLoader>
|
||||
)
|
||||
await flushPromises()
|
||||
expect(screen.getByTestId('probe')).toHaveTextContent('empty')
|
||||
|
||||
await act(async () => {
|
||||
jest.advanceTimersByTime(5_000)
|
||||
})
|
||||
expect(fetchAudioData).toHaveBeenCalledTimes(2)
|
||||
expect(screen.getByTestId('probe')).toHaveTextContent('loaded')
|
||||
|
||||
consoleWarn.mockRestore()
|
||||
})
|
||||
|
||||
it('gives up after exhausting transient retries', async () => {
|
||||
fetchAudioData.mockRejectedValue(new AudioFetchError(503))
|
||||
const consoleWarn = jest.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
const consoleError = jest.spyOn(console, 'error').mockImplementation(() => {})
|
||||
|
||||
render(
|
||||
<VocalsAudioDataLoader audioUrl="https://api/audio/vocals">
|
||||
<Probe />
|
||||
</VocalsAudioDataLoader>
|
||||
)
|
||||
await flushPromises()
|
||||
|
||||
// 5s + 15s + 30s + 60s of backoff = 4 retries after the initial attempt.
|
||||
for (const delay of [5_000, 15_000, 30_000, 60_000, 120_000]) {
|
||||
await act(async () => {
|
||||
jest.advanceTimersByTime(delay)
|
||||
})
|
||||
}
|
||||
expect(fetchAudioData).toHaveBeenCalledTimes(5)
|
||||
expect(screen.getByTestId('probe')).toHaveTextContent('empty')
|
||||
expect(consoleError).toHaveBeenCalled()
|
||||
|
||||
consoleWarn.mockRestore()
|
||||
consoleError.mockRestore()
|
||||
})
|
||||
|
||||
it('does not retry a 404 (AudioFetchError, terminal)', async () => {
|
||||
fetchAudioData.mockRejectedValue(new AudioFetchError(404))
|
||||
const consoleError = jest.spyOn(console, 'error').mockImplementation(() => {})
|
||||
|
||||
render(
|
||||
<VocalsAudioDataLoader audioUrl="https://api/audio/vocals">
|
||||
<Probe />
|
||||
</VocalsAudioDataLoader>
|
||||
)
|
||||
await flushPromises()
|
||||
|
||||
await act(async () => {
|
||||
jest.advanceTimersByTime(120_000)
|
||||
})
|
||||
expect(fetchAudioData).toHaveBeenCalledTimes(1)
|
||||
expect(screen.getByTestId('probe')).toHaveTextContent('empty')
|
||||
|
||||
consoleError.mockRestore()
|
||||
})
|
||||
|
||||
it('stops polling on unmount', async () => {
|
||||
fetchAudioData.mockRejectedValue(new AudioNotReadyError())
|
||||
|
||||
@@ -114,3 +185,108 @@ describe('VocalsAudioDataLoader', () => {
|
||||
expect(fetchAudioData).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('VocalsAudioDataLoader peaks-first behavior', () => {
|
||||
const audioDataLib = jest.requireMock('@/lib/audio-data')
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks()
|
||||
jest.useFakeTimers()
|
||||
audioDataLib.fetchVocalsPeaks = jest.fn()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
jest.useRealTimers()
|
||||
})
|
||||
|
||||
it('prefers the peaks endpoint and never downloads the full audio', async () => {
|
||||
audioDataLib.fetchVocalsPeaks.mockResolvedValue(AUDIO_DATA)
|
||||
|
||||
render(
|
||||
<VocalsAudioDataLoader audioUrl="https://api/audio/vocals" peaksUrl="https://api/vocals-peaks">
|
||||
<Probe />
|
||||
</VocalsAudioDataLoader>
|
||||
)
|
||||
await flushPromises()
|
||||
|
||||
expect(screen.getByTestId('probe')).toHaveTextContent('loaded')
|
||||
expect(audioDataLib.fetchVocalsPeaks).toHaveBeenCalledTimes(1)
|
||||
expect(fetchAudioData).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('falls back to full audio decode when peaks fail terminally', async () => {
|
||||
audioDataLib.fetchVocalsPeaks.mockRejectedValue(new AudioFetchError(404))
|
||||
fetchAudioData.mockResolvedValue(AUDIO_DATA)
|
||||
const consoleWarn = jest.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
|
||||
render(
|
||||
<VocalsAudioDataLoader audioUrl="https://api/audio/vocals" peaksUrl="https://api/vocals-peaks">
|
||||
<Probe />
|
||||
</VocalsAudioDataLoader>
|
||||
)
|
||||
await flushPromises()
|
||||
|
||||
expect(fetchAudioData).toHaveBeenCalledTimes(1)
|
||||
expect(screen.getByTestId('probe')).toHaveTextContent('loaded')
|
||||
consoleWarn.mockRestore()
|
||||
})
|
||||
|
||||
it('retries peaks once on a transient error, then falls back to audio', async () => {
|
||||
audioDataLib.fetchVocalsPeaks.mockRejectedValue(new AudioFetchError(503))
|
||||
fetchAudioData.mockResolvedValue(AUDIO_DATA)
|
||||
const consoleWarn = jest.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
|
||||
render(
|
||||
<VocalsAudioDataLoader audioUrl="https://api/audio/vocals" peaksUrl="https://api/vocals-peaks">
|
||||
<Probe />
|
||||
</VocalsAudioDataLoader>
|
||||
)
|
||||
await flushPromises()
|
||||
expect(audioDataLib.fetchVocalsPeaks).toHaveBeenCalledTimes(1)
|
||||
|
||||
// One quick retry of peaks...
|
||||
await act(async () => {
|
||||
jest.advanceTimersByTime(5_000)
|
||||
})
|
||||
expect(audioDataLib.fetchVocalsPeaks).toHaveBeenCalledTimes(2)
|
||||
// ...then immediate fallback to the audio path (no more peaks calls).
|
||||
expect(fetchAudioData).toHaveBeenCalledTimes(1)
|
||||
expect(screen.getByTestId('probe')).toHaveTextContent('loaded')
|
||||
|
||||
consoleWarn.mockRestore()
|
||||
})
|
||||
|
||||
it('polls peaks on 202 while separation is running', async () => {
|
||||
audioDataLib.fetchVocalsPeaks
|
||||
.mockRejectedValueOnce(new AudioNotReadyError())
|
||||
.mockResolvedValue(AUDIO_DATA)
|
||||
|
||||
render(
|
||||
<VocalsAudioDataLoader audioUrl="https://api/audio/vocals" peaksUrl="https://api/vocals-peaks">
|
||||
<Probe />
|
||||
</VocalsAudioDataLoader>
|
||||
)
|
||||
await flushPromises()
|
||||
expect(screen.getByTestId('probe')).toHaveTextContent('empty')
|
||||
|
||||
await act(async () => {
|
||||
jest.advanceTimersByTime(15_000)
|
||||
})
|
||||
expect(screen.getByTestId('probe')).toHaveTextContent('loaded')
|
||||
expect(fetchAudioData).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('works with only audioUrl (local mode without a peaks endpoint)', async () => {
|
||||
fetchAudioData.mockResolvedValue(AUDIO_DATA)
|
||||
|
||||
render(
|
||||
<VocalsAudioDataLoader audioUrl="https://api/audio/vocals">
|
||||
<Probe />
|
||||
</VocalsAudioDataLoader>
|
||||
)
|
||||
await flushPromises()
|
||||
|
||||
expect(screen.getByTestId('probe')).toHaveTextContent('loaded')
|
||||
expect(audioDataLib.fetchVocalsPeaks).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,71 @@
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import WaveformSegmentRow from '../WaveformSegmentRow'
|
||||
import { LyricsSegment } from '@/lib/lyrics-review/types'
|
||||
|
||||
const timedSegment: LyricsSegment = {
|
||||
id: 's0',
|
||||
text: 'No looking back',
|
||||
start_time: 140.6,
|
||||
end_time: 142.6,
|
||||
words: [
|
||||
{ id: 'w1', text: 'No', start_time: 140.6, end_time: 141.0, confidence: 1 },
|
||||
{ id: 'w2', text: 'looking', start_time: 141.0, end_time: 142.3, confidence: 1 },
|
||||
{ id: 'w3', text: 'back', start_time: 142.4, end_time: 142.6, confidence: 1 },
|
||||
],
|
||||
}
|
||||
|
||||
function renderRow(overrides: Partial<React.ComponentProps<typeof WaveformSegmentRow>> = {}) {
|
||||
const props = {
|
||||
segment: timedSegment,
|
||||
segmentIndex: 0,
|
||||
contextWords: [],
|
||||
wordDecorations: new Map(),
|
||||
onCommit: jest.fn(),
|
||||
onPlaySegment: jest.fn(),
|
||||
onEditSegment: jest.fn(),
|
||||
onDeleteSegment: jest.fn(),
|
||||
...overrides,
|
||||
}
|
||||
render(<WaveformSegmentRow {...props} />)
|
||||
return props
|
||||
}
|
||||
|
||||
describe('WaveformSegmentRow', () => {
|
||||
it('opens the edit modal when the segment index is clicked', async () => {
|
||||
const user = userEvent.setup()
|
||||
const props = renderRow()
|
||||
await user.click(screen.getByTitle('Edit segment 0'))
|
||||
expect(props.onEditSegment).toHaveBeenCalledWith(0)
|
||||
})
|
||||
|
||||
it('deletes the segment when the trash control is clicked', async () => {
|
||||
const user = userEvent.setup()
|
||||
const props = renderRow()
|
||||
await user.click(screen.getByTitle('Delete segment'))
|
||||
expect(props.onDeleteSegment).toHaveBeenCalledWith(0)
|
||||
})
|
||||
|
||||
it('renders a word bar per timed word', () => {
|
||||
renderRow()
|
||||
// Word text is rendered inside the draggable bars.
|
||||
expect(screen.getByText('No')).toBeInTheDocument()
|
||||
expect(screen.getByText('looking')).toBeInTheDocument()
|
||||
expect(screen.getByText('back')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows a clickable fallback (no timeline) for an untimed segment', async () => {
|
||||
const user = userEvent.setup()
|
||||
const untimed: LyricsSegment = {
|
||||
id: 's1',
|
||||
text: 'untimed line',
|
||||
start_time: null,
|
||||
end_time: null,
|
||||
words: [{ id: 'u1', text: 'untimed line', start_time: null, end_time: null, confidence: 1 }],
|
||||
}
|
||||
const props = renderRow({ segment: untimed, segmentIndex: 4 })
|
||||
const fallback = screen.getByText('untimed line')
|
||||
await user.click(fallback)
|
||||
expect(props.onEditSegment).toHaveBeenCalledWith(4)
|
||||
})
|
||||
})
|
||||
@@ -108,10 +108,11 @@ export default function ReviewChangesModal({
|
||||
const selected: 'clean' | 'with_backing' =
|
||||
currentSelection ?? recommendedSelection ?? (hasBackingStem ? 'with_backing' : 'clean')
|
||||
|
||||
// Only offer the backing waveform (which clicks through to the backing stem)
|
||||
// when that stem is playable and the reviewer is currently keeping backing.
|
||||
// Always show the backing-vocals waveform whenever a playable backing stem exists — even
|
||||
// when "clean" is selected — so the reviewer can see (and click to hear) the backing vocals
|
||||
// they'd be discarding, rather than accepting the clean default sight-unseen.
|
||||
const showBackingWaveform =
|
||||
!reviewInstrumentalAnyway && selected === 'with_backing' && hasBackingStem && !!getWaveformData
|
||||
!reviewInstrumentalAnyway && hasBackingStem && !!getWaveformData
|
||||
|
||||
const chooseInstrumental = (choice: 'clean' | 'with_backing') => {
|
||||
onToggleReviewInstrumental?.(false)
|
||||
@@ -251,6 +252,7 @@ export default function ReviewChangesModal({
|
||||
<BackingVocalsWaveform
|
||||
getWaveformData={getWaveformData}
|
||||
currentTime={previewTime}
|
||||
kept={selected === 'with_backing'}
|
||||
onSeek={(time) => previewRef.current?.auditionInstrumental('with_backing', time)}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -83,9 +83,15 @@ async function locateVisibleInFrames(
|
||||
* Complete the Stripe Checkout page with card details from environment.
|
||||
*
|
||||
* @param page - Playwright page that will be redirected to checkout.stripe.com
|
||||
* @returns void — after this, the page will redirect to the success URL
|
||||
* @returns `{ redirected }` — whether the browser was observed navigating back
|
||||
* to our success/app URL after payment. The redirect can be slow or dropped
|
||||
* even when the charge succeeds (Stripe→site hop, 3DS interstitial), so this
|
||||
* is reported rather than thrown: callers should treat the *server-side*
|
||||
* credit grant (Stripe webhook) as the source of truth and use `redirected`
|
||||
* only as a best-effort UX signal. Genuine failures (no Pay button, card
|
||||
* declined) still throw.
|
||||
*/
|
||||
export async function completeStripeCheckout(page: Page): Promise<void> {
|
||||
export async function completeStripeCheckout(page: Page): Promise<{ redirected: boolean }> {
|
||||
const card = getCardDetailsFromEnv();
|
||||
|
||||
// Step 1: Wait for Stripe Checkout page to fully load
|
||||
@@ -232,12 +238,26 @@ export async function completeStripeCheckout(page: Page): Promise<void> {
|
||||
await finalPay.click();
|
||||
|
||||
console.log(' Payment submitted, waiting for redirect...');
|
||||
// Wait for redirect back to our site
|
||||
await page.waitForURL(/nomadkaraoke\.com.*payment\/success|nomadkaraoke\.com.*\/app/, {
|
||||
timeout: 60_000,
|
||||
});
|
||||
await page.screenshot({ path: 'test-results/stripe-checkout-complete.png' });
|
||||
console.log(' Stripe Checkout complete — redirected to success page');
|
||||
// Wait for redirect back to our site. The charge itself completes on Stripe's
|
||||
// side and is confirmed to us via webhook; the browser redirect back is a
|
||||
// separate, sometimes-slow hop (and can stall on a 3DS interstitial). So a
|
||||
// redirect timeout is NOT a payment failure — report it and let the caller
|
||||
// verify the credit grant server-side instead of failing the whole test.
|
||||
try {
|
||||
await page.waitForURL(/nomadkaraoke\.com.*payment\/success|nomadkaraoke\.com.*\/app/, {
|
||||
timeout: 60_000,
|
||||
});
|
||||
await page.screenshot({ path: 'test-results/stripe-checkout-complete.png' });
|
||||
console.log(' Stripe Checkout complete — redirected to success page');
|
||||
return { redirected: true };
|
||||
} catch {
|
||||
await page.screenshot({ path: 'test-results/stripe-checkout-no-redirect.png' });
|
||||
console.warn(
|
||||
' ⚠️ Payment submitted but no redirect within 60s — will verify the credit ' +
|
||||
'grant server-side (charge may have succeeded with a slow/dropped redirect)'
|
||||
);
|
||||
return { redirected: false };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// frontend/e2e/production/credit-purchase-real.spec.ts
|
||||
import { test, expect } from '@playwright/test';
|
||||
import type { APIRequestContext } from '@playwright/test';
|
||||
import { createEmailHelper, isEmailTestingAvailable } from '../helpers/email-testing';
|
||||
import { completeStripeCheckout } from '../helpers/stripe-checkout';
|
||||
import { getPageAuthToken, clickCompleteSignInGate } from '../helpers/auth';
|
||||
@@ -7,6 +8,53 @@ import { URLS, TIMEOUTS } from '../helpers/constants';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
|
||||
/**
|
||||
* Read a user's current credit balance via the read-only admin detail endpoint.
|
||||
* This is the server-side source of truth for whether a purchase landed —
|
||||
* independent of any browser redirect. Returns null if the lookup fails.
|
||||
*/
|
||||
async function getCreditsViaAdmin(
|
||||
request: APIRequestContext,
|
||||
apiBase: string,
|
||||
adminToken: string,
|
||||
email: string
|
||||
): Promise<number | null> {
|
||||
try {
|
||||
const res = await request.get(
|
||||
`${apiBase}/api/users/admin/users/${encodeURIComponent(email)}/detail`,
|
||||
{ headers: { 'X-Admin-Token': adminToken } }
|
||||
);
|
||||
if (!res.ok()) return null;
|
||||
const data = await res.json();
|
||||
return typeof data.credits === 'number' ? data.credits : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Poll the admin detail endpoint until the user's credit balance rises above
|
||||
* `baseline` — the Stripe webhook grants the purchased credit asynchronously,
|
||||
* so this can lag the payment by a few seconds. Returns the increased balance,
|
||||
* or null if it never rose within the timeout.
|
||||
*/
|
||||
async function waitForCreditIncrease(
|
||||
request: APIRequestContext,
|
||||
apiBase: string,
|
||||
adminToken: string,
|
||||
email: string,
|
||||
baseline: number,
|
||||
timeoutMs = 90_000
|
||||
): Promise<number | null> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (Date.now() < deadline) {
|
||||
const latest = await getCreditsViaAdmin(request, apiBase, adminToken, email);
|
||||
if (latest !== null && latest > baseline) return latest;
|
||||
await new Promise((r) => setTimeout(r, 3000));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* E2E Test: Real Credit Purchase via Stripe Checkout
|
||||
*
|
||||
@@ -169,27 +217,56 @@ test.describe('Real Credit Purchase Flow', () => {
|
||||
const buttonText = await checkoutButton.textContent();
|
||||
console.log(` Checkout button: "${buttonText}"`);
|
||||
|
||||
// Record the credit balance BEFORE paying, so we can assert the purchase
|
||||
// actually landed server-side (baseline + 1) regardless of the browser
|
||||
// redirect. Falls back to 0 if the admin lookup is unavailable.
|
||||
const baselineCredits = (await getCreditsViaAdmin(request, API_URL, adminToken!, inbox.emailAddress)) ?? 0;
|
||||
console.log(` Baseline credits before purchase: ${baselineCredits}`);
|
||||
|
||||
// ===== STEP 5: Proceed to Stripe Checkout =====
|
||||
console.log('\n=== STEP 5: Stripe Checkout ===');
|
||||
await checkoutButton.click();
|
||||
|
||||
// Complete Stripe Checkout with real card
|
||||
await completeStripeCheckout(page);
|
||||
// Complete Stripe Checkout with real card. The redirect back to our site
|
||||
// is best-effort — the authoritative signal is the server-side credit grant.
|
||||
const checkout = await completeStripeCheckout(page);
|
||||
|
||||
// ===== STEP 6: Verify payment success page =====
|
||||
console.log('\n=== STEP 6: Verify payment success ===');
|
||||
await page.waitForURL(/payment\/success/, { timeout: 30000 });
|
||||
// ===== STEP 6: Verify the purchase landed (server-side source of truth) =====
|
||||
console.log('\n=== STEP 6: Verify credit grant (server-side) ===');
|
||||
// Stripe's webhook grants the purchased credit asynchronously; poll for it.
|
||||
// This is the real pass/fail gate — a slow or dropped browser redirect must
|
||||
// NOT fail a purchase that actually succeeded (the historical E2E flake).
|
||||
const newBalance = await waitForCreditIncrease(
|
||||
request, API_URL, adminToken!, inbox.emailAddress, baselineCredits
|
||||
);
|
||||
expect(
|
||||
newBalance,
|
||||
`Credit balance did not increase above ${baselineCredits} within 90s after payment — ` +
|
||||
`the Stripe webhook / credit grant did not complete (this IS a real failure, ` +
|
||||
`unlike a slow browser redirect)`
|
||||
).not.toBeNull();
|
||||
console.log(` ✅ Server-side credit grant confirmed: ${baselineCredits} → ${newBalance}`);
|
||||
|
||||
// Verify success indicators
|
||||
const successText = page.getByText(/payment successful/i);
|
||||
await expect(successText).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
|
||||
// Verify credit balance is shown — the number and "credits available"
|
||||
// may be in separate DOM elements, so check for each independently
|
||||
const creditsAvailableText = page.getByText(/credits?\s+available/i);
|
||||
await expect(creditsAvailableText).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
await page.screenshot({ path: 'test-results/06-payment-success.png' });
|
||||
console.log(' Payment success page confirmed with credits');
|
||||
// Best-effort UX check: if the browser redirected to the success page,
|
||||
// confirm it renders the expected confirmation. A missing redirect is only
|
||||
// a UX nicety here (the charge + grant are already proven above), so don't
|
||||
// fail the test on it.
|
||||
if (checkout.redirected) {
|
||||
const onSuccessPage = await page
|
||||
.waitForURL(/payment\/success/, { timeout: 30000 })
|
||||
.then(() => true)
|
||||
.catch(() => false);
|
||||
if (onSuccessPage) {
|
||||
const successText = page.getByText(/payment successful/i);
|
||||
await expect(successText).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
const creditsAvailableText = page.getByText(/credits?\s+available/i);
|
||||
await expect(creditsAvailableText).toBeVisible({ timeout: TIMEOUTS.action });
|
||||
await page.screenshot({ path: 'test-results/06-payment-success.png' });
|
||||
console.log(' Payment success page confirmed with credits');
|
||||
}
|
||||
} else {
|
||||
console.log(' ⚠️ No browser redirect observed — skipping success-page UX assertions (grant already verified above)');
|
||||
}
|
||||
|
||||
// ===== STEP 7: Verify via API =====
|
||||
console.log('\n=== STEP 7: Verify credits via API ===');
|
||||
|
||||
@@ -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
|
||||
@@ -129,6 +130,54 @@ async function getAuthToken(page: Page): Promise<string | null> {
|
||||
return await page.evaluate(() => localStorage.getItem('karaoke_access_token'));
|
||||
}
|
||||
|
||||
// States a job sits in WHILE it is waiting for the reviewer to finish. Leaving
|
||||
// these means the review-completion POST (/api/review/{id}/complete) landed.
|
||||
const REVIEW_WAIT_STATES = ['awaiting_review', 'in_review'];
|
||||
|
||||
/**
|
||||
* Read a job's backend status via the API (as the job owner, falling back to the
|
||||
* admin token), independent of any UI rendering.
|
||||
*/
|
||||
async function getJobStatus(page: Page, jobId: string): Promise<string> {
|
||||
const token = await getAuthToken(page);
|
||||
const headers: Record<string, string> = {};
|
||||
if (token) headers['Authorization'] = `Bearer ${token}`;
|
||||
else if (process.env.E2E_ADMIN_TOKEN) headers['X-Admin-Token'] = process.env.E2E_ADMIN_TOKEN;
|
||||
const res = await page.request.get(`${API_URL}/api/jobs/${jobId}`, { headers });
|
||||
if (!res.ok()) throw new Error(`GET /api/jobs/${jobId} → ${res.status()}`);
|
||||
const job = await res.json();
|
||||
return String(job?.status || '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert that a review-completion submit actually advanced the job past the
|
||||
* review-wait states. A job frozen at `in_review`/`awaiting_review` means the
|
||||
* approval POST never landed — historically the Stage-2 "flake" surfaced ~40 min
|
||||
* later as a misleading "Timeout waiting for job completion". Verifying the
|
||||
* transition here fails LOUD at the submit step with an actionable message, and
|
||||
* lets the caller retry the submit deterministically instead of tolerating flake.
|
||||
*/
|
||||
async function assertReviewSubmitted(page: Page, jobId: string, timeoutMs = 90_000): Promise<void> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
let last = '';
|
||||
while (Date.now() < deadline) {
|
||||
last = await getJobStatus(page, jobId).catch((e) => {
|
||||
console.log(` review-status poll error: ${e}`);
|
||||
return '';
|
||||
});
|
||||
if (last && !REVIEW_WAIT_STATES.includes(last.toLowerCase())) {
|
||||
console.log(` Review submit confirmed — job advanced to "${last}"`);
|
||||
return;
|
||||
}
|
||||
await page.waitForTimeout(3000);
|
||||
}
|
||||
throw new Error(
|
||||
`Review submit did not advance job ${jobId} past review (still "${last}") after ` +
|
||||
`${Math.round(timeoutMs / 1000)}s — the completeReview POST never landed. This is a ` +
|
||||
`review-submit failure, NOT a slow render.`
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Navigate to a URL with retry logic for transient network errors.
|
||||
* Production tests can hit ERR_INTERNET_DISCONNECTED or similar when opening new pages.
|
||||
@@ -139,7 +188,12 @@ async function gotoWithRetry(
|
||||
options: { waitUntil?: 'networkidle' | 'load' | 'domcontentloaded'; timeout?: number } = {},
|
||||
maxRetries = 3
|
||||
): Promise<void> {
|
||||
const { waitUntil = 'networkidle', timeout = 60000 } = options;
|
||||
// Default to 'domcontentloaded': this is a long-polling SPA that keeps
|
||||
// connections open, so 'networkidle' frequently never settles and the goto
|
||||
// times out at 60s (a real Stage-2 retry failure, run #170). Callers that need
|
||||
// a stronger wait pass waitUntil explicitly; they also assert on concrete
|
||||
// elements after navigating, so they don't rely on network-idle for readiness.
|
||||
const { waitUntil = 'domcontentloaded', timeout = 60000 } = options;
|
||||
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
||||
try {
|
||||
await page.goto(url, { waitUntil, timeout });
|
||||
@@ -168,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,
|
||||
@@ -207,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
|
||||
@@ -241,15 +360,25 @@ test.describe('E2E Happy Path - Real User with Full UI Interactions', () => {
|
||||
accessToken = getPreConfiguredToken();
|
||||
console.log(` Using token: ${accessToken.substring(0, 8)}...`);
|
||||
|
||||
// Navigate to app and inject token into localStorage
|
||||
await gotoWithRetry(page, `${PROD_URL}/app`);
|
||||
await page.evaluate((token) => {
|
||||
localStorage.setItem('karaoke_access_token', token);
|
||||
// Seed the auth token via addInitScript BEFORE navigating, so the app is
|
||||
// authenticated on first load with NO evaluate-after-navigation race.
|
||||
// The previous "goto → page.evaluate(setItem) → reload" pattern raced the
|
||||
// /app client-side redirect and threw "Execution context was destroyed"
|
||||
// once gotoWithRetry began returning on 'domcontentloaded' (PR #1003)
|
||||
// instead of waiting for network idle — which broke the post-deploy canary.
|
||||
// addInitScript runs before page scripts on every navigation, so no reload
|
||||
// or post-nav evaluate is needed.
|
||||
await page.addInitScript((token) => {
|
||||
try { window.localStorage.setItem('karaoke_access_token', token); } catch {}
|
||||
}, accessToken);
|
||||
|
||||
// Reload to apply the token
|
||||
await page.reload();
|
||||
await page.waitForLoadState('networkidle');
|
||||
await gotoWithRetry(page, `${PROD_URL}/app`);
|
||||
// Wait for authentication to RESOLVE, not just the load event. The app reads
|
||||
// the seeded token on load and fetchUser() then populates the credit
|
||||
// indicator; sampling AuthStatus while fetchUser() is still pending would
|
||||
// catch a transient "Login" and misclassify a valid token. The canary user
|
||||
// always has credits, so the credit indicator is the authenticated signal.
|
||||
await expect(page.getByText(/\d+\s+credits?/i).first())
|
||||
.toBeVisible({ timeout: TIMEOUTS.action });
|
||||
|
||||
await page.screenshot({ path: 'test-results/02-token-injected.png' });
|
||||
console.log('STEP 2 COMPLETE: Token injected, skipping signup');
|
||||
@@ -528,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}`);
|
||||
}
|
||||
}
|
||||
@@ -852,6 +982,9 @@ test.describe('E2E Happy Path - Real User with Full UI Interactions', () => {
|
||||
}
|
||||
if (completionOutcome === 'completed') {
|
||||
console.log(' Review completed (redirected to /app)');
|
||||
// The /app redirect implies success, but confirm the backend actually
|
||||
// advanced the job — a stale UI redirect must not mask a lost submit.
|
||||
if (jobId) await assertReviewSubmitted(reviewPage, jobId, 60_000);
|
||||
} else if (completionOutcome === 'fallback') {
|
||||
console.log(' WARNING: Inline completion failed — product fell back to the instrumental screen; continuing with Step 8');
|
||||
needsInstrumentalScreen = true;
|
||||
@@ -925,6 +1058,26 @@ test.describe('E2E Happy Path - Real User with Full UI Interactions', () => {
|
||||
|
||||
await reviewPage.screenshot({ path: 'test-results/08c-instrumental-submitted.png', fullPage: true });
|
||||
|
||||
// Deterministically confirm the submit landed (job left the review states).
|
||||
// Previously this step just clicked + slept, so a dropped click / swallowed
|
||||
// completeReview left the job frozen at in_review and failed 40 min later at
|
||||
// "job completion". Verify the transition here and retry the submit ONCE
|
||||
// before failing loud — no flake tolerance.
|
||||
if (jobId) {
|
||||
try {
|
||||
await assertReviewSubmitted(reviewPage, jobId, 60_000);
|
||||
} catch (e) {
|
||||
console.log(` WARNING: ${e instanceof Error ? e.message : e}`);
|
||||
console.log(' Retrying instrumental submit once...');
|
||||
if (await submitBtn.isVisible().catch(() => false)) {
|
||||
await submitBtn.click();
|
||||
console.log(' Re-clicked "Confirm & Continue"');
|
||||
}
|
||||
await reviewPage.waitForTimeout(3000);
|
||||
await assertReviewSubmitted(reviewPage, jobId, 60_000);
|
||||
}
|
||||
}
|
||||
|
||||
// The page redirects to /app after completion, or may close
|
||||
// Wait a bit for the redirect/close to happen
|
||||
if (!reviewPage.isClosed()) {
|
||||
@@ -1222,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,158 @@
|
||||
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+$/);
|
||||
});
|
||||
|
||||
// Concurrent-load hardening (v0.230.0): vocals byte proxy + cached waveform-data.
|
||||
test('vocals audio serves with Range support and cache headers', async ({ request }) => {
|
||||
const url = proxyUrl(`/api/review/${JOB_ID}/audio/vocals`);
|
||||
|
||||
const full = await request.get(url);
|
||||
console.log(`audio/vocals status=${full.status()} type=${full.headers()['content-type']}`);
|
||||
expect(full.ok()).toBeTruthy();
|
||||
expect(full.headers()['content-type']).toMatch(/audio\//);
|
||||
expect(full.headers()['accept-ranges']).toBe('bytes');
|
||||
expect(full.headers()['cache-control']).toContain('max-age');
|
||||
|
||||
const ranged = await request.get(url, { headers: { Range: 'bytes=0-1023' } });
|
||||
expect(ranged.status()).toBe(206);
|
||||
expect(ranged.headers()['content-range']).toMatch(/^bytes 0-\d+\/\d+$/);
|
||||
expect((await ranged.body()).length).toBe(1024);
|
||||
});
|
||||
|
||||
test('waveform-data returns quickly from the persistent cache', async ({ request }) => {
|
||||
const base = `${API_URL}/api/review/${JOB_ID}/waveform-data`;
|
||||
const url = REVIEW_TOKEN ? `${base}?review_token=${encodeURIComponent(REVIEW_TOKEN)}` : base;
|
||||
|
||||
// First call may compute+cache (bounded, off the event loop); the second
|
||||
// must be a pure GCS-cache read and come back fast.
|
||||
const warm = await request.get(url, { headers: authHeaders() });
|
||||
expect(warm.ok()).toBeTruthy();
|
||||
|
||||
const started = Date.now();
|
||||
const res = await request.get(url, { headers: authHeaders() });
|
||||
const elapsedMs = Date.now() - started;
|
||||
console.log(`waveform-data (cached) status=${res.status()} elapsed=${elapsedMs}ms`);
|
||||
expect(res.ok()).toBeTruthy();
|
||||
expect(elapsedMs).toBeLessThan(10_000);
|
||||
|
||||
const data = await res.json();
|
||||
expect(Array.isArray(data.amplitudes)).toBeTruthy();
|
||||
expect(data.amplitudes.length).toBeGreaterThan(0);
|
||||
expect(data.duration_seconds).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
// Sub-second strips (v0.232.0): precomputed vocals peak envelope.
|
||||
test('vocals-peaks returns a compact cached envelope quickly', async ({ request }) => {
|
||||
const base = `${API_URL}/api/review/${JOB_ID}/vocals-peaks`;
|
||||
const url = REVIEW_TOKEN ? `${base}?review_token=${encodeURIComponent(REVIEW_TOKEN)}` : base;
|
||||
|
||||
// First call may compute+cache; the second must be a pure cache read.
|
||||
const warm = await request.get(url, { headers: authHeaders() });
|
||||
expect([200, 202]).toContain(warm.status());
|
||||
if (warm.status() === 202) return; // separation still running for this job
|
||||
|
||||
const started = Date.now();
|
||||
const res = await request.get(url, { headers: authHeaders() });
|
||||
const elapsedMs = Date.now() - started;
|
||||
console.log(`vocals-peaks (cached) status=${res.status()} elapsed=${elapsedMs}ms`);
|
||||
expect(res.ok()).toBeTruthy();
|
||||
expect(elapsedMs).toBeLessThan(5_000);
|
||||
expect(res.headers()['cache-control']).toContain('max-age');
|
||||
|
||||
const data = await res.json();
|
||||
expect(data.encoding).toBe('u8');
|
||||
expect(typeof data.peaks_b64).toBe('string');
|
||||
expect(data.peaks_b64.length).toBeGreaterThan(0);
|
||||
expect(data.peaks_per_second).toBe(400);
|
||||
expect(data.duration_seconds).toBeGreaterThan(0);
|
||||
// Envelope should be dramatically smaller than the audio it replaces.
|
||||
expect(data.peaks_b64.length).toBeLessThan(1_000_000);
|
||||
});
|
||||
});
|
||||
@@ -116,3 +116,47 @@ describe('computePeaks', () => {
|
||||
expect(peaks[0]).toBeCloseTo(0.5)
|
||||
})
|
||||
})
|
||||
|
||||
describe('fetchVocalsPeaks', () => {
|
||||
const { fetchVocalsPeaks, AudioNotReadyError, AudioFetchError } = jest.requireActual('@/lib/audio-data')
|
||||
|
||||
const mockJsonResponse = (status: number, body?: unknown) =>
|
||||
({ ok: status >= 200 && status < 300, status, json: async () => body }) as Response
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('decodes the u8/base64 payload into AudioData', async () => {
|
||||
// peaks [0, 128, 255] -> [0, ~0.5, 1]
|
||||
const b64 = btoa(String.fromCharCode(0, 128, 255))
|
||||
global.fetch = jest.fn(async () =>
|
||||
mockJsonResponse(200, {
|
||||
peaks_b64: b64,
|
||||
encoding: 'u8',
|
||||
peaks_per_second: 400,
|
||||
duration_seconds: 0.0075,
|
||||
})
|
||||
) as unknown as typeof fetch
|
||||
|
||||
const data = await fetchVocalsPeaks('https://api/vocals-peaks')
|
||||
expect(data.peaksPerSecond).toBe(400)
|
||||
expect(data.duration).toBeCloseTo(0.0075)
|
||||
expect(Array.from(data.peaks)).toEqual([0, Math.fround(128 / 255), 1])
|
||||
})
|
||||
|
||||
it('throws AudioNotReadyError on 202', async () => {
|
||||
global.fetch = jest.fn(async () => mockJsonResponse(202)) as unknown as typeof fetch
|
||||
await expect(fetchVocalsPeaks('u')).rejects.toBeInstanceOf(AudioNotReadyError)
|
||||
})
|
||||
|
||||
it('throws AudioFetchError with status on non-2xx', async () => {
|
||||
global.fetch = jest.fn(async () => mockJsonResponse(404)) as unknown as typeof fetch
|
||||
await expect(fetchVocalsPeaks('u')).rejects.toMatchObject({ status: 404 })
|
||||
})
|
||||
|
||||
it('treats a malformed payload as a transient server error', async () => {
|
||||
global.fetch = jest.fn(async () => mockJsonResponse(200, { nope: true })) as unknown as typeof fetch
|
||||
await expect(fetchVocalsPeaks('u')).rejects.toBeInstanceOf(AudioFetchError)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* @jest-environment jsdom
|
||||
* @jest-environment-options {"url": "https://gen.nomadkaraoke.com/app/jobs?x=1#/abc12345/review"}
|
||||
*/
|
||||
|
||||
import {
|
||||
reportDegradationEvent,
|
||||
jobIdFromLocation,
|
||||
__resetDegradationEventsForTest,
|
||||
} from '@/lib/degradation-events'
|
||||
|
||||
describe('degradation-events reporter', () => {
|
||||
let fetchMock: jest.Mock
|
||||
|
||||
beforeEach(() => {
|
||||
__resetDegradationEventsForTest()
|
||||
fetchMock = jest.fn(() => Promise.resolve({ ok: true }))
|
||||
global.fetch = fetchMock as unknown as typeof fetch
|
||||
})
|
||||
|
||||
it('POSTs the event with sanitized url, job id and detail', () => {
|
||||
reportDegradationEvent('banner_unavailable', { stall_ms: 21000, probe_ok: false })
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
const [url, init] = fetchMock.mock.calls[0]
|
||||
expect(url).toBe('https://api.nomadkaraoke.com/api/client-events')
|
||||
const body = JSON.parse((init as RequestInit).body as string)
|
||||
expect(body.type).toBe('banner_unavailable')
|
||||
expect(body.url).not.toContain('x=1') // query stripped
|
||||
expect(body.job_id).toBe('abc12345')
|
||||
expect(body.detail).toEqual({ stall_ms: 21000, probe_ok: false })
|
||||
expect((init as RequestInit).keepalive).toBe(true)
|
||||
})
|
||||
|
||||
it('throttles repeat reports of the same type', () => {
|
||||
reportDegradationEvent('banner_reconnecting')
|
||||
reportDegradationEvent('banner_reconnecting')
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1)
|
||||
|
||||
// A different type is NOT throttled by the first one.
|
||||
reportDegradationEvent('waveform_failed')
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('never throws when fetch rejects', () => {
|
||||
fetchMock.mockImplementation(() => Promise.reject(new Error('offline')))
|
||||
expect(() => reportDegradationEvent('waveform_slow')).not.toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
describe('jobIdFromLocation', () => {
|
||||
it('parses hash-router review URLs', () => {
|
||||
expect(jobIdFromLocation('https://gen.nomadkaraoke.com/app/jobs#/d93747cd/review')).toBe('d93747cd')
|
||||
})
|
||||
|
||||
it('parses path-style job URLs', () => {
|
||||
expect(jobIdFromLocation('https://gen.nomadkaraoke.com/en/jobs/0370244a')).toBe('0370244a')
|
||||
})
|
||||
|
||||
it('returns null when no job id is present', () => {
|
||||
expect(jobIdFromLocation('https://gen.nomadkaraoke.com/')).toBeNull()
|
||||
expect(jobIdFromLocation('not a url')).toBeNull()
|
||||
})
|
||||
})
|
||||
+71
-7
@@ -2617,7 +2617,32 @@ export interface CommunityReviewItem {
|
||||
community_checked_at?: string | null;
|
||||
}
|
||||
|
||||
export interface CommunityRequestItem {
|
||||
id: string;
|
||||
artist: string;
|
||||
title: string;
|
||||
status: string;
|
||||
submitted_by: string;
|
||||
owner_email?: string | null;
|
||||
vote_count: number;
|
||||
job_id?: string | null;
|
||||
youtube_url?: string | null;
|
||||
review_state?: string | null;
|
||||
created_at?: string | null;
|
||||
picked_at?: string | null;
|
||||
}
|
||||
|
||||
export const adminApi = {
|
||||
/**
|
||||
* Full history of requests-board submissions across every status.
|
||||
*/
|
||||
async listCommunityRequests(): Promise<{ requests: CommunityRequestItem[] }> {
|
||||
const response = await apiFetch(`${API_BASE_URL}/api/admin/community-requests`, {
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
return handleResponse(response);
|
||||
},
|
||||
|
||||
/**
|
||||
* List requests-board picks flagged for existing-community-version review.
|
||||
*/
|
||||
@@ -3896,6 +3921,7 @@ export interface LyricsReviewApiClient {
|
||||
searchLyrics: (artist: string, title: string, forceSources?: string[]) => Promise<SearchLyricsResponse>
|
||||
getAudioUrl: (hash: string) => string
|
||||
getVocalsAudioUrl: () => string
|
||||
getVocalsPeaksUrl: () => string
|
||||
generatePreviewVideo: (data: CorrectionData, isDuet?: boolean) => Promise<{
|
||||
status: string
|
||||
message?: string
|
||||
@@ -4050,6 +4076,16 @@ export function createLyricsReviewApiClient(jobId: string): LyricsReviewApiClien
|
||||
return token ? `${base}?token=${encodeURIComponent(token)}` : base
|
||||
},
|
||||
|
||||
/**
|
||||
* Pre-computed vocals peak-envelope URL (Waveforms review mode).
|
||||
* ~150 KB JSON instead of downloading + decoding the whole vocal stem.
|
||||
*/
|
||||
getVocalsPeaksUrl(): string {
|
||||
const token = getAccessToken()
|
||||
const base = `${API_BASE_URL}/api/review/${jobId}/vocals-peaks`
|
||||
return token ? `${base}?token=${encodeURIComponent(token)}` : base
|
||||
},
|
||||
|
||||
/**
|
||||
* Generate a preview video from the current correction data.
|
||||
*
|
||||
@@ -4112,12 +4148,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(
|
||||
@@ -4125,7 +4161,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 ?? [])
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -4181,6 +4217,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 = {
|
||||
/**
|
||||
@@ -4193,7 +4252,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
|
||||
},
|
||||
|
||||
/**
|
||||
|
||||
@@ -23,6 +23,25 @@ export class AudioNotReadyError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
// Non-2xx response from the vocals endpoint. Carries the status so callers can
|
||||
// tell transient overload (5xx/429 — worth retrying) from terminal answers
|
||||
// (404: this job has no vocal stem; retrying would never succeed).
|
||||
export class AudioFetchError extends Error {
|
||||
constructor(public readonly status: number) {
|
||||
super(`Failed to fetch vocals audio: ${status}`)
|
||||
this.name = 'AudioFetchError'
|
||||
}
|
||||
}
|
||||
|
||||
export function isTransientAudioError(error: unknown): boolean {
|
||||
if (error instanceof AudioFetchError) {
|
||||
return error.status >= 500 || error.status === 429
|
||||
}
|
||||
// fetch() rejects with a TypeError on network-level failures (offline,
|
||||
// connection reset, CORS blip) — all worth retrying.
|
||||
return error instanceof TypeError
|
||||
}
|
||||
|
||||
// Minimal structural subset of AudioBuffer, so the peak math is testable
|
||||
// without constructing a real (browser-only) AudioContext.
|
||||
export interface DecodedAudioLike {
|
||||
@@ -74,6 +93,37 @@ export function computePeaks(decoded: DecodedAudioLike): AudioData {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the server-side pre-computed vocals peak envelope (~150 KB JSON) and
|
||||
* adapt it to the same AudioData shape computePeaks produces — so waveform
|
||||
* strips paint sub-second instead of after a multi-MB download + decode.
|
||||
* Throws AudioNotReadyError on 202 (separation still running) and
|
||||
* AudioFetchError on other non-2xx, mirroring fetchAudioData.
|
||||
*/
|
||||
export async function fetchVocalsPeaks(url: string): Promise<AudioData> {
|
||||
const response = await fetch(url)
|
||||
if (response.status === 202) {
|
||||
throw new AudioNotReadyError()
|
||||
}
|
||||
if (!response.ok) {
|
||||
throw new AudioFetchError(response.status)
|
||||
}
|
||||
const data = await response.json()
|
||||
if (data?.encoding !== 'u8' || typeof data.peaks_b64 !== 'string' || !data.peaks_b64) {
|
||||
throw new AudioFetchError(500) // unexpected payload — treat as transient server trouble
|
||||
}
|
||||
const raw = atob(data.peaks_b64)
|
||||
const peaks = new Float32Array(raw.length)
|
||||
for (let i = 0; i < raw.length; i++) {
|
||||
peaks[i] = raw.charCodeAt(i) / 255
|
||||
}
|
||||
return {
|
||||
duration: Number(data.duration_seconds) || 0,
|
||||
peaks,
|
||||
peaksPerSecond: Number(data.peaks_per_second) || PEAKS_PER_SECOND,
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchAudioData(url: string): Promise<AudioData> {
|
||||
// fetch() resolves even for 4xx/5xx; the vocals endpoint 404s when a job has
|
||||
// no vocal stem. Fail explicitly so the caller sees "no vocals" rather than an
|
||||
@@ -83,7 +133,7 @@ export async function fetchAudioData(url: string): Promise<AudioData> {
|
||||
throw new AudioNotReadyError()
|
||||
}
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch vocals audio: ${response.status}`)
|
||||
throw new AudioFetchError(response.status)
|
||||
}
|
||||
const arrayBuffer = await response.arrayBuffer()
|
||||
|
||||
|
||||
@@ -47,6 +47,11 @@ export const STALL_RECONNECTING_MS = 10_000
|
||||
export const STALL_UNAVAILABLE_MS = 20_000
|
||||
/** A health-probe verdict is trusted this long before we re-probe during a stall. */
|
||||
export const PROBE_FRESH_MS = 10_000
|
||||
/** Escalating to the full "unavailable" card needs this many CONSECUTIVE failed
|
||||
* probes — one failed 4s probe against a briefly-busy instance (e.g. a heavy
|
||||
* transcode pinning the CPU) is not an outage. The reconnecting pill still
|
||||
* shows after a single failure; the assertive message waits for confirmation. */
|
||||
export const UNAVAILABLE_PROBE_FAILURES = 2
|
||||
|
||||
let nextId = 1
|
||||
/** id -> startedAt (ms) for every tracked backend GET currently in flight. */
|
||||
@@ -65,6 +70,8 @@ let probeInFlight = false
|
||||
/** Last probe verdict (null = no verdict yet) and when it settled. */
|
||||
let lastProbeOk: boolean | null = null
|
||||
let lastProbeAt = 0
|
||||
/** Failed probes in a row (reset by any success or reconfiguration). */
|
||||
let consecutiveProbeFailures = 0
|
||||
/** Bumped on configureHealthProbe so a probe from a previous config can't land. */
|
||||
let probeEpoch = 0
|
||||
|
||||
@@ -98,10 +105,15 @@ function maybeStartProbe() {
|
||||
if (lastProbeOk !== null && Date.now() - lastProbeAt < PROBE_FRESH_MS) return
|
||||
probeInFlight = true
|
||||
const epoch = probeEpoch
|
||||
const record = (ok: boolean) => {
|
||||
if (epoch !== probeEpoch) return
|
||||
lastProbeOk = ok
|
||||
consecutiveProbeFailures = ok ? 0 : consecutiveProbeFailures + 1
|
||||
}
|
||||
healthProbe()
|
||||
.then(
|
||||
(ok) => (epoch === probeEpoch ? (lastProbeOk = ok) : undefined),
|
||||
() => (epoch === probeEpoch ? (lastProbeOk = false) : undefined),
|
||||
(ok) => record(ok),
|
||||
() => record(false),
|
||||
)
|
||||
.finally(() => {
|
||||
if (epoch !== probeEpoch) return
|
||||
@@ -118,7 +130,13 @@ function recompute() {
|
||||
// read is treated as a legitimately slow endpoint and the banner stays hidden.
|
||||
if (devOverride === null && next !== 'online' && healthProbe) {
|
||||
maybeStartProbe()
|
||||
if (lastProbeOk !== false) next = 'online'
|
||||
if (lastProbeOk !== false) {
|
||||
next = 'online'
|
||||
} else if (next === 'unavailable' && consecutiveProbeFailures < UNAVAILABLE_PROBE_FAILURES) {
|
||||
// One failed probe can just be a briefly-pegged instance; keep the calm
|
||||
// pill until a second consecutive failure confirms real unreachability.
|
||||
next = 'reconnecting'
|
||||
}
|
||||
}
|
||||
setStatus(next)
|
||||
// Stop the clock once nothing is outstanding (and no dev override needs it).
|
||||
@@ -163,6 +181,26 @@ export function configureHealthProbe(probe: HealthProbe | null): void {
|
||||
probeInFlight = false
|
||||
lastProbeOk = null
|
||||
lastProbeAt = 0
|
||||
consecutiveProbeFailures = 0
|
||||
}
|
||||
|
||||
/** Diagnostic snapshot for degradation telemetry (see lib/degradation-events). */
|
||||
export function getBackendStatusDebug(): {
|
||||
oldestStallMs: number
|
||||
inFlightCount: number
|
||||
lastProbeOk: boolean | null
|
||||
consecutiveProbeFailures: number
|
||||
} {
|
||||
let oldest = Infinity
|
||||
for (const startedAt of inFlight.values()) {
|
||||
if (startedAt < oldest) oldest = startedAt
|
||||
}
|
||||
return {
|
||||
oldestStallMs: inFlight.size === 0 ? 0 : Date.now() - oldest,
|
||||
inFlightCount: inFlight.size,
|
||||
lastProbeOk,
|
||||
consecutiveProbeFailures,
|
||||
}
|
||||
}
|
||||
|
||||
export function getBackendStatus(): BackendStatus {
|
||||
|
||||
Loaded 100 of 161 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user