mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-27 01:18:42 +09:00
fix: harden 4 prod error paths (seek non-finite, auto-correct 429, download race + timeout) (#877)
## Summary Investigated and fixed four production error patterns flagged by the error monitor, each with tests. ## Changes **Frontend — `TypeError: currentTime non-finite`** (`/en/app/jobs` review UI) - Guard lyrics-review/audio-editor seek sinks (`AudioPlayer.seekAndPlay`/`handleSeek`, `AudioEditor.seekTo`) and the `handlePlaySegment` dispatcher with `Number.isFinite`; harden `TimelineEditor.handleTimelineClick` against a zero-width container. Restores parity with instrumental-review, which already had these guards. **Backend — auto-correct Vertex `429 RESOURCE_EXHAUSTED` surfaced as generic 502** - Retry model calls with exponential backoff on transient (rate-limit/overload) errors via `_is_transient_model_error`; surface a distinct **retryable 429** instead of 502. Retry env knobs parsed defensively (clamp + warn, never crash at import). **Backend — `audio-download-job` `InvalidStateTransitionError: downloading -> downloading`** - Root cause: a manual `/retry` raced the Cloud Run auto-retry; the losing run's post-download transition raised and the generic `except` `fail_job`'d a job the winner had already advanced. Fix: idempotent transition — re-read status first, treat an already-advanced job as success, and use `raise_on_invalid=False` so a race never fails a live job. **Backend/infra — `audio-download-job` 600s task-timeout SIGKILL** - Internal `wait_for_download` timeout equalled the Cloud Run task timeout, so slow torrents were SIGKILLed before failing gracefully (leaving the orphaned retry that fed the race above). New `DOWNLOAD_WAIT_TIMEOUT_SECONDS=1080` kept strictly below the task timeout, raised `600s → 1200s`. **Infra already applied to prod via `pulumi up` (targeted); stack is clean.** ## Testing - [x] Backend: 122 tests across touched suites pass (auto_correct incl. 10 retry/env, audio_download_worker incl. 3 race/timeout, review API, proactive) - [x] Frontend: full jest suite 1073/1073 pass (incl. new AudioPlayer non-finite guard test); `tsc` clean for changed files - [x] Infra: `pulumi preview` clean (273 unchanged) after applying timeout + reconciling pre-existing divebar drift ## Review - [x] Local CodeRabbit review completed (1 major finding — retry env validation — fixed + tested) - [x] Version bumped 0.190.5 → 0.191.0 @coderabbitai ignore --- 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
b8e67e6ba6
commit
ad3c0bffc0
12 files changed
+439
-15
No files matched your search
@@ -4,6 +4,7 @@ from __future__ import annotations
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
from dataclasses import asdict, dataclass, field
|
||||
@@ -35,9 +36,63 @@ VALID_CATEGORIES = {
|
||||
|
||||
|
||||
class AutoCorrectServiceError(Exception):
|
||||
def __init__(self, message: str, *, status_code: int = 400) -> None:
|
||||
def __init__(
|
||||
self, message: str, *, status_code: int = 400, retryable: bool = False
|
||||
) -> None:
|
||||
super().__init__(message)
|
||||
self.status_code = status_code
|
||||
# True for transient provider conditions (rate limits, overload) the
|
||||
# caller may safely retry; drives backoff in _call_model.
|
||||
self.retryable = retryable
|
||||
|
||||
|
||||
# Retry knobs for a single model call. Vertex 429 RESOURCE_EXHAUSTED is a
|
||||
# recurring, transient condition; a short app-level backoff lets quota recover
|
||||
# where the SDK's fast internal retry cannot. Kept small so a request never
|
||||
# stalls the review UI for long. Parsed defensively: a malformed env override
|
||||
# clamps to a safe value with a warning rather than crashing the backend at
|
||||
# import or breaking the retry loop.
|
||||
def _env_number(name: str, default: float, *, minimum: float, is_int: bool) -> float:
|
||||
raw = os.environ.get(name)
|
||||
if raw is None:
|
||||
return default
|
||||
try:
|
||||
val: float = int(raw) if is_int else float(raw)
|
||||
except ValueError:
|
||||
logger.warning("invalid %s=%r; using default %s", name, raw, default)
|
||||
return default
|
||||
import math as _math
|
||||
|
||||
if not _math.isfinite(val) or val < minimum:
|
||||
logger.warning(
|
||||
"%s=%s out of range (min %s); clamping to %s", name, val, minimum, minimum
|
||||
)
|
||||
return minimum
|
||||
return val
|
||||
|
||||
|
||||
_MODEL_CALL_MAX_ATTEMPTS = int(
|
||||
_env_number("AUTO_CORRECT_MODEL_MAX_ATTEMPTS", 3, minimum=1, is_int=True)
|
||||
)
|
||||
_MODEL_CALL_BACKOFF_SECONDS = float(
|
||||
_env_number("AUTO_CORRECT_MODEL_BACKOFF_SECONDS", 2.0, minimum=0.0, is_int=False)
|
||||
)
|
||||
|
||||
|
||||
def _is_transient_model_error(exc: BaseException) -> bool:
|
||||
"""True when a provider exception is a retryable rate-limit/overload.
|
||||
|
||||
Matches both structured status codes (google-genai ClientError/ServerError
|
||||
expose ``code``; Anthropic errors expose ``status_code``) and, as a
|
||||
fallback, the textual markers Vertex/Anthropic use — so detection survives
|
||||
SDK exception-class churn.
|
||||
"""
|
||||
code = getattr(exc, "code", None) or getattr(exc, "status_code", None)
|
||||
if isinstance(code, int) and code in {429, 500, 502, 503, 529}:
|
||||
return True
|
||||
text = str(exc).upper()
|
||||
markers = ("RESOURCE_EXHAUSTED", "UNAVAILABLE", "OVERLOADED", "429", "503", "529")
|
||||
return any(m in text for m in markers)
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -388,10 +443,33 @@ class AutoCorrectService:
|
||||
def _call_model(
|
||||
self, model: str, system_prompt: str, user_prompt: str, *, job_id: str
|
||||
) -> tuple[Any, Optional[TokenUsage]]:
|
||||
"""Return (parsed_json, token_usage). Usage is None if unreadable."""
|
||||
if model.startswith("claude"):
|
||||
return self._call_anthropic(model, system_prompt, user_prompt, job_id=job_id)
|
||||
return self._call_gemini(model, system_prompt, user_prompt, job_id=job_id)
|
||||
"""Return (parsed_json, token_usage). Usage is None if unreadable.
|
||||
|
||||
Transient provider errors (rate limits / overload, flagged
|
||||
``retryable``) are retried with exponential backoff. Permanent errors
|
||||
(misconfig, malformed output) fail fast.
|
||||
"""
|
||||
for attempt in range(1, _MODEL_CALL_MAX_ATTEMPTS + 1):
|
||||
try:
|
||||
if model.startswith("claude"):
|
||||
return self._call_anthropic(
|
||||
model, system_prompt, user_prompt, job_id=job_id
|
||||
)
|
||||
return self._call_gemini(
|
||||
model, system_prompt, user_prompt, job_id=job_id
|
||||
)
|
||||
except AutoCorrectServiceError as exc:
|
||||
if not exc.retryable or attempt == _MODEL_CALL_MAX_ATTEMPTS:
|
||||
raise
|
||||
backoff = _MODEL_CALL_BACKOFF_SECONDS * (2 ** (attempt - 1))
|
||||
logger.warning(
|
||||
"auto-correct model call transient failure job=%s model=%s "
|
||||
"attempt=%d/%d; retrying in %.1fs (%s)",
|
||||
job_id, model, attempt, _MODEL_CALL_MAX_ATTEMPTS, backoff, exc,
|
||||
)
|
||||
time.sleep(backoff)
|
||||
# Unreachable: the loop either returns or raises on the final attempt.
|
||||
raise AssertionError("retry loop exited without returning or raising")
|
||||
|
||||
@staticmethod
|
||||
def _anthropic_usage(response: Any) -> Optional[TokenUsage]:
|
||||
@@ -440,8 +518,6 @@ class AutoCorrectService:
|
||||
def _call_anthropic(
|
||||
self, model: str, system_prompt: str, user_prompt: str, *, job_id: str
|
||||
) -> tuple[Any, Optional[TokenUsage]]:
|
||||
import os
|
||||
|
||||
import anthropic
|
||||
|
||||
if not os.environ.get("ANTHROPIC_API_KEY"):
|
||||
@@ -478,6 +554,16 @@ class AutoCorrectService:
|
||||
output_config={"format": {"type": "json_schema", "schema": strict_schema}},
|
||||
)
|
||||
except Exception as exc:
|
||||
if _is_transient_model_error(exc):
|
||||
logger.warning(
|
||||
"auto-correct model rate-limited/overloaded job=%s model=%s (%s)",
|
||||
job_id, model, exc,
|
||||
)
|
||||
raise AutoCorrectServiceError(
|
||||
"AI model is temporarily rate-limited",
|
||||
status_code=429,
|
||||
retryable=True,
|
||||
) from exc
|
||||
logger.exception("auto-correct model call failed job=%s model=%s", job_id, model)
|
||||
raise AutoCorrectServiceError(
|
||||
"AI model call failed", status_code=502
|
||||
@@ -520,6 +606,16 @@ class AutoCorrectService:
|
||||
),
|
||||
)
|
||||
except Exception as exc: # surface as 502, never a stuck job
|
||||
if _is_transient_model_error(exc):
|
||||
logger.warning(
|
||||
"auto-correct model rate-limited/overloaded job=%s model=%s (%s)",
|
||||
job_id, model, exc,
|
||||
)
|
||||
raise AutoCorrectServiceError(
|
||||
"AI model is temporarily rate-limited",
|
||||
status_code=429,
|
||||
retryable=True,
|
||||
) from exc
|
||||
logger.exception("auto-correct model call failed job=%s model=%s", job_id, model)
|
||||
raise AutoCorrectServiceError(
|
||||
"AI model call failed", status_code=502
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
"""Tests for model-call retry/backoff on transient Vertex/Anthropic errors.
|
||||
|
||||
A Vertex 429 RESOURCE_EXHAUSTED is a recurring, transient condition (other
|
||||
call sites like parse_titles degrade gracefully). Auto-correct should retry
|
||||
with backoff and only surface a distinct, retryable 429 to the caller when
|
||||
the rate limit persists — never a generic 502 that reads as a hard failure.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from backend.services.auto_correct.service import (
|
||||
AutoCorrectService,
|
||||
AutoCorrectServiceError,
|
||||
_env_number,
|
||||
_is_transient_model_error,
|
||||
)
|
||||
|
||||
|
||||
class _FakeClientError(Exception):
|
||||
"""Mimics google.genai.errors.ClientError (has a numeric ``code``)."""
|
||||
|
||||
def __init__(self, code: int, message: str) -> None:
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
|
||||
|
||||
def _service() -> AutoCorrectService:
|
||||
return AutoCorrectService()
|
||||
|
||||
|
||||
def test_is_transient_detects_429_resource_exhausted() -> None:
|
||||
exc = _FakeClientError(429, "429 RESOURCE_EXHAUSTED. Resource exhausted.")
|
||||
assert _is_transient_model_error(exc) is True
|
||||
|
||||
|
||||
def test_is_transient_detects_503_and_overloaded() -> None:
|
||||
assert _is_transient_model_error(_FakeClientError(503, "UNAVAILABLE")) is True
|
||||
assert _is_transient_model_error(Exception("529 overloaded_error")) is True
|
||||
|
||||
|
||||
def test_is_transient_ignores_permanent_client_errors() -> None:
|
||||
assert _is_transient_model_error(_FakeClientError(400, "INVALID_ARGUMENT")) is False
|
||||
assert _is_transient_model_error(ValueError("bad schema")) is False
|
||||
|
||||
|
||||
def test_env_number_uses_default_when_unset(monkeypatch) -> None:
|
||||
monkeypatch.delenv("AC_TEST_KNOB", raising=False)
|
||||
assert _env_number("AC_TEST_KNOB", 3, minimum=1, is_int=True) == 3
|
||||
|
||||
|
||||
def test_env_number_clamps_below_minimum(monkeypatch) -> None:
|
||||
monkeypatch.setenv("AC_TEST_KNOB", "0")
|
||||
assert _env_number("AC_TEST_KNOB", 3, minimum=1, is_int=True) == 1
|
||||
|
||||
|
||||
def test_env_number_falls_back_on_garbage(monkeypatch) -> None:
|
||||
monkeypatch.setenv("AC_TEST_KNOB", "not-a-number")
|
||||
assert _env_number("AC_TEST_KNOB", 2.0, minimum=0.0, is_int=False) == 2.0
|
||||
|
||||
|
||||
def test_env_number_rejects_non_finite(monkeypatch) -> None:
|
||||
monkeypatch.setenv("AC_TEST_KNOB", "inf")
|
||||
assert _env_number("AC_TEST_KNOB", 2.0, minimum=0.0, is_int=False) == 0.0
|
||||
|
||||
|
||||
def test_retryable_call_retries_then_succeeds() -> None:
|
||||
"""A transient failure is retried; a later success is returned."""
|
||||
service = _service()
|
||||
attempts = {"n": 0}
|
||||
|
||||
def flaky(model, system_prompt, user_prompt, *, job_id):
|
||||
attempts["n"] += 1
|
||||
if attempts["n"] < 3:
|
||||
raise AutoCorrectServiceError(
|
||||
"AI model is rate-limited", status_code=429, retryable=True
|
||||
)
|
||||
return {"suggestions": []}, None
|
||||
|
||||
with patch.object(service, "_call_gemini", side_effect=flaky), \
|
||||
patch.object(service, "_call_anthropic", side_effect=flaky), \
|
||||
patch("backend.services.auto_correct.service.time.sleep") as sleep:
|
||||
raw, usage = service._call_model(
|
||||
"gemini-3.1-pro-preview", "sys", "user", job_id="job-1"
|
||||
)
|
||||
|
||||
assert raw == {"suggestions": []}
|
||||
assert attempts["n"] == 3
|
||||
assert sleep.call_count == 2 # slept before each retry
|
||||
|
||||
|
||||
def test_retryable_call_exhausts_and_raises_429() -> None:
|
||||
"""Persistent rate-limit surfaces a retryable 429, not a generic 502."""
|
||||
service = _service()
|
||||
|
||||
def always_rate_limited(model, system_prompt, user_prompt, *, job_id):
|
||||
raise AutoCorrectServiceError(
|
||||
"AI model is rate-limited", status_code=429, retryable=True
|
||||
)
|
||||
|
||||
with patch.object(service, "_call_gemini", side_effect=always_rate_limited), \
|
||||
patch("backend.services.auto_correct.service.time.sleep"), \
|
||||
patch("backend.services.auto_correct.service._MODEL_CALL_MAX_ATTEMPTS", 3):
|
||||
with pytest.raises(AutoCorrectServiceError) as ei:
|
||||
service._call_model("gemini-3.1-pro-preview", "sys", "user", job_id="j")
|
||||
|
||||
assert ei.value.status_code == 429
|
||||
assert ei.value.retryable is True
|
||||
|
||||
|
||||
def test_non_retryable_error_fails_fast_without_sleeping() -> None:
|
||||
"""A permanent error (e.g. bad output) is not retried."""
|
||||
service = _service()
|
||||
calls = {"n": 0}
|
||||
|
||||
def bad_output(model, system_prompt, user_prompt, *, job_id):
|
||||
calls["n"] += 1
|
||||
raise AutoCorrectServiceError("AI returned non-JSON output", status_code=502)
|
||||
|
||||
with patch.object(service, "_call_gemini", side_effect=bad_output), \
|
||||
patch("backend.services.auto_correct.service.time.sleep") as sleep:
|
||||
with pytest.raises(AutoCorrectServiceError) as ei:
|
||||
service._call_model("gemini-3.1-pro-preview", "sys", "user", job_id="j")
|
||||
|
||||
assert calls["n"] == 1
|
||||
assert ei.value.status_code == 502
|
||||
sleep.assert_not_called()
|
||||
@@ -14,10 +14,41 @@ from backend.workers.audio_download_worker import (
|
||||
process_audio_download,
|
||||
_extract_gcs_path,
|
||||
_download_audio,
|
||||
DOWNLOAD_WAIT_TIMEOUT_SECONDS,
|
||||
)
|
||||
from backend.services.audio_search_service import DownloadError
|
||||
|
||||
|
||||
def _cloud_run_task_timeout_seconds() -> int:
|
||||
"""Parse the audio-download-job task timeout from the Pulumi module."""
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
src = (
|
||||
pathlib.Path(__file__).resolve().parents[2]
|
||||
/ "infrastructure" / "modules" / "cloud_run.py"
|
||||
).read_text()
|
||||
# The audio-download job block sets timeout="NNNNs" right before max_retries.
|
||||
m = re.search(r'timeout="(\d+)s",\s*\n\s*max_retries=2,\s*\n\s*vpc_access=', src)
|
||||
assert m, "could not locate audio-download-job timeout in cloud_run.py"
|
||||
return int(m.group(1))
|
||||
|
||||
|
||||
def test_download_wait_timeout_below_cloud_run_task_timeout():
|
||||
"""The in-worker download wait MUST expire before Cloud Run SIGKILLs the task.
|
||||
|
||||
If they are equal (the old 600s/600s), the SIGKILL bypasses graceful
|
||||
failure handling and leaves an in-flight auto-retry racing manual retries
|
||||
(job 1cd29294). Keep meaningful headroom for the final upload + transition.
|
||||
"""
|
||||
task_timeout = _cloud_run_task_timeout_seconds()
|
||||
assert DOWNLOAD_WAIT_TIMEOUT_SECONDS < task_timeout, (
|
||||
f"download wait {DOWNLOAD_WAIT_TIMEOUT_SECONDS}s must be < Cloud Run "
|
||||
f"task timeout {task_timeout}s"
|
||||
)
|
||||
assert task_timeout - DOWNLOAD_WAIT_TIMEOUT_SECONDS >= 60
|
||||
|
||||
|
||||
def _make_job(
|
||||
job_id: str = "test-job-123",
|
||||
status=JobStatus.DOWNLOADING_AUDIO,
|
||||
@@ -195,6 +226,83 @@ class TestProcessAudioDownload:
|
||||
mock_ws.trigger_audio_worker.assert_not_awaited()
|
||||
mock_ws.trigger_lyrics_worker.assert_not_awaited()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_concurrent_run_completing_mid_download_is_idempotent(self):
|
||||
"""A second run finishing while we download must not fail the job.
|
||||
|
||||
Regression for job 1cd29294: a manual /retry raced this task's Cloud
|
||||
Run auto-retry. The loser downloaded, then tried DOWNLOADING ->
|
||||
DOWNLOADING, which raised InvalidStateTransitionError, and the generic
|
||||
except marked a job the winner had already advanced as FAILED. The
|
||||
loser must instead detect the advance and return success without
|
||||
transitioning, failing, or re-triggering downstream workers.
|
||||
"""
|
||||
entry_job = _make_job(status=JobStatus.DOWNLOADING_AUDIO)
|
||||
# By the time our download finishes, a concurrent run advanced the job.
|
||||
advanced_job = _make_job(status=JobStatus.DOWNLOADING)
|
||||
|
||||
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
|
||||
patch("backend.workers.audio_download_worker.StorageService"), \
|
||||
patch("backend.workers.audio_download_worker._download_audio", new_callable=AsyncMock) as mock_dl, \
|
||||
patch("backend.workers.audio_download_worker.get_worker_service") as mock_ws_factory:
|
||||
|
||||
mock_jm = MagicMock()
|
||||
# Entry sees DOWNLOADING_AUDIO; the pre-transition re-read sees the
|
||||
# concurrent run's advance to DOWNLOADING.
|
||||
mock_jm.get_job.side_effect = [entry_job, advanced_job]
|
||||
mock_jm_cls.return_value = mock_jm
|
||||
|
||||
mock_dl.return_value = ("uploads/test-job-123/audio/song.mp3", "song.mp3")
|
||||
|
||||
mock_ws = AsyncMock()
|
||||
mock_ws_factory.return_value = mock_ws
|
||||
|
||||
result = await process_audio_download("test-job-123")
|
||||
|
||||
assert result is True
|
||||
mock_dl.assert_awaited_once() # we did download before detecting the race
|
||||
mock_jm.transition_to_state.assert_not_called()
|
||||
mock_jm.fail_job.assert_not_called()
|
||||
mock_ws.trigger_audio_worker.assert_not_awaited()
|
||||
mock_ws.trigger_lyrics_worker.assert_not_awaited()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_invalid_transition_at_commit_treated_as_success_if_advanced(self):
|
||||
"""A race that slips past the guard still must not fail the job.
|
||||
|
||||
If the job advances between the pre-transition re-read and the
|
||||
transition itself, transition_to_state returns False (raise_on_invalid
|
||||
is off); we re-read, see the advance, and return success.
|
||||
"""
|
||||
entry_job = _make_job(status=JobStatus.DOWNLOADING_AUDIO)
|
||||
|
||||
with patch("backend.workers.audio_download_worker.JobManager") as mock_jm_cls, \
|
||||
patch("backend.workers.audio_download_worker.StorageService"), \
|
||||
patch("backend.workers.audio_download_worker._download_audio", new_callable=AsyncMock) as mock_dl, \
|
||||
patch("backend.workers.audio_download_worker.get_worker_service") as mock_ws_factory:
|
||||
|
||||
mock_jm = MagicMock()
|
||||
# Entry + pre-transition guard both see DOWNLOADING_AUDIO (guard
|
||||
# passes); the transition fails; the post-failure re-read sees the
|
||||
# concurrent advance.
|
||||
mock_jm.get_job.side_effect = [
|
||||
entry_job,
|
||||
_make_job(status=JobStatus.DOWNLOADING_AUDIO),
|
||||
_make_job(status=JobStatus.DOWNLOADING),
|
||||
]
|
||||
mock_jm.transition_to_state.return_value = False
|
||||
mock_jm_cls.return_value = mock_jm
|
||||
|
||||
mock_dl.return_value = ("uploads/test-job-123/audio/song.mp3", "song.mp3")
|
||||
mock_ws = AsyncMock()
|
||||
mock_ws_factory.return_value = mock_ws
|
||||
|
||||
result = await process_audio_download("test-job-123")
|
||||
|
||||
assert result is True
|
||||
mock_jm.fail_job.assert_not_called()
|
||||
mock_ws.trigger_audio_worker.assert_not_awaited()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_uses_state_data_selection_when_available(self):
|
||||
"""Should prefer state_data search results over job-level params."""
|
||||
|
||||
@@ -80,6 +80,15 @@ DOWNLOAD_ALREADY_DONE_STATUSES = frozenset({
|
||||
JobStatus.CANCELLED,
|
||||
})
|
||||
|
||||
# How long to wait for a flacfetch download before giving up. This MUST stay
|
||||
# strictly below the Cloud Run task `timeout` for audio-download-job (see
|
||||
# infrastructure/modules/cloud_run.py::create_audio_download_job). If they are
|
||||
# equal, Cloud Run SIGKILLs the task before this timeout can fire, so the
|
||||
# worker never records retry-pending or fails gracefully — leaving an in-flight
|
||||
# auto-retry that races manual retries (job 1cd29294). The headroom below the
|
||||
# task timeout covers the final GCS upload + state transition.
|
||||
DOWNLOAD_WAIT_TIMEOUT_SECONDS = 1080 # task timeout is 1200s
|
||||
|
||||
|
||||
def _current_task_attempt() -> int:
|
||||
"""Read CLOUD_RUN_TASK_ATTEMPT env var injected by Cloud Run Jobs.
|
||||
@@ -227,6 +236,22 @@ async def process_audio_download(job_id: str) -> bool:
|
||||
storage_service=storage_service,
|
||||
)
|
||||
|
||||
# Concurrency guard: a second download run may have completed while we
|
||||
# were downloading — e.g. a manual /retry racing this task's Cloud Run
|
||||
# auto-retry. Re-read status now (it was read once at entry, before a
|
||||
# potentially minutes-long download). If another run already advanced
|
||||
# the job, treat this as an idempotent success: don't re-write the input
|
||||
# path, don't re-transition (that would be an invalid
|
||||
# downloading -> downloading), and don't re-trigger downstream workers.
|
||||
# The winning run owns all of that.
|
||||
latest = job_manager.get_job(job_id)
|
||||
if latest and latest.status in DOWNLOAD_ALREADY_DONE_STATUSES:
|
||||
logger.info(
|
||||
f"[job:{job_id}] Another run already advanced the job "
|
||||
f"(status={latest.status}); skipping duplicate transition/triggers"
|
||||
)
|
||||
return True
|
||||
|
||||
# Update job with GCS path
|
||||
job_manager.update_job(job_id, {
|
||||
'input_media_gcs_path': audio_gcs_path,
|
||||
@@ -241,13 +266,32 @@ async def process_audio_download(job_id: str) -> bool:
|
||||
# previous error so the UI stops showing a resolved failure.
|
||||
_clear_retry_pending_and_error(job_manager, job_id)
|
||||
|
||||
# Transition from DOWNLOADING_AUDIO to DOWNLOADING
|
||||
job_manager.transition_to_state(
|
||||
# Transition from DOWNLOADING_AUDIO (or FAILED, on recovery) to
|
||||
# DOWNLOADING. Use raise_on_invalid=False so a tight race that slipped
|
||||
# past the guard above (another run advancing the job between our
|
||||
# re-read and here) does NOT raise into the generic except and fail_job
|
||||
# a job another run already succeeded on.
|
||||
transitioned = job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.DOWNLOADING,
|
||||
progress=15,
|
||||
message="Audio downloaded, starting processing"
|
||||
message="Audio downloaded, starting processing",
|
||||
raise_on_invalid=False,
|
||||
)
|
||||
if not transitioned:
|
||||
latest = job_manager.get_job(job_id)
|
||||
if latest and latest.status in DOWNLOAD_ALREADY_DONE_STATUSES:
|
||||
logger.info(
|
||||
f"[job:{job_id}] Concurrent run advanced job during transition "
|
||||
f"(status={latest.status}); treating as idempotent success"
|
||||
)
|
||||
return True
|
||||
# Genuinely unexpected state (not a concurrency case) — surface it
|
||||
# through the normal failure path so retry-pending is recorded.
|
||||
raise DownloadError(
|
||||
f"Could not transition to DOWNLOADING "
|
||||
f"(status={latest.status if latest else 'missing'})"
|
||||
)
|
||||
|
||||
# Check if audio editing was requested — enter blocking state instead of processing
|
||||
job = job_manager.get_job(job_id)
|
||||
@@ -423,7 +467,7 @@ async def _download_torrent(
|
||||
|
||||
final_status = await flacfetch_client.wait_for_download(
|
||||
download_id,
|
||||
timeout=600,
|
||||
timeout=DOWNLOAD_WAIT_TIMEOUT_SECONDS,
|
||||
)
|
||||
|
||||
filepath = final_status.get("gcs_path") or final_status.get("output_path")
|
||||
@@ -461,7 +505,7 @@ async def _download_spotify(
|
||||
|
||||
final_status = await flacfetch_client.wait_for_download(
|
||||
download_id,
|
||||
timeout=600,
|
||||
timeout=DOWNLOAD_WAIT_TIMEOUT_SECONDS,
|
||||
)
|
||||
|
||||
filepath = final_status.get("gcs_path") or final_status.get("output_path")
|
||||
|
||||
+3
-1
@@ -630,7 +630,9 @@ best-effort — storage failures degrade to a normal uncached run.
|
||||
|
||||
`op` is `replace` | `delete` | `insert_after` (for `insert_after`, `word_ids`
|
||||
holds the anchor word). Errors: `422` when no reference lyrics are available,
|
||||
`400` for invalid settings, `502` when the model call fails or returns
|
||||
`400` for invalid settings, `429` when the model provider is temporarily
|
||||
rate-limited (transient — retryable; the service already retries with backoff
|
||||
before surfacing this), `502` when the model call otherwise fails or returns
|
||||
malformed output. Design/eval background:
|
||||
`docs/archive/2026-06-10-lyrics-auto-correction-reeval-plan.md`.
|
||||
|
||||
|
||||
@@ -495,6 +495,9 @@ export function AudioEditor({ job }: AudioEditorProps) {
|
||||
const seekTo = useCallback((time: number) => {
|
||||
const audio = audioRef.current
|
||||
if (!audio) return
|
||||
// Math.min/max propagate NaN, so a non-finite input still throws on the
|
||||
// currentTime assignment — reject it before clamping.
|
||||
if (!Number.isFinite(time)) return
|
||||
audio.currentTime = Math.max(0, Math.min(time, audio.duration || currentDuration))
|
||||
setCurrentTime(audio.currentTime)
|
||||
}, [currentDuration])
|
||||
|
||||
@@ -134,6 +134,9 @@ export default function AudioPlayer({ audioUrl, onTimeUpdate }: AudioPlayerProps
|
||||
const handleSeek = (value: number[]) => {
|
||||
if (!audioRef.current || !isReadyRef.current) return
|
||||
const time = value[0]
|
||||
// Non-finite (NaN/Infinity) throws "The provided double value is
|
||||
// non-finite" when assigned to currentTime — guard the sink.
|
||||
if (!Number.isFinite(time)) return
|
||||
audioRef.current.currentTime = time
|
||||
setCurrentTime(time)
|
||||
}
|
||||
@@ -146,6 +149,9 @@ export default function AudioPlayer({ audioUrl, onTimeUpdate }: AudioPlayerProps
|
||||
|
||||
const seekAndPlay = useCallback((time: number) => {
|
||||
if (!audioRef.current || !isReadyRef.current) return
|
||||
// A non-finite target (e.g. a click that resolved to NaN/Infinity) throws
|
||||
// on assignment to currentTime; drop it rather than crash the review UI.
|
||||
if (!Number.isFinite(time)) return
|
||||
|
||||
audioRef.current.currentTime = time
|
||||
setCurrentTime(time)
|
||||
|
||||
@@ -1070,6 +1070,9 @@ export default function LyricsAnalyzer({
|
||||
if (typeof window !== 'undefined' && window.seekAndPlayAudio) {
|
||||
const adjustedStartTime =
|
||||
timingOffsetMs !== 0 ? startTime + timingOffsetMs / 1000 : startTime
|
||||
// A caller can resolve to a non-finite time (e.g. an untimed segment or
|
||||
// a zero-width timeline click); don't forward it to the media element.
|
||||
if (!Number.isFinite(adjustedStartTime)) return
|
||||
window.seekAndPlayAudio(adjustedStartTime)
|
||||
}
|
||||
},
|
||||
|
||||
@@ -213,9 +213,13 @@ export default function TimelineEditor({
|
||||
const handleTimelineClick = (e: React.MouseEvent) => {
|
||||
const rect = containerRef.current?.getBoundingClientRect()
|
||||
if (!rect || !onPlaySegment) return
|
||||
// A not-yet-laid-out container has zero width, making the ratio non-finite;
|
||||
// bail so we never hand a NaN/Infinity time to the audio element.
|
||||
if (rect.width <= 0) return
|
||||
|
||||
const x = e.clientX - rect.left
|
||||
const clickedPosition = (x / rect.width) * (endTime - startTime) + startTime
|
||||
if (!Number.isFinite(clickedPosition)) return
|
||||
|
||||
onPlaySegment(clickedPosition)
|
||||
}
|
||||
|
||||
@@ -75,6 +75,30 @@ describe('AudioPlayer readiness gating', () => {
|
||||
expect(created[0].currentTime).toBe(12)
|
||||
})
|
||||
|
||||
it('ignores non-finite seek targets instead of crashing the media element', () => {
|
||||
renderPlayer()
|
||||
fireOnAudio('canplaythrough')
|
||||
expect(window.isAudioReady).toBe(true)
|
||||
|
||||
// NaN / Infinity would throw "The provided double value is non-finite"
|
||||
// in a real browser. The guard must no-op: never seek, never play.
|
||||
act(() => {
|
||||
window.seekAndPlayAudio?.(Number.NaN)
|
||||
})
|
||||
act(() => {
|
||||
window.seekAndPlayAudio?.(Number.POSITIVE_INFINITY)
|
||||
})
|
||||
expect(created[0].play).not.toHaveBeenCalled()
|
||||
expect(Number.isFinite(created[0].currentTime)).toBe(true)
|
||||
|
||||
// A finite target still works.
|
||||
act(() => {
|
||||
window.seekAndPlayAudio?.(7)
|
||||
})
|
||||
expect(created[0].currentTime).toBe(7)
|
||||
expect(created[0].play).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('reveals playback controls and publishes ready once canplaythrough fires', () => {
|
||||
const onReady = jest.fn()
|
||||
window.addEventListener(AUDIO_READY_EVENT, onReady)
|
||||
|
||||
@@ -377,7 +377,12 @@ def create_audio_download_job(
|
||||
)
|
||||
],
|
||||
service_account=service_account.email,
|
||||
timeout="600s", # 10 minutes max (downloads typically < 5 min)
|
||||
# 20 min max. Slow torrent (RED/OPS) downloads can exceed 10 min;
|
||||
# a SIGKILL at the old 600s bypassed graceful failure handling and
|
||||
# left in-flight auto-retries racing manual retries (job 1cd29294).
|
||||
# The worker's DOWNLOAD_WAIT_TIMEOUT_SECONDS (1080s) is kept
|
||||
# strictly below this so it fails cleanly before Cloud Run kills it.
|
||||
timeout="1200s",
|
||||
max_retries=2,
|
||||
vpc_access=vpc_access,
|
||||
),
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-gen"
|
||||
version = "0.190.5"
|
||||
version = "0.191.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"
|
||||
|
||||
Reference in new issue
Block a user