mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-12-04 00:56:43 +09:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c5bca2240a | ||
|
|
807145a6f9 | ||
|
|
f5d3bdf426 | ||
|
|
5291d6ca78 | ||
|
|
ec99164a05 | ||
|
|
b389927351 | ||
|
|
46cc4012ac | ||
|
|
c716c79022 | ||
|
|
d6361ca7ad | ||
|
|
c94abbf7f4 | ||
|
|
d9ecc0d0d0 |
No files matched your search
@@ -1657,13 +1657,13 @@ jobs:
|
||||
# ============================================
|
||||
# Deploy to Cloud Run
|
||||
# ============================================
|
||||
# PREREQUISITE (edge-security): the `edge-origin-secret` Secret Manager
|
||||
# secret is referenced in --set-secrets below. `gcloud run deploy` FAILS
|
||||
# if that secret has no version. Before this change reaches main, add a
|
||||
# value: printf '%s' "$(openssl rand -hex 32)" | \
|
||||
# gcloud secrets versions add edge-origin-secret --data-file=- --project=nomadkaraoke
|
||||
# (and set the SAME value as Pulumi `edge:originSecret`). Until cutover the
|
||||
# backend runs EDGE_AUTH_MODE=off, so the secret is loaded but not enforced.
|
||||
# EDGE-SECURITY: the `edge-origin-secret` Secret Manager secret is
|
||||
# referenced in --set-secrets below (created 2026-07-20; has a value).
|
||||
# EDGE_AUTH_MODE=enforce (in --set-env-vars) means the backend rejects
|
||||
# requests to public routes that lack the Cloudflare-injected X-Edge-Auth
|
||||
# header — i.e. direct-to-origin traffic bypassing the edge (health/root
|
||||
# exempt). Cutover done 2026-07-20; validated via prod E2E with 0 blocked
|
||||
# legit callers. To disable, set EDGE_AUTH_MODE=off here and redeploy.
|
||||
- name: Deploy to Cloud Run
|
||||
run: |
|
||||
VERSION="${{ steps.version_check.outputs.version }}"
|
||||
@@ -1689,7 +1689,7 @@ jobs:
|
||||
--min-instances 1 \
|
||||
--vpc-connector projects/nomadkaraoke/locations/us-central1/connectors/cloud-run-connector \
|
||||
--vpc-egress private-ranges-only \
|
||||
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-opus-4-8,AUTO_CORRECT_COMPARE_MODELS=claude-opus-4-8;gemini-3.1-pro-preview,AUTO_CORRECT_PROACTIVE_ENABLED=true,EDGE_AUTH_MODE=off,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
|
||||
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-opus-4-8,AUTO_CORRECT_COMPARE_MODELS=claude-opus-4-8;gemini-3.1-pro-preview,AUTO_CORRECT_PROACTIVE_ENABLED=true,EDGE_AUTH_MODE=enforce,COMMIT_SHA=${{ steps.build-meta.outputs.sha }},PR_NUMBER=${{ steps.build-meta.outputs.pr_number }},PR_TITLE=${{ steps.build-meta.outputs.pr_title }}" \
|
||||
--set-secrets "ANTHROPIC_API_KEY=anthropic-api-key:latest,AUDIOSHAKE_API_TOKEN=audioshake-api-key:latest,GENIUS_API_TOKEN=genius-api-key:latest,SPOTIFY_COOKIE_SP_DC=spotify-cookie:latest,RAPIDAPI_KEY=rapidapi-key:latest,DEFAULT_DISCORD_WEBHOOK_URL=discord-releases-webhook:latest,ADMIN_TOKENS=admin-tokens:latest,RED_API_KEY=red-api-key:latest,RED_API_URL=red-api-url:latest,OPS_API_KEY=ops-api-key:latest,OPS_API_URL=ops-api-url:latest,FLACFETCH_API_URL=flacfetch-api-url:latest,FLACFETCH_API_KEY=flacfetch-api-key:latest,POSTMARK_SERVER_TOKEN=postmark-server-token:latest,STRIPE_SECRET_KEY=stripe-secret-key:latest,STRIPE_WEBHOOK_SECRET=stripe-webhook-secret:latest,LANGFUSE_PUBLIC_KEY=langfuse-public-key:latest,LANGFUSE_SECRET_KEY=langfuse-secret-key:latest,LANGFUSE_HOST=langfuse-host:latest,ENCODING_WORKER_URL=encoding-worker-url:latest,ENCODING_WORKER_API_KEY=encoding-worker-api-key:latest,ENCODING_WORKER_FALLBACK_VMS=encoding-worker-fallback-vms:latest,VAPID_PUBLIC_KEY=vapid-public-key:latest,VAPID_PRIVATE_KEY=vapid-private-key:latest,E2E_BYPASS_KEY=e2e-bypass-key:latest,GDRIVE_VALIDATOR_URL=gdrive-validator-url:latest,EDGE_ORIGIN_SECRET=edge-origin-secret:latest"
|
||||
|
||||
- name: Update Cloud Run Jobs with new image
|
||||
|
||||
@@ -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])
|
||||
|
||||
|
||||
@@ -18,6 +18,8 @@ from backend.services.error_monitor.frontend_ingestion import (
|
||||
FrontendErrorReport,
|
||||
RateLimiter,
|
||||
build_pattern_data,
|
||||
is_bot_user_agent,
|
||||
sanitize_url,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -64,6 +66,20 @@ def report_client_error(payload: ClientErrorPayload, request: Request) -> Client
|
||||
if not _limiter.allow(client_ip, time.monotonic()):
|
||||
raise HTTPException(status_code=429, detail="too many reports")
|
||||
|
||||
# Crawler/bot crashes are pure alert noise (bots run headless Chrome and trip
|
||||
# DOM errors no real user hits). Accept the report so the client doesn't retry,
|
||||
# but don't persist/alert on it.
|
||||
if is_bot_user_agent(payload.user_agent):
|
||||
# Log the bot UA (not sensitive) + sanitized URL (query/token stripped)
|
||||
# for visibility into what's being dropped, without persisting/alerting.
|
||||
logger.info(
|
||||
"frontend_crash_ignored_bot ua=%r url=%s source=%s",
|
||||
payload.user_agent[:120],
|
||||
sanitize_url(payload.url),
|
||||
payload.source,
|
||||
)
|
||||
return ClientErrorResponse(pattern_id="bot-ignored", is_new=False)
|
||||
|
||||
report = FrontendErrorReport(
|
||||
message=payload.message,
|
||||
stack=payload.stack,
|
||||
|
||||
+216
-20
@@ -796,58 +796,254 @@ async def recover_stuck_jobs(
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
):
|
||||
"""
|
||||
Detect and recover jobs stuck in downloading_audio status.
|
||||
Detect and recover jobs stuck in a processing status.
|
||||
|
||||
Called by Cloud Scheduler (every 5 minutes) or manually from admin.
|
||||
Finds jobs stuck in DOWNLOADING_AUDIO for >10 minutes and fails them
|
||||
so they can be retried.
|
||||
- DOWNLOADING_AUDIO stuck >10 min:
|
||||
* torrent sources (RED/OPS) → park into DOWNLOAD_PENDING_RETRY and keep
|
||||
auto-retrying for up to 24h (handles rare tracks with intermittent
|
||||
seeders and transient tracker outages gracefully).
|
||||
* other sources → fail so the user can retry.
|
||||
- DOWNLOAD_PENDING_RETRY → re-trigger the download; permanently fail after 24h.
|
||||
- RENDERING_VIDEO stuck with no progress (worker died mid-render) →
|
||||
re-park into RENDER_PENDING_CAPACITY so the existing
|
||||
retry-pending-render-jobs cron resumes it automatically. Closes the orphan
|
||||
gap where a hard-killed render worker leaves the job frozen at
|
||||
"rendering_video" forever with no error and no Retry button.
|
||||
"""
|
||||
from backend.services.job_health_service import check_job_consistency
|
||||
from backend.services.worker_service import get_worker_service
|
||||
from backend.models.job import JobStatus
|
||||
|
||||
trace_context = extract_trace_context(dict(http_request.headers))
|
||||
extract_trace_context(dict(http_request.headers))
|
||||
logger.info("RECOVER_STUCK_JOBS starting")
|
||||
add_span_attribute("operation", "recover_stuck_jobs")
|
||||
|
||||
job_manager = JobManager()
|
||||
worker_service = get_worker_service()
|
||||
|
||||
# Query jobs in downloading_audio status
|
||||
from google.cloud.firestore_v1 import FieldFilter
|
||||
jobs_ref = job_manager.firestore.db.collection("jobs")
|
||||
|
||||
recovered = [] # download jobs failed for user retry
|
||||
download_parked = [] # transient torrent downloads parked for auto-retry
|
||||
download_retried = [] # parked downloads re-triggered this tick
|
||||
download_timed_out = [] # parked downloads that exceeded the 24h ceiling
|
||||
reparked = [] # render jobs re-parked for auto-retry
|
||||
|
||||
# --- Stuck audio downloads: park torrents for auto-retry, else fail ---
|
||||
stuck_query = jobs_ref.where(
|
||||
filter=FieldFilter("status", "==", "downloading_audio")
|
||||
filter=FieldFilter("status", "==", JobStatus.DOWNLOADING_AUDIO.value)
|
||||
).stream()
|
||||
|
||||
recovered = []
|
||||
for doc in stuck_query:
|
||||
job_data = doc.to_dict()
|
||||
job_id = job_data.get("job_id", doc.id)
|
||||
|
||||
# Use the health service to check if actually stuck
|
||||
job_id = (doc.to_dict() or {}).get("job_id", doc.id)
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
continue
|
||||
|
||||
issues = check_job_consistency(job)
|
||||
stuck_issues = [i for i in issues if "downloading_audio_stuck" in i]
|
||||
|
||||
if stuck_issues:
|
||||
logger.warning(f"[job:{job_id}] Recovering stuck download: {stuck_issues[0]}")
|
||||
if not any("downloading_audio_stuck" in i for i in check_job_consistency(job)):
|
||||
continue
|
||||
if _is_retryable_torrent_source(job):
|
||||
logger.warning(f"[job:{job_id}] Parking stuck torrent download for auto-retry")
|
||||
if _park_download_for_retry(job_manager, job_id, "download stalled (>10 min)"):
|
||||
download_parked.append(job_id)
|
||||
else:
|
||||
logger.warning(f"[job:{job_id}] Recovering stuck download (non-torrent)")
|
||||
job_manager.fail_job(
|
||||
job_id,
|
||||
"Audio download timed out (stuck >10 minutes). Use retry to re-attempt."
|
||||
)
|
||||
recovered.append(job_id)
|
||||
|
||||
logger.info(f"RECOVER_STUCK_JOBS complete: recovered={len(recovered)} jobs")
|
||||
add_span_event("recovery_complete", {"recovered_count": len(recovered)})
|
||||
# --- Parked downloads: re-trigger, or permanently fail after 24h ---
|
||||
retried_this_tick = 0
|
||||
pending_query = jobs_ref.where(
|
||||
filter=FieldFilter("status", "==", JobStatus.DOWNLOAD_PENDING_RETRY.value)
|
||||
).limit(100).stream()
|
||||
for doc in pending_query:
|
||||
job_id = (doc.to_dict() or {}).get("job_id", doc.id)
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
continue
|
||||
meta = (job.state_data or {}).get("download_retry", {}) or {}
|
||||
first_seen = meta.get("first_seen_at")
|
||||
if _download_retry_expired(first_seen):
|
||||
hours = int(DOWNLOAD_RETRY_MAX_SECONDS // 3600)
|
||||
logger.error(f"[job:{job_id}] Download retries exhausted after {hours}h — failing")
|
||||
job_manager.fail_job(
|
||||
job_id,
|
||||
f"Couldn't find a working source for this track after {hours}h of "
|
||||
"automatic retries. It may be too rare to source right now — please "
|
||||
"try a different version or contact support.",
|
||||
error_details={"stage": "audio_download", "permanent_download_timeout": True},
|
||||
)
|
||||
download_timed_out.append(job_id)
|
||||
continue
|
||||
if retried_this_tick >= DOWNLOAD_RETRIES_PER_TICK:
|
||||
continue
|
||||
# Count the dispatch ATTEMPT against the per-tick cap before awaiting, so
|
||||
# a failing audio-worker (helper returns False after an external dispatch)
|
||||
# can't fan out to every queried job in one tick.
|
||||
retried_this_tick += 1
|
||||
if await _retrigger_parked_download(job_manager, worker_service, job_id):
|
||||
download_retried.append(job_id)
|
||||
|
||||
# --- Orphaned renders: re-park for automatic retry ---
|
||||
render_query = jobs_ref.where(
|
||||
filter=FieldFilter("status", "==", JobStatus.RENDERING_VIDEO.value)
|
||||
).stream()
|
||||
for doc in render_query:
|
||||
job_id = (doc.to_dict() or {}).get("job_id", doc.id)
|
||||
job = job_manager.get_job(job_id)
|
||||
if not job:
|
||||
continue
|
||||
if any("rendering_video_stuck" in i for i in check_job_consistency(job)):
|
||||
logger.warning(f"[job:{job_id}] Re-parking orphaned render for auto-retry")
|
||||
if _repark_stalled_render(job_manager, job_id):
|
||||
reparked.append(job_id)
|
||||
|
||||
logger.info(
|
||||
f"RECOVER_STUCK_JOBS complete: recovered={len(recovered)} "
|
||||
f"download_parked={len(download_parked)} download_retried={len(download_retried)} "
|
||||
f"download_timed_out={len(download_timed_out)} reparked={len(reparked)}"
|
||||
)
|
||||
add_span_event("recovery_complete", {
|
||||
"recovered_count": len(recovered),
|
||||
"download_parked_count": len(download_parked),
|
||||
"download_retried_count": len(download_retried),
|
||||
"download_timed_out_count": len(download_timed_out),
|
||||
"reparked_count": len(reparked),
|
||||
})
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"recovered_jobs": recovered,
|
||||
"recovered_count": len(recovered),
|
||||
"download_parked_jobs": download_parked,
|
||||
"download_retried_jobs": download_retried,
|
||||
"download_timed_out_jobs": download_timed_out,
|
||||
"reparked_render_jobs": reparked,
|
||||
"reparked_render_count": len(reparked),
|
||||
}
|
||||
|
||||
|
||||
# Torrent sources whose downloads are worth auto-retrying over a long window —
|
||||
# they fail transiently when a rare release has few/intermittent seeders or the
|
||||
# private tracker is briefly unreachable. Non-torrent sources (YouTube/Spotify/
|
||||
# URL) fail deterministically, so they are not auto-retried here.
|
||||
RETRYABLE_TORRENT_SOURCES = frozenset({"RED", "OPS"})
|
||||
DOWNLOAD_RETRY_MAX_SECONDS = 24 * 60 * 60 # keep retrying a transient download for 24h
|
||||
DOWNLOAD_RETRIES_PER_TICK = 10 # cap re-triggers per 5-min tick
|
||||
|
||||
|
||||
def _is_retryable_torrent_source(job) -> bool:
|
||||
"""True if the job's audio came from a torrent tracker (RED/OPS)."""
|
||||
return (getattr(job, "source_name", "") or "").upper() in RETRYABLE_TORRENT_SOURCES
|
||||
|
||||
|
||||
def _download_retry_expired(first_seen_at: Optional[str]) -> bool:
|
||||
"""True if the first parked failure is older than the 24h retry ceiling."""
|
||||
if not first_seen_at:
|
||||
return False
|
||||
from datetime import datetime, UTC
|
||||
try:
|
||||
age = datetime.now(UTC) - datetime.fromisoformat(first_seen_at)
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
return age.total_seconds() > DOWNLOAD_RETRY_MAX_SECONDS
|
||||
|
||||
|
||||
def _park_download_for_retry(job_manager: JobManager, job_id: str, reason: str) -> bool:
|
||||
"""Park a transient torrent-download failure into DOWNLOAD_PENDING_RETRY.
|
||||
|
||||
The recover-stuck cron re-triggers parked downloads on later ticks (up to
|
||||
24h) instead of dead-ending the job at FAILED after ~1h.
|
||||
"""
|
||||
from datetime import datetime, UTC
|
||||
from backend.models.job import JobStatus
|
||||
|
||||
now = datetime.now(UTC).isoformat()
|
||||
job = job_manager.get_job(job_id)
|
||||
existing = (job.state_data or {}).get("download_retry", {}) if job else {}
|
||||
meta = {
|
||||
"first_seen_at": existing.get("first_seen_at") or now,
|
||||
"last_attempt_at": now,
|
||||
"attempt_count": int(existing.get("attempt_count", 0)) + 1,
|
||||
"last_reason": str(reason)[:300],
|
||||
}
|
||||
job_manager.update_state_data(job_id, "download_retry", meta)
|
||||
# Clear any Cloud Run auto-retry marker so the UI reflects the parked state.
|
||||
job_manager.update_state_data(job_id, "cloud_run_retry_pending", None)
|
||||
return bool(job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.DOWNLOAD_PENDING_RETRY,
|
||||
progress=12,
|
||||
message=(
|
||||
"Still finding a good source for this track — it may be rare, or a "
|
||||
"source is temporarily offline. We'll keep trying automatically for up "
|
||||
"to 24 hours; no action needed."
|
||||
),
|
||||
raise_on_invalid=False,
|
||||
))
|
||||
|
||||
|
||||
async def _retrigger_parked_download(job_manager: JobManager, worker_service, job_id: str) -> bool:
|
||||
"""Re-trigger the audio download for a DOWNLOAD_PENDING_RETRY job."""
|
||||
from backend.models.job import JobStatus
|
||||
|
||||
job_manager.update_job(job_id, {"error_message": None, "error_details": None})
|
||||
if not job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.DOWNLOADING_AUDIO,
|
||||
progress=12,
|
||||
message="Retrying audio download — checking sources again",
|
||||
raise_on_invalid=False,
|
||||
):
|
||||
logger.warning(f"[job:{job_id}] Could not transition parked download for retry")
|
||||
return False
|
||||
try:
|
||||
await worker_service.trigger_audio_download_worker(job_id)
|
||||
logger.info(f"[job:{job_id}] Parked download re-triggered")
|
||||
return True
|
||||
except Exception as e: # noqa: BLE001
|
||||
logger.error(f"[job:{job_id}] Failed to re-trigger parked download: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def _repark_stalled_render(job_manager: JobManager, job_id: str) -> bool:
|
||||
"""Re-park a render orphaned at RENDERING_VIDEO into RENDER_PENDING_CAPACITY.
|
||||
|
||||
Mirrors render_video_worker._park_job_for_capacity_retry but for a mid-render
|
||||
stall (no EncodingWorkerStartError to carry). The existing
|
||||
retry-pending-render-jobs cron then resets it to REVIEW_COMPLETE and
|
||||
re-triggers the render, with the same 24h permanent-failure ceiling.
|
||||
"""
|
||||
from datetime import datetime, UTC
|
||||
from backend.models.job import JobStatus
|
||||
|
||||
now = datetime.now(UTC).isoformat()
|
||||
job = job_manager.get_job(job_id)
|
||||
existing = (job.state_data or {}).get("render_pending_capacity", {}) if job else {}
|
||||
pending_meta = {
|
||||
"first_seen_at": existing.get("first_seen_at") or now,
|
||||
"last_attempt_at": now,
|
||||
"attempt_count": int(existing.get("attempt_count", 0)) + 1,
|
||||
"last_code": "render_stalled",
|
||||
"last_zone": existing.get("last_zone", ""),
|
||||
"last_vm": existing.get("last_vm", ""),
|
||||
}
|
||||
job_manager.update_state_data(job_id, "render_pending_capacity", pending_meta)
|
||||
return bool(job_manager.transition_to_state(
|
||||
job_id=job_id,
|
||||
new_status=JobStatus.RENDER_PENDING_CAPACITY,
|
||||
progress=70,
|
||||
message=(
|
||||
"The render was interrupted (a worker was recycled). Your job will "
|
||||
"retry automatically — no action needed."
|
||||
),
|
||||
raise_on_invalid=False,
|
||||
))
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
async def internal_health(
|
||||
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
|
||||
|
||||
@@ -18,6 +18,7 @@ from typing import List, Optional, Dict, Any
|
||||
from fastapi import APIRouter, HTTPException, BackgroundTasks, Depends, Request, UploadFile, File
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from google.cloud.exceptions import NotFound
|
||||
from backend.utils.request_helpers import get_client_ip
|
||||
from backend.models.job import Job, JobCreate, JobResponse, JobStatus
|
||||
from backend.models.requests import (
|
||||
@@ -1646,6 +1647,17 @@ DOWNLOAD_FILENAME_SUFFIXES = {
|
||||
}
|
||||
|
||||
|
||||
def _cleanup_temp_file(path: Optional[str]) -> None:
|
||||
"""Best-effort removal of a temp file created for a download that failed
|
||||
before streaming started (so it never reaches the iterator's cleanup)."""
|
||||
if not path:
|
||||
return
|
||||
try:
|
||||
os.unlink(path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
@router.get("/{job_id}/download/{category}/{file_key}")
|
||||
async def download_file(
|
||||
job_id: str,
|
||||
@@ -1719,6 +1731,11 @@ async def download_file(
|
||||
else:
|
||||
filename = gcs_path.split('/')[-1] # Fallback to original
|
||||
|
||||
# Created below with delete=False; the streaming iterator's finally removes it
|
||||
# on the happy path. If download/setup raises before streaming starts, the
|
||||
# except handlers below unlink it so failed (e.g. 404) requests don't leak
|
||||
# temp files and fill local disk.
|
||||
tmp_path = None
|
||||
try:
|
||||
# Download to temp file and stream
|
||||
storage = StorageService()
|
||||
@@ -1754,7 +1771,16 @@ async def download_file(
|
||||
'Content-Disposition': content_disposition
|
||||
}
|
||||
)
|
||||
except NotFound:
|
||||
# The recorded output is gone from GCS (e.g. a stale download link hit
|
||||
# mid-reprocess after a visibility change / edit deleted the finals). This
|
||||
# is "not found", not a server error — return 404 and log at warning so it
|
||||
# doesn't trip the error-monitor.
|
||||
_cleanup_temp_file(tmp_path)
|
||||
logger.warning(f"Download requested for missing object {gcs_path}")
|
||||
raise HTTPException(status_code=404, detail=t(locale, "jobs.fileNoLongerAvailable"))
|
||||
except Exception as e:
|
||||
_cleanup_temp_file(tmp_path)
|
||||
logger.error(f"Error downloading {gcs_path}: {e}")
|
||||
raise HTTPException(status_code=500, detail=f"Error downloading file: {e}")
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1705,8 +1705,13 @@ class EmailService:
|
||||
# Use "ET" (Eastern Time) to be correct for both EST and EDT
|
||||
deadline_str = deadline_eastern.strftime("%B %d, %Y at %I:%M %p") + " ET"
|
||||
|
||||
# Link to /app/ with admin login token for one-click access
|
||||
app_url = f"{self.frontend_url.rstrip('/')}/app/?admin_token={admin_login_token}"
|
||||
# Link to /app/ with admin login token for one-click access, deep-linked to the
|
||||
# awaiting-audio-selection queue so the made-for-you order is shown immediately
|
||||
# (made-for-you cards render there; the status param pre-selects the filter).
|
||||
app_url = (
|
||||
f"{self.frontend_url.rstrip('/')}/app/"
|
||||
f"?admin_token={admin_login_token}&status=awaiting_audio_selection"
|
||||
)
|
||||
|
||||
content = f"""
|
||||
<div class="order-info">
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ Cloud Run Job handle all alerting / Discord plumbing.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from urllib.parse import urlsplit, urlunsplit
|
||||
@@ -19,6 +20,35 @@ from backend.services.error_monitor.normalizer import (
|
||||
MAX_SAMPLE_MESSAGE_CHARS = 4000
|
||||
MAX_URL_CHARS = 512
|
||||
|
||||
# Crawlers/bots execute our JS (e.g. bingbot/Googlebot run headless Chrome) and
|
||||
# trip React DOM-reconciliation errors that no real user ever sees. Their reports
|
||||
# are pure alert-channel noise, so we drop them at ingestion. Matches the common
|
||||
# crawler tokens plus the generic bot/crawler/spider/headless markers that
|
||||
# well-behaved automated agents put in their UA string.
|
||||
_BOT_UA_RE = re.compile(
|
||||
# Generic markers. The bot forms are anchored so we never match the "bot"
|
||||
# inside ordinary words like "robot": a standalone "bot" token (\bbot\b does
|
||||
# not match inside "robot" — no word boundary there) or the crawler
|
||||
# "<name>bot/<version>" convention, with "robot/" explicitly excluded.
|
||||
r"\bbot\b|(?<!ro)bot/|spider|crawler|crawl\b|slurp|bingpreview|headless|"
|
||||
# Explicit crawler names (some don't use the "/version" convention).
|
||||
r"googlebot|bingbot|applebot|yandex|baiduspider|duckduckbot|"
|
||||
r"ahrefs|semrush|petalbot|facebookexternalhit|"
|
||||
r"chrome-lighthouse|google page speed|python-requests|curl/|wget/",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def is_bot_user_agent(user_agent: str | None) -> bool:
|
||||
"""Return True if the UA looks like a crawler/bot/automated agent.
|
||||
|
||||
Conservative: only matches explicit bot markers, so a real browser UA (which
|
||||
never contains these tokens) is never misclassified.
|
||||
"""
|
||||
if not user_agent:
|
||||
return False
|
||||
return bool(_BOT_UA_RE.search(user_agent))
|
||||
|
||||
|
||||
@dataclass
|
||||
class FrontendErrorReport:
|
||||
|
||||
@@ -56,6 +56,33 @@ _IGNORE_PATTERNS: list[tuple[str, re.Pattern, str]] = [
|
||||
re.compile(r"stopping idle encoding worker", re.IGNORECASE),
|
||||
"Encoding worker idle shutdown — expected behaviour when no jobs are queued",
|
||||
),
|
||||
(
|
||||
"encoding_worker_capacity_retry",
|
||||
# Only the TRANSIENT start failures: GCE 503/SERVICE UNAVAILABLE or a
|
||||
# capacity code (ZONE_RESOURCE_POOL_EXHAUSTED / STOCKOUT / QUOTA_EXCEEDED
|
||||
# — see encoding_errors.CAPACITY_ERROR_CODES). The render worker parks
|
||||
# these for auto-retry. A non-transient EncodingWorkerStartError (other /
|
||||
# unknown code) shares the "aborting retries" prefix but must still page,
|
||||
# so we require the transient signal, not just the prefix.
|
||||
# Bind the transient signal to the GCE error CODE field — which appears
|
||||
# immediately after "start failed in <zone>: " / "could not be started in
|
||||
# <zone>: " (see encoding_errors.classify_gce_error). Matching the code in
|
||||
# position (not anywhere in the line) prevents a non-transient failure
|
||||
# whose message text merely contains "503" from being suppressed.
|
||||
re.compile(
|
||||
r"encoding worker start failed, aborting retries:.*?"
|
||||
r"(?:start failed|could not be started) in [\w.-]+:\s*"
|
||||
r"(?:503\b|service unavailable|zone_resource_pool_exhausted"
|
||||
r"|stockout|quota_exceeded)",
|
||||
re.IGNORECASE,
|
||||
),
|
||||
(
|
||||
"GCE encoding worker VM start hit a transient GCP condition (zone "
|
||||
"capacity exhaustion or 503 SERVICE UNAVAILABLE) — the render worker "
|
||||
"parks the job for auto-retry rather than failing it. Non-transient "
|
||||
"start failures still alert."
|
||||
),
|
||||
),
|
||||
(
|
||||
"health_check_404",
|
||||
re.compile(
|
||||
|
||||
@@ -79,6 +79,15 @@ _NORMALIZERS: list[tuple[re.Pattern, str]] = [
|
||||
re.compile(r"/jobs/[A-Za-z0-9]+"),
|
||||
"/jobs/<ID>",
|
||||
),
|
||||
# 9b. Preview render job IDs: preview_<jobid>_<renderid> (underscore-joined
|
||||
# hex runs). The generic hex rule (11) is \b-anchored and '_' is a word
|
||||
# char, so it can't reach these — leaving every preview render of the
|
||||
# same job as a distinct pattern (N alerts for one incident). Collapse
|
||||
# the whole token so they map to a single pattern.
|
||||
(
|
||||
re.compile(r"\bpreview_[0-9a-fA-F]{6,}(?:_[0-9a-fA-F]{6,})+\b"),
|
||||
"preview_<ID>",
|
||||
),
|
||||
# 10. Firebase UIDs (20–28 mixed-case alphanumeric characters)
|
||||
# Firebase Auth UIDs are typically 28 chars; allow 20-28 for flexibility.
|
||||
# Must contain both letters and digits (to avoid replacing plain words).
|
||||
|
||||
@@ -198,6 +198,7 @@ class FirestoreService:
|
||||
SUMMARY_FIELD_PATHS = [
|
||||
'job_id', 'status', 'progress', 'created_at', 'artist', 'title',
|
||||
'error_message', 'non_interactive', 'outputs_deleted_at', 'user_email', 'is_private',
|
||||
'made_for_you', 'customer_email',
|
||||
'url', 'filename', 'audio_search_artist', 'audio_search_title',
|
||||
'audio_source_type', 'source_name', 'source_id', 'target_file', 'download_url',
|
||||
'state_data.brand_code', 'state_data.youtube_url', 'state_data.dropbox_link',
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import asyncio
|
||||
import glob as glob_module
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
@@ -539,59 +538,152 @@ def run_render_video(job_id: str, work_dir: Path, request: "RenderVideoRequest")
|
||||
raise
|
||||
|
||||
|
||||
# Wheel install/verification tuning.
|
||||
#
|
||||
# On a freshly-provisioned worker the Packer image only pre-installs a handful
|
||||
# of packages (fastapi/uvicorn/gcs/...) and boot installs the wheel with
|
||||
# --no-deps, so the FIRST job's install here has to resolve the entire
|
||||
# karaoke-gen dependency tree (torch, langchain, tenacity, ...). That can take
|
||||
# well over 5 minutes and, if it times out or partially completes, leaves the
|
||||
# environment importable-but-broken (e.g. "No module named 'tenacity'"). We
|
||||
# therefore retry, and — critically — verify the import chain actually works
|
||||
# before declaring success, since pip can return 0 while a dependency is still
|
||||
# missing.
|
||||
WHEEL_INSTALL_TIMEOUT = int(os.environ.get("WHEEL_INSTALL_TIMEOUT", "900"))
|
||||
WHEEL_INSTALL_ATTEMPTS = int(os.environ.get("WHEEL_INSTALL_ATTEMPTS", "3"))
|
||||
|
||||
# Modules exercised by the render (OutputGenerator) and encode
|
||||
# (LocalEncodingService) code paths. Importing these confirms the whole
|
||||
# dependency tree they pull in — including transitive deps like tenacity — is
|
||||
# actually present, not just that `pip install` exited 0.
|
||||
_WHEEL_IMPORT_CHECK = (
|
||||
"import tenacity; "
|
||||
"from karaoke_gen.lyrics_transcriber.output.generator import OutputGenerator; "
|
||||
"from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations; "
|
||||
"from backend.services.local_encoding_service import LocalEncodingService"
|
||||
)
|
||||
|
||||
|
||||
def verify_wheel_imports():
|
||||
'''Verify the karaoke-gen render/encode import chain is fully importable.
|
||||
|
||||
Runs in a subprocess so a broken/partial install surfaces as a clean
|
||||
boolean instead of crashing (or half-importing into) the worker process.
|
||||
Returns True if every module imports, False otherwise.
|
||||
'''
|
||||
try:
|
||||
check = subprocess.run(
|
||||
[sys.executable, "-c", _WHEEL_IMPORT_CHECK],
|
||||
capture_output=True, text=True, timeout=180,
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
logger.warning("Wheel import verification timed out")
|
||||
return False
|
||||
if check.returncode != 0:
|
||||
# Tail of stderr carries the actionable ModuleNotFoundError.
|
||||
logger.warning(f"Wheel import verification failed: {check.stderr.strip()[-500:]}")
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def ensure_latest_wheel():
|
||||
'''Download and install latest karaoke-gen wheel from GCS.
|
||||
'''Download, install, and verify the latest karaoke-gen wheel from GCS.
|
||||
|
||||
Called at the start of each job to enable hot code updates without restart.
|
||||
In-progress jobs continue with their version, new jobs get latest code.
|
||||
|
||||
Retries the install and verifies the full import chain before returning, so
|
||||
a transient/partial dependency install can't leave the worker running jobs
|
||||
against a broken environment. Returns True only when the wheel is installed
|
||||
AND its render/encode imports succeed.
|
||||
'''
|
||||
try:
|
||||
logger.info("Checking for latest karaoke-gen wheel in GCS...")
|
||||
|
||||
# Download latest wheel
|
||||
result = subprocess.run(
|
||||
["gsutil", "cp", "gs://karaoke-gen-storage-nomadkaraoke/wheels/karaoke_gen-*.whl", "/tmp/"],
|
||||
capture_output=True, text=True, timeout=60
|
||||
)
|
||||
|
||||
# Find the downloaded wheel (get the latest by version sorting)
|
||||
wheels = glob_module.glob("/tmp/karaoke_gen-*.whl")
|
||||
# Filter out karaoke_gen-current.whl (not a valid PEP 427 wheel name)
|
||||
wheels = [w for w in wheels if '-current' not in w]
|
||||
|
||||
if not wheels:
|
||||
logger.warning("No wheel found in GCS, using fallback encoding logic")
|
||||
return False
|
||||
|
||||
# Sort to get latest version (by semantic version, not alphabetically)
|
||||
# Sort helper: extract version from a wheel name/URI like
|
||||
# karaoke_gen-0.116.1-py3-none-any.whl
|
||||
def extract_version(wheel_path):
|
||||
"""Extract version from wheel filename like karaoke_gen-0.116.1-py3-none-any.whl"""
|
||||
match = re.search(r'karaoke_gen-([0-9.]+)-', wheel_path)
|
||||
if match:
|
||||
return Version(match.group(1))
|
||||
return Version("0.0.0") # Fallback for unparseable filenames
|
||||
|
||||
wheels.sort(key=extract_version, reverse=True)
|
||||
wheel_path = wheels[0]
|
||||
logger.info(f"Installing wheel: {wheel_path}")
|
||||
|
||||
# Install (or upgrade) the wheel
|
||||
# Use 5-minute timeout - first install at job start may need to resolve dependencies
|
||||
# Subsequent installs are faster since dependencies are cached
|
||||
install_result = subprocess.run(
|
||||
[sys.executable, "-m", "pip", "install", "--upgrade", "--quiet", wheel_path],
|
||||
capture_output=True, text=True, timeout=300
|
||||
# List wheel names only (fast), then copy just the single latest one.
|
||||
# NOTE: `gsutil cp gs://.../karaoke_gen-*.whl /tmp/` would download the
|
||||
# ENTIRE wheels/ directory (hundreds of wheels, multiple GiB) on every
|
||||
# job and blow the timeout on fresh workers — the historical cause of
|
||||
# "no wheel found" / partial installs. Listing + single copy is ~2s.
|
||||
ls_result = subprocess.run(
|
||||
["gsutil", "ls", "gs://karaoke-gen-storage-nomadkaraoke/wheels/karaoke_gen-*.whl"],
|
||||
capture_output=True, text=True, timeout=60
|
||||
)
|
||||
# Filter out karaoke_gen-current.whl (not a valid PEP 427 wheel name)
|
||||
wheel_uris = [
|
||||
line.strip() for line in ls_result.stdout.splitlines()
|
||||
if line.strip() and '-current' not in line
|
||||
]
|
||||
|
||||
if install_result.returncode != 0:
|
||||
logger.warning(f"Wheel installation failed: {install_result.stderr}")
|
||||
if not wheel_uris:
|
||||
logger.warning("No versioned wheel found in GCS, using fallback encoding logic")
|
||||
return False
|
||||
|
||||
logger.info(f"Successfully installed wheel: {wheel_path}")
|
||||
return True
|
||||
wheel_uris.sort(key=extract_version)
|
||||
latest_uri = wheel_uris[-1]
|
||||
wheel_path = os.path.join("/tmp", latest_uri.rsplit("/", 1)[-1])
|
||||
|
||||
cp_result = subprocess.run(
|
||||
["gsutil", "cp", latest_uri, wheel_path],
|
||||
capture_output=True, text=True, timeout=120
|
||||
)
|
||||
if cp_result.returncode != 0:
|
||||
logger.warning(f"Failed to download wheel {latest_uri}: {cp_result.stderr.strip()[-500:]}")
|
||||
return False
|
||||
|
||||
# Install (with deps), then verify the import chain is complete. Retry a
|
||||
# failed or partial install: pip is resumable, so a second pass fills in
|
||||
# dependencies a timed-out first pass left missing (e.g. tenacity).
|
||||
for attempt in range(1, WHEEL_INSTALL_ATTEMPTS + 1):
|
||||
logger.info(f"Installing wheel (attempt {attempt}/{WHEEL_INSTALL_ATTEMPTS}): {wheel_path}")
|
||||
try:
|
||||
install_result = subprocess.run(
|
||||
[sys.executable, "-m", "pip", "install", "--upgrade", "--quiet", wheel_path],
|
||||
capture_output=True, text=True, timeout=WHEEL_INSTALL_TIMEOUT
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
logger.warning(
|
||||
f"Wheel install timed out after {WHEEL_INSTALL_TIMEOUT}s "
|
||||
f"(attempt {attempt}/{WHEEL_INSTALL_ATTEMPTS})"
|
||||
)
|
||||
install_result = None
|
||||
|
||||
if install_result is not None and install_result.returncode != 0:
|
||||
logger.warning(
|
||||
f"Wheel installation failed (attempt {attempt}/{WHEEL_INSTALL_ATTEMPTS}): "
|
||||
f"{install_result.stderr.strip()[-500:]}"
|
||||
)
|
||||
elif install_result is not None:
|
||||
logger.info(f"pip install completed for wheel: {wheel_path}")
|
||||
|
||||
# A clean `pip install` exit is not sufficient — confirm the deps
|
||||
# the render/encode paths need are actually importable before we let
|
||||
# a job run against this environment.
|
||||
if verify_wheel_imports():
|
||||
logger.info(f"Successfully installed and verified wheel: {wheel_path}")
|
||||
return True
|
||||
|
||||
logger.warning(
|
||||
f"Wheel environment incomplete after attempt {attempt}/{WHEEL_INSTALL_ATTEMPTS}; "
|
||||
"dependencies are missing or failed to import"
|
||||
)
|
||||
|
||||
logger.error(
|
||||
f"Wheel not ready after {WHEEL_INSTALL_ATTEMPTS} attempts: import verification "
|
||||
"still failing (environment is missing dependencies)"
|
||||
)
|
||||
return False
|
||||
|
||||
except subprocess.TimeoutExpired:
|
||||
logger.warning("Wheel download/install timed out, using fallback")
|
||||
logger.warning("Wheel download timed out, using fallback")
|
||||
return False
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to ensure latest wheel: {e}")
|
||||
@@ -873,8 +965,18 @@ async def process_job(job_id: str, request: EncodeRequest):
|
||||
# Process an encoding job asynchronously
|
||||
try:
|
||||
# Download and install latest wheel at job start (allows hot updates without restart)
|
||||
# This means in-progress jobs continue with their version, new jobs get latest code
|
||||
ensure_latest_wheel()
|
||||
# This means in-progress jobs continue with their version, new jobs get latest code.
|
||||
# Fail fast (retryable) if the environment isn't ready rather than proceeding into a
|
||||
# confusing "No module named ..." ImportError deep in encoding.
|
||||
# ensure_latest_wheel() makes blocking subprocess calls (install can retry for many
|
||||
# minutes) — run it in the thread pool so the async event loop keeps serving health
|
||||
# checks and status polls.
|
||||
loop = asyncio.get_event_loop()
|
||||
if not await loop.run_in_executor(executor, ensure_latest_wheel):
|
||||
raise RuntimeError(
|
||||
"karaoke-gen wheel/dependencies not ready on this worker after retries; "
|
||||
"job should be retried on a healthy worker"
|
||||
)
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
work_dir = Path(temp_dir) / "work"
|
||||
@@ -971,8 +1073,17 @@ async def process_preview_job(job_id: str, request: EncodePreviewRequest):
|
||||
async def process_render_video_job(job_id: str, request: RenderVideoRequest):
|
||||
# Process a render-video job asynchronously
|
||||
try:
|
||||
# Download and install latest wheel at job start (allows hot updates without restart)
|
||||
ensure_latest_wheel()
|
||||
# Download and install latest wheel at job start (allows hot updates without restart).
|
||||
# Fail fast (retryable) if the environment isn't ready rather than proceeding into a
|
||||
# confusing "No module named 'tenacity'" ImportError inside render_video.
|
||||
# Run in the thread pool: ensure_latest_wheel() blocks on subprocess installs (which
|
||||
# can retry for many minutes) and must not stall the async event loop.
|
||||
loop = asyncio.get_event_loop()
|
||||
if not await loop.run_in_executor(executor, ensure_latest_wheel):
|
||||
raise RuntimeError(
|
||||
"karaoke-gen wheel/dependencies not ready on this worker after retries; "
|
||||
"job should be retried on a healthy worker"
|
||||
)
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
work_dir = Path(temp_dir) / "work"
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -55,6 +55,12 @@ class StorageService:
|
||||
blob.download_to_filename(destination_path)
|
||||
logger.info(f"Downloaded gs://{settings.gcs_bucket_name}/{source_path} to {destination_path}")
|
||||
return destination_path
|
||||
except NotFound:
|
||||
# A missing object is a routine "not found", not a server-side failure.
|
||||
# Log at warning so it doesn't trip the error-monitor, and let the caller
|
||||
# decide how to surface it (e.g. the download route returns HTTP 404).
|
||||
logger.warning(f"Object not found downloading {source_path}")
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Error downloading file {source_path}: {e}")
|
||||
raise
|
||||
|
||||
@@ -141,7 +141,11 @@ class VisibilityChangeService:
|
||||
f"jobs/{job_id}/videos/with_vocals.mov",
|
||||
]:
|
||||
try:
|
||||
storage.delete_file(path)
|
||||
# Best-effort delete over a template of possible artifacts; many of
|
||||
# these intermediates legitimately never existed for a given render
|
||||
# path. ignore_missing keeps a 404 a quiet no-op instead of a noisy
|
||||
# ERROR log (which would otherwise trip the error-monitor).
|
||||
storage.delete_file(path, ignore_missing=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -55,6 +55,18 @@ def test_accepts_valid_report_and_upserts(client):
|
||||
assert pd.resource_type == "browser"
|
||||
|
||||
|
||||
def test_bot_report_is_accepted_but_not_persisted(client):
|
||||
bot_ua = (
|
||||
"Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; "
|
||||
"bingbot/2.0; +http://www.bing.com/bingbot.htm) Chrome/136.0.0.0 Safari/537.36"
|
||||
)
|
||||
resp = client.post("/api/client-errors", json=_payload(user_agent=bot_ua))
|
||||
# Accepted (so the bot won't retry) but never upserted / alerted.
|
||||
assert resp.status_code == 202
|
||||
assert resp.json()["is_new"] is False
|
||||
client.fake_adapter.upsert_pattern.assert_not_called()
|
||||
|
||||
|
||||
def test_rejects_missing_message(client):
|
||||
resp = client.post("/api/client-errors", json=_payload(message=""))
|
||||
assert resp.status_code == 422
|
||||
|
||||
@@ -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)"
|
||||
@@ -179,6 +179,37 @@ class TestChangeToPublic:
|
||||
mock_worker.trigger_screens_worker.assert_called_once_with("test-123")
|
||||
mock_theme.assert_called_once_with(job_id="test-123", theme_id="nomad")
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_intermediate_deletes_ignore_missing(self):
|
||||
"""Best-effort deletes of intermediate render artifacts must pass
|
||||
ignore_missing=True so absent .mov/.mkv files are a quiet no-op instead
|
||||
of a noisy ERROR log that trips the error-monitor (regression)."""
|
||||
mock_job_manager = MagicMock()
|
||||
mock_job_ref = MagicMock()
|
||||
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
|
||||
|
||||
service = VisibilityChangeService(job_manager=mock_job_manager)
|
||||
job = _make_job(is_private=True, state_data={})
|
||||
|
||||
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock), \
|
||||
patch("backend.services.visibility_change_service.StorageService") as mock_storage_cls, \
|
||||
patch("backend.api.routes.file_upload._prepare_theme_for_job", return_value=("jobs/test-123/style/style_params.json", {"bg": "bg.png"}, None)), \
|
||||
patch("backend.services.worker_service.get_worker_service") as mock_worker_svc:
|
||||
|
||||
mock_storage = MagicMock()
|
||||
mock_storage_cls.return_value = mock_storage
|
||||
mock_worker = MagicMock()
|
||||
mock_worker.trigger_screens_worker = AsyncMock(return_value=True)
|
||||
mock_worker_svc.return_value = mock_worker
|
||||
|
||||
await service.change_to_public("test-123", job, "user@example.com")
|
||||
|
||||
assert mock_storage.delete_file.call_count > 0
|
||||
for call in mock_storage.delete_file.call_args_list:
|
||||
assert call.kwargs.get("ignore_missing") is True, (
|
||||
f"delete_file called without ignore_missing=True: {call}"
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_resets_styles_to_nomad_theme(self):
|
||||
mock_job_manager = MagicMock()
|
||||
|
||||
@@ -670,6 +670,30 @@ class TestMadeForYouAdminNotification:
|
||||
html_content = call_kwargs.get('html_content')
|
||||
assert "abc-def-123" in html_content
|
||||
|
||||
def test_send_admin_notification_link_deep_links_to_audio_queue(self):
|
||||
"""Admin 'Open Job' link must one-click login AND deep-link to the
|
||||
awaiting-audio-selection queue so the made-for-you order is visible
|
||||
(a bare /app link lands on a dashboard that filters it out)."""
|
||||
service = EmailService()
|
||||
service.provider = Mock()
|
||||
service.provider.send_email.return_value = True
|
||||
|
||||
service.send_made_for_you_admin_notification(
|
||||
to_email="admin@nomadkaraoke.com",
|
||||
customer_email="customer@example.com",
|
||||
artist="Test Artist",
|
||||
title="Test Song",
|
||||
job_id="job-123",
|
||||
admin_login_token="tok-xyz",
|
||||
)
|
||||
|
||||
call_kwargs = service.provider.send_email.call_args.kwargs
|
||||
html_content = call_kwargs.get('html_content')
|
||||
text_content = call_kwargs.get('text_content')
|
||||
for body in (html_content, text_content):
|
||||
assert "admin_token=tok-xyz" in body
|
||||
assert "status=awaiting_audio_selection" in body
|
||||
|
||||
def test_send_admin_notification_includes_audio_count(self):
|
||||
"""Test admin notification includes audio source count."""
|
||||
service = EmailService()
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -555,3 +555,168 @@ class TestScreenVideoStaging:
|
||||
|
||||
assert (outputs / "Artist - Title (Title).mov").is_file()
|
||||
assert not (outputs / "Artist - Title (End).mov").exists()
|
||||
|
||||
|
||||
class TestEnsureLatestWheelVerification:
|
||||
"""Test ensure_latest_wheel() install-retry + import-verification behavior.
|
||||
|
||||
Regression: a freshly-provisioned worker installs the wheel with --no-deps
|
||||
at boot and relies on ensure_latest_wheel() to install the full dependency
|
||||
tree at the first job. A transient/partial install could leave the env
|
||||
importable-but-broken (`pip` exits 0 while `tenacity` is still missing),
|
||||
and the return value was ignored, so the job proceeded and died with
|
||||
"No module named 'tenacity'" deep inside render_video.
|
||||
|
||||
Fix: verify the render/encode import chain (via subprocess) and only return
|
||||
True when it imports; retry a failed/partial install; callers fail fast.
|
||||
"""
|
||||
|
||||
# A couple of versioned wheels plus the (filtered-out) current wheel, as
|
||||
# `gsutil ls` would emit them.
|
||||
DEFAULT_LS = (
|
||||
"gs://karaoke-gen-storage-nomadkaraoke/wheels/karaoke_gen-0.192.5-py3-none-any.whl\n"
|
||||
"gs://karaoke-gen-storage-nomadkaraoke/wheels/karaoke_gen-0.192.6-py3-none-any.whl\n"
|
||||
"gs://karaoke-gen-storage-nomadkaraoke/wheels/karaoke_gen-current.whl\n"
|
||||
)
|
||||
|
||||
def _completed(self, returncode=0, stdout="", stderr=""):
|
||||
import subprocess
|
||||
return subprocess.CompletedProcess(args=[], returncode=returncode, stdout=stdout, stderr=stderr)
|
||||
|
||||
def _side_effect(self, ls_stdout=None, ls_rc=0, cp_rc=0, install_rc=0, verify_results=None):
|
||||
"""Build a subprocess.run side_effect keyed on the command.
|
||||
|
||||
Models the download flow (gsutil ls -> gsutil cp of a single wheel),
|
||||
the pip install, and the import-verification subprocess.
|
||||
|
||||
verify_results: list of booleans consumed in order, one per verify call
|
||||
(True -> returncode 0). Lets a test model "install succeeded but imports
|
||||
fail, then a retry fixes them".
|
||||
"""
|
||||
import sys
|
||||
ls = self.DEFAULT_LS if ls_stdout is None else ls_stdout
|
||||
verify_iter = iter(verify_results or [])
|
||||
|
||||
def side_effect(cmd, *args, **kwargs):
|
||||
if cmd and cmd[0] == "gsutil" and cmd[1] == "ls":
|
||||
return self._completed(returncode=ls_rc, stdout=ls)
|
||||
if cmd and cmd[0] == "gsutil" and cmd[1] == "cp":
|
||||
return self._completed(returncode=cp_rc)
|
||||
if len(cmd) >= 2 and cmd[0] == sys.executable and cmd[1] == "-m":
|
||||
# pip install ...
|
||||
return self._completed(returncode=install_rc)
|
||||
if len(cmd) >= 2 and cmd[0] == sys.executable and cmd[1] == "-c":
|
||||
# import verification subprocess
|
||||
ok = next(verify_iter, False)
|
||||
return self._completed(
|
||||
returncode=0 if ok else 1,
|
||||
stderr="" if ok else "ModuleNotFoundError: No module named 'tenacity'",
|
||||
)
|
||||
return self._completed(returncode=0)
|
||||
|
||||
return side_effect
|
||||
|
||||
def test_downloads_only_latest_single_wheel(self, monkeypatch):
|
||||
"""Must `gsutil cp` exactly one wheel (the latest version), not the whole dir."""
|
||||
from backend.services.gce_encoding import main
|
||||
|
||||
cp_targets = []
|
||||
base = self._side_effect(verify_results=[True])
|
||||
|
||||
def spy(cmd, *args, **kwargs):
|
||||
if cmd and cmd[0] == "gsutil" and cmd[1] == "cp":
|
||||
cp_targets.append(cmd[2])
|
||||
return base(cmd, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(main.subprocess, "run", spy)
|
||||
|
||||
assert main.ensure_latest_wheel() is True
|
||||
assert cp_targets == [
|
||||
"gs://karaoke-gen-storage-nomadkaraoke/wheels/karaoke_gen-0.192.6-py3-none-any.whl"
|
||||
]
|
||||
|
||||
def test_returns_true_when_install_and_imports_succeed(self, monkeypatch):
|
||||
from backend.services.gce_encoding import main
|
||||
monkeypatch.setattr(main.subprocess, "run", self._side_effect(verify_results=[True]))
|
||||
assert main.ensure_latest_wheel() is True
|
||||
|
||||
def test_returns_false_when_pip_ok_but_imports_broken(self, monkeypatch):
|
||||
"""The core regression: pip exits 0 but a dependency is missing."""
|
||||
from backend.services.gce_encoding import main
|
||||
# install always "succeeds", verification always fails -> not ready.
|
||||
monkeypatch.setattr(main.subprocess, "run",
|
||||
self._side_effect(install_rc=0, verify_results=[False, False, False]))
|
||||
assert main.ensure_latest_wheel() is False
|
||||
|
||||
def test_retries_and_succeeds_after_partial_install(self, monkeypatch):
|
||||
"""First attempt leaves deps missing; a retry completes them."""
|
||||
from backend.services.gce_encoding import main
|
||||
monkeypatch.setattr(main.subprocess, "run", self._side_effect(verify_results=[False, True]))
|
||||
assert main.ensure_latest_wheel() is True
|
||||
|
||||
def test_returns_false_when_no_wheel_found(self, monkeypatch):
|
||||
"""Only the current wheel exists (filtered out) -> no versioned wheel."""
|
||||
from backend.services.gce_encoding import main
|
||||
only_current = "gs://karaoke-gen-storage-nomadkaraoke/wheels/karaoke_gen-current.whl\n"
|
||||
monkeypatch.setattr(main.subprocess, "run", self._side_effect(ls_stdout=only_current))
|
||||
assert main.ensure_latest_wheel() is False
|
||||
|
||||
def test_returns_false_when_download_fails(self, monkeypatch):
|
||||
"""A failed single-wheel copy is reported, not silently installed."""
|
||||
from backend.services.gce_encoding import main
|
||||
monkeypatch.setattr(main.subprocess, "run", self._side_effect(cp_rc=1))
|
||||
assert main.ensure_latest_wheel() is False
|
||||
|
||||
def test_install_timeout_then_success(self, monkeypatch):
|
||||
"""A timed-out first install must not abort the whole routine."""
|
||||
import sys
|
||||
import subprocess
|
||||
from backend.services.gce_encoding import main
|
||||
|
||||
state = {"install_calls": 0}
|
||||
base = self._side_effect()
|
||||
|
||||
def side_effect(cmd, *args, **kwargs):
|
||||
if len(cmd) >= 2 and cmd[0] == sys.executable and cmd[1] == "-m":
|
||||
state["install_calls"] += 1
|
||||
if state["install_calls"] == 1:
|
||||
raise subprocess.TimeoutExpired(cmd, main.WHEEL_INSTALL_TIMEOUT)
|
||||
return self._completed(returncode=0)
|
||||
if len(cmd) >= 2 and cmd[0] == sys.executable and cmd[1] == "-c":
|
||||
# Imports fail after the timed-out first install, succeed after retry.
|
||||
return self._completed(returncode=0 if state["install_calls"] >= 2 else 1,
|
||||
stderr="ModuleNotFoundError")
|
||||
return base(cmd, *args, **kwargs)
|
||||
|
||||
monkeypatch.setattr(main.subprocess, "run", side_effect)
|
||||
assert main.ensure_latest_wheel() is True
|
||||
|
||||
|
||||
class TestVerifyWheelImports:
|
||||
"""Test the verify_wheel_imports() helper in isolation."""
|
||||
|
||||
def test_true_on_clean_import(self, monkeypatch):
|
||||
import subprocess
|
||||
from backend.services.gce_encoding import main
|
||||
monkeypatch.setattr(main.subprocess, "run",
|
||||
lambda *a, **k: subprocess.CompletedProcess([], 0, "", ""))
|
||||
assert main.verify_wheel_imports() is True
|
||||
|
||||
def test_false_on_import_error(self, monkeypatch):
|
||||
import subprocess
|
||||
from backend.services.gce_encoding import main
|
||||
monkeypatch.setattr(
|
||||
main.subprocess, "run",
|
||||
lambda *a, **k: subprocess.CompletedProcess(
|
||||
[], 1, "", "ModuleNotFoundError: No module named 'tenacity'"))
|
||||
assert main.verify_wheel_imports() is False
|
||||
|
||||
def test_false_on_timeout(self, monkeypatch):
|
||||
import subprocess
|
||||
from backend.services.gce_encoding import main
|
||||
|
||||
def _timeout(*a, **k):
|
||||
raise subprocess.TimeoutExpired(["python", "-c"], 180)
|
||||
|
||||
monkeypatch.setattr(main.subprocess, "run", _timeout)
|
||||
assert main.verify_wheel_imports() is False
|
||||
@@ -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()
|
||||
@@ -662,6 +662,21 @@ class TestSummaryEndpoint:
|
||||
'audio_source_type', 'source_name', 'source_id', 'target_file', 'download_url']:
|
||||
assert field in paths, f"{field} must be in summary projection for source details modal"
|
||||
|
||||
def test_summary_projection_includes_made_for_you(self):
|
||||
"""Verify SUMMARY_FIELD_PATHS includes made_for_you (and customer_email).
|
||||
|
||||
The dashboard needs made_for_you in the summary payload so it can keep
|
||||
made-for-you orders (which sit at awaiting_audio_selection) visible as
|
||||
cards instead of filtering them out with self-service guided-flow jobs.
|
||||
"""
|
||||
from backend.services.firestore_service import FirestoreService
|
||||
paths = FirestoreService.SUMMARY_FIELD_PATHS
|
||||
assert 'made_for_you' in paths, (
|
||||
"'made_for_you' must be in summary projection so the dashboard can "
|
||||
"surface made-for-you orders awaiting audio selection"
|
||||
)
|
||||
assert 'customer_email' in paths
|
||||
|
||||
def test_prune_file_urls_keeps_allowed_keys(self):
|
||||
"""Verify _prune_file_urls keeps only dashboard-required keys."""
|
||||
from backend.api.routes.jobs import _prune_file_urls
|
||||
|
||||
@@ -206,9 +206,34 @@ class TestStorageServiceDownload:
|
||||
|
||||
with pytest.raises(Exception) as exc_info:
|
||||
service.download_file("missing/file.flac", "/local/path")
|
||||
|
||||
|
||||
assert "File not found" in str(exc_info.value)
|
||||
|
||||
|
||||
@patch("backend.services.storage_service.storage.Client")
|
||||
@patch("backend.services.storage_service.settings")
|
||||
def test_download_file_missing_reraises_notfound(self, mock_settings, mock_client_class):
|
||||
"""A 404 from GCS re-raises NotFound (so callers can map it to HTTP 404)
|
||||
and is logged at warning, not error, to avoid tripping the error-monitor."""
|
||||
from google.cloud.exceptions import NotFound
|
||||
|
||||
mock_settings.google_cloud_project = "test-project"
|
||||
mock_settings.gcs_bucket_name = "test-bucket"
|
||||
|
||||
mock_blob = Mock()
|
||||
mock_blob.download_to_filename.side_effect = NotFound("No such object")
|
||||
mock_bucket = Mock()
|
||||
mock_bucket.blob.return_value = mock_blob
|
||||
mock_client = Mock()
|
||||
mock_client.bucket.return_value = mock_bucket
|
||||
mock_client_class.return_value = mock_client
|
||||
|
||||
service = StorageService()
|
||||
with patch("backend.services.storage_service.logger") as mock_logger:
|
||||
with pytest.raises(NotFound):
|
||||
service.download_file("jobs/abc/finals/lossy_4k_mp4.mp4", "/local/path")
|
||||
mock_logger.error.assert_not_called()
|
||||
mock_logger.warning.assert_called_once()
|
||||
|
||||
@patch("backend.services.storage_service.storage.Client")
|
||||
@patch("backend.services.storage_service.settings")
|
||||
def test_download_json(self, mock_settings, mock_client_class):
|
||||
|
||||
@@ -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
|
||||
)
|
||||
@@ -14,6 +14,7 @@
|
||||
"authError": "Authentication error: no user identity available",
|
||||
"noDefaultTheme": "No default theme configured. Please contact support or specify a theme_id.",
|
||||
"notFound": "Job not found",
|
||||
"fileNoLongerAvailable": "File no longer available",
|
||||
"noPermissionAccess": "You don't have permission to access this job",
|
||||
"noPermissionEdit": "You don't have permission to edit this job",
|
||||
"noPermissionDelete": "You don't have permission to delete this job",
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
"invalidInstrumentalSelection": "instrumental_selection غير صالح. يجب أن يكون واحدًا من: {valid_selections}",
|
||||
"instrumentalSelected": "تم تحديد المسار الموسيقي. بدأ إنشاء الفيديو.",
|
||||
"instrumentalSelectionError": "خطأ في تحديد المسار الموسيقي للمهمة {job_id}: {error}",
|
||||
"downloadUrlsError": "خطأ في الحصول على روابط التنزيل: {error}"
|
||||
"downloadUrlsError": "خطأ في الحصول على روابط التنزيل: {error}",
|
||||
"fileNoLongerAvailable": "الملف لم يعد متاحاً"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "المهمة غير موجودة",
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
"invalidInstrumentalSelection": "instrumental_selection no vàlid. Ha de ser un de: {valid_selections}",
|
||||
"instrumentalSelected": "Pista instrumental seleccionada. S'ha iniciat la generació del vídeo.",
|
||||
"instrumentalSelectionError": "Error en seleccionar la pista instrumental per a la tasca {job_id}: {error}",
|
||||
"downloadUrlsError": "Error en obtenir els URL de descàrrega: {error}"
|
||||
"downloadUrlsError": "Error en obtenir els URL de descàrrega: {error}",
|
||||
"fileNoLongerAvailable": "El fitxer ja no està disponible"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Tasca no trobada",
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
"invalidInstrumentalSelection": "Neplatné instrumental_selection. Musí být jedno z: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumentál vybrán. Začalo generování videa.",
|
||||
"instrumentalSelectionError": "Chyba při výběru instrumentálu pro úlohu {job_id}: {error}",
|
||||
"downloadUrlsError": "Chyba při získávání adres URL ke stažení: {error}"
|
||||
"downloadUrlsError": "Chyba při získávání adres URL ke stažení: {error}",
|
||||
"fileNoLongerAvailable": "Soubor již není dostupný"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Úloha nebyla nalezena",
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
"invalidInstrumentalSelection": "Ugyldig instrumental_selection. Skal være en af: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumental valgt. Videogenerering er startet.",
|
||||
"instrumentalSelectionError": "Fejl ved valg af instrumental for job {job_id}: {error}",
|
||||
"downloadUrlsError": "Fejl ved hentning af download-URL'er: {error}"
|
||||
"downloadUrlsError": "Fejl ved hentning af download-URL'er: {error}",
|
||||
"fileNoLongerAvailable": "Filen er ikke længere tilgængelig"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Jobbet blev ikke fundet",
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
"invalidInstrumentalSelection": "Ungültige instrumental_selection. Muss eines der folgenden sein: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumental ausgewählt. Video-Generierung gestartet.",
|
||||
"instrumentalSelectionError": "Fehler bei der Auswahl des Instrumentals für Auftrag {job_id}: {error}",
|
||||
"downloadUrlsError": "Fehler beim Abrufen der Download-URLs: {error}"
|
||||
"downloadUrlsError": "Fehler beim Abrufen der Download-URLs: {error}",
|
||||
"fileNoLongerAvailable": "Datei nicht mehr verfügbar"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Auftrag nicht gefunden",
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
"invalidInstrumentalSelection": "Μη έγκυρο instrumental_selection. Πρέπει να είναι ένα από τα: {valid_selections}",
|
||||
"instrumentalSelected": "Το instrumental επιλέχθηκε. Ξεκίνησε η δημιουργία βίντεο.",
|
||||
"instrumentalSelectionError": "Σφάλμα κατά την επιλογή instrumental για την εργασία {job_id}: {error}",
|
||||
"downloadUrlsError": "Σφάλμα κατά τη λήψη των URL λήψης: {error}"
|
||||
"downloadUrlsError": "Σφάλμα κατά τη λήψη των URL λήψης: {error}",
|
||||
"fileNoLongerAvailable": "Το αρχείο δεν είναι πλέον διαθέσιμο"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Η εργασία δεν βρέθηκε",
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"authError": "Authentication error: no user identity available",
|
||||
"noDefaultTheme": "No default theme configured. Please contact support or specify a theme_id.",
|
||||
"notFound": "Job not found",
|
||||
"fileNoLongerAvailable": "File no longer available",
|
||||
"noPermissionAccess": "You don't have permission to access this job",
|
||||
"noPermissionEdit": "You don't have permission to edit this job",
|
||||
"noPermissionDelete": "You don't have permission to delete this job",
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
"invalidInstrumentalSelection": "instrumental_selection inválido. Debe ser uno de: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumental seleccionado. Generación de video iniciada.",
|
||||
"instrumentalSelectionError": "Error al seleccionar el instrumental para el trabajo {job_id}: {error}",
|
||||
"downloadUrlsError": "Error al obtener las URLs de descarga: {error}"
|
||||
"downloadUrlsError": "Error al obtener las URLs de descarga: {error}",
|
||||
"fileNoLongerAvailable": "El archivo ya no está disponible"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Trabajo no encontrado",
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
"invalidInstrumentalSelection": "Virheellinen instrumental_selection. Täytyy olla jokin näistä: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumentaali valittu. Videon luonti aloitettu.",
|
||||
"instrumentalSelectionError": "Virhe valittaessa instrumentaalia työlle {job_id}: {error}",
|
||||
"downloadUrlsError": "Virhe haettaessa latausosoitteita: {error}"
|
||||
"downloadUrlsError": "Virhe haettaessa latausosoitteita: {error}",
|
||||
"fileNoLongerAvailable": "Tiedosto ei ole enää saatavilla"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Työtä ei löytynyt",
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
"invalidInstrumentalSelection": "instrumental_selection invalide. Doit être l'un de : {valid_selections}",
|
||||
"instrumentalSelected": "Instrumental sélectionné. La génération de la vidéo a commencé.",
|
||||
"instrumentalSelectionError": "Erreur lors de la sélection de l'instrumental pour la tâche {job_id} : {error}",
|
||||
"downloadUrlsError": "Erreur lors de l'obtention des URL de téléchargement : {error}"
|
||||
"downloadUrlsError": "Erreur lors de l'obtention des URL de téléchargement : {error}",
|
||||
"fileNoLongerAvailable": "Le fichier n'est plus disponible"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Tâche introuvable",
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
"invalidInstrumentalSelection": "בחירת instrumental_selection לא חוקית. חייב להיות אחד מ: {valid_selections}",
|
||||
"instrumentalSelected": "הפלייבק נבחר. יצירת הווידאו התחילה.",
|
||||
"instrumentalSelectionError": "שגיאה בבחירת פלייבק עבור המשימה {job_id}: {error}",
|
||||
"downloadUrlsError": "שגיאה בקבלת כתובות ההורדה: {error}"
|
||||
"downloadUrlsError": "שגיאה בקבלת כתובות ההורדה: {error}",
|
||||
"fileNoLongerAvailable": "הקובץ אינו זמין יותר"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "המשימה לא נמצאה",
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
"invalidInstrumentalSelection": "अमान्य instrumental_selection। इनमें से एक होना चाहिए: {valid_selections}",
|
||||
"instrumentalSelected": "इंस्ट्रुमेंटल चुना गया। वीडियो जनरेशन शुरू हो गया है।",
|
||||
"instrumentalSelectionError": "जॉब {job_id} के लिए इंस्ट्रुमेंटल चुनने में त्रुटि: {error}",
|
||||
"downloadUrlsError": "डाउनलोड URLs प्राप्त करने में त्रुटि: {error}"
|
||||
"downloadUrlsError": "डाउनलोड URLs प्राप्त करने में त्रुटि: {error}",
|
||||
"fileNoLongerAvailable": "फ़ाइल अब उपलब्ध नहीं है"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "जॉब नहीं मिली",
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
"invalidInstrumentalSelection": "Nevažeći instrumental_selection. Mora biti jedno od: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumental je odabran. Generiranje videa je započelo.",
|
||||
"instrumentalSelectionError": "Pogreška pri odabiru instrumentala za zadatak {job_id}: {error}",
|
||||
"downloadUrlsError": "Pogreška pri dohvaćanju URL-ova za preuzimanje: {error}"
|
||||
"downloadUrlsError": "Pogreška pri dohvaćanju URL-ova za preuzimanje: {error}",
|
||||
"fileNoLongerAvailable": "Datoteka više nije dostupna"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Zadatak nije pronađen",
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
"invalidInstrumentalSelection": "Érvénytelen instrumental_selection. A következők egyike kell legyen: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumentális sáv kiválasztva. A videó generálása megkezdődött.",
|
||||
"instrumentalSelectionError": "Hiba a(z) {job_id} feladat instrumentális sávjának kiválasztásakor: {error}",
|
||||
"downloadUrlsError": "Hiba a letöltési URL-ek lekérésekor: {error}"
|
||||
"downloadUrlsError": "Hiba a letöltési URL-ek lekérésekor: {error}",
|
||||
"fileNoLongerAvailable": "A fájl már nem elérhető"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "A feladat nem található",
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
"invalidInstrumentalSelection": "instrumental_selection tidak valid. Harus salah satu dari: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumental dipilih. Pembuatan video dimulai.",
|
||||
"instrumentalSelectionError": "Kesalahan saat memilih instrumental untuk tugas {job_id}: {error}",
|
||||
"downloadUrlsError": "Kesalahan saat mendapatkan URL unduhan: {error}"
|
||||
"downloadUrlsError": "Kesalahan saat mendapatkan URL unduhan: {error}",
|
||||
"fileNoLongerAvailable": "File sudah tidak tersedia"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Tugas tidak ditemukan",
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
"invalidInstrumentalSelection": "instrumental_selection non valido. Deve essere uno tra: {valid_selections}",
|
||||
"instrumentalSelected": "Strumentale selezionata. Generazione del video avviata.",
|
||||
"instrumentalSelectionError": "Errore durante la selezione della strumentale per il lavoro {job_id}: {error}",
|
||||
"downloadUrlsError": "Errore durante il recupero degli URL di download: {error}"
|
||||
"downloadUrlsError": "Errore durante il recupero degli URL di download: {error}",
|
||||
"fileNoLongerAvailable": "File non più disponibile"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Lavoro non trovato",
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
"invalidInstrumentalSelection": "無効な instrumental_selection です。次のいずれかである必要があります: {valid_selections}",
|
||||
"instrumentalSelected": "インストゥルメンタルが選択されました。動画の生成を開始しました。",
|
||||
"instrumentalSelectionError": "ジョブ {job_id} のインストゥルメンタル選択中にエラーが発生しました: {error}",
|
||||
"downloadUrlsError": "ダウンロードURLの取得中にエラーが発生しました: {error}"
|
||||
"downloadUrlsError": "ダウンロードURLの取得中にエラーが発生しました: {error}",
|
||||
"fileNoLongerAvailable": "ファイルはご利用いただけなくなりました"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "ジョブが見つかりません",
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
"invalidInstrumentalSelection": "잘못된 instrumental_selection입니다. 다음 중 하나여야 합니다: {valid_selections}",
|
||||
"instrumentalSelected": "반주가 선택되었습니다. 비디오 생성이 시작되었습니다.",
|
||||
"instrumentalSelectionError": "작업 {job_id}의 반주 선택 중 오류 발생: {error}",
|
||||
"downloadUrlsError": "다운로드 URL을 가져오는 중 오류 발생: {error}"
|
||||
"downloadUrlsError": "다운로드 URL을 가져오는 중 오류 발생: {error}",
|
||||
"fileNoLongerAvailable": "파일을 더 이상 사용할 수 없습니다"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "작업을 찾을 수 없습니다",
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
"invalidInstrumentalSelection": "instrumental_selection tidak sah. Mesti salah satu daripada: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumental dipilih. Penjanaan video bermula.",
|
||||
"instrumentalSelectionError": "Ralat memilih instrumental untuk tugasan {job_id}: {error}",
|
||||
"downloadUrlsError": "Ralat mendapatkan URL muat turun: {error}"
|
||||
"downloadUrlsError": "Ralat mendapatkan URL muat turun: {error}",
|
||||
"fileNoLongerAvailable": "Fail tidak lagi tersedia"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Tugasan tidak dijumpai",
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
"invalidInstrumentalSelection": "Ugyldig instrumental_selection. Må være en av: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumental valgt. Videogenerering startet.",
|
||||
"instrumentalSelectionError": "Feil ved valg av instrumental for jobb {job_id}: {error}",
|
||||
"downloadUrlsError": "Feil ved henting av nedlastings-URL-er: {error}"
|
||||
"downloadUrlsError": "Feil ved henting av nedlastings-URL-er: {error}",
|
||||
"fileNoLongerAvailable": "Filen er ikke lenger tilgjengelig"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Jobben ble ikke funnet",
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
"invalidInstrumentalSelection": "Ongeldige instrumental_selection. Moet een van de volgende zijn: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumental geselecteerd. Videogeneratie is gestart.",
|
||||
"instrumentalSelectionError": "Fout bij het selecteren van instrumental voor taak {job_id}: {error}",
|
||||
"downloadUrlsError": "Fout bij het ophalen van download-URL's: {error}"
|
||||
"downloadUrlsError": "Fout bij het ophalen van download-URL's: {error}",
|
||||
"fileNoLongerAvailable": "Bestand niet meer beschikbaar"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Taak niet gevonden",
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
"invalidInstrumentalSelection": "Nieprawidłowe instrumental_selection. Musi to być jedno z: {valid_selections}",
|
||||
"instrumentalSelected": "Wybrano podkład. Rozpoczęto generowanie wideo.",
|
||||
"instrumentalSelectionError": "Błąd podczas wybierania podkładu dla zadania {job_id}: {error}",
|
||||
"downloadUrlsError": "Błąd podczas pobierania linków: {error}"
|
||||
"downloadUrlsError": "Błąd podczas pobierania linków: {error}",
|
||||
"fileNoLongerAvailable": "Plik nie jest już dostępny"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Nie znaleziono zadania",
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
"invalidInstrumentalSelection": "instrumental_selection inválido. Deve ser um de: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumental selecionado. Geração de vídeo iniciada.",
|
||||
"instrumentalSelectionError": "Erro ao selecionar instrumental para o job {job_id}: {error}",
|
||||
"downloadUrlsError": "Erro ao obter URLs de download: {error}"
|
||||
"downloadUrlsError": "Erro ao obter URLs de download: {error}",
|
||||
"fileNoLongerAvailable": "O arquivo não está mais disponível"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Job não encontrado",
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
"invalidInstrumentalSelection": "instrumental_selection invalid. Trebuie să fie unul dintre: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumental selectat. A început generarea videoclipului.",
|
||||
"instrumentalSelectionError": "Eroare la selectarea instrumentalului pentru jobul {job_id}: {error}",
|
||||
"downloadUrlsError": "Eroare la obținerea adreselor URL de descărcare: {error}"
|
||||
"downloadUrlsError": "Eroare la obținerea adreselor URL de descărcare: {error}",
|
||||
"fileNoLongerAvailable": "Fișierul nu mai este disponibil"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Jobul nu a fost găsit",
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
"invalidInstrumentalSelection": "Недопустимый instrumental_selection. Должно быть одно из: {valid_selections}",
|
||||
"instrumentalSelected": "Инструментал выбран. Началась генерация видео.",
|
||||
"instrumentalSelectionError": "Ошибка при выборе инструментала для задачи {job_id}: {error}",
|
||||
"downloadUrlsError": "Ошибка при получении URL-адресов для скачивания: {error}"
|
||||
"downloadUrlsError": "Ошибка при получении URL-адресов для скачивания: {error}",
|
||||
"fileNoLongerAvailable": "Файл больше недоступен"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Задача не найдена",
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
"invalidInstrumentalSelection": "Neplatný výber inštrumentálu. Musí byť jeden z: {valid_selections}",
|
||||
"instrumentalSelected": "Inštrumentál bol vybraný. Začalo sa generovanie videa.",
|
||||
"instrumentalSelectionError": "Chyba pri výbere inštrumentálu pre úlohu {job_id}: {error}",
|
||||
"downloadUrlsError": "Chyba pri získavaní adries URL na stiahnutie: {error}"
|
||||
"downloadUrlsError": "Chyba pri získavaní adries URL na stiahnutie: {error}",
|
||||
"fileNoLongerAvailable": "Súbor už nie je dostupný"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Úloha sa nenašla",
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
"invalidInstrumentalSelection": "Ogiltigt instrumental_selection. Måste vara en av: {valid_selections}",
|
||||
"instrumentalSelected": "Instrumental vald. Videogenereringen har startat.",
|
||||
"instrumentalSelectionError": "Fel vid val av instrumental för jobb {job_id}: {error}",
|
||||
"downloadUrlsError": "Fel vid hämtning av nedladdningslänkar: {error}"
|
||||
"downloadUrlsError": "Fel vid hämtning av nedladdningslänkar: {error}",
|
||||
"fileNoLongerAvailable": "Filen är inte längre tillgänglig"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Jobbet hittades inte",
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
"invalidInstrumentalSelection": "instrumental_selection ไม่ถูกต้อง ต้องเป็นหนึ่งใน: {valid_selections}",
|
||||
"instrumentalSelected": "เลือกดนตรีบรรเลงแล้ว กำลังเริ่มสร้างวิดีโอ",
|
||||
"instrumentalSelectionError": "เกิดข้อผิดพลาดในการเลือกดนตรีบรรเลงสำหรับงาน {job_id}: {error}",
|
||||
"downloadUrlsError": "เกิดข้อผิดพลาดในการรับ URL สำหรับดาวน์โหลด: {error}"
|
||||
"downloadUrlsError": "เกิดข้อผิดพลาดในการรับ URL สำหรับดาวน์โหลด: {error}",
|
||||
"fileNoLongerAvailable": "ไฟล์ไม่พร้อมใช้งานแล้ว"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "ไม่พบงาน",
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
"invalidInstrumentalSelection": "Mali ang instrumental_selection. Dapat isa sa: {valid_selections}",
|
||||
"instrumentalSelected": "Napili na ang instrumental. Nagsimula na ang paggawa ng video.",
|
||||
"instrumentalSelectionError": "Error sa pagpili ng instrumental para sa job {job_id}: {error}",
|
||||
"downloadUrlsError": "Error sa pagkuha ng mga download URL: {error}"
|
||||
"downloadUrlsError": "Error sa pagkuha ng mga download URL: {error}",
|
||||
"fileNoLongerAvailable": "Hindi na available ang file"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Hindi nahanap ang job",
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
"invalidInstrumentalSelection": "Geçersiz instrumental_selection. Şunlardan biri olmalıdır: {valid_selections}",
|
||||
"instrumentalSelected": "Enstrümantal seçildi. Video oluşturma başladı.",
|
||||
"instrumentalSelectionError": "{job_id} işi için enstrümantal seçme hatası: {error}",
|
||||
"downloadUrlsError": "İndirme URL'lerini alma hatası: {error}"
|
||||
"downloadUrlsError": "İndirme URL'lerini alma hatası: {error}",
|
||||
"fileNoLongerAvailable": "Dosya artık mevcut değil"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "İş bulunamadı",
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
"invalidInstrumentalSelection": "Недійсний instrumental_selection. Має бути одним із: {valid_selections}",
|
||||
"instrumentalSelected": "Інструментал вибрано. Розпочато генерацію відео.",
|
||||
"instrumentalSelectionError": "Помилка вибору інструменталу для завдання {job_id}: {error}",
|
||||
"downloadUrlsError": "Помилка отримання URL-адрес для завантаження: {error}"
|
||||
"downloadUrlsError": "Помилка отримання URL-адрес для завантаження: {error}",
|
||||
"fileNoLongerAvailable": "Файл більше недоступний"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Завдання не знайдено",
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
"invalidInstrumentalSelection": "instrumental_selection không hợp lệ. Phải là một trong: {valid_selections}",
|
||||
"instrumentalSelected": "Đã chọn nhạc nền. Đã bắt đầu tạo video.",
|
||||
"instrumentalSelectionError": "Lỗi khi chọn nhạc nền cho công việc {job_id}: {error}",
|
||||
"downloadUrlsError": "Lỗi khi lấy URL tải xuống: {error}"
|
||||
"downloadUrlsError": "Lỗi khi lấy URL tải xuống: {error}",
|
||||
"fileNoLongerAvailable": "Tệp không còn khả dụng"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "Không tìm thấy công việc",
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
"invalidInstrumentalSelection": "无效的 instrumental_selection。必须是以下之一:{valid_selections}",
|
||||
"instrumentalSelected": "已选择伴奏。已开始生成视频。",
|
||||
"instrumentalSelectionError": "为任务 {job_id} 选择伴奏时出错:{error}",
|
||||
"downloadUrlsError": "获取下载 URL 时出错:{error}"
|
||||
"downloadUrlsError": "获取下载 URL 时出错:{error}",
|
||||
"fileNoLongerAvailable": "文件已不可用"
|
||||
},
|
||||
"review": {
|
||||
"jobNotFound": "未找到任务",
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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
|
||||
@@ -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)
|
||||
|
||||
@@ -2,6 +2,13 @@
|
||||
|
||||
Base URL: `https://api.nomadkaraoke.com` (production) or `http://localhost:8000` (local)
|
||||
|
||||
> **Edge:** production traffic must go through `https://api.nomadkaraoke.com`
|
||||
> (proxied by Cloudflare — WAF + rate limiting). The Cloud Run origin is
|
||||
> **origin-locked**: requests hitting the raw `*.run.app` URL directly are
|
||||
> rejected with `403` unless they carry the Cloudflare-injected `X-Edge-Auth`
|
||||
> header (`/` and `/api/health*` are exempt for probes). See
|
||||
> [ARCHITECTURE.md § Edge Security](ARCHITECTURE.md#edge-security-cloudflare).
|
||||
|
||||
## Authentication
|
||||
|
||||
All endpoints except `/health` and `/api/themes` require authentication.
|
||||
|
||||
+40
-1
@@ -11,9 +11,17 @@
|
||||
│ HTTPS
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ Cloudflare edge (api.nomadkaraoke.com proxied — orange-cloud) │
|
||||
│ WAF (exploit-path block) + rate limit + injects X-Edge-Auth │
|
||||
│ header. See § Edge Security (Cloudflare). │
|
||||
└───────────────────────────┬─────────────────────────────────────┘
|
||||
│ HTTPS (SSL "full")
|
||||
▼
|
||||
┌─────────────────────────────────────────────────────────────────┐
|
||||
│ Backend API (Cloud Run) │
|
||||
│ FastAPI + Python 3.12 │
|
||||
│ https://api.nomadkaraoke.com │
|
||||
│ https://api.nomadkaraoke.com (origin lock: rejects direct- │
|
||||
│ to-origin requests lacking X-Edge-Auth, health/root exempt) │
|
||||
│ │
|
||||
│ Workers: │
|
||||
│ • Audio Worker - Stem separation via Cloud Run GPU (L4) │
|
||||
@@ -61,6 +69,37 @@ Discord-alerting pipeline. `ChunkLoadError` after deploy triggers an automatic
|
||||
hard reload; the `CrashReport` card also checks `/version.json` and shows an
|
||||
"Update now" CTA when the running bundle is stale.
|
||||
|
||||
## Edge Security (Cloudflare)
|
||||
|
||||
`api.nomadkaraoke.com` is proxied through Cloudflare (orange-cloud) — the same
|
||||
zone that already fronts the marketing site, `gen`, `decide`, and the tenant
|
||||
portals. Cut over 2026-07-20 after a vuln-scanner hammered the previously
|
||||
directly-exposed Cloud Run origin. Managed as IaC in
|
||||
`infrastructure/modules/edge_security.py` (`pulumi_cloudflare`).
|
||||
|
||||
**Request path:** client → Cloudflare edge → Cloud Run. At the edge:
|
||||
- **WAF** (`http_request_firewall_custom`) blocks exploit/secret-exposure paths
|
||||
(`/.env`, `/.git/`, `/.ssh/`, `wp-config`, `/etc/passwd`, …) — uses the
|
||||
`contains` operator (regex `matches` needs a Business plan; zone is Free).
|
||||
- **Rate limiting** (`http_ratelimit`) — per-IP flood control (Free-plan limits:
|
||||
`period=10s`, characteristics must include `cf.colo.id`). Excludes
|
||||
`/api/internal/*` (scheduler/Cloud-Tasks cron).
|
||||
- **Origin lock** — a Transform Rule injects a secret `X-Edge-Auth` header
|
||||
(`http_request_late_transform`); the backend's `EdgeAuthMiddleware`
|
||||
(`backend/middleware/edge_auth.py`, `EDGE_AUTH_MODE=enforce`) rejects public
|
||||
requests lacking it, so hitting the raw `*.run.app` origin directly is blocked
|
||||
(health/root exempt for Cloud Run probes). Internal callers reach the backend
|
||||
via `api.nomadkaraoke.com` (Cloud Tasks use `CLOUD_RUN_SERVICE_URL`), so they
|
||||
traverse the edge and carry the header.
|
||||
|
||||
**SSL:** zone TLS mode is **"full"** (not strict). The Cloud Run domain-mapping
|
||||
managed cert cannot provision behind Cloudflare (ACME challenge not visible), but
|
||||
"full" mode doesn't validate the origin cert, so the edge works and is
|
||||
**renewal-safe** — no run.app Origin Rule or load balancer needed. **Never switch
|
||||
the zone to "full (strict)".** Full rationale + cutover runbook:
|
||||
`docs/archive/2026-07-20-edge-security-hardening-plan.md` and
|
||||
`docs/archive/2026-07-20-edge-security-cutover-runbook.md`.
|
||||
|
||||
## Processing Pipeline
|
||||
|
||||
```text
|
||||
|
||||
+127
-2
@@ -6,6 +6,44 @@ Key insights for future AI agents working on this codebase.
|
||||
|
||||
---
|
||||
|
||||
## Cloudflare edge in front of Cloud Run — the SSL "dragon" (Jul 2026)
|
||||
|
||||
Putting `api.nomadkaraoke.com` behind Cloudflare (WAF/rate-limit/origin-lock)
|
||||
surfaced several non-obvious gotchas. See `infrastructure/modules/edge_security.py`
|
||||
and `docs/archive/2026-07-20-edge-security-*.md`.
|
||||
|
||||
- **Cloud Run domain-mapping managed certs cannot provision behind Cloudflare.**
|
||||
Even with a correct grey-cloud CNAME → `ghs.googlehosted.com` (right DNS,
|
||||
propagated, no CAA), Google's ACME challenge is "not visible through the public
|
||||
internet" and the cert stays `pending` forever. Recreating the mapping doesn't
|
||||
help. **This does not matter** because the zone SSL mode is **"full" (not
|
||||
strict)**: Cloudflare encrypts to the origin but doesn't validate its cert, so
|
||||
the edge works regardless and is **renewal-safe** (a never-provisioning /
|
||||
never-renewing cert can't cause a 525 when the cert isn't checked). **Rule:
|
||||
keep the zone on "full", never "full (strict)".** The much-feared run.app
|
||||
SNI-override Origin Rule and a GCP load balancer are both unnecessary — and the
|
||||
Origin Rule is blocked anyway by the zone's singleton `http_request_origin`
|
||||
entrypoint (already holds a flacfetch prod rule).
|
||||
- **A proxied (orange) record blocks cert issuance** (DNS points at Cloudflare,
|
||||
not `ghs`) — so if you ever DO need the managed cert, create grey → provision →
|
||||
flip orange. For the prod cutover this was moot: `api`'s cert already existed
|
||||
and "full" mode tolerates it, so the cutover was just the grey→orange flip.
|
||||
- **Cloudflare Free-plan WAF/rate-limit constraints (fail at apply time):** the
|
||||
regex `matches` operator needs Business+ (use `contains`); rate-limit `period`
|
||||
must be `10`s and `characteristics` MUST include `cf.colo.id` (per-colo
|
||||
counting); managed OWASP ruleset is Pro+ only.
|
||||
- **Origin lock without breaking internal callers:** all internal traffic (Cloud
|
||||
Tasks via `CLOUD_RUN_SERVICE_URL`, schedulers, frontend) reaches the backend
|
||||
through `api.nomadkaraoke.com`, so it traverses Cloudflare and carries the
|
||||
injected `X-Edge-Auth` header. Validated by running the prod E2E in `warn` mode
|
||||
first and confirming **zero** missing-header warnings before flipping to
|
||||
`enforce`. Health/root paths are exempt (Cloud Run probes hit the origin
|
||||
directly).
|
||||
- **Applying from a worktree:** the prod Pulumi stack shows benign cross-worktree
|
||||
Cloud Function source-archive drift (last applied from a different worktree) —
|
||||
apply edge changes with `pulumi up --target <urn>` to avoid touching it. CI
|
||||
does NOT auto-run `pulumi up` (apply locally before merge).
|
||||
|
||||
## Magic-link auth vs. email link-scanners (Jul 2026)
|
||||
|
||||
- **Never auto-consume a single-use token on page render.** `/auth/verify` used to
|
||||
@@ -220,7 +258,7 @@ When two sequential human review steps can be combined into one, do it. We origi
|
||||
|
||||
3. **`compute.instances.start` returns `503 SERVICE_UNAVAILABLE` for transient backend stress, not just capacity.** Initial fix only classified `ZONE_RESOURCE_POOL_EXHAUSTED` as transient/recoverable; `503` got the generic `EncodingWorkerStartError` and never triggered multi-zone fallback. Either treat the `EncodingWorkerStartError` parent class as fallback-worthy (what we did, PR #750) or expand the capacity error code list.
|
||||
|
||||
4. **GCE `c4d-highcpu-32` capacity in `us-central1-f` is unreliable enough to be useless as a fallback.** Provisioning failed there at create time on multiple attempts (the very thing the fallback is meant to mitigate). `-a` and `-b` are stable. (PR #749)
|
||||
4. **GCE `c4d-highcpu-32` capacity in `us-central1-f` is unreliable enough to be useless as a fallback.** Provisioning failed there at create time on multiple attempts (the very thing the fallback is meant to mitigate). `-a` and `-b` were stable *at the time*. (PR #749) — **Superseded 2026-08-12:** see "Machine-family diversification" below; `-a`/`-b` are NOT immune — the whole `c4d-highcpu-32` family stocked out region-wide (a/b/c at once).
|
||||
|
||||
5. **`google-auth ≥ 2.40` uses mTLS-over-HTTPS for the GCE metadata server when `/run/google-mds-mtls/` certs exist on the VM.** Newer GCE images ship those certs; the mTLS handshake then fails with `SSL CERTIFICATE_VERIFY_FAILED` on freshly-provisioned VMs. The worker can't refresh its SA token, all GCS reads/writes break. Fix: set `GCE_METADATA_MTLS_MODE=none` in the systemd EnvironmentFile to force HTTP-on-port-80 metadata access. (PR #750)
|
||||
|
||||
@@ -228,8 +266,21 @@ When two sequential human review steps can be combined into one, do it. We origi
|
||||
|
||||
7. **`_request_with_retry` captured the URL once before the retry loop.** When the warmup-fallback updated the active URL override (e.g., switching from a dead primary to a live fallback), the retry loop kept hitting the original (dead) URL for all 8 attempts. Fix: thread the relative `path` through and re-resolve `_get_worker_url() + path` on retries after warmup has fired. (PR #752)
|
||||
|
||||
### Machine-family diversification (August 2026)
|
||||
|
||||
**Incident 2026-08-12:** `c4d-highcpu-32` hit a **region-wide `ZONE_RESOURCE_POOL_EXHAUSTED` stockout across `us-central1-a`, `-b` AND `-c` simultaneously.** Because the primary pair *and* both fallbacks were all the same machine family, every lane in `ensure_any_running` failed at once. Effects:
|
||||
- **Preview** (`POST /api/review/{id}/preview-video`) fell through to slow local Cloud-Run encoding (~130–160 s), which **exceeds Cloudflare's ~100 s edge timeout** → browser got a **524 / "NetworkError when attempting to fetch resource"** even though the backend actually returned 200. The 524 and the NetworkError are the same event; backend logs showing 200 are misleading because the client was already disconnected.
|
||||
- **Render** parked in `RENDER_PENDING_CAPACITY` and auto-retried (safe only if capacity returns within 24 h).
|
||||
|
||||
**Root lesson:** zone diversity is not enough — a stockout is per **(machine family × region)**, and it can take out *every* zone of a family in a region at once. The fallback fleet must diversify **machine family**, not just zone.
|
||||
|
||||
**Fix (Option B):** added `n2-highcpu-32` capacity fallbacks (`encoding-worker-fallback-n2c`/`-n2f` in `us-central1-c`/`-f`) — an independent, much deeper capacity pool. Runtime needed **no change** (`ensure_any_running` already iterates arbitrary `{vm,zone,ip}` candidates; `start_vm(zone=...)` is zone-generic); it's purely `infrastructure/config.py::EncodingWorkerConfig.FALLBACKS` (now carries per-VM `machine_type` + `disk_type`) + `encoding_worker_vm.py` + a new `encoding-worker-fallback-vms` secret version. Gotchas:
|
||||
- **n2 does not support `hyperdisk-balanced`** → its fallbacks use `pd-balanced` boot disks (per-VM `disk_type`).
|
||||
- **Keep the existing `-a`/`-b` entries byte-identical** (including the IP `description` string!) — changing even the Address description forces the Address to replace, which cascades to *replacing the c4d VM* (needs the very capacity that's out). Always `pulumi preview` and confirm the diff is purely additive (`+N to create`, no `+-replace` on existing encoding-worker VMs) before `pulumi up`.
|
||||
- **Preview-timeout is a separate, still-open fragility:** a synchronous preval that outlives the ~100 s edge timeout gives users an opaque 524. Fast-follow options: make preview async/polling (like render), fail fast to local encode when all VM starts stock out, or raise the edge read-timeout for that route.
|
||||
|
||||
**Architecture summary (post-fixes):**
|
||||
- 4 GCE encoding workers: 2 primaries in `us-central1-c` (blue-green) + 2 capacity fallbacks in `us-central1-a` and `us-central1-b`. All idle by default; started on demand.
|
||||
- 6 GCE encoding workers: 2 primaries in `us-central1-c` (blue-green, `c4d-highcpu-32`) + 2 `c4d` capacity fallbacks in `us-central1-a`/`-b` + 2 `n2-highcpu-32` fallbacks in `us-central1-c`/`-f`. All idle by default; started on demand.
|
||||
- `EncodingWorkerCandidate` list iterated in `ensure_any_running` — primary first, fallbacks in declared order. Capacity errors fall through to next candidate; non-capacity start errors also fall through (broadened in PR #750).
|
||||
- New `RENDER_PENDING_CAPACITY` job state for transient infra failures — different from `FAILED` (which is for unrecoverable bugs).
|
||||
- Cloud Scheduler fires `/api/internal/retry-pending-render-jobs` every 5 min; 24h hard timeout per job.
|
||||
@@ -1399,3 +1450,77 @@ 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.
|
||||
|
||||
## Server-Created Jobs Must Fit the Dashboard's UI Assumptions (Aug 2026)
|
||||
|
||||
**Symptom:** A paid "Made for you" Stripe order auto-created its job perfectly
|
||||
(webhook → `_handle_made_for_you_order`, job `b092648c` at
|
||||
`awaiting_audio_selection` with 10 audio sources found, admin notified) — yet
|
||||
the operator saw *nothing* on the dashboard and re-created the job by hand,
|
||||
producing a duplicate.
|
||||
|
||||
**Root cause:** Two UI assumptions that only hold for *self-service* jobs:
|
||||
1. The dashboard filtered out **all** `awaiting_audio_selection` jobs, because
|
||||
for a self-service user those are mid-wizard and owned by the guided-flow
|
||||
component. Made-for-you jobs are created **server-side** by the Stripe
|
||||
webhook, so they sit at that same status with **no active wizard session** —
|
||||
and got silently dropped.
|
||||
2. The admin notification email's "Open Job" button linked to bare `/app/`,
|
||||
i.e. the exact page that filters the job out.
|
||||
|
||||
**Fix (v0.192.5):** `shouldShowJobOnDashboard()` keeps `made_for_you` jobs
|
||||
visible at `awaiting_audio_selection` (hiding only self-service ones); added
|
||||
`made_for_you`/`customer_email` to `SUMMARY_FIELD_PATHS` so the summary payload
|
||||
carries the flag; the email now deep-links to
|
||||
`/app/?admin_token=…&status=awaiting_audio_selection` (dashboard honors a
|
||||
`status` URL param).
|
||||
|
||||
**Principles for next time:**
|
||||
- A UI filter written for one creation path (interactive wizard) will silently
|
||||
swallow items from another path (server/webhook). When adding a server-created
|
||||
job that reuses an interactive status, audit every place that status is
|
||||
special-cased in the frontend.
|
||||
- A notification's action link must point at a view that actually **renders the
|
||||
item** — verify the deep-link, don't assume "/app shows everything".
|
||||
- Any field a frontend filter branches on must be in `SUMMARY_FIELD_PATHS`, or
|
||||
it arrives `undefined` and the branch silently takes the wrong path.
|
||||
@@ -43,6 +43,7 @@
|
||||
| **i18n / Multilingual (frontend)** | Working (next-intl, en/es/de, 1062 strings, [locale] routing) |
|
||||
| **Referral system** | Working (referral links with configurable discounts, 20% cash kickback via Stripe Connect, auto-payout at $20) |
|
||||
| **Error monitor** | New (Cloud Run Job every 15 min — log collection, normalization, LLM dedup/grouping, Discord alerts, auto-resolution, daily digest) |
|
||||
| **Edge security (Cloudflare)** | Working (api.nomadkaraoke.com proxied — WAF + rate limit + origin lock enforced; 2026-07-20) |
|
||||
|
||||
## Known Issues
|
||||
|
||||
@@ -54,6 +55,8 @@
|
||||
|
||||
## Recent Changes
|
||||
|
||||
- **Cloudflare Edge Security for the Backend API** (2026-07-20): `api.nomadkaraoke.com` is now proxied through Cloudflare (WAF + rate limiting + origin lock), after a vuln-scanner hammered the previously directly-exposed Cloud Run origin. WAF blocks exploit/secret-exposure paths (`contains` operator — regex needs a Business plan); per-IP rate limiting excludes `/api/internal/*`; a Transform Rule injects a secret `X-Edge-Auth` header that the backend's `EdgeAuthMiddleware` (`EDGE_AUTH_MODE=enforce`) requires, blocking direct-to-`*.run.app` bypass (health/root exempt). Key finding: the Cloud Run managed cert can't provision behind Cloudflare, but zone SSL mode "full" (not strict) doesn't validate the origin cert, so it works and is renewal-safe — **never switch the zone to "full (strict)".** Managed as IaC in `infrastructure/modules/edge_security.py`. Also retuned the "High Error Rate" alert to 5xx-only (scanner 404s no longer page). See [ARCHITECTURE.md § Edge Security](ARCHITECTURE.md#edge-security-cloudflare), [LESSONS-LEARNED.md](LESSONS-LEARNED.md#cloudflare-edge-in-front-of-cloud-run--the-ssl-dragon-jul-2026), and [archive/2026-07-20-edge-security-cutover-runbook.md](archive/2026-07-20-edge-security-cutover-runbook.md).
|
||||
|
||||
- **AI Auto-Correct Suggestions** (2026-06-11): Opt-in AI correction suggestions in the lyrics review UI — the third attempt at lyrics auto-correction, redesigned around the failures that led to disabling it in PR #321 (Jan 2026). One whole-song LLM call (default Gemini 3.1 Pro via Vertex, `AUTO_CORRECT_MODEL` env) compares the working transcription against reference lyrics and returns word-id-keyed suggestions; nothing is applied until the reviewer accepts each one (or accept-all) in a dedicated panel with per-row undo. New `POST /api/review/{job_id}/auto-correct` endpoint + `backend/services/auto_correct/`; frontend `useAutoCorrect` hook, `AutoCorrectModal` (knobs: adlib removal, insertions, confidence filter), `AutoCorrectPanel`. Accept/reject decisions land in the EditLog (`ai_suggestion_*` ops) to measure real accept rates. 5-model offline eval over 30 real jobs with human ground truth picked the default (Fable 5 ≈ Gemini 3.1 Pro ≫ GPT-5.2, which made lyrics worse). See [archive/2026-06-10-lyrics-auto-correction-reeval-plan.md](archive/2026-06-10-lyrics-auto-correction-reeval-plan.md).
|
||||
|
||||
- **Syllable-Aware Custom Lyrics** (2026-05-02): Enhanced the Custom Lyrics LLM mode with syllable-count validation and a per-line repair loop. Backend computes per-line target/candidate syllable counts via the existing `SyllablesMatchHandler` engine and re-prompts Gemini up to 3 times until lines fit budget (Δ ≤ 2 default, configurable via Verbatim/Loose/Balanced/Tight/Strict strictness). New `GenerationSettings` (`allow_reword`, `allow_omit`, `fixed_line_count`, `strictness`) exposed in the modal as a collapsible settings panel. New `CustomLyricsPreview` component shows per-line syllable annotations (target / actual / Δ) with severity badges and stop-reason banners. Variable-line-count mode (when `fixed_line_count=false`) re-times segments proportionally. Eval harness with disk-backed Gemini cache, per-line + per-fixture + corpus scorers, and 4 fixtures (1 from production, 3 handcrafted public-domain). v1-ships criteria validation (Year 5 ≥75% pass@2, macro corpus ≥70% pass@2) deferred to post-merge. See [archive/2026-05-02-custom-lyrics-syllable-aware-design.md](archive/2026-05-02-custom-lyrics-syllable-aware-design.md) and [archive/2026-05-02-custom-lyrics-syllable-aware-plan.md](archive/2026-05-02-custom-lyrics-syllable-aware-plan.md).
|
||||
|
||||
+101
-9
@@ -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:**
|
||||
|
||||
@@ -100,6 +102,46 @@ gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
|
||||
|
||||
---
|
||||
|
||||
## Render fails: `No module named '<pkg>'` (e.g. tenacity) on encoding worker
|
||||
|
||||
**Symptoms:** A render fails with `OutputGenerator not available: No module named 'tenacity'. The karaoke-gen wheel must be installed. Check that ensure_latest_wheel() succeeded.` (or another missing package). Retries hit the same VM and fail identically.
|
||||
|
||||
**Cause:** A freshly-provisioned encoding-worker VM comes up with only a handful of packages baked into the Packer image, and boot installs the wheel with `--no-deps`. The full karaoke-gen dependency tree (torch, langchain, tenacity, …) is installed lazily at the first job by `ensure_latest_wheel()`. If that install fails or partially completes, the venv is left importable-but-incomplete and the render dies on the first missing import. First seen 2026-08-13 (job 233b9536) on a fresh `n2-highcpu-32` fallback added in #903.
|
||||
|
||||
**Fixed in v0.192.7:** `ensure_latest_wheel()` now downloads only the single latest wheel (was: copying the entire ~6 GiB `wheels/` dir every job with a 60 s timeout), retries the install (3× at 900 s), and **verifies the render/encode import chain** before returning — a clean `pip` exit is no longer trusted. Callers fail the job with a clear retryable error instead of proceeding. Fresh workers pick this up via the wheel-at-boot.
|
||||
|
||||
**Manual repair (if a running VM is stuck on an old wheel):** the venv is root-owned, so use `sudo`:
|
||||
|
||||
```bash
|
||||
# Identify the running worker
|
||||
gcloud compute instances list --project=nomadkaraoke --filter="name~encoding AND status=RUNNING"
|
||||
|
||||
# Repair: install the latest versioned wheel WITH deps, then verify
|
||||
gcloud compute ssh <worker-name> --zone=<zone> --project=nomadkaraoke --tunnel-through-iap --command='
|
||||
V=$(gsutil ls "gs://karaoke-gen-storage-nomadkaraoke/wheels/karaoke_gen-*.whl" | grep -v current | sort -V | tail -1)
|
||||
WHEEL="/tmp/$(basename "$V")" # keep the PEP 427 filename so pip accepts it
|
||||
gsutil cp "$V" "$WHEEL"
|
||||
sudo /opt/encoding-worker/venv/bin/python -m pip install --upgrade "$WHEEL"
|
||||
/opt/encoding-worker/venv/bin/python -c "import tenacity; from karaoke_gen.lyrics_transcriber.output.generator import OutputGenerator; from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations; from backend.services.local_encoding_service import LocalEncodingService; print(\"OK\")"
|
||||
'
|
||||
```
|
||||
|
||||
**Re-render a job that already failed past review:** a failed job is terminal, and admin `/jobs/{id}/reset` has no `review_complete` target. Reset to `awaiting_review`, then re-submit the review (reuses the existing GCS corrections):
|
||||
|
||||
```bash
|
||||
ADMIN_TOKEN=$(gcloud secrets versions access latest --secret=admin-tokens --project=nomadkaraoke | cut -d',' -f1)
|
||||
curl -s -X POST "https://api.nomadkaraoke.com/api/admin/jobs/<id>/reset" \
|
||||
-H "X-Admin-Token: $ADMIN_TOKEN" -H "Content-Type: application/json" \
|
||||
-d '{"target_state": "awaiting_review"}'
|
||||
# instrumental_selection is "clean" or "with_backing" (read prior value from Firestore state_data before reset)
|
||||
curl -s -X POST "https://api.nomadkaraoke.com/api/review/<id>/complete?review_token=<token>" \
|
||||
-H "Content-Type: application/json" -d '{"instrumental_selection": "with_backing"}'
|
||||
```
|
||||
|
||||
Do **not** reset to `instrumental_selected` — that triggers the final video worker, which needs the (missing) lyrics video and fails "prerequisites not met"; and triggering render-video from `instrumental_selected` gets superseded (invalid `instrumental_selected → rendering_video`).
|
||||
|
||||
---
|
||||
|
||||
## GDrive validator reports sequence gap
|
||||
|
||||
**Symptoms:** Email from "Nomad Karaoke GDrive Validator" reporting `SEQUENCE GAPS: MP4: missing XXXX`.
|
||||
@@ -195,11 +237,47 @@ 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).
|
||||
**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. 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).
|
||||
|
||||
The fallback fleet is diversified by **machine family** (since incident 2026-08-12): `c4d-highcpu-32` primaries in `us-central1-c` + `c4d` fallbacks in `-a`/`-b` + `n2-highcpu-32` fallbacks (`encoding-worker-fallback-n2c`/`-n2f`) in `-c`/`-f`. The n2 pool is much deeper, so a full `c4d` region-wide stockout (which took out a/b/c at once on 2026-08-12) should now still find n2 capacity. If you see EVERY candidate (c4d **and** n2) return stockout, that's a genuinely severe regional event — wait, or add a cross-region fallback.
|
||||
|
||||
**Related symptom — preview 524 / "NetworkError":** the same capacity exhaustion also makes `POST /api/review/{id}/preview-video` fall back to slow local encoding (~130–160 s), which exceeds Cloudflare's ~100 s edge timeout → the browser shows a **524** or Firefox *"NetworkError when attempting to fetch resource"* even though the backend returns 200. If a user reports the review preview failing, check for a concurrent stockout; the already-rendered preview mp4 (if any) is fetchable via `GET /api/review/{id}/preview-video/{hash}` (302 → signed GCS URL) with a Bearer admin token. Completing the review does **not** require the preview.
|
||||
|
||||
**Check how many retries have run:**
|
||||
```bash
|
||||
@@ -218,13 +296,27 @@ curl -X POST https://api.nomadkaraoke.com/api/internal/retry-pending-render-jobs
|
||||
-H "X-Admin-Token: $ADMIN_TOKEN"
|
||||
```
|
||||
|
||||
**Verify GCE has any capacity right now:**
|
||||
**Verify GCE has any capacity right now** (the real error reason is in the Compute op, not the app's "503"):
|
||||
```bash
|
||||
# If this returns ZONE_RESOURCE_POOL_EXHAUSTED across all 4 zones, just wait
|
||||
for ZONE in us-central1-a us-central1-b us-central1-c us-central1-f; do
|
||||
gcloud compute instances describe "encoding-worker-fallback-${ZONE##*-}" \
|
||||
--zone=$ZONE --project=nomadkaraoke --format='value(status)' 2>/dev/null \
|
||||
&& echo " ↑ in $ZONE"
|
||||
# See the actual stockout reason (ZONE_RESOURCE_POOL_EXHAUSTED / stockout) + vmType
|
||||
gcloud logging read 'protoPayload.methodName:"instances.start" AND "ZONE_RESOURCE_POOL_EXHAUSTED"' \
|
||||
--project=nomadkaraoke --freshness=30m --limit=5 \
|
||||
--format='value(timestamp, protoPayload.resourceName)'
|
||||
|
||||
# Try starting a fallback in each family; if BOTH c4d and n2 refuse, it's severe — wait.
|
||||
# Synchronous (no --async) so the start op surfaces stockout inline, and we capture
|
||||
# gcloud's own exit status rather than piping (a pipe would return sed's status).
|
||||
for VM_ZONE in \
|
||||
"encoding-worker-fallback-a:us-central1-a" \
|
||||
"encoding-worker-fallback-b:us-central1-b" \
|
||||
"encoding-worker-fallback-n2c:us-central1-c" \
|
||||
"encoding-worker-fallback-n2f:us-central1-f"; do
|
||||
VM="${VM_ZONE%%:*}"; ZONE="${VM_ZONE##*:}"
|
||||
if OUT=$(gcloud compute instances start "$VM" --zone="$ZONE" --project=nomadkaraoke 2>&1); then
|
||||
echo "$VM: OK (started — remember to stop it)"
|
||||
else
|
||||
echo "$VM: FAILED — $(echo "$OUT" | tr '\n' ' ')"
|
||||
fi
|
||||
done
|
||||
```
|
||||
|
||||
|
||||
@@ -96,35 +96,31 @@ CI env) is already in this branch.
|
||||
|
||||
---
|
||||
|
||||
## Phase B — Validate everything on staging 🟢 ✅
|
||||
## Phase B — Validate everything on staging 🟢 ✅ DONE (2026-07-20)
|
||||
|
||||
6. **The SSL dragon (grey → provision → orange).** With the record grey-cloud,
|
||||
wait for the Cloud Run managed cert to provision (DNS must resolve to `ghs`
|
||||
for ACME — a proxied record blocks issuance):
|
||||
```bash
|
||||
gcloud beta run domain-mappings describe --domain api-edge-test.nomadkaraoke.com \
|
||||
--region us-central1 --project nomadkaraoke \
|
||||
--format='value(status.conditions[].type, status.conditions[].status)'
|
||||
# wait until Ready=True / CertificateProvisioned=True (~15 min)
|
||||
```
|
||||
Then flip the staging record to **orange-cloud** and choose SSL mode:
|
||||
> **RESULT: staging validation PASSED.** With the zone on SSL "full" mode, the
|
||||
> managed cert does NOT need to provision — flip straight to orange and it works.
|
||||
> (The cert stays "pending" behind Cloudflare forever; "full" mode ignores it.
|
||||
> See plan §4.) Recorded here for the eventual prod cutover.
|
||||
|
||||
6. Flip the staging record to **orange-cloud** — no cert wait needed in "full"
|
||||
mode:
|
||||
```bash
|
||||
pulumi config set edge:proxyStaging true
|
||||
pulumi up --target 'urn:...:DnsRecord::api-edge-test-dns'
|
||||
```
|
||||
Zone SSL/TLS mode should be **Full (strict)**; if the proxied host then throws
|
||||
525/handshake, step down the ladder (step 8).
|
||||
7. Run the verification suite against **staging** (`HOST=api-edge-test.nomadkaraoke.com`):
|
||||
Keep zone SSL/TLS mode = **Full** (NOT strict — strict would 525 since the
|
||||
managed cert can't validate behind CF).
|
||||
7. Verification suite against **staging** (`HOST=api-edge-test.nomadkaraoke.com`) —
|
||||
**actual results 2026-07-20 in `[ ]`**:
|
||||
```bash
|
||||
HOST=api-edge-test.nomadkaraoke.com
|
||||
curl -sI https://$HOST/ | grep -iE 'server|cf-ray' # expect server: cloudflare + cf-ray
|
||||
curl -sI https://$HOST/ | grep -iE 'server|cf-ray' # [200, server: cloudflare, cf-ray ✅]
|
||||
for p in '.env' 'home/root/.ssh/id_rsa' 'wp-config.php' 'etc/passwd'; do
|
||||
echo -n "$p -> "; curl -s -o /dev/null -w '%{http_code}\n' "https://$HOST/$p"; done # expect 403
|
||||
curl -s -o /dev/null -w 'health %{http_code}\n' https://$HOST/api/health # expect 200
|
||||
for i in $(seq 1 120); do curl -s -o /dev/null -w '%{http_code} ' https://$HOST/api/health; done; echo # rate-limit trips
|
||||
echo -n "$p -> "; curl -s -o /dev/null -w '%{http_code}\n' "https://$HOST/$p"; done # [all 403 ✅]
|
||||
curl -s -o /dev/null -w 'health %{http_code}\n' https://$HOST/api/health # [200 ✅]
|
||||
```
|
||||
✅ cf-ray present, exploit paths 403, health 200, rate-limit engages, **no
|
||||
525/SSL handshake errors**.
|
||||
✅ cf-ray present, exploit paths 403, health 200, **no 525** — edge fully works.
|
||||
|
||||
8. **If SSL errors appear**, step down the ladder (edit `edge_security.py` /
|
||||
zone SSL mode) and re-test:
|
||||
|
||||
@@ -87,37 +87,36 @@ without re-architecting.
|
||||
(default false), so merging it can't make `pulumi up` attempt Cloudflare calls
|
||||
with the wrong token.
|
||||
|
||||
## 4. The dragon: Cloud Run domain mapping × Cloudflare proxy (TLS)
|
||||
## 4. The dragon: Cloud Run domain mapping × Cloudflare proxy (TLS) — RESOLVED
|
||||
|
||||
The reason the API is grey-cloud today is almost certainly the **managed-cert ×
|
||||
proxy interaction**:
|
||||
**Investigated + resolved live on staging 2026-07-20.** The theory:
|
||||
- A Cloud Run domain mapping provisions a Google-managed cert via ACME, which
|
||||
needs the host to resolve directly to `ghs` — a proxied (orange) record blocks
|
||||
issuance; and renewal (~90d) could fail behind the proxy → delayed 525/526.
|
||||
|
||||
- A Cloud Run domain mapping provisions a **Google-managed TLS cert** via ACME,
|
||||
which needs the hostname to resolve to `ghs.googlehosted.com` for validation.
|
||||
- With Cloudflare orange-cloud + **Full (strict)**, Cloudflare connects to the
|
||||
origin over TLS and validates the origin cert for `api.nomadkaraoke.com`. Works
|
||||
**while the cert is valid**.
|
||||
- **The delayed failure:** the managed cert must **renew** (~every 90d). Renewal
|
||||
validation traffic can be broken by the proxy terminating TLS/ALPN → renewal
|
||||
fails weeks later → **525/526 SSL errors** even though it "worked at first."
|
||||
This matches the "it worked then broke" memory.
|
||||
**What we actually found (staging `api-edge-test.nomadkaraoke.com`):**
|
||||
- Fresh managed-cert provisioning genuinely **does not work** behind Cloudflare
|
||||
even grey-cloud — the ACME challenge is never "visible" (confirmed correct DNS,
|
||||
propagation, no CAA; recreating the mapping didn't help). So the managed cert
|
||||
stays "pending" indefinitely.
|
||||
- **BUT the zone SSL mode is "full" (not strict)** — and in "full" mode Cloudflare
|
||||
encrypts to the origin **without validating the origin cert**. So through the
|
||||
proxy, the managed cert's status is **irrelevant**: `ghs` serves the request
|
||||
over TLS that "full" mode accepts, and Cloud Run routes via the domain mapping.
|
||||
- **Result: the proxied edge works end-to-end** — `GET /` → 200 + `cf-ray` + real
|
||||
backend JSON; exploit paths → 403 (WAF); `/api/health` → 200.
|
||||
|
||||
**Mitigation = an SSL fallback ladder, proven on staging (§5, Phase B):**
|
||||
**Conclusion — no ladder, no run.app Origin Rule, no LB needed.** "Full" mode is
|
||||
inherently renewal-safe (a never-provisioning / never-renewing managed cert can't
|
||||
525 when the cert isn't validated). The only rule: **keep the zone on "full"; do
|
||||
NOT switch to "full (strict)"** unless the managed cert is actually valid (it
|
||||
can't be, behind CF). The run.app-SNI-override (Origin Rule) was implemented and
|
||||
then removed — it's blocked anyway by the zone's singleton `http_request_origin`
|
||||
entrypoint (already used by a flacfetch prod rule) and adds no benefit over "full".
|
||||
|
||||
1. **Full (strict) on the existing mapping** — simplest; test first.
|
||||
2. **Full (not strict)** — Cloudflare encrypts to origin but skips strict cert
|
||||
validation, so a renewal hiccup won't 525. Slightly weaker (CF↔Google hop),
|
||||
low risk on Google's network.
|
||||
3. **SNI-override to the `*.run.app` origin** (most robust): a Cloudflare **Origin
|
||||
Rule** sets origin host + SNI to `karaoke-backend-…-uc.a.run.app` (whose
|
||||
Google cert is always valid and never our concern), while the public host stays
|
||||
`api.nomadkaraoke.com`. Sidesteps the managed-cert dependency entirely. Requires
|
||||
the backend to accept the run.app Host (ingress=all already does) and CORS to
|
||||
allow the public origin (already `*`).
|
||||
|
||||
We pick the highest rung that passes on staging and **leave staging proxied for a
|
||||
few days** to smoke-test before prod cutover. If we want to fully eliminate the
|
||||
cert dragon long-term, the follow-up is a GCP HTTPS LB (deferred — cost/scope).
|
||||
**Prod cutover is therefore simple:** the prod `api` domain mapping already has a
|
||||
(historically-provisioned) cert, and "full" mode tolerates it regardless — so the
|
||||
cutover is just the DNS proxy flip; no cert wait, no 525 risk.
|
||||
|
||||
## 5. Phased plan (zero-downtime by construction)
|
||||
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
# Encoding worker capacity resilience — machine-type diversification (Option B)
|
||||
|
||||
**Date:** 2026-08-12
|
||||
**Trigger:** Live incident — `POST /api/review/98bbd8b0/preview-video` returned 524 (Cloudflare
|
||||
edge timeout) → browser "NetworkError". Final render for the same job also at risk.
|
||||
|
||||
## Root cause (confirmed via prod logs)
|
||||
|
||||
`c4d-highcpu-32` hit a **region-wide `ZONE_RESOURCE_POOL_EXHAUSTED` stockout** across
|
||||
`us-central1-a`, `-b`, and `-c` simultaneously. The encoding-worker fleet is:
|
||||
|
||||
- primary pair `encoding-worker-{a,b}` — `c4d-highcpu-32`, `us-central1-c`
|
||||
- fallbacks `encoding-worker-fallback-{a,b}` — `c4d-highcpu-32`, `us-central1-a` / `-b`
|
||||
|
||||
Every lane is the **same machine family in the same region**, so a single-family stockout
|
||||
exhausts all of them. `ensure_any_running` iterated all candidates, all returned 503/stockout,
|
||||
and:
|
||||
|
||||
- **Preview** fell back to slow local Cloud-Run encoding (~130–160 s) → exceeded Cloudflare's
|
||||
~100 s edge timeout → **524 / NetworkError** (backend actually returned 200, but the client
|
||||
was already disconnected).
|
||||
- **Render** parks in `RENDER_PENDING_CAPACITY` and auto-retries every 5 min (24 h window) —
|
||||
safe only if c4d capacity returns within 24 h.
|
||||
|
||||
Prior work (May 2026) already flagged this fragility: *gotcha #5 — "c4d-highcpu-32 capacity in
|
||||
us-central1-f is unreliable."* We diversified **zones** but never **machine family**.
|
||||
|
||||
## Fix (Option B): diversify the fallback fleet across an independent capacity pool
|
||||
|
||||
Add fallback VMs on **`n2-highcpu-32`** (Intel Cascade/Ice Lake) — the deepest, most broadly
|
||||
available pool on GCP — in `us-central1`. A c4d shortage cannot exhaust the n2 pool.
|
||||
|
||||
Decisions (confirmed with operator):
|
||||
- Machine type: **n2-highcpu-32** (deepest pool). n2 does **not** support `hyperdisk-balanced`,
|
||||
so these VMs use **`pd-balanced`** boot disks (per-VM disk-type override).
|
||||
- Region: **same region (us-central1)** — preserves GCS bucket locality; the idle-shutdown
|
||||
function already iterates fallback zones generically. Cross-region is a possible fast-follow.
|
||||
|
||||
The runtime **needs no logic change**: `ensure_any_running` already iterates arbitrary
|
||||
`{vm, zone, ip}` candidates and `start_vm(zone=...)` is zone-generic. VMs are provisioned
|
||||
**stopped**, so creating them needs no capacity; only an on-demand *start* draws from the n2 pool.
|
||||
|
||||
### New fleet (after change)
|
||||
| VM | machine type | zone | disk |
|
||||
|----|--------------|------|------|
|
||||
| encoding-worker-fallback-a | c4d-highcpu-32 | us-central1-a | hyperdisk-balanced |
|
||||
| encoding-worker-fallback-b | c4d-highcpu-32 | us-central1-b | hyperdisk-balanced |
|
||||
| **encoding-worker-fallback-n2c** | **n2-highcpu-32** | us-central1-c | pd-balanced |
|
||||
| **encoding-worker-fallback-n2f** | **n2-highcpu-32** | us-central1-f | pd-balanced |
|
||||
|
||||
## Change surface
|
||||
|
||||
1. `infrastructure/config.py` — add `MachineTypes.ENCODING_WORKER_ALT = "n2-highcpu-32"`;
|
||||
replace the parallel `FALLBACK_*` lists with a structured `FALLBACKS` list carrying
|
||||
`machine_type` + `disk_type` per VM (a/b kept byte-identical so Pulumi does not recreate them).
|
||||
2. `infrastructure/compute/encoding_worker_vm.py` — build fallback IPs + VMs from `FALLBACKS`,
|
||||
honouring per-VM `machine_type` and `disk_type`.
|
||||
3. Idle-shutdown function — **no change** (already zone-generic via the secret). Add a regression
|
||||
test covering an n2 fallback entry.
|
||||
4. `encoding-worker-fallback-vms` **secret** — operator-set value: append the two n2 entries
|
||||
`{vm, zone, ip}` (with the newly-allocated static IPs) after `pulumi up`.
|
||||
5. Tests — pure-Python config invariants (machine-type diversity present, n2⇒pd-balanced,
|
||||
unique names/IPs) + idle-shutdown n2 case.
|
||||
6. Docs — `docs/LESSONS-LEARNED.md`, `docs/TROUBLESHOOTING.md`; version bump.
|
||||
|
||||
## Operational rollout (after merge-ready code)
|
||||
|
||||
1. `pulumi up` locally → provisions n2 IPs + VMs (stopped). Creating stopped VMs is not blocked
|
||||
by the c4d stockout.
|
||||
2. Read the two allocated static IPs; add a new `encoding-worker-fallback-vms` secret version
|
||||
including the n2 entries.
|
||||
3. Cloud Run picks up the new secret on next revision (or force a no-op deploy); the
|
||||
`video-encoding-job` and idle-shutdown function read `:latest` too.
|
||||
4. Smoke test: manually `gcloud compute instances start` one n2 fallback → confirm `/health` 200
|
||||
and a test encode succeeds on n2, then stop it.
|
||||
5. The live parked job (98bbd8b0) clears automatically once any capacity (n2 or recovered c4d)
|
||||
is reachable.
|
||||
|
||||
## Invariants to preserve (from May 2026 work)
|
||||
- Both Cloud Run service AND `video-encoding-job` read `ENCODING_WORKER_FALLBACK_VMS`.
|
||||
- `start_vm` inspects `operation.error_code` (never fire-and-forget).
|
||||
- Capacity-like errors stay typed as `EncodingWorkerStartError` so the render worker parks.
|
||||
- Idle-shutdown must stop the n2 fallbacks in their own zones (secret-driven — verified).
|
||||
@@ -2,7 +2,7 @@
|
||||
* Unit tests for job-status.ts utility functions
|
||||
*/
|
||||
|
||||
import { getJobStep, formatStepIndicator, isBlockingStatus, isNotifiableBlockingStatus, getJobProgressPercent, sortJobsByDate, isAutoRetryPending, JobStep, STATUS_CONFIG } from '../lib/job-status';
|
||||
import { getJobStep, formatStepIndicator, isBlockingStatus, isNotifiableBlockingStatus, getJobProgressPercent, sortJobsByDate, isAutoRetryPending, isWaitingForEncodingCapacity, isVisibilityChangeInProgress, shouldShowJobOnDashboard, JobStep, STATUS_CONFIG } from '../lib/job-status';
|
||||
import type { Job } from '../lib/api';
|
||||
|
||||
// Helper to create a minimal Job object for testing
|
||||
@@ -597,3 +597,51 @@ describe('isAutoRetryPending', () => {
|
||||
expect(isAutoRetryPending({ state_data: { cloud_run_retry_pending: {} } })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isWaitingForEncodingCapacity', () => {
|
||||
it('returns true when parked in render_pending_capacity', () => {
|
||||
expect(isWaitingForEncodingCapacity(createJob('render_pending_capacity'))).toBe(true);
|
||||
});
|
||||
|
||||
it('returns true during an in-flight retry attempt (status flips) with breadcrumb', () => {
|
||||
const meta = { render_pending_capacity: { attempt_count: 2 } };
|
||||
expect(isWaitingForEncodingCapacity(createJob('rendering_video', meta))).toBe(true);
|
||||
expect(isWaitingForEncodingCapacity(createJob('review_complete', meta))).toBe(true);
|
||||
});
|
||||
|
||||
it('returns false for a normal render with no capacity breadcrumb', () => {
|
||||
expect(isWaitingForEncodingCapacity(createJob('rendering_video'))).toBe(false);
|
||||
expect(isWaitingForEncodingCapacity(createJob('review_complete', { render_pending_capacity: {} }))).toBe(false);
|
||||
});
|
||||
|
||||
it('does not show the note after the render succeeds even if the breadcrumb lingers', () => {
|
||||
const meta = { render_pending_capacity: { attempt_count: 3 } };
|
||||
expect(isWaitingForEncodingCapacity(createJob('encoding', meta))).toBe(false);
|
||||
expect(isWaitingForEncodingCapacity(createJob('packaging', meta))).toBe(false);
|
||||
expect(isWaitingForEncodingCapacity(createJob('complete', meta))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isVisibilityChangeInProgress', () => {
|
||||
it('returns true only when the flag is set', () => {
|
||||
expect(isVisibilityChangeInProgress(createJob('rendering_video', { visibility_change_in_progress: true }))).toBe(true);
|
||||
expect(isVisibilityChangeInProgress(createJob('rendering_video'))).toBe(false);
|
||||
expect(isVisibilityChangeInProgress(createJob('complete', {}))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('shouldShowJobOnDashboard', () => {
|
||||
it('shows normal (non-audio-selection) jobs', () => {
|
||||
expect(shouldShowJobOnDashboard({ status: 'complete' })).toBe(true);
|
||||
expect(shouldShowJobOnDashboard({ status: 'awaiting_review' })).toBe(true);
|
||||
});
|
||||
|
||||
it('hides self-service jobs still in the guided-flow at awaiting_audio_selection', () => {
|
||||
expect(shouldShowJobOnDashboard({ status: 'awaiting_audio_selection' })).toBe(false);
|
||||
expect(shouldShowJobOnDashboard({ status: 'awaiting_audio_selection', made_for_you: false })).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps made-for-you orders visible even at awaiting_audio_selection', () => {
|
||||
expect(shouldShowJobOnDashboard({ status: 'awaiting_audio_selection', made_for_you: true })).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
} from "@/components/ui/select"
|
||||
import { Music2, RefreshCw, Loader2, Search, Gift, X, Shield, ShieldOff } from "lucide-react"
|
||||
import { useTranslations } from "next-intl"
|
||||
import { sortJobsByDate } from "@/lib/job-status"
|
||||
import { sortJobsByDate, shouldShowJobOnDashboard } from "@/lib/job-status"
|
||||
import { WarmingUpLoader } from "@/components/WarmingUpLoader"
|
||||
import { JobCard } from "@/components/job"
|
||||
import { GuidedJobFlow } from "@/components/job/GuidedJobFlow"
|
||||
@@ -88,9 +88,10 @@ function AppPageContent() {
|
||||
// Check if user is admin (for exclude_test parameter)
|
||||
const isAdmin = user?.role === "admin" || user?.email?.endsWith("@nomadkaraoke.com")
|
||||
|
||||
// Filter out in-progress search jobs (managed by the guided flow, not standalone cards)
|
||||
// Hide self-service jobs still in the guided-flow wizard, but keep made-for-you orders
|
||||
// visible even at awaiting_audio_selection (see shouldShowJobOnDashboard).
|
||||
const jobs = useMemo(
|
||||
() => allJobs.filter(job => job.status !== 'awaiting_audio_selection'),
|
||||
() => allJobs.filter(shouldShowJobOnDashboard),
|
||||
[allJobs]
|
||||
)
|
||||
|
||||
@@ -100,6 +101,20 @@ function AppPageContent() {
|
||||
return () => clearTimeout(timer)
|
||||
}, [searchInput])
|
||||
|
||||
// Honor a `status` URL param (e.g. made-for-you admin email deep-links to
|
||||
// /app/?admin_token=...&status=awaiting_audio_selection). Applied on mount before
|
||||
// the admin_token handler strips the query string, so the actionable queue is shown.
|
||||
useEffect(() => {
|
||||
const statusParam = searchParams.get("status")
|
||||
if (statusParam) {
|
||||
setStatusFilter(statusParam)
|
||||
if (typeof window !== "undefined") {
|
||||
localStorage.setItem("nomad-karaoke-status-filter", statusParam)
|
||||
}
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [])
|
||||
|
||||
// Memoize loadJobs for use with visibility refresh
|
||||
const loadJobs = useCallback(async () => {
|
||||
if (!getAccessToken()) {
|
||||
|
||||
@@ -86,6 +86,48 @@ describe('OutputLinks', () => {
|
||||
expect(screen.getByText('YouTube')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('hides GCS downloads + distribution links during a private->public re-render', () => {
|
||||
// Making public deletes the finals and re-renders (status leaves
|
||||
// "complete"), so the now-stale download + distribution links must go.
|
||||
const reRenderJob: Job = {
|
||||
...baseJob,
|
||||
status: 'rendering_video',
|
||||
state_data: {
|
||||
...baseJob.state_data,
|
||||
visibility_change_in_progress: true,
|
||||
},
|
||||
}
|
||||
|
||||
render(<OutputLinks job={reRenderJob} />)
|
||||
|
||||
expect(screen.queryByText('4K Video')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('720p Video')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('YouTube')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Dropbox')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps GCS downloads but hides distribution links during a public->private change', () => {
|
||||
// Making private is the fast path: it keeps the GCS finals and stays
|
||||
// "complete", only tearing down + redistributing YouTube/Dropbox.
|
||||
const toPrivateJob: Job = {
|
||||
...baseJob,
|
||||
status: 'complete',
|
||||
state_data: {
|
||||
...baseJob.state_data,
|
||||
visibility_change_in_progress: true,
|
||||
},
|
||||
}
|
||||
|
||||
render(<OutputLinks job={toPrivateJob} />)
|
||||
|
||||
// Finals still available for download
|
||||
expect(screen.getByText('4K Video')).toBeInTheDocument()
|
||||
expect(screen.getByText('720p Video')).toBeInTheDocument()
|
||||
// Distribution links torn down / redistributing
|
||||
expect(screen.queryByText('YouTube')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Dropbox')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows Dropbox link when dropbox_link is in state_data', () => {
|
||||
render(<OutputLinks job={baseJob} />)
|
||||
|
||||
|
||||
@@ -4,14 +4,14 @@ import { useState } from "react"
|
||||
import { useTranslations, useLocale } from 'next-intl'
|
||||
import { Job } from "@/lib/api"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Zap } from "lucide-react"
|
||||
import { Zap, Globe } from "lucide-react"
|
||||
import { JobActions } from "./JobActions"
|
||||
import { AdminJobActions } from "./AdminJobActions"
|
||||
import { OutputLinks } from "./OutputLinks"
|
||||
import { AudioSearchDialog } from "../audio-search/AudioSearchDialog"
|
||||
import { DurationCostConfirm } from "./DurationCostConfirm"
|
||||
import { BuyCreditsDialog } from "@/components/credits/BuyCreditsDialog"
|
||||
import { getJobStep, formatStepIndicator, getJobProgressPercent } from "@/lib/job-status"
|
||||
import { getJobStep, formatStepIndicator, getJobProgressPercent, isWaitingForEncodingCapacity, isVisibilityChangeInProgress } from "@/lib/job-status"
|
||||
import { useAuth } from "@/lib/auth"
|
||||
import { useDurationConfirm } from "@/hooks/use-duration-confirm"
|
||||
|
||||
@@ -30,9 +30,22 @@ function StatusIndicator({ job }: { job: Job }) {
|
||||
: tStatus(label as any)
|
||||
const formattedStatus = formatStepIndicator(step, total, translatedLabel)
|
||||
|
||||
// When the render is parked waiting for GCE encoding capacity, the status label
|
||||
// itself already reads "waiting for encoding server" (render_pending_capacity).
|
||||
// During the brief in-flight retry attempts the status flips to rendering, so
|
||||
// append a small note there too, keeping the user informed that the delay is
|
||||
// capacity, not a hang.
|
||||
const showCapacityNote =
|
||||
isWaitingForEncodingCapacity(job) && job.status?.toLowerCase() !== "render_pending_capacity"
|
||||
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<span className={color}>{formattedStatus}</span>
|
||||
{showCapacityNote && (
|
||||
<span className="text-amber-400/80 text-[11px]">
|
||||
{t('waitingForEncodingServer')}
|
||||
</span>
|
||||
)}
|
||||
{isBlocking && (
|
||||
<span className="text-amber-400 text-[10px] font-medium uppercase tracking-wide">
|
||||
{t('actionNeeded')}
|
||||
@@ -222,6 +235,17 @@ export function JobCard({ job, onRefresh, showAdminControls }: JobCardProps) {
|
||||
{/* Progress bar for active jobs */}
|
||||
<ProgressBar job={job} />
|
||||
|
||||
{/* Visibility change (private -> public) in progress: the track is being
|
||||
re-rendered with default branding and republished. Outputs are deleted
|
||||
for the duration, so set expectations up front (~15-30 min) rather than
|
||||
letting a "complete" track silently revert to a generic processing state. */}
|
||||
{isVisibilityChangeInProgress(job) && !isComplete && (
|
||||
<div className="mt-2 text-xs bg-blue-500/10 text-blue-300 rounded p-2 flex items-start gap-2">
|
||||
<Globe className="w-3.5 h-3.5 mt-0.5 shrink-0" />
|
||||
<span>{t('makingPublicInProgress')}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error message — only shown when the job is actually in a failed
|
||||
state. Completed jobs may carry a stale error_message from a transient
|
||||
failure that was auto-retried; we don't want to alarm users about
|
||||
|
||||
@@ -74,13 +74,23 @@ export function OutputLinks({ job, onJobUpdated }: OutputLinksProps) {
|
||||
// Check if outputs have been deleted by admin
|
||||
const outputsDeleted = !!job.outputs_deleted_at
|
||||
|
||||
// Filter external links based on tenant features (and outputs not deleted)
|
||||
const showYoutubeLink = features.youtube_upload && youtubeUrl && !outputsDeleted
|
||||
const showDropboxLink = features.dropbox_upload && dropboxUrl && !outputsDeleted
|
||||
// A visibility change tears down the distribution links (YouTube/Dropbox) in
|
||||
// BOTH directions while it redistributes, so any recorded external URLs are
|
||||
// stale for the duration. The private -> public path additionally deletes the
|
||||
// GCS finals and re-renders (status leaves "complete"); the fast public ->
|
||||
// private path keeps the finals and stays "complete", so its downloads remain
|
||||
// valid. Distinguish the two by status so we only hide GCS downloads during
|
||||
// the re-render.
|
||||
const visibilityChangeInProgress = !!job.state_data?.visibility_change_in_progress
|
||||
const visibilityReRenderInProgress = visibilityChangeInProgress && job.status !== "complete"
|
||||
const outputsUnavailable = outputsDeleted || visibilityReRenderInProgress
|
||||
|
||||
// Filter external links based on tenant features (and outputs available)
|
||||
const showYoutubeLink = features.youtube_upload && youtubeUrl && !outputsDeleted && !visibilityChangeInProgress
|
||||
const showDropboxLink = features.dropbox_upload && dropboxUrl && !outputsDeleted && !visibilityChangeInProgress
|
||||
|
||||
// Visibility change: available for completed consumer jobs (not tenant)
|
||||
const isPrivate = !!job.is_private
|
||||
const visibilityChangeInProgress = !!job.state_data?.visibility_change_in_progress
|
||||
const canChangeVisibility = job.status === "complete" && !tenantId && !visibilityChangeInProgress
|
||||
|
||||
const copyToClipboard = useCallback(async (url: string) => {
|
||||
@@ -178,10 +188,10 @@ export function OutputLinks({ job, onJobUpdated }: OutputLinksProps) {
|
||||
}
|
||||
}, [job.job_id, isPrivate, onJobUpdated])
|
||||
|
||||
const hasOutputs = showYoutubeLink || showDropboxLink || (downloadUrls && Object.keys(downloadUrls).length > 0)
|
||||
const hasOutputs = showYoutubeLink || showDropboxLink || (!outputsUnavailable && downloadUrls && Object.keys(downloadUrls).length > 0)
|
||||
|
||||
// Check if we have any downloads (and outputs haven't been deleted)
|
||||
const hasDownloads = !outputsDeleted && downloadUrls && (
|
||||
// Check if we have any downloads (and outputs are currently available)
|
||||
const hasDownloads = !outputsUnavailable && downloadUrls && (
|
||||
downloadUrls?.finals?.lossy_720p_mp4 ||
|
||||
downloadUrls?.finals?.lossy_4k_mp4 ||
|
||||
downloadUrls?.finals?.with_vocals_mp4 ||
|
||||
|
||||
@@ -145,6 +145,7 @@ export interface Job {
|
||||
brand_prefix?: string;
|
||||
// Customer order fields
|
||||
customer_email?: string;
|
||||
made_for_you?: boolean;
|
||||
// Request tracking metadata
|
||||
request_metadata?: Record<string, any>;
|
||||
}
|
||||
|
||||
@@ -25,6 +25,40 @@ export function isAutoRetryPending(job: Pick<Job, 'state_data'>): boolean {
|
||||
return expiresAt > Date.now();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true when a job is stuck waiting for GCE encoding-worker capacity.
|
||||
*
|
||||
* The canonical signal is the `render_pending_capacity` status (parked, auto-
|
||||
* retried every 5 min). During the retry cycle the status briefly flips to
|
||||
* `review_complete`/`rendering_video` while an attempt is in flight, so we also
|
||||
* treat those as "waiting" when the persistent `state_data.render_pending_capacity`
|
||||
* breadcrumb (attempt_count >= 1) is present. Scoped to the render step so the
|
||||
* lingering breadcrumb never shows the note after the render succeeds and the
|
||||
* job moves on to encoding/packaging/complete.
|
||||
*/
|
||||
export function isWaitingForEncodingCapacity(job: Pick<Job, 'status' | 'state_data'>): boolean {
|
||||
const status = job.status?.toLowerCase() || "";
|
||||
if (status === "render_pending_capacity") return true;
|
||||
if (status === "review_complete" || status === "rendering_video") {
|
||||
const meta = job.state_data?.render_pending_capacity as
|
||||
| { attempt_count?: number }
|
||||
| undefined;
|
||||
return !!meta && Number(meta.attempt_count ?? 0) >= 1;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true while a private -> public visibility change is re-rendering and
|
||||
* republishing the track. Backed by `state_data.visibility_change_in_progress`,
|
||||
* set synchronously when the change starts and cleared when the job completes.
|
||||
* The track's outputs (finals, distribution links) are deleted for the duration,
|
||||
* so download buttons must be suppressed and the user told to wait (~15-30 min).
|
||||
*/
|
||||
export function isVisibilityChangeInProgress(job: Pick<Job, 'state_data'>): boolean {
|
||||
return !!job.state_data?.visibility_change_in_progress;
|
||||
}
|
||||
|
||||
export interface JobStep {
|
||||
step: number;
|
||||
total: number;
|
||||
@@ -62,6 +96,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 +128,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" },
|
||||
@@ -316,3 +356,17 @@ export function sortJobsByDate(jobs: Job[]): Job[] {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a job should render as a standalone card on the main dashboard.
|
||||
*
|
||||
* Self-service jobs at `awaiting_audio_selection` are driven by the guided-flow
|
||||
* wizard in the same browser session and must NOT appear as standalone cards
|
||||
* (the wizard owns them). Made-for-you orders also sit at that status, but they
|
||||
* are created server-side by the Stripe webhook with no active guided-flow
|
||||
* session — so they'd otherwise be invisible to an admin. Keep those visible so
|
||||
* their built-in "Open Audio Selection" action is reachable from the dashboard.
|
||||
*/
|
||||
export function shouldShowJobOnDashboard(job: Pick<Job, 'status' | 'made_for_you'>): boolean {
|
||||
return job.status !== 'awaiting_audio_selection' || Boolean(job.made_for_you);
|
||||
}
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "جاري التصحيح",
|
||||
"lyricsDone": "اكتملت الكلمات",
|
||||
"lyrics": "الكلمات",
|
||||
"confirmDurationCost": "تأكيد التكلفة"
|
||||
"confirmDurationCost": "تأكيد التكلفة",
|
||||
"findingAudioSources": "جارٍ البحث عن مصادر الصوت (إعادة المحاولة)",
|
||||
"waitingForCapacity": "في انتظار خادم الترميز (جاري إعادة المحاولة)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "إجراء مطلوب",
|
||||
@@ -604,7 +606,9 @@
|
||||
"autoSelect": "سيتم التحديد التلقائي",
|
||||
"willAutoSelectFirst": "سيتم التحديد التلقائي للأول",
|
||||
"noOutputsAvailable": "لا توجد مخرجات متاحة بعد",
|
||||
"confirmCost": "تأكيد التكلفة"
|
||||
"confirmCost": "تأكيد التكلفة",
|
||||
"makingPublicInProgress": "يتم الآن جعل هذا المسار عاماً — تتم إعادة المعالجة بالعلامة التجارية الافتراضية وإعادة النشر. يستغرق هذا عادةً من 15 إلى 30 دقيقة.",
|
||||
"waitingForEncodingServer": "(في انتظار توفر خادم الترميز)"
|
||||
},
|
||||
"jobActions": {
|
||||
"delete": "حذف",
|
||||
|
||||
@@ -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 el servidor de codificació (reintentant)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Acció necessària",
|
||||
@@ -604,7 +606,9 @@
|
||||
"autoSelect": "Se seleccionarà automàticament",
|
||||
"willAutoSelectFirst": "Se seleccionarà automàticament el primer",
|
||||
"noOutputsAvailable": "Encara no hi ha sortides disponibles",
|
||||
"confirmCost": "Confirmar cost"
|
||||
"confirmCost": "Confirmar cost",
|
||||
"makingPublicInProgress": "Fent pública aquesta pista — renderitzant de nou amb la marca predeterminada i republicant. Això sol trigar 15–30 minuts.",
|
||||
"waitingForEncodingServer": "(esperant la disponibilitat del servidor de codificació)"
|
||||
},
|
||||
"jobActions": {
|
||||
"delete": "Suprimeix",
|
||||
|
||||
@@ -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á se na kódovací server (opakovaný pokus)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Vyžadována akce",
|
||||
@@ -604,7 +606,9 @@
|
||||
"autoSelect": "Automaticky se vybere",
|
||||
"willAutoSelectFirst": "Automaticky se vybere první",
|
||||
"noOutputsAvailable": "Zatím nejsou k dispozici žádné výstupy",
|
||||
"confirmCost": "Potvrdit cenu"
|
||||
"confirmCost": "Potvrdit cenu",
|
||||
"makingPublicInProgress": "Zveřejňujeme tuto skladbu — znovu ji renderujeme s výchozím brandingem a publikujeme. Obvykle to trvá 15–30 minut.",
|
||||
"waitingForEncodingServer": "(čeká se na dostupnost kódovacího serveru)"
|
||||
},
|
||||
"jobActions": {
|
||||
"delete": "Smazat",
|
||||
|
||||
@@ -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å kodningsserver (prøver igen)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Handling påkrævet",
|
||||
@@ -604,7 +606,9 @@
|
||||
"autoSelect": "Vil automatisk vælge",
|
||||
"willAutoSelectFirst": "Vil automatisk vælge første",
|
||||
"noOutputsAvailable": "Ingen outputs tilgængelige endnu",
|
||||
"confirmCost": "Bekræft pris"
|
||||
"confirmCost": "Bekræft pris",
|
||||
"makingPublicInProgress": "Gør dette nummer offentligt — gen-renderer med standardbranding og genudgiver. Det tager normalt 15–30 minutter.",
|
||||
"waitingForEncodingServer": "(venter på, at kodningsserveren bliver ledig)"
|
||||
},
|
||||
"jobActions": {
|
||||
"delete": "Slet",
|
||||
|
||||
@@ -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 Kodierungsserver (erneuter Versuch)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Aktion erforderlich",
|
||||
@@ -604,7 +606,9 @@
|
||||
"autoSelect": "Wird automatisch ausgewählt",
|
||||
"willAutoSelectFirst": "Wird automatisch das Erste auswählen",
|
||||
"noOutputsAvailable": "Noch keine Ausgaben verfügbar",
|
||||
"confirmCost": "Kosten bestätigen"
|
||||
"confirmCost": "Kosten bestätigen",
|
||||
"makingPublicInProgress": "Dieser Track wird öffentlich gemacht — erneutes Rendern mit Standard-Branding und erneute Veröffentlichung. Das dauert in der Regel 15–30 Minuten.",
|
||||
"waitingForEncodingServer": "(Warten auf Verfügbarkeit des Kodierungsservers)"
|
||||
},
|
||||
"jobActions": {
|
||||
"delete": "Löschen",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "Διόρθωση",
|
||||
"lyricsDone": "Οι στίχοι ολοκληρώθηκαν",
|
||||
"lyrics": "Στίχοι",
|
||||
"confirmDurationCost": "Επιβεβαίωση κόστους"
|
||||
"confirmDurationCost": "Επιβεβαίωση κόστους",
|
||||
"findingAudioSources": "Εύρεση πηγών ήχου (επαναπροσπάθεια)",
|
||||
"waitingForCapacity": "Αναμονή για διακομιστή κωδικοποίησης (νέα προσπάθεια)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Απαιτείται ενέργεια",
|
||||
@@ -604,7 +606,9 @@
|
||||
"autoSelect": "Θα γίνει αυτόματη επιλογή",
|
||||
"willAutoSelectFirst": "Θα γίνει αυτόματη επιλογή του πρώτου",
|
||||
"noOutputsAvailable": "Δεν υπάρχουν διαθέσιμα αποτελέσματα ακόμα",
|
||||
"confirmCost": "Επιβεβαίωση κόστους"
|
||||
"confirmCost": "Επιβεβαίωση κόστους",
|
||||
"makingPublicInProgress": "Κάνουμε αυτό το κομμάτι δημόσιο — επαναδημιουργία με την προεπιλεγμένη επωνυμία και αναδημοσίευση. Αυτό συνήθως διαρκεί 15–30 λεπτά.",
|
||||
"waitingForEncodingServer": "(αναμονή για διαθεσιμότητα διακομιστή κωδικοποίησης)"
|
||||
},
|
||||
"jobActions": {
|
||||
"delete": "Διαγραφή",
|
||||
|
||||
@@ -556,6 +556,8 @@
|
||||
"searchingForAudio": "Searching for audio",
|
||||
"selectAudioSource": "Select audio source",
|
||||
"downloadingAudio": "Downloading audio",
|
||||
"findingAudioSources": "Finding audio sources (retrying)",
|
||||
"waitingForCapacity": "Waiting for encoding server (retrying)",
|
||||
"downloading": "Downloading",
|
||||
"editAudio": "Edit audio",
|
||||
"editingAudio": "Editing audio",
|
||||
@@ -596,6 +598,8 @@
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Action needed",
|
||||
"waitingForEncodingServer": "(waiting for encoding server availability)",
|
||||
"makingPublicInProgress": "Making this track public — re-rendering with default branding and republishing. This usually takes 15–30 minutes.",
|
||||
"reviewLyrics": "Review Lyrics",
|
||||
"editAudio": "Edit Audio",
|
||||
"selectAudio": "Select Audio",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "Corrigiendo",
|
||||
"lyricsDone": "Letras terminadas",
|
||||
"lyrics": "Letras",
|
||||
"confirmDurationCost": "Confirmar costo"
|
||||
"confirmDurationCost": "Confirmar costo",
|
||||
"findingAudioSources": "Buscando fuentes de audio (reintentando)",
|
||||
"waitingForCapacity": "Esperando al servidor de codificación (reintentando)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Acción necesaria",
|
||||
@@ -604,7 +606,9 @@
|
||||
"autoSelect": "Seleccionará automáticamente",
|
||||
"willAutoSelectFirst": "Seleccionará automáticamente el primero",
|
||||
"noOutputsAvailable": "No hay salidas disponibles aún",
|
||||
"confirmCost": "Confirmar costo"
|
||||
"confirmCost": "Confirmar costo",
|
||||
"makingPublicInProgress": "Haciendo pública esta pista — re-renderizando con la marca predeterminada y republicando. Esto normalmente tarda de 15 a 30 minutos.",
|
||||
"waitingForEncodingServer": "(esperando disponibilidad del servidor de codificación)"
|
||||
},
|
||||
"jobActions": {
|
||||
"delete": "Eliminar",
|
||||
|
||||
@@ -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 enkoodauspalvelinta (yritetään uudelleen)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Toimenpiteitä tarvitaan",
|
||||
@@ -604,7 +606,9 @@
|
||||
"autoSelect": "Valitsee automaattisesti",
|
||||
"willAutoSelectFirst": "Valitsee automaattisesti ensimmäisen",
|
||||
"noOutputsAvailable": "Ei tulosteita vielä saatavilla",
|
||||
"confirmCost": "Vahvista hinta"
|
||||
"confirmCost": "Vahvista hinta",
|
||||
"makingPublicInProgress": "Kappaleesta tehdään julkinen — se renderöidään uudelleen oletusbrändäyksellä ja julkaistaan uudestaan. Tämä kestää yleensä 15–30 minuuttia.",
|
||||
"waitingForEncodingServer": "(odotetaan enkoodauspalvelimen vapautumista)"
|
||||
},
|
||||
"jobActions": {
|
||||
"delete": "Poista",
|
||||
|
||||
@@ -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 du serveur d'encodage (nouvelle tentative)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Action requise",
|
||||
@@ -604,7 +606,9 @@
|
||||
"autoSelect": "Sélectionnera automatiquement",
|
||||
"willAutoSelectFirst": "Sélectionnera automatiquement le premier",
|
||||
"noOutputsAvailable": "Aucune sortie disponible pour le moment",
|
||||
"confirmCost": "Confirmer le coût"
|
||||
"confirmCost": "Confirmer le coût",
|
||||
"makingPublicInProgress": "Nous rendons cette piste publique — nouveau rendu avec l'image de marque par défaut et republication. Cela prend généralement 15 à 30 minutes.",
|
||||
"waitingForEncodingServer": "(en attente de la disponibilité du serveur d'encodage)"
|
||||
},
|
||||
"jobActions": {
|
||||
"delete": "Supprimer",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "מתקן",
|
||||
"lyricsDone": "מילים הושלמו",
|
||||
"lyrics": "מילים",
|
||||
"confirmDurationCost": "אישור עלות"
|
||||
"confirmDurationCost": "אישור עלות",
|
||||
"findingAudioSources": "מחפש מקורות שמע (מנסה שוב)",
|
||||
"waitingForCapacity": "ממתין לשרת הקידוד (מנסה שוב)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "נדרשת פעולה",
|
||||
@@ -604,7 +606,9 @@
|
||||
"autoSelect": "יבחר אוטומטית",
|
||||
"willAutoSelectFirst": "יבחר אוטומטית ראשון",
|
||||
"noOutputsAvailable": "אין פלטים זמינים עדיין",
|
||||
"confirmCost": "אישור עלות"
|
||||
"confirmCost": "אישור עלות",
|
||||
"makingPublicInProgress": "הופך את הרצועה הזו לציבורית — מעבד מחדש עם מיתוג ברירת המחדל ומפרסם מחדש. זה בדרך כלל לוקח 15–30 דקות.",
|
||||
"waitingForEncodingServer": "(ממתין לזמינות שרת הקידוד)"
|
||||
},
|
||||
"jobActions": {
|
||||
"delete": "מחק",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "सही किया जा रहा है",
|
||||
"lyricsDone": "लिरिक्स हो गए",
|
||||
"lyrics": "लिरिक्स",
|
||||
"confirmDurationCost": "लागत की पुष्टि करो"
|
||||
"confirmDurationCost": "लागत की पुष्टि करो",
|
||||
"findingAudioSources": "ऑडियो स्रोत खोज रहे हैं (फिर से कोशिश कर रहे हैं)",
|
||||
"waitingForCapacity": "एनकोडिंग सर्वर का इंतज़ार किया जा रहा है (फिर से कोशिश की जा रही है)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "एक्शन की ज़रूरत है",
|
||||
@@ -604,7 +606,9 @@
|
||||
"autoSelect": "अपने आप सिलेक्ट करेगा",
|
||||
"willAutoSelectFirst": "अपने आप पहला सिलेक्ट करेगा",
|
||||
"noOutputsAvailable": "अभी तक कोई आउटपुट उपलब्ध नहीं है",
|
||||
"confirmCost": "लागत की पुष्टि करो"
|
||||
"confirmCost": "लागत की पुष्टि करो",
|
||||
"makingPublicInProgress": "इस ट्रैक को पब्लिक किया जा रहा है — डिफ़ॉल्ट ब्रांडिंग के साथ फिर से रेंडर और पब्लिश किया जा रहा है। इसमें आमतौर पर 15–30 मिनट लगते हैं।",
|
||||
"waitingForEncodingServer": "(एनकोडिंग सर्वर के उपलब्ध होने का इंतज़ार किया जा रहा है)"
|
||||
},
|
||||
"jobActions": {
|
||||
"delete": "डिलीट करो",
|
||||
|
||||
@@ -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": "Čeka se server za kodiranje (ponovni pokušaj)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Potrebna akcija",
|
||||
@@ -604,7 +606,9 @@
|
||||
"autoSelect": "Automatski će odabrati",
|
||||
"willAutoSelectFirst": "Automatski će odabrati prvo",
|
||||
"noOutputsAvailable": "Još nema dostupnih izlaza",
|
||||
"confirmCost": "Potvrdi cijenu"
|
||||
"confirmCost": "Potvrdi cijenu",
|
||||
"makingPublicInProgress": "Objavljivanje ove pjesme — ponovno renderiranje sa zadanim brendiranjem i ponovno objavljivanje. To obično traje 15–30 minuta.",
|
||||
"waitingForEncodingServer": "(čeka se dostupnost servera za kodiranje)"
|
||||
},
|
||||
"jobActions": {
|
||||
"delete": "Izbriši",
|
||||
|
||||
@@ -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 a kódoló szerverre (újrapróbálkozás)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Művelet szükséges",
|
||||
@@ -604,7 +606,9 @@
|
||||
"autoSelect": "Automatikusan kiválasztja",
|
||||
"willAutoSelectFirst": "Automatikusan kiválasztja az elsőt",
|
||||
"noOutputsAvailable": "Még nincsenek elérhető kimenetek",
|
||||
"confirmCost": "Költség megerősítése"
|
||||
"confirmCost": "Költség megerősítése",
|
||||
"makingPublicInProgress": "A dal nyilvánossá tétele folyamatban — újrarenderelés az alapértelmezett arculattal és újraközzététel. Ez általában 15–30 percet vesz igénybe.",
|
||||
"waitingForEncodingServer": "(várakozás a kódoló szerver elérhetőségére)"
|
||||
},
|
||||
"jobActions": {
|
||||
"delete": "Törlés",
|
||||
|
||||
@@ -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 server encoding (mencoba lagi)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Perlu tindakan",
|
||||
@@ -604,7 +606,9 @@
|
||||
"autoSelect": "Akan memilih otomatis",
|
||||
"willAutoSelectFirst": "Akan memilih otomatis yang pertama",
|
||||
"noOutputsAvailable": "Belum ada output yang tersedia",
|
||||
"confirmCost": "Konfirmasi Biaya"
|
||||
"confirmCost": "Konfirmasi Biaya",
|
||||
"makingPublicInProgress": "Menjadikan trek ini publik — merender ulang dengan branding bawaan dan memublikasikan ulang. Proses ini biasanya memakan waktu 15–30 menit.",
|
||||
"waitingForEncodingServer": "(menunggu ketersediaan server encoding)"
|
||||
},
|
||||
"jobActions": {
|
||||
"delete": "Hapus",
|
||||
|
||||
@@ -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 del server di codifica (nuovo tentativo)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Azione richiesta",
|
||||
@@ -604,7 +606,9 @@
|
||||
"autoSelect": "Selezionerà automaticamente",
|
||||
"willAutoSelectFirst": "Selezionerà automaticamente il primo",
|
||||
"noOutputsAvailable": "Nessun output ancora disponibile",
|
||||
"confirmCost": "Conferma costo"
|
||||
"confirmCost": "Conferma costo",
|
||||
"makingPublicInProgress": "Stiamo rendendo pubblica questa traccia — nuovo rendering con il branding predefinito e ripubblicazione in corso. Di solito ci vogliono 15–30 minuti.",
|
||||
"waitingForEncodingServer": "(in attesa della disponibilità del server di codifica)"
|
||||
},
|
||||
"jobActions": {
|
||||
"delete": "Elimina",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "修正中",
|
||||
"lyricsDone": "歌詞完了",
|
||||
"lyrics": "歌詞",
|
||||
"confirmDurationCost": "料金を確認"
|
||||
"confirmDurationCost": "料金を確認",
|
||||
"findingAudioSources": "音源を検索中(再試行中)",
|
||||
"waitingForCapacity": "エンコーディングサーバーの空きを待機中(再試行中)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "アクションが必要です",
|
||||
@@ -604,7 +606,9 @@
|
||||
"autoSelect": "自動選択されます",
|
||||
"willAutoSelectFirst": "最初を自動選択します",
|
||||
"noOutputsAvailable": "まだ利用可能な出力がありません",
|
||||
"confirmCost": "料金を確認"
|
||||
"confirmCost": "料金を確認",
|
||||
"makingPublicInProgress": "このトラックを公開しています — デフォルトのブランディングで再レンダリングし、再公開しています。通常15〜30分ほどかかります。",
|
||||
"waitingForEncodingServer": "(エンコーディングサーバーの空きを待機中)"
|
||||
},
|
||||
"jobActions": {
|
||||
"delete": "削除",
|
||||
|
||||
@@ -592,7 +592,9 @@
|
||||
"correcting": "수정 중",
|
||||
"lyricsDone": "가사 완료",
|
||||
"lyrics": "가사",
|
||||
"confirmDurationCost": "비용 확인"
|
||||
"confirmDurationCost": "비용 확인",
|
||||
"findingAudioSources": "오디오 소스 찾는 중 (재시도 중)",
|
||||
"waitingForCapacity": "인코딩 서버 대기 중 (재시도 중)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "조치 필요",
|
||||
@@ -604,7 +606,9 @@
|
||||
"autoSelect": "자동 선택 예정",
|
||||
"willAutoSelectFirst": "첫 번째 항목 자동 선택 예정",
|
||||
"noOutputsAvailable": "아직 사용 가능한 출력이 없습니다",
|
||||
"confirmCost": "비용 확인"
|
||||
"confirmCost": "비용 확인",
|
||||
"makingPublicInProgress": "이 트랙을 공개로 전환하는 중입니다 — 기본 브랜딩으로 재렌더링 및 재게시를 진행합니다. 보통 15~30분 정도 소요됩니다.",
|
||||
"waitingForEncodingServer": "(인코딩 서버 대기 중)"
|
||||
},
|
||||
"jobActions": {
|
||||
"delete": "삭제",
|
||||
|
||||
@@ -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 pelayan pengekodan (mencuba semula)"
|
||||
},
|
||||
"jobCard": {
|
||||
"actionNeeded": "Tindakan diperlukan",
|
||||
@@ -604,7 +606,9 @@
|
||||
"autoSelect": "Akan pilih automatik",
|
||||
"willAutoSelectFirst": "Akan pilih automatik yang pertama",
|
||||
"noOutputsAvailable": "Tiada output tersedia lagi",
|
||||
"confirmCost": "Sahkan Kos"
|
||||
"confirmCost": "Sahkan Kos",
|
||||
"makingPublicInProgress": "Menjadikan trek ini awam — merender semula dengan penjenamaan lalai dan menerbitkan semula. Proses ini biasanya mengambil masa 15–30 minit.",
|
||||
"waitingForEncodingServer": "(menunggu ketersediaan pelayan pengekodan)"
|
||||
},
|
||||
"jobActions": {
|
||||
"delete": "Padam",
|
||||
|
||||
Loaded 100 of 130 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user