mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-04 17:16:04 +09:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
30cf41e7d6 | ||
|
|
e0f3d1bb45 | ||
|
|
01440a1ec0 | ||
|
|
54edd0a8f9 | ||
|
|
b336f36f4e | ||
|
|
527d55ef63 | ||
|
|
f997cd7de2 | ||
|
|
303ff7e728 |
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"}
|
||||
+183
-46
@@ -13,6 +13,7 @@ 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
|
||||
@@ -41,6 +42,7 @@ 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 (
|
||||
@@ -245,7 +247,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)
|
||||
|
||||
@@ -277,12 +279,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:
|
||||
@@ -348,7 +403,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(
|
||||
@@ -631,7 +686,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"))
|
||||
|
||||
@@ -665,7 +724,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:
|
||||
@@ -673,7 +732,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")
|
||||
@@ -681,7 +740,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)
|
||||
@@ -724,19 +783,22 @@ async def get_correction_data(
|
||||
|
||||
# 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
|
||||
)
|
||||
@@ -764,33 +826,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.
|
||||
|
||||
@@ -801,7 +866,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"))
|
||||
|
||||
@@ -845,8 +910,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():
|
||||
@@ -873,13 +943,21 @@ _DEV_AUDIO_CACHE: Dict[str, Tuple[bytes, str]] = {}
|
||||
# BOUNDED cache of transcoded review-audio bytes for the PROD byte proxy (Option B).
|
||||
# Serving the ~3 MB OGG through the API means each play/seek would otherwise re-download
|
||||
# the object from GCS; cache a small number of recently-served objects so Range seeks and
|
||||
# repeat plays are cheap. Unlike _DEV_AUDIO_CACHE this is size-capped (LRU) so a busy prod
|
||||
# instance can't grow memory without limit — worst case ~_REVIEW_AUDIO_CACHE_MAX × object
|
||||
# size. Keyed by GCS path (the transcoded-OGG source), guarded by a lock for thread safety.
|
||||
# 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:
|
||||
@@ -890,18 +968,66 @@ def _review_audio_cache_get(path: str) -> Optional[Tuple[bytes, str]]:
|
||||
|
||||
|
||||
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.move_to_end(path)
|
||||
while len(_review_audio_cache) > _REVIEW_AUDIO_CACHE_MAX:
|
||||
_review_audio_cache.popitem(last=False) # evict least-recently-used
|
||||
_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()
|
||||
@@ -977,7 +1103,7 @@ async def get_instrumental_audio(
|
||||
if not stem_key:
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.audioNotFound"))
|
||||
|
||||
job = JobManager().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"))
|
||||
|
||||
@@ -987,13 +1113,9 @@ async def get_instrumental_audio(
|
||||
raise HTTPException(status_code=404, detail=t("en", "review.audioNotFound"))
|
||||
|
||||
try:
|
||||
cached = _review_audio_cache_get(source_gcs_path)
|
||||
if cached is None:
|
||||
from backend.services.audio_transcoding_service import AudioTranscodingService
|
||||
transcoding = AudioTranscodingService(storage_service=StorageService())
|
||||
cached = await transcoding.get_review_audio_bytes_async(source_gcs_path)
|
||||
_review_audio_cache_put(source_gcs_path, cached)
|
||||
data, content_type = cached
|
||||
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:
|
||||
@@ -1805,9 +1927,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)
|
||||
@@ -1979,7 +2099,7 @@ async def get_instrumental_urls(
|
||||
cheap, backwards-compatible way to do so. Returns the same shape as correction-data's
|
||||
``instrumental_options``.
|
||||
"""
|
||||
job = JobManager().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"))
|
||||
|
||||
@@ -2004,7 +2124,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"))
|
||||
|
||||
@@ -2071,6 +2191,16 @@ 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}/waveform-data")
|
||||
async def get_waveform_data(
|
||||
job_id: str,
|
||||
@@ -2081,12 +2211,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"))
|
||||
|
||||
@@ -2103,11 +2237,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,91 @@ 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
|
||||
|
||||
def cache_waveform_data(
|
||||
self,
|
||||
gcs_audio_path: str,
|
||||
@@ -343,7 +429,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,148 @@ 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
|
||||
@@ -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") == {}
|
||||
@@ -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."""
|
||||
|
||||
|
||||
@@ -1447,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"
|
||||
@@ -1821,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()
|
||||
@@ -1832,9 +1836,306 @@ 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())
|
||||
@@ -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
|
||||
@@ -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,25 @@ 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}")
|
||||
|
||||
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}")
|
||||
|
||||
+44
@@ -383,6 +383,23 @@ the query string (`?token=` for a full/owner token, `?review_token=` for a revie
|
||||
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
|
||||
@@ -2652,3 +2669,30 @@ 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).
|
||||
@@ -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:
|
||||
|
||||
@@ -329,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,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 }))
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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") {
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { AudioData, AudioNotReadyError, fetchAudioData } from '@/lib/audio-data'
|
||||
import { AudioData, AudioNotReadyError, fetchAudioData, 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 {
|
||||
@@ -14,6 +20,11 @@ export interface AudioDataLoaderProps extends PropsWithChildren {
|
||||
const NOT_READY_RETRY_MS = 15_000
|
||||
const NOT_READY_MAX_RETRIES = 40 // 40 × 15s = 10 minutes
|
||||
|
||||
// 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, children }: AudioDataLoaderProps) => {
|
||||
const [audioData, setAudioData] = useState<AudioData | null>(null)
|
||||
|
||||
@@ -25,24 +36,46 @@ export const VocalsAudioDataLoader = ({ audioUrl, children }: AudioDataLoaderPro
|
||||
// audioUrl has already been set.
|
||||
let cancelled = false
|
||||
let retryTimer: ReturnType<typeof setTimeout> | undefined
|
||||
const startedAt = Date.now()
|
||||
|
||||
const load = (attempt: number) => {
|
||||
const load = (attempt: number, transientAttempt: number) => {
|
||||
fetchAudioData(audioUrl)
|
||||
.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,
|
||||
})
|
||||
}
|
||||
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), NOT_READY_RETRY_MS)
|
||||
return
|
||||
}
|
||||
if (isTransientAudioError(error) && transientAttempt < TRANSIENT_RETRY_DELAYS_MS.length) {
|
||||
const delay = TRANSIENT_RETRY_DELAYS_MS[transientAttempt]
|
||||
console.warn(`Vocals audio load failed, retrying in ${delay / 1000}s`, error)
|
||||
retryTimer = setTimeout(() => load(attempt, transientAttempt + 1), delay)
|
||||
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)
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
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', () => {
|
||||
@@ -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())
|
||||
|
||||
|
||||
@@ -88,4 +88,43 @@ test.describe('Review fast-full-load contract', () => {
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -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 {
|
||||
@@ -83,7 +102,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"
|
||||
@@ -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.229.2"
|
||||
version = "0.231.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()
|
||||
|
||||
@@ -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