Compare commits

...
2 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 4.8 46cc4012ac fix: harden admin reset against render/video worker supersession race (#899)
## Summary
- Fixes the admin-reset / render race that flipped job `7f457087` to
**failed** with *"Invalid state transition … in_review ->
instrumental_selected"*. Hitting an admin **Reset** button (e.g.
"Review") on a `rendering_video` job left the in-flight render running;
when it finished it attempted its normal `rendering_video ->
instrumental_selected` transition — now illegal — and the worker's
generic handler clobbered the operator's reset with a spurious failure.
- Long-running render/video workers are now **fenced against
supersession**, so any reset / cancel / re-trigger causes an in-flight
worker to discard its stale result quietly instead of failing the job or
overwriting fresher outputs. Resetting a rendering job is safe at any
timing.

## Changes
- **`backend/workers/supersede.py`** (new): shared fencing helper with
two independent nets — a **status fence** (job no longer in the status
the worker owns) and a **generation fence**
(`state_data.worker_generation`).
- **`JobManager.bump_worker_generation()`**: atomic Firestore
`Increment(1)` on the fence (best-effort; never blocks dispatch).
- Fence bumped at every supersede point: the
`trigger_render_video_worker` / `trigger_video_worker` choke points, and
atomically within `admin.py reset_job`.
- **Render worker**: captures generation at start; supersede-checks
before writing outputs (GCE + local paths); guards the progress callback
so a stale render can't drag a reset job's progress bar; and — key fix —
its `except InvalidStateTransitionError` now **confirms** supersession
via `check_superseded()` before bailing gracefully, otherwise falls
through to the real failure path so genuine workflow defects still
surface.
- **Video worker**: same graceful/confirmed
`InvalidStateTransitionError` handling in both the orchestrated and
legacy paths.
- Docs: `TROUBLESHOOTING.md` (new reset/render-race runbook) +
`LESSONS-LEARNED.md` (fencing principles).

## Known follow-up (documented in code)
Fully closing the residual GCS/metadata write window (a stale render can
leave transient bytes under the shared `jobs/{job_id}/` prefix before
the read-time check) requires **generation-scoped output prefixes + a
conditional promote on the encoder side** — a larger cross-service
change, deliberately deferred. The failed-job incident and any bad
downstream trigger are fully fixed here; the worst residual is a
transient stale object that a newer generation overwrites.

## Testing
- [x] `backend/tests/test_worker_supersede_race.py` (new): helper unit
tests, atomic-increment, progress-callback guard, and render-worker
scenarios — status-reset, generation-bump,
confirmed-supersession-is-graceful (the `7f457087` repro),
**not-superseded-still-fails**, and normal-completion.
- [x] `test_admin_job_reset.py`: reset bumps the generation fence.
- [x] Full backend suite green (3767 passed).

## Review
- [x] Local CodeRabbit review completed (3 cycles; final pass: no new
findings)
- [x] Feedback addressed (over-broad `InvalidStateTransitionError`
suppression fixed; TOCTOU residuals documented with a deferred
follow-up)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-07 21:25:04 +02:00
Andrew Beveridge ☄️andClaude Opus 4.8 c716c79022 feat(resilience): auto-recover stuck renders + transient downloads; retry 503 blips (#898)
## Why

Investigating two stuck real-user jobs (a render frozen at "[7/10]
Rendering video" for ~1.3 days, and a torrent download that gave up
after ~1h) surfaced a common gap: **a job can dead-end when a downstream
resource (encoding VM / torrent seeders / tracker) is briefly
unavailable, with no automatic recovery.** All three fixes apply the
same proven **park + periodic-retry-up-to-24h** pattern, folded into the
**existing** `recover-stuck-jobs` cron (every 5 min) — **no new
infra/Cloud Scheduler**.

## What

**1. Render staleness watchdog** (`job_health_service` +
`recover-stuck-jobs`)
A render worker killed mid-render (instance recycle / SIGKILL / lost VM)
left the job frozen at `RENDERING_VIDEO` forever — invisible to the
capacity-retry cron (which only queries `RENDER_PENDING_CAPACITY`), no
watchdog, and (per the UI) no Retry button. Now: `rendering_video` with
no progress for >45 min → re-park into `RENDER_PENDING_CAPACITY` so the
existing retry cron resets it to `REVIEW_COMPLETE` and re-renders (same
24h ceiling).

**2. Transient torrent-download retry** (new `DOWNLOAD_PENDING_RETRY`
status)
Rare tracks with few/intermittent seeders and brief tracker outages hit
gen's ~1h give-up and failed permanently ("Audio download timed out …
Use retry"). Now a stuck **RED/OPS** download parks into
`DOWNLOAD_PENDING_RETRY` and is auto-retried for up to 24h with a
friendly "we'll keep trying automatically" message; permanent failure
only after 24h. Non-torrent sources (YouTube/Spotify/URL) still fail
fast (deterministic). Per-tick dispatch cap prevents fan-out during an
audio-worker outage.

**3. VM-start 503 whole-set retry**
(`encoding_worker_manager.ensure_any_running`)
A transient `503 SERVICE_UNAVAILABLE` (distinct from a capacity
`STOCKOUT`) that hits all zones at once is retried across the whole
candidate set with backoff before giving up — but **only when every
candidate failure was transient** (a capacity or `PERMISSION_DENIED`
failure raises immediately; the 24h park handles a real shortage).
Per-candidate zone failover is unchanged.

**Frontend:** friendly i18n labels for `download_pending_retry` and
`render_pending_capacity` (the latter previously fell through to a raw
status), translated to all 33 locales.

## Verification
- The two triggering jobs were unstuck live: **`87eb17c3` completed +
published**; `7f457087` is a genuinely seedless release right now (RED
healthy for others) — exactly the case Feature 2 now auto-retries for
24h.
- Tests: render/download watchdog + retry paths, per-tick cap, 503
whole-set retry incl. the mixed non-transient case. Full backend suite
green locally.

Local CodeRabbit review completed; both findings (all-transient retry
guard; per-tick dispatch counting) were addressed with tests.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **New Features**
- Added automatic recovery and retries for stalled audio downloads and
video rendering jobs.
  - Jobs can wait for processing capacity and resume automatically.
  - Downloads now retry for up to 24 hours before permanent failure.

- **Bug Fixes**
- Improved handling of stuck downloads, renders, and transient capacity
errors.

- **Localization**
- Added retry and capacity-waiting status messages in supported
languages.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-07 11:20:05 +02:00
52 changed files with 1465 additions and 68 deletions

No files matched your search

+9 -1
View File
@@ -1203,7 +1203,7 @@ async def reset_job(
job_manager.update_job(job_id, updates)
# Clear the state data keys and error state using direct Firestore update
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion, Increment
job_ref = user_service.db.collection("jobs").document(job_id)
@@ -1219,6 +1219,14 @@ async def reset_job(
clear_updates["error_message"] = DELETE_FIELD
clear_updates["error_details"] = DELETE_FIELD
# Advance the supersession fence: a reset is a "stop what you're doing" event.
# Any render/video worker still in flight (e.g. the operator hit "Review"
# mid-render) will observe the bumped generation and discard its stale result
# instead of overwriting fresh outputs or failing this reset. See
# backend/workers/supersede.py. Atomic with the clears above so an in-flight
# worker can never observe a half-applied reset.
clear_updates["state_data.worker_generation"] = Increment(1)
# Add timeline event
clear_updates["timeline"] = ArrayUnion([timeline_event])
+216 -20
View File
@@ -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)
+6 -1
View File
@@ -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
+73 -2
View File
@@ -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
+27
View File
@@ -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
+28
View File
@@ -786,6 +786,34 @@ class JobManager:
self.update_job(job_id, {'state_data': state_data})
logger.debug(f"Job {job_id} state_data updated: {key} = {value}")
def bump_worker_generation(self, job_id: str) -> Optional[int]:
"""
Atomically increment the ``state_data.worker_generation`` fence.
Every trigger of a long-running render/video worker bumps this counter.
A worker captures the value at start; if it later differs, a newer run
has superseded it and its (now stale) result must be discarded rather
than written back or used to fail the job. See
:mod:`backend.workers.supersede`.
Returns the new generation, or ``None`` if the update failed (best-effort
— a failed bump must never block triggering the worker).
"""
try:
from google.cloud.firestore_v1 import Increment
self.firestore.update_job(job_id, {
'state_data.worker_generation': Increment(1),
})
job = self.get_job(job_id)
new_generation = (job.state_data or {}).get('worker_generation') if job else None
logger.info(f"Job {job_id}: bumped worker_generation to {new_generation}")
return new_generation
except Exception as e:
# Never let a fence bump block worker dispatch — the status fence
# (Layer A) still protects against the reset race on its own.
logger.warning(f"Job {job_id}: failed to bump worker_generation: {e}")
return None
def update_processing_metadata(self, job_id: str, section: str, data) -> None:
"""
Write data into processing_metadata[section] using Firestore dot-notation.
+19
View File
@@ -513,6 +513,7 @@ class WorkerService:
uses Cloud Run Jobs for execution (supports >30 min encoding).
Otherwise, uses Cloud Tasks or direct HTTP.
"""
self._bump_worker_generation(job_id)
self._warmup_encoding_worker(job_id)
if self._use_cloud_tasks and self.settings.use_cloud_run_jobs_for_video:
return await self._trigger_cloud_run_job(job_id)
@@ -606,9 +607,27 @@ class WorkerService:
async def trigger_render_video_worker(self, job_id: str) -> bool:
"""Trigger render video worker (post-review)."""
self._bump_worker_generation(job_id)
self._warmup_encoding_worker(job_id)
return await self.trigger_worker("render-video", job_id)
def _bump_worker_generation(self, job_id: str) -> None:
"""
Advance the supersession fence before dispatching a render/video worker.
Bumping here (the single choke point for both workers) means every run
captures a unique generation at start. If an older run of the same stage
is still in flight — because an admin reset then re-triggered the job —
it will observe the newer generation and discard its stale result
instead of overwriting fresh outputs or failing the job. Best-effort:
a failed bump is logged and ignored (the status fence still applies).
"""
try:
from backend.services.job_manager import JobManager
JobManager().bump_worker_generation(job_id)
except Exception as e:
logger.warning(f"[job:{job_id}] Failed to bump worker generation before trigger: {e}")
async def schedule_idle_reminder(
self,
job_id: str,
+48
View File
@@ -1116,3 +1116,51 @@ class TestResetJobToAwaitingAudioEdit:
# We check the update_job call for status change
update_args = mock_jm.update_job.call_args[0][1]
assert update_args["status"] == "awaiting_audio_edit"
class TestResetBumpsWorkerGenerationFence:
"""A reset is a 'stop what you're doing' event for in-flight workers.
It must atomically bump state_data.worker_generation so a render/video worker
that is still running (e.g. operator hit "Review" mid-render) detects it has
been superseded and discards its stale result instead of failing the reset.
Regression guard for the 7f457087 admin-reset race.
"""
def test_reset_increments_worker_generation(self, client, mock_job):
from backend.services.user_service import get_user_service
mock_user_service = Mock()
mock_job_ref = Mock()
mock_user_service.db.collection.return_value.document.return_value = mock_job_ref
app.dependency_overrides[get_user_service] = lambda: mock_user_service
try:
# Patch the Increment symbol the endpoint imports so the assertion is
# robust even when another test replaced firestore_v1 with a mock.
with patch('backend.api.routes.admin.JobManager') as mock_jm_class, \
patch('google.cloud.firestore_v1.Increment') as mock_incr:
mock_incr.return_value = "INCREMENT(1)"
mock_jm = Mock()
mock_jm.get_job.return_value = mock_job
mock_jm.update_job.return_value = None
mock_jm_class.return_value = mock_jm
response = client.post(
"/api/admin/jobs/test-job-123/reset",
json={"target_state": "awaiting_review"},
)
finally:
del app.dependency_overrides[get_user_service]
assert response.status_code == 200
mock_incr.assert_called_once_with(1) # atomic +1 on the fence
# The clear_updates payload sent to job_ref.update() must carry the fence bump.
update_payloads = [c.args[0] for c in mock_job_ref.update.call_args_list if c.args]
fence_updates = [
p for p in update_payloads
if isinstance(p, dict) and "state_data.worker_generation" in p
]
assert fence_updates, "Reset must bump state_data.worker_generation"
assert fence_updates[-1]["state_data.worker_generation"] == "INCREMENT(1)"
+97 -8
View File
@@ -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
+30
View File
@@ -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()
+337
View File
@@ -0,0 +1,337 @@
"""
Regression tests for the admin-reset / render race (job 7f457087).
Scenario: an operator hits the admin "Review" reset button while a render is
still in flight. The render finishes a moment later and attempts its normal
terminal transition (rendering_video -> instrumental_selected), which is now
illegal because the job was reset back to review. Previously this raised
InvalidStateTransitionError, was caught by the worker's generic handler, and
flipped a perfectly-good reset to `failed` with the confusing message:
Video render failed: Invalid state transition for job 7f457087:
in_review -> instrumental_selected
These tests lock in the hardened behaviour:
* A superseded render (status reset OR generation bumped) is discarded
quietly — it must NOT call fail_job and must NOT write stale outputs.
* An InvalidStateTransitionError at the terminal step is treated as
supersession (graceful bail), never a job failure.
* A normal, un-superseded render still transitions to INSTRUMENTAL_SELECTED.
"""
from unittest.mock import MagicMock, patch, AsyncMock
import pytest
from backend.models.job import JobStatus
from backend.exceptions import InvalidStateTransitionError
from backend.workers.supersede import capture_generation, check_superseded
# ---------------------------------------------------------------------------
# supersede helper unit tests
# ---------------------------------------------------------------------------
def _job(generation=0, status=JobStatus.RENDERING_VIDEO):
job = MagicMock()
job.state_data = {"worker_generation": generation}
job.status = status
return job
def test_capture_generation_defaults_to_zero():
job = MagicMock()
job.state_data = {}
assert capture_generation(job) == 0
job.state_data = None
assert capture_generation(job) == 0
def test_check_superseded_none_when_current():
jm = MagicMock()
jm.get_job.return_value = _job(generation=3, status=JobStatus.RENDERING_VIDEO)
assert check_superseded(jm, "j", 3, {JobStatus.RENDERING_VIDEO}) is None
def test_check_superseded_detects_generation_bump():
jm = MagicMock()
jm.get_job.return_value = _job(generation=4, status=JobStatus.RENDERING_VIDEO)
reason = check_superseded(jm, "j", 3, {JobStatus.RENDERING_VIDEO})
assert reason and "generation" in reason
def test_check_superseded_detects_status_reset():
jm = MagicMock()
# Status strings are how Job.status deserialises (use_enum_values=True)
jm.get_job.return_value = _job(generation=3, status="awaiting_review")
reason = check_superseded(jm, "j", 3, {JobStatus.RENDERING_VIDEO})
assert reason and "status" in reason
def test_check_superseded_when_job_deleted():
jm = MagicMock()
jm.get_job.return_value = None
assert check_superseded(jm, "j", 0, {JobStatus.RENDERING_VIDEO})
# ---------------------------------------------------------------------------
# JobManager.bump_worker_generation
# ---------------------------------------------------------------------------
def test_bump_worker_generation_uses_atomic_increment():
from backend.services.job_manager import JobManager
jm = JobManager.__new__(JobManager) # bypass __init__/Firestore connect
jm.firestore = MagicMock()
# Post-increment read reflects Increment(1) applied to a job at generation 5.
bumped_job = MagicMock()
bumped_job.state_data = {"worker_generation": 6}
jm.get_job = MagicMock(return_value=bumped_job)
# Patch the Increment symbol the production code imports so this assertion is
# robust even when another test has replaced the firestore_v1 module with a
# mock (real-vs-mock class identity would otherwise flake in the full suite).
with patch("google.cloud.firestore_v1.Increment") as mock_incr:
mock_incr.return_value = "INCREMENT(1)"
result = jm.bump_worker_generation("job-x")
# The returned value is informational (logging only) — workers never consume
# it as a token; they compare their captured generation against the current
# one. Correctness therefore only needs the fence to CHANGE, not to hand back
# a unique per-dispatch token, so concurrent bumps sharing a read are benign.
assert result == 6
mock_incr.assert_called_once_with(1) # atomic +1, not a read-modify-write
args, _ = jm.firestore.update_job.call_args
payload = args[1]
assert payload["state_data.worker_generation"] == "INCREMENT(1)"
def test_bump_worker_generation_is_best_effort():
"""A failed bump must never raise — the status fence still protects us."""
from backend.services.job_manager import JobManager
jm = JobManager.__new__(JobManager)
jm.firestore = MagicMock()
jm.firestore.update_job.side_effect = RuntimeError("firestore down")
jm.get_job = MagicMock()
assert jm.bump_worker_generation("job-x") is None
# ---------------------------------------------------------------------------
# render worker (GCE path) supersession behaviour
# ---------------------------------------------------------------------------
def _render_job(generation=1):
job = MagicMock()
job.artist = "John Maus"
job.title = "The Fear"
job.input_media_gcs_path = "jobs/test/audio.flac"
job.style_assets = {}
job.style_params_gcs_path = None
job.subtitle_offset_ms = 0
job.prep_only = False
job.state_data = {"worker_generation": generation, "is_duet": False}
job.file_urls = {}
job.status = JobStatus.RENDERING_VIDEO
return job
def _gce_result():
return {
"output_files": ["gs://test-bucket/jobs/test/videos/with_vocals.mkv"],
"metadata": {},
}
async def _run_gce_render(job_start, job_after, transition_side_effect=None):
"""Drive process_render_video down the GCE path with controlled get_job snapshots."""
from backend.workers import render_video_worker as rvw
jm = MagicMock()
seq = [job_start]
def _get_job(_job_id):
return seq.pop(0) if seq else job_after
jm.get_job.side_effect = _get_job
if transition_side_effect is not None:
jm.transition_to_state.side_effect = transition_side_effect
else:
jm.transition_to_state.return_value = True
encoding_service = MagicMock()
encoding_service.is_enabled = True
encoding_service.render_video_on_gce = AsyncMock(return_value=_gce_result())
storage = MagicMock()
storage.file_exists.return_value = False
worker_service = MagicMock()
worker_service.trigger_video_worker = AsyncMock(return_value=True)
with patch.object(rvw, "JobManager", return_value=jm), \
patch.object(rvw, "StorageService", return_value=storage), \
patch.object(rvw, "get_settings"), \
patch.object(rvw, "create_job_logger", return_value=MagicMock()), \
patch.object(rvw, "setup_job_logging", return_value=MagicMock()), \
patch.object(rvw, "validate_worker_can_run", return_value=None), \
patch.object(rvw, "get_encoding_service", return_value=encoding_service), \
patch("backend.services.worker_service.get_worker_service", return_value=worker_service):
result = await rvw.process_render_video("7f457087")
return result, jm
@pytest.mark.asyncio
async def test_render_superseded_by_status_reset_does_not_fail_job():
"""Admin reset moved the job to awaiting_review mid-render → discard, don't fail."""
job_start = _render_job(generation=1)
job_after = _render_job(generation=1)
job_after.status = "awaiting_review" # reset out from under the render
result, jm = await _run_gce_render(job_start, job_after)
assert result is False
jm.fail_job.assert_not_called()
# No stale outputs written and no terminal INSTRUMENTAL_SELECTED transition
jm.update_file_url.assert_not_called()
instrumental_transitions = [
c for c in jm.transition_to_state.call_args_list
if c.kwargs.get("new_status") == JobStatus.INSTRUMENTAL_SELECTED
]
assert not instrumental_transitions
@pytest.mark.asyncio
async def test_render_superseded_by_generation_bump_does_not_fail_job():
"""A newer render was triggered (generation bumped) → discard the stale run."""
job_start = _render_job(generation=1)
job_after = _render_job(generation=2) # newer run took over
result, jm = await _run_gce_render(job_start, job_after)
assert result is False
jm.fail_job.assert_not_called()
jm.update_file_url.assert_not_called()
@pytest.mark.asyncio
async def test_invalid_terminal_transition_is_graceful_when_superseded():
"""
The reset lands during the terminal transition itself: transition_to_state
raises InvalidStateTransitionError AND a re-read confirms supersession (the
reset moved the job to awaiting_review). The worker must bail gracefully,
exactly reproducing and fixing the 7f457087 incident.
"""
job_start = _render_job(generation=1)
job_after = _render_job(generation=1)
job_after.status = "awaiting_review" # reset confirmed on re-read in the handler
invalid = InvalidStateTransitionError(
"Invalid state transition for job 7f457087: in_review -> instrumental_selected",
job_id="7f457087",
from_status="in_review",
to_status="instrumental_selected",
valid_transitions=["review_complete", "awaiting_review", "failed"],
)
# 1st transition (RENDERING_VIDEO) ok, 2nd (INSTRUMENTAL_SELECTED) raises
result, jm = await _run_gce_render(
job_start, job_after, transition_side_effect=[True, invalid]
)
assert result is False
jm.fail_job.assert_not_called()
@pytest.mark.asyncio
async def test_invalid_transition_when_not_superseded_still_fails():
"""
An InvalidStateTransitionError that is NOT explained by supersession is a real
workflow defect — it must still fail the job (loudly) rather than be silently
swallowed and leave the job stuck. Guards against over-broad error suppression.
"""
job_start = _render_job(generation=1)
job_after = _render_job(generation=1) # same gen + still rendering_video => NOT superseded
invalid = InvalidStateTransitionError(
"Invalid state transition for job x: rendering_video -> instrumental_selected",
job_id="x",
)
result, jm = await _run_gce_render(
job_start, job_after, transition_side_effect=[True, invalid]
)
assert result is False
jm.fail_job.assert_called_once()
@pytest.mark.asyncio
async def test_progress_callback_skips_update_when_superseded():
"""A stale render's progress ticks must not drag a reset job's progress bar."""
from backend.workers import render_video_worker as rvw
job_start = _render_job(generation=1)
superseded = _render_job(generation=2) # reset bumped the fence mid-render
jm = MagicMock()
calls = {"n": 0}
def _get_job(_job_id):
calls["n"] += 1
return job_start if calls["n"] == 1 else superseded
jm.get_job.side_effect = _get_job
jm.transition_to_state.return_value = True
async def _render(_job_id, _config, progress_callback=None):
progress_callback(50) # encoder emits a tick on the now-stale job
return _gce_result()
encoding_service = MagicMock()
encoding_service.is_enabled = True
encoding_service.render_video_on_gce = AsyncMock(side_effect=_render)
storage = MagicMock()
storage.file_exists.return_value = False
with patch.object(rvw, "JobManager", return_value=jm), \
patch.object(rvw, "StorageService", return_value=storage), \
patch.object(rvw, "get_settings"), \
patch.object(rvw, "create_job_logger", return_value=MagicMock()), \
patch.object(rvw, "setup_job_logging", return_value=MagicMock()), \
patch.object(rvw, "validate_worker_can_run", return_value=None), \
patch.object(rvw, "get_encoding_service", return_value=encoding_service):
result = await rvw.process_render_video("7f457087")
assert result is False # bails after render (superseded)
jm.fail_job.assert_not_called()
# No progress write happened during the superseded tick
progress_writes = [
c for c in jm.update_job.call_args_list
if len(c.args) > 1 and isinstance(c.args[1], dict) and "progress" in c.args[1]
]
assert not progress_writes, "Superseded render must not stamp progress onto the job"
@pytest.mark.asyncio
async def test_normal_render_still_completes():
"""Un-superseded render must still write outputs and transition to INSTRUMENTAL_SELECTED."""
job_start = _render_job(generation=1)
job_after = _render_job(generation=1) # same gen, still rendering_video
result, jm = await _run_gce_render(job_start, job_after)
assert result is True
jm.fail_job.assert_not_called()
instrumental_transitions = [
c for c in jm.transition_to_state.call_args_list
if c.kwargs.get("new_status") == JobStatus.INSTRUMENTAL_SELECTED
]
assert instrumental_transitions, "Normal render must reach INSTRUMENTAL_SELECTED"
# with_vocals output recorded
assert any(
c.args[1:3] == ("videos", "with_vocals")
for c in jm.update_file_url.call_args_list
)
+103
View File
@@ -35,9 +35,11 @@ from typing import Optional, Dict, Any
from dataclasses import dataclass
from backend.models.job import JobStatus
from backend.exceptions import InvalidStateTransitionError
from backend.services.job_manager import JobManager
from backend.services.storage_service import StorageService
from backend.services.job_health_service import validate_worker_can_run
from backend.workers.supersede import capture_generation, check_superseded
from backend.config import get_settings
from backend.workers.registry import worker_registry
from backend.workers.worker_logging import create_job_logger, setup_job_logging, job_logging_context
@@ -123,6 +125,12 @@ async def process_render_video(job_id: str) -> bool:
job_log.error(f"Job {job_id} not found in Firestore!")
return False
# Capture the supersession fence at start. If an admin reset (or a newer
# render trigger) advances the generation while we render, our result is
# stale and must be discarded instead of overwriting fresh outputs or
# failing the job. See backend/workers/supersede.py.
captured_generation = capture_generation(job)
# Validate job status is appropriate for render video worker
# This helps catch bugs where the worker is triggered incorrectly
status_error = validate_worker_can_run("render_video_worker", job)
@@ -199,6 +207,16 @@ async def process_render_video(job_id: str) -> bool:
# gets logged via the error monitor, and (2) flood the
# timeline with redundant "transitioned" events for
# every tick.
#
# Supersession guard: if the job was reset/cancelled or a
# newer render took over while this (now stale) render is
# still emitting ticks, don't stamp our progress onto the
# job — that would drag a reset job's progress bar back to
# ~75-82% while it sits in awaiting_review.
if check_superseded(
job_manager, job_id, captured_generation, {JobStatus.RENDERING_VIDEO}
):
return
scaled = 75 + int(progress * 0.07) # Map 0-100 to 75-82
job_manager.update_job(job_id, {
'progress': scaled,
@@ -216,6 +234,30 @@ async def process_render_video(job_id: str) -> bool:
job_log.info(f"GCE render_video complete in {render_duration:.1f}s")
logger.info(f"[job:{job_id}] GCE render_video complete in {render_duration:.1f}s")
# Supersession fence: if the job was reset/cancelled or a newer
# render was triggered while we rendered, discard this stale
# result rather than recording its file_urls / transitioning
# (which would fail on an invalid terminal transition below).
#
# Residual (accepted): the GCE render already wrote the with_vocals
# object under the shared jobs/{job_id}/ prefix before this check, so
# a stale run can leave stale bytes there. A newer generation always
# re-renders and overwrites the same object, so the worst case is a
# transient stale object — never a failed job or a bad downstream
# trigger (those are blocked here + by the InvalidStateTransition
# guard). Fully closing the GCS window needs generation-scoped output
# prefixes + a conditional promote on the encoder side (follow-up).
superseded = check_superseded(
job_manager, job_id, captured_generation, {JobStatus.RENDERING_VIDEO}
)
if superseded:
job_log.warning(f"Render superseded, discarding stale GCE result: {superseded}")
logger.info(
f"[job:{job_id}] WORKER_END worker=render-video status=superseded "
f"reason={superseded}"
)
return False
# Parse response and update Firestore
output_files = result.get("output_files", [])
metadata = result.get("metadata", {})
@@ -479,6 +521,31 @@ async def process_render_video(job_id: str) -> bool:
title=job.title
)
# Supersession fence: bail before overwriting outputs if
# the job was reset/cancelled or a newer render started
# while we rendered (mirrors the GCE path above).
#
# Same accepted residual as the GCE path: earlier writes in
# this path (lyrics_metadata countdown padding, GCS objects
# under the shared jobs/{job_id}/ prefix) can still land on a
# newer generation in the narrow window before this check. A
# newer render re-renders and overwrites them, and the
# InvalidStateTransition guard blocks any bad downstream
# trigger, so the worst case is transient stale bytes/metadata.
# Fully closing it needs generation-scoped output paths +
# conditional promote (deferred follow-up). NB: prod renders
# via the GCE path; this local path is dev/fallback only.
superseded = check_superseded(
job_manager, job_id, captured_generation, {JobStatus.RENDERING_VIDEO}
)
if superseded:
job_log.warning(f"Render superseded, discarding stale local result: {superseded}")
logger.info(
f"[job:{job_id}] WORKER_END worker=render-video status=superseded "
f"reason={superseded}"
)
return False
# 9. Upload video to GCS
if outputs.video and os.path.exists(outputs.video):
video_size = os.path.getsize(outputs.video)
@@ -584,6 +651,42 @@ async def process_render_video(job_id: str) -> bool:
)
_park_job_for_capacity_retry(job_manager, job_id, e)
return False
except InvalidStateTransitionError as e:
# Safety net for the reset race: if our terminal transition became illegal
# because the job was reset/cancelled out from under us mid-render (e.g.
# admin "Review" reset while rendering_video -> the transition to
# instrumental_selected is no longer valid), the operator moved the job
# deliberately. Discard our stale result quietly instead of clobbering
# their reset with a spurious "failed" (the original 7f457087 incident).
#
# But an InvalidStateTransitionError does NOT by itself prove supersession
# — it also fires for genuine workflow defects (a bad initial transition,
# a state-machine bug). CONFIRM supersession before swallowing the error;
# otherwise fall through to the real failure path so a non-superseded job
# surfaces instead of silently stalling.
duration = time.time() - start_time
supersede_reason = check_superseded(
job_manager, job_id, captured_generation, {JobStatus.RENDERING_VIDEO}
)
if supersede_reason:
job_log.warning(
f"Render superseded mid-transition, discarding stale result: "
f"{supersede_reason} ({e})"
)
logger.info(
f"[job:{job_id}] WORKER_END worker=render-video status=superseded "
f"duration={duration:.1f}s reason={supersede_reason}"
)
return False
# Not superseded: this is a real defect, not the reset race. Fail loudly.
error_text = str(e) or repr(e)
job_log.error(f"Video render failed (unexpected invalid transition): {error_text}")
logger.error(
f"[job:{job_id}] WORKER_END worker=render-video status=error "
f"duration={duration:.1f}s error={error_text}"
)
job_manager.fail_job(job_id, f"Video render failed: {error_text}")
return False
except Exception as e:
duration = time.time() - start_time
# Use repr() so empty-string exceptions still produce a useful message;
+89
View File
@@ -0,0 +1,89 @@
"""
Worker supersession fencing.
A long-running worker (render-video, video) can be "superseded" mid-flight when
an operator resets the job (admin "Review"/"Audio"/"Reprocess" buttons), a user
cancels it, or a newer run of the same stage is triggered. When that happens the
worker's result is stale and must be DISCARDED — not written back and, above all,
not used to fail a job the operator deliberately moved.
Two independent nets detect supersession:
1. Status fence (Layer A) — the job is no longer in a status this worker owns.
Catches admin resets that move the job backwards (e.g. rendering_video ->
awaiting_review) even when no new worker has been triggered yet.
2. Generation fence (Layer B) — ``state_data.worker_generation`` is bumped every
time a render/video worker is triggered. A worker captures the generation at
start; if it later differs, a newer run has taken over. This closes the race
where a stale run finishes just after a new one started and would otherwise
overwrite the newer run's outputs.
Together these guarantee that no sequence of admin resets / re-submissions can
push a job into an invalid state or clobber a fresher render.
"""
from typing import Iterable, Optional
from backend.models.job import JobStatus
def capture_generation(job) -> int:
"""Read the worker-generation fence off a job snapshot (0 if unset)."""
state_data = getattr(job, "state_data", None) or {}
try:
return int(state_data.get("worker_generation", 0) or 0)
except (TypeError, ValueError):
return 0
def _normalize_status(status) -> Optional[JobStatus]:
"""Job.status is deserialised with use_enum_values=True (a plain str)."""
if isinstance(status, JobStatus):
return status
try:
return JobStatus(status)
except (ValueError, TypeError):
return None
def check_superseded(
job_manager,
job_id: str,
captured_generation: int,
expected_statuses: Iterable[JobStatus],
) -> Optional[str]:
"""
Re-read the job and decide whether this worker has been superseded.
Args:
job_manager: JobManager instance (re-reads fresh from Firestore).
job_id: Job being processed.
captured_generation: Value from :func:`capture_generation` at worker start.
expected_statuses: Statuses this worker legitimately owns right now.
Returns:
A human-readable reason string if superseded, else ``None``.
"""
job = job_manager.get_job(job_id)
if job is None:
return "job no longer exists"
current_generation = capture_generation(job)
if current_generation != captured_generation:
return (
f"worker generation changed "
f"({captured_generation} -> {current_generation}) — a newer run took over"
)
status = _normalize_status(job.status)
expected = set(expected_statuses)
if status not in expected:
status_value = status.value if status else repr(job.status)
expected_values = sorted(s.value for s in expected)
return (
f"job status is {status_value}, no longer one of {expected_values} "
f"(reset or cancelled out from under this worker)"
)
return None
+25 -1
View File
@@ -32,6 +32,7 @@ from typing import Optional, Dict, Any
from pathlib import Path
from backend.models.job import JobStatus
from backend.exceptions import InvalidStateTransitionError
from backend.services.job_manager import JobManager
from backend.services.storage_service import StorageService
from backend.services.job_health_service import validate_worker_can_run
@@ -423,6 +424,18 @@ async def generate_video_orchestrated(job_id: str) -> bool:
job_manager.update_state_data(job_id, 'video_progress', {'stage': 'complete'})
return True
except InvalidStateTransitionError as e:
# The job was reset/cancelled out from under us mid-encode (e.g. admin
# reset while generating_video/encoding). Discard our stale result quietly
# rather than failing a job the operator deliberately moved. See
# backend/workers/supersede.py and render_video_worker for the same guard.
duration = time.time() - start_time
logger.info(
f"[job:{job_id}] WORKER_END worker=video orchestrator=true status=superseded "
f"duration={duration:.1f}s reason={e}"
)
return False
except Exception as e:
duration = time.time() - start_time
logger.error(f"[job:{job_id}] WORKER_END worker=video orchestrator=true status=error duration={duration:.1f}s error={e}")
@@ -957,6 +970,17 @@ async def generate_video_legacy(job_id: str) -> bool:
job_manager.update_state_data(job_id, 'video_progress', {'stage': 'complete'})
return True
except InvalidStateTransitionError as e:
# Job reset/cancelled out from under us mid-encode — discard the stale
# result quietly instead of failing the operator's reset (see the
# orchestrated path and render_video_worker for the same guard).
duration = time.time() - start_time
logger.info(
f"[job:{job_id}] WORKER_END worker=video status=superseded "
f"duration={duration:.1f}s reason={e}"
)
return False
except Exception as e:
duration = time.time() - start_time
logger.error(f"[job:{job_id}] WORKER_END worker=video status=error duration={duration:.1f}s error={e}")
@@ -966,7 +990,7 @@ async def generate_video_legacy(job_id: str) -> bool:
error_details={"stage": "video_generation", "error": str(e)}
)
return False
finally:
# Restore original working directory
os.chdir(original_cwd)
+40
View File
@@ -1437,3 +1437,43 @@ CJK token like `立ち向かう`) and counts the inter-token space the renderer
splitters map zero words and would return `[]`, silently dropping lyrics.
- The CJK font is a **system fallback** (Noto Sans CJK); the configured karaoke
font (Montserrat/Avenir) has no CJK glyphs. See `video_generator._find_cjk_font`.
## Long-Running Workers Must Be Fenced Against Supersession (Aug 2026)
**Symptom:** An operator reset a `rendering_video` job via the admin "Review"
button, then the job flipped itself to `failed` seconds later with *"Invalid
state transition … in_review -> instrumental_selected"* (job `7f457087`). The
reset was fine; the job died on its own.
**Root cause:** Admin reset hard-writes the status backwards but does **not**
stop the render worker already running on the encoder. When that render
finished it ran its normal terminal transition (`rendering_video ->
instrumental_selected`), now illegal, and the worker's generic `except
Exception` handler called `fail_job()` — clobbering the operator's reset. A
classic stale-worker / lost-update race: whoever finishes last wins, and the
loser is a perfectly good reset.
**Fix (v0.192.4):** Fence long-running render/video workers against
supersession with two independent nets (`backend/workers/supersede.py`):
1. **Status fence** — re-read the job before writing outputs / transitioning;
if it's no longer in the status this worker owns, discard the result.
2. **Generation fence** — `state_data.worker_generation`, atomically
`Increment`ed by every admin reset *and* every render/video trigger. A worker
captures it at start; if it later differs, a newer run took over.
Plus a targeted `except InvalidStateTransitionError` **before** the generic
handler in both workers: a terminal transition that became illegal is treated
as supersession (log + `return False`), never `fail_job()`.
**Principles for next time:**
- A worker must **never** `fail_job()` because its *own* success transition
became illegal — that only happens when something deliberately moved the job.
- Bump the fence at the **trigger choke point** (`trigger_render_video_worker` /
`trigger_video_worker`), so every run gets a unique generation without having
to hunt down every caller. Cloud Tasks/Run retries re-invoke the worker (not
the trigger), so they keep the same generation — correct, it's the same run.
- Check the fence **before writing outputs**, not just before the terminal
transition — otherwise a stale render can overwrite a newer render's video.
- Test-isolation gotcha: assert an atomic bump via
`patch("google.cloud.firestore_v1.Increment")` + `assert_called_once_with(1)`,
not `isinstance(..., Increment)` — another test in the suite replaces the
firestore module with a mock, so real-vs-mock class identity flakes.
+36 -2
View File
@@ -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,41 @@ 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 flips to `failed` right after an admin reset (reset/render race)
**Symptoms:** An operator hit an admin **Reset** button (e.g. "Review") on a job that was `rendering_video`, and moments later the job went to `failed` with a message like *"Video render failed: Invalid state transition for job …: in_review -> instrumental_selected"*. The reset itself looked fine, but the job died on its own.
**Cause (fixed in v0.192.4):** The reset moved the job backwards while the render worker was still running on the encoder. When that render finished it attempted its normal terminal transition (`rendering_video -> instrumental_selected`), which was now illegal, and the worker's generic error handler flipped the job to `failed` — clobbering the operator's reset. First seen on job `7f457087`.
**Auto-handling (v0.192.4+):** Long-running render/video workers are now fenced against supersession — a reset or a newer trigger causes the in-flight worker to **discard its stale result quietly** instead of failing the job. Two nets: a **status fence** (job no longer in the status the worker owns) and a **generation fence** (`state_data.worker_generation`, bumped by every reset and every render/video trigger). An `InvalidStateTransitionError` at the terminal step is treated as supersession, not failure. So resetting a rendering job is now safe at any timing — no manual action needed.
**If you still see a `failed` job from an older occurrence:** use the admin **Retry** endpoint. For a job that has corrections + screens but no committed `instrumental_selection`, it returns cleanly to `awaiting_review` so the review (and instrumental choice) can be re-submitted.
---
## 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).
+6
View File
@@ -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" },
+3 -1
View File
@@ -592,7 +592,9 @@
"correcting": "جاري التصحيح",
"lyricsDone": "اكتملت الكلمات",
"lyrics": "الكلمات",
"confirmDurationCost": "تأكيد التكلفة"
"confirmDurationCost": "تأكيد التكلفة",
"findingAudioSources": "جارٍ البحث عن مصادر الصوت (إعادة المحاولة)",
"waitingForCapacity": "في انتظار توفر السعة (إعادة المحاولة)"
},
"jobCard": {
"actionNeeded": "إجراء مطلوب",
+3 -1
View File
@@ -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",
+3 -1
View File
@@ -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",
+3 -1
View File
@@ -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",
+3 -1
View File
@@ -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",
+3 -1
View File
@@ -592,7 +592,9 @@
"correcting": "Διόρθωση",
"lyricsDone": "Οι στίχοι ολοκληρώθηκαν",
"lyrics": "Στίχοι",
"confirmDurationCost": "Επιβεβαίωση κόστους"
"confirmDurationCost": "Επιβεβαίωση κόστους",
"findingAudioSources": "Εύρεση πηγών ήχου (επαναπροσπάθεια)",
"waitingForCapacity": "Αναμονή για διαθεσιμότητα (επαναπροσπάθεια)"
},
"jobCard": {
"actionNeeded": "Απαιτείται ενέργεια",
+2
View File
@@ -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",
+3 -1
View File
@@ -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",
+3 -1
View File
@@ -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",
+3 -1
View File
@@ -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",
+3 -1
View File
@@ -592,7 +592,9 @@
"correcting": "מתקן",
"lyricsDone": "מילים הושלמו",
"lyrics": "מילים",
"confirmDurationCost": "אישור עלות"
"confirmDurationCost": "אישור עלות",
"findingAudioSources": "מחפש מקורות שמע (מנסה שוב)",
"waitingForCapacity": "ממתין למשאבים פנויים (מנסה שוב)"
},
"jobCard": {
"actionNeeded": "נדרשת פעולה",
+3 -1
View File
@@ -592,7 +592,9 @@
"correcting": "सही किया जा रहा है",
"lyricsDone": "लिरिक्स हो गए",
"lyrics": "लिरिक्स",
"confirmDurationCost": "लागत की पुष्टि करो"
"confirmDurationCost": "लागत की पुष्टि करो",
"findingAudioSources": "ऑडियो स्रोत खोज रहे हैं (फिर से कोशिश कर रहे हैं)",
"waitingForCapacity": "क्षमता का इंतज़ार कर रहे हैं (फिर से कोशिश कर रहे हैं)"
},
"jobCard": {
"actionNeeded": "एक्शन की ज़रूरत है",
+3 -1
View File
@@ -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",
+3 -1
View File
@@ -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",
+3 -1
View File
@@ -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",
+3 -1
View File
@@ -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",
+3 -1
View File
@@ -592,7 +592,9 @@
"correcting": "修正中",
"lyricsDone": "歌詞完了",
"lyrics": "歌詞",
"confirmDurationCost": "料金を確認"
"confirmDurationCost": "料金を確認",
"findingAudioSources": "音源を検索中(再試行中)",
"waitingForCapacity": "処理の空きを待機中(再試行中)"
},
"jobCard": {
"actionNeeded": "アクションが必要です",
+3 -1
View File
@@ -592,7 +592,9 @@
"correcting": "수정 중",
"lyricsDone": "가사 완료",
"lyrics": "가사",
"confirmDurationCost": "비용 확인"
"confirmDurationCost": "비용 확인",
"findingAudioSources": "오디오 소스 찾는 중 (재시도 중)",
"waitingForCapacity": "처리 용량 대기 중 (재시도 중)"
},
"jobCard": {
"actionNeeded": "조치 필요",
+3 -1
View File
@@ -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",
+3 -1
View File
@@ -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",
+3 -1
View File
@@ -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",
+3 -1
View File
@@ -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",
+3 -1
View File
@@ -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",
+3 -1
View File
@@ -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ă",
+3 -1
View File
@@ -592,7 +592,9 @@
"correcting": "Исправление",
"lyricsDone": "Текст готов",
"lyrics": "Текст",
"confirmDurationCost": "Подтвердить стоимость"
"confirmDurationCost": "Подтвердить стоимость",
"findingAudioSources": "Поиск аудиоисточников (повторная попытка)",
"waitingForCapacity": "Ожидание свободных ресурсов (повторная попытка)"
},
"jobCard": {
"actionNeeded": "Требуется действие",
+3 -1
View File
@@ -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",
+3 -1
View File
@@ -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",
+3 -1
View File
@@ -592,7 +592,9 @@
"correcting": "กำลังแก้ไข",
"lyricsDone": "เนื้อเพลงเสร็จสิ้น",
"lyrics": "เนื้อเพลง",
"confirmDurationCost": "ยืนยันค่าใช้จ่าย"
"confirmDurationCost": "ยืนยันค่าใช้จ่าย",
"findingAudioSources": "กำลังค้นหาแหล่งเสียง (กำลังลองอีกครั้ง)",
"waitingForCapacity": "กำลังรอระบบว่าง (กำลังลองอีกครั้ง)"
},
"jobCard": {
"actionNeeded": "ต้องการการดำเนินการ",
+3 -1
View File
@@ -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",
+3 -1
View File
@@ -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",
+3 -1
View File
@@ -592,7 +592,9 @@
"correcting": "Виправлення",
"lyricsDone": "Текст готовий",
"lyrics": "Текст",
"confirmDurationCost": "Підтвердити вартість"
"confirmDurationCost": "Підтвердити вартість",
"findingAudioSources": "Пошук джерел аудіо (повторна спроба)",
"waitingForCapacity": "Очікування вільних ресурсів (повторна спроба)"
},
"jobCard": {
"actionNeeded": "Потрібна дія",
+3 -1
View File
@@ -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",
+3 -1
View File
@@ -592,7 +592,9 @@
"correcting": "校对中",
"lyricsDone": "歌词完成",
"lyrics": "歌词",
"confirmDurationCost": "确认费用"
"confirmDurationCost": "确认费用",
"findingAudioSources": "正在查找音频源(重试中)",
"waitingForCapacity": "等待可用资源(重试中)"
},
"jobCard": {
"actionNeeded": "需要操作",
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.192.2"
version = "0.192.4"
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"