Compare commits

..
4 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 5.5 a10e548606 fix(url-jobs): retry a YouTube bot block, then point to Audio Search (v0.290.1) (#1244)
Implements fix C from section 4 of the 2026-11-03 alerts triage handoff.
Job 526bf46c, from a paying customer, failed within 3s of a YouTube bot
wall and showed the raw yt-dlp error. The credit was refunded, and the
customer then uploaded an MP3.

## Changes

- **Download:** `create-from-url` retries a bot-blocked download once
after 30s. Other download errors behave as before.
- **Still blocked:** the job fails with a translated message pointing to
Audio Search. The raw error goes in `error_details`. The response stays
a 500, because the frontend treats 503 as a transient backend blip.
- **Pre-check:** a bot-blocked availability check now waits 30s and
checks again before rejecting. No job or credit exists yet at that
point. A repeat block returns the same translated message instead of the
old hardcoded English. CodeRabbit raised this: without it, the retry
never ran when the pre-check caught the block.
- **Logging:** the bot-block paths log WARNING rather than ERROR,
because `fail_job` already raises the alert for the failure.

`audio_search.py` has its own bot-block handling, which this PR doesn't
change. The monitor and start-review changes are in a separate PR.

## Depends on flacfetch

The retries only help much with
https://github.com/nomadkaraoke/flacfetch/pull/61 deployed, since that's
what requests fresh cookies straight away. Without it, new cookies only
arrive from the keeper's 30-minute probe, so a 30s wait rarely helps.
This PR is safe to deploy first, but it adds up to 30s before the same
failure.

## Testing

- New `test_create_from_url_bot_block.py`, written test-first: retries,
final failure, pre-check, non-bot errors and all 33 locales.
- Backend tests selected with `-k "url or youtube or audio_search or
i18n or translation"`: 785 passed, 5 skipped. Emulator and integration
tests excluded. I did not run the full `make test`, so CI is the full
check.
- Backend translation key parity passes.
- Local CodeRabbit review: 1 finding, fixed. The fresh re-review had no
new findings.

**Not verified:**
- Nothing has run in production, and I created no test jobs.
- **The 32 new translations were written by hand, not by
`translate.py`.** gcloud auth had expired, so the Gemini key wasn't
available. To replace them, run `translate.py` for that key with a valid
login.
- ruff reports F823 for `asyncio` at about line 647 of `file_upload.py`.
It's also on main, in a different function, and I left it alone.

Alert:
https://discord.com/channels/1198691101943541770/1265517528608669707/1567241547739570298
Alert:
https://discord.com/channels/1198691101943541770/1265517528608669707/1567252495535841386
Alert:
https://discord.com/channels/1198691101943541770/1265517528608669707/1567252497620537415

@coderabbitai ignore

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

https://claude.ai/code/session_012RYLVTvqXyL4QyA2EjzQMG

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 23:18:13 +00:00
Andrew Beveridge ☄️andClaude Opus 5.5 08b146fce0 fix: no review push before AI suggestions are scored; start-review 409 after review ends (v0.290.1) (#1246)
Andrew's job `7f89f884` (2026-11-03) got a "review your lyrics" push,
then auto-approved about 3.7 minutes later. Tapping the push afterwards
left the app on its loader.

**False review push.** The screens worker's first score ran at 00:15:40,
before the proactive auto-correct finished at 00:15:46. Without
suggestions the lyrics scored `needs-review`, so `hold_for_audio` was
false and review opened with its push. The audio worker's re-score then
saw the suggestions (`auto/ai-resolved`) and auto-approved. In the last
14 days 5 jobs auto-approved, and 4 of them opened review first
(typically about 3.7 minutes before).

`route_after_scoring` now waits for the suggestions and scores again
when the first pass ran without them, then holds or auto-completes. If
suggestions can't be had, or the re-score reaches no verdict, the first
verdict stands and review opens as before.

**start-review on a finished job.** `complete -> in_review` raised an
invalid transition: a 500, an ERROR log (4 in prod for this job, which
the error monitor can turn into an #alerts message), and the app
retrying as if it were transient. It now returns 409 without attempting
the transition. The app's handling is in nomad-mobile #44.

**Tests:** `test_review_gate.py` and `test_jobs_api.py` pass with new
cases. `test_internal_api.py` has 7 auth test failures locally that also
fail on the main clone, so they aren't from this change.

@coderabbitai ignore

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

https://claude.ai/code/session_012RYLVTajJiZnzPUt9qsVEJ

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 18:13:25 -05:00
Andrew Beveridge ☄️andClaude Opus 5.5 70bdd0e693 fix(alerts): start-review 409, per-cause crash patterns, one alert per job failure (v0.290.1) (#1243)
Section 1 of the 2026-11-03 #alerts triage handoff: a stale push on a
finished song got a 500, and the error monitor could stay silent on a
new crash.

Alert:
https://discord.com/channels/1198691101943541770/1265517528608669707/1566980744448843886
Alert:
https://discord.com/channels/1198691101943541770/1265517528608669707/1566980746394996879
Alert:
https://discord.com/channels/1198691101943541770/1265517528608669707/1566980747905073224
Alert:
https://discord.com/channels/1198691101943541770/1265517528608669707/1565697725280948294
Alert:
https://discord.com/channels/1198691101943541770/1265517528608669707/1565803187334815775
Alert:
https://discord.com/channels/1198691101943541770/1265517528608669707/1565818418072916110
Alert:
https://discord.com/channels/1198691101943541770/1265517528608669707/1566225593354420226
Alert:
https://discord.com/channels/1198691101943541770/1265517528608669707/1566256141074169987
Alert:
https://discord.com/channels/1198691101943541770/1265517528608669707/1567207141994135654
Alert:
https://discord.com/channels/1198691101943541770/1265517528608669707/1567252495535841386
Alert:
https://discord.com/channels/1198691101943541770/1265517528608669707/1567252497620537415

## What changed

**1a. start-review:** a job not in review gets 409
(`jobs.jobNotInReviewState`) with no transition attempted. Losing the
auto-approver race is a 409 too. `correction-data` has the same race,
and its `except Exception` turned it into a 500; it now returns 409
(`except HTTPException: raise` added). Its status gate still returns
400, as before.

**1b. Crash patterns:** `Exception in ASGI application` and
`request_audit_error` become `Unhandled exception: <Type: message>`,
read from the entry's `exception` field. The handoff's suspicion is
confirmed in `upsert_pattern`: an existing `new` pattern returns
`is_new=False`, so a second, different crash stayed silent. Both log
lines of one crash now share one pattern. The path and method go in the
sample only.

I read the line after the last frame rather than the traceback's last
line. pydantic's last line is a docs link shared by every failure, and
group tracebacks end in a separator.

**1c. One alert per failure:**
- YouTube ids are normalized out of signatures, which also fixes the
false "first time" line in `ops_alerts`.
- `Job <id> failed` (both call sites in `job_manager`) logs WARNING,
since the status write sends the job-failed alert.
- `URL download failed:` is ignored in the monitor, not demoted, because
`file_upload.py` belongs to the section 4 PR.
- `[job:<id>] Download failed` logs WARNING for the expected
`DownloadError`/`FlacfetchServiceError` types. This wasn't named in the
handoff, but it is the same duplicate on the audio-search path.
Unexpected exceptions there stay ERROR with a traceback.

**1d. Suppressions and demotions:**
- Zalo's `zaloJSV2 is not defined`: dropped at `/api/client-errors`,
only with a Zalo UA.
- `python -c` experiments on `audio-separation-job`: ignored, using the
handoff's regex.
- Spotify 403 on `/lyrics`: WARNING with `response.text[:200]`. 401 on
`/lyrics` and 401/403 on `/search` stay ERROR.
- Dropbox token probe: WARNING. A rejected refresh used to log nothing,
so it now logs ERROR, as does having no refresh credentials.
- decide-search health aborts: this was a small change. `should_ignore`
takes an optional `request_url` and matches the exact path
`/api/search/health`.

**1e. Cold start:** `anyio._backends._asyncio` is added to
`_LAZY_ROUTE_IMPORTS`. The prod stack from 10-30 confirms the stall was
in that import. Lifespan also sends one `/api/health` request through
the app in a worker thread, bounded by the existing 30s timeout and
best-effort.

## Testing

- TDD: new tests failed first, then passed.
- Affected suites: 826 passed.
- `backend/tests` (excluding `backend/tests/emulator`): 7088 passed, 8
failed, 29 skipped. All 8 are in `test_emulator_integration.py`, and
that file also shows 8 failures at the base commit a8f9618a. I did not
compare the 8 test names one by one.
- `tests/unit` outside the listed files was not run.
`test_audio_fetcher.py` and `test_remote_cli.py` fail to collect in my
environment; I didn't change either file.
- Read-only replay of real prod entries through the new code: the 11-03
crash gave one specific pattern with `POST
/api/jobs/7f89f884/start-review` in the sample, the decide-search health
aborts and the experiment traceback were ignored.
- Local CodeRabbit review completed with 0 findings.

## Not verified

- Nothing is live, so the alert volume and the cold-start stall haven't
been measured. The warm request has only run in tests, not on a real
Cloud Run cold start.
- A request's first-use imports beyond the anyio backend aren't
individually checked.
- My test environment has no `flacfetch`, so its lazy imports only log a
warning here.
- Zalo: the trigger is one report (11-03).

## Known leftovers

- `validate_state_transition` still logs ERROR before raising, so the
auto-approver race (and the existing in_review race) still emits one
`Invalid state transition` ERROR even though the client now gets a clean
response. The stale-push case no longer reaches it. I left this because
other callers rely on that log.
- A crash that also logs its own ERROR first still gives two patterns,
the ERROR and `Unhandled exception`.
- The first bot block after deploy shows "first time" once, because the
normalized signature is new.
- Old `Exception in ASGI application` and `request_audit_error` patterns
stop recurring and will auto-resolve.
- If the section 4 PR rewords `URL download failed:`, the ignore entry
in `known_issues.py` needs the same wording.

## For Andrew (infra and cost, not changed here)

- Cloud Run startup probe and min-instances for `karaoke-backend`, if
cold-start stalls continue after this ships.
- decide-search's min-0 is why its health pings abort. The suppression
hides those, but real search paths will still alert on the same abort.

@coderabbitai ignore

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

https://claude.ai/code/session_012RYLVTvqXyL4QyA2EjzQMG

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 23:04:04 +00:00
Andrew Beveridge ☄️andClaude Opus 5.5 ea69386e50 fix(ci): Java 25 for the Firestore emulator (#1245)
`google-cloud-cli-firestore-emulator` 592.0.0 is compiled for Java 25
(class file 69), and the package is installed unpinned from apt, so CI's
Java 21 fails with `UnsupportedClassVersionError`. This blocks every PR:
Backend Emulator Integration and Local Stack E2E both failed on #1243
and #1244 (runs 41705112128, 41706068761). Main last passed 11-02.
CI-only change; this PR's own run is the test.

@coderabbitai ignore not added: no local review was run on this one-line
CI change, so the bot may review it.

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

https://claude.ai/code/session_012RYLVTvqXyL4QyA2EjzQMG

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 17:53:53 -05:00
65 changed files with 1347 additions and 39 deletions

No files matched your search

+8 -4
View File
@@ -723,11 +723,13 @@ jobs:
restore-keys: |
venv-backend-hosted-${{ runner.os }}-py3.13-
- name: Set up Java 21 (required by Firestore emulator)
# The emulator package is unpinned (latest from apt), and 592.0.0 is compiled for
# Java 25 (class file 69): older runtimes fail with UnsupportedClassVersionError.
- name: Set up Java 25 (required by Firestore emulator)
uses: actions/setup-java@v4
with:
distribution: "temurin"
java-version: "21"
java-version: "25"
- name: Install Firestore emulator
run: |
@@ -834,11 +836,13 @@ jobs:
restore-keys: |
venv-backend-hosted-${{ runner.os }}-py3.13-
- name: Set up Java 21 (required by Firestore emulator)
# The emulator package is unpinned (latest from apt), and 592.0.0 is compiled for
# Java 25 (class file 69): older runtimes fail with UnsupportedClassVersionError.
- name: Set up Java 25 (required by Firestore emulator)
uses: actions/setup-java@v4
with:
distribution: "temurin"
java-version: "21"
java-version: "25"
- name: Install Firestore emulator + ffmpeg
run: |
+10
View File
@@ -19,6 +19,7 @@ from backend.services.error_monitor.frontend_ingestion import (
RateLimiter,
build_pattern_data,
is_bot_user_agent,
is_host_app_injection_error,
is_opaque_script_error,
sanitize_url,
)
@@ -90,6 +91,15 @@ def report_client_error(payload: ClientErrorPayload, request: Request) -> Client
)
return ClientErrorResponse(pattern_id="opaque-script-error-ignored", is_new=False)
# A script the in-app browser's host app injected (Zalo), not our code.
if is_host_app_injection_error(payload.message, payload.user_agent):
logger.info(
"frontend_crash_ignored_host_app_injection url=%s source=%s",
sanitize_url(payload.url),
payload.source,
)
return ClientErrorResponse(pattern_id="host-app-injection-ignored", is_new=False)
report = FrontendErrorReport(
message=payload.message,
stack=payload.stack,
+46 -7
View File
@@ -45,6 +45,7 @@ from backend.services.tracing import add_span_attribute
from backend.services.youtube_download_service import (
get_youtube_download_service,
YouTubeDownloadError,
is_bot_block_error,
)
from backend.i18n import t, get_locale_from_request, get_full_locale_from_request
@@ -56,6 +57,9 @@ def _is_youtube_url(url: str) -> bool:
return any(domain in url.lower() for domain in [
'youtube.com', 'youtu.be', 'youtube-nocookie.com'
])
# Wait before retrying a bot-blocked URL download, so a cookie re-export can finish.
BOT_BLOCK_RETRY_DELAY_SECONDS = 30
router = APIRouter(tags=["jobs"])
@@ -1975,6 +1979,25 @@ def validate_job_url(
return ValidateUrlResponse(supported=True)
async def _download_url_with_bot_block_retry(download_service, **download_kwargs) -> str:
"""Download a URL, retrying once if YouTube bot-blocks flacfetch's session.
flacfetch already asks its credential keeper for fresh cookies and retries before
reporting a bot block. The delay here covers the case where that re-export was
still in progress or on cooldown.
"""
try:
return await download_service.download(**download_kwargs)
except YouTubeDownloadError as e:
if not is_bot_block_error(e):
raise
logger.warning(
f"URL download bot-blocked, retrying in {BOT_BLOCK_RETRY_DELAY_SECONDS}s: {e}"
)
await asyncio.sleep(BOT_BLOCK_RETRY_DELAY_SECONDS)
return await download_service.download(**download_kwargs)
@router.post("/jobs/create-from-url", response_model=CreateJobFromUrlResponse)
async def create_job_from_url(
request: Request,
@@ -2032,6 +2055,15 @@ async def create_job_from_url(
youtube_service = get_youtube_download_service()
availability = await youtube_service.check_availability(body.url)
# flacfetch starts a cookie re-export when this check gets bot-blocked,
# so give it time and check again before turning the user away.
if availability and availability.get("is_bot_blocked"):
logger.warning(
f"Availability check bot-blocked, rechecking in {BOT_BLOCK_RETRY_DELAY_SECONDS}s: {body.url}"
)
await asyncio.sleep(BOT_BLOCK_RETRY_DELAY_SECONDS)
availability = await youtube_service.check_availability(body.url)
if availability and not availability.get("available"):
error_msg = availability.get("error", "This video is not available")
@@ -2046,12 +2078,7 @@ async def create_job_from_url(
elif availability.get("is_removed"):
detail = "This YouTube video has been removed and cannot be downloaded."
elif availability.get("is_bot_blocked"):
detail = (
"We're temporarily unable to access YouTube to download this video — "
"YouTube is asking our server to verify it's not a bot. "
"Please try again in a few minutes, or use Audio Search to find this song "
"from another source."
)
detail = t(locale, "audioSearch.youtubeBotBlocked")
elif availability.get("is_age_restricted"):
detail = "This YouTube video is age-restricted and cannot be downloaded."
else:
@@ -2209,7 +2236,8 @@ async def create_job_from_url(
logger.info(f"Downloading audio from URL via flacfetch: {body.url}")
try:
download_service = get_youtube_download_service()
audio_gcs_path = await download_service.download(
audio_gcs_path = await _download_url_with_bot_block_retry(
download_service,
url=body.url,
job_id=job_id,
artist=artist,
@@ -2236,6 +2264,17 @@ async def create_job_from_url(
)
except YouTubeDownloadError as e:
if is_bot_block_error(e):
# Our problem, not the user's or the video's: don't show them yt-dlp's
# advice about cookies. fail_job raises the alert, so WARNING here.
logger.warning(f"URL download still bot-blocked after retry: {e}")
detail = t(locale, "audioSearch.youtubeBotBlocked")
job_manager.fail_job(
job_id,
detail,
error_details={"code": "youtube_bot_block", "raw_error": str(e)},
)
raise HTTPException(status_code=500, detail=detail)
logger.error(f"URL download failed: {e}")
job_manager.fail_job(job_id, f"Download failed: {e}")
raise HTTPException(
+29 -4
View File
@@ -22,7 +22,7 @@ from google.cloud.exceptions import NotFound
from backend.utils.loop_bridge import run_in_body_thread, run_on_loop
from backend.utils.request_helpers import get_client_ip
from backend.services.review_state import ensure_in_review
from backend.models.job import Job, JobCreate, JobResponse, JobStatus
from backend.models.job import Job, JobCreate, JobResponse, JobStatus, STATE_TRANSITIONS
from backend.models.requests import (
URLSubmissionRequest,
CorrectionsSubmission,
@@ -1085,6 +1085,14 @@ def get_review_data(
}
def _job_not_in_review_conflict(locale: str, status: Any) -> HTTPException:
"""409 for a review request on a job that isn't in review."""
return HTTPException(
status_code=409,
detail=t(locale, "jobs.jobNotInReviewState", status=getattr(status, "value", status)),
)
@router.post("/{job_id}/start-review")
def start_review(
job_id: str,
@@ -1106,13 +1114,30 @@ def start_review(
if not _check_job_ownership(job, auth_result):
raise HTTPException(status_code=403, detail=t(locale, "jobs.noPermissionAccess"))
# The review is over (auto-approved, submitted, finished): an expected answer
# for a stale link or notification, not a server error. Clients go to the job.
if job.status != JobStatus.IN_REVIEW and JobStatus.IN_REVIEW not in STATE_TRANSITIONS.get(job.status, []):
logger.info(f"Job {job_id}: start-review refused, status is {job.status}")
raise HTTPException(status_code=409, detail=t(locale, "jobs.reviewCannotStart"))
# Idempotent: concurrent/duplicate opens (React double-mount, double-tap, two
# tabs) must not fail with "in_review -> in_review". Already in review == success,
# and the one-time side effects (record_review_started) are not repeated.
# A job past review (e.g. a stale "review lyrics" push tapped on a finished song)
# is the client's to handle: 409, no transition attempted, nothing logged at ERROR.
if job.status not in [JobStatus.AWAITING_REVIEW, JobStatus.IN_REVIEW]:
raise _job_not_in_review_conflict(locale, job.status)
was_awaiting = job.status == JobStatus.AWAITING_REVIEW
result = ensure_in_review(
job_manager, job_id, job.status, "User started reviewing lyrics"
)
try:
result = ensure_in_review(
job_manager, job_id, job.status, "User started reviewing lyrics"
)
except InvalidStateTransitionError:
# Lost the race: the auto-approver (or another worker) moved the job on
# between our read and the transition.
current = job_manager.get_job(job_id)
raise _job_not_in_review_conflict(locale, current.status if current else job.status)
if result == "refused":
raise HTTPException(status_code=400, detail=t(locale, "jobs.reviewCannotStart"))
if result == "started" and was_awaiting:
+20 -7
View File
@@ -32,6 +32,7 @@ from google.cloud.firestore_v1.field_path import FieldPath
from backend.models.job import JobStatus
from backend.models.review_session import ReviewSession, ReviewSessionSummary
from backend.services.job_manager import JobManager
from backend.exceptions import InvalidStateTransitionError
from backend.services.review_state import ensure_in_review
from backend.services.firestore_service import FirestoreService
from backend.services.storage_service import StorageService
@@ -932,13 +933,23 @@ async def get_correction_data(
if not replay and job.status == JobStatus.AWAITING_REVIEW:
# Idempotent: iOS/in-app browsers fire two concurrent loads; the loser
# must not 500 on "in_review -> in_review" nor repeat one-time side effects.
started = "started" == await asyncio.to_thread(
ensure_in_review,
job_manager,
job_id,
job.status,
"User opened combined review interface",
)
try:
started = "started" == await asyncio.to_thread(
ensure_in_review,
job_manager,
job_id,
job.status,
"User opened combined review interface",
)
except InvalidStateTransitionError:
# Lost the race: the auto-approver moved the job on after the status
# gate above. Not a load failure, so 409 rather than the 500 below.
current = await asyncio.to_thread(job_manager.get_job, job_id)
status = current.status if current else job.status
raise HTTPException(
status_code=409,
detail=t("en", "review.reviewNotReady", status=getattr(status, "value", status)),
)
if started:
# Set by require_review_auth (absent for review-token links).
auth_state = getattr(request, "state", None)
@@ -978,6 +989,8 @@ async def get_correction_data(
logger.info(f"Job {job_id}: Serving correction data (replay={replay}) for combined review")
return corrections_data
except HTTPException:
raise
except Exception as e:
logger.error(f"Job {job_id}: Error loading corrections: {e}", exc_info=True)
raise HTTPException(status_code=500, detail=t("en", "review.correctionsLoadFailed", error=str(e)))
+37
View File
@@ -9,6 +9,7 @@ import logging
import threading
import time
from contextlib import asynccontextmanager
from typing import Any
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
@@ -95,6 +96,9 @@ _LAZY_ROUTE_IMPORTS = (
"flacfetch.core.manager",
"flacfetch.downloaders.youtube",
"yt_dlp",
# starlette/middleware/base.py picks the anyio backend on the first request:
# 17.3s on the loop with 18 requests in flight (2026-10-30).
"anyio._backends._asyncio",
)
@@ -137,6 +141,29 @@ def _warm_route_contexts(application: FastAPI) -> int:
return count
def _warm_middleware_stack(application: Any) -> None:
"""Send one request through the app, so the first user's request isn't what builds
the middleware stack and runs its first-use imports on the loop.
Blocking: runs its own event loop, so call it from a worker thread. /api/health is
exempt from the edge lock, skips the audit log and touches no storage. Best-effort.
"""
import httpx
async def _request() -> None:
transport = httpx.ASGITransport(app=application)
async with httpx.AsyncClient(transport=transport, base_url="http://localhost") as client:
await client.get("/api/health")
start = time.time()
try:
asyncio.run(_request())
except Exception as e: # noqa: BLE001 - warmup must never block startup
logger.warning(f"Middleware warm request failed (stack builds on first request): {e}")
return
logger.info(f"Warmed middleware stack in {time.time() - start:.2f}s")
def _warm_route_contexts_safely(application: FastAPI) -> None:
start = time.time()
try:
@@ -243,6 +270,16 @@ async def lifespan(app: FastAPI):
f"Route-context warmup exceeded {LAZY_ROUTE_IMPORT_TIMEOUT_S}s; continuing startup"
)
# Same reason, for what only the first request through the middleware touches.
try:
await asyncio.wait_for(
asyncio.to_thread(_warm_middleware_stack, app), timeout=LAZY_ROUTE_IMPORT_TIMEOUT_S
)
except asyncio.TimeoutError:
logger.warning(
f"Middleware warmup exceeded {LAZY_ROUTE_IMPORT_TIMEOUT_S}s; continuing startup"
)
# NLP model / credential warmup runs in the background so it doesn't gate
# readiness — Cloud Run holds all routed requests until lifespan startup
# returns, and these preloads were ~7.5s of the ~16s cold start.
+2 -1
View File
@@ -261,7 +261,8 @@ async def maybe_auto_complete_review(job_id: str, trigger: str) -> Dict[str, Any
payload["hold_for_audio"] = hold_for_audio
job_manager.update_processing_metadata(job_id, "auto_approval", payload)
return {"outcome": "review", "overall_auto": verdict.overall_auto,
"blockers": blockers, "hold_for_audio": hold_for_audio}
"blockers": blockers, "hold_for_audio": hold_for_audio,
"ai_suggestions_available": ai_suggestions is not None}
# ---- ENFORCE: complete the review exactly like a human would ----
# The status gate above used a snapshot read. Re-read now so a human who
@@ -70,6 +70,9 @@ async def route_after_scoring(
from backend.services.job_manager import JobManager
job_manager = job_manager or JobManager()
auto_result = await _rescore_if_suggestions_were_missing(job_id, auto_result, job_log)
if auto_result.get("outcome") in ("auto_completed", "wrong_status"):
return str(auto_result["outcome"])
if not auto_result.get("hold_for_audio"):
await enter_human_review(job_id, job_log, job_manager)
return "review"
@@ -91,6 +94,43 @@ async def route_after_scoring(
return "released_elsewhere"
async def _rescore_if_suggestions_were_missing(
job_id: str, auto_result: Dict[str, Any], job_log: Optional[logging.Logger] = None
) -> Dict[str, Any]:
"""Score again if the first pass ran before the AI suggestions landed.
Lyrics finish moments before the proactive auto-correct, and without its
suggestions the lyrics score "needs review". Opening review on that verdict
sent the customer a "review your lyrics" push, and the audio worker's re-score
then auto-approved the job minutes later (4 of 5 auto-approved jobs,
2026-10-20..11-03). Returns the verdict to route on; the original one when
suggestions can't be had or the re-score didn't reach a verdict.
"""
if auto_result.get("outcome") != "review" or auto_result.get("ai_suggestions_available") is not False:
return auto_result
from backend.config import get_settings
from backend.services.auto_approval.executor import maybe_auto_complete_review
if not getattr(get_settings(), "auto_correct_proactive_enabled", False):
return auto_result
try:
from backend.workers.auto_correct_worker import process_proactive_auto_correct
await process_proactive_auto_correct(job_id) # bounded (180s), joins a run in flight
except Exception as e: # noqa: BLE001 best-effort, like ensure_and_pre_apply
logger.warning(f"[job:{job_id}] Waiting for AI suggestions before review failed: {e}")
return auto_result
rescored = await maybe_auto_complete_review(job_id, trigger="screens_worker")
outcome = rescored.get("outcome")
logger.info(f"[job:{job_id}] Re-scored once AI suggestions were ready: {outcome} "
f"(hold_for_audio={rescored.get('hold_for_audio', False)})")
if outcome == "auto_completed" and job_log:
job_log.info("Auto-approved once AI suggestions were ready: review skipped")
return rescored if outcome in ("review", "auto_completed", "wrong_status") else auto_result
async def release_audio_hold(job_id: str, reason: str) -> Optional[str]:
"""Release a held job (audio worker / stuck-job sweep).
+8 -3
View File
@@ -222,7 +222,9 @@ class CredentialManager:
message="Dropbox credentials refreshed successfully",
last_checked=datetime.utcnow()
)
else:
logger.error("Dropbox access token rejected and no refresh credentials are stored")
return CredentialCheckResult(
service="dropbox",
status=CredentialStatus.INVALID,
@@ -410,7 +412,9 @@ class CredentialManager:
return True
except Exception as e:
logger.error(f"Dropbox API test failed: {e}")
# Short-lived tokens expire constantly and the caller refreshes them, so
# the probe failing isn't page-worthy; the refresh failing is.
logger.warning(f"Dropbox API test failed: {e}")
return False
def _refresh_dropbox_token(self, creds: dict) -> bool:
@@ -436,7 +440,8 @@ class CredentialManager:
# Update in Secret Manager
self._update_dropbox_credentials(creds)
return True
logger.error(f"Dropbox token refresh rejected ({response.status_code}): {response.text[:200]}")
return False
except Exception as e:
@@ -74,6 +74,20 @@ def is_opaque_script_error(message: str | None, source: str | None = None, extra
return not extra.get("filename") and not extra.get("lineno")
# Zalo's in-app browser injects scripts into every page it opens; one references a
# global it hasn't defined yet. Not our code, and nothing the user sees. Needs both
# the host app's UA and its global, so a real error inside Zalo still reports.
_HOST_APP_INJECTION_RE = re.compile(r"\bzaloJSV\d*\b is not defined")
_ZALO_UA_RE = re.compile(r"\bZalo\b", re.IGNORECASE)
def is_host_app_injection_error(message: str | None, user_agent: str | None) -> bool:
"""True for an error from a script the in-app browser's host app injected."""
if not message or not user_agent:
return False
return bool(_HOST_APP_INJECTION_RE.search(message) and _ZALO_UA_RE.search(user_agent))
# A chunk-load failure is a tab running an old build after a deploy: the client
# auto-reloads (frontend/lib/version-check.ts), so one report is not actionable.
# Mirrors isChunkLoadError() there. Reports collapse into one pattern per build
+46 -2
View File
@@ -15,6 +15,7 @@ Usage:
import re
from dataclasses import dataclass
from urllib.parse import urlsplit
@dataclass
@@ -129,18 +130,55 @@ _SERVICE_IGNORE_PATTERNS: list[tuple[str, frozenset[str], re.Pattern, str]] = [
"while instances start, GitHub redelivers and the runners still dispatch "
"(seen 2026-09-20, 09-23, 09-27, 10-08)",
),
(
"audio_separation_experiment_traceback",
frozenset({"audio-separation-job"}),
# Two consecutive <string> frames: `python -c` running exec'd code, i.e. an
# experiment on a prod job image. A multiprocessing-spawn traceback also
# starts with a <string> frame, but its second frame is a real file.
re.compile(r'File "<string>", line 1, in <module>\s+File "<string>", line \d+'),
"Ad-hoc experiment run on a prod audio-separation-job image, not a job failure "
"(seen 2026-10-31, 11-01)",
),
(
"url_download_failed_duplicate",
frozenset({"karaoke-backend"}),
# file_upload.py logs this, then fail_job: ops_alerts' job-failed alert is the
# one alert for the failure.
re.compile(r"^URL download failed: "),
"Same failure as the job-failed alert that fail_job sends right after this line",
),
]
def should_ignore(service: str, message: str) -> IgnoreReason | None:
# Noise only for one service AND request URL path (Cloud Run request logs carry the
# URL outside the message). (pattern_name, services, message regex, exact URL path, reason)
_SERVICE_URL_IGNORE_PATTERNS: list[tuple[str, frozenset[str], re.Pattern, str, str]] = [
(
"decide_search_health_abort",
frozenset({"karaoke-decide-search"}),
re.compile(
r"request was aborted after waiting too long for an available instance",
re.IGNORECASE,
),
"/api/search/health",
"The keep-warm ping waiting on a min-0 cold start (seen 2026-10-30). The same "
"abort on a real search path drops a user's request and still alerts.",
),
]
def should_ignore(service: str, message: str, request_url: str | None = None) -> IgnoreReason | None:
"""Check whether a log entry matches a known infrastructure noise pattern.
``_IGNORE_PATTERNS`` match on the message alone; ``_SERVICE_IGNORE_PATTERNS``
also require ``service`` to be one of the listed services.
also require ``service`` to be one of the listed services, and
``_SERVICE_URL_IGNORE_PATTERNS`` also require ``request_url``'s path.
Args:
service: The originating service name (e.g. ``"karaoke-backend"``).
message: The raw log message string to evaluate.
request_url: The entry's request URL, if it is a request log.
Returns:
An :class:`IgnoreReason` if the message matches a known noise pattern,
@@ -157,4 +195,10 @@ def should_ignore(service: str, message: str) -> IgnoreReason | None:
if service in services and pattern.search(message):
return IgnoreReason(pattern_name=pattern_name, reason=reason)
if request_url:
url_path = urlsplit(request_url).path
for pattern_name, services, pattern, path, reason in _SERVICE_URL_IGNORE_PATTERNS:
if service in services and url_path == path and pattern.search(message):
return IgnoreReason(pattern_name=pattern_name, reason=reason)
return None
+67 -3
View File
@@ -15,6 +15,7 @@ from __future__ import annotations
import logging
import os
import re
from datetime import datetime, timedelta, timezone
from typing import Any
@@ -115,6 +116,39 @@ def _build_log_filter(
)
#: Fixed messages uvicorn and the audit middleware log for every unhandled exception.
#: The cause is only in the entry's ``exception`` field.
_UNHANDLED_EXCEPTION_MESSAGES = frozenset({"Exception in ASGI application", "request_audit_error"})
#: The margin of an ExceptionGroup traceback (" | ", " | | ", " + ").
_TRACEBACK_MARGIN_RE = re.compile(r"^\s*(?:[|+] )+")
#: Its separators (" +-+---- 1 ----", " +-------").
_TRACEBACK_SEPARATOR_RE = re.compile(r"^\s*(?:\| )*\+[-+]")
_TRACEBACK_FRAME_RE = re.compile(r'^\s*File ".*", line \d+')
def _exception_summary(exception_text: str) -> str | None:
"""The ``Type: message`` line a traceback ends on, without its group margin.
Looks after the last frame, not at the last line: a multi-line exception message
(pydantic's ends in a docs link shared by every failure) would otherwise replace
the cause. Frame source and caret lines are indented; the exception line isn't.
"""
lines = [
_TRACEBACK_MARGIN_RE.sub("", line)
for line in exception_text.splitlines()
if line.strip() and not _TRACEBACK_SEPARATOR_RE.match(line)
]
if not lines:
return None
last_frame = max((i for i, line in enumerate(lines) if _TRACEBACK_FRAME_RE.match(line)), default=None)
if last_frame is not None:
for line in lines[last_frame + 1 :]:
if not line[0].isspace():
return line
return lines[-1].strip()
def _extract_message(entry: Any) -> str | None:
"""Extract the log message text from a Cloud Logging entry.
@@ -125,6 +159,9 @@ def _extract_message(entry: Any) -> str | None:
``"msg"`` keys in that order.
* ``None`` payload — returns ``None``.
An unhandled-exception message becomes ``Unhandled exception: <cause>``, so
each cause is its own pattern and both log lines of one crash share it.
Args:
entry: A Cloud Logging ``LogEntry`` object.
@@ -140,13 +177,40 @@ def _extract_message(entry: Any) -> str | None:
for key in ("message", "textPayload", "error", "msg"):
value = payload.get(key)
if value:
return str(value)
text = str(value)
if text.strip() in _UNHANDLED_EXCEPTION_MESSAGES:
summary = _exception_summary(str(payload.get("exception") or ""))
if summary:
return f"Unhandled exception: {summary}"
return text
return None
# Fallback: convert to string representation
text = str(payload)
return text if text else None
def _extract_sample(entry: Any, message: str) -> str:
"""The alert's sample: the message, led by the request path when the entry has one.
The path stays out of the pattern (one cause on many jobs or endpoints is one
alert) but the alert needs it to say where to look.
"""
payload = entry.payload
path = payload.get("path") if isinstance(payload, dict) else None
if not path:
return message
method = payload.get("method")
return f"{method} {path}\n{message}" if method else f"{path}\n{message}"
def _extract_request_url(entry: Any) -> str | None:
"""The request URL on a Cloud Run request-log entry, if any."""
http_request = getattr(entry, "http_request", None)
if not isinstance(http_request, dict):
return None
return http_request.get("requestUrl") or None
def _extract_service_name(entry: Any, resource_type: str) -> str:
"""Extract the service/job/function/instance name from a log entry.
@@ -370,7 +434,7 @@ class ErrorMonitor:
if not message:
continue
service = _extract_service_name(entry, resource_type)
ignore_reason = should_ignore(service, message)
ignore_reason = should_ignore(service, message, _extract_request_url(entry))
if ignore_reason:
logger.debug(
"Ignoring entry from %s (%s): %s",
@@ -387,7 +451,7 @@ class ErrorMonitor:
"service": service,
"resource_type": _classify_resource_type(resource_type),
"normalized": normalized,
"message": message,
"message": _extract_sample(entry, message),
}
)
except Exception as exc: # noqa: BLE001
@@ -74,6 +74,17 @@ _NORMALIZERS: list[tuple[re.Pattern, str]] = [
re.compile(r"https?://([A-Za-z0-9.\-]+(:\d+)?)/[^\s]*"),
r"https://\1",
),
# 8b. YouTube video IDs: yt-dlp's "[youtube] <id>: <error>" and bare watch links.
# Otherwise the same error on each video is a new pattern and a "first time"
# job-failure signature (ops_alerts._signature uses this normalizer).
(
re.compile(r"(\[youtube(?::[\w-]+)?\]) [A-Za-z0-9_-]{11}(?=:)"),
r"\1 <VIDEO_ID>",
),
(
re.compile(r"(youtube\.com/watch\?v=|youtu\.be/)[A-Za-z0-9_-]{11}(?![A-Za-z0-9_-])"),
r"\1<VIDEO_ID>",
),
# 9. Job IDs in paths (/jobs/<alphanumeric>)
(
re.compile(r"/jobs/[A-Za-z0-9]+"),
+4 -2
View File
@@ -1346,7 +1346,8 @@ class JobManager:
message=error_message
)
logger.error(f"Job {job_id} failed: {error_message}")
# WARNING: the status write above sends the one job-failed alert (ops_alerts).
logger.warning(f"Job {job_id} failed: {error_message}")
# Auto-refund credit on failure
job = self.get_job(job_id)
@@ -1693,7 +1694,8 @@ class JobManager:
message=f"Failed: {error_message}",
**updates
)
logger.error(f"Job {job_id} failed: {error_message}")
# WARNING: the status write above sends the one job-failed alert (ops_alerts).
logger.warning(f"Job {job_id} failed: {error_message}")
if not already_notified:
self._trigger_state_notifications(job_id, JobStatus.FAILED)
@@ -29,6 +29,16 @@ class YouTubeDownloadError(Exception):
pass
def is_bot_block_error(error: Exception) -> bool:
"""Whether YouTube rejected flacfetch's session, as opposed to the video failing.
Matches flacfetch's own check. Loose so rewording doesn't disarm it, and "not a
bot" sidesteps yt-dlp's curly apostrophe in "you're".
"""
message = str(error).lower()
return "not a bot" in message or "cookies are no longer valid" in message
class YouTubeDownloadService:
"""
Single point of entry for all YouTube downloads in the cloud backend.
+29
View File
@@ -142,3 +142,32 @@ def test_strips_sensitive_query_string(client):
(pd,), _ = client.fake_adapter.upsert_pattern.call_args
assert "SECRET" not in pd.sample_message
assert "token=" not in pd.sample_message
ZALO_UA = (
"Mozilla/5.0 (Linux; Android 16; X Build/Y;) AppleWebKit/537.36 (KHTML, like Gecko) "
"Version/4.0 Chrome/156.0.8078.47 Mobile Safari/537.36 Zalo android/261002903 ZaloTheme/light"
)
ZALO_MESSAGE = "ReferenceError: zaloJSV2 is not defined"
def test_zalo_host_app_injection_is_accepted_but_not_persisted(client):
resp = client.post(
"/api/client-errors",
json=_payload(message=ZALO_MESSAGE, stack=f"{ZALO_MESSAGE}\n at <anonymous>:1:2", user_agent=ZALO_UA),
)
assert resp.status_code == 202
assert resp.json()["is_new"] is False
client.fake_adapter.upsert_pattern.assert_not_called()
def test_real_errors_inside_zalo_are_persisted(client):
resp = client.post("/api/client-errors", json=_payload(user_agent=ZALO_UA))
assert resp.status_code == 202
client.fake_adapter.upsert_pattern.assert_called_once()
def test_zalo_message_from_another_browser_is_persisted(client):
resp = client.post("/api/client-errors", json=_payload(message=ZALO_MESSAGE))
assert resp.status_code == 202
client.fake_adapter.upsert_pattern.assert_called_once()
@@ -156,3 +156,80 @@ async def test_review_fallback_crash_restores_hold_for_sweep() -> None:
auto_result={"outcome": "review"})
assert out == "error"
jm.park_review_for_auto_check.assert_called_once_with("j1")
def _suggestion_patches(wait=None):
return (
patch("backend.workers.auto_correct_worker.process_proactive_auto_correct",
wait or AsyncMock()),
patch("backend.config.get_settings",
return_value=SimpleNamespace(auto_correct_proactive_enabled=True)),
)
async def _route_without_suggestions(jm, rescored, wait=None):
first = {"outcome": "review", "ai_suggestions_available": False}
p_wait, p_settings = _suggestion_patches(wait)
with p_wait, p_settings:
return await _call(review_gate.route_after_scoring, jm, "j1", first, auto_result=rescored)
@pytest.mark.asyncio
async def test_missing_suggestions_rescore_holds_instead_of_notifying() -> None:
"""Job 7f89f884: the "review your lyrics" push went out minutes before auto-approval."""
jm = _jm(_job(audio_complete=False))
out, auto, pre = await _route_without_suggestions(
jm, {"outcome": "review", "hold_for_audio": True, "ai_suggestions_available": True})
assert out == "held"
auto.assert_awaited_once_with("j1", trigger="screens_worker")
jm.park_review_for_auto_check.assert_called_once_with("j1")
jm.transition_to_state.assert_not_called()
pre.assert_not_awaited()
@pytest.mark.asyncio
async def test_missing_suggestions_rescore_can_auto_complete() -> None:
jm = _jm()
out, _, pre = await _route_without_suggestions(jm, {"outcome": "auto_completed"})
assert out == "auto_completed"
jm.transition_to_state.assert_not_called()
pre.assert_not_awaited()
@pytest.mark.asyncio
async def test_missing_suggestions_rescore_still_review_opens_review() -> None:
jm = _jm()
out, auto, pre = await _route_without_suggestions(
jm, {"outcome": "review", "hold_for_audio": False, "ai_suggestions_available": True})
assert out == "review"
auto.assert_awaited_once()
pre.assert_awaited_once_with("j1")
assert jm.transition_to_state.call_args.kwargs["new_status"] == JobStatus.AWAITING_REVIEW
@pytest.mark.asyncio
async def test_suggestions_wait_failure_still_opens_review() -> None:
jm = _jm()
out, auto, _ = await _route_without_suggestions(
jm, {"outcome": "auto_completed"}, wait=AsyncMock(side_effect=RuntimeError("llm down")))
assert out == "review"
auto.assert_not_awaited()
assert jm.transition_to_state.call_args.kwargs["new_status"] == JobStatus.AWAITING_REVIEW
@pytest.mark.asyncio
async def test_rescore_with_no_verdict_keeps_first_verdict() -> None:
jm = _jm()
out, _, _ = await _route_without_suggestions(jm, {"outcome": "error"})
assert out == "review"
assert jm.transition_to_state.call_args.kwargs["new_status"] == JobStatus.AWAITING_REVIEW
@pytest.mark.asyncio
async def test_suggestions_present_scores_only_once() -> None:
jm = _jm()
out, auto, _ = await _call(
review_gate.route_after_scoring, jm, "j1",
{"outcome": "review", "ai_suggestions_available": True})
assert out == "review"
auto.assert_not_awaited()
@@ -1085,6 +1085,17 @@ class TestTorrentStallAwaitsUser:
assert details["stall_minutes"] == 60
assert details["keep_trying"] is True
@pytest.mark.asyncio
async def test_known_download_failure_logs_warning_not_error(self, caplog):
"""fail_job's job-failed alert is the one alert for this failure."""
import logging
flacfetch = _mock_flacfetch(FlacfetchServiceError("Download failed: tracker 500"))
with caplog.at_level(logging.INFO, logger="backend.workers.audio_download_worker"):
await self._run(_red_job(), flacfetch, attempt="0")
records = [r for r in caplog.records if "Download failed: Download failed" in r.getMessage()]
assert [r.levelno for r in records] == [logging.WARNING]
@pytest.mark.asyncio
async def test_non_stall_failure_still_marks_retry_pending(self):
flacfetch = _mock_flacfetch(FlacfetchServiceError("Download failed: tracker 500"))
@@ -0,0 +1,174 @@
"""create-from-url when YouTube bot-blocks the download.
Job 526bf46c (2026-11-03) failed within 3s of the first bot wall and showed the
customer the raw yt-dlp error, while the credential keeper replaces dead cookies
within minutes.
"""
import json
from pathlib import Path
from unittest.mock import AsyncMock, Mock, patch
import pytest
from fastapi import HTTPException
from backend.api.routes import file_upload
from backend.api.routes.file_upload import CreateJobFromUrlRequest, create_job_from_url
from backend.services.auth_service import AuthResult, UserType
from backend.services.youtube_download_service import (
YouTubeDownloadError,
is_bot_block_error,
)
BOT_WALL = (
"Remote download failed: Download failed: ERROR: [youtube] abcdefghijk: Sign in to "
"confirm you’re not a bot. This helps protect our community. Use "
"--cookies-from-browser or --cookies for the authentication."
)
TRANSLATIONS = Path(file_upload.__file__).parents[2] / "translations"
async def _create(download, availability=None):
request = Mock()
request.headers = {}
request.client = Mock(host="127.0.0.1")
request.url = Mock(path="/api/jobs/create-from-url")
request.state.tenant_config = None
service = Mock()
service.check_availability = availability or AsyncMock(return_value=None)
service.download = download
auth = AuthResult(
is_valid=True, user_type=UserType.ADMIN, remaining_uses=-1,
message="ok", user_email="user@example.com", is_admin=True,
)
body = CreateJobFromUrlRequest(url="https://www.youtube.com/watch?v=abcdefghijk", artist="A", title="T")
with patch.object(file_upload, "job_manager") as job_manager, \
patch.object(file_upload, "worker_service"), \
patch.object(file_upload, "get_credential_manager"), \
patch.object(file_upload, "get_youtube_download_service", return_value=service), \
patch.object(file_upload.asyncio, "sleep", new=AsyncMock()) as sleep:
job_manager.create_job.return_value = Mock(job_id="job-1")
try:
result = await create_job_from_url(
request=request, background_tasks=Mock(), body=body, auth_result=auth,
)
except HTTPException as e:
result = e
return result, job_manager, sleep
@pytest.mark.asyncio
async def test_bot_block_retries_after_delay_and_succeeds():
download = AsyncMock(side_effect=[YouTubeDownloadError(BOT_WALL), "uploads/job-1/audio/a.flac"])
result, job_manager, sleep = await _create(download)
assert result.job_id == "job-1"
assert download.await_count == 2
sleep.assert_awaited_once_with(file_upload.BOT_BLOCK_RETRY_DELAY_SECONDS)
job_manager.fail_job.assert_not_called()
@pytest.mark.asyncio
async def test_bot_block_twice_fails_job_with_friendly_message():
download = AsyncMock(side_effect=YouTubeDownloadError(BOT_WALL))
result, job_manager, _ = await _create(download)
assert download.await_count == 2
assert isinstance(result, HTTPException)
assert result.status_code == 500 # 503 would read as a backend blip in the frontend
assert "Audio Search" in result.detail
assert "cookies" not in result.detail
assert "ERROR" not in result.detail
job_manager.fail_job.assert_called_once()
args = job_manager.fail_job.call_args
assert args.args[1] == result.detail
# Operators keep the real error.
assert "not a bot" in args.kwargs["error_details"]["raw_error"]
assert args.kwargs["error_details"]["code"] == "youtube_bot_block"
@pytest.mark.asyncio
async def test_retry_failing_differently_reports_the_new_error():
download = AsyncMock(side_effect=[YouTubeDownloadError(BOT_WALL), YouTubeDownloadError("Video unavailable")])
result, job_manager, _ = await _create(download)
assert download.await_count == 2
assert "Video unavailable" in result.detail
assert "Video unavailable" in job_manager.fail_job.call_args.args[1]
@pytest.mark.asyncio
async def test_other_download_errors_fail_without_retry():
download = AsyncMock(side_effect=YouTubeDownloadError("Video unavailable"))
result, job_manager, sleep = await _create(download)
assert download.await_count == 1
sleep.assert_not_awaited()
assert result.status_code == 500
assert "Video unavailable" in result.detail
assert job_manager.fail_job.call_args.args[1] == "Download failed: Video unavailable"
BLOCKED_CHECK = {"available": False, "is_bot_blocked": True, "error": "not a bot"}
@pytest.mark.asyncio
async def test_bot_blocked_precheck_is_rechecked_and_job_proceeds():
"""Before any job exists, the same wait gives the cookie re-export time to finish."""
availability = AsyncMock(side_effect=[BLOCKED_CHECK, {"available": True}])
download = AsyncMock(return_value="uploads/job-1/audio/a.flac")
result, job_manager, sleep = await _create(download, availability)
assert result.job_id == "job-1"
assert availability.await_count == 2
sleep.assert_awaited_once_with(file_upload.BOT_BLOCK_RETRY_DELAY_SECONDS)
job_manager.create_job.assert_called_once()
@pytest.mark.asyncio
async def test_bot_blocked_precheck_twice_rejects_without_creating_a_job():
availability = AsyncMock(return_value=BLOCKED_CHECK)
download = AsyncMock()
result, job_manager, _ = await _create(download, availability)
assert availability.await_count == 2
assert result.status_code == 400
assert "Audio Search" in result.detail
job_manager.create_job.assert_not_called()
download.assert_not_awaited()
@pytest.mark.asyncio
async def test_other_unavailable_precheck_rejects_without_recheck():
availability = AsyncMock(return_value={"available": False, "is_private": True})
result, _, sleep = await _create(AsyncMock(), availability)
assert availability.await_count == 1
sleep.assert_not_awaited()
assert result.status_code == 400
assert "private" in result.detail
@pytest.mark.parametrize("message,expected", [
(BOT_WALL, True),
("Sign in to confirm you're NOT A BOT", True),
("The provided YouTube account cookies are no longer valid.", True),
("Sign in to confirm your age", False),
("Video unavailable", False),
])
def test_is_bot_block_error(message, expected):
assert is_bot_block_error(YouTubeDownloadError(message)) is expected
def test_friendly_message_is_translated_in_every_locale():
locale_files = sorted(TRANSLATIONS.glob("*.json"))
assert len(locale_files) == 33
english = json.loads((TRANSLATIONS / "en.json").read_text())["audioSearch"]["youtubeBotBlocked"]
for path in locale_files:
value = json.loads(path.read_text())["audioSearch"]["youtubeBotBlocked"]
assert value.strip(), path.name
if path.name != "en.json":
assert value != english, f"{path.name} is untranslated"
+60
View File
@@ -1,6 +1,7 @@
"""
Tests for credential manager and auth endpoints.
"""
import logging
import pytest
import json
from unittest.mock import MagicMock, patch
@@ -194,6 +195,65 @@ class TestCredentialManager:
assert result is False
def test_expired_dropbox_token_probe_logs_warning_not_error(self, caplog):
"""Short-lived tokens expire constantly and get refreshed; that isn't page-worthy."""
manager = CredentialManager()
with patch('dropbox.Dropbox', side_effect=Exception("expired_access_token")):
with caplog.at_level(logging.INFO, logger="backend.services.credential_manager"):
assert manager._test_dropbox_api({"access_token": "test"}) is False
levels = [r.levelno for r in caplog.records if "Dropbox" in r.message]
assert levels == [logging.WARNING]
def _dropbox_manager(self, creds):
manager = CredentialManager()
manager.settings = MagicMock()
manager.settings.get_secret.return_value = json.dumps(creds)
return manager
FULL_DROPBOX_CREDS = {"access_token": "a", "refresh_token": "r", "app_key": "k", "app_secret": "s"}
def test_dropbox_refresh_success_logs_no_error(self, caplog):
manager = self._dropbox_manager(self.FULL_DROPBOX_CREDS)
ok = MagicMock(status_code=200)
ok.json.return_value = {"access_token": "new"}
with patch('dropbox.Dropbox', side_effect=Exception("expired_access_token")), \
patch('requests.post', return_value=ok), \
patch.object(manager, "_update_dropbox_credentials", return_value=True):
with caplog.at_level(logging.INFO, logger="backend.services.credential_manager"):
result = manager.check_dropbox_credentials()
assert result.status == CredentialStatus.VALID
assert not [r for r in caplog.records if r.levelno >= logging.ERROR]
def test_dropbox_refresh_rejected_logs_error(self, caplog):
manager = self._dropbox_manager(self.FULL_DROPBOX_CREDS)
bad = MagicMock(status_code=400, text='{"error": "invalid_grant"}')
with patch('dropbox.Dropbox', side_effect=Exception("expired_access_token")), \
patch('requests.post', return_value=bad):
with caplog.at_level(logging.INFO, logger="backend.services.credential_manager"):
result = manager.check_dropbox_credentials()
assert result.status == CredentialStatus.INVALID
errors = [r.message for r in caplog.records if r.levelno >= logging.ERROR]
assert len(errors) == 1
assert "400" in errors[0]
assert "invalid_grant" in errors[0]
def test_dropbox_refresh_raising_logs_one_error(self, caplog):
manager = self._dropbox_manager(self.FULL_DROPBOX_CREDS)
with patch('dropbox.Dropbox', side_effect=Exception("expired_access_token")), \
patch('requests.post', side_effect=RuntimeError("network down")):
with caplog.at_level(logging.INFO, logger="backend.services.credential_manager"):
result = manager.check_dropbox_credentials()
assert result.status == CredentialStatus.INVALID
assert len([r for r in caplog.records if r.levelno >= logging.ERROR]) == 1
def test_dropbox_invalid_with_no_refresh_token_logs_error(self, caplog):
manager = self._dropbox_manager({"access_token": "a"})
with patch('dropbox.Dropbox', side_effect=Exception("expired_access_token")):
with caplog.at_level(logging.INFO, logger="backend.services.credential_manager"):
result = manager.check_dropbox_credentials()
assert result.status == CredentialStatus.INVALID
assert len([r for r in caplog.records if r.levelno >= logging.ERROR]) == 1
def test_send_credential_alert_no_webhook(self):
"""Test alert without webhook URL."""
manager = CredentialManager()
+18
View File
@@ -290,6 +290,24 @@ class TestJobStatusTransitions:
class TestJobFailure:
"""Test job failure handling."""
def test_fail_job_logs_warning_not_error(self, job_manager, mock_firestore_service, caplog):
"""ops_alerts' job-failed alert is the one alert; an ERROR here made a second one."""
import logging
mock_firestore_service.get_job.return_value = None
with caplog.at_level(logging.INFO, logger="backend.services.job_manager"):
job_manager.fail_job("job-1", "Download failed: boom")
records = [r for r in caplog.records if "job-1 failed" in r.getMessage()]
assert [r.levelno for r in records] == [logging.WARNING]
def test_mark_job_failed_logs_warning_not_error(self, job_manager, mock_firestore_service, caplog):
import logging
with caplog.at_level(logging.INFO, logger="backend.services.job_manager"):
job_manager.mark_job_failed("job-2", "boom")
records = [r for r in caplog.records if "job-2 failed" in r.getMessage()]
assert [r.levelno for r in records] == [logging.WARNING]
def test_mark_job_as_failed(self, job_manager, mock_firestore_service):
"""Test marking a job as failed."""
error_message = "Audio separation failed"
+29 -3
View File
@@ -426,6 +426,14 @@ class TestStartReview:
mock_job_manager.transition_to_state.assert_not_called()
mock_job_manager.record_review_started.assert_not_called()
@pytest.mark.parametrize("status", [JobStatus.COMPLETE, JobStatus.REVIEW_COMPLETE, JobStatus.ENCODING])
def test_start_review_after_review_ended_is_409(self, client, mock_job_manager, mock_job, auth_headers, status):
"""A stale link or notification gets an expected 409, with no transition attempt (which logs ERROR)."""
mock_job.status = status
response = client.post("/api/jobs/test123/start-review", json={}, headers=auth_headers)
assert response.status_code == 409
mock_job_manager.transition_to_state.assert_not_called()
def test_start_review_lost_race_is_success(self, client, mock_job_manager, mock_job, auth_headers):
"""Both requests saw awaiting_review; the loser's transition raises but job is in_review."""
from backend.exceptions import InvalidStateTransitionError
@@ -440,12 +448,30 @@ class TestStartReview:
assert response.json() == {"status": "success", "job_status": "in_review"}
mock_job_manager.record_review_started.assert_not_called()
def test_start_review_invalid_transition_otherwise_still_errors(self, client, mock_job_manager, mock_job, auth_headers):
def test_start_review_invalid_transition_race_returns_409(self, client, mock_job_manager, mock_job, auth_headers):
"""The auto-approver moved the job past review between our read and the transition."""
from backend.exceptions import InvalidStateTransitionError
mock_job.status = JobStatus.AWAITING_REVIEW
moved_on = mock_job.model_copy(update={"status": JobStatus.REVIEW_COMPLETE})
mock_job_manager.get_job.side_effect = [mock_job, moved_on, moved_on]
mock_job_manager.transition_to_state.side_effect = InvalidStateTransitionError(message="nope")
with pytest.raises(InvalidStateTransitionError):
client.post("/api/jobs/test123/start-review", json={}, headers=auth_headers)
response = client.post("/api/jobs/test123/start-review", json={}, headers=auth_headers)
assert response.status_code == 409
assert "review_complete" in response.json()["detail"]
mock_job_manager.record_review_started.assert_not_called()
@pytest.mark.parametrize("status", [JobStatus.COMPLETE, JobStatus.FAILED, JobStatus.PENDING])
def test_start_review_outside_review_returns_409_without_transition(
self, client, mock_job_manager, mock_job, auth_headers, status
):
"""A stale "review lyrics" push on a finished job: no 500, no transition, no ERROR log."""
mock_job.status = status
response = client.post("/api/jobs/test123/start-review", json={}, headers=auth_headers)
assert response.status_code == 409
assert status.value in response.json()["detail"]
assert "JobStatus." not in response.json()["detail"]
mock_job_manager.transition_to_state.assert_not_called()
mock_job_manager.record_review_started.assert_not_called()
def test_start_review_from_awaiting_records_once(self, client, mock_job_manager, mock_job, auth_headers):
mock_job.status = JobStatus.AWAITING_REVIEW
+64
View File
@@ -181,3 +181,67 @@ def test_lifespan_warms_route_contexts_off_loop_before_readiness():
assert seen[0][0] is main_module.app
assert seen[0][1].startswith("asyncio_"), seen
def test_anyio_backend_is_a_lazy_route_import():
"""starlette/middleware/base.py imports it on the first request: 17.3s on the loop
with 18 requests in flight, 2026-10-30."""
assert "anyio._backends._asyncio" in main_module._LAZY_ROUTE_IMPORTS
def test_warm_request_runs_through_the_whole_middleware_stack_off_loop():
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import PlainTextResponse
from starlette.routing import Route
seen = {}
class Spy(BaseHTTPMiddleware):
async def dispatch(self, request, call_next):
seen["thread"] = threading.current_thread().name
seen["path"] = request.url.path
return await call_next(request)
async def health(_request):
return PlainTextResponse("ok")
app = Starlette(routes=[Route("/api/health", health)], middleware=[Middleware(Spy)])
assert app.middleware_stack is None
worker = threading.Thread(target=main_module._warm_middleware_stack, args=(app,), name="warm-test")
worker.start()
worker.join(timeout=10)
assert seen == {"thread": "warm-test", "path": "/api/health"}
assert app.middleware_stack is not None
def test_warm_request_failure_never_blocks_startup():
async def broken_app(scope, receive, send):
raise RuntimeError("boom")
main_module._warm_middleware_stack(broken_app) # must not raise
def test_lifespan_warms_the_middleware_stack_before_readiness():
calls = []
def fake_warm(application):
calls.append(application)
with patch.object(main_module, "_run_background_warmup"), \
patch.object(main_module, "_warm_middleware_stack", fake_warm):
with TestClient(main_module.app):
assert calls == [main_module.app]
def test_warm_request_on_the_real_app_returns_healthy_and_skips_the_audit_log(caplog):
import logging
with caplog.at_level(logging.INFO):
main_module._warm_middleware_stack(main_module.app)
assert main_module.app.middleware_stack is not None
assert not [r for r in caplog.records if r.name == "audit"]
assert not [r for r in caplog.records if "warm request failed" in r.message.lower()]
+29
View File
@@ -1738,6 +1738,35 @@ class TestReplayCorrectionData:
finally:
self._teardown()
def _awaiting_job(self):
from backend.models.job import JobStatus
job = self._completed_job()
job.status = JobStatus.AWAITING_REVIEW
job.state_data = {}
return job
def test_auto_approver_race_returns_409_not_500(self):
"""Job read as awaiting_review, then auto-approved before our transition."""
from backend.exceptions import InvalidStateTransitionError
from backend.models.job import JobStatus
client = self._client_with_auth("full")
try:
with patch("backend.api.routes.review.JobManager") as jm, \
patch("backend.api.routes.review.StorageService") as storage_cls:
moved_on = self._awaiting_job()
moved_on.status = JobStatus.REVIEW_COMPLETE
jm.return_value.get_job.side_effect = [self._awaiting_job(), moved_on, moved_on]
jm.return_value.transition_to_state.side_effect = InvalidStateTransitionError(message="nope")
storage_cls.return_value.file_exists.return_value = True
storage_cls.return_value.download_json.return_value = {"corrected_segments": []}
resp = client.get("/api/review/job1/correction-data")
assert resp.status_code == 409
assert "review_complete" in resp.json()["detail"]
jm.return_value.record_review_started.assert_not_called()
finally:
self._teardown()
def test_replay_requires_full_auth(self):
client = self._client_with_auth("review_token")
try:
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "فهرس تحديد غير صالح {selection_index}. النطاق الصالح: 0-{max}",
"selectionError": "خطأ أثناء تحديد الصوت للمهمة {job_id}: {error}",
"youtubeDownloadError": "فشل تنزيل YouTube: {error}",
"youtubeBotBlocked": "يحظر YouTube خادمنا مؤقتاً، لذا لم نتمكن من تنزيل هذا الفيديو. يرجى استخدام البحث الصوتي للعثور على هذه الأغنية من مصدر آخر، أو المحاولة مرة أخرى بعد بضع دقائق.",
"torrentDownloadError": "لا يمكن التنزيل من {source} بدون خدمة flacfetch عن بُعد. قم بإعداد FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "لا يتوفر source_id أو remote_search_id لتنزيل {source}",
"remoteDownloadCompleteNoPath": "اكتمل التنزيل عن بُعد ولكن لم يتم إرجاع مسار الملف",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Índex de selecció no vàlid {selection_index}. Rang vàlid: 0-{max}",
"selectionError": "Error durant la selecció d'àudio per a la tasca {job_id}: {error}",
"youtubeDownloadError": "La descàrrega de YouTube ha fallat: {error}",
"youtubeBotBlocked": "YouTube està bloquejant temporalment el nostre servidor, així que no hem pogut baixar aquest vídeo. Utilitza la Cerca d'àudio per trobar aquesta cançó en una altra font, o torna-ho a provar d'aquí a uns minuts.",
"torrentDownloadError": "No es pot descarregar des de {source} sense el servei remot flacfetch. Configura FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "No hi ha cap source_id o remote_search_id disponible per a la descàrrega de {source}",
"remoteDownloadCompleteNoPath": "Descàrrega remota completada però no s'ha retornat cap camí de fitxer",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Neplatný index výběru {selection_index}. Platný rozsah: 0-{max}",
"selectionError": "Chyba při výběru zvuku pro úlohu {job_id}: {error}",
"youtubeDownloadError": "Stahování z YouTube selhalo: {error}",
"youtubeBotBlocked": "YouTube dočasně blokuje náš server, takže se nám toto video nepodařilo stáhnout. Použij prosím Audio Search k vyhledání této písně z jiného zdroje, nebo to zkus znovu za pár minut.",
"torrentDownloadError": "Nelze stahovat z {source} bez vzdálené služby flacfetch. Nakonfiguruj FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Pro stahování z {source} není k dispozici žádné source_id nebo remote_search_id",
"remoteDownloadCompleteNoPath": "Vzdálené stahování bylo dokončeno, ale nebyla vrácena žádná cesta k souboru",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Ugyldigt valgindeks {selection_index}. Gyldigt område: 0-{max}",
"selectionError": "Fejl under lydvalg for job {job_id}: {error}",
"youtubeDownloadError": "YouTube-download mislykkedes: {error}",
"youtubeBotBlocked": "YouTube blokerer midlertidigt vores server, så vi kunne ikke downloade denne video. Brug Audio Search til at finde denne sang fra en anden kilde, eller prøv igen om et par minutter.",
"torrentDownloadError": "Kan ikke downloade fra {source} uden ekstern flacfetch-tjeneste. Konfigurer FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Ingen source_id eller remote_search_id tilgængelig for {source}-download",
"remoteDownloadCompleteNoPath": "Ekstern download fuldført, men ingen filsti blev returneret",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Ungültiger Auswahlindex {selection_index}. Gültiger Bereich: 0-{max}",
"selectionError": "Fehler bei der Audioauswahl für Auftrag {job_id}: {error}",
"youtubeDownloadError": "YouTube-Download fehlgeschlagen: {error}",
"youtubeBotBlocked": "YouTube blockiert unseren Server vorübergehend, daher konnten wir dieses Video nicht herunterladen. Bitte verwende die Audiosuche, um diesen Song aus einer anderen Quelle zu finden, oder versuche es in ein paar Minuten noch einmal.",
"torrentDownloadError": "Download von {source} ohne Remote-flacfetch-Dienst nicht möglich. Konfiguriere FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Keine source_id oder remote_search_id für den {source}-Download verfügbar",
"remoteDownloadCompleteNoPath": "Remote-Download abgeschlossen, aber kein Dateipfad zurückgegeben",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Μη έγκυρο ευρετήριο επιλογής {selection_index}. Έγκυρο εύρος: 0-{max}",
"selectionError": "Σφάλμα κατά την επιλογή ήχου για την εργασία {job_id}: {error}",
"youtubeDownloadError": "Η λήψη από το YouTube απέτυχε: {error}",
"youtubeBotBlocked": "Το YouTube μπλοκάρει προσωρινά τον διακομιστή μας, οπότε δεν μπορέσαμε να κατεβάσουμε αυτό το βίντεο. Χρησιμοποίησε την Αναζήτηση Ήχου για να βρεις αυτό το τραγούδι από άλλη πηγή, ή δοκίμασε ξανά σε λίγα λεπτά.",
"torrentDownloadError": "Δεν είναι δυνατή η λήψη από το {source} χωρίς την απομακρυσμένη υπηρεσία flacfetch. Ρύθμισε το FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Δεν υπάρχει διαθέσιμο source_id ή remote_search_id για τη λήψη από το {source}",
"remoteDownloadCompleteNoPath": "Η απομακρυσμένη λήψη ολοκληρώθηκε αλλά δεν επιστράφηκε διαδρομή αρχείου",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Invalid selection index {selection_index}. Valid range: 0-{max}",
"selectionError": "Error during audio selection for job {job_id}: {error}",
"youtubeDownloadError": "YouTube download failed: {error}",
"youtubeBotBlocked": "YouTube is temporarily blocking our server, so we couldn't download this video. Please use Audio Search to find this song from another source, or try again in a few minutes.",
"drmUrlUnsupported": "{platform} links are copy-protected, so we can't download them directly. Try downloading the audio with a third-party tool first, then upload the audio file here. You can also paste a YouTube link, or use Audio Search to find this song.",
"drmUrlUnsupportedWithLink": "{platform} links are copy-protected, so we can't download them directly. You can download the track using a tool like {downloader} and then upload the audio file here. You can also paste a YouTube link, or use Audio Search to find this song.",
"drmUrlUnsupportedSearch": "{platform} links are copy-protected, so we can't download them directly. Search the web for a \"{platform} downloader\" to get the audio — for example {searchUrl} — then upload the audio file here. You can also paste a YouTube link, or use Audio Search to find this song.",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Índice de selección inválido {selection_index}. Rango válido: 0-{max}",
"selectionError": "Error durante la selección de audio para el trabajo {job_id}: {error}",
"youtubeDownloadError": "La descarga de YouTube falló: {error}",
"youtubeBotBlocked": "YouTube está bloqueando temporalmente nuestro servidor, así que no pudimos descargar este video. Usa la Búsqueda de Audio para encontrar esta canción en otra fuente, o inténtalo de nuevo en unos minutos.",
"torrentDownloadError": "No se puede descargar de {source} sin el servicio remoto flacfetch. Configura FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "No hay source_id o remote_search_id disponible para la descarga de {source}",
"remoteDownloadCompleteNoPath": "Descarga remota completada pero no se devolvió la ruta del archivo",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Virheellinen valintaindeksi {selection_index}. Sallittu väli: 0-{max}",
"selectionError": "Virhe äänen valinnassa työlle {job_id}: {error}",
"youtubeDownloadError": "YouTube-lataus epäonnistui: {error}",
"youtubeBotBlocked": "YouTube estää palvelimemme tilapäisesti, joten emme voineet ladata tätä videota. Etsi tämä kappale toisesta lähteestä Äänihaun avulla tai yritä uudelleen muutaman minuutin kuluttua.",
"torrentDownloadError": "Ei voida ladata lähteestä {source} ilman etä-flacfetch-palvelua. Määritä FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Lähdetunnusta (source_id) tai etähakutunnusta (remote_search_id) ei ole saatavilla {source}-lataukseen",
"remoteDownloadCompleteNoPath": "Etälataus valmistui, mutta tiedostopolkua ei palautettu",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Index de sélection invalide {selection_index}. Plage valide : 0-{max}",
"selectionError": "Erreur lors de la sélection audio pour la tâche {job_id} : {error}",
"youtubeDownloadError": "Le téléchargement YouTube a échoué : {error}",
"youtubeBotBlocked": "YouTube bloque temporairement notre serveur, nous n'avons donc pas pu télécharger cette vidéo. Utilise la Recherche Audio pour trouver cette chanson depuis une autre source, ou réessaie dans quelques minutes.",
"torrentDownloadError": "Impossible de télécharger depuis {source} sans le service flacfetch distant. Configure FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Aucun source_id ou remote_search_id disponible pour le téléchargement {source}",
"remoteDownloadCompleteNoPath": "Téléchargement distant terminé mais aucun chemin de fichier retourné",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "אינדקס בחירה לא חוקי {selection_index}. טווח חוקי: 0-{max}",
"selectionError": "שגיאה במהלך בחירת האודיו עבור המשימה {job_id}: {error}",
"youtubeDownloadError": "ההורדה מ-YouTube נכשלה: {error}",
"youtubeBotBlocked": "YouTube חוסם זמנית את השרת שלנו, ולכן לא הצלחנו להוריד את הסרטון הזה. אפשר להשתמש בחיפוש אודיו כדי למצוא את השיר הזה ממקור אחר, או לנסות שוב בעוד כמה דקות.",
"torrentDownloadError": "לא ניתן להוריד מ-{source} ללא שירות flacfetch מרוחק. הגדירו את FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "אין source_id או remote_search_id זמינים להורדה מ-{source}",
"remoteDownloadCompleteNoPath": "ההורדה המרוחקת הושלמה אך לא הוחזר נתיב קובץ",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "अमान्य सिलेक्शन इंडेक्स {selection_index}। मान्य रेंज: 0-{max}",
"selectionError": "जॉब {job_id} के लिए ऑडियो सिलेक्शन के दौरान त्रुटि: {error}",
"youtubeDownloadError": "YouTube डाउनलोड विफल: {error}",
"youtubeBotBlocked": "YouTube अस्थायी रूप से हमारे सर्वर को ब्लॉक कर रहा है, इसलिए हम यह वीडियो डाउनलोड नहीं कर सके। कृपया इस गाने को किसी अन्य स्रोत से खोजने के लिए Audio Search का उपयोग करो, या कुछ मिनट बाद फिर से कोशिश करो।",
"torrentDownloadError": "रिमोट flacfetch सर्विस के बिना {source} से डाउनलोड नहीं किया जा सकता। FLACFETCH_API_URL कॉन्फ़िगर करो।",
"remoteDownloadNoSearchId": "{source} डाउनलोड के लिए कोई source_id या remote_search_id उपलब्ध नहीं है",
"remoteDownloadCompleteNoPath": "रिमोट डाउनलोड पूरा हुआ लेकिन कोई फ़ाइल पाथ नहीं मिला",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Nevažeći indeks odabira {selection_index}. Važeći raspon: 0-{max}",
"selectionError": "Pogreška tijekom odabira zvuka za zadatak {job_id}: {error}",
"youtubeDownloadError": "Preuzimanje s YouTubea nije uspjelo: {error}",
"youtubeBotBlocked": "YouTube privremeno blokira naš poslužitelj pa nismo mogli preuzeti ovaj videozapis. Koristi pretraživanje zvuka da pronađeš ovu pjesmu iz drugog izvora ili pokušaj ponovno za nekoliko minuta.",
"torrentDownloadError": "Nije moguće preuzeti s {source} bez udaljene flacfetch usluge. Konfiguriraj FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Nema dostupnog source_id ili remote_search_id za preuzimanje s {source}",
"remoteDownloadCompleteNoPath": "Udaljeno preuzimanje je završeno, ali putanja datoteke nije vraćena",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Érvénytelen kiválasztási index: {selection_index}. Érvényes tartomány: 0-{max}",
"selectionError": "Hiba a hang kiválasztása során a(z) {job_id} feladatnál: {error}",
"youtubeDownloadError": "A YouTube letöltés sikertelen: {error}",
"youtubeBotBlocked": "A YouTube ideiglenesen blokkolja a szerverünket, ezért nem tudtuk letölteni ezt a videót. Használd az Audio Search funkciót, hogy más forrásból találd meg a dalt, vagy próbáld újra néhány perc múlva.",
"torrentDownloadError": "Nem lehet letölteni a(z) {source} forrásból távoli flacfetch szolgáltatás nélkül. Konfiguráld a FLACFETCH_API_URL-t.",
"remoteDownloadNoSearchId": "Nincs elérhető source_id vagy remote_search_id a(z) {source} letöltéshez",
"remoteDownloadCompleteNoPath": "A távoli letöltés befejeződött, de nem tért vissza fájlútvonallal",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Indeks pilihan tidak valid {selection_index}. Rentang yang valid: 0-{max}",
"selectionError": "Kesalahan selama pemilihan audio untuk tugas {job_id}: {error}",
"youtubeDownloadError": "Unduhan YouTube gagal: {error}",
"youtubeBotBlocked": "YouTube sedang memblokir server kami untuk sementara, jadi kami tidak dapat mengunduh video ini. Gunakan Pencarian Audio untuk menemukan lagu ini dari sumber lain, atau coba lagi dalam beberapa menit.",
"torrentDownloadError": "Tidak dapat mengunduh dari {source} tanpa layanan flacfetch jarak jauh. Konfigurasikan FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Tidak ada source_id atau remote_search_id yang tersedia untuk unduhan {source}",
"remoteDownloadCompleteNoPath": "Unduhan jarak jauh selesai tetapi tidak ada jalur file yang dikembalikan",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Indice di selezione non valido {selection_index}. Intervallo valido: 0-{max}",
"selectionError": "Errore durante la selezione dell'audio per il lavoro {job_id}: {error}",
"youtubeDownloadError": "Download da YouTube non riuscito: {error}",
"youtubeBotBlocked": "YouTube sta bloccando temporaneamente il nostro server, quindi non siamo riusciti a scaricare questo video. Usa la Ricerca Audio per trovare questa canzone da un'altra fonte, oppure riprova tra qualche minuto.",
"torrentDownloadError": "Impossibile scaricare da {source} senza il servizio flacfetch remoto. Configura FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Nessun source_id o remote_search_id disponibile per il download da {source}",
"remoteDownloadCompleteNoPath": "Download remoto completato ma non è stato restituito alcun percorso file",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "無効な選択インデックス {selection_index} です。有効な範囲: 0-{max}",
"selectionError": "ジョブ {job_id} のオーディオ選択中にエラーが発生しました: {error}",
"youtubeDownloadError": "YouTubeのダウンロードに失敗しました: {error}",
"youtubeBotBlocked": "YouTubeが一時的に当社のサーバーをブロックしているため、この動画をダウンロードできませんでした。オーディオ検索を使って別のソースからこの曲を探すか、数分後にもう一度お試しください。",
"torrentDownloadError": "リモートのflacfetchサービスなしで {source} からダウンロードすることはできません。FLACFETCH_API_URLを設定してください。",
"remoteDownloadNoSearchId": "{source} のダウンロードに利用できる source_id または remote_search_id がありません",
"remoteDownloadCompleteNoPath": "リモートダウンロードは完了しましたが、ファイルパスが返されませんでした",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "잘못된 선택 인덱스 {selection_index}. 유효 범위: 0-{max}",
"selectionError": "작업 {job_id}의 오디오 선택 중 오류 발생: {error}",
"youtubeDownloadError": "YouTube 다운로드 실패: {error}",
"youtubeBotBlocked": "YouTube가 일시적으로 저희 서버를 차단하고 있어 이 동영상을 다운로드할 수 없습니다. 오디오 검색을 사용하여 다른 소스에서 이 노래를 찾거나 몇 분 후에 다시 시도해 주세요.",
"torrentDownloadError": "원격 flacfetch 서비스 없이 {source}에서 다운로드할 수 없습니다. FLACFETCH_API_URL을 구성하세요.",
"remoteDownloadNoSearchId": "{source} 다운로드에 사용할 수 있는 source_id 또는 remote_search_id가 없습니다",
"remoteDownloadCompleteNoPath": "원격 다운로드가 완료되었지만 파일 경로가 반환되지 않았습니다",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Indeks pilihan tidak sah {selection_index}. Julat sah: 0-{max}",
"selectionError": "Ralat semasa pemilihan audio untuk tugasan {job_id}: {error}",
"youtubeDownloadError": "Muat turun YouTube gagal: {error}",
"youtubeBotBlocked": "YouTube sedang menyekat pelayan kami buat sementara waktu, jadi kami tidak dapat memuat turun video ini. Sila gunakan Carian Audio untuk mencari lagu ini daripada sumber lain, atau cuba lagi dalam beberapa minit.",
"torrentDownloadError": "Tidak dapat memuat turun daripada {source} tanpa perkhidmatan flacfetch jauh. Konfigurasikan FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Tiada source_id atau remote_search_id tersedia untuk muat turun {source}",
"remoteDownloadCompleteNoPath": "Muat turun jauh selesai tetapi tiada laluan fail dikembalikan",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Ugyldig valgindeks {selection_index}. Gyldig område: 0-{max}",
"selectionError": "Feil under lydvalg for jobb {job_id}: {error}",
"youtubeDownloadError": "YouTube-nedlasting mislyktes: {error}",
"youtubeBotBlocked": "YouTube blokkerer serveren vår midlertidig, så vi kunne ikke laste ned denne videoen. Bruk Lydsøk for å finne denne sangen fra en annen kilde, eller prøv igjen om noen minutter.",
"torrentDownloadError": "Kan ikke laste ned fra {source} uten ekstern flacfetch-tjeneste. Konfigurer FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Ingen source_id eller remote_search_id tilgjengelig for {source}-nedlasting",
"remoteDownloadCompleteNoPath": "Ekstern nedlasting fullført, men ingen filbane returnert",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Ongeldige selectie-index {selection_index}. Geldig bereik: 0-{max}",
"selectionError": "Fout tijdens audioselectie voor taak {job_id}: {error}",
"youtubeDownloadError": "YouTube download mislukt: {error}",
"youtubeBotBlocked": "YouTube blokkeert onze server tijdelijk, dus we konden deze video niet downloaden. Gebruik Audio Search om dit nummer via een andere bron te vinden, of probeer het over een paar minuten opnieuw.",
"torrentDownloadError": "Kan niet downloaden van {source} zonder externe flacfetch-service. Configureer FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Geen source_id of remote_search_id beschikbaar voor {source} download",
"remoteDownloadCompleteNoPath": "Externe download voltooid maar geen bestandspad geretourneerd",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Nieprawidłowy indeks wyboru {selection_index}. Prawidłowy zakres: 0-{max}",
"selectionError": "Błąd podczas wyboru audio dla zadania {job_id}: {error}",
"youtubeDownloadError": "Pobieranie z YouTube nie powiodło się: {error}",
"youtubeBotBlocked": "YouTube tymczasowo blokuje nasz serwer, więc nie udało się pobrać tego filmu. Użyj wyszukiwania audio, aby znaleźć tę piosenkę z innego źródła, lub spróbuj ponownie za kilka minut.",
"torrentDownloadError": "Nie można pobrać z {source} bez zdalnej usługi flacfetch. Skonfiguruj FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Brak dostępnego source_id lub remote_search_id dla pobierania z {source}",
"remoteDownloadCompleteNoPath": "Zdalne pobieranie zakończone, ale nie zwrócono ścieżki pliku",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Índice de seleção inválido {selection_index}. Intervalo válido: 0-{max}",
"selectionError": "Erro durante a seleção de áudio para o job {job_id}: {error}",
"youtubeDownloadError": "Falha no download do YouTube: {error}",
"youtubeBotBlocked": "O YouTube está bloqueando temporariamente nosso servidor, então não conseguimos baixar este vídeo. Use a Pesquisa de Áudio para encontrar esta música em outra fonte ou tente novamente em alguns minutos.",
"torrentDownloadError": "Não é possível baixar de {source} sem o serviço remoto flacfetch. Configure FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Nenhum source_id ou remote_search_id disponível para o download de {source}",
"remoteDownloadCompleteNoPath": "Download remoto concluído, mas nenhum caminho de arquivo retornado",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Index de selecție invalid {selection_index}. Interval valid: 0-{max}",
"selectionError": "Eroare în timpul selecției audio pentru jobul {job_id}: {error}",
"youtubeDownloadError": "Descărcarea de pe YouTube a eșuat: {error}",
"youtubeBotBlocked": "YouTube ne blochează temporar serverul, așa că nu am putut descărca acest videoclip. Folosește Căutare Audio pentru a găsi această melodie din altă sursă sau încearcă din nou peste câteva minute.",
"torrentDownloadError": "Nu se poate descărca de pe {source} fără serviciul remote flacfetch. Configurează FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Niciun source_id sau remote_search_id disponibil pentru descărcarea de pe {source}",
"remoteDownloadCompleteNoPath": "Descărcarea de la distanță s-a finalizat, dar nu a fost returnată nicio cale de fișier",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Недопустимый индекс выбора {selection_index}. Допустимый диапазон: 0-{max}",
"selectionError": "Ошибка при выборе аудио для задачи {job_id}: {error}",
"youtubeDownloadError": "Ошибка скачивания с YouTube: {error}",
"youtubeBotBlocked": "YouTube временно блокирует наш сервер, поэтому нам не удалось скачать это видео. Используй Поиск аудио, чтобы найти эту песню в другом источнике, или попробуй ещё раз через несколько минут.",
"torrentDownloadError": "Невозможно скачать с {source} без удаленного сервиса flacfetch. Настрой FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Нет доступных source_id или remote_search_id для скачивания с {source}",
"remoteDownloadCompleteNoPath": "Удаленное скачивание завершено, но путь к файлу не возвращен",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Neplatný index výberu {selection_index}. Platný rozsah: 0-{max}",
"selectionError": "Chyba počas výberu zvuku pre úlohu {job_id}: {error}",
"youtubeDownloadError": "Sťahovanie z YouTube zlyhalo: {error}",
"youtubeBotBlocked": "YouTube dočasne blokuje náš server, takže sa nám toto video nepodarilo stiahnuť. Použi vyhľadávanie zvuku na nájdenie tejto piesne z iného zdroja alebo to skús znova o pár minút.",
"torrentDownloadError": "Nemožno sťahovať z {source} bez vzdialenej služby flacfetch. Nakonfiguruj FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Pre sťahovanie z {source} nie je k dispozícii žiadne source_id alebo remote_search_id",
"remoteDownloadCompleteNoPath": "Vzdialené sťahovanie bolo dokončené, ale nebola vrátená žiadna cesta k súboru",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Ogiltigt urvalsindex {selection_index}. Giltigt intervall: 0-{max}",
"selectionError": "Fel vid ljudval för jobb {job_id}: {error}",
"youtubeDownloadError": "YouTube-nedladdning misslyckades: {error}",
"youtubeBotBlocked": "YouTube blockerar tillfälligt vår server, så vi kunde inte ladda ner den här videon. Använd Ljudsökning för att hitta den här låten från en annan källa, eller försök igen om några minuter.",
"torrentDownloadError": "Kan inte ladda ner från {source} utan fjärrtjänsten flacfetch. Konfigurera FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Inget source_id eller remote_search_id tillgängligt för nedladdning från {source}",
"remoteDownloadCompleteNoPath": "Fjärrnedladdning slutförd men ingen filsökväg returnerades",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "ดัชนีการเลือก {selection_index} ไม่ถูกต้อง ช่วงที่ถูกต้อง: 0-{max}",
"selectionError": "เกิดข้อผิดพลาดระหว่างการเลือกเสียงสำหรับงาน {job_id}: {error}",
"youtubeDownloadError": "การดาวน์โหลด YouTube ล้มเหลว: {error}",
"youtubeBotBlocked": "YouTube กำลังบล็อกเซิร์ฟเวอร์ของเราชั่วคราว เราจึงไม่สามารถดาวน์โหลดวิดีโอนี้ได้ โปรดใช้ Audio Search เพื่อค้นหาเพลงนี้จากแหล่งอื่น หรือลองอีกครั้งในอีกสักครู่",
"torrentDownloadError": "ไม่สามารถดาวน์โหลดจาก {source} โดยไม่มีบริการ flacfetch ระยะไกล โปรดกำหนดค่า FLACFETCH_API_URL",
"remoteDownloadNoSearchId": "ไม่มี source_id หรือ remote_search_id สำหรับการดาวน์โหลด {source}",
"remoteDownloadCompleteNoPath": "การดาวน์โหลดระยะไกลเสร็จสมบูรณ์แต่ไม่ส่งคืนเส้นทางไฟล์",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Mali ang selection index na {selection_index}. Valid na range: 0-{max}",
"selectionError": "Error habang pumipili ng audio para sa job {job_id}: {error}",
"youtubeDownloadError": "Nabigo ang pag-download sa YouTube: {error}",
"youtubeBotBlocked": "Pansamantalang bina-block ng YouTube ang aming server, kaya hindi namin na-download ang video na ito. Gamitin ang Audio Search para hanapin ang kantang ito mula sa ibang source, o subukang muli pagkalipas ng ilang minuto.",
"torrentDownloadError": "Hindi maka-download mula sa {source} nang walang remote flacfetch service. I-configure ang FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Walang available na source_id o remote_search_id para sa {source} download",
"remoteDownloadCompleteNoPath": "Nakumpleto ang remote download pero walang ibinalik na file path",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Geçersiz seçim indeksi {selection_index}. Geçerli aralık: 0-{max}",
"selectionError": "{job_id} işi için ses seçimi sırasında hata: {error}",
"youtubeDownloadError": "YouTube indirmesi başarısız oldu: {error}",
"youtubeBotBlocked": "YouTube sunucumuzu geçici olarak engelliyor, bu yüzden bu videoyu indiremedik. Bu şarkıyı başka bir kaynaktan bulmak için Ses Arama'yı kullan veya birkaç dakika sonra tekrar dene.",
"torrentDownloadError": "Uzak flacfetch hizmeti olmadan {source} kaynağından indirilemiyor. FLACFETCH_API_URL'yi yapılandır.",
"remoteDownloadNoSearchId": "{source} indirmesi için source_id veya remote_search_id mevcut değil",
"remoteDownloadCompleteNoPath": "Uzak indirme tamamlandı ancak dosya yolu döndürülmedi",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Недійсний індекс вибору {selection_index}. Допустимий діапазон: 0-{max}",
"selectionError": "Помилка під час вибору аудіо для завдання {job_id}: {error}",
"youtubeDownloadError": "Помилка завантаження з YouTube: {error}",
"youtubeBotBlocked": "YouTube тимчасово блокує наш сервер, тому нам не вдалося завантажити це відео. Скористайся пошуком аудіо, щоб знайти цю пісню в іншому джерелі, або спробуй ще раз за кілька хвилин.",
"torrentDownloadError": "Не вдається завантажити з {source} без віддаленого сервісу flacfetch. Налаштуй FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Немає доступного source_id або remote_search_id для завантаження з {source}",
"remoteDownloadCompleteNoPath": "Віддалене завантаження завершено, але шлях до файлу не повернуто",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "Chỉ số lựa chọn không hợp lệ {selection_index}. Phạm vi hợp lệ: 0-{max}",
"selectionError": "Lỗi trong quá trình chọn âm thanh cho công việc {job_id}: {error}",
"youtubeDownloadError": "Tải xuống YouTube thất bại: {error}",
"youtubeBotBlocked": "YouTube đang tạm thời chặn máy chủ của chúng tôi nên chúng tôi không thể tải video này xuống. Vui lòng sử dụng Tìm kiếm Âm thanh để tìm bài hát này từ nguồn khác hoặc thử lại sau vài phút.",
"torrentDownloadError": "Không thể tải xuống từ {source} mà không có dịch vụ flacfetch từ xa. Hãy cấu hình FLACFETCH_API_URL.",
"remoteDownloadNoSearchId": "Không có source_id hoặc remote_search_id nào cho tải xuống {source}",
"remoteDownloadCompleteNoPath": "Tải xuống từ xa hoàn tất nhưng không trả về đường dẫn tệp",
+1
View File
@@ -93,6 +93,7 @@
"invalidSelectionIndex": "无效的选择索引 {selection_index}。有效范围:0-{max}",
"selectionError": "在为任务 {job_id} 选择音频时出错:{error}",
"youtubeDownloadError": "YouTube 下载失败:{error}",
"youtubeBotBlocked": "YouTube 暂时屏蔽了我们的服务器,因此我们无法下载此视频。请使用音频搜索从其他来源查找这首歌,或者几分钟后再试。",
"torrentDownloadError": "如果没有远程 flacfetch 服务,则无法从 {source} 下载。请配置 FLACFETCH_API_URL。",
"remoteDownloadNoSearchId": "没有可用于 {source} 下载的 source_id 或 remote_search_id",
"remoteDownloadCompleteNoPath": "远程下载已完成,但未返回文件路径",
+2 -1
View File
@@ -399,7 +399,8 @@ async def process_audio_download(job_id: str) -> bool:
if not isinstance(e, (DownloadError, FlacfetchServiceError)):
logger.error(f"[job:{job_id}] Download failed: {e}", exc_info=True)
else:
logger.error(f"[job:{job_id}] Download failed: {e}")
# Expected failure type; fail_job below sends the one job-failed alert.
logger.warning(f"[job:{job_id}] Download failed: {e}")
_mark_retry_pending_if_attempts_remain(job_manager, job_id)
job_manager.fail_job(job_id, f"Audio download failed: {e}",
error_details={'stage': 'audio_download'})
+8 -1
View File
@@ -117,7 +117,14 @@ Keeping #alerts readable (one root cause → one message):
`ended` line is ERROR (≥10s blocked with a request affected), so one freeze is
one pattern. The `backend/event_loop_stalls` metric keys on that line too.
- **Known noise** (`known_issues.py`) can be service-scoped, e.g.
github-runner-manager's scale-up "no available instance" aborts.
github-runner-manager's scale-up "no available instance" aborts, and scoped to a
request path too (decide-search's `/api/search/health` aborts).
- **Unhandled exceptions**: `Exception in ASGI application` and `request_audit_error`
become one `Unhandled exception: <Type: message>` pattern per cause, read from the
entry's `exception` field; the path goes in the sample only.
- **One alert per job failure**: `ops_alerts` sends it from the status write, so
`Job <id> failed` and the download-failure lines before it are not ERROR patterns.
YouTube video ids are normalized out of signatures.
Frontend crashes are captured via `window.onerror`, `unhandledrejection`, Next.js
`error.tsx`, and a `CrashReportBoundary` around the review UIs. They POST to
@@ -110,6 +110,13 @@ class SpotifyProvider(BaseLyricsProvider):
self.logger.debug(f"Making RapidAPI lyrics request for track ID {track_id}")
lyrics_response = requests.get(lyrics_url, headers=headers, params=lyrics_params, timeout=10)
if lyrics_response.status_code == 403:
# The search just succeeded with the same key, so the key is fine: a 401/403
# on /search stays the dead-key ERROR. Other providers fill in.
self.logger.warning(
f"Spotify RapidAPI lyrics step returned 403 for track {track_id}: {lyrics_response.text[:200]}"
)
return None
lyrics_response.raise_for_status()
lyrics_data = lyrics_response.json()
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.290.0"
version = "0.290.2"
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
license = "MIT"
@@ -585,3 +585,111 @@ class TestRunnerManagerNoAvailableInstance:
from backend.services.error_monitor.known_issues import should_ignore
assert should_ignore("github-runner-manager", "Failed to create runner VM: quota exceeded") is None
class TestAudioSeparationExperimentTracebacks:
"""Ad-hoc `python -c` experiments on prod job images (2026-10-31, 11-01) are not
job failures: two consecutive <string> frames."""
EXPERIMENT = (
"Traceback (most recent call last):\n"
' File "<string>", line 1, in <module>\n'
' File "<string>", line 250, in <module>\n'
' File "<string>", line 228, in forced_align\n'
"OverflowError: Python integer 1162 out of bounds for int8"
)
SPAWN = (
"Traceback (most recent call last):\n"
' File "<string>", line 1, in <module>\n'
' File "/usr/local/lib/python3.11/multiprocessing/spawn.py", line 122, in spawn_main\n'
" exitcode = _main(fd, parent_sentinel)\n"
"RuntimeError: a real worker crash"
)
def test_experiment_ignored_on_the_job(self):
from backend.services.error_monitor.known_issues import should_ignore
result = should_ignore("audio-separation-job", self.EXPERIMENT)
assert result is not None
assert result.pattern_name == "audio_separation_experiment_traceback"
def test_multiprocessing_spawn_traceback_still_alerts(self):
from backend.services.error_monitor.known_issues import should_ignore
assert should_ignore("audio-separation-job", self.SPAWN) is None
def test_same_traceback_on_other_services_still_alerts(self):
from backend.services.error_monitor.known_issues import should_ignore
assert should_ignore("karaoke-backend", self.EXPERIMENT) is None
def test_extract_message_does_not_truncate_before_should_ignore(self):
from unittest.mock import MagicMock
from backend.services.error_monitor.known_issues import should_ignore
from backend.services.error_monitor.monitor import _extract_message
entry = MagicMock()
entry.payload = "x" * 5000 + "\n" + self.EXPERIMENT
assert should_ignore("audio-separation-job", _extract_message(entry)) is not None
class TestUrlDownloadFailedDuplicate:
"""fail_job follows this line, and ops_alerts' job-failed alert is the one alert."""
MSG = "URL download failed: Remote download failed: ERROR: [youtube] abcdefghijk: Sign in to confirm"
def test_ignored_on_the_backend(self):
from backend.services.error_monitor.known_issues import should_ignore
result = should_ignore("karaoke-backend", self.MSG)
assert result is not None
assert result.pattern_name == "url_download_failed_duplicate"
def test_other_download_errors_still_alert(self):
from backend.services.error_monitor.known_issues import should_ignore
assert should_ignore("karaoke-backend", "GCS upload failed: URL download failed: x") is None
assert should_ignore("karaoke-backend", "Download failed: something") is None
class TestDecideSearchHealthAborts:
MSG = (
"The request was aborted after waiting too long for an available instance. "
"Additional troubleshooting documentation can be found at: "
"https://cloud.google.com/run/docs/troubleshooting#abort-request"
)
HEALTH = "https://karaoke-decide-search-x.a.run.app/api/search/health"
def test_health_probe_ignored(self):
from backend.services.error_monitor.known_issues import should_ignore
result = should_ignore("karaoke-decide-search", self.MSG, self.HEALTH)
assert result is not None
assert result.pattern_name == "decide_search_health_abort"
def test_health_probe_with_query_string_ignored(self):
from backend.services.error_monitor.known_issues import should_ignore
assert should_ignore("karaoke-decide-search", self.MSG, self.HEALTH + "?ping=1") is not None
def test_real_search_paths_still_alert(self):
from backend.services.error_monitor.known_issues import should_ignore
for url in (
"https://karaoke-decide-search-x.a.run.app/api/search?q=hello",
"https://karaoke-decide-search-x.a.run.app/api/search/health/deep",
"https://karaoke-decide-search-x.a.run.app/api/search/songs?q=/api/search/health",
):
assert should_ignore("karaoke-decide-search", self.MSG, url) is None
def test_no_url_still_alerts(self):
from backend.services.error_monitor.known_issues import should_ignore
assert should_ignore("karaoke-decide-search", self.MSG) is None
def test_other_services_and_messages_still_alert(self):
from backend.services.error_monitor.known_issues import should_ignore
assert should_ignore("karaoke-decide", self.MSG, self.HEALTH) is None
assert should_ignore("karaoke-decide-search", "boom", self.HEALTH) is None
@@ -178,6 +178,243 @@ class TestExtractMessage:
assert result is None or result == ""
# Invented paths/ids; the shapes are copied from real prod entries (2026-11-03).
_PLAIN_TRACEBACK = (
"Traceback (most recent call last):\n"
' File "/app/backend/middleware/audit_logging.py", line 63, in dispatch\n'
" response = await call_next(request)\n"
" ^^^^^^^^^^^^^^^^^^^^^^^^\n"
' File "/app/backend/services/job_manager.py", line 657, in validate_state_transition\n'
" raise InvalidStateTransitionError(\n"
"backend.exceptions.InvalidStateTransitionError: Invalid state transition for job 7f89f884: "
"complete -> in_review. Valid transitions: ['awaiting_review', 'lyrics_complete']\n"
)
_GROUP_TRACEBACK = (
" + Exception Group Traceback (most recent call last):\n"
' | File "/usr/local/lib/python3.11/site-packages/starlette/_utils.py", line 104, in create_collapsing_task_group\n'
" | async with anyio.create_task_group() as tg:\n"
' | File "/usr/local/lib/python3.11/site-packages/anyio/_backends/_asyncio.py", line 847, in __aexit__\n'
" | raise BaseExceptionGroup(\n"
" | ExceptionGroup: unhandled errors in a TaskGroup (1 sub-exception)\n"
" +-+---------------- 1 ----------------\n"
" | Traceback (most recent call last):\n"
' | File "/app/backend/services/job_manager.py", line 657, in validate_state_transition\n'
" | raise InvalidStateTransitionError(\n"
" | backend.exceptions.InvalidStateTransitionError: Invalid state transition for job 7f89f884: "
"complete -> in_review. Valid transitions: ['awaiting_review', 'lyrics_complete']\n"
" +------------------------------------\n"
)
_EXPECTED_CAUSE = (
"Unhandled exception: backend.exceptions.InvalidStateTransitionError: Invalid state transition "
"for job 7f89f884: complete -> in_review. Valid transitions: ['awaiting_review', 'lyrics_complete']"
)
class TestUnhandledExceptionMessages:
"""Every unhandled exception logs one of two fixed messages; the pattern must
come from the exception, or all crashes share one (already 'new') pattern and
a second, different crash never alerts."""
def _entry(self, message, exception, **extra):
entry = MagicMock()
entry.payload = {"message": message, "exception": exception, **extra}
return entry
def test_audit_error_plain_traceback(self):
m = _import_monitor_module()
entry = self._entry("request_audit_error", _PLAIN_TRACEBACK, path="/api/jobs/x/start-review", method="POST")
assert m._extract_message(entry) == _EXPECTED_CAUSE
def test_asgi_exception_group_traceback_with_pipe_prefixes(self):
m = _import_monitor_module()
entry = self._entry("Exception in ASGI application\n", _GROUP_TRACEBACK)
assert m._extract_message(entry) == _EXPECTED_CAUSE
def test_nested_exception_group(self):
m = _import_monitor_module()
nested = (
" + Exception Group Traceback (most recent call last):\n"
" | ExceptionGroup: outer (1 sub-exception)\n"
" +-+---------------- 1 ----------------\n"
" | Exception Group Traceback (most recent call last):\n"
" | ExceptionGroup: inner (1 sub-exception)\n"
" +-+---------------- 1 ----------------\n"
" | Traceback (most recent call last):\n"
' | File "/app/a.py", line 1, in f\n'
" | boom()\n"
" | ValueError: the real cause\n"
" +------------------------------------\n"
" +------------------------------------\n"
)
assert m._extract_message(self._entry("request_audit_error", nested)) == (
"Unhandled exception: ValueError: the real cause"
)
def test_multiline_exception_message_uses_its_first_line(self):
# pydantic's last traceback line is a docs link, the same for every failure.
m = _import_monitor_module()
exc = (
"Traceback (most recent call last):\n"
' File "/app/a.py", line 1, in f\n'
" boom()\n"
"pydantic_core._pydantic_core.ValidationError: 1 validation error for Job\n"
"status\n"
" Input should be a valid string\n"
" For further information visit https://errors.pydantic.dev/2/v/string_type\n"
)
assert m._extract_message(self._entry("request_audit_error", exc)) == (
"Unhandled exception: pydantic_core._pydantic_core.ValidationError: 1 validation error for Job"
)
def test_chained_exception_uses_the_final_one(self):
m = _import_monitor_module()
exc = (
"Traceback (most recent call last):\n"
' File "/app/a.py", line 1, in f\n'
" boom()\n"
"KeyError: 'first'\n\n"
"During handling of the above exception, another exception occurred:\n\n"
"Traceback (most recent call last):\n"
' File "/app/b.py", line 2, in g\n'
" bang()\n"
"RuntimeError: second\n"
)
assert m._extract_message(self._entry("request_audit_error", exc)) == (
"Unhandled exception: RuntimeError: second"
)
def test_no_exception_field_keeps_the_message(self):
m = _import_monitor_module()
entry = MagicMock()
entry.payload = {"message": "request_audit_error"}
assert m._extract_message(entry) == "request_audit_error"
def test_unparseable_exception_keeps_last_line(self):
m = _import_monitor_module()
assert m._extract_message(self._entry("request_audit_error", "something odd\nno frames here\n")) == (
"Unhandled exception: no frames here"
)
def test_other_messages_with_exception_field_are_untouched(self):
m = _import_monitor_module()
entry = self._entry("Job 1 could not save", _PLAIN_TRACEBACK)
assert m._extract_message(entry) == "Job 1 could not save"
def test_both_log_lines_of_one_crash_collapse_to_one_pattern(self):
from backend.services.error_monitor.normalizer import compute_pattern_hash, normalize_message
m = _import_monitor_module()
audit = m._extract_message(self._entry("request_audit_error", _PLAIN_TRACEBACK))
asgi = m._extract_message(self._entry("Exception in ASGI application\n", _GROUP_TRACEBACK))
assert compute_pattern_hash("s", normalize_message(audit)) == compute_pattern_hash("s", normalize_message(asgi))
def test_two_different_crashes_are_two_patterns(self):
from backend.services.error_monitor.normalizer import normalize_message
m = _import_monitor_module()
other = _PLAIN_TRACEBACK.replace(
"backend.exceptions.InvalidStateTransitionError: Invalid state transition for job 7f89f884: "
"complete -> in_review. Valid transitions: ['awaiting_review', 'lyrics_complete']",
"ZeroDivisionError: division by zero",
)
first = m._extract_message(self._entry("request_audit_error", _PLAIN_TRACEBACK))
second = m._extract_message(self._entry("request_audit_error", other))
assert normalize_message(first) != normalize_message(second)
def test_sample_keeps_the_path_but_the_pattern_does_not(self):
m = _import_monitor_module()
entry = self._entry(
"request_audit_error", _PLAIN_TRACEBACK, path="/api/jobs/7f89f884/start-review", method="POST"
)
message = m._extract_message(entry)
sample = m._extract_sample(entry, message)
assert sample.startswith("POST /api/jobs/7f89f884/start-review\n")
assert sample.endswith(_EXPECTED_CAUSE)
assert "start-review" not in message
def test_sample_is_the_message_without_a_path(self):
m = _import_monitor_module()
entry = self._entry("Exception in ASGI application\n", _GROUP_TRACEBACK)
message = m._extract_message(entry)
assert m._extract_sample(entry, message) == message
@patch("backend.services.error_monitor.monitor.get_llm_enabled", return_value=False)
@patch("backend.services.error_monitor.monitor.get_digest_mode", return_value=False)
def test_cycle_groups_a_crash_into_one_alert_with_the_path_in_its_sample(self, _digest, _llm):
from backend.services.error_monitor.firestore_adapter import UpsertResult
m = _import_monitor_module()
audit = _make_entry(
payload={
"message": "request_audit_error",
"exception": _PLAIN_TRACEBACK,
"path": "/api/jobs/7f89f884/start-review",
"method": "POST",
}
)
asgi = _make_entry(payload={"message": "Exception in ASGI application\n", "exception": _GROUP_TRACEBACK})
audit.http_request = asgi.http_request = None
monitor = _make_monitor_with_mocks()
monitor.logging_client.list_entries.side_effect = [iter([audit, asgi])] + [iter([])] * (
len(m.RESOURCE_TYPE_FILTERS) - 1
)
monitor.firestore_adapter.upsert_pattern.return_value = UpsertResult(pattern_id="p", is_new=True)
monitor.firestore_adapter.get_patterns_for_auto_resolve.return_value = []
monitor.firestore_adapter.get_active_patterns.return_value = []
monitor.firestore_adapter.get_unalerted_new_patterns.return_value = []
monitor.discord.send_message.return_value = True
monitor._run_monitor_cycle()
assert monitor.firestore_adapter.upsert_pattern.call_count == 1
data = monitor.firestore_adapter.upsert_pattern.call_args[0][0]
assert data.count == 2
assert "/api/jobs/7f89f884/start-review" in data.sample_message
assert "start-review" not in data.normalized_message
assert "InvalidStateTransitionError" in data.normalized_message
assert monitor.discord.send_message.call_count == 1
class TestExtractRequestUrl:
def test_reads_the_cloud_run_request_url(self):
m = _import_monitor_module()
entry = MagicMock()
entry.http_request = {"requestUrl": "https://x.a.run.app/api/search/health"}
assert m._extract_request_url(entry) == "https://x.a.run.app/api/search/health"
def test_none_without_http_request(self):
m = _import_monitor_module()
entry = MagicMock()
entry.http_request = None
assert m._extract_request_url(entry) is None
@patch("backend.services.error_monitor.monitor.get_llm_enabled", return_value=False)
@patch("backend.services.error_monitor.monitor.get_digest_mode", return_value=False)
def test_cycle_drops_health_aborts_but_alerts_real_search_paths(self, _digest, _llm):
from backend.services.error_monitor.firestore_adapter import UpsertResult
m = _import_monitor_module()
msg = "The request was aborted after waiting too long for an available instance."
health = _make_entry(payload=msg, service_name="karaoke-decide-search")
health.http_request = {"requestUrl": "https://x.a.run.app/api/search/health"}
real = _make_entry(payload=msg, service_name="karaoke-decide-search")
real.http_request = {"requestUrl": "https://x.a.run.app/api/search?q=hello"}
monitor = _make_monitor_with_mocks()
monitor.logging_client.list_entries.side_effect = [iter([health, real])] + [iter([])] * (
len(m.RESOURCE_TYPE_FILTERS) - 1
)
monitor.firestore_adapter.upsert_pattern.return_value = UpsertResult(pattern_id="p", is_new=True)
monitor.firestore_adapter.get_patterns_for_auto_resolve.return_value = []
monitor.firestore_adapter.get_active_patterns.return_value = []
monitor.firestore_adapter.get_unalerted_new_patterns.return_value = []
monitor.discord.send_message.return_value = True
monitor._run_monitor_cycle()
assert monitor.firestore_adapter.upsert_pattern.call_count == 1
assert monitor.firestore_adapter.upsert_pattern.call_args[0][0].count == 1
# ---------------------------------------------------------------------------
# Tests: _extract_service_name
# ---------------------------------------------------------------------------
@@ -452,3 +452,46 @@ def test_loop_stall_request_counts_collapse_to_one_pattern():
b = normalize_message("EVENT_LOOP_STALL ended duration_ms=81183 culprit=x.py:539 in f requests_affected=3")
assert a == b
assert "requests_affected=<N>" in a
class TestYouTubeVideoIds:
"""A video id in the text made every bot block a "first time" signature."""
def _bot_block(self, video_id):
return (
f"Download failed: ERROR: [youtube] {video_id}: Sign in to confirm you\u2019re not a bot. "
"Use --cookies-from-browser or --cookies for the authentication."
)
def test_same_error_on_different_videos_is_one_signature(self):
from backend.services.error_monitor.normalizer import normalize_message
assert normalize_message(self._bot_block("mBJivIsN0n0")) == normalize_message(self._bot_block("a_b-cDeFgHi"))
def test_id_replaced_with_a_placeholder(self):
from backend.services.error_monitor.normalizer import normalize_message
result = normalize_message(self._bot_block("mBJivIsN0n0"))
assert "[youtube] <VIDEO_ID>: Sign in" in result
assert "mBJivIsN0n0" not in result
def test_tab_extractor_variant(self):
from backend.services.error_monitor.normalizer import normalize_message
assert "[youtube:tab] <VIDEO_ID>:" in normalize_message("ERROR: [youtube:tab] mBJivIsN0n0: gone")
def test_bare_watch_url_id(self):
from backend.services.error_monitor.normalizer import normalize_message
result = normalize_message("Could not fetch youtube.com/watch?v=mBJivIsN0n0 today")
assert "mBJivIsN0n0" not in result
def test_youtube_words_without_an_id_are_kept(self):
from backend.services.error_monitor.normalizer import normalize_message
assert normalize_message("[youtube] Downloading webpage") == "[youtube] Downloading webpage"
def test_ops_alert_signature_ignores_the_video_id(self):
from backend.services.ops_alerts import _signature
assert _signature(self._bot_block("mBJivIsN0n0")) == _signature(self._bot_block("a_b-cDeFgHi"))
@@ -0,0 +1,65 @@
"""Log levels on the Spotify RapidAPI provider: ERROR pages a human, so a 403 on the
/lyrics step (the search just succeeded with the same key, other providers fill in)
is a WARNING, while 401/403 on /search stays the dead-key ERROR."""
import logging
from unittest.mock import MagicMock, patch
import pytest
import requests
from karaoke_gen.lyrics_transcriber.lyrics.base_lyrics_provider import LyricsProviderConfig
from karaoke_gen.lyrics_transcriber.lyrics.spotify import SpotifyProvider
SEARCH_OK = {"status": True, "errorId": "Success", "id": "track1"}
def _response(status, body=None, text=""):
resp = MagicMock()
resp.status_code = status
resp.text = text
resp.json.return_value = body or {}
if status >= 400:
err = requests.exceptions.HTTPError(f"{status} Client Error", response=resp)
resp.raise_for_status.side_effect = err
return resp
def _provider():
return SpotifyProvider(LyricsProviderConfig(rapidapi_key="test-key"), logger=logging.getLogger("spotify-test"))
def _levels(caplog):
return [r.levelno for r in caplog.records if r.name == "spotify-test"]
def test_lyrics_403_is_a_warning_with_the_body(caplog):
long_body = "not subscribed " + "x" * 500
with patch("requests.get", side_effect=[_response(200, SEARCH_OK), _response(403, text=long_body)]):
with caplog.at_level(logging.INFO, logger="spotify-test"):
assert _provider()._fetch_from_rapidapi("A", "T") is None
assert logging.ERROR not in _levels(caplog)
warning = next(r.message for r in caplog.records if r.levelno == logging.WARNING)
assert "not subscribed" in warning
assert "x" * 201 not in warning
@pytest.mark.parametrize("status", [401, 403])
def test_search_auth_failure_stays_an_error(caplog, status):
with patch("requests.get", side_effect=[_response(status)]):
with caplog.at_level(logging.INFO, logger="spotify-test"):
assert _provider()._fetch_from_rapidapi("A", "T") is None
assert logging.ERROR in _levels(caplog)
def test_lyrics_401_stays_an_error(caplog):
with patch("requests.get", side_effect=[_response(200, SEARCH_OK), _response(401)]):
with caplog.at_level(logging.INFO, logger="spotify-test"):
assert _provider()._fetch_from_rapidapi("A", "T") is None
assert logging.ERROR in _levels(caplog)
def test_lyrics_success_still_returns_data():
with patch("requests.get", side_effect=[_response(200, SEARCH_OK), _response(200, {"lyrics": []})]):
result = _provider()._fetch_from_rapidapi("A", "T")
assert result["_rapidapi_source"] is True