mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-03 16:48:05 +09:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c716c79022 |
No files matched your search
+216
-20
@@ -796,58 +796,254 @@ async def recover_stuck_jobs(
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
):
|
||||
"""
|
||||
Detect and recover jobs stuck in downloading_audio status.
|
||||
Detect and recover jobs stuck in a processing status.
|
||||
|
||||
Called by Cloud Scheduler (every 5 minutes) or manually from admin.
|
||||
Finds jobs stuck in DOWNLOADING_AUDIO for >10 minutes and fails them
|
||||
so they can be retried.
|
||||
- DOWNLOADING_AUDIO stuck >10 min:
|
||||
* torrent sources (RED/OPS) → park into DOWNLOAD_PENDING_RETRY and keep
|
||||
auto-retrying for up to 24h (handles rare tracks with intermittent
|
||||
seeders and transient tracker outages gracefully).
|
||||
* other sources → fail so the user can retry.
|
||||
- DOWNLOAD_PENDING_RETRY → re-trigger the download; permanently fail after 24h.
|
||||
- RENDERING_VIDEO stuck with no progress (worker died mid-render) →
|
||||
re-park into RENDER_PENDING_CAPACITY so the existing
|
||||
retry-pending-render-jobs cron resumes it automatically. Closes the orphan
|
||||
gap where a hard-killed render worker leaves the job frozen at
|
||||
"rendering_video" forever with no error and no Retry button.
|
||||
"""
|
||||
from backend.services.job_health_service import check_job_consistency
|
||||
from backend.services.worker_service import get_worker_service
|
||||
from backend.models.job import JobStatus
|
||||
|
||||
trace_context = extract_trace_context(dict(http_request.headers))
|
||||
extract_trace_context(dict(http_request.headers))
|
||||
logger.info("RECOVER_STUCK_JOBS starting")
|
||||
add_span_attribute("operation", "recover_stuck_jobs")
|
||||
|
||||
job_manager = JobManager()
|
||||
worker_service = get_worker_service()
|
||||
|
||||
# Query jobs in downloading_audio status
|
||||
from google.cloud.firestore_v1 import FieldFilter
|
||||
jobs_ref = job_manager.firestore.db.collection("jobs")
|
||||
|
||||
recovered = [] # download jobs failed for user retry
|
||||
download_parked = [] # transient torrent downloads parked for auto-retry
|
||||
download_retried = [] # parked downloads re-triggered this tick
|
||||
download_timed_out = [] # parked downloads that exceeded the 24h ceiling
|
||||
reparked = [] # render jobs re-parked for auto-retry
|
||||
|
||||
# --- Stuck audio downloads: park torrents for auto-retry, else fail ---
|
||||
stuck_query = jobs_ref.where(
|
||||
filter=FieldFilter("status", "==", "downloading_audio")
|
||||
filter=FieldFilter("status", "==", JobStatus.DOWNLOADING_AUDIO.value)
|
||||
).stream()
|
||||
|
||||
recovered = []
|
||||
for doc in stuck_query:
|
||||
job_data = doc.to_dict()
|
||||
job_id = job_data.get("job_id", doc.id)
|
||||
|
||||
# Use the health service to check if actually stuck
|
||||
job_id = (doc.to_dict() or {}).get("job_id", doc.id)
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
continue
|
||||
|
||||
issues = check_job_consistency(job)
|
||||
stuck_issues = [i for i in issues if "downloading_audio_stuck" in i]
|
||||
|
||||
if stuck_issues:
|
||||
logger.warning(f"[job:{job_id}] Recovering stuck download: {stuck_issues[0]}")
|
||||
if not any("downloading_audio_stuck" in i for i in check_job_consistency(job)):
|
||||
continue
|
||||
if _is_retryable_torrent_source(job):
|
||||
logger.warning(f"[job:{job_id}] Parking stuck torrent download for auto-retry")
|
||||
if _park_download_for_retry(job_manager, job_id, "download stalled (>10 min)"):
|
||||
download_parked.append(job_id)
|
||||
else:
|
||||
logger.warning(f"[job:{job_id}] Recovering stuck download (non-torrent)")
|
||||
job_manager.fail_job(
|
||||
job_id,
|
||||
"Audio download timed out (stuck >10 minutes). Use retry to re-attempt."
|
||||
)
|
||||
recovered.append(job_id)
|
||||
|
||||
logger.info(f"RECOVER_STUCK_JOBS complete: recovered={len(recovered)} jobs")
|
||||
add_span_event("recovery_complete", {"recovered_count": len(recovered)})
|
||||
# --- Parked downloads: re-trigger, or permanently fail after 24h ---
|
||||
retried_this_tick = 0
|
||||
pending_query = jobs_ref.where(
|
||||
filter=FieldFilter("status", "==", JobStatus.DOWNLOAD_PENDING_RETRY.value)
|
||||
).limit(100).stream()
|
||||
for doc in pending_query:
|
||||
job_id = (doc.to_dict() or {}).get("job_id", doc.id)
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
continue
|
||||
meta = (job.state_data or {}).get("download_retry", {}) or {}
|
||||
first_seen = meta.get("first_seen_at")
|
||||
if _download_retry_expired(first_seen):
|
||||
hours = int(DOWNLOAD_RETRY_MAX_SECONDS // 3600)
|
||||
logger.error(f"[job:{job_id}] Download retries exhausted after {hours}h — failing")
|
||||
job_manager.fail_job(
|
||||
job_id,
|
||||
f"Couldn't find a working source for this track after {hours}h of "
|
||||
"automatic retries. It may be too rare to source right now — please "
|
||||
"try a different version or contact support.",
|
||||
error_details={"stage": "audio_download", "permanent_download_timeout": True},
|
||||
)
|
||||
download_timed_out.append(job_id)
|
||||
continue
|
||||
if retried_this_tick >= DOWNLOAD_RETRIES_PER_TICK:
|
||||
continue
|
||||
# Count the dispatch ATTEMPT against the per-tick cap before awaiting, so
|
||||
# a failing audio-worker (helper returns False after an external dispatch)
|
||||
# can't fan out to every queried job in one tick.
|
||||
retried_this_tick += 1
|
||||
if await _retrigger_parked_download(job_manager, worker_service, job_id):
|
||||
download_retried.append(job_id)
|
||||
|
||||
# --- Orphaned renders: re-park for automatic retry ---
|
||||
render_query = jobs_ref.where(
|
||||
filter=FieldFilter("status", "==", JobStatus.RENDERING_VIDEO.value)
|
||||
).stream()
|
||||
for doc in render_query:
|
||||
job_id = (doc.to_dict() or {}).get("job_id", doc.id)
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
continue
|
||||
if any("rendering_video_stuck" in i for i in check_job_consistency(job)):
|
||||
logger.warning(f"[job:{job_id}] Re-parking orphaned render for auto-retry")
|
||||
if _repark_stalled_render(job_manager, job_id):
|
||||
reparked.append(job_id)
|
||||
|
||||
logger.info(
|
||||
f"RECOVER_STUCK_JOBS complete: recovered={len(recovered)} "
|
||||
f"download_parked={len(download_parked)} download_retried={len(download_retried)} "
|
||||
f"download_timed_out={len(download_timed_out)} reparked={len(reparked)}"
|
||||
)
|
||||
add_span_event("recovery_complete", {
|
||||
"recovered_count": len(recovered),
|
||||
"download_parked_count": len(download_parked),
|
||||
"download_retried_count": len(download_retried),
|
||||
"download_timed_out_count": len(download_timed_out),
|
||||
"reparked_count": len(reparked),
|
||||
})
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"recovered_jobs": recovered,
|
||||
"recovered_count": len(recovered),
|
||||
"download_parked_jobs": download_parked,
|
||||
"download_retried_jobs": download_retried,
|
||||
"download_timed_out_jobs": download_timed_out,
|
||||
"reparked_render_jobs": reparked,
|
||||
"reparked_render_count": len(reparked),
|
||||
}
|
||||
|
||||
|
||||
# Torrent sources whose downloads are worth auto-retrying over a long window —
|
||||
# they fail transiently when a rare release has few/intermittent seeders or the
|
||||
# private tracker is briefly unreachable. Non-torrent sources (YouTube/Spotify/
|
||||
# URL) fail deterministically, so they are not auto-retried here.
|
||||
RETRYABLE_TORRENT_SOURCES = frozenset({"RED", "OPS"})
|
||||
DOWNLOAD_RETRY_MAX_SECONDS = 24 * 60 * 60 # keep retrying a transient download for 24h
|
||||
DOWNLOAD_RETRIES_PER_TICK = 10 # cap re-triggers per 5-min tick
|
||||
|
||||
|
||||
def _is_retryable_torrent_source(job) -> bool:
|
||||
"""True if the job's audio came from a torrent tracker (RED/OPS)."""
|
||||
return (getattr(job, "source_name", "") or "").upper() in RETRYABLE_TORRENT_SOURCES
|
||||
|
||||
|
||||
def _download_retry_expired(first_seen_at: Optional[str]) -> bool:
|
||||
"""True if the first parked failure is older than the 24h retry ceiling."""
|
||||
if not first_seen_at:
|
||||
return False
|
||||
from datetime import datetime, UTC
|
||||
try:
|
||||
age = datetime.now(UTC) - datetime.fromisoformat(first_seen_at)
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
return age.total_seconds() > DOWNLOAD_RETRY_MAX_SECONDS
|
||||
|
||||
|
||||
def _park_download_for_retry(job_manager: JobManager, job_id: str, reason: str) -> bool:
|
||||
"""Park a transient torrent-download failure into DOWNLOAD_PENDING_RETRY.
|
||||
|
||||
The recover-stuck cron re-triggers parked downloads on later ticks (up to
|
||||
24h) instead of dead-ending the job at FAILED after ~1h.
|
||||
"""
|
||||
from datetime import datetime, UTC
|
||||
from backend.models.job import JobStatus
|
||||
|
||||
now = datetime.now(UTC).isoformat()
|
||||
job = job_manager.get_job(job_id)
|
||||
existing = (job.state_data or {}).get("download_retry", {}) if job else {}
|
||||
meta = {
|
||||
"first_seen_at": existing.get("first_seen_at") or now,
|
||||
"last_attempt_at": now,
|
||||
"attempt_count": int(existing.get("attempt_count", 0)) + 1,
|
||||
"last_reason": str(reason)[:300],
|
||||
}
|
||||
job_manager.update_state_data(job_id, "download_retry", meta)
|
||||
# Clear any Cloud Run auto-retry marker so the UI reflects the parked state.
|
||||
job_manager.update_state_data(job_id, "cloud_run_retry_pending", None)
|
||||
return bool(job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.DOWNLOAD_PENDING_RETRY,
|
||||
progress=12,
|
||||
message=(
|
||||
"Still finding a good source for this track — it may be rare, or a "
|
||||
"source is temporarily offline. We'll keep trying automatically for up "
|
||||
"to 24 hours; no action needed."
|
||||
),
|
||||
raise_on_invalid=False,
|
||||
))
|
||||
|
||||
|
||||
async def _retrigger_parked_download(job_manager: JobManager, worker_service, job_id: str) -> bool:
|
||||
"""Re-trigger the audio download for a DOWNLOAD_PENDING_RETRY job."""
|
||||
from backend.models.job import JobStatus
|
||||
|
||||
job_manager.update_job(job_id, {"error_message": None, "error_details": None})
|
||||
if not job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.DOWNLOADING_AUDIO,
|
||||
progress=12,
|
||||
message="Retrying audio download — checking sources again",
|
||||
raise_on_invalid=False,
|
||||
):
|
||||
logger.warning(f"[job:{job_id}] Could not transition parked download for retry")
|
||||
return False
|
||||
try:
|
||||
await worker_service.trigger_audio_download_worker(job_id)
|
||||
logger.info(f"[job:{job_id}] Parked download re-triggered")
|
||||
return True
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.error(f"[job:{job_id}] Failed to re-trigger parked download: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def _repark_stalled_render(job_manager: JobManager, job_id: str) -> bool:
|
||||
"""Re-park a render orphaned at RENDERING_VIDEO into RENDER_PENDING_CAPACITY.
|
||||
|
||||
Mirrors render_video_worker._park_job_for_capacity_retry but for a mid-render
|
||||
stall (no EncodingWorkerStartError to carry). The existing
|
||||
retry-pending-render-jobs cron then resets it to REVIEW_COMPLETE and
|
||||
re-triggers the render, with the same 24h permanent-failure ceiling.
|
||||
"""
|
||||
from datetime import datetime, UTC
|
||||
from backend.models.job import JobStatus
|
||||
|
||||
now = datetime.now(UTC).isoformat()
|
||||
job = job_manager.get_job(job_id)
|
||||
existing = (job.state_data or {}).get("render_pending_capacity", {}) if job else {}
|
||||
pending_meta = {
|
||||
"first_seen_at": existing.get("first_seen_at") or now,
|
||||
"last_attempt_at": now,
|
||||
"attempt_count": int(existing.get("attempt_count", 0)) + 1,
|
||||
"last_code": "render_stalled",
|
||||
"last_zone": existing.get("last_zone", ""),
|
||||
"last_vm": existing.get("last_vm", ""),
|
||||
}
|
||||
job_manager.update_state_data(job_id, "render_pending_capacity", pending_meta)
|
||||
return bool(job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.RENDER_PENDING_CAPACITY,
|
||||
progress=70,
|
||||
message=(
|
||||
"The render was interrupted (a worker was recycled). Your job will "
|
||||
"retry automatically — no action needed."
|
||||
),
|
||||
raise_on_invalid=False,
|
||||
))
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
async def internal_health(
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
|
||||
@@ -37,6 +37,7 @@ class JobStatus(str, Enum):
|
||||
SEARCHING_AUDIO = "searching_audio" # Searching for audio sources via flacfetch
|
||||
AWAITING_AUDIO_SELECTION = "awaiting_audio_selection" # ⚠️ WAITING FOR USER - select audio source
|
||||
DOWNLOADING_AUDIO = "downloading_audio" # Downloading selected audio from source
|
||||
DOWNLOAD_PENDING_RETRY = "download_pending_retry" # Download hit a transient issue (few/no seeders, tracker blip); auto-retrying for up to 24h
|
||||
|
||||
DOWNLOADING = "downloading" # Downloading from URL or processing upload
|
||||
|
||||
@@ -110,7 +111,11 @@ STATE_TRANSITIONS = {
|
||||
# Audio search flow (for artist+title search mode)
|
||||
JobStatus.SEARCHING_AUDIO: [JobStatus.AWAITING_AUDIO_SELECTION, JobStatus.DOWNLOADING_AUDIO, JobStatus.FAILED],
|
||||
JobStatus.AWAITING_AUDIO_SELECTION: [JobStatus.DOWNLOADING_AUDIO, JobStatus.FAILED, JobStatus.CANCELLED],
|
||||
JobStatus.DOWNLOADING_AUDIO: [JobStatus.DOWNLOADING, JobStatus.AWAITING_DURATION_CONFIRM, JobStatus.FAILED],
|
||||
JobStatus.DOWNLOADING_AUDIO: [JobStatus.DOWNLOADING, JobStatus.AWAITING_DURATION_CONFIRM, JobStatus.DOWNLOAD_PENDING_RETRY, JobStatus.FAILED],
|
||||
# DOWNLOAD_PENDING_RETRY = parked when a torrent download hits a transient
|
||||
# issue (few/no seeders, tracker outage); auto-retried by the recover-stuck
|
||||
# cron for up to 24h before failing permanently.
|
||||
JobStatus.DOWNLOAD_PENDING_RETRY: [JobStatus.DOWNLOADING_AUDIO, JobStatus.FAILED, JobStatus.CANCELLED],
|
||||
|
||||
# DOWNLOADING allows parallel processing (audio + lyrics) and then screens when both complete
|
||||
# Can also enter optional audio edit phase if requires_audio_edit flag is set
|
||||
|
||||
@@ -27,6 +27,7 @@ Usage:
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, UTC
|
||||
from typing import Any, Optional
|
||||
@@ -48,7 +49,35 @@ logger = logging.getLogger(__name__)
|
||||
# or returned an immediate error like ZONE_RESOURCE_POOL_EXHAUSTED.
|
||||
START_OPERATION_TIMEOUT_SECONDS = 30.0
|
||||
|
||||
# A GCE instances.start returning 503 SERVICE_UNAVAILABLE (or 500/INTERNAL) is a
|
||||
# transient GCP control-plane error — distinct from a capacity STOCKOUT — and
|
||||
# usually succeeds on a quick retry. Retry the start a few times in-zone with
|
||||
# backoff before letting the caller fail over to another zone.
|
||||
START_TRANSIENT_MAX_RETRIES = 3
|
||||
START_TRANSIENT_BACKOFF_SECONDS = 5.0
|
||||
# Substrings (matched case-insensitively against the GCE error code/message)
|
||||
# that mark a retryable transient control-plane failure.
|
||||
_TRANSIENT_START_MARKERS = (
|
||||
"503",
|
||||
"service unavailable",
|
||||
"internal error",
|
||||
"internalerror",
|
||||
"backenderror",
|
||||
"500",
|
||||
)
|
||||
|
||||
CONFIG_COLLECTION = "config"
|
||||
|
||||
|
||||
def _is_transient_start_error(error: "EncodingWorkerStartError") -> bool:
|
||||
"""True if a VM-start failure looks like a retryable transient GCP error.
|
||||
|
||||
Capacity errors (ZONE_RESOURCE_POOL_EXHAUSTED etc.) are NOT transient in the
|
||||
same zone — retrying in-zone is pointless, the caller should fail over. Those
|
||||
are a distinct subclass and are excluded by the caller.
|
||||
"""
|
||||
haystack = f"{getattr(error, 'code', '') or ''} {error}".lower()
|
||||
return any(marker in haystack for marker in _TRANSIENT_START_MARKERS)
|
||||
CONFIG_DOCUMENT = "encoding-worker"
|
||||
ENCODING_WORKER_PORT = 8080
|
||||
|
||||
@@ -322,6 +351,38 @@ class EncodingWorkerManager:
|
||||
}
|
||||
|
||||
def ensure_any_running(self, candidates: list) -> dict:
|
||||
"""Start any candidate VM; retry the whole set on an all-zones transient blip.
|
||||
|
||||
Delegates to :meth:`_ensure_any_running_once` (one attempt per candidate).
|
||||
If EVERY candidate fails with a *transient* error — e.g. a brief 503
|
||||
SERVICE_UNAVAILABLE control-plane blip that hits all zones at once — and
|
||||
none hit real capacity exhaustion, retry the whole candidate set a few
|
||||
times with backoff before giving up. Capacity exhaustion is NOT spun on
|
||||
here (retrying in seconds won't conjure hardware); the render worker parks
|
||||
the job and the 24h auto-retry cron handles a sustained shortage.
|
||||
"""
|
||||
if not candidates:
|
||||
raise ValueError("ensure_any_running requires at least one candidate")
|
||||
attempt = 0
|
||||
while True:
|
||||
attempt += 1
|
||||
try:
|
||||
return self._ensure_any_running_once(candidates)
|
||||
except EncodingWorkerCapacityError:
|
||||
raise
|
||||
except EncodingWorkerStartError as e:
|
||||
if attempt <= START_TRANSIENT_MAX_RETRIES and _is_transient_start_error(e):
|
||||
backoff = START_TRANSIENT_BACKOFF_SECONDS * attempt
|
||||
logger.warning(
|
||||
"All encoding candidates failed transiently (pass %d/%d): %s — "
|
||||
"retrying whole set in %.0fs",
|
||||
attempt, START_TRANSIENT_MAX_RETRIES + 1, e, backoff,
|
||||
)
|
||||
time.sleep(backoff)
|
||||
continue
|
||||
raise
|
||||
|
||||
def _ensure_any_running_once(self, candidates: list) -> dict:
|
||||
"""Start the first candidate VM that GCE accepts; raise if all are exhausted.
|
||||
|
||||
Iterates `candidates` in order, attempting to start each one. A
|
||||
@@ -359,6 +420,7 @@ class EncodingWorkerManager:
|
||||
# capacity exhaustion (transient, retry on a different VM/zone helps).
|
||||
last_capacity_error: Optional[EncodingWorkerCapacityError] = None
|
||||
last_start_error: Optional[EncodingWorkerStartError] = None
|
||||
last_non_transient_error: Optional[EncodingWorkerStartError] = None
|
||||
for index, candidate in enumerate(candidates):
|
||||
try:
|
||||
status = self.get_vm_status(candidate.vm_name, zone=candidate.zone)
|
||||
@@ -405,12 +467,21 @@ class EncodingWorkerManager:
|
||||
candidate.vm_name, candidate.zone, start_err.code or "no-code",
|
||||
)
|
||||
last_start_error = start_err
|
||||
if not _is_transient_start_error(start_err):
|
||||
last_non_transient_error = start_err
|
||||
continue
|
||||
|
||||
# Every candidate failed. Prefer raising the capacity error if any
|
||||
# candidate hit one (more actionable for the caller / user message).
|
||||
# Every candidate failed. Raise the most actionable / least-retryable
|
||||
# representative error so the caller (ensure_any_running) retries the
|
||||
# whole set ONLY when every failure was a transient blip:
|
||||
# capacity > non-transient start error > transient start error
|
||||
# A capacity error means a real shortage (park + 24h retry handles it);
|
||||
# a non-transient error (e.g. PERMISSION_DENIED) means something is
|
||||
# actually broken — neither should trigger the fast whole-set retry.
|
||||
if last_capacity_error is not None:
|
||||
raise last_capacity_error
|
||||
if last_non_transient_error is not None:
|
||||
raise last_non_transient_error
|
||||
assert last_start_error is not None
|
||||
raise last_start_error
|
||||
|
||||
|
||||
@@ -16,6 +16,15 @@ from backend.models.job import Job, JobStatus
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# A render that started (status=rendering_video) but whose worker died mid-way
|
||||
# (Cloud Run instance recycle / SIGKILL / lost GCE VM) stops advancing
|
||||
# updated_at. The render worker's own timeout is ~1h, so if a job sits here far
|
||||
# longer than that with no update, no live worker is driving it — it's orphaned
|
||||
# and must be re-parked for retry. Kept above the worst-case gap between render
|
||||
# progress callbacks to avoid re-parking a slow-but-alive render.
|
||||
RENDERING_VIDEO_STUCK_MINUTES = 45
|
||||
|
||||
|
||||
# Jobs in these statuses should NOT have audio_complete flag set
|
||||
# (unless they're actively processing or beyond)
|
||||
STATUSES_BEFORE_AUDIO_START = {
|
||||
@@ -141,6 +150,24 @@ def check_job_consistency(job: Job) -> List[str]:
|
||||
f"downloading_audio_stuck: status=downloading_audio for {minutes} min without update (updated_at={updated_at.isoformat()})"
|
||||
)
|
||||
|
||||
# Check: job stuck in rendering_video status with no progress.
|
||||
# If the render worker died mid-render (hard kill / lost VM), updated_at
|
||||
# stops advancing and NO existing mechanism recovers it: the capacity-retry
|
||||
# cron only looks at render_pending_capacity, recover-stuck-jobs only looked
|
||||
# at downloading_audio, and the render Cloud Task has finite attempts. This
|
||||
# detects that orphan so the recovery sweep can re-park it for auto-retry.
|
||||
if status == JobStatus.RENDERING_VIDEO and job.updated_at:
|
||||
now = datetime.now(timezone.utc)
|
||||
updated_at = job.updated_at
|
||||
if updated_at.tzinfo is None:
|
||||
updated_at = updated_at.replace(tzinfo=timezone.utc)
|
||||
render_age = now - updated_at
|
||||
if render_age > timedelta(minutes=RENDERING_VIDEO_STUCK_MINUTES):
|
||||
minutes = int(render_age.total_seconds() / 60)
|
||||
issues.append(
|
||||
f"rendering_video_stuck: status=rendering_video for {minutes} min without update (updated_at={updated_at.isoformat()})"
|
||||
)
|
||||
|
||||
return issues
|
||||
|
||||
|
||||
|
||||
@@ -260,6 +260,16 @@ class TestVMLifecycle:
|
||||
manager.start_vm("encoding-worker-blue")
|
||||
mock_compute.start.assert_not_called()
|
||||
|
||||
def test_is_transient_start_error_classification(self):
|
||||
from backend.services.encoding_worker_manager import _is_transient_start_error
|
||||
from backend.services.encoding_errors import EncodingWorkerStartError
|
||||
assert _is_transient_start_error(
|
||||
EncodingWorkerStartError("VM x start failed: 503 — SERVICE UNAVAILABLE", code="503")
|
||||
)
|
||||
assert not _is_transient_start_error(
|
||||
EncodingWorkerStartError("VM x start failed: PERMISSION_DENIED", code="PERMISSION_DENIED")
|
||||
)
|
||||
|
||||
def test_stop_vm_calls_compute_stop(self, manager, mock_compute):
|
||||
mock_instance = MagicMock()
|
||||
mock_instance.status = "RUNNING"
|
||||
@@ -588,22 +598,101 @@ class TestEnsureAnyRunning:
|
||||
mock_instance.status = "TERMINATED"
|
||||
mock_compute.get.return_value = mock_instance
|
||||
|
||||
op_503 = MagicMock()
|
||||
op_503.error_code = "503"
|
||||
op_503.error_message = "SERVICE UNAVAILABLE"
|
||||
op_503.result.return_value = None
|
||||
mock_compute.start.side_effect = [op_503, op_503]
|
||||
def _op_503():
|
||||
op = MagicMock()
|
||||
op.error_code = "503"
|
||||
op.error_message = "SERVICE UNAVAILABLE"
|
||||
op.result.return_value = None
|
||||
return op
|
||||
|
||||
# All-transient: the whole candidate set is retried a few times before
|
||||
# giving up, so provide enough operations for every pass.
|
||||
mock_compute.start.side_effect = [_op_503() for _ in range(20)]
|
||||
|
||||
candidates = [
|
||||
EncodingWorkerCandidate(vm_name="primary", zone="us-central1-c", ip="10.0.0.1"),
|
||||
EncodingWorkerCandidate(vm_name="fb-a", zone="us-central1-a", ip="10.0.0.2"),
|
||||
]
|
||||
|
||||
with pytest.raises(EncodingWorkerStartError) as exc_info:
|
||||
manager.ensure_any_running(candidates)
|
||||
with patch("backend.services.encoding_worker_manager.time.sleep") as sleep:
|
||||
with pytest.raises(EncodingWorkerStartError) as exc_info:
|
||||
manager.ensure_any_running(candidates)
|
||||
# Should NOT be a capacity error — there were none in this scenario.
|
||||
assert not isinstance(exc_info.value, EncodingWorkerCapacityError)
|
||||
assert mock_compute.start.call_count == 2
|
||||
# Retried the whole 2-candidate set across multiple passes before failing.
|
||||
assert mock_compute.start.call_count > 2
|
||||
assert sleep.called
|
||||
|
||||
def test_retries_whole_set_on_all_transient_then_succeeds(self, manager, mock_db, mock_compute):
|
||||
"""A brief all-zones 503 blip: first pass fails everywhere, retry succeeds."""
|
||||
mock_instance = MagicMock()
|
||||
mock_instance.status = "TERMINATED"
|
||||
mock_compute.get.return_value = mock_instance
|
||||
|
||||
def _op_503():
|
||||
op = MagicMock(); op.error_code = "503"; op.error_message = "SERVICE UNAVAILABLE"
|
||||
op.result.return_value = None
|
||||
return op
|
||||
|
||||
# Pass 1: both candidates 503. Pass 2: primary succeeds.
|
||||
mock_compute.start.side_effect = [_op_503(), _op_503(), _ok_op()]
|
||||
candidates = [
|
||||
EncodingWorkerCandidate(vm_name="primary", zone="us-central1-c", ip="10.0.0.1"),
|
||||
EncodingWorkerCandidate(vm_name="fb-a", zone="us-central1-a", ip="10.0.0.2"),
|
||||
]
|
||||
with patch("backend.services.encoding_worker_manager.time.sleep") as sleep, \
|
||||
patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
|
||||
mock_dt.now.return_value = datetime(2026, 5, 6, 17, 0, 0, tzinfo=UTC)
|
||||
mock_dt.side_effect = lambda *a, **kw: datetime(*a, **kw)
|
||||
result = manager.ensure_any_running(candidates)
|
||||
assert result["vm_name"] == "primary"
|
||||
assert result["fell_back"] is False
|
||||
assert mock_compute.start.call_count == 3
|
||||
sleep.assert_called_once()
|
||||
|
||||
def test_does_not_retry_whole_set_on_mixed_nontransient(self, manager, mock_db, mock_compute):
|
||||
"""If any candidate fails non-transiently (PERMISSION_DENIED), do NOT retry
|
||||
the whole set even though the last failure was a transient 503."""
|
||||
from backend.services.encoding_errors import EncodingWorkerStartError
|
||||
mock_instance = MagicMock()
|
||||
mock_instance.status = "TERMINATED"
|
||||
mock_compute.get.return_value = mock_instance
|
||||
|
||||
op_perm = MagicMock()
|
||||
op_perm.error_code = "PERMISSION_DENIED"; op_perm.error_message = "denied"
|
||||
op_perm.result.return_value = None
|
||||
op_503 = MagicMock()
|
||||
op_503.error_code = "503"; op_503.error_message = "SERVICE UNAVAILABLE"
|
||||
op_503.result.return_value = None
|
||||
# primary: PERMISSION_DENIED (non-transient); fallback: 503 (transient/last)
|
||||
mock_compute.start.side_effect = [op_perm, op_503]
|
||||
candidates = [
|
||||
EncodingWorkerCandidate(vm_name="primary", zone="us-central1-c", ip="10.0.0.1"),
|
||||
EncodingWorkerCandidate(vm_name="fb-a", zone="us-central1-a", ip="10.0.0.2"),
|
||||
]
|
||||
with patch("backend.services.encoding_worker_manager.time.sleep") as sleep:
|
||||
with pytest.raises(EncodingWorkerStartError) as exc:
|
||||
manager.ensure_any_running(candidates)
|
||||
assert exc.value.code == "PERMISSION_DENIED" # non-transient surfaced
|
||||
assert mock_compute.start.call_count == 2 # one pass only
|
||||
sleep.assert_not_called()
|
||||
|
||||
def test_does_not_retry_whole_set_on_capacity(self, manager, mock_db, mock_compute):
|
||||
"""Capacity exhaustion is not spun on — it raises immediately for the park path."""
|
||||
from backend.services.encoding_errors import EncodingWorkerCapacityError
|
||||
mock_instance = MagicMock()
|
||||
mock_instance.status = "TERMINATED"
|
||||
mock_compute.get.return_value = mock_instance
|
||||
mock_compute.start.side_effect = [_capacity_op(), _capacity_op()]
|
||||
candidates = [
|
||||
EncodingWorkerCandidate(vm_name="primary", zone="us-central1-c", ip="10.0.0.1"),
|
||||
EncodingWorkerCandidate(vm_name="fb-a", zone="us-central1-a", ip="10.0.0.2"),
|
||||
]
|
||||
with patch("backend.services.encoding_worker_manager.time.sleep") as sleep:
|
||||
with pytest.raises(EncodingWorkerCapacityError):
|
||||
manager.ensure_any_running(candidates)
|
||||
assert mock_compute.start.call_count == 2 # one pass only, no whole-set retry
|
||||
sleep.assert_not_called()
|
||||
|
||||
def test_prefers_capacity_error_when_mixed_failures(self, manager, mock_db, mock_compute):
|
||||
"""When some candidates hit capacity and others hit generic errors, prefer raising
|
||||
|
||||
@@ -202,6 +202,36 @@ class TestCheckJobConsistency:
|
||||
issues = check_job_consistency(job)
|
||||
assert not any("downloading_audio_stuck" in i for i in issues)
|
||||
|
||||
def test_rendering_video_recently_updated_not_flagged(self):
|
||||
"""A render that updated 20 min ago (< 45) should not be flagged."""
|
||||
job = create_test_job(status=JobStatus.RENDERING_VIDEO)
|
||||
job.updated_at = datetime.now(timezone.utc) - timedelta(minutes=20)
|
||||
issues = check_job_consistency(job)
|
||||
assert not any("rendering_video_stuck" in i for i in issues)
|
||||
|
||||
def test_rendering_video_stuck_60_min_flagged(self):
|
||||
"""A render with no update for 60 min (worker died) should be flagged."""
|
||||
job = create_test_job(status=JobStatus.RENDERING_VIDEO)
|
||||
job.updated_at = datetime.now(timezone.utc) - timedelta(minutes=60)
|
||||
issues = check_job_consistency(job)
|
||||
assert any("rendering_video_stuck" in i for i in issues)
|
||||
stuck_issue = [i for i in issues if "rendering_video_stuck" in i][0]
|
||||
assert "60 min" in stuck_issue
|
||||
|
||||
def test_rendering_video_at_44_min_not_flagged(self):
|
||||
"""At 44 min it must not flag yet (threshold is 45)."""
|
||||
job = create_test_job(status=JobStatus.RENDERING_VIDEO)
|
||||
job.updated_at = datetime.now(timezone.utc) - timedelta(minutes=44)
|
||||
issues = check_job_consistency(job)
|
||||
assert not any("rendering_video_stuck" in i for i in issues)
|
||||
|
||||
def test_rendering_video_stuck_with_naive_datetime(self):
|
||||
"""rendering_video_stuck handles naive datetime (no tzinfo)."""
|
||||
job = create_test_job(status=JobStatus.RENDERING_VIDEO)
|
||||
job.updated_at = datetime.utcnow() - timedelta(minutes=50)
|
||||
issues = check_job_consistency(job)
|
||||
assert any("rendering_video_stuck" in i for i in issues)
|
||||
|
||||
|
||||
class TestCheckJobConsistencyDetailed:
|
||||
"""Tests for check_job_consistency_detailed function."""
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
"""Tests for POST /api/internal/recover-stuck-jobs resilience paths.
|
||||
|
||||
Covers the three recovery behaviours the endpoint drives every 5 min:
|
||||
1. Stuck torrent downloads (RED/OPS) → parked into DOWNLOAD_PENDING_RETRY and
|
||||
re-tried for up to 24h (rare tracks / intermittent seeders / tracker blips).
|
||||
2. Parked downloads → re-triggered, or permanently failed after 24h.
|
||||
3. Orphaned renders stuck at RENDERING_VIDEO → re-parked into
|
||||
RENDER_PENDING_CAPACITY so the existing retry cron resumes them.
|
||||
"""
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from backend.api.dependencies import require_admin
|
||||
from backend.main import app
|
||||
from backend.models.job import Job, JobStatus
|
||||
from backend.services.auth_service import AuthResult, UserType
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
async def fake_admin():
|
||||
return AuthResult(
|
||||
is_valid=True, user_type=UserType.ADMIN, remaining_uses=999,
|
||||
message="test admin", is_admin=True, user_email="test@example.com",
|
||||
)
|
||||
|
||||
app.dependency_overrides[require_admin] = fake_admin
|
||||
try:
|
||||
yield TestClient(app)
|
||||
finally:
|
||||
app.dependency_overrides.pop(require_admin, None)
|
||||
|
||||
|
||||
def _doc(job_id, status):
|
||||
doc = MagicMock()
|
||||
doc.id = job_id
|
||||
doc.to_dict.return_value = {"job_id": job_id, "status": status.value}
|
||||
return doc
|
||||
|
||||
|
||||
def _job(job_id, status, *, minutes_stale=0, source_name=None, download_retry=None):
|
||||
sd = {}
|
||||
if download_retry is not None:
|
||||
sd["download_retry"] = download_retry
|
||||
return Job(
|
||||
job_id=job_id, artist="A", title="B", status=status,
|
||||
created_at=datetime.now(timezone.utc) - timedelta(hours=2),
|
||||
updated_at=datetime.now(timezone.utc) - timedelta(minutes=minutes_stale),
|
||||
state_data=sd, source_name=source_name, audio_source_type="audio_search",
|
||||
source_id="123",
|
||||
)
|
||||
|
||||
|
||||
def _mock_jm(*, downloading=None, pending=None, rendering=None, jobs=None):
|
||||
"""Wire a JobManager mock for the endpoint's 3 status queries.
|
||||
|
||||
downloading/rendering use .where().stream(); pending uses .where().limit().stream().
|
||||
`jobs` maps job_id -> Job returned by get_job().
|
||||
"""
|
||||
mock_jm = MagicMock()
|
||||
where = mock_jm.firestore.db.collection.return_value.where.return_value
|
||||
# Two non-limited .stream() calls in order: downloading_audio, rendering_video
|
||||
where.stream.side_effect = [iter(downloading or []), iter(rendering or [])]
|
||||
# One .limit().stream() call: download_pending_retry
|
||||
where.limit.return_value.stream.return_value = iter(pending or [])
|
||||
mock_jm.get_job.side_effect = lambda jid: (jobs or {}).get(jid)
|
||||
mock_jm.transition_to_state.return_value = True
|
||||
return mock_jm
|
||||
|
||||
|
||||
def _run(client, mock_jm):
|
||||
mock_ws = MagicMock()
|
||||
mock_ws.trigger_audio_download_worker = AsyncMock(return_value=True)
|
||||
with patch("backend.api.routes.internal.JobManager", return_value=mock_jm), \
|
||||
patch("backend.services.worker_service.get_worker_service", return_value=mock_ws):
|
||||
resp = client.post("/api/internal/recover-stuck-jobs")
|
||||
return resp, mock_ws
|
||||
|
||||
|
||||
def test_stuck_torrent_download_is_parked(client):
|
||||
"""A stuck RED download is parked into DOWNLOAD_PENDING_RETRY, not failed."""
|
||||
job = _job("dl1", JobStatus.DOWNLOADING_AUDIO, minutes_stale=15, source_name="RED")
|
||||
mock_jm = _mock_jm(downloading=[_doc("dl1", JobStatus.DOWNLOADING_AUDIO)], jobs={"dl1": job})
|
||||
resp, _ = _run(client, mock_jm)
|
||||
data = resp.json()
|
||||
assert data["download_parked_jobs"] == ["dl1"]
|
||||
assert data["recovered_count"] == 0
|
||||
assert mock_jm.transition_to_state.call_args.kwargs["new_status"] == JobStatus.DOWNLOAD_PENDING_RETRY
|
||||
mock_jm.fail_job.assert_not_called()
|
||||
|
||||
|
||||
def test_stuck_nontorrent_download_is_failed(client):
|
||||
"""A stuck YouTube download still fails (deterministic source, no auto-retry)."""
|
||||
job = _job("dl2", JobStatus.DOWNLOADING_AUDIO, minutes_stale=15, source_name="YouTube")
|
||||
mock_jm = _mock_jm(downloading=[_doc("dl2", JobStatus.DOWNLOADING_AUDIO)], jobs={"dl2": job})
|
||||
resp, _ = _run(client, mock_jm)
|
||||
data = resp.json()
|
||||
assert data["recovered_jobs"] == ["dl2"]
|
||||
assert data["download_parked_jobs"] == []
|
||||
mock_jm.fail_job.assert_called_once()
|
||||
|
||||
|
||||
def test_parked_download_is_retriggered(client):
|
||||
"""A parked download within 24h is re-triggered."""
|
||||
job = _job("dl3", JobStatus.DOWNLOAD_PENDING_RETRY,
|
||||
download_retry={"first_seen_at": (datetime.now(timezone.utc) - timedelta(hours=2)).isoformat(),
|
||||
"attempt_count": 3})
|
||||
mock_jm = _mock_jm(pending=[_doc("dl3", JobStatus.DOWNLOAD_PENDING_RETRY)], jobs={"dl3": job})
|
||||
resp, mock_ws = _run(client, mock_jm)
|
||||
data = resp.json()
|
||||
assert data["download_retried_jobs"] == ["dl3"]
|
||||
mock_ws.trigger_audio_download_worker.assert_awaited_once_with("dl3")
|
||||
|
||||
|
||||
def test_parked_download_retry_cap_counts_failed_dispatches(client):
|
||||
"""Dispatch attempts count against the per-tick cap even when the audio
|
||||
worker trigger fails, so an outage can't fan out to every queried job."""
|
||||
import backend.api.routes.internal as mod
|
||||
|
||||
fresh = (datetime.now(timezone.utc) - timedelta(hours=1)).isoformat()
|
||||
n = mod.DOWNLOAD_RETRIES_PER_TICK + 5
|
||||
docs = [_doc(f"p{i}", JobStatus.DOWNLOAD_PENDING_RETRY) for i in range(n)]
|
||||
jobs = {f"p{i}": _job(f"p{i}", JobStatus.DOWNLOAD_PENDING_RETRY,
|
||||
download_retry={"first_seen_at": fresh, "attempt_count": 1})
|
||||
for i in range(n)}
|
||||
mock_jm = _mock_jm(pending=docs, jobs=jobs)
|
||||
|
||||
mock_ws = MagicMock()
|
||||
# Every dispatch raises → helper returns False, but attempts must still be capped.
|
||||
mock_ws.trigger_audio_download_worker = AsyncMock(side_effect=RuntimeError("audio worker down"))
|
||||
with patch("backend.api.routes.internal.JobManager", return_value=mock_jm), \
|
||||
patch("backend.services.worker_service.get_worker_service", return_value=mock_ws):
|
||||
resp = client.post("/api/internal/recover-stuck-jobs")
|
||||
|
||||
assert resp.status_code == 200
|
||||
# No more than the per-tick cap of dispatch attempts, despite n>cap parked jobs.
|
||||
assert mock_ws.trigger_audio_download_worker.await_count == mod.DOWNLOAD_RETRIES_PER_TICK
|
||||
assert resp.json()["download_retried_jobs"] == [] # all dispatches failed
|
||||
|
||||
|
||||
def test_parked_download_times_out_after_24h(client):
|
||||
"""A parked download older than 24h is permanently failed."""
|
||||
job = _job("dl4", JobStatus.DOWNLOAD_PENDING_RETRY,
|
||||
download_retry={"first_seen_at": (datetime.now(timezone.utc) - timedelta(hours=25)).isoformat(),
|
||||
"attempt_count": 40})
|
||||
mock_jm = _mock_jm(pending=[_doc("dl4", JobStatus.DOWNLOAD_PENDING_RETRY)], jobs={"dl4": job})
|
||||
resp, mock_ws = _run(client, mock_jm)
|
||||
data = resp.json()
|
||||
assert data["download_timed_out_jobs"] == ["dl4"]
|
||||
assert data["download_retried_jobs"] == []
|
||||
mock_jm.fail_job.assert_called_once()
|
||||
mock_ws.trigger_audio_download_worker.assert_not_awaited()
|
||||
|
||||
|
||||
def test_orphaned_render_is_reparked(client):
|
||||
"""A render stale >45 min is re-parked into RENDER_PENDING_CAPACITY."""
|
||||
job = _job("r1", JobStatus.RENDERING_VIDEO, minutes_stale=60)
|
||||
mock_jm = _mock_jm(rendering=[_doc("r1", JobStatus.RENDERING_VIDEO)], jobs={"r1": job})
|
||||
resp, _ = _run(client, mock_jm)
|
||||
data = resp.json()
|
||||
assert data["reparked_render_jobs"] == ["r1"]
|
||||
assert mock_jm.transition_to_state.call_args.kwargs["new_status"] == JobStatus.RENDER_PENDING_CAPACITY
|
||||
meta = mock_jm.update_state_data.call_args.args[2]
|
||||
assert meta["last_code"] == "render_stalled"
|
||||
|
||||
|
||||
def test_fresh_render_not_reparked(client):
|
||||
"""A render updated 10 min ago is NOT re-parked."""
|
||||
job = _job("r2", JobStatus.RENDERING_VIDEO, minutes_stale=10)
|
||||
mock_jm = _mock_jm(rendering=[_doc("r2", JobStatus.RENDERING_VIDEO)], jobs={"r2": job})
|
||||
resp, _ = _run(client, mock_jm)
|
||||
assert resp.json()["reparked_render_count"] == 0
|
||||
mock_jm.transition_to_state.assert_not_called()
|
||||
+24
-2
@@ -8,7 +8,9 @@ Operational runbooks for known production issues.
|
||||
|
||||
**Cause:** Before v0.130.0, audio downloads ran as FastAPI BackgroundTasks. Cloud Run would terminate "idle" instances mid-download. Since v0.130.0, downloads use a Cloud Run Job (`audio-download-job`) and a Cloud Scheduler recovery job runs every 5 minutes to fail stuck downloads automatically.
|
||||
|
||||
**Auto-recovery:** The `recover-stuck-downloads` scheduler detects jobs stuck in `downloading_audio` for >10 minutes and fails them. Use the admin retry button to re-attempt.
|
||||
**Auto-recovery:** The `recover-stuck-downloads` scheduler (`/api/internal/recover-stuck-jobs`, every 5 min) detects jobs stuck in `downloading_audio` for >10 minutes and, since v0.192.3:
|
||||
- **Torrent sources (RED/OPS)** → parks the job in `download_pending_retry` and keeps re-attempting the download for up to **24 hours** (handles rare tracks with few/intermittent seeders and transient tracker outages), then fails permanently with a clear message. No manual action needed. See `download_pending_retry` below.
|
||||
- **Other sources (YouTube/Spotify/URL)** → fails the job (deterministic); use the admin retry button to re-attempt.
|
||||
|
||||
**Manual recovery:**
|
||||
|
||||
@@ -195,9 +197,29 @@ gcloud compute instances describe encoding-worker-a \
|
||||
|
||||
---
|
||||
|
||||
## Job stuck at `rendering_video` (orphaned render)
|
||||
|
||||
**Symptoms:** Job frozen at `rendering_video` (step 7/10) for a long time with **no error** and **no Retry button** (it's a processing state, not `failed`).
|
||||
|
||||
**Cause:** The render worker started (VM up, rendering underway) then died mid-render — Cloud Run instance recycle / SIGKILL / OOM / lost GCE VM — without unregistering. `updated_at` stops advancing. Before v0.192.3 nothing recovered this: the capacity-retry cron only looks at `render_pending_capacity`, `recover-stuck-jobs` only looked at `downloading_audio`, and the render Cloud Task has finite attempts.
|
||||
|
||||
**Auto-recovery (v0.192.3+):** `recover-stuck-jobs` (every 5 min) now flags a job in `rendering_video` with no progress for **>45 min** (`rendering_video_stuck`) and re-parks it into `render_pending_capacity`, so the existing `retry-pending-render-jobs` cron resets it to `review_complete` and re-renders (same 24h ceiling). No manual action needed.
|
||||
|
||||
**Manual unstick (if needed):** don't re-trigger the render worker while status is `rendering_video` (it starts mid-state and fails with "Invalid state transition"). Instead let it fail (or re-park it), then use the admin **Retry** which resumes cleanly from `review_complete`. If a ghost `render_progress.stage='running'` blocks re-trigger, clear it first (`update({'state_data.render_progress': {'stage': 'pending'}})`).
|
||||
|
||||
---
|
||||
|
||||
## Job in `download_pending_retry`
|
||||
|
||||
**Symptoms:** Job status is `download_pending_retry` (introduced v0.192.3), step 3/10, message *"Still finding a good source for this track — … We'll keep trying automatically for up to 24 hours; no action needed."*
|
||||
|
||||
**Background:** A **torrent** (RED/OPS) download stalled (few/no seeders or a brief tracker outage). Rather than dead-end the job at `failed` after ~1h, `recover-stuck-jobs` parks it here and re-triggers the download on later ticks for up to **24h**, then fails permanently with a "too rare to source right now" message. This is expected, self-healing behaviour — a seedless release simply may never complete. `state_data.download_retry` holds `{first_seen_at, attempt_count}`. To source it a different way, retry with an alternate release/source.
|
||||
|
||||
---
|
||||
|
||||
## Job stuck in `render_pending_capacity`
|
||||
|
||||
**Symptoms:** Job status is `render_pending_capacity` (introduced 2026-05-05). User-facing message says *"Encoding capacity is temporarily unavailable. Your job will retry automatically — no action needed."*
|
||||
**Symptoms:** Job status is `render_pending_capacity` (introduced 2026-05-05). User-facing message says *"Encoding capacity is temporarily unavailable. Your job will retry automatically — no action needed."* (As of v0.192.3 a mid-render stall can also land here — see "orphaned render" above.)
|
||||
|
||||
**Background — what this state means:** GCE returned `ZONE_RESOURCE_POOL_EXHAUSTED` or transient `503 SERVICE_UNAVAILABLE` from `compute.instances.start` on every encoding-worker VM (primary in `us-central1-c`, plus capacity fallbacks in `-a` and `-b`). The render worker parks the job in `RENDER_PENDING_CAPACITY` instead of failing it; Cloud Scheduler retries it every 5 min via `/api/internal/retry-pending-render-jobs`. Hard timeout is 24 hours (then transitions to `failed` with a clear permanent-failure message).
|
||||
|
||||
|
||||
@@ -62,6 +62,9 @@ export const STATUS_CONFIG: Record<
|
||||
|
||||
// Step 3: Download
|
||||
downloading_audio: { step: 3, label: "downloadingAudio", isBlocking: false, color: "text-blue-400" },
|
||||
// Transient torrent-download issue (rare track / few seeders / tracker blip);
|
||||
// auto-retried for up to 24h by the recover-stuck cron. Not blocking — no user action.
|
||||
download_pending_retry: { step: 3, label: "findingAudioSources", isBlocking: false, color: "text-amber-400" },
|
||||
downloading: { step: 3, label: "downloading", isBlocking: false, color: "text-blue-400" },
|
||||
|
||||
// Step 3.5: Audio Editing (optional, BLOCKING)
|
||||
@@ -91,6 +94,9 @@ export const STATUS_CONFIG: Record<
|
||||
// Step 7: Video Rendering
|
||||
review_complete: { step: 7, label: "startingRender", isBlocking: false, color: "text-teal-400" },
|
||||
rendering_video: { step: 7, label: "renderingVideo", isBlocking: false, color: "text-indigo-400" },
|
||||
// Parked waiting for GCE encoding capacity (or re-parked after a mid-render
|
||||
// stall); auto-retried by the scheduler. Not blocking — no user action.
|
||||
render_pending_capacity: { step: 7, label: "waitingForCapacity", isBlocking: false, color: "text-amber-400" },
|
||||
|
||||
// Step 8: Instrumental Selection (BLOCKING - requires user action)
|
||||
awaiting_instrumental_selection: { step: 8, label: "selectInstrumental", isBlocking: true, color: "text-amber-400" },
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "جاري التصحيح",
|
||||
"lyricsDone": "اكتملت الكلمات",
|
||||
"lyrics": "الكلمات",
|
||||
"confirmDurationCost": "تأكيد التكلفة"
|
||||
"confirmDurationCost": "تأكيد التكلفة",
|
||||
"findingAudioSources": "جارٍ البحث عن مصادر الصوت (إعادة المحاولة)",
|
||||
"waitingForCapacity": "في انتظار توفر السعة (إعادة المحاولة)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "إجراء مطلوب",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "Corregint",
|
||||
"lyricsDone": "Lletres fetes",
|
||||
"lyrics": "Lletres",
|
||||
"confirmDurationCost": "Confirma el cost"
|
||||
"confirmDurationCost": "Confirma el cost",
|
||||
"findingAudioSources": "Cercant fonts d'àudio (reintentant)",
|
||||
"waitingForCapacity": "Esperant disponibilitat (reintentant)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Acció necessària",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "Opravování",
|
||||
"lyricsDone": "Text hotov",
|
||||
"lyrics": "Text",
|
||||
"confirmDurationCost": "Potvrdit cenu"
|
||||
"confirmDurationCost": "Potvrdit cenu",
|
||||
"findingAudioSources": "Hledání zdrojů zvuku (opakování pokusu)",
|
||||
"waitingForCapacity": "Čekání na volnou kapacitu (opakování pokusu)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Vyžadována akce",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "Retter",
|
||||
"lyricsDone": "Sangtekster færdige",
|
||||
"lyrics": "Sangtekster",
|
||||
"confirmDurationCost": "Bekræft pris"
|
||||
"confirmDurationCost": "Bekræft pris",
|
||||
"findingAudioSources": "Finder lydkilder (prøver igen)",
|
||||
"waitingForCapacity": "Venter på kapacitet (prøver igen)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Handling påkrævet",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "Korrigiere",
|
||||
"lyricsDone": "Text fertig",
|
||||
"lyrics": "Text",
|
||||
"confirmDurationCost": "Kosten bestätigen"
|
||||
"confirmDurationCost": "Kosten bestätigen",
|
||||
"findingAudioSources": "Suche nach Audioquellen (erneuter Versuch)",
|
||||
"waitingForCapacity": "Warten auf Kapazität (erneuter Versuch)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Aktion erforderlich",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "Διόρθωση",
|
||||
"lyricsDone": "Οι στίχοι ολοκληρώθηκαν",
|
||||
"lyrics": "Στίχοι",
|
||||
"confirmDurationCost": "Επιβεβαίωση κόστους"
|
||||
"confirmDurationCost": "Επιβεβαίωση κόστους",
|
||||
"findingAudioSources": "Εύρεση πηγών ήχου (επαναπροσπάθεια)",
|
||||
"waitingForCapacity": "Αναμονή για διαθεσιμότητα (επαναπροσπάθεια)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Απαιτείται ενέργεια",
|
||||
|
||||
@@ -556,6 +556,8 @@
|
||||
"searchingForAudio": "Searching for audio",
|
||||
"selectAudioSource": "Select audio source",
|
||||
"downloadingAudio": "Downloading audio",
|
||||
"findingAudioSources": "Finding audio sources (retrying)",
|
||||
"waitingForCapacity": "Waiting for capacity (retrying)",
|
||||
"downloading": "Downloading",
|
||||
"editAudio": "Edit audio",
|
||||
"editingAudio": "Editing audio",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "Corrigiendo",
|
||||
"lyricsDone": "Letras terminadas",
|
||||
"lyrics": "Letras",
|
||||
"confirmDurationCost": "Confirmar costo"
|
||||
"confirmDurationCost": "Confirmar costo",
|
||||
"findingAudioSources": "Buscando fuentes de audio (reintentando)",
|
||||
"waitingForCapacity": "Esperando capacidad (reintentando)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Acción necesaria",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "Korjataan",
|
||||
"lyricsDone": "Sanoitukset valmiit",
|
||||
"lyrics": "Sanoitukset",
|
||||
"confirmDurationCost": "Vahvista hinta"
|
||||
"confirmDurationCost": "Vahvista hinta",
|
||||
"findingAudioSources": "Etsitään äänilähteitä (yritetään uudelleen)",
|
||||
"waitingForCapacity": "Odotetaan kapasiteettia (yritetään uudelleen)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Toimenpiteitä tarvitaan",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "Correction",
|
||||
"lyricsDone": "Paroles terminées",
|
||||
"lyrics": "Paroles",
|
||||
"confirmDurationCost": "Confirmer le coût"
|
||||
"confirmDurationCost": "Confirmer le coût",
|
||||
"findingAudioSources": "Recherche de sources audio (nouvelle tentative)",
|
||||
"waitingForCapacity": "En attente de disponibilité (nouvelle tentative)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Action requise",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "מתקן",
|
||||
"lyricsDone": "מילים הושלמו",
|
||||
"lyrics": "מילים",
|
||||
"confirmDurationCost": "אישור עלות"
|
||||
"confirmDurationCost": "אישור עלות",
|
||||
"findingAudioSources": "מחפש מקורות שמע (מנסה שוב)",
|
||||
"waitingForCapacity": "ממתין למשאבים פנויים (מנסה שוב)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "נדרשת פעולה",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "सही किया जा रहा है",
|
||||
"lyricsDone": "लिरिक्स हो गए",
|
||||
"lyrics": "लिरिक्स",
|
||||
"confirmDurationCost": "लागत की पुष्टि करो"
|
||||
"confirmDurationCost": "लागत की पुष्टि करो",
|
||||
"findingAudioSources": "ऑडियो स्रोत खोज रहे हैं (फिर से कोशिश कर रहे हैं)",
|
||||
"waitingForCapacity": "क्षमता का इंतज़ार कर रहे हैं (फिर से कोशिश कर रहे हैं)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "एक्शन की ज़रूरत है",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "Ispravljanje",
|
||||
"lyricsDone": "Tekst gotov",
|
||||
"lyrics": "Tekst",
|
||||
"confirmDurationCost": "Potvrdi cijenu"
|
||||
"confirmDurationCost": "Potvrdi cijenu",
|
||||
"findingAudioSources": "Traženje izvora zvuka (ponovni pokušaj)",
|
||||
"waitingForCapacity": "Čekanje na kapacitet (ponovni pokušaj)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Potrebna akcija",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "Javítás",
|
||||
"lyricsDone": "Dalszöveg kész",
|
||||
"lyrics": "Dalszöveg",
|
||||
"confirmDurationCost": "Költség megerősítése"
|
||||
"confirmDurationCost": "Költség megerősítése",
|
||||
"findingAudioSources": "Hangforrások keresése (újrapróbálkozás)",
|
||||
"waitingForCapacity": "Várakozás szabad kapacitásra (újrapróbálkozás)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Művelet szükséges",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "Memperbaiki",
|
||||
"lyricsDone": "Lirik selesai",
|
||||
"lyrics": "Lirik",
|
||||
"confirmDurationCost": "Konfirmasi biaya"
|
||||
"confirmDurationCost": "Konfirmasi biaya",
|
||||
"findingAudioSources": "Mencari sumber audio (mencoba lagi)",
|
||||
"waitingForCapacity": "Menunggu kapasitas (mencoba lagi)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Perlu tindakan",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "Correzione",
|
||||
"lyricsDone": "Testo completato",
|
||||
"lyrics": "Testo",
|
||||
"confirmDurationCost": "Conferma costo"
|
||||
"confirmDurationCost": "Conferma costo",
|
||||
"findingAudioSources": "Ricerca delle fonti audio (nuovo tentativo)",
|
||||
"waitingForCapacity": "In attesa di disponibilità (nuovo tentativo)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Azione richiesta",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "修正中",
|
||||
"lyricsDone": "歌詞完了",
|
||||
"lyrics": "歌詞",
|
||||
"confirmDurationCost": "料金を確認"
|
||||
"confirmDurationCost": "料金を確認",
|
||||
"findingAudioSources": "音源を検索中(再試行中)",
|
||||
"waitingForCapacity": "処理の空きを待機中(再試行中)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "アクションが必要です",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "수정 중",
|
||||
"lyricsDone": "가사 완료",
|
||||
"lyrics": "가사",
|
||||
"confirmDurationCost": "비용 확인"
|
||||
"confirmDurationCost": "비용 확인",
|
||||
"findingAudioSources": "오디오 소스 찾는 중 (재시도 중)",
|
||||
"waitingForCapacity": "처리 용량 대기 중 (재시도 중)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "조치 필요",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "Membetulkan",
|
||||
"lyricsDone": "Lirik selesai",
|
||||
"lyrics": "Lirik",
|
||||
"confirmDurationCost": "Sahkan kos"
|
||||
"confirmDurationCost": "Sahkan kos",
|
||||
"findingAudioSources": "Mencari sumber audio (mencuba semula)",
|
||||
"waitingForCapacity": "Menunggu kapasiti (mencuba semula)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Tindakan diperlukan",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "Korrigerer",
|
||||
"lyricsDone": "Tekst ferdig",
|
||||
"lyrics": "Tekst",
|
||||
"confirmDurationCost": "Bekreft pris"
|
||||
"confirmDurationCost": "Bekreft pris",
|
||||
"findingAudioSources": "Finner lydkilder (prøver på nytt)",
|
||||
"waitingForCapacity": "Venter på kapasitet (prøver på nytt)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Handling kreves",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "Corrigeren",
|
||||
"lyricsDone": "Songteksten klaar",
|
||||
"lyrics": "Songteksten",
|
||||
"confirmDurationCost": "Kosten bevestigen"
|
||||
"confirmDurationCost": "Kosten bevestigen",
|
||||
"findingAudioSources": "Audiobronnen zoeken (opnieuw proberen)",
|
||||
"waitingForCapacity": "Wachten op capaciteit (opnieuw proberen)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Actie vereist",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "Poprawianie",
|
||||
"lyricsDone": "Tekst gotowy",
|
||||
"lyrics": "Tekst",
|
||||
"confirmDurationCost": "Potwierdź koszt"
|
||||
"confirmDurationCost": "Potwierdź koszt",
|
||||
"findingAudioSources": "Wyszukiwanie źródeł audio (ponawianie)",
|
||||
"waitingForCapacity": "Oczekiwanie na wolne zasoby (ponawianie)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Wymagane działanie",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "Corrigindo",
|
||||
"lyricsDone": "Letras concluídas",
|
||||
"lyrics": "Letras",
|
||||
"confirmDurationCost": "Confirmar custo"
|
||||
"confirmDurationCost": "Confirmar custo",
|
||||
"findingAudioSources": "Buscando fontes de áudio (tentando novamente)",
|
||||
"waitingForCapacity": "Aguardando disponibilidade (tentando novamente)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Ação necessária",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "Se corectează",
|
||||
"lyricsDone": "Versuri terminate",
|
||||
"lyrics": "Versuri",
|
||||
"confirmDurationCost": "Confirmă costul"
|
||||
"confirmDurationCost": "Confirmă costul",
|
||||
"findingAudioSources": "Căutare surse audio (reîncercare)",
|
||||
"waitingForCapacity": "Așteptare resurse disponibile (reîncercare)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Acțiune necesară",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "Исправление",
|
||||
"lyricsDone": "Текст готов",
|
||||
"lyrics": "Текст",
|
||||
"confirmDurationCost": "Подтвердить стоимость"
|
||||
"confirmDurationCost": "Подтвердить стоимость",
|
||||
"findingAudioSources": "Поиск аудиоисточников (повторная попытка)",
|
||||
"waitingForCapacity": "Ожидание свободных ресурсов (повторная попытка)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Требуется действие",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "Opravuje sa",
|
||||
"lyricsDone": "Text hotový",
|
||||
"lyrics": "Text",
|
||||
"confirmDurationCost": "Potvrdiť cenu"
|
||||
"confirmDurationCost": "Potvrdiť cenu",
|
||||
"findingAudioSources": "Hľadanie zdrojov zvuku (opakovaný pokus)",
|
||||
"waitingForCapacity": "Čakanie na kapacitu (opakovaný pokus)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Vyžaduje sa akcia",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "Korrigerar",
|
||||
"lyricsDone": "Text klar",
|
||||
"lyrics": "Text",
|
||||
"confirmDurationCost": "Bekräfta kostnad"
|
||||
"confirmDurationCost": "Bekräfta kostnad",
|
||||
"findingAudioSources": "Söker efter ljudkällor (försöker igen)",
|
||||
"waitingForCapacity": "Väntar på kapacitet (försöker igen)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Åtgärd krävs",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "กำลังแก้ไข",
|
||||
"lyricsDone": "เนื้อเพลงเสร็จสิ้น",
|
||||
"lyrics": "เนื้อเพลง",
|
||||
"confirmDurationCost": "ยืนยันค่าใช้จ่าย"
|
||||
"confirmDurationCost": "ยืนยันค่าใช้จ่าย",
|
||||
"findingAudioSources": "กำลังค้นหาแหล่งเสียง (กำลังลองอีกครั้ง)",
|
||||
"waitingForCapacity": "กำลังรอระบบว่าง (กำลังลองอีกครั้ง)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "ต้องการการดำเนินการ",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "Itinatama",
|
||||
"lyricsDone": "Tapos na ang lyrics",
|
||||
"lyrics": "Lyrics",
|
||||
"confirmDurationCost": "Kumpirmahin ang halaga"
|
||||
"confirmDurationCost": "Kumpirmahin ang halaga",
|
||||
"findingAudioSources": "Naghahanap ng mga audio source (sinusubukang muli)",
|
||||
"waitingForCapacity": "Naghihintay ng kapasidad (sinusubukang muli)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Kailangan ng aksyon",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "Düzeltiliyor",
|
||||
"lyricsDone": "Sözler bitti",
|
||||
"lyrics": "Sözler",
|
||||
"confirmDurationCost": "Maliyeti onayla"
|
||||
"confirmDurationCost": "Maliyeti onayla",
|
||||
"findingAudioSources": "Ses kaynakları aranıyor (yeniden deneniyor)",
|
||||
"waitingForCapacity": "Kapasite bekleniyor (yeniden deneniyor)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Eylem gerekiyor",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "Виправлення",
|
||||
"lyricsDone": "Текст готовий",
|
||||
"lyrics": "Текст",
|
||||
"confirmDurationCost": "Підтвердити вартість"
|
||||
"confirmDurationCost": "Підтвердити вартість",
|
||||
"findingAudioSources": "Пошук джерел аудіо (повторна спроба)",
|
||||
"waitingForCapacity": "Очікування вільних ресурсів (повторна спроба)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Потрібна дія",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "Đang sửa",
|
||||
"lyricsDone": "Lời bài hát xong",
|
||||
"lyrics": "Lời bài hát",
|
||||
"confirmDurationCost": "Xác nhận chi phí"
|
||||
"confirmDurationCost": "Xác nhận chi phí",
|
||||
"findingAudioSources": "Đang tìm nguồn âm thanh (đang thử lại)",
|
||||
"waitingForCapacity": "Đang chờ tài nguyên (đang thử lại)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Cần hành động",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "校对中",
|
||||
"lyricsDone": "歌词完成",
|
||||
"lyrics": "歌词",
|
||||
"confirmDurationCost": "确认费用"
|
||||
"confirmDurationCost": "确认费用",
|
||||
"findingAudioSources": "正在查找音频源(重试中)",
|
||||
"waitingForCapacity": "等待可用资源(重试中)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "需要操作",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-gen"
|
||||
version = "0.192.2"
|
||||
version = "0.192.3"
|
||||
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
|
||||
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
|
||||
license = "MIT"
|
||||
|
||||
Reference in new issue
Block a user