mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-04 17:16:04 +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 \
|
||||
|
||||
@@ -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}")
|
||||
|
||||
@@ -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
|
||||
|
||||
+367
-112
@@ -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,47 +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:
|
||||
# Best-effort: signing goes through IAM signBlob over the network and is
|
||||
# now bounded to SIGNED_URL_TIMEOUT_S (see storage_service). A stall must
|
||||
# NOT blow up the whole review load — on failure we return the option with
|
||||
# a null audio_url; the frontend re-fetches via GET /{job_id}/instrumental-urls.
|
||||
results = await asyncio.gather(*url_tasks.values(), return_exceptions=True)
|
||||
for key, res in zip(url_tasks.keys(), results):
|
||||
if isinstance(res, Exception):
|
||||
logger.warning(f"Signing review audio URL failed ({key}): {res}")
|
||||
signed_urls[key] = None
|
||||
else:
|
||||
signed_urls[key] = res
|
||||
def _audio_url(option_id: str, source_gcs_path: str) -> Optional[str]:
|
||||
# Local dev (no URL-signing creds) keeps its existing byte proxy, which takes the
|
||||
# GCS path directly; prod/default returns the option-scoped proxy path.
|
||||
if _dev_audio_proxy_enabled():
|
||||
return _dev_audio_url(job.job_id, source_gcs_path, str(request.base_url))
|
||||
return _instrumental_proxy_path(job.job_id, option_id)
|
||||
|
||||
instrumental_options: List[Dict[str, Any]] = []
|
||||
if clean_url:
|
||||
@@ -458,14 +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
|
||||
|
||||
@@ -626,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"))
|
||||
|
||||
@@ -660,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:
|
||||
@@ -668,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")
|
||||
@@ -676,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)
|
||||
@@ -693,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)
|
||||
@@ -711,40 +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. Best-effort + off the event loop: signing is
|
||||
# a network round-trip (IAM signBlob, bounded to SIGNED_URL_TIMEOUT_S), so run
|
||||
# it in a thread and never let a stall/timeout fail the review load — the
|
||||
# waveform is a nice-to-have, the lyrics are not.
|
||||
analysis_files = job.file_urls.get('analysis', {})
|
||||
waveform_url = analysis_files.get('backing_vocals_waveform')
|
||||
if waveform_url:
|
||||
try:
|
||||
if _dev_audio_proxy_enabled():
|
||||
corrections_data['backing_vocals_waveform_url'] = _dev_audio_url(
|
||||
job_id, waveform_url, str(request.base_url)
|
||||
)
|
||||
else:
|
||||
corrections_data['backing_vocals_waveform_url'] = await asyncio.to_thread(
|
||||
storage.generate_signed_url, waveform_url, expiration_minutes=120
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"Job {job_id}: waveform URL signing failed, omitting: {e}")
|
||||
# NOTE: we intentionally do NOT sign/emit a ``backing_vocals_waveform_url`` here.
|
||||
# The frontend renders the backing-vocals waveform from the Bearer-authenticated
|
||||
# JSON endpoint ``GET /{job_id}/waveform-data`` (amplitudes drawn on a canvas), and
|
||||
# never consumed this field. Signing it was a pure IAM-signBlob round-trip on the
|
||||
# review hot path with no consumer — removed as part of the 2026-09-17 fast-load
|
||||
# re-architecture so ``correction-data`` performs zero signing.
|
||||
|
||||
# Transition to IN_REVIEW if not already (never in replay — read-only)
|
||||
if not replay and job.status == JobStatus.AWAITING_REVIEW:
|
||||
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
|
||||
)
|
||||
@@ -772,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.
|
||||
|
||||
@@ -809,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"))
|
||||
|
||||
@@ -817,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
|
||||
@@ -853,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():
|
||||
@@ -878,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()
|
||||
@@ -935,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,
|
||||
@@ -1734,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)
|
||||
@@ -1900,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}
|
||||
|
||||
|
||||
@@ -1936,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"))
|
||||
|
||||
@@ -2003,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,
|
||||
@@ -2013,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"))
|
||||
|
||||
@@ -2035,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,
|
||||
|
||||
@@ -263,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
|
||||
|
||||
@@ -20,6 +20,7 @@ from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
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
|
||||
@@ -164,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."""
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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"
|
||||
@@ -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,19 +148,19 @@ class TestGetCorrectionDataReturnsUpdatedCorrections:
|
||||
# Verify the returned data is the original
|
||||
assert result["corrected_segments"][0]["text"] == "Hello world"
|
||||
|
||||
def test_signing_stall_returns_200_and_omits_waveform_url(
|
||||
def test_returns_proxy_audio_urls_and_omits_waveform_without_signing(
|
||||
self, mock_job, original_corrections
|
||||
):
|
||||
"""A stalled IAM signBlob must not fail the review load (incident 2026-09-17).
|
||||
|
||||
When signing raises SignedUrlTimeout, get_correction_data must still return
|
||||
the lyrics payload with HTTP 200, omit ``backing_vocals_waveform_url``, and
|
||||
return instrumental options with null audio_url (the frontend re-fetches).
|
||||
"""Root-cause fix (2026-09-17, Option B): the review hot path performs NO URL
|
||||
signing. get_correction_data returns 200 with the lyrics payload, same-origin
|
||||
proxy paths for the instrumental options, and no ``backing_vocals_waveform_url``
|
||||
(the frontend renders the waveform from the JSON /waveform-data endpoint, and
|
||||
never consumed this field). The IAM signBlob round-trip that stalled and took gen
|
||||
down on 2026-09-17 is gone entirely.
|
||||
"""
|
||||
from backend.api.routes.review import get_correction_data
|
||||
from backend.services.storage_service import SignedUrlTimeout
|
||||
|
||||
# Job has both a waveform and instrumental stems, so all signing paths run.
|
||||
# Job has both a waveform and instrumental stems, so every former signing path runs.
|
||||
mock_job.file_urls["analysis"] = {
|
||||
"backing_vocals_waveform": "jobs/test-job-123/analysis/backing_vocals_waveform.png"
|
||||
}
|
||||
@@ -179,21 +179,24 @@ class TestGetCorrectionDataReturnsUpdatedCorrections:
|
||||
storage = MockStorageService.return_value
|
||||
storage.file_exists.side_effect = lambda path: "corrections_updated" not in path
|
||||
storage.download_json.return_value = original_corrections.copy()
|
||||
# Every sign stalls — the whole point of the incident.
|
||||
storage.generate_signed_url.side_effect = SignedUrlTimeout("stalled")
|
||||
|
||||
import asyncio
|
||||
result = asyncio.run(
|
||||
get_correction_data("test-job-123", ("user@test.com", "job_owner"))
|
||||
)
|
||||
|
||||
# Endpoint succeeded with the lyrics payload despite the signing stall.
|
||||
# Endpoint succeeded with the lyrics payload.
|
||||
assert result["corrected_segments"][0]["text"] == "Hello world"
|
||||
# Waveform URL omitted rather than 500-ing the load.
|
||||
# Waveform URL is not emitted at all (dead field, no consumer).
|
||||
assert "backing_vocals_waveform_url" not in result
|
||||
# Instrumental options present but with null audio_url (client retries).
|
||||
# Instrumental options carry same-origin proxy paths (no signing, never expire).
|
||||
opts = {o["id"]: o["audio_url"] for o in result["instrumental_options"]}
|
||||
assert opts == {"clean": None, "with_backing": None}
|
||||
assert opts == {
|
||||
"clean": "/api/review/test-job-123/instrumental-audio/clean",
|
||||
"with_backing": "/api/review/test-job-123/instrumental-audio/with_backing",
|
||||
}
|
||||
# The critical assertion: the hot path signed nothing.
|
||||
storage.generate_signed_url.assert_not_called()
|
||||
|
||||
def test_checks_direct_gcs_path_when_not_in_file_urls(
|
||||
self, mock_job, updated_corrections
|
||||
|
||||
@@ -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."""
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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,12 +373,9 @@ class TestInstrumentalUrlsRefresh:
|
||||
options = response.json()["instrumental_options"]
|
||||
assert [o["id"] for o in options] == ["clean"]
|
||||
|
||||
def test_signing_stall_degrades_to_null_url_not_500(self, test_client):
|
||||
"""A stalled IAM signBlob must not fail the refresh — the stem is returned
|
||||
with a null audio_url so the client retries, rather than a 500/hang
|
||||
(incident 2026-09-17)."""
|
||||
from backend.services.storage_service import SignedUrlTimeout
|
||||
|
||||
def test_does_not_sign_urls_on_hot_path(self, test_client):
|
||||
"""The root-cause fix: building instrumental options must perform NO URL signing
|
||||
(the IAM signBlob round-trip is what stalled and took gen down on 2026-09-17)."""
|
||||
mock_job = MagicMock()
|
||||
mock_job.job_id = "job1"
|
||||
mock_job.file_urls = {
|
||||
@@ -398,24 +385,16 @@ class TestInstrumentalUrlsRefresh:
|
||||
}
|
||||
}
|
||||
|
||||
async def stalled_sign(src, expiration_minutes=120):
|
||||
# 'clean' signs fine; 'with_backing' hits the stalled signer.
|
||||
if "with_backing" in src:
|
||||
raise SignedUrlTimeout("stalled")
|
||||
return f"https://signed/{src}"
|
||||
|
||||
with patch("backend.api.routes.review.JobManager") as mock_jm, \
|
||||
patch("backend.api.routes.review.StorageService"), \
|
||||
patch("backend.api.routes.review.StorageService") as mock_storage, \
|
||||
patch("backend.api.routes.review._dev_audio_proxy_enabled", return_value=False), \
|
||||
patch("backend.services.audio_transcoding_service.AudioTranscodingService.get_review_audio_url_async",
|
||||
side_effect=stalled_sign):
|
||||
patch("backend.services.audio_transcoding_service.AudioTranscodingService.get_review_audio_url_async") as mock_sign_async:
|
||||
mock_jm.return_value.get_job.return_value = mock_job
|
||||
response = test_client.get("/api/review/job1/instrumental-urls")
|
||||
|
||||
assert response.status_code == 200
|
||||
options = {o["id"]: o["audio_url"] for o in response.json()["instrumental_options"]}
|
||||
assert options["clean"].endswith("instrumental_clean.flac")
|
||||
assert options["with_backing"] is None
|
||||
mock_sign_async.assert_not_called()
|
||||
mock_storage.return_value.generate_signed_url.assert_not_called()
|
||||
|
||||
def test_missing_job_returns_404(self, test_client):
|
||||
with patch("backend.api.routes.review.JobManager") as mock_jm, \
|
||||
@@ -425,6 +404,122 @@ class TestInstrumentalUrlsRefresh:
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
class TestInstrumentalAudioProxy:
|
||||
"""GET /{job_id}/instrumental-audio/{option_id} — same-origin byte proxy.
|
||||
|
||||
Option B of the 2026-09-17 fast-load re-architecture: serves the transcoded OGG
|
||||
bytes with HTTP Range support instead of a signed GCS URL, so playback never depends
|
||||
on IAM signBlob. The stem GCS path is resolved server-side from the option id.
|
||||
"""
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def auth_overrides(self):
|
||||
from backend.main import app
|
||||
from backend.api.dependencies import require_review_auth
|
||||
|
||||
async def mock_require_review_auth(job_id: str = "test123"):
|
||||
return (job_id, "full")
|
||||
|
||||
app.dependency_overrides[require_review_auth] = mock_require_review_auth
|
||||
yield
|
||||
app.dependency_overrides.pop(require_review_auth, None)
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clear_audio_cache(self):
|
||||
# The proxy caches bytes per GCS path at module scope; clear it so a prior
|
||||
# test's stubbed bytes don't leak into the next test's assertions.
|
||||
from backend.api.routes import review as review_module
|
||||
review_module._review_audio_cache.clear()
|
||||
yield
|
||||
review_module._review_audio_cache.clear()
|
||||
|
||||
def _mock_job(self):
|
||||
job = MagicMock()
|
||||
job.job_id = "job1"
|
||||
job.file_urls = {
|
||||
"stems": {
|
||||
"instrumental_clean": "jobs/job1/stems/instrumental_clean.flac",
|
||||
"instrumental_with_backing": "jobs/job1/stems/instrumental_with_backing.flac",
|
||||
}
|
||||
}
|
||||
return job
|
||||
|
||||
def test_streams_transcoded_bytes(self, test_client):
|
||||
audio = b"OggS" + b"\x00" * 100
|
||||
with patch("backend.api.routes.review.JobManager") as mock_jm, \
|
||||
patch("backend.api.routes.review.StorageService"), \
|
||||
patch("backend.services.audio_transcoding_service.AudioTranscodingService.get_review_audio_bytes_async",
|
||||
new=AsyncMock(return_value=(audio, "audio/ogg"))):
|
||||
mock_jm.return_value.get_job.return_value = self._mock_job()
|
||||
response = test_client.get("/api/review/job1/instrumental-audio/clean")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.headers["content-type"] == "audio/ogg"
|
||||
assert response.headers["accept-ranges"] == "bytes"
|
||||
assert response.content == audio
|
||||
|
||||
def test_supports_range_requests(self, test_client):
|
||||
audio = bytes(range(50)) * 4 # 200 deterministic bytes
|
||||
with patch("backend.api.routes.review.JobManager") as mock_jm, \
|
||||
patch("backend.api.routes.review.StorageService"), \
|
||||
patch("backend.services.audio_transcoding_service.AudioTranscodingService.get_review_audio_bytes_async",
|
||||
new=AsyncMock(return_value=(audio, "audio/ogg"))):
|
||||
mock_jm.return_value.get_job.return_value = self._mock_job()
|
||||
response = test_client.get(
|
||||
"/api/review/job1/instrumental-audio/clean",
|
||||
headers={"Range": "bytes=10-19"},
|
||||
)
|
||||
|
||||
assert response.status_code == 206
|
||||
assert response.headers["content-range"] == f"bytes 10-19/{len(audio)}"
|
||||
assert response.content == audio[10:20]
|
||||
|
||||
def test_unknown_option_id_returns_404(self, test_client):
|
||||
with patch("backend.api.routes.review.JobManager") as mock_jm, \
|
||||
patch("backend.api.routes.review.StorageService"):
|
||||
mock_jm.return_value.get_job.return_value = self._mock_job()
|
||||
response = test_client.get("/api/review/job1/instrumental-audio/bogus")
|
||||
assert response.status_code == 404
|
||||
|
||||
def test_missing_stem_returns_404(self, test_client):
|
||||
job = MagicMock()
|
||||
job.job_id = "job1"
|
||||
job.file_urls = {"stems": {"instrumental_clean": "jobs/job1/stems/instrumental_clean.flac"}}
|
||||
with patch("backend.api.routes.review.JobManager") as mock_jm, \
|
||||
patch("backend.api.routes.review.StorageService"):
|
||||
mock_jm.return_value.get_job.return_value = job
|
||||
response = test_client.get("/api/review/job1/instrumental-audio/with_backing")
|
||||
assert response.status_code == 404
|
||||
|
||||
def test_missing_job_returns_404(self, test_client):
|
||||
with patch("backend.api.routes.review.JobManager") as mock_jm, \
|
||||
patch("backend.api.routes.review.StorageService"):
|
||||
mock_jm.return_value.get_job.return_value = None
|
||||
response = test_client.get("/api/review/job1/instrumental-audio/clean")
|
||||
assert response.status_code == 404
|
||||
|
||||
def test_deleted_gcs_object_returns_404_not_500(self, test_client):
|
||||
from google.cloud.exceptions import NotFound
|
||||
with patch("backend.api.routes.review.JobManager") as mock_jm, \
|
||||
patch("backend.api.routes.review.StorageService"), \
|
||||
patch("backend.services.audio_transcoding_service.AudioTranscodingService.get_review_audio_bytes_async",
|
||||
new=AsyncMock(side_effect=NotFound("gone"))):
|
||||
mock_jm.return_value.get_job.return_value = self._mock_job()
|
||||
response = test_client.get("/api/review/job1/instrumental-audio/clean")
|
||||
assert response.status_code == 404
|
||||
|
||||
def test_does_not_sign_urls(self, test_client):
|
||||
audio = b"OggS"
|
||||
with patch("backend.api.routes.review.JobManager") as mock_jm, \
|
||||
patch("backend.api.routes.review.StorageService") as mock_storage, \
|
||||
patch("backend.services.audio_transcoding_service.AudioTranscodingService.get_review_audio_bytes_async",
|
||||
new=AsyncMock(return_value=(audio, "audio/ogg"))):
|
||||
mock_jm.return_value.get_job.return_value = self._mock_job()
|
||||
response = test_client.get("/api/review/job1/instrumental-audio/clean")
|
||||
assert response.status_code == 200
|
||||
mock_storage.return_value.generate_signed_url.assert_not_called()
|
||||
|
||||
|
||||
class TestReviewResubmissionClearsWorkerProgress:
|
||||
"""Tests for ensuring review submission clears worker progress keys.
|
||||
|
||||
@@ -1352,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"
|
||||
@@ -1726,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()
|
||||
@@ -1737,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,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
|
||||
@@ -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)
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -483,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
|
||||
@@ -632,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
|
||||
@@ -650,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
|
||||
@@ -766,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}")
|
||||
|
||||
+79
-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
|
||||
@@ -2635,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.
|
||||
@@ -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:
|
||||
|
||||
+27
-8
@@ -42,14 +42,21 @@ gcloud logging read 'resource.type="cloud_run_revision" AND resource.labels.serv
|
||||
If a restart doesn't clear it, the IAM Credentials API is genuinely degraded in the
|
||||
region — wait it out / open a GCP ticket.
|
||||
|
||||
**Durable mitigation (shipped v0.228.1):** every sign now runs on a dedicated bounded
|
||||
thread pool with a wall-clock budget (`SIGNED_URL_TIMEOUT_S`, default 12s) and bounded
|
||||
admission (`SIGNED_URL_MAX_INFLIGHT`) in `storage_service._generate_signed_url_internal`
|
||||
— a stall raises `SignedUrlTimeout` fast instead of hanging, saturation is refused
|
||||
immediately rather than queued, and neither can starve GCS data-plane reads or the request pool.
|
||||
The review endpoints treat audio-URL signing as best-effort (return the option with a
|
||||
null `audio_url`; the frontend re-fetches via `GET /{job_id}/instrumental-urls`), so
|
||||
the lyrics page loads even during a signing stall.
|
||||
**Root-cause fix (shipped v0.229.0 — Option B):** `correction-data` no longer signs any
|
||||
URL on the review hot path, so it can't stall on IAM signBlob at all. The two instrumental
|
||||
options are delivered by a **same-origin byte proxy** (`GET /api/review/{job_id}/instrumental-audio/{option_id}`,
|
||||
served with HTTP Range so `<audio>` can seek — no signing, never expires), and the dead
|
||||
`backing_vocals_waveform_url` (never consumed; the waveform comes from the JSON
|
||||
`GET /api/review/{job_id}/waveform-data` endpoint) was removed. The frontend turns each option's relative
|
||||
`audio_url` into an absolute token URL exactly like `getVocalsAudioUrl`. See
|
||||
`docs/archive/2026-09-17-review-fast-full-load-plan.md`.
|
||||
|
||||
**Safety net (still in place, v0.228.1):** signing anywhere else (e.g. preview-video)
|
||||
still runs on a dedicated bounded thread pool with a wall-clock budget
|
||||
(`SIGNED_URL_TIMEOUT_S`, default 12s) and bounded admission (`SIGNED_URL_MAX_INFLIGHT`) in
|
||||
`storage_service._generate_signed_url_internal` — a stall raises `SignedUrlTimeout` fast
|
||||
instead of hanging, and saturation is refused immediately rather than queued. Left as
|
||||
defense-in-depth beneath the signing-free review path.
|
||||
|
||||
---
|
||||
|
||||
@@ -322,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,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,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,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,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 {
|
||||
|
||||
@@ -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") {
|
||||
|
||||
@@ -88,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
|
||||
@@ -177,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)
|
||||
@@ -657,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)
|
||||
@@ -1532,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}
|
||||
|
||||
@@ -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 }}>
|
||||
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,7 @@
|
||||
import { test, expect, Page, BrowserContext } from '@playwright/test';
|
||||
import { createEmailHelper, isEmailTestingAvailable } from '../helpers/email-testing';
|
||||
import { clickCompleteSignInGate } from '../helpers/auth';
|
||||
import { deleteTestJob } from '../helpers/test-cleanup';
|
||||
|
||||
/**
|
||||
* E2E Happy Path Test - Real User Journey with Full UI Interactions
|
||||
@@ -221,6 +222,31 @@ test.describe('E2E Happy Path - Real User with Full UI Interactions', () => {
|
||||
// retries, so there's no steady-state cost.
|
||||
test.describe.configure({ retries: 1 });
|
||||
|
||||
// Safety-net job tracker. The in-flow cleanup (Step 12) only runs on a fully
|
||||
// successful pass through review -> complete. If the test fails or times out
|
||||
// before Step 12 (e.g. stuck at "awaiting_review"), the job it created was
|
||||
// being stranded in production under the e2e-test-runner account — visible in
|
||||
// the admin dashboard and never cleaned up. The afterEach below deletes it
|
||||
// regardless of where the test stopped, on every attempt (incl. retries).
|
||||
let capturedJobId: string | null = null;
|
||||
|
||||
test.afterEach(async () => {
|
||||
if (!capturedJobId) return;
|
||||
const jobToDelete = capturedJobId;
|
||||
capturedJobId = null;
|
||||
const adminToken = process.env.E2E_ADMIN_TOKEN;
|
||||
if (!adminToken) {
|
||||
console.log(` [teardown] No E2E_ADMIN_TOKEN — cannot delete job ${jobToDelete}; manual cleanup needed`);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await deleteTestJob(jobToDelete, adminToken, { cleanupDistribution: true }, API_URL);
|
||||
console.log(` [teardown] ${result.message}`);
|
||||
} catch (e) {
|
||||
console.log(` [teardown] Failed to delete job ${jobToDelete}: ${e}`);
|
||||
}
|
||||
});
|
||||
|
||||
test('Complete flow: New user signup -> Karaoke generation -> Distribution -> Cleanup', async ({
|
||||
page,
|
||||
context,
|
||||
@@ -260,6 +286,46 @@ test.describe('E2E Happy Path - Real User with Full UI Interactions', () => {
|
||||
}
|
||||
});
|
||||
|
||||
// Pin the song identity to the typed input so the created job is
|
||||
// deterministically "piri - dog". The AI match-judge normally runs on the
|
||||
// guided-flow search and may rewrite the typed artist to its canonical form
|
||||
// (e.g. "piri" -> "piri & tommy"), nondeterministically depending on the
|
||||
// audio-confidence tier and LLM output. That's a legitimate product feature,
|
||||
// but it made the daily/canary jobs show up under two different names. Here
|
||||
// we stub the judge to a no-op "none" verdict echoing the typed values so
|
||||
// the correction never applies. (Does not affect the generation pipeline the
|
||||
// happy path exists to exercise.)
|
||||
await page.route('**/api/catalog/match-judge', async (route) => {
|
||||
const request = route.request();
|
||||
if (request.method() === 'POST') {
|
||||
let artist = TEST_SONG.artist;
|
||||
let title = TEST_SONG.title;
|
||||
try {
|
||||
const body = request.postDataJSON();
|
||||
if (body?.artist) artist = body.artist;
|
||||
if (body?.title) title = body.title;
|
||||
} catch {
|
||||
// fall back to TEST_SONG
|
||||
}
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
kind: 'none',
|
||||
confident: true,
|
||||
canonical_artist: artist,
|
||||
canonical_title: title,
|
||||
alternatives: [],
|
||||
engine: 'deterministic',
|
||||
reason: 'E2E: match-judge stubbed to keep song identity deterministic',
|
||||
needs_ai: false,
|
||||
}),
|
||||
});
|
||||
} else {
|
||||
await route.continue();
|
||||
}
|
||||
});
|
||||
|
||||
try {
|
||||
// =========================================================================
|
||||
// STEP 1: Landing Page
|
||||
@@ -591,6 +657,7 @@ test.describe('E2E Happy Path - Real User with Full UI Interactions', () => {
|
||||
const idMatch = idText.match(/ID:\s*([a-f0-9]{8,})/i);
|
||||
if (idMatch) {
|
||||
jobId = idMatch[1];
|
||||
capturedJobId = jobId; // hand to afterEach so a partial run still cleans up
|
||||
console.log(` Job ID: ${jobId}`);
|
||||
}
|
||||
}
|
||||
@@ -1308,6 +1375,7 @@ test.describe('E2E Happy Path - Real User with Full UI Interactions', () => {
|
||||
console.log(` Dropbox: ${result.dropbox?.status}`);
|
||||
console.log(` GDrive: ${result.gdrive?.status}`);
|
||||
console.log(` Job deleted: ${result.job_deleted}`);
|
||||
if (result.job_deleted) capturedJobId = null; // already gone; skip afterEach re-delete
|
||||
} else {
|
||||
console.log(` WARNING: Cleanup failed with status ${cleanupResponse.status()}`);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,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()
|
||||
})
|
||||
})
|
||||
+46
-7
@@ -3921,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
|
||||
@@ -4075,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.
|
||||
*
|
||||
@@ -4137,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(
|
||||
@@ -4150,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 ?? [])
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -4206,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 = {
|
||||
/**
|
||||
@@ -4218,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 {
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* Degradation-event reporter: fire-and-forget telemetry for every user-visible
|
||||
* degraded-service surface (connectivity banner, "temporarily unavailable"
|
||||
* lyrics failure, slow/failed waveform). POSTs to /api/client-events, which
|
||||
* persists to Cloud Logging + Firestore so frequency can be reviewed later.
|
||||
*
|
||||
* - Never throws; failures are swallowed (telemetry must not cause UX noise).
|
||||
* - Per-type throttle so a flapping status can't spam the API.
|
||||
* - No-ops on localhost (would otherwise report dev blips to prod).
|
||||
*
|
||||
* NOTE: intentionally does NOT import from lib/api.ts — api.ts imports
|
||||
* backend-status.ts, and this module is called from banner-adjacent code, so
|
||||
* importing api.ts here risks a module cycle. The base URL is derived the same
|
||||
* way api.ts derives it.
|
||||
*/
|
||||
|
||||
export type DegradationEventType =
|
||||
| 'banner_reconnecting'
|
||||
| 'banner_unavailable'
|
||||
| 'lyrics_load_failed'
|
||||
| 'waveform_slow'
|
||||
| 'waveform_failed'
|
||||
|
||||
/** Minimum gap between two reports of the same event type. */
|
||||
const THROTTLE_MS = 60_000
|
||||
const lastSentAt = new Map<DegradationEventType, number>()
|
||||
|
||||
export function __resetDegradationEventsForTest() {
|
||||
lastSentAt.clear()
|
||||
}
|
||||
|
||||
function apiBaseUrl(): string {
|
||||
if (typeof window === 'undefined') return ''
|
||||
const h = window.location.hostname
|
||||
if (h === 'localhost' || h === '127.0.0.1') return '' // guarded below anyway
|
||||
return process.env.NEXT_PUBLIC_API_URL || 'https://api.nomadkaraoke.com'
|
||||
}
|
||||
|
||||
function isLocalhost(): boolean {
|
||||
if (typeof window === 'undefined') return true
|
||||
const h = window.location.hostname
|
||||
return h === 'localhost' || h === '127.0.0.1' || h === '[::1]' || h === '::1'
|
||||
}
|
||||
|
||||
/** Best-effort job id from review-style URLs (/app/jobs#/{id}/… or /jobs/{id}). */
|
||||
export function jobIdFromLocation(href: string): string | null {
|
||||
try {
|
||||
const u = new URL(href)
|
||||
const hashMatch = u.hash.match(/^#\/([0-9a-f-]{6,64})(\/|$)/i)
|
||||
if (hashMatch) return hashMatch[1]
|
||||
const pathMatch = u.pathname.match(/\/jobs\/([0-9a-f-]{6,64})(\/|$)/i)
|
||||
if (pathMatch) return pathMatch[1]
|
||||
return null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function sanitizedHref(): string {
|
||||
try {
|
||||
const u = new URL(window.location.href)
|
||||
u.search = ''
|
||||
return u.toString().slice(0, 2048)
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Report one degradation event. Safe to call from anywhere client-side;
|
||||
* throttled per type, silent on failure.
|
||||
*/
|
||||
export function reportDegradationEvent(
|
||||
type: DegradationEventType,
|
||||
detail?: Record<string, unknown>,
|
||||
): void {
|
||||
try {
|
||||
if (typeof window === 'undefined' || isLocalhost()) return
|
||||
|
||||
const now = Date.now()
|
||||
const last = lastSentAt.get(type)
|
||||
if (last && now - last < THROTTLE_MS) return
|
||||
lastSentAt.set(type, now)
|
||||
|
||||
const body = {
|
||||
type,
|
||||
url: sanitizedHref(),
|
||||
job_id: jobIdFromLocation(window.location.href),
|
||||
user_email: null as string | null,
|
||||
locale: document.documentElement.lang || 'en',
|
||||
release: process.env.NEXT_PUBLIC_COMMIT_SHA || '',
|
||||
detail: detail ?? null,
|
||||
}
|
||||
|
||||
void fetch(`${apiBaseUrl()}/api/client-events`, {
|
||||
method: 'POST',
|
||||
keepalive: true,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
}).catch(() => {
|
||||
/* swallow — telemetry must never surface */
|
||||
})
|
||||
} catch {
|
||||
/* swallow */
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,13 @@ Provides search and cross-reference endpoints for the KJ Controller:
|
||||
POST / {"action": "search", "query": "bohemian rhapsody", "limit": 50}
|
||||
→ Search Divebar catalog by artist/title
|
||||
|
||||
POST / {"action": "kn_community_search", "query": "...", "limit": 50}
|
||||
→ Search our KaraokeNerds community catalog (web-playable tracks only)
|
||||
|
||||
POST / {"action": "kn_search", "query": "...", "limit": 50}
|
||||
→ Search BOTH KaraokeNerds catalogs at once: community (playable, with
|
||||
YouTube URLs) + full (every release incl. commercial disc brands)
|
||||
|
||||
POST / {"action": "lookup", "kn_ids": [123, 456]}
|
||||
→ Bulk lookup which KN songs have Divebar versions
|
||||
|
||||
@@ -75,14 +82,30 @@ def _json_response(data: dict, status: int = 200):
|
||||
|
||||
|
||||
def _search_divebar(query: str, limit: int = 50) -> list[dict]:
|
||||
"""Search the Divebar catalog in BigQuery by artist/title."""
|
||||
"""Search the Divebar catalog in BigQuery by artist/title.
|
||||
|
||||
Matching is accent-insensitive: the query and the artist/title haystack are
|
||||
both diacritic-folded (NFD + drop combining marks, then lowered), mirroring
|
||||
``_search_kn_community``. Without this, a caller searching with normalized
|
||||
text ("Jose Feliciano Feliz Navidad") could never match an accented catalog
|
||||
row ("José Feliciano") — which broke the KJ Controller's loose-CDG sibling
|
||||
pairing on approval, since sing requests store KN-normalized, accent-free
|
||||
artist text.
|
||||
"""
|
||||
client = bigquery.Client(project=GCP_PROJECT_ID)
|
||||
|
||||
# Normalize query for matching
|
||||
normalized = query.lower().strip()
|
||||
# Diacritic-fold + lowercase the query, mirroring the SQL haystack below.
|
||||
normalized = "".join(
|
||||
c for c in unicodedata.normalize("NFD", query) if not unicodedata.combining(c)
|
||||
).lower().strip()
|
||||
|
||||
# Use LIKE for simple substring matching (BigQuery doesn't have FTS5)
|
||||
# For better search, consider using CONTAINS or SEARCH functions
|
||||
fold_sql = (
|
||||
"LOWER(REGEXP_REPLACE("
|
||||
"NORMALIZE(CONCAT(COALESCE(artist, ''), ' ', COALESCE(title, '')), NFD),"
|
||||
r" r'\p{Mn}', ''))"
|
||||
)
|
||||
sql = f"""
|
||||
SELECT
|
||||
file_id,
|
||||
@@ -97,7 +120,7 @@ def _search_divebar(query: str, limit: int = 50) -> list[dict]:
|
||||
gcs_path
|
||||
FROM `{GCP_PROJECT_ID}.{DATASET}.divebar_catalog`
|
||||
WHERE
|
||||
LOWER(CONCAT(COALESCE(artist, ''), ' ', COALESCE(title, '')))
|
||||
{fold_sql}
|
||||
LIKE @query_pattern
|
||||
ORDER BY
|
||||
CASE WHEN artist IS NOT NULL AND title IS NOT NULL THEN 0 ELSE 1 END,
|
||||
@@ -131,25 +154,35 @@ def _search_divebar(query: str, limit: int = 50) -> list[dict]:
|
||||
return results
|
||||
|
||||
|
||||
def _search_kn_community(query: str, limit: int = 50) -> list[dict]:
|
||||
"""Search our OWN KaraokeNerds community catalog (never scrapes karaokenerds.com).
|
||||
# Diacritic-fold the Artist/Title haystack in SQL (NFD + drop combining marks,
|
||||
# then lower) so matching is accent-insensitive on both sides — mirrors the
|
||||
# Python-side fold in _kn_match_parts.
|
||||
_KN_FOLD_SQL = (
|
||||
"LOWER(REGEXP_REPLACE("
|
||||
"NORMALIZE(CONCAT(COALESCE(Artist, ''), ' ', COALESCE(Title, '')), NFD),"
|
||||
r" r'\p{Mn}', ''))"
|
||||
)
|
||||
|
||||
Reads `karaokenerds_community` — the free, directly-playable (web/YouTube)
|
||||
tracks populated daily by the authorized `kn-data-sync` export. Matching is
|
||||
token-AND (every whitespace token must match "artist title"), which mirrors
|
||||
the KaraokeNerds search box while tolerating "artist title" / "title artist"
|
||||
/ partial queries. Two forms of tolerance per token:
|
||||
• accent-insensitive — both sides are diacritic-folded (so "maximo" matches
|
||||
"Maxïmo");
|
||||
|
||||
def _kn_match_parts(query: str) -> tuple[list[str], list]:
|
||||
"""Build the shared token-AND match clause for the KaraokeNerds tables.
|
||||
|
||||
Matching is token-AND (every whitespace token must match the folded
|
||||
"artist title" haystack ``hay``), which mirrors the KaraokeNerds search box
|
||||
while tolerating "artist title" / "title artist" / partial queries. Two
|
||||
forms of tolerance per token:
|
||||
• accent-insensitive — both sides are diacritic-folded (so "maximo"
|
||||
matches "Maxïmo");
|
||||
• typo-tolerant — a token matches a catalog word within a small Levenshtein
|
||||
`EDIT_DISTANCE` (so "boxs" matches "Boxes"), scaled by token length to
|
||||
avoid noise on short words. Exact substring still matches (partials).
|
||||
|
||||
Returns flat rows ``{artist, title, brand, watch}``; the caller groups them.
|
||||
Returns ``(conditions, params)``; empty conditions means "no usable tokens,
|
||||
skip BigQuery entirely".
|
||||
"""
|
||||
def _fold(s: str) -> str:
|
||||
# Diacritic-fold + lowercase, mirroring the SQL haystack below, so an
|
||||
# ASCII query ("maximo") matches an accented catalog value ("Maxïmo").
|
||||
# Diacritic-fold + lowercase, mirroring _KN_FOLD_SQL, so an ASCII query
|
||||
# ("maximo") matches an accented catalog value ("Maxïmo").
|
||||
return "".join(
|
||||
c for c in unicodedata.normalize("NFD", s or "") if not unicodedata.combining(c)
|
||||
).lower()
|
||||
@@ -163,17 +196,6 @@ def _search_kn_community(query: str, limit: int = 50) -> list[dict]:
|
||||
return 1 if n <= 6 else 2
|
||||
|
||||
tokens = [t for t in (_fold(w) for w in query.split()) if t][:12]
|
||||
if not tokens:
|
||||
return []
|
||||
|
||||
client = bigquery.Client(project=GCP_PROJECT_ID)
|
||||
# Diacritic-fold the columns too (NFD + drop combining marks, then lower) so
|
||||
# matching is accent-insensitive on both sides — mirrors _fold() above.
|
||||
fold_sql = (
|
||||
"LOWER(REGEXP_REPLACE("
|
||||
"NORMALIZE(CONCAT(COALESCE(Artist, ''), ' ', COALESCE(Title, '')), NFD),"
|
||||
r" r'\p{Mn}', ''))"
|
||||
)
|
||||
conditions = []
|
||||
params = []
|
||||
for i, tok in enumerate(tokens):
|
||||
@@ -194,11 +216,29 @@ def _search_kn_community(query: str, limit: int = 50) -> list[dict]:
|
||||
f"WHERE EDIT_DISTANCE(w, @tok{i}) <= {thr}))"
|
||||
)
|
||||
params.append(bigquery.ScalarQueryParameter(f"tok{i}", "STRING", tok))
|
||||
return conditions, params
|
||||
|
||||
|
||||
def _search_kn_community(query: str, limit: int = 50) -> list[dict]:
|
||||
"""Search our OWN KaraokeNerds community catalog (never scrapes karaokenerds.com).
|
||||
|
||||
Reads `karaokenerds_community` — the free, directly-playable (web/YouTube)
|
||||
tracks populated daily by the authorized `kn-data-sync` export. Matching
|
||||
semantics live in `_kn_match_parts` (token-AND, accent-insensitive,
|
||||
typo-tolerant).
|
||||
|
||||
Returns flat rows ``{artist, title, brand, watch}``; the caller groups them.
|
||||
"""
|
||||
conditions, params = _kn_match_parts(query)
|
||||
if not conditions:
|
||||
return []
|
||||
|
||||
client = bigquery.Client(project=GCP_PROJECT_ID)
|
||||
params.append(bigquery.ScalarQueryParameter("limit", "INT64", limit))
|
||||
|
||||
sql = f"""
|
||||
WITH c AS (
|
||||
SELECT Artist, Title, Brand, Watch, {fold_sql} AS hay
|
||||
SELECT Artist, Title, Brand, Watch, {_KN_FOLD_SQL} AS hay
|
||||
FROM `{GCP_PROJECT_ID}.{DATASET}.karaokenerds_community`
|
||||
)
|
||||
SELECT Artist, Title, Brand, Watch
|
||||
@@ -227,6 +267,70 @@ def _search_kn_community(query: str, limit: int = 50) -> list[dict]:
|
||||
return results
|
||||
|
||||
|
||||
def _search_kn_all(query: str, limit: int = 50) -> dict:
|
||||
"""Search BOTH KaraokeNerds catalogs in one BigQuery job.
|
||||
|
||||
Community rows (`karaokenerds_community`) carry a single brand code plus a
|
||||
playable YouTube URL; full-catalog rows (`karaokenerds_raw`) carry the
|
||||
comma-separated brand-code list for EVERY karaoke release KN knows about —
|
||||
including commercial disc brands that have no web version (so no URL).
|
||||
Sharing one UNION query keeps latency identical to the community-only
|
||||
search, and the per-source `QUALIFY` limit stops a broad query on the
|
||||
~300k-row full catalog from starving the community rows.
|
||||
|
||||
Returns ``{"community": [{artist, title, brand, watch}],
|
||||
"full": [{artist, title, brands}]}``.
|
||||
"""
|
||||
conditions, params = _kn_match_parts(query)
|
||||
if not conditions:
|
||||
return {"community": [], "full": []}
|
||||
|
||||
client = bigquery.Client(project=GCP_PROJECT_ID)
|
||||
params.append(bigquery.ScalarQueryParameter("limit", "INT64", limit))
|
||||
|
||||
sql = f"""
|
||||
WITH c AS (
|
||||
SELECT 'community' AS src, Artist, Title, Brand AS brand_info, Watch,
|
||||
{_KN_FOLD_SQL} AS hay
|
||||
FROM `{GCP_PROJECT_ID}.{DATASET}.karaokenerds_community`
|
||||
UNION ALL
|
||||
SELECT 'full', Artist, Title, Brands, CAST(NULL AS STRING),
|
||||
{_KN_FOLD_SQL}
|
||||
FROM `{GCP_PROJECT_ID}.{DATASET}.karaokenerds_raw`
|
||||
)
|
||||
SELECT src, Artist, Title, brand_info, Watch
|
||||
FROM c
|
||||
WHERE {" AND ".join(conditions)}
|
||||
QUALIFY ROW_NUMBER() OVER (
|
||||
PARTITION BY src ORDER BY Artist, Title, brand_info) <= @limit
|
||||
ORDER BY Artist, Title, brand_info
|
||||
"""
|
||||
|
||||
# Same public-endpoint cost cap as _search_kn_community; the raw table is
|
||||
# still only tens of MB, so 1 GB is a generous ceiling.
|
||||
job_config = bigquery.QueryJobConfig(
|
||||
query_parameters=params,
|
||||
maximum_bytes_billed=1_000_000_000, # 1 GB ceiling
|
||||
)
|
||||
|
||||
out = {"community": [], "full": []}
|
||||
for row in client.query(sql, job_config=job_config).result():
|
||||
if row.src == "community":
|
||||
out["community"].append({
|
||||
"artist": row.Artist,
|
||||
"title": row.Title,
|
||||
"brand": row.brand_info,
|
||||
"watch": row.Watch,
|
||||
})
|
||||
else:
|
||||
out["full"].append({
|
||||
"artist": row.Artist,
|
||||
"title": row.Title,
|
||||
"brands": row.brand_info,
|
||||
})
|
||||
return out
|
||||
|
||||
|
||||
def _lookup_kn_ids(kn_ids: list[int]) -> dict[int, list[dict]]:
|
||||
"""Look up which KN songs have Divebar versions via the cross-reference table."""
|
||||
if not kn_ids:
|
||||
@@ -619,6 +723,22 @@ def divebar_lookup(request):
|
||||
results = _search_kn_community(query, limit)
|
||||
return _json_response({"status": "ok", "results": results, "count": len(results)})
|
||||
|
||||
elif action == "kn_search":
|
||||
raw_query = body.get("query")
|
||||
if not isinstance(raw_query, str) or not (query := raw_query.strip()):
|
||||
return _json_response({"status": "error", "message": "query required"}, 400)
|
||||
raw_limit = body.get("limit", 50)
|
||||
if isinstance(raw_limit, bool) or not isinstance(raw_limit, int):
|
||||
return _json_response({"status": "error", "message": "limit must be an integer"}, 400)
|
||||
limit = max(0, min(raw_limit, 200))
|
||||
both = _search_kn_all(query, limit)
|
||||
return _json_response({
|
||||
"status": "ok",
|
||||
"community": both["community"],
|
||||
"full": both["full"],
|
||||
"count": len(both["community"]) + len(both["full"]),
|
||||
})
|
||||
|
||||
elif action == "lookup":
|
||||
kn_ids = body.get("kn_ids", [])
|
||||
if not kn_ids or not isinstance(kn_ids, list):
|
||||
|
||||
@@ -244,6 +244,49 @@ def _kn_row(artist, title, brand, watch):
|
||||
return row
|
||||
|
||||
|
||||
class TestDivebarSearch:
|
||||
"""`search` matches accent-insensitively on both the query and the haystack."""
|
||||
|
||||
def _patch_query(self, monkeypatch, rows):
|
||||
captured = {}
|
||||
client = MagicMock()
|
||||
|
||||
def _query(sql, job_config=None):
|
||||
captured["sql"] = sql
|
||||
captured["params"] = job_config.query_parameters if job_config else []
|
||||
result = MagicMock()
|
||||
result.result.return_value = rows
|
||||
return result
|
||||
|
||||
client.query.side_effect = _query
|
||||
monkeypatch.setattr(main.bigquery, "Client", lambda project=None: client)
|
||||
return captured
|
||||
|
||||
def test_haystack_is_diacritic_folded(self, monkeypatch):
|
||||
captured = self._patch_query(monkeypatch, [])
|
||||
main._search_divebar("feliz navidad")
|
||||
sql = captured["sql"]
|
||||
# The artist/title haystack diacritic-folds (NORMALIZE NFD + drop
|
||||
# combining marks) so an ASCII query matches "José Feliciano".
|
||||
assert "NORMALIZE" in sql and r"\p{Mn}" in sql
|
||||
assert "divebar_catalog" in sql
|
||||
|
||||
def test_accented_query_is_folded_before_matching(self, monkeypatch):
|
||||
# Symmetric: an accented query must also match unaccented catalog rows.
|
||||
# bigquery is a stub module here, so capture the param factory's args.
|
||||
from types import SimpleNamespace
|
||||
captured = self._patch_query(monkeypatch, [])
|
||||
monkeypatch.setattr(
|
||||
main.bigquery, "ScalarQueryParameter",
|
||||
lambda name, typ, value: (name, typ, value))
|
||||
monkeypatch.setattr(
|
||||
main.bigquery, "QueryJobConfig",
|
||||
lambda **kw: SimpleNamespace(query_parameters=kw.get("query_parameters", [])))
|
||||
main._search_divebar("José Feliciano Feliz Navidad")
|
||||
pattern = next(p for p in captured["params"] if p[0] == "query_pattern")
|
||||
assert pattern[2] == "%jose feliciano feliz navidad%"
|
||||
|
||||
|
||||
class TestKnCommunitySearch:
|
||||
"""`kn_community_search` reads our own karaokenerds_community — no scraping."""
|
||||
|
||||
@@ -361,3 +404,96 @@ class TestKnCommunitySearch:
|
||||
MockRequest({"action": "kn_community_search", "query": "abba", "limit": -5})
|
||||
)
|
||||
assert status == 200
|
||||
|
||||
|
||||
def _kn_union_row(src, artist, title, brand_info, watch=None):
|
||||
row = MagicMock()
|
||||
row.src, row.Artist, row.Title, row.brand_info, row.Watch = (
|
||||
src, artist, title, brand_info, watch)
|
||||
return row
|
||||
|
||||
|
||||
class TestKnSearch:
|
||||
"""`kn_search` returns community + full-catalog rows from ONE BigQuery job."""
|
||||
|
||||
def _patch_query(self, monkeypatch, rows):
|
||||
captured = {}
|
||||
client = MagicMock()
|
||||
|
||||
def _query(sql, job_config=None):
|
||||
captured["sql"] = sql
|
||||
captured["params"] = job_config.query_parameters if job_config else []
|
||||
result = MagicMock()
|
||||
result.result.return_value = rows
|
||||
return result
|
||||
|
||||
client.query.side_effect = _query
|
||||
monkeypatch.setattr(main.bigquery, "Client", lambda project=None: client)
|
||||
return captured
|
||||
|
||||
def test_splits_rows_by_source(self, monkeypatch):
|
||||
rows = [
|
||||
_kn_union_row("community", "Tenacious D", "Tribute", "BELLY", "https://youtu.be/j"),
|
||||
_kn_union_row("full", "Tenacious D", "Tribute", "BELLY,CK,KV,SF"),
|
||||
]
|
||||
self._patch_query(monkeypatch, rows)
|
||||
out = main._search_kn_all("tenacious d tribute")
|
||||
assert out["community"] == [
|
||||
{"artist": "Tenacious D", "title": "Tribute", "brand": "BELLY", "watch": "https://youtu.be/j"},
|
||||
]
|
||||
assert out["full"] == [
|
||||
{"artist": "Tenacious D", "title": "Tribute", "brands": "BELLY,CK,KV,SF"},
|
||||
]
|
||||
|
||||
def test_queries_both_tables_in_one_job_with_per_source_limit(self, monkeypatch):
|
||||
# The whole point: a song with only commercial disc brands (in the raw
|
||||
# table, not the community table) must be findable — in a single BQ job,
|
||||
# with the limit applied per source so the 300k-row raw table can't
|
||||
# starve community rows.
|
||||
captured = self._patch_query(monkeypatch, [])
|
||||
main._search_kn_all("big green tractor")
|
||||
sql = captured["sql"]
|
||||
assert "karaokenerds_community" in sql
|
||||
assert "karaokenerds_raw" in sql
|
||||
assert "UNION ALL" in sql
|
||||
assert "QUALIFY" in sql and "PARTITION BY src" in sql
|
||||
|
||||
def test_same_matching_semantics_as_community_search(self, monkeypatch):
|
||||
# Both searches share _kn_match_parts — token-AND STRPOS + fuzzy fallback.
|
||||
captured = self._patch_query(monkeypatch, [])
|
||||
main._search_kn_all("daft punk one more time")
|
||||
sql = captured["sql"]
|
||||
assert sql.count("STRPOS(hay, @tok") == 5
|
||||
assert "LIKE" not in sql and "ESCAPE" not in sql
|
||||
assert "NORMALIZE" in sql and r"\p{Mn}" in sql
|
||||
|
||||
def test_blank_query_returns_empty_without_bq(self, monkeypatch):
|
||||
monkeypatch.setattr(main.bigquery, "Client",
|
||||
MagicMock(side_effect=AssertionError("BQ should not be called")))
|
||||
assert main._search_kn_all(" ") == {"community": [], "full": []}
|
||||
|
||||
def test_dispatch_returns_both_sets_and_count(self, monkeypatch):
|
||||
self._patch_query(monkeypatch, [
|
||||
_kn_union_row("community", "ABBA", "SOS", "NOMAD", "https://youtu.be/s"),
|
||||
_kn_union_row("full", "ABBA", "SOS", "NOMAD,SF,KV"),
|
||||
])
|
||||
body, status, _ = main.divebar_lookup(
|
||||
MockRequest({"action": "kn_search", "query": "abba sos"})
|
||||
)
|
||||
assert status == 200
|
||||
payload = json.loads(body)
|
||||
assert payload["status"] == "ok"
|
||||
assert payload["count"] == 2
|
||||
assert payload["community"][0]["watch"] == "https://youtu.be/s"
|
||||
assert payload["full"][0]["brands"] == "NOMAD,SF,KV"
|
||||
|
||||
def test_dispatch_missing_query_returns_400(self, monkeypatch):
|
||||
_body, status, _ = main.divebar_lookup(MockRequest({"action": "kn_search"}))
|
||||
assert status == 400
|
||||
|
||||
def test_dispatch_non_integer_limit_returns_400(self, monkeypatch):
|
||||
for bad in ("50", True, 1.5):
|
||||
_body, status, _ = main.divebar_lookup(
|
||||
MockRequest({"action": "kn_search", "query": "abba", "limit": bad})
|
||||
)
|
||||
assert status == 400, f"limit={bad!r} should be rejected"
|
||||
@@ -208,7 +208,60 @@ class WaveformGenerator:
|
||||
amplitudes.append(normalized)
|
||||
|
||||
return amplitudes, duration_seconds
|
||||
|
||||
|
||||
def generate_peaks(
|
||||
self,
|
||||
audio_path: str,
|
||||
peaks_per_second: int = 400,
|
||||
) -> Tuple[np.ndarray, float]:
|
||||
"""
|
||||
Generate a max-abs peak envelope at a fixed time resolution.
|
||||
|
||||
Mirrors the review frontend's ``computePeaks`` (lib/audio-data.ts):
|
||||
one peak per 1/peaks_per_second bucket, each the maximum absolute
|
||||
sample value across all channels, normalized to 0.0–1.0. Serving this
|
||||
pre-computed lets the review page draw per-segment waveform strips
|
||||
without downloading + decoding the whole vocal stem client-side.
|
||||
|
||||
Vectorized (numpy) — a 4-minute stereo track computes in well under a
|
||||
second, vs the pure-Python RMS loop in generate_data_only.
|
||||
|
||||
Returns:
|
||||
Tuple of (peaks float32 ndarray in 0..1, duration_seconds)
|
||||
"""
|
||||
path = Path(audio_path)
|
||||
if not path.exists():
|
||||
raise FileNotFoundError(f"Audio file not found: {audio_path}")
|
||||
|
||||
audio = AudioSegment.from_file(audio_path)
|
||||
duration_seconds = len(audio) / 1000.0
|
||||
|
||||
samples = np.abs(
|
||||
np.asarray(audio.get_array_of_samples(), dtype=np.float32)
|
||||
) / float(audio.max_possible_amplitude)
|
||||
if audio.channels > 1:
|
||||
# Interleaved -> (frames, channels) -> per-frame max across channels
|
||||
frames = len(samples) // audio.channels
|
||||
samples = samples[: frames * audio.channels]
|
||||
samples = samples.reshape(frames, audio.channels).max(axis=1)
|
||||
|
||||
bucket_count = max(1, math.ceil(duration_seconds * peaks_per_second))
|
||||
# Fractional stride with floored boundaries, matching the frontend's
|
||||
# drift-free bucketing (see the 44.1kHz drift fix notes there).
|
||||
samples_per_bucket = len(samples) / bucket_count
|
||||
boundaries = np.floor(np.arange(bucket_count + 1) * samples_per_bucket).astype(np.int64)
|
||||
boundaries[-1] = len(samples)
|
||||
|
||||
peaks = np.zeros(bucket_count, dtype=np.float32)
|
||||
# maximum.reduceat needs strictly valid starts; guard empty buckets.
|
||||
starts = boundaries[:-1]
|
||||
if len(samples):
|
||||
reduced = np.maximum.reduceat(samples, np.minimum(starts, len(samples) - 1))
|
||||
widths = boundaries[1:] - starts
|
||||
peaks = np.where(widths > 0, reduced, 0.0).astype(np.float32)
|
||||
|
||||
return peaks, duration_seconds
|
||||
|
||||
def _get_envelope(
|
||||
self,
|
||||
audio: AudioSegment,
|
||||
|
||||
@@ -36,10 +36,22 @@ class OutputConfig:
|
||||
output_styles_json: str
|
||||
default_max_line_length: int = 36
|
||||
styles: Dict[str, Any] = field(default_factory=dict)
|
||||
output_dir: Optional[str] = os.getcwd()
|
||||
cache_dir: str = os.getenv(
|
||||
"LYRICS_TRANSCRIBER_CACHE_DIR",
|
||||
os.path.join(os.path.expanduser("~"), "lyrics-transcriber-cache")
|
||||
# output_dir / cache_dir MUST use default_factory so they are resolved at
|
||||
# instantiation time, not at import time. The cloud lyrics worker sets
|
||||
# LYRICS_TRANSCRIBER_CACHE_DIR to a per-job temp dir at *runtime* (after this
|
||||
# module is already imported) so that the transcriber writes its cache where
|
||||
# the GCS cache-sync agent reads/writes it. A bare `os.getenv(...)` default is
|
||||
# captured once at import and ignores that runtime value — which silently
|
||||
# broke the cross-container AudioShake cache (transcriber wrote to
|
||||
# ~/lyrics-transcriber-cache while the sync used {temp}/lyrics-cache), so the
|
||||
# GCS cache never populated and every job made a fresh, credit-spending
|
||||
# AudioShake call. default_factory re-reads the env on each construction.
|
||||
output_dir: Optional[str] = field(default_factory=os.getcwd)
|
||||
cache_dir: str = field(
|
||||
default_factory=lambda: os.getenv(
|
||||
"LYRICS_TRANSCRIBER_CACHE_DIR",
|
||||
os.path.join(os.path.expanduser("~"), "lyrics-transcriber-cache"),
|
||||
)
|
||||
)
|
||||
|
||||
fetch_lyrics: bool = True
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-gen"
|
||||
version = "0.228.2"
|
||||
version = "0.232.0"
|
||||
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
|
||||
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
|
||||
license = "MIT"
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Concurrent review-page load test (the "10 tabs" regression guard).
|
||||
|
||||
Reproduces the 2026-09-18 incident scenario: N simultaneous lyrics-review tab
|
||||
loads, each firing the page's real GET trio (correction-data, waveform-data,
|
||||
audio/vocals with a Range header). Before v0.230.0 this melted the backend
|
||||
(9/30 requests 500'd, Cloud Run "no available instance"); after, all requests
|
||||
succeed with warm tabs completing in a few seconds.
|
||||
|
||||
Auth: per-job review tokens read from Firestore via ADC (read-only SA works) —
|
||||
no admin secret needed. Requests go through curl (browser-ish UA) because the
|
||||
Cloudflare WAF blocks python-urllib.
|
||||
|
||||
Usage:
|
||||
python scripts/load-test-review.py # 10 tabs vs prod
|
||||
python scripts/load-test-review.py --tabs 20
|
||||
python scripts/load-test-review.py --max-tab-seconds 45 # cold-cache run
|
||||
|
||||
Exit code 0 = pass (no failed requests, all tabs under --max-tab-seconds);
|
||||
1 = regression. Prints a per-request table either way.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import concurrent.futures
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
API_DEFAULT = "https://api.nomadkaraoke.com"
|
||||
UA = (
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
|
||||
"(KHTML, like Gecko) Chrome/128 Safari/537.36"
|
||||
)
|
||||
|
||||
|
||||
def fetch_review_jobs(limit: int) -> list[dict]:
|
||||
"""In-review jobs + review tokens from Firestore (ADC)."""
|
||||
os.environ.setdefault("GOOGLE_CLOUD_PROJECT", "nomadkaraoke")
|
||||
from google.cloud import firestore # type: ignore[import]
|
||||
|
||||
db = firestore.Client(project="nomadkaraoke")
|
||||
query = db.collection("jobs").where(
|
||||
filter=firestore.FieldFilter("status", "in", ["in_review", "awaiting_review"])
|
||||
).limit(limit * 2)
|
||||
jobs = []
|
||||
for doc in query.stream():
|
||||
data = doc.to_dict()
|
||||
token = data.get("review_token") or (data.get("state_data") or {}).get("review_token")
|
||||
if token:
|
||||
jobs.append({"job_id": doc.id, "token": token})
|
||||
if len(jobs) >= limit:
|
||||
break
|
||||
return jobs
|
||||
|
||||
|
||||
def curl(url: str, extra_args: list[str] | None = None, timeout: int = 90) -> dict:
|
||||
"""One GET via curl; returns {status, seconds, bytes}."""
|
||||
cmd = [
|
||||
"curl", "-sS", "-o", "/dev/null", "-A", UA, "--max-time", str(timeout),
|
||||
"-w", "%{http_code} %{time_total} %{size_download}",
|
||||
*(extra_args or []),
|
||||
url,
|
||||
]
|
||||
started = time.monotonic()
|
||||
proc = subprocess.run(cmd, capture_output=True, text=True)
|
||||
if proc.returncode != 0 and not proc.stdout.strip():
|
||||
return {"status": 0, "seconds": time.monotonic() - started, "bytes": 0}
|
||||
status, seconds, size = proc.stdout.strip().split()[:3]
|
||||
return {"status": int(status), "seconds": float(seconds), "bytes": int(size)}
|
||||
|
||||
|
||||
def tab_requests(api: str, job: dict) -> list[tuple[str, str, list[str]]]:
|
||||
base = f"{api}/api/review/{job['job_id']}"
|
||||
tok = f"review_token={job['token']}"
|
||||
return [
|
||||
("correction-data", f"{base}/correction-data?{tok}", []),
|
||||
("waveform-data", f"{base}/waveform-data?{tok}", []),
|
||||
("vocals", f"{base}/audio/vocals?{tok}", ["-r", "0-131071"]),
|
||||
]
|
||||
|
||||
|
||||
def simulate_tab(api: str, job: dict) -> dict:
|
||||
started = time.monotonic()
|
||||
results = {}
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=3) as pool:
|
||||
futures = {
|
||||
pool.submit(curl, url, extra): name
|
||||
for name, url, extra in tab_requests(api, job)
|
||||
}
|
||||
for fut in concurrent.futures.as_completed(futures):
|
||||
results[futures[fut]] = fut.result()
|
||||
return {"job_id": job["job_id"], "seconds": time.monotonic() - started, "requests": results}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--tabs", type=int, default=10)
|
||||
parser.add_argument("--api", default=API_DEFAULT)
|
||||
parser.add_argument(
|
||||
"--max-tab-seconds", type=float, default=20.0,
|
||||
help="Fail if any simulated tab takes longer than this (default 20; "
|
||||
"use ~45 for a cold-cache run where waveforms compute for the first time)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--jobs-file", default=None,
|
||||
help="JSON file of [{job_id, token}] to skip the Firestore lookup",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
if args.tabs < 1:
|
||||
parser.error("--tabs must be >= 1")
|
||||
|
||||
if args.jobs_file:
|
||||
jobs = json.load(open(args.jobs_file))[: args.tabs]
|
||||
else:
|
||||
print(f"Fetching up to {args.tabs} in-review jobs from Firestore…")
|
||||
jobs = fetch_review_jobs(args.tabs)
|
||||
if len(jobs) < args.tabs:
|
||||
# A partial run would "PASS" without reproducing the requested burst.
|
||||
print(
|
||||
f"Only {len(jobs)} in-review jobs available but --tabs {args.tabs} requested. "
|
||||
"Aborting — re-run with a smaller --tabs to test at reduced scale."
|
||||
)
|
||||
return 1
|
||||
print(f"Simulating {len(jobs)} concurrent review tabs against {args.api}\n")
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=len(jobs)) as pool:
|
||||
tabs = list(pool.map(lambda j: simulate_tab(args.api, j), jobs))
|
||||
|
||||
failed_requests = 0
|
||||
slow_tabs = 0
|
||||
for tab in sorted(tabs, key=lambda t: t["seconds"]):
|
||||
parts = []
|
||||
for name in ("correction-data", "waveform-data", "vocals"):
|
||||
r = tab["requests"][name]
|
||||
ok = 200 <= r["status"] < 300
|
||||
failed_requests += 0 if ok else 1
|
||||
parts.append(f"{name}={r['status']}({r['seconds']:.1f}s)")
|
||||
slow = tab["seconds"] > args.max_tab_seconds
|
||||
slow_tabs += 1 if slow else 0
|
||||
flag = " ← SLOW" if slow else ""
|
||||
print(f" {tab['job_id']} tab={tab['seconds']:5.1f}s {' '.join(parts)}{flag}")
|
||||
|
||||
total = len(jobs) * 3
|
||||
print(f"\n{total - failed_requests}/{total} requests OK; "
|
||||
f"{slow_tabs} tab(s) over {args.max_tab_seconds}s")
|
||||
if failed_requests or slow_tabs:
|
||||
print("RESULT: FAIL — concurrent review-load regression "
|
||||
"(see docs/archive/2026-09-18-concurrent-review-reliability-investigation-and-plan.md)")
|
||||
return 1
|
||||
print("RESULT: PASS")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,120 @@
|
||||
"""
|
||||
Tests for BaseTranscriber's on-disk cache round-trip.
|
||||
|
||||
This is the mechanism the OutputConfig.cache_dir fix depends on: the transcriber
|
||||
writes its raw + converted API responses into `cache_dir` (keyed by the audio
|
||||
file's MD5), and a subsequent transcription of the same audio reads them back
|
||||
instead of calling the (credit-spending) provider API. The cloud worker's GCS
|
||||
cache-sync relies on those files landing in the configured directory.
|
||||
"""
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from karaoke_gen.lyrics_transcriber.transcribers.base_transcriber import BaseTranscriber
|
||||
from karaoke_gen.lyrics_transcriber.types import TranscriptionData
|
||||
|
||||
|
||||
class FakeTranscriber(BaseTranscriber):
|
||||
"""Concrete transcriber that counts how often it hits the 'API'."""
|
||||
|
||||
def __init__(self, cache_dir, logger=None):
|
||||
super().__init__(cache_dir=cache_dir, logger=logger)
|
||||
self.perform_calls = 0
|
||||
|
||||
def get_name(self) -> str:
|
||||
return "FakeProvider"
|
||||
|
||||
def _perform_transcription(self, audio_filepath: str):
|
||||
self.perform_calls += 1
|
||||
# Raw API payload shape mirrors what real providers return before
|
||||
# conversion; here it is already the TranscriptionData dict form.
|
||||
return {
|
||||
"segments": [],
|
||||
"words": [],
|
||||
"text": "hello world",
|
||||
"source": "fakeprovider",
|
||||
"metadata": {"audio": os.path.basename(audio_filepath)},
|
||||
}
|
||||
|
||||
def _convert_result_format(self, raw_data) -> TranscriptionData:
|
||||
return TranscriptionData(
|
||||
segments=raw_data.get("segments", []),
|
||||
words=raw_data.get("words", []),
|
||||
text=raw_data["text"],
|
||||
source=raw_data["source"],
|
||||
metadata=raw_data.get("metadata", {}),
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def audio_file(tmp_path):
|
||||
path = tmp_path / "song.wav"
|
||||
path.write_bytes(b"deterministic fake audio bytes for md5 hashing")
|
||||
return str(path)
|
||||
|
||||
|
||||
def test_first_call_transcribes_and_writes_cache(tmp_path, audio_file):
|
||||
cache_dir = tmp_path / "cache"
|
||||
t = FakeTranscriber(cache_dir=str(cache_dir))
|
||||
|
||||
result = t.transcribe(audio_file)
|
||||
|
||||
assert result.text == "hello world"
|
||||
assert t.perform_calls == 1
|
||||
# Both raw and converted cache files land in the configured cache_dir,
|
||||
# named "{provider}_{audio_md5}_{suffix}.json".
|
||||
written = sorted(p.name for p in cache_dir.glob("fakeprovider_*.json"))
|
||||
assert any(name.endswith("_raw.json") for name in written)
|
||||
assert any(name.endswith("_converted.json") for name in written)
|
||||
|
||||
|
||||
def test_second_call_hits_converted_cache_without_reperforming(tmp_path, audio_file):
|
||||
cache_dir = tmp_path / "cache"
|
||||
t = FakeTranscriber(cache_dir=str(cache_dir))
|
||||
|
||||
t.transcribe(audio_file)
|
||||
assert t.perform_calls == 1
|
||||
|
||||
# Same audio -> same MD5 -> converted-cache hit -> no second API call.
|
||||
result2 = t.transcribe(audio_file)
|
||||
assert result2.text == "hello world"
|
||||
assert t.perform_calls == 1
|
||||
|
||||
|
||||
def test_raw_cache_hit_when_only_raw_present(tmp_path, audio_file):
|
||||
cache_dir = tmp_path / "cache"
|
||||
t = FakeTranscriber(cache_dir=str(cache_dir))
|
||||
t.transcribe(audio_file)
|
||||
|
||||
# Delete only the converted cache so the raw-cache branch is exercised.
|
||||
for p in cache_dir.glob("*_converted.json"):
|
||||
p.unlink()
|
||||
|
||||
result = t.transcribe(audio_file)
|
||||
assert result.text == "hello world"
|
||||
# Still no new API call — served from the raw cache.
|
||||
assert t.perform_calls == 1
|
||||
# The converted cache is rebuilt from raw.
|
||||
assert list(cache_dir.glob("*_converted.json"))
|
||||
|
||||
|
||||
def test_corrupt_cache_file_is_ignored(tmp_path, audio_file):
|
||||
cache_dir = tmp_path / "cache"
|
||||
t = FakeTranscriber(cache_dir=str(cache_dir))
|
||||
t.transcribe(audio_file)
|
||||
|
||||
# Corrupt both cache files -> loader returns None -> re-transcribes.
|
||||
for p in cache_dir.glob("fakeprovider_*.json"):
|
||||
p.write_text("{ not valid json")
|
||||
|
||||
result = t.transcribe(audio_file)
|
||||
assert result.text == "hello world"
|
||||
assert t.perform_calls == 2
|
||||
|
||||
|
||||
def test_missing_audio_file_raises(tmp_path):
|
||||
t = FakeTranscriber(cache_dir=str(tmp_path / "cache"))
|
||||
with pytest.raises(FileNotFoundError):
|
||||
t.transcribe(str(tmp_path / "does-not-exist.wav"))
|
||||
assert t.perform_calls == 0
|
||||
@@ -0,0 +1,62 @@
|
||||
"""
|
||||
Regression tests for OutputConfig.cache_dir / output_dir resolution timing.
|
||||
|
||||
Background: the cloud lyrics worker sets LYRICS_TRANSCRIBER_CACHE_DIR to a
|
||||
per-job temp dir at *runtime* (after the config module is already imported) so
|
||||
that the transcriber writes its AudioShake/lyrics cache into the same directory
|
||||
the GCS cache-sync agent reads/writes. Previously OutputConfig.cache_dir used a
|
||||
bare `os.getenv(...)` dataclass default, which is evaluated once at import time
|
||||
and therefore ignored the worker's runtime value. That silently broke the
|
||||
cross-container cache and made every job spend a fresh AudioShake credit.
|
||||
|
||||
These tests lock in that cache_dir (and output_dir) are resolved when an
|
||||
OutputConfig is *instantiated*, honoring the current environment.
|
||||
"""
|
||||
import os
|
||||
from unittest.mock import patch
|
||||
|
||||
from karaoke_gen.lyrics_transcriber.core.config import OutputConfig
|
||||
|
||||
|
||||
STYLES = "/tmp/does-not-need-to-exist-styles.json"
|
||||
|
||||
|
||||
def test_cache_dir_reads_env_set_after_import():
|
||||
"""cache_dir must reflect LYRICS_TRANSCRIBER_CACHE_DIR set at runtime."""
|
||||
runtime_dir = "/tmp/job-abc123/lyrics-cache"
|
||||
with patch.dict(os.environ, {"LYRICS_TRANSCRIBER_CACHE_DIR": runtime_dir}):
|
||||
config = OutputConfig(output_styles_json=STYLES)
|
||||
assert config.cache_dir == runtime_dir
|
||||
|
||||
|
||||
def test_cache_dir_falls_back_to_home_when_env_unset():
|
||||
"""Without the env var, cache_dir falls back to ~/lyrics-transcriber-cache."""
|
||||
env = {k: v for k, v in os.environ.items() if k != "LYRICS_TRANSCRIBER_CACHE_DIR"}
|
||||
with patch.dict(os.environ, env, clear=True):
|
||||
config = OutputConfig(output_styles_json=STYLES)
|
||||
expected = os.path.join(os.path.expanduser("~"), "lyrics-transcriber-cache")
|
||||
assert config.cache_dir == expected
|
||||
|
||||
|
||||
def test_cache_dir_is_reevaluated_per_instance():
|
||||
"""Two instances constructed under different env values must differ."""
|
||||
with patch.dict(os.environ, {"LYRICS_TRANSCRIBER_CACHE_DIR": "/tmp/first"}):
|
||||
first = OutputConfig(output_styles_json=STYLES)
|
||||
with patch.dict(os.environ, {"LYRICS_TRANSCRIBER_CACHE_DIR": "/tmp/second"}):
|
||||
second = OutputConfig(output_styles_json=STYLES)
|
||||
assert first.cache_dir == "/tmp/first"
|
||||
assert second.cache_dir == "/tmp/second"
|
||||
|
||||
|
||||
def test_explicit_cache_dir_argument_wins():
|
||||
"""An explicitly passed cache_dir overrides the env-derived default."""
|
||||
with patch.dict(os.environ, {"LYRICS_TRANSCRIBER_CACHE_DIR": "/tmp/env-dir"}):
|
||||
config = OutputConfig(output_styles_json=STYLES, cache_dir="/tmp/explicit")
|
||||
assert config.cache_dir == "/tmp/explicit"
|
||||
|
||||
|
||||
def test_output_dir_defaults_to_cwd_at_instantiation(tmp_path, monkeypatch):
|
||||
"""output_dir default should track the cwd at construction, not import."""
|
||||
monkeypatch.chdir(tmp_path)
|
||||
config = OutputConfig(output_styles_json=STYLES)
|
||||
assert os.path.realpath(config.output_dir) == os.path.realpath(str(tmp_path))
|
||||
@@ -0,0 +1,117 @@
|
||||
"""Tests for backend.utils.audio_filenames.
|
||||
|
||||
Regression tests for the 2026-09-17 incident where an uploaded MP3 with a
|
||||
~1.2 MB ID3 tag was downloaded to temp files named `*.flac`, making ffmpeg
|
||||
commit to the flac demuxer (extension fallback) and fail every consumer of
|
||||
the input audio (waveform, review transcode, preview encode, duration probe).
|
||||
"""
|
||||
|
||||
import os
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from backend.utils.audio_filenames import audio_content_type, local_audio_filename
|
||||
|
||||
|
||||
class TestLocalAudioFilename:
|
||||
def test_preserves_mp3_extension(self):
|
||||
assert local_audio_filename(
|
||||
"jobs/e026e727/input/Don Omar - El Elegido (Video Oficial) - (192 Kbps).mp3",
|
||||
"audio",
|
||||
) == "audio.mp3"
|
||||
|
||||
def test_preserves_flac_extension(self):
|
||||
assert local_audio_filename(
|
||||
"jobs/x/stems/backing_vocals.flac", "backing_vocals"
|
||||
) == "backing_vocals.flac"
|
||||
|
||||
def test_lowercases_extension(self):
|
||||
assert local_audio_filename("jobs/x/input/SONG.MP3", "input") == "input.mp3"
|
||||
|
||||
def test_unknown_extension_falls_back_to_bare_stem(self):
|
||||
# Bare name = no misleading hint; ffmpeg relies on content probing.
|
||||
assert local_audio_filename("jobs/x/input/file.xyz", "audio") == "audio"
|
||||
|
||||
def test_no_extension_falls_back_to_bare_stem(self):
|
||||
assert local_audio_filename("jobs/x/input/rawfile", "audio") == "audio"
|
||||
|
||||
def test_m4a_and_wav(self):
|
||||
assert local_audio_filename("a/b/song.m4a", "audio") == "audio.m4a"
|
||||
assert local_audio_filename("a/b/song.wav", "audio") == "audio.wav"
|
||||
|
||||
def test_dots_in_filename_only_last_suffix_used(self):
|
||||
assert local_audio_filename("a/b/artist - title (feat. x).mp3", "audio") == "audio.mp3"
|
||||
|
||||
|
||||
class TestAudioContentType:
|
||||
def test_common_types(self):
|
||||
assert audio_content_type("a/b/song.flac") == "audio/flac"
|
||||
assert audio_content_type("a/b/song.mp3") == "audio/mpeg"
|
||||
assert audio_content_type("a/b/song.M4A") == "audio/mp4"
|
||||
assert audio_content_type("a/b/song.ogg") == "audio/ogg"
|
||||
|
||||
def test_unknown_extension_is_octet_stream(self):
|
||||
assert audio_content_type("a/b/file.xyz") == "application/octet-stream"
|
||||
assert audio_content_type("a/b/file") == "application/octet-stream"
|
||||
|
||||
def test_transcode_fallback_uses_source_content_type(self):
|
||||
"""Regression: the transcode-failure fallback must not serve an MP3
|
||||
source as audio/flac."""
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
storage = MagicMock()
|
||||
storage.download_bytes.return_value = b"mp3bytes"
|
||||
service = AudioTranscodingService(storage_service=storage)
|
||||
service.transcode_if_needed = MagicMock(side_effect=RuntimeError("ffmpeg failed"))
|
||||
|
||||
data, content_type = service.get_review_audio_bytes("jobs/j1/input/song.mp3")
|
||||
assert data == b"mp3bytes"
|
||||
assert content_type == "audio/mpeg"
|
||||
|
||||
|
||||
class TestServicesUseSourceExtension:
|
||||
"""The services must download GCS audio to a temp name matching the
|
||||
source object's extension, not a hardcoded `.flac`."""
|
||||
|
||||
MP3_PATH = "jobs/j1/input/Song (192 Kbps).mp3"
|
||||
|
||||
def _capture_download(self):
|
||||
captured = {}
|
||||
|
||||
def fake_download(gcs_path, local_path):
|
||||
captured[gcs_path] = local_path
|
||||
# Write a stub so downstream code that opens the file can proceed
|
||||
# far enough for our assertion (tests stub out the analyzers).
|
||||
with open(local_path, "wb") as f:
|
||||
f.write(b"\x00")
|
||||
return local_path
|
||||
|
||||
return captured, fake_download
|
||||
|
||||
def test_transcoding_service_temp_name_matches_source(self):
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
|
||||
captured, fake_download = self._capture_download()
|
||||
storage = MagicMock()
|
||||
storage.download_file.side_effect = fake_download
|
||||
|
||||
service = AudioTranscodingService(storage_service=storage)
|
||||
try:
|
||||
service._transcode_and_upload(self.MP3_PATH, "jobs/j1/review-audio/out.ogg")
|
||||
except Exception:
|
||||
pass # ffmpeg on a stub file fails; we only assert the temp name
|
||||
assert os.path.basename(captured[self.MP3_PATH]) == "input.mp3"
|
||||
|
||||
def test_analysis_service_waveform_temp_name_matches_source(self):
|
||||
from backend.services.audio_analysis_service import AudioAnalysisService
|
||||
|
||||
captured, fake_download = self._capture_download()
|
||||
storage = MagicMock()
|
||||
storage.download_file.side_effect = fake_download
|
||||
|
||||
service = AudioAnalysisService(storage_service=storage)
|
||||
service.waveform_generator = MagicMock()
|
||||
service.waveform_generator.generate_data_only.return_value = ([0.0], 1.0)
|
||||
|
||||
service.get_waveform_data(self.MP3_PATH, "j1", num_points=10)
|
||||
assert os.path.basename(captured[self.MP3_PATH]) == "backing_vocals.mp3"
|
||||
@@ -98,6 +98,11 @@ class TestProcessAudioSeparationMode:
|
||||
|
||||
mock_jm = MagicMock()
|
||||
mock_jm.get_job.return_value = mock_job
|
||||
# advance_to_screens_if_ready is an async method that the worker awaits
|
||||
# after a successful separation (durable prep->screens handoff, #1002).
|
||||
# It must be an AsyncMock, or `await` raises TypeError and the worker
|
||||
# reports status=error / result=False.
|
||||
mock_jm.advance_to_screens_if_ready = AsyncMock(return_value=True)
|
||||
mock_job_manager_cls.return_value = mock_jm
|
||||
|
||||
mock_settings_obj = MagicMock()
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
"""Tests for WaveformGenerator.generate_peaks (review Waveforms-mode envelope)."""
|
||||
|
||||
import math
|
||||
import tempfile
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
from pydub import AudioSegment
|
||||
from pydub.generators import Sine
|
||||
|
||||
from karaoke_gen.instrumental_review.waveform import WaveformGenerator
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def stereo_wav(tmp_path_factory):
|
||||
"""3s stereo: -6dB 440Hz left, -20dB 880Hz right."""
|
||||
left = Sine(440).to_audio_segment(duration=3000).apply_gain(-6)
|
||||
right = Sine(880).to_audio_segment(duration=3000).apply_gain(-20)
|
||||
seg = AudioSegment.from_mono_audiosegments(left, right)
|
||||
path = tmp_path_factory.mktemp("audio") / "stereo.wav"
|
||||
seg.export(str(path), format="wav")
|
||||
return str(path)
|
||||
|
||||
|
||||
class TestGeneratePeaks:
|
||||
def test_bucket_count_and_duration(self, stereo_wav):
|
||||
peaks, duration = WaveformGenerator().generate_peaks(stereo_wav, peaks_per_second=400)
|
||||
assert duration == pytest.approx(3.0, abs=0.05)
|
||||
assert len(peaks) == math.ceil(duration * 400)
|
||||
|
||||
def test_peaks_are_max_abs_across_channels_normalized(self, stereo_wav):
|
||||
peaks, _ = WaveformGenerator().generate_peaks(stereo_wav, peaks_per_second=400)
|
||||
# The louder channel (-6 dB sine) dominates: peak amplitude ~10^(-6/20)=0.501
|
||||
assert float(peaks.max()) == pytest.approx(0.501, abs=0.01)
|
||||
assert float(peaks.min()) >= 0.0
|
||||
assert peaks.dtype == np.float32
|
||||
|
||||
def test_matches_naive_reference(self, stereo_wav):
|
||||
pps = 400
|
||||
peaks, duration = WaveformGenerator().generate_peaks(stereo_wav, peaks_per_second=pps)
|
||||
|
||||
audio = AudioSegment.from_file(stereo_wav)
|
||||
s = np.abs(np.asarray(audio.get_array_of_samples(), dtype=np.float32)) / audio.max_possible_amplitude
|
||||
frames = len(s) // audio.channels
|
||||
s = s[: frames * audio.channels].reshape(frames, audio.channels).max(axis=1)
|
||||
bucket_count = math.ceil(duration * pps)
|
||||
spb = len(s) / bucket_count
|
||||
ref = np.array(
|
||||
[
|
||||
s[math.floor(i * spb): (len(s) if i == bucket_count - 1 else max(math.floor((i + 1) * spb), math.floor(i * spb) + 1))].max()
|
||||
for i in range(bucket_count)
|
||||
],
|
||||
dtype=np.float32,
|
||||
)
|
||||
assert np.abs(ref - peaks).max() == 0.0
|
||||
|
||||
def test_missing_file_raises(self):
|
||||
with pytest.raises(FileNotFoundError):
|
||||
WaveformGenerator().generate_peaks("/nonexistent.wav")
|
||||
@@ -210,10 +210,90 @@ class TestTranscriptionStage:
|
||||
|
||||
with patch('karaoke_gen.lyrics_processor.LyricsProcessor', side_effect=Exception("Test error")):
|
||||
result = await stage.execute(context)
|
||||
|
||||
|
||||
assert result.status == StageStatus.FAILED
|
||||
assert "Test error" in result.error_message
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_execute_happy_path_builds_outputs(self, tmp_path):
|
||||
"""Full execute: transcribe, collect file outputs, parse countdown padding."""
|
||||
from karaoke_gen.pipeline.stages.transcription import TranscriptionStage
|
||||
from karaoke_gen.pipeline.context import PipelineContext
|
||||
from karaoke_gen.pipeline.base import StageStatus
|
||||
|
||||
output_dir = tmp_path / "out"
|
||||
lyrics_dir = output_dir / "lyrics"
|
||||
lyrics_dir.mkdir(parents=True)
|
||||
# A countdown padding file the stage should read back as a float.
|
||||
(lyrics_dir / "countdown_padding_seconds.txt").write_text("3.0\n")
|
||||
|
||||
stage = TranscriptionStage(skip_transcription=False)
|
||||
# style_params (no style_params_json) -> exercises the temp-file write branch.
|
||||
context = PipelineContext(
|
||||
job_id="test",
|
||||
artist="Artist",
|
||||
title="Title",
|
||||
input_audio_path="/audio.flac",
|
||||
output_dir=str(output_dir),
|
||||
style_params={"foo": "bar"},
|
||||
)
|
||||
|
||||
mock_processor = MagicMock()
|
||||
mock_processor.transcribe_lyrics.return_value = {
|
||||
"lrc_filepath": "/out/lyrics.lrc",
|
||||
"ass_filepath": "/out/lyrics.ass",
|
||||
"corrected_txt_path": "/out/corrected.txt",
|
||||
}
|
||||
mock_processor.corrections_result = {"corrections": []}
|
||||
|
||||
with patch('karaoke_gen.lyrics_processor.LyricsProcessor', return_value=mock_processor):
|
||||
result = await stage.execute(context)
|
||||
|
||||
assert result.status == StageStatus.COMPLETED
|
||||
assert result.outputs["lrc_filepath"] == "/out/lyrics.lrc"
|
||||
assert result.outputs["ass_filepath"] == "/out/lyrics.ass"
|
||||
assert result.outputs["corrected_txt_path"] == "/out/corrected.txt"
|
||||
assert result.outputs["corrections_result"] == {"corrections": []}
|
||||
assert result.outputs["countdown_padding_seconds"] == 3.0
|
||||
# transcribe_lyrics received the context's audio path and artist/title.
|
||||
_, kwargs = mock_processor.transcribe_lyrics.call_args
|
||||
assert kwargs["input_audio_wav"] == "/audio.flac"
|
||||
assert kwargs["artist"] == "Artist"
|
||||
|
||||
# style_params (no style_params_json) makes the stage write a temp file and
|
||||
# register it on the context; clean it up so the test leaves no /tmp files.
|
||||
context.cleanup_temp_paths()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_execute_ignores_malformed_countdown_file(self, tmp_path):
|
||||
"""A non-numeric countdown file is ignored, not fatal."""
|
||||
from karaoke_gen.pipeline.stages.transcription import TranscriptionStage
|
||||
from karaoke_gen.pipeline.context import PipelineContext
|
||||
from karaoke_gen.pipeline.base import StageStatus
|
||||
|
||||
output_dir = tmp_path / "out"
|
||||
lyrics_dir = output_dir / "lyrics"
|
||||
lyrics_dir.mkdir(parents=True)
|
||||
(lyrics_dir / "countdown_padding_seconds.txt").write_text("not-a-number")
|
||||
|
||||
stage = TranscriptionStage(skip_transcription=False)
|
||||
context = PipelineContext(
|
||||
job_id="test",
|
||||
artist="Artist",
|
||||
title="Title",
|
||||
input_audio_path="/audio.flac",
|
||||
output_dir=str(output_dir),
|
||||
)
|
||||
|
||||
mock_processor = MagicMock()
|
||||
mock_processor.transcribe_lyrics.return_value = {}
|
||||
|
||||
with patch('karaoke_gen.lyrics_processor.LyricsProcessor', return_value=mock_processor):
|
||||
result = await stage.execute(context)
|
||||
|
||||
assert result.status == StageStatus.COMPLETED
|
||||
assert "countdown_padding_seconds" not in result.outputs
|
||||
|
||||
|
||||
class TestScreensStage:
|
||||
"""Tests for ScreensStage."""
|
||||
|
||||
Reference in new issue
Block a user