Compare commits

..
Author SHA1 Message Date
Andrew BeveridgeandClaude Opus 5.5 374be827c0 fix(storage): retention job exits non-zero when any job errored
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-04 01:00:51 -04:00
Andrew BeveridgeandClaude Opus 5.5 d042a155dc fix(storage): clear the screens idempotency mark around stems restore
The regenerate E2E stalled after the stems restore: the first screens dispatch
had marked screens_progress=running, so the restore's re-trigger was skipped as
'already running'. Drop the mark when the gate hands off (and on completion),
and let recover-stuck-jobs re-trigger re-render/regenerate jobs left parked at
lyrics_complete for >10 min.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-04 00:50:14 -04:00
Andrew BeveridgeandClaude Opus 5.5 e9d2157546 fix(storage): run the retention pass as a Cloud Run Job (v0.265.1)
The scheduled endpoint ran the pass as a FastAPI BackgroundTask, which starves
on the API service (CPU throttled outside requests), and Cloudflare cuts
synchronous requests at 100s. Start a dedicated storage-retention-job Cloud Run
Job (Pulumi, applied) with the dry-run flag and report path as args; scoped
job_ids runs stay synchronous.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-04 00:30:30 -04:00
133 changed files with 524 additions and 6891 deletions

No files matched your search

+2 -22
View File
@@ -294,19 +294,8 @@ jobs:
--reporter=list \
--timeout=3600000
- name: Scrub secrets from artifacts (public repo)
id: scrub
if: always()
working-directory: frontend
env:
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
E2E_BYPASS_KEY: ${{ secrets.E2E_BYPASS_KEY }}
E2E_TEST_TOKEN: ${{ steps.refresh_token.outputs.token }}
run: node e2e/scripts/scrub-artifacts.mjs test-results playwright-report
- name: Upload test artifacts
if: always() && steps.scrub.outcome == 'success'
if: always()
uses: actions/upload-artifact@v4
with:
name: e2e-happy-path-results
@@ -2038,7 +2027,7 @@ jobs:
--max-instances 20 \
--min-instances 0 \
--clear-vpc-connector \
--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,USE_CLOUD_RUN_JOBS_FOR_RENDER=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-opus-5-5,AUTO_CORRECT_COMPARE_MODELS=claude-opus-5-5;gemini-3.8-flash,AUTO_CORRECT_PROACTIVE_ENABLED=true,AUTO_APPROVAL_BACKING_KEEP_ENABLED=true,COMMUNITY_DAILY_PICK_ENABLED=true,STORAGE_RETENTION_DRY_RUN=false,STORAGE_RETENTION_MAX_JOBS_PER_RUN=50,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-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,USE_CLOUD_RUN_JOBS_FOR_RENDER=true,EMAIL_PROVIDER=postmark,AUTO_CORRECT_MODEL=claude-opus-5-5,AUTO_CORRECT_COMPARE_MODELS=claude-opus-5-5;gemini-3.8-flash,AUTO_CORRECT_PROACTIVE_ENABLED=true,AUTO_APPROVAL_BACKING_KEEP_ENABLED=true,COMMUNITY_DAILY_PICK_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,GEMINI_API_KEY=gemini-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,KARAOKEHUNT_FORWARDER_SECRET=karaokehunt-forwarder-secret:latest,KJBOX_PARTNER_SECRET=kjbox-partner-secret:latest"
# R3/R4 — smoke the tagged candidate revision BEFORE it serves any traffic.
@@ -2127,15 +2116,6 @@ jobs:
--project ${{ env.PROJECT_ID }} \
--quiet
# Storage-retention job (CPU, us-east4): pin to this commit's image so
# the deletion code (generation-pinned deletes + audit log) always
# matches the API that starts it.
gcloud run jobs update storage-retention-job \
--image "$CPU_JOBS_IMAGE" \
--region us-east4 \
--project ${{ env.PROJECT_ID }} \
--quiet
# Audio separation job (GPU, us-east4) — uses GPU image
gcloud run jobs update audio-separation-job \
--image "$GPU_IMAGE" \
+8 -49
View File
@@ -58,7 +58,6 @@ jobs:
outputs:
session_token: ${{ steps.extract_token.outputs.token }}
result: ${{ steps.test_result.outputs.result }}
failure_reason: ${{ steps.test_result.outputs.failure_reason }}
healed: ${{ steps.self_heal.outputs.healed }}
env:
HAS_GEMINI_SECRET: ${{ secrets.GEMINI_API_KEY != '' }}
@@ -149,12 +148,9 @@ jobs:
E2E_STRIPE_CARDHOLDER_NAME: ${{ secrets.E2E_STRIPE_CARDHOLDER_NAME }}
E2E_STRIPE_ZIP: ${{ secrets.E2E_STRIPE_ZIP }}
E2E_SELF_HEAL_FORCE_LLM: ${{ inputs.self_heal_force_llm || '' }}
# No real card available → 'checkout-only' (no charge). Set the repo variable
# E2E_REAL_PAYMENT=true to go back to buying a credit with E2E_STRIPE_CARD_*.
E2E_PAYMENT_MODE: ${{ vars.E2E_REAL_PAYMENT == 'true' && 'real' || 'checkout-only' }}
DEBUG_MODE: ${{ inputs.debug_mode || 'false' }}
run: |
echo "=== Stage 1: Credit Purchase via Real Stripe (mode: $E2E_PAYMENT_MODE) ==="
echo "=== Stage 1: Credit Purchase via Real Stripe ==="
echo "Time: $(date)"
npx playwright test credit-purchase-real.spec.ts \
--config=playwright.production.config.ts \
@@ -174,13 +170,6 @@ jobs:
echo "result=success" >> "$GITHUB_OUTPUT"
else
echo "result=failure" >> "$GITHUB_OUTPUT"
# A declined card is an issuer/card problem, not a broken checkout —
# say so in the alerts (marker comes from e2e/helpers/stripe-checkout.ts).
REASON=$(grep -m1 -o 'STRIPE_CARD_DECLINED:.*' frontend/test-output-payment.log 2>/dev/null | sed 's/ — .*//' | tr -d '"\\' || true)
if [ -n "$REASON" ]; then
echo "failure_reason=Test card declined, not a checkout bug (${REASON#STRIPE_CARD_DECLINED: }). Check the card/issuer for a fraud hold, then re-run." >> "$GITHUB_OUTPUT"
echo "::error::$REASON"
fi
fi
- name: Detect self-healed Stripe steps
@@ -229,21 +218,8 @@ jobs:
echo "token=" >> $GITHUB_OUTPUT
fi
- name: Scrub secrets from artifacts (public repo)
id: scrub
if: always()
working-directory: frontend
env:
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
E2E_STRIPE_CARD_NUMBER: ${{ secrets.E2E_STRIPE_CARD_NUMBER }}
E2E_STRIPE_CARD_EXPIRY: ${{ secrets.E2E_STRIPE_CARD_EXPIRY }}
E2E_STRIPE_CARD_CVC: ${{ secrets.E2E_STRIPE_CARD_CVC }}
E2E_SESSION_TOKEN: ${{ steps.extract_token.outputs.token }}
run: node e2e/scripts/scrub-artifacts.mjs --drop-videos --blank-inputs test-results test-output-payment.log
- name: Upload artifacts
if: always() && steps.scrub.outcome == 'success'
if: always()
uses: actions/upload-artifact@v4
with:
name: e2e-payment-results-${{ github.run_number }}
@@ -254,16 +230,10 @@ jobs:
- name: Discord notification (failure)
if: steps.test_result.outputs.result == 'failure'
env:
# Via env + jq, never ${{ }} in the script: the reason contains Stripe's message text.
REASON: ${{ steps.test_result.outputs.failure_reason || 'Payment flow is broken. Customers may not be receiving credits.' }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
RUN_NUMBER: ${{ github.run_number }}
WEBHOOK: ${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}
run: |
jq -n --arg reason "$REASON" --arg run "$RUN_NUMBER" --arg url "$RUN_URL" \
'{embeds: [{title: "🚨 E2E Daily Test FAILED — Stage 1: Credit Purchase", description: "\($reason)\n\n**Run:** #\($run)\n**Details:** \($url)", color: 15158332}]}' |
curl -s -H "Content-Type: application/json" -d @- "$WEBHOOK"
curl -s -H "Content-Type: application/json" \
-d "{\"embeds\": [{\"title\": \"🚨 E2E Daily Test FAILED — Stage 1: Credit Purchase\", \"description\": \"Payment flow is broken. Customers may not be receiving credits.\n\n**Run:** #${{ github.run_number }}\n**Details:** ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}\", \"color\": 15158332}]}" \
"${{ secrets.DISCORD_ALERT_WEBHOOK_URL }}"
- name: Fail if test failed
if: steps.test_result.outputs.result == 'failure'
@@ -529,19 +499,8 @@ jobs:
echo "result=failure" >> "$GITHUB_OUTPUT"
fi
- name: Scrub secrets from artifacts (public repo)
id: scrub
if: always()
working-directory: frontend
env:
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
E2E_BYPASS_KEY: ${{ secrets.E2E_BYPASS_KEY }}
E2E_TEST_TOKEN: ${{ steps.refresh_token.outputs.token || needs.e2e-credit-purchase.outputs.session_token || '' }}
run: node e2e/scripts/scrub-artifacts.mjs test-results playwright-report test-output-happy-path.log
- name: Upload test artifacts
if: always() && steps.scrub.outcome == 'success'
if: always()
uses: actions/upload-artifact@v4
with:
name: e2e-happy-path-results-${{ github.run_number }}
@@ -552,7 +511,7 @@ jobs:
retention-days: 30
- name: Upload video recordings
if: always() && steps.scrub.outcome == 'success'
if: always()
uses: actions/upload-artifact@v4
with:
name: e2e-happy-path-videos-${{ github.run_number }}
@@ -622,7 +581,7 @@ jobs:
E2E Daily Test Results
======================
Stage 1 (Credit Purchase): ${{ needs.e2e-credit-purchase.result || 'skipped' }}${{ vars.E2E_REAL_PAYMENT != 'true' && ' [checkout-only: no real payment]' || '' }}${{ needs.e2e-credit-purchase.outputs.failure_reason && format(' — {0}', needs.e2e-credit-purchase.outputs.failure_reason) || '' }}
Stage 1 (Credit Purchase): ${{ needs.e2e-credit-purchase.result || 'skipped' }}
Stage 2 (Happy Path): ${{ needs.e2e-happy-path.result || 'skipped' }}
Stripe self-heal: ${{ needs.e2e-credit-purchase.outputs.healed == 'true' && format('Stripe changed its checkout; LLM fallback healed it. Auto-merge PR: {0}', needs.self-heal-pr.outputs.pr_url || (needs.self-heal-pr.outputs.unchanged == 'true' && '(already on main)' || '(failed to open — see run)')) || 'not needed' }}
+1 -10
View File
@@ -83,17 +83,8 @@ jobs:
echo "exit_code=${PIPESTATUS[0]}" >> "$GITHUB_OUTPUT"
continue-on-error: true
- name: Scrub secrets from artifacts (public repo)
id: scrub
if: always()
working-directory: frontend
env:
E2E_ADMIN_TOKEN: ${{ secrets.E2E_ADMIN_TOKEN }}
TESTMAIL_API_KEY: ${{ secrets.TESTMAIL_API_KEY }}
run: node e2e/scripts/scrub-artifacts.mjs test-results playwright-report e2e-output.log
- name: Upload logs
if: always() && steps.scrub.outcome == 'success'
if: always()
uses: actions/upload-artifact@v4
with:
name: e2e-tenant-${{ matrix.tenant }}-${{ github.run_number }}
-42
View File
@@ -4505,45 +4505,3 @@ async def action_community_review(
status="made", request_id=request_id,
message=f"Making our version (job {result.get('job_id')}).",
)
class PersistUploadsResponse(BaseModel):
dry_run: bool
jobs: Dict[str, Any] # job_id -> {"copied", "updated"} | {"would_copy"} | {"error"} | {"orphan"}
@router.post("/persist-uploads", response_model=PersistUploadsResponse)
def persist_uploads(dry_run: bool = True, auth_data: AuthResult = Depends(require_admin)):
"""Backfill: copy every job's ``uploads/{job_id}/**`` into ``jobs/{job_id}/input/``.
Same operation the workers run on entry (``input_persistence``), for jobs that
no worker will touch again. Folders with no job document (abandoned uploads)
are reported as ``orphan`` and left in place. Plain ``def``: blocking GCS and
Firestore calls run in the threadpool.
"""
from backend.services.input_persistence import persist_job_inputs, persisted_path
storage = StorageService()
job_manager = JobManager()
by_job: Dict[str, List[str]] = {}
for blob in storage.bucket.list_blobs(prefix="uploads/"):
parts = blob.name.split("/")
if len(parts) > 2 and parts[1]:
by_job.setdefault(parts[1], []).append(blob.name)
results: Dict[str, Any] = {}
for job_id, names in sorted(by_job.items()):
try:
job = job_manager.get_job(job_id)
if job is None:
results[job_id] = {"orphan": len(names)}
continue
if dry_run:
results[job_id] = {"would_copy": {n: persisted_path(job_id, n) for n in names}}
continue
copied, updates = persist_job_inputs(job, storage, job_manager)
results[job_id] = {"copied": copied, "updated": updates}
except Exception as e: # noqa: BLE001
logger.error(f"persist-uploads: job {job_id} failed: {e}")
results[job_id] = {"error": str(e)}
return PersistUploadsResponse(dry_run=dry_run, jobs=results)
+3 -3
View File
@@ -729,17 +729,17 @@ async def search_audio(
credential_manager = get_credential_manager()
if effective_enable_youtube_upload:
result = await asyncio.to_thread(credential_manager.check_youtube_credentials)
result = credential_manager.check_youtube_credentials()
if result.status != CredentialStatus.VALID:
invalid_services.append(f"youtube ({result.message})")
if effective_dropbox_path:
result = await asyncio.to_thread(credential_manager.check_dropbox_credentials)
result = credential_manager.check_dropbox_credentials()
if result.status != CredentialStatus.VALID:
invalid_services.append(f"dropbox ({result.message})")
if effective_gdrive_folder_id:
result = await asyncio.to_thread(credential_manager.check_gdrive_credentials)
result = credential_manager.check_gdrive_credentials()
if result.status != CredentialStatus.VALID:
invalid_services.append(f"gdrive ({result.message})")
+17 -29
View File
@@ -610,17 +610,17 @@ async def upload_and_create_job(
credential_manager = get_credential_manager()
if effective_enable_youtube_upload and not is_private:
result = await asyncio.to_thread(credential_manager.check_youtube_credentials)
result = credential_manager.check_youtube_credentials()
if result.status != CredentialStatus.VALID:
invalid_services.append(f"youtube ({result.message})")
if dist.dropbox_path:
result = await asyncio.to_thread(credential_manager.check_dropbox_credentials)
result = credential_manager.check_dropbox_credentials()
if result.status != CredentialStatus.VALID:
invalid_services.append(f"dropbox ({result.message})")
if dist.gdrive_folder_id and not is_private:
result = await asyncio.to_thread(credential_manager.check_gdrive_credentials)
result = credential_manager.check_gdrive_credentials()
if result.status != CredentialStatus.VALID:
invalid_services.append(f"gdrive ({result.message})")
@@ -930,7 +930,7 @@ async def upload_and_create_job(
distribution_services: Dict[str, Any] = {}
if dist.dropbox_path:
dropbox_result = await asyncio.to_thread(credential_manager.check_dropbox_credentials)
dropbox_result = credential_manager.check_dropbox_credentials()
distribution_services["dropbox"] = {
"enabled": True,
"path": dist.dropbox_path,
@@ -939,7 +939,7 @@ async def upload_and_create_job(
}
if dist.gdrive_folder_id:
gdrive_result = await asyncio.to_thread(credential_manager.check_gdrive_credentials)
gdrive_result = credential_manager.check_gdrive_credentials()
distribution_services["gdrive"] = {
"enabled": True,
"folder_id": dist.gdrive_folder_id,
@@ -948,7 +948,7 @@ async def upload_and_create_job(
}
if effective_enable_youtube_upload:
youtube_result = await asyncio.to_thread(credential_manager.check_youtube_credentials)
youtube_result = credential_manager.check_youtube_credentials()
distribution_services["youtube"] = {
"enabled": True,
"credentials_valid": youtube_result.status == CredentialStatus.VALID,
@@ -1105,20 +1105,8 @@ async def _validate_audio_durations(
Returns:
Tuple of (is_valid, audio_duration, instrumental_duration)
"""
# Two GCS downloads + two full decodes (15s+ seen in prod) — never on the loop.
return await asyncio.to_thread(
_validate_audio_durations_sync, storage, audio_gcs_path, instrumental_gcs_path, tolerance_seconds
)
def _validate_audio_durations_sync(
storage: StorageService,
audio_gcs_path: str,
instrumental_gcs_path: str,
tolerance_seconds: float,
) -> Tuple[bool, float, float]:
from pydub import AudioSegment
temp_dir = tempfile.mkdtemp(prefix="duration_check_")
try:
# Download audio file
@@ -1327,17 +1315,17 @@ async def create_job_with_upload_urls(
credential_manager = get_credential_manager()
if effective_enable_youtube_upload and not effective_is_private:
result = await asyncio.to_thread(credential_manager.check_youtube_credentials)
result = credential_manager.check_youtube_credentials()
if result.status != CredentialStatus.VALID:
invalid_services.append(f"youtube ({result.message})")
if dist.dropbox_path:
result = await asyncio.to_thread(credential_manager.check_dropbox_credentials)
result = credential_manager.check_dropbox_credentials()
if result.status != CredentialStatus.VALID:
invalid_services.append(f"dropbox ({result.message})")
if dist.gdrive_folder_id and not effective_is_private:
result = await asyncio.to_thread(credential_manager.check_gdrive_credentials)
result = credential_manager.check_gdrive_credentials()
if result.status != CredentialStatus.VALID:
invalid_services.append(f"gdrive ({result.message})")
@@ -1664,7 +1652,7 @@ async def mark_uploads_complete(
logger.warning(f"Duration validation failed with error: {e}. Proceeding without validation.")
# Don't block the job if we can't validate - the video worker will fail more gracefully
# uploads/ expires (bucket lifecycle): keep the user's instrumental at the job
# uploads/ expires after 7 days: keep the user's instrumental at the job
# root (where the video pipeline stages it anyway) so later re-renders,
# regenerates and edits still have it.
if (update_data.get('existing_instrumental_gcs_path') or '').startswith('uploads/'):
@@ -1707,7 +1695,7 @@ async def mark_uploads_complete(
updated_job = job_manager.get_job(job_id)
if updated_job.dropbox_path:
dropbox_result = await asyncio.to_thread(credential_manager.check_dropbox_credentials)
dropbox_result = credential_manager.check_dropbox_credentials()
distribution_services["dropbox"] = {
"enabled": True,
"path": updated_job.dropbox_path,
@@ -1715,7 +1703,7 @@ async def mark_uploads_complete(
}
if updated_job.gdrive_folder_id:
gdrive_result = await asyncio.to_thread(credential_manager.check_gdrive_credentials)
gdrive_result = credential_manager.check_gdrive_credentials()
distribution_services["gdrive"] = {
"enabled": True,
"folder_id": updated_job.gdrive_folder_id,
@@ -1723,7 +1711,7 @@ async def mark_uploads_complete(
}
if updated_job.enable_youtube_upload:
youtube_result = await asyncio.to_thread(credential_manager.check_youtube_credentials)
youtube_result = credential_manager.check_youtube_credentials()
distribution_services["youtube"] = {
"enabled": True,
"credentials_valid": youtube_result.status == CredentialStatus.VALID,
@@ -2041,17 +2029,17 @@ async def create_job_from_url(
credential_manager = get_credential_manager()
if effective_enable_youtube_upload and not body.is_private:
result = await asyncio.to_thread(credential_manager.check_youtube_credentials)
result = credential_manager.check_youtube_credentials()
if result.status != CredentialStatus.VALID:
invalid_services.append(f"youtube ({result.message})")
if dist.dropbox_path:
result = await asyncio.to_thread(credential_manager.check_dropbox_credentials)
result = credential_manager.check_dropbox_credentials()
if result.status != CredentialStatus.VALID:
invalid_services.append(f"dropbox ({result.message})")
if dist.gdrive_folder_id and not body.is_private:
result = await asyncio.to_thread(credential_manager.check_gdrive_credentials)
result = credential_manager.check_gdrive_credentials()
if result.status != CredentialStatus.VALID:
invalid_services.append(f"gdrive ({result.message})")
+9 -84
View File
@@ -28,7 +28,6 @@ from backend.workers.render_video_worker import process_render_video
from backend.api.dependencies import require_admin
from backend.services.auth_service import AuthResult, UserType
from backend.services.job_manager import JobManager, PREP_PHASE_STATUSES
from backend.utils.loop_bridge import run_in_body_thread, run_on_loop
from backend.services.tracing import (
extract_trace_context,
start_span_with_context,
@@ -777,50 +776,6 @@ async def storage_retention_run_endpoint(
}
ORPHAN_DELETE_CONFIRMATION = "delete-orphan-job-folders"
@router.post("/storage-retention/orphans")
async def storage_retention_orphans_endpoint(
dry_run: bool = True,
confirm: Optional[str] = None,
max_folders: Optional[int] = None,
auth_data: Tuple[str, UserType, int] = Depends(require_admin),
):
"""
One-off cleanup of ``jobs/{id}/`` folders with no job record: keep ``input/``,
delete everything else (backend/services/storage_retention.py purge_orphans).
DRY-RUN unless ``dry_run=false&confirm=delete-orphan-job-folders``. Independent
of STORAGE_RETENTION_DRY_RUN and never run by the scheduler. Runs as the
storage-retention-job Cloud Run Job; the report path is returned.
"""
from datetime import datetime, timezone
from backend.config import get_settings
from backend.services.storage_retention import REPORT_PREFIX
from backend.services.worker_service import get_worker_service
if not dry_run and confirm != ORPHAN_DELETE_CONFIRMATION:
raise HTTPException(
status_code=400,
detail=f"A real orphan cleanup needs confirm={ORPHAN_DELETE_CONFIRMATION}",
)
settings = get_settings()
now = datetime.now(timezone.utc)
report_path = f"{REPORT_PREFIX}/{now.strftime('%Y%m%dT%H%M%SZ')}-orphans-{'dry-run' if dry_run else 'run'}.json"
started = await get_worker_service().trigger_storage_retention_job(
dry_run=dry_run, report_path=report_path, mode="orphans", max_folders=max_folders,
)
if not started:
raise HTTPException(status_code=503, detail="Couldn't start the storage-retention job")
return {
"status": "started",
"mode": "orphans",
"dry_run": dry_run,
"report_path": f"gs://{settings.gcs_bucket_name}/{report_path}",
}
@router.post("/community-daily-pick")
async def community_daily_pick_endpoint(
http_request: Request,
@@ -932,10 +887,7 @@ async def trigger_gdrive_validation_endpoint(
add_span_attribute("brand_code", str(brand_code))
try:
# Sync OIDC fetch + HTTP POST (up to 60s) — off the event loop.
result = await asyncio.to_thread(
trigger_gdrive_validation, brand_code=brand_code, expect_cdg=expect_cdg
)
result = trigger_gdrive_validation(brand_code=brand_code, expect_cdg=expect_cdg)
if result is None:
return {"status": "skipped", "message": "GDRIVE_VALIDATOR_URL not configured"}
@@ -953,16 +905,6 @@ async def retry_pending_render_jobs(
http_request: Request,
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
):
"""Cron: auto-retry RENDER_PENDING_CAPACITY jobs — see ``_retry_pending_render_jobs_sync``.
Firestore scans + updates run in a worker thread (they stalled the loop on
every tick); render triggers run back on the loop.
"""
loop = asyncio.get_running_loop()
return await run_in_body_thread(_retry_pending_render_jobs_sync, http_request, loop)
def _retry_pending_render_jobs_sync(http_request: Request, loop: asyncio.AbstractEventLoop):
"""
Auto-retry jobs parked in RENDER_PENDING_CAPACITY.
@@ -1087,7 +1029,7 @@ def _retry_pending_render_jobs_sync(http_request: Request, loop: asyncio.Abstrac
continue
try:
run_on_loop(loop, worker_service.trigger_render_video_worker(job_id))
await worker_service.trigger_render_video_worker(job_id)
retried.append(job_id)
logger.info(f"[job:{job_id}] Auto-retry triggered")
except Exception as e:
@@ -1120,17 +1062,6 @@ async def recover_stuck_jobs(
http_request: Request,
auth_data: Tuple[str, UserType, int] = Depends(require_admin)
):
"""Cron watchdog for stuck jobs — see ``_recover_stuck_jobs_sync``.
Its Firestore scans were the #1 event-loop staller (~260 stalls in a week,
up to 5s each), so the scan runs in a worker thread; worker re-triggers run
back on the loop.
"""
loop = asyncio.get_running_loop()
return await run_in_body_thread(_recover_stuck_jobs_sync, http_request, loop)
def _recover_stuck_jobs_sync(http_request: Request, loop: asyncio.AbstractEventLoop):
"""
Detect and recover jobs stuck in a processing status.
@@ -1220,7 +1151,7 @@ def _recover_stuck_jobs_sync(http_request: Request, loop: asyncio.AbstractEventL
# 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 _retrigger_parked_download(job_manager, worker_service, job_id, loop):
if await _retrigger_parked_download(job_manager, worker_service, job_id):
download_retried.append(job_id)
# --- Orphaned renders: re-park for automatic retry ---
@@ -1262,7 +1193,7 @@ def _recover_stuck_jobs_sync(http_request: Request, loop: asyncio.AbstractEventL
continue
logger.warning(f"[job:{job_id}] REVIEW_COMPLETE stalled >10 min with no render — re-triggering")
try:
if run_on_loop(loop, worker_service.trigger_render_video_worker(job_id)):
if await worker_service.trigger_render_video_worker(job_id):
render_retriggered.append(job_id)
except Exception as e:
logger.warning(f"[job:{job_id}] render re-trigger failed: {e}")
@@ -1298,7 +1229,7 @@ def _recover_stuck_jobs_sync(http_request: Request, loop: asyncio.AbstractEventL
"no screens — re-triggering"
)
try:
if run_on_loop(loop, job_manager.advance_to_screens_if_ready(job_id)):
if await job_manager.advance_to_screens_if_ready(job_id):
screens_retriggered.append(job_id)
except Exception as e:
logger.warning(f"[job:{job_id}] screens re-trigger failed: {e}")
@@ -1332,7 +1263,7 @@ def _recover_stuck_jobs_sync(http_request: Request, loop: asyncio.AbstractEventL
logger.warning(f"[job:{job_id}] Re-render parked at lyrics_complete >10 min — re-triggering screens")
job_manager.update_job(job_id, {"state_data.screens_progress": _DEL})
try:
if run_on_loop(loop, worker_service.trigger_screens_worker(job_id)):
if await worker_service.trigger_screens_worker(job_id):
regen_screens_retriggered.append(job_id)
except Exception as e: # noqa: BLE001
logger.warning(f"[job:{job_id}] re-render screens re-trigger failed: {e}")
@@ -1503,14 +1434,8 @@ def _park_download_for_retry(job_manager: JobManager, job_id: str, reason: str)
))
def _retrigger_parked_download(
job_manager: JobManager, worker_service, job_id: str, loop: asyncio.AbstractEventLoop
) -> bool:
"""Re-trigger the audio download for a DOWNLOAD_PENDING_RETRY job.
Called from the recover-stuck-jobs worker thread: the Firestore writes run
here, only the trigger coroutine goes back to the loop.
"""
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})
@@ -1524,7 +1449,7 @@ def _retrigger_parked_download(
logger.warning(f"[job:{job_id}] Could not transition parked download for retry")
return False
try:
run_on_loop(loop, worker_service.trigger_audio_download_worker(job_id))
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
+11 -48
View File
@@ -19,7 +19,6 @@ from fastapi import APIRouter, HTTPException, BackgroundTasks, Depends, Request,
from datetime import datetime, timezone
from google.cloud.exceptions import NotFound
from backend.utils.loop_bridge import run_in_body_thread, run_on_loop
from backend.utils.request_helpers import get_client_ip
from backend.models.job import Job, JobCreate, JobResponse, JobStatus
from backend.models.requests import (
@@ -52,7 +51,6 @@ from backend.models.requests import ChangeVisibilityRequest, ChangeVisibilityRes
from backend.services.user_service import get_user_service
from backend.services.youtube_download_service import get_youtube_download_service
from backend.services.pricing import duration_to_credits, is_blocked
from backend.workers.style_helper import screen_included
from pydantic import BaseModel, Field, HttpUrl, validator
@@ -459,13 +457,6 @@ def edit_completed_track(
for key in list(file_urls.get('screens', {}).keys()):
update_payload[f"file_urls.screens.{key}"] = DELETE_FIELD
# Tenant track made with an older theme: the edited version uses the current one.
try:
from backend.services.theme_change_service import edit_theme_update
update_payload.update(edit_theme_update(job, screens_regenerating=metadata_updated))
except Exception as e:
logger.warning(f"Couldn't apply the current theme to edited job {job_id}: {e}")
# Add timeline event with structured metadata
edit_number = (job.edit_count if hasattr(job, 'edit_count') else 0) + 1
timeline_event = {
@@ -590,10 +581,8 @@ def _is_auto_retry_pending(state_data: Optional[Dict[str, Any]]) -> bool:
return expires_at > datetime.now(timezone.utc)
def _has_title_screen(file_urls: Dict[str, Any], state_data: Optional[Dict[str, Any]] = None) -> bool:
"""Return True if the screens stage is done: a title screen image (jpg or png)
was generated, or the theme leaves the title screen out and the screens worker
finished.
def _has_title_screen(file_urls: Dict[str, Any]) -> bool:
"""Return True if a title screen image (jpg or png) was generated.
Used by the /retry endpoint to decide whether to resume from the render
stage or rewind further. The actual screen URLs live under format-specific
@@ -602,15 +591,9 @@ def _has_title_screen(file_urls: Dict[str, Any], state_data: Optional[Dict[str,
completed-review jobs back to AWAITING_REVIEW.
"""
screens = file_urls.get('screens') or {}
if isinstance(screens, dict) and any(k == 'title' or k.startswith('title_') for k in screens):
return True
# No title image by design: rely on the screens worker's completion marker
# (cleared by every re-render/regeneration, so a stale "omitted" can't count).
state_data = state_data or {}
return (
not screen_included(state_data, 'title')
and (state_data.get('screens_progress') or {}).get('stage') == 'complete'
)
if not isinstance(screens, dict):
return False
return any(k == 'title' or k.startswith('title_') for k in screens)
def _prune_state_data(data: Dict[str, Any]) -> Dict[str, Any]:
@@ -2102,13 +2085,12 @@ async def retry_job(
# resume it correctly.
theme_rerender = state_data.get('theme_rerender') or {}
if (theme_rerender.get('theme_id') and original_status == JobStatus.FAILED
and not _has_title_screen(file_urls, state_data)):
and not _has_title_screen(file_urls)):
from backend.services.theme_rerender_service import RerenderError, ThemeRerenderService
try:
await ThemeRerenderService(job_manager).start(
job, theme_id=theme_rerender['theme_id'],
requested_by=auth_result.user_email or "unknown",
notify_customer=theme_rerender.get('notify_customer', True),
)
except RerenderError as e:
raise HTTPException(status_code=e.status_code, detail=str(e))
@@ -2123,7 +2105,7 @@ async def retry_job(
# keeping the admin's notify_customer choice. Its published outputs were
# already removed on the first attempt (recorded in the marker).
if (admin_rerender and original_status in (JobStatus.FAILED, JobStatus.CANCELLED)
and not _has_title_screen(file_urls, state_data)):
and not _has_title_screen(file_urls)):
from backend.services.admin_rerender_service import AdminRerenderService
from backend.services.theme_rerender_service import RerenderError
try:
@@ -2148,7 +2130,7 @@ async def retry_job(
from backend.services.theme_rerender_service import RerenderError
regenerate = active_regenerate(job)
if (regenerate and original_status in (JobStatus.FAILED, JobStatus.CANCELLED)
and (not _has_title_screen(file_urls, state_data) or stems_need_restore(job))):
and (not _has_title_screen(file_urls) or stems_need_restore(job))):
try:
await RegenerateService(job_manager).start(
job,
@@ -2227,7 +2209,7 @@ async def retry_job(
# Review completion is proven by instrumental_selection in state_data
# (set only when user submits the review endpoint)
elif (file_urls.get('lyrics', {}).get('corrections') and
_has_title_screen(file_urls, state_data) and
_has_title_screen(file_urls) and
state_data.get('instrumental_selection')):
logger.info(f"Job {job_id}: Has corrections, screens, and completed review — retrying from render stage")
@@ -2264,7 +2246,7 @@ async def retry_job(
# If we have corrections and screens but review was NOT completed,
# return to awaiting_review so the user can review lyrics
elif (file_urls.get('lyrics', {}).get('corrections') and
_has_title_screen(file_urls, state_data)):
_has_title_screen(file_urls)):
logger.info(f"Job {job_id}: Has corrections and screens but review not completed — returning to review")
@@ -2786,25 +2768,6 @@ async def create_job_from_search(
background_tasks: BackgroundTasks,
body: CreateFromSearchRequest,
auth_result: AuthResult = Depends(require_auth)
) -> JobResponse:
"""Create a job from a search session — see ``_create_job_from_search_sync``.
The work is almost all sync Firestore/GCS I/O (theme prep's upload_json
stalled the loop 5-9s), so it runs in a worker thread; only the audio
download trigger runs back on the loop.
"""
loop = asyncio.get_running_loop()
return await run_in_body_thread(
_create_job_from_search_sync, request, background_tasks, body, auth_result, loop
)
def _create_job_from_search_sync(
request: Request,
background_tasks: BackgroundTasks,
body: CreateFromSearchRequest,
auth_result: AuthResult,
loop: asyncio.AbstractEventLoop,
) -> JobResponse:
"""
Create a karaoke job from a previously completed standalone search session.
@@ -3006,7 +2969,7 @@ def _create_job_from_search_sync(
# Trigger audio download as a Cloud Run Job (survives instance shutdown)
worker_service = get_worker_service()
triggered = run_on_loop(loop, worker_service.trigger_audio_download_worker(job_id))
triggered = await worker_service.trigger_audio_download_worker(job_id)
if not triggered:
job_manager.fail_job(job_id, "Failed to trigger audio download worker")
raise HTTPException(status_code=500, detail="Failed to trigger audio download worker")
+24 -37
View File
@@ -1282,42 +1282,6 @@ async def complete_review(
After saving, triggers the render video worker which will use the
pre-selected instrumental (no separate instrumental selection step).
"""
# Validation + GCS/Firestore writes are all sync (the corrections upload alone
# took 21s on 2026-10-08, freezing every request on the instance) — run them
# in a worker thread; only the render dispatch below runs on the loop.
instrumental_selection = await asyncio.to_thread(_save_review_completion, job_id, updated_data)
# Trigger the render video worker. AWAIT the dispatch (don't fire-and-forget)
# so the Cloud Task / Cloud Run Job dispatch is guaranteed enqueued before we
# return — a background asyncio task can be dropped if the Cloud Run instance
# is recycled right after the response, stranding the job at REVIEW_COMPLETE.
# If the dispatch itself fails we DON'T fail the user's approval: the job is
# safely at REVIEW_COMPLETE and the recover-stuck-jobs watchdog re-triggers
# render for REVIEW_COMPLETE jobs with no render underway within ~5 min.
from backend.services.worker_service import get_worker_service
worker_service = get_worker_service()
try:
await worker_service.trigger_render_video_worker(job_id)
logger.info(f"Job {job_id}: Combined review complete, render video worker triggered")
except Exception as e:
logger.error(
f"Job {job_id}: render trigger failed after review completion "
f"(watchdog will recover): {e}",
exc_info=True,
)
return {
"status": "success",
"instrumental_selection": instrumental_selection,
}
def _save_review_completion(job_id: str, updated_data: Dict[str, Any]) -> str:
"""Validate a review submission, persist it and move the job to REVIEW_COMPLETE.
Sync (blocking GCS + Firestore I/O) — call via ``asyncio.to_thread``.
Returns the resolved instrumental selection.
"""
job_manager = JobManager()
storage = StorageService()
@@ -1434,7 +1398,30 @@ def _save_review_completion(job_id: str, updated_data: Dict[str, Any]) -> str:
progress=70,
message=f"Review complete (instrumental: {instrumental_selection}), rendering video"
)
return instrumental_selection
# Trigger the render video worker. AWAIT the dispatch (don't fire-and-forget)
# so the Cloud Task / Cloud Run Job dispatch is guaranteed enqueued before we
# return — a background asyncio task can be dropped if the Cloud Run instance
# is recycled right after the response, stranding the job at REVIEW_COMPLETE.
# If the dispatch itself fails we DON'T fail the user's approval: the job is
# safely at REVIEW_COMPLETE and the recover-stuck-jobs watchdog re-triggers
# render for REVIEW_COMPLETE jobs with no render underway within ~5 min.
from backend.services.worker_service import get_worker_service
worker_service = get_worker_service()
try:
await worker_service.trigger_render_video_worker(job_id)
logger.info(f"Job {job_id}: Combined review complete, render video worker triggered")
except Exception as e:
logger.error(
f"Job {job_id}: render trigger failed after review completion "
f"(watchdog will recover): {e}",
exc_info=True,
)
return {
"status": "success",
"instrumental_selection": instrumental_selection,
}
except HTTPException:
raise
+4 -107
View File
@@ -29,7 +29,6 @@ from backend.services.tenant_theme_service import (
save_tenant_theme,
store_uploaded_asset,
)
from backend.services.theme_change_service import outdated_jobs, refresh_inflight_jobs
from backend.services.theme_preview_service import ThemePreviewError, render_theme_preview
from backend.services.tenant_admin_service import _theme_id_for
@@ -87,10 +86,8 @@ class PreviewRequest(BaseModel):
class PreviewResponse(BaseModel):
# data:image/jpeg;base64,... — null for a screen the theme leaves out of videos.
title_card: Optional[str] = None
title_card: str # data:image/jpeg;base64,...
karaoke_frame: str
end_screen: Optional[str] = None
class SaveRequest(BaseModel):
@@ -164,110 +161,10 @@ async def preview_theme(body: PreviewRequest, config: TenantConfig = Depends(req
return PreviewResponse(**images.as_data_urls())
class SaveResponse(ThemeResponse):
# In-progress tracks switched to the new theme by this save.
refreshed_jobs: int = 0
# The caller's finished tracks made with an older theme (re-render to update).
outdated_job_ids: List[str] = Field(default_factory=list)
class OutdatedJobsResponse(BaseModel):
theme_updated_at: Optional[str] = None
job_ids: List[str]
class RerenderOutdatedResponse(BaseModel):
started: List[str]
failed: Dict[str, str]
# Outdated tracks beyond this call's cap (ask again to start them).
remaining: List[str] = Field(default_factory=list)
# Tracks started per bulk call: bounds the request time and the burst of
# render/encode work it queues. The UI offers the remainder again.
MAX_BULK_RERENDER = 20
def _owner_scope(auth_result: AuthResult) -> Optional[str]:
"""Admins act on all the portal's tracks; members only on their own."""
return None if auth_result.is_admin else auth_result.user_email
@router.put("", response_model=SaveResponse)
def save_theme(
body: SaveRequest,
config: TenantConfig = Depends(require_tenant_member),
auth_result: AuthResult = Depends(require_auth),
):
@router.put("", response_model=ThemeResponse)
def save_theme(body: SaveRequest, config: TenantConfig = Depends(require_tenant_member)):
try:
save_tenant_theme(config, body.style_params)
theme = get_theme_for_editor(config)
return ThemeResponse(**get_theme_for_editor(config))
except TenantValidationError as exc:
_raise_http(exc)
theme_id = _theme_id_for(config)
# Never fail the save over the follow-up work: the theme is already stored.
refreshed = 0
try:
refreshed = refresh_inflight_jobs(config.id, theme_id)["updated"]
except Exception:
logger.exception(f"Tenant '{config.id}': refreshing in-progress tracks after theme save failed")
outdated: List[str] = []
try:
outdated = outdated_jobs(config.id, theme_id, _owner_scope(auth_result))["job_ids"]
except Exception:
logger.exception(f"Tenant '{config.id}': listing outdated tracks after theme save failed")
return SaveResponse(**theme, refreshed_jobs=refreshed, outdated_job_ids=outdated)
@router.get("/outdated-jobs", response_model=OutdatedJobsResponse)
def get_outdated_jobs(
config: TenantConfig = Depends(require_tenant_member),
auth_result: AuthResult = Depends(require_auth),
):
"""Finished tracks made with an older version of the theme (re-render to update)."""
return OutdatedJobsResponse(**outdated_jobs(config.id, _theme_id_for(config), _owner_scope(auth_result)))
@router.post("/rerender-outdated", response_model=RerenderOutdatedResponse)
async def rerender_outdated(
config: TenantConfig = Depends(require_tenant_member),
auth_result: AuthResult = Depends(require_auth),
):
"""Re-render every outdated finished track with the current theme.
Quiet: no per-track "your video is ready" email/push (one per track would
flood the inbox); the portal shows progress on each track.
"""
from backend.services.job_manager import JobManager
from backend.services.theme_rerender_service import RerenderError, ThemeRerenderService
theme_id = _theme_id_for(config)
job_ids = (await run_in_threadpool(
outdated_jobs, config.id, theme_id, _owner_scope(auth_result)
))["job_ids"]
batch, remaining = job_ids[:MAX_BULK_RERENDER], job_ids[MAX_BULK_RERENDER:]
job_manager = JobManager()
service = ThemeRerenderService(job_manager)
started: List[str] = []
failed: Dict[str, str] = {}
for job_id in batch:
job = await run_in_threadpool(job_manager.get_job, job_id)
if job is None:
continue
try:
await service.start(
job, theme_id=theme_id,
requested_by=auth_result.user_email or "unknown",
notify_customer=False,
)
started.append(job_id)
except RerenderError as e:
failed[job_id] = str(e)
except Exception as e:
logger.exception(f"[job:{job_id}] Bulk theme re-render failed to start")
failed[job_id] = "Couldn't start the re-render."
logger.info(
f"Tenant '{config.id}': bulk re-render started {len(started)}, failed {len(failed)}, "
f"remaining {len(remaining)}"
)
return RerenderOutdatedResponse(started=started, failed=failed, remaining=remaining)
-42
View File
@@ -71,35 +71,6 @@ def validate_credentials_on_startup():
logger.error(f"Failed to validate credentials on startup: {e}")
# Modules that route handlers import lazily. On a fresh instance the first such
# import ran ON the event loop: httpx/httpcore (via flacfetch_client /
# worker_service) froze it 3-15s on cold disk reads (EVENT_LOOP_STALL in
# importlib, 2026-10-08). Lifespan startup imports them in a worker thread before
# readiness — a background thread alone would still race the first request.
_LAZY_ROUTE_IMPORTS = (
"httpx",
"backend.services.worker_service",
"backend.services.flacfetch_client",
"backend.services.catalog_proxy_service",
"backend.services.ip_geolocation_service",
"backend.services.email_validation_service",
"backend.services.musicbrainz_service",
)
LAZY_ROUTE_IMPORT_TIMEOUT_S = 30
def _import_lazy_route_modules() -> None:
import importlib
for module in _LAZY_ROUTE_IMPORTS:
try:
importlib.import_module(module)
except Exception as e:
logger.warning(f"Startup import of {module} failed (will import lazily): {e}")
def _run_background_warmup():
"""Warm caches that used to block startup (runs in a daemon thread).
@@ -166,19 +137,6 @@ async def lifespan(app: FastAPI):
# URL). No-op outside production. (Fallback audit 2026-06-09, Theme 7.)
validate_production_config()
# Off the loop, but before readiness (Cloud Run holds requests meanwhile).
# Bounded so a hung cold-disk read can't keep the instance from ever going
# ready; the import keeps running in its thread and routes fall back to it.
try:
await asyncio.wait_for(
asyncio.to_thread(_import_lazy_route_modules), timeout=LAZY_ROUTE_IMPORT_TIMEOUT_S
)
except asyncio.TimeoutError:
logger.error(
f"Startup import of lazy route modules exceeded {LAZY_ROUTE_IMPORT_TIMEOUT_S}s; "
"continuing startup (first requests may import them on the event loop)"
)
# NLP model / credential warmup runs in the background so it doesn't gate
# readiness — Cloud Run holds all routed requests until lifespan startup
# returns, and these preloads were ~7.5s of the ~16s cold start.
-3
View File
@@ -306,9 +306,6 @@ class Job(BaseModel):
# Theme configuration (pre-made themes from GCS)
theme_id: Optional[str] = None # Theme identifier (e.g., "nomad", "default")
# When the theme was last re-snapshotted onto the job after creation (theme
# edit refresh, re-render, Edit). None = the creation-time snapshot (created_at).
theme_applied_at: Optional[datetime] = None
color_overrides: Dict[str, str] = Field(default_factory=dict)
"""
User color overrides applied on top of theme. Keys:
+1 -5
View File
@@ -204,15 +204,11 @@ def suppress_customer_notifications(job) -> bool:
"""True if this run's customer-facing notifications must be skipped.
Only an active admin re-render the admin didn't opt into announcing
suppresses them; normal jobs and a single tenant theme re-render notify.
suppresses them; normal jobs and the tenant theme re-render always notify.
"""
marker = active_admin_rerender(job)
if marker:
return not marker.get("notify_customer", False)
# A bulk "re-render all outdated tracks" theme re-render is started quietly.
theme_marker = (getattr(job, "state_data", None) or {}).get("theme_rerender") or {}
if theme_marker.get("notify_customer") is False:
return True
# A storage-retention regenerate notifies unless it was started quietly.
from backend.services.regenerate_service import regenerate_suppresses_notifications
return regenerate_suppresses_notifications(job)
-63
View File
@@ -8,7 +8,6 @@ replacing rclone for server-side operations. It handles:
Credentials are loaded from Google Cloud Secret Manager.
"""
import hashlib
import json
import logging
import os
@@ -20,22 +19,6 @@ from google.cloud import secretmanager
logger = logging.getLogger(__name__)
_DROPBOX_HASH_BLOCK = 4 * 1024 * 1024
def dropbox_content_hash(path: str) -> str:
"""Dropbox ``content_hash`` of a local file: SHA-256 of the concatenated
SHA-256 digests of each 4 MiB block (https://www.dropbox.com/developers/reference/content-hash)."""
overall = hashlib.sha256()
with open(path, "rb") as f:
while True:
block = f.read(_DROPBOX_HASH_BLOCK)
if not block:
break
overall.update(hashlib.sha256(block).digest())
return overall.hexdigest()
class DropboxService:
"""Dropbox operations using native Python SDK."""
@@ -301,46 +284,11 @@ class DropboxService:
)
cursor.offset = file_obj.tell()
def _remote_content_hashes(self, remote_path: str) -> dict:
"""``{path_lower: content_hash}`` for every file under ``remote_path``.
Best-effort: a missing folder is empty, and any other error returns ``{}``
(the caller then uploads everything, as before).
"""
from dropbox.exceptions import ApiError
from dropbox.files import FileMetadata
try:
result = self.client.files_list_folder(remote_path, recursive=True)
except ApiError as e:
err = e.error
if err.is_path() and err.get_path().is_not_found():
return {}
logger.warning(f"Couldn't list {remote_path} to skip unchanged files: {e}")
return {}
except Exception as e:
logger.warning(f"Couldn't list {remote_path} to skip unchanged files: {e}")
return {}
hashes = {}
try:
while True:
for entry in result.entries:
if isinstance(entry, FileMetadata) and entry.content_hash:
hashes[entry.path_lower] = entry.content_hash
if not result.has_more:
break
result = self.client.files_list_folder_continue(result.cursor)
except Exception as e:
logger.warning(f"Couldn't finish listing {remote_path} to skip unchanged files: {e}")
return {}
return hashes
def upload_folder(
self,
local_dir: str,
remote_path: str,
exclude_suffixes: Sequence[str] = (),
skip_unchanged: bool = False,
) -> None:
"""
Recursively upload all files and subdirectories to Dropbox folder.
@@ -350,9 +298,6 @@ class DropboxService:
remote_path: Dropbox destination folder path
exclude_suffixes: Filename suffixes to skip (see
dropbox_skip_suffixes_for). Skipped files stay on local disk / GCS.
skip_unchanged: Don't re-upload files already in the folder with the
same Dropbox content hash (one recursive listing up front). Used
when a second pass adds files to a folder that was just uploaded.
"""
# Ensure remote path starts with /
if not remote_path.startswith("/"):
@@ -360,11 +305,8 @@ class DropboxService:
logger.info(f"Uploading folder {local_dir} to {remote_path}")
remote_hashes = self._remote_content_hashes(remote_path) if skip_unchanged else {}
uploaded_count = 0
skipped_count = 0
unchanged_count = 0
for root, _dirs, files in os.walk(local_dir):
# Calculate the relative path from local_dir to current root
rel_root = os.path.relpath(root, local_dir)
@@ -380,17 +322,12 @@ class DropboxService:
continue
local_file = os.path.join(root, filename)
remote_file = f"{current_remote}/{filename}"
remote_hash = remote_hashes.get(remote_file.lower())
if remote_hash and remote_hash == dropbox_content_hash(local_file):
unchanged_count += 1
continue
self.upload_file(local_file, remote_file)
uploaded_count += 1
logger.info(
f"Uploaded {uploaded_count} files to {remote_path}"
+ (f" (skipped {skipped_count} excluded)" if skipped_count else "")
+ (f" ({unchanged_count} already up to date)" if unchanged_count else "")
)
def create_shared_link(self, path: str) -> str:
+1 -7
View File
@@ -137,7 +137,7 @@ class EncodingInput:
Contains all the paths and metadata needed to encode a karaoke video.
"""
# Required input files
title_video_path: Optional[str] # Title card video (MOV); None = theme omits it
title_video_path: str # Title card video (MOV)
karaoke_video_path: str # Main karaoke video with vocals (MOV/MKV)
instrumental_audio_path: str # Instrumental audio track (FLAC)
@@ -465,12 +465,6 @@ class GCEEncodingBackend(EncodingBackend):
if existing_instrumental:
encoding_config["existing_instrumental"] = existing_instrumental
# Screens the theme leaves out: the encoder must skip them rather than
# rebuild them from whatever matching PNG it finds in the job folder.
for flag in ("include_title_screen", "include_end_screen"):
if input_config.options.get(flag) is False:
encoding_config[flag] = False
countdown_padding = input_config.options.get("countdown_padding_seconds")
if countdown_padding:
encoding_config["countdown_padding_seconds"] = countdown_padding
+1 -5
View File
@@ -627,11 +627,7 @@ class EncodingWorkerManager:
zone = config.active_override_zone
if not vm:
# Primary pair was serving — see docstring; leave selection untouched.
# Logged at ERROR so it alerts: on 2026-10-06 a primary that booted
# without its env failed every job for an hour while this was a WARNING.
# The worker now restarts itself (gce_encoding/self_heal.py); if this
# keeps firing, that self-heal isn't working.
logger.error(
logger.warning(
"Active encoding worker hit an infra failure while the primary was "
"serving; leaving selection unchanged for bounded retry: %s", reason,
)
+8 -53
View File
@@ -15,21 +15,11 @@ from contextlib import asynccontextmanager
from pathlib import Path
from typing import Optional
# Force google-auth to reach the metadata server over plain HTTP. google-auth
# >=2.40 switches to mTLS over HTTPS when /run/google-mds-mtls/ certs exist, and
# that handshake fails with CERTIFICATE_VERIFY_FAILED on our images. startup.sh
# sets this in the systemd env file, but the Packer-baked startup-fallback.sh
# (used when GCS is unreachable at boot) does not, which broke every job on
# 2026-10-06. Defaulting it here covers every boot path. Must run before any
# google library is imported.
os.environ.setdefault("GCE_METADATA_MTLS_MODE", "none")
from fastapi import FastAPI, BackgroundTasks, HTTPException, Header, Depends
from google.cloud import storage
from packaging.version import Version
from pydantic import BaseModel
from . import self_heal
from .persistence import JobStatePersister
from backend.utils.audio_filenames import local_audio_filename
@@ -98,28 +88,8 @@ def _persist(job_id: str) -> None:
persister.save(state)
def _has_active_jobs() -> bool:
return any(j.get("status") in ("running", "pending") for j in jobs.values())
def _self_heal_after_failure(error: Exception) -> None:
"""Restart the worker if a job failed because the VM itself can't reach GCP."""
try:
self_heal.schedule_restart_if_unhealthy(str(error), _has_active_jobs)
except Exception as exc: # noqa: BLE001 — must never mask the job failure
logger.warning("Self-heal scheduling failed: %r", exc)
@asynccontextmanager
async def lifespan(app: FastAPI):
# Refuse to serve if this boot came up broken (no API key / no GCP
# credentials, e.g. bootstrap fell back because the network wasn't up yet).
# Failing startup makes uvicorn exit; systemd then re-runs the bootstrap.
problem = await asyncio.to_thread(self_heal.boot_health_problem)
if problem:
logger.critical("Encoding worker booted unhealthy, exiting for systemd restart: %s", problem)
raise RuntimeError(f"Encoding worker booted unhealthy: {problem}")
# Startup: read back any in-progress jobs from Firestore. They were
# interrupted by the restart that brought us here — their work_dir is
# gone, so mark them failed with the restart code so polls return a
@@ -867,13 +837,8 @@ def resolve_instrumental(work_dir: Path, config: dict):
if existing_instrumental:
# User-provided instrumental uploaded at job creation
# Downloaded to work_dir by process_job before run_encoding is called.
# Prefer that top-level copy (it's exactly config["existing_instrumental"]):
# the job folder also holds persisted inputs (input/audio/existing_instrumental.*
# = the raw upload, input/conformed/... = its aligned copy), which the
# recursive glob below could return instead.
top_level = sorted(work_dir.glob("existing_instrumental.*"))
instrumental = top_level[0] if top_level else find_file(
# Downloaded to work_dir by process_job before run_encoding is called
instrumental = find_file(
work_dir,
"*existing_instrumental*", "*Instrumental User*",
)
@@ -1091,20 +1056,15 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
# Title/end screens: look for MOV first, fall back to generating from PNG.
# Since PR #640 right-sized Cloud Run to 2Gi, the screens_worker only generates
# PNG/JPG images — MOV video generation now happens here on the GCE worker.
# A theme may leave a screen out. Don't look for it at all then: the loose globs
# below also match theme assets (style/cdg_title_background.png,
# style/end_background.png) and old finals, which would bring it back.
include_title = config.get("include_title_screen", True) is not False
include_end = config.get("include_end_screen", True) is not False
title_video = find_file(work_dir, "screens/title.mov", "*Title*.mov", "*title*.mov") if include_title else None
end_video = find_file(work_dir, "screens/end.mov", "*End*.mov", "*end*.mov") if include_end else None
title_video = find_file(work_dir, "screens/title.mov", "*Title*.mov", "*title*.mov")
end_video = find_file(work_dir, "screens/end.mov", "*End*.mov", "*end*.mov")
# Get intro/end video durations from style config (default 5s)
intro_duration = config.get("intro_video_duration", 5)
end_duration = config.get("end_video_duration", 5)
# Generate title MOV from PNG if missing or invalid (< 1KB = empty shell)
if include_title and (not title_video or title_video.stat().st_size < 1024):
if not title_video or title_video.stat().st_size < 1024:
title_png = find_file(work_dir, "screens/title.png", "*Title*.png", "*title*.png")
if title_png:
title_mov_path = title_png.parent / "title.mov"
@@ -1114,7 +1074,7 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
logger.warning(f"Title MOV is only {title_video.stat().st_size} bytes and no PNG found")
# Generate end MOV from PNG if missing or invalid
if include_end and (not end_video or end_video.stat().st_size < 1024):
if not end_video or (end_video and end_video.stat().st_size < 1024):
end_png = find_file(work_dir, "screens/end.png", "*End*.png", "*end*.png")
if end_png:
end_mov_path = end_png.parent / "end.mov"
@@ -1169,10 +1129,8 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
logger.info(f" Countdown padding: {countdown_padding_seconds}s - will be handled by LocalEncodingService")
# Validate required files
if include_title and not title_video:
if not title_video:
raise ValueError(f"No title video found in {work_dir}. Check screens/ subdirectory.")
if not include_title or not include_end:
logger.info(f" Theme omits screens: title={'kept' if include_title else 'omitted'}, end={'kept' if include_end else 'omitted'}")
if not karaoke_video:
raise ValueError(f"No karaoke video found in {work_dir}")
if not instrumental:
@@ -1186,7 +1144,7 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
# Build encoding config with proper file names
# Note: countdown_padding_seconds is passed to LocalEncodingService which handles padding
encoding_config = EncodingConfig(
title_video=str(title_video) if title_video else None,
title_video=str(title_video),
karaoke_video=str(karaoke_video),
instrumental_audio=str(instrumental),
end_video=str(end_video) if end_video else None,
@@ -1339,7 +1297,6 @@ async def process_job(job_id: str, request: EncodeRequest):
jobs[job_id]["status"] = "failed"
jobs[job_id]["error"] = str(e)
_persist(job_id)
_self_heal_after_failure(e)
async def process_preview_job(job_id: str, request: EncodePreviewRequest):
@@ -1370,7 +1327,6 @@ async def process_preview_job(job_id: str, request: EncodePreviewRequest):
jobs[job_id]["status"] = "failed"
jobs[job_id]["error"] = str(e)
_persist(job_id)
_self_heal_after_failure(e)
async def process_render_video_job(job_id: str, request: RenderVideoRequest):
@@ -1413,7 +1369,6 @@ async def process_render_video_job(job_id: str, request: RenderVideoRequest):
jobs[job_id]["status"] = "failed"
jobs[job_id]["error"] = str(e)
_persist(job_id)
_self_heal_after_failure(e)
@app.post("/encode-preview")
-148
View File
@@ -1,148 +0,0 @@
"""Self-healing for an encoding worker that booted into a broken state.
Incident 2026-10-06 (job ebfe4344): the primary VM booted before its network was
up, so ``bootstrap.sh`` could not download the CI-managed ``startup.sh`` from GCS
and fell back to the Packer-baked ``startup-fallback.sh``. That fallback wrote an
env file with no ``ENCODING_API_KEY`` and no ``GCE_METADATA_MTLS_MODE=none``, so
google-auth talked mTLS to the metadata server and every job failed with
``CERTIFICATE_VERIFY_FAILED``. The worker still answered /health, and the backend
deliberately keeps retrying the primary on infra errors, so customer renders
looped for an hour until someone ran ``systemctl restart encoding-worker``.
This module performs that restart automatically. Exiting the process makes
systemd (``Restart=always``) re-run ``ExecStartPre=bootstrap.sh``, which, now that
the network is up, downloads the real ``startup.sh`` and rewrites the env file.
Only active on an encoding-worker VM running under systemd (``INVOCATION_ID`` is
set by systemd for every service process, and the Packer image installs
``/opt/encoding-worker/bootstrap.sh``), so local runs, CI and tests never exit.
"""
import logging
import os
import threading
import time
from typing import Callable, Optional
from backend.services.encoding_errors import is_worker_infra_error
logger = logging.getLogger(__name__)
# Credential probe: a few attempts so a single metadata-server blip doesn't
# restart a healthy worker.
PROBE_ATTEMPTS = 3
PROBE_RETRY_SECONDS = 5.0
# After an infra-failed job, wait before checking/restarting so the backend's
# status poll (every ~10s) sees the "failed" status first and parks the job for
# retry rather than hitting a vanished worker.
RESTART_DELAY_SECONDS = 30.0
_restart_lock = threading.Lock()
_restart_pending = False
BOOTSTRAP_PATH = "/opt/encoding-worker/bootstrap.sh"
def running_on_worker_vm() -> bool:
"""True only for the encoding-worker systemd service on a worker VM."""
return bool(os.environ.get("INVOCATION_ID")) and os.path.exists(BOOTSTRAP_PATH)
def _refresh_default_credentials() -> None:
import google.auth
import google.auth.transport.requests
credentials, _ = google.auth.default(
scopes=["https://www.googleapis.com/auth/cloud-platform"]
)
credentials.refresh(google.auth.transport.requests.Request())
def probe_credentials(
attempts: int = PROBE_ATTEMPTS,
retry_seconds: float = PROBE_RETRY_SECONDS,
refresh: Callable[[], None] = _refresh_default_credentials,
) -> Optional[str]:
"""Try to fetch a service-account token. Returns None if healthy, else the last error."""
last_error = ""
for attempt in range(1, attempts + 1):
try:
refresh()
return None
except Exception as e: # noqa: BLE001 — any failure means "can't authenticate"
last_error = str(e) or repr(e)
logger.warning(
"Credential probe failed (attempt %d/%d): %s", attempt, attempts, last_error
)
if attempt < attempts:
time.sleep(retry_seconds)
return last_error
def boot_health_problem(probe: Callable[[], Optional[str]] = probe_credentials) -> Optional[str]:
"""Describe why this worker booted broken, or None if it is fine to serve.
Returns None outside systemd so local/dev runs are unaffected.
"""
if not running_on_worker_vm():
return None
problems = []
if not os.environ.get("ENCODING_API_KEY"):
problems.append("ENCODING_API_KEY is not set (startup fell back without the real env)")
probe_error = probe()
if probe_error:
problems.append(f"cannot obtain GCP credentials: {probe_error}")
return "; ".join(problems) or None
def schedule_restart_if_unhealthy(
error_text: str,
has_active_jobs: Callable[[], bool],
*,
delay_seconds: float = RESTART_DELAY_SECONDS,
probe: Callable[[], Optional[str]] = probe_credentials,
exit_process: Callable[[int], None] = os._exit,
) -> bool:
"""After a job failed with a VM infra/auth error, restart the worker if it is still broken.
Runs in a daemon thread: waits ``delay_seconds``, re-probes credentials, and if
they still fail, waits for in-flight jobs to drain and exits so systemd
re-bootstraps the service. Returns True if a check was scheduled.
"""
global _restart_pending
if not running_on_worker_vm() or not is_worker_infra_error(error_text):
return False
with _restart_lock:
if _restart_pending:
return False
_restart_pending = True
def _run() -> None:
global _restart_pending
try:
while True:
time.sleep(delay_seconds)
probe_error = probe()
if not probe_error:
logger.info("Credentials healthy again after infra failure; not restarting")
return
if has_active_jobs():
logger.warning(
"Credentials still failing but jobs are in flight; "
"re-checking before restarting: %s", probe_error,
)
continue
logger.critical(
"Encoding worker cannot authenticate to GCP (%s); exiting so systemd "
"re-runs the bootstrap", probe_error,
)
exit_process(1)
return
finally:
with _restart_lock:
_restart_pending = False
threading.Thread(target=_run, name="encoding-worker-self-heal", daemon=True).start()
return True
-106
View File
@@ -1,106 +0,0 @@
"""
Keep user-uploaded inputs forever: copy ``uploads/{job_id}/**`` into ``jobs/{job_id}/input/``.
Uploads land under ``uploads/{job_id}/`` (signed-URL / multipart / downloader
destinations). That prefix has a bucket lifecycle delete, and user inputs (the
mix, a bring-your-own instrumental and its conformed copy, a lyrics file, style
uploads) are irreplaceable: re-renders, regenerations after the storage-retention
purge and late reviews all need them again. Losing them made tenant re-renders
fail (2026-10-08: every randy-vild job left in review for >7 days had lost its
mix and instrumental).
``persist_job_inputs`` server-side copies every object under ``uploads/{job_id}/``
to ``jobs/{job_id}/input/<same relative path>`` (``input/`` is KEEP-forever in
``storage_retention``) and repoints every job field that referenced the
``uploads/`` copy. It is idempotent and cheap when there's nothing new, so each
worker calls it on entry: inputs uploaded later in a job's life (conformed
instrumentals, style uploads, review-time uploads) are caught by the next worker.
"""
import logging
from typing import Any, Dict, Optional, Tuple
logger = logging.getLogger(__name__)
UPLOADS_PREFIX = "uploads/"
def uploads_prefix(job_id: str) -> str:
return f"{UPLOADS_PREFIX}{job_id}/"
def persisted_path(job_id: str, path: str) -> Optional[str]:
"""``uploads/{job_id}/a/b.wav`` -> ``jobs/{job_id}/input/a/b.wav`` (None if not this job's upload)."""
prefix = uploads_prefix(job_id)
if not isinstance(path, str) or not path.startswith(prefix) or path == prefix:
return None
return f"jobs/{job_id}/input/{path[len(prefix):]}"
def _rewrites(value: Any, mapping: Dict[str, str], path: str, out: Dict[str, str]) -> None:
"""Collect dotted Firestore field paths whose string value is a mapped upload path."""
if isinstance(value, str):
if value in mapping:
out[path] = mapping[value]
elif isinstance(value, dict):
for key, child in value.items():
if isinstance(key, str) and "." not in key and "`" not in key:
_rewrites(child, mapping, f"{path}.{key}" if path else key, out)
# Job fields that can hold an input path (top-level, plus everything under these maps).
_SCALAR_FIELDS = (
"input_media_gcs_path", "existing_instrumental_gcs_path", "lyrics_file_gcs_path", "style_params_gcs_path",
)
_MAP_FIELDS = ("file_urls", "state_data", "style_assets")
def persist_job_inputs(job, storage, job_manager) -> Tuple[int, Dict[str, str]]:
"""Copy this job's uploads into ``jobs/{id}/input/`` and repoint the job.
Returns ``(objects_copied, field_updates)``. Raises on storage/Firestore errors.
"""
job_id = job.job_id
copied = 0
mapping: Dict[str, str] = {}
for blob in storage.bucket.list_blobs(prefix=uploads_prefix(job_id)):
dest = persisted_path(job_id, blob.name)
if not dest:
continue
mapping[blob.name] = dest
existing = storage.bucket.get_blob(dest)
if existing is not None and existing.md5_hash == blob.md5_hash and existing.size == blob.size:
continue
storage.bucket.copy_blob(blob, storage.bucket, dest)
copied += 1
updates: Dict[str, str] = {}
for field in _SCALAR_FIELDS:
value = getattr(job, field, None)
if value in mapping:
updates[field] = mapping[value]
for field in _MAP_FIELDS:
_rewrites(getattr(job, field, None) or {}, mapping, field, updates)
if updates:
job_manager.update_job(job_id, dict(updates))
# Keep the in-memory job consistent for the caller.
for field in _SCALAR_FIELDS:
if field in updates:
setattr(job, field, updates[field])
if copied or updates:
logger.info(f"Job {job_id}: persisted {copied} upload(s) to jobs/{job_id}/input/; repointed {sorted(updates)}")
return copied, updates
def ensure_job_inputs_persisted(job, storage, job_manager, worker: str = "") -> None:
"""Worker-entry wrapper: never fails the job, but logs an ERROR (alerts) on failure.
The ``uploads/`` lifecycle gives months to retry, and every later worker retries.
"""
try:
persist_job_inputs(job, storage, job_manager)
except Exception as e: # noqa: BLE001
logger.error(
f"Job {getattr(job, 'job_id', '?')}: failed to persist uploaded inputs to jobs/ "
f"({worker or 'worker'}): {e}"
)
-6
View File
@@ -1052,12 +1052,6 @@ class JobManager:
if any(state_data.get(k) for k in ("regenerate", "admin_rerender", "theme_rerender")):
logger.info(f"Job {job_id}: cancelled re-run of a delivered track, skipping refund")
return False
# Same for a customer edit: "Edit" reopens a completed (delivered) track
# for review, so a delete/cancel/fail after it must not refund — otherwise
# complete → edit → delete returns the credit for a video already received.
if job.edit_count:
logger.info(f"Job {job_id}: edited track was already delivered, skipping refund")
return False
credits_charged = int(state_data.get("credits_charged", 1))
if credits_charged == 0:
+23 -20
View File
@@ -25,7 +25,7 @@ logger = logging.getLogger(__name__)
@dataclass
class EncodingConfig:
"""Configuration for video encoding."""
title_video: Optional[str] # Path to title video (None = theme omits the title screen)
title_video: str # Path to title video
karaoke_video: str # Path to karaoke video (with vocals)
instrumental_audio: str # Path to instrumental audio
end_video: Optional[str] = None # Optional path to end credits video
@@ -369,16 +369,16 @@ class LocalEncodingService:
def encode_lossless_mp4(
self,
title_video: Optional[str],
title_video: str,
karaoke_video: str,
output_file: str,
end_video: Optional[str] = None,
) -> bool:
"""
Create lossless 4K MP4 by concatenating the title (if any), karaoke and end (if any) videos.
Create lossless 4K MP4 by concatenating title, karaoke, and optionally end videos.
Args:
title_video: Path to title video, or None when the theme omits the title screen
title_video: Path to title video
karaoke_video: Path to karaoke video
output_file: Path for output file
end_video: Optional path to end credits video
@@ -386,31 +386,34 @@ class LocalEncodingService:
Returns:
True if successful, False otherwise
"""
# (path, hardware-decode) per concat segment, in order
segments = []
if title_video:
segments.append((title_video, True))
segments.append((karaoke_video, True))
if end_video and os.path.isfile(end_video):
segments.append((end_video, False))
# Quote file paths
title_quoted = shlex.quote(os.path.abspath(title_video))
karaoke_quoted = shlex.quote(os.path.abspath(karaoke_video))
def inputs(hwaccel: bool) -> str:
return " ".join(
(f"{self.hwaccel_decode_flags} " if hwaccel and hw else "") + f"-i {shlex.quote(os.path.abspath(path))}"
for path, hw in segments
# Build filter and inputs for concatenation
if end_video and os.path.isfile(end_video):
end_quoted = shlex.quote(os.path.abspath(end_video))
extra_input = f"-i {end_quoted}"
concat_filter = (
'-filter_complex "[0:v:0][0:a:0][1:v:0][1:a:0][2:v:0][2:a:0]'
'concat=n=3:v=1:a=1[outv][outa]"'
)
else:
extra_input = ""
concat_filter = (
'-filter_complex "[0:v:0][0:a:0][1:v:0][1:a:0]'
'concat=n=2:v=1:a=1[outv][outa]"'
)
streams = "".join(f"[{i}:v:0][{i}:a:0]" for i in range(len(segments)))
concat_filter = f'-filter_complex "{streams}concat=n={len(segments)}:v=1:a=1[outv][outa]"'
gpu_command = (
f"{self._ffmpeg_base_command} {inputs(True)} "
f"{self._ffmpeg_base_command} {self.hwaccel_decode_flags} -i {title_quoted} "
f"{self.hwaccel_decode_flags} -i {karaoke_quoted} {extra_input} "
f'{concat_filter} -map "[outv]" -map "[outa]" -c:v {self.video_encoder} '
f'{self._get_nvenc_quality_settings("lossless")} -c:a pcm_s16le '
f'{self.MP4_FLAGS} "{output_file}"'
)
cpu_command = (
f"{self._ffmpeg_base_command} {inputs(False)} "
f"{self._ffmpeg_base_command} -i {title_quoted} -i {karaoke_quoted} {extra_input} "
f'{concat_filter} -map "[outv]" -map "[outa]" -c:v libx264 -c:a pcm_s16le '
f'{self.MP4_FLAGS} "{output_file}"'
)
-54
View File
@@ -88,9 +88,6 @@ class LoopWatchdog:
sample_at_s: tuple[float, ...] = (1.0, 5.0, 15.0),
recorder: Optional[Recorder] = None,
clock: Callable[[], float] = time.monotonic,
cpu_clock: Callable[[], float] = time.process_time,
frozen_gap_s: float = 0.75,
frozen_cpu_ratio: float = 0.25,
) -> None:
self.tick_s = tick_s
self.stall_threshold_s = stall_threshold_s
@@ -99,23 +96,6 @@ class LoopWatchdog:
self.sample_at_s = tuple(sorted(sample_at_s))
self.recorder = recorder
self._clock = clock
self._cpu_clock = cpu_clock
# Cloud Run --cpu-throttling freezes the WHOLE process between requests —
# sometimes mid-callback, where the "loop parked in select()" check can't
# see it (2026-10-08: a 30s "stall" in asyncio's get_debug on an instance
# with no requests in flight). Signature: this watchdog thread itself
# oversleeps by >= frozen_gap_s while the process burns almost no CPU
# (a blocking I/O call lets this thread wake on time; GIL-hogging CPU
# work burns CPU). That frozen time is discounted from the stall.
# 0.75s = 3 missed ticks: measured wake gaps stay <= 0.27s under sync I/O,
# pure-Python CPU and C-extension CPU on the loop, while partial throttling
# gives short 1-2.5s freezes (126 of 128 asyncio-internal "stalls" on
# 2026-10-08 had no request waiting on them).
self.frozen_gap_s = frozen_gap_s
self.frozen_cpu_ratio = frozen_cpu_ratio
self._last_check: Optional[float] = None
self._last_cpu = 0.0
self._stall_frozen_s = 0.0
self._last_tick = clock()
self._loop_thread_id: Optional[int] = None
@@ -190,21 +170,8 @@ class LoopWatchdog:
extra={"loop_stall_age_ms": int(age * 1000), "loop_stall_culprit": culprit},
)
def _frozen_gap(self, now: float) -> float:
"""Seconds since the previous check during which the whole process was frozen."""
cpu = self._cpu_clock()
prev_check, prev_cpu = self._last_check, self._last_cpu
self._last_check, self._last_cpu = now, cpu
if prev_check is None:
return 0.0
gap = now - prev_check
if gap >= self.frozen_gap_s and (cpu - prev_cpu) < gap * self.frozen_cpu_ratio:
return gap
return 0.0
def check(self, now: Optional[float] = None) -> None:
now = self._clock() if now is None else now
frozen = self._frozen_gap(now)
last = self._last_tick
age = now - last
@@ -214,11 +181,8 @@ class LoopWatchdog:
self._stall_started_tick = last
self._samples = []
self._next_sample_idx = 0
self._stall_frozen_s = 0.0
else:
return
# Only the part of the frozen gap after the last heartbeat belongs to this stall.
self._stall_frozen_s += min(frozen, age)
# In a stall: has the heartbeat resumed?
if last > self._stall_started_tick:
@@ -228,16 +192,6 @@ class LoopWatchdog:
self._finish(duration)
return
if frozen:
# Just thawed: the loop's stack shows where the freeze caught it, not
# what blocked it. Skip the samples due during the freeze.
while (
self._next_sample_idx < len(self.sample_at_s)
and age >= self.sample_at_s[self._next_sample_idx]
):
self._next_sample_idx += 1
return
while (
self._next_sample_idx < len(self.sample_at_s)
and age >= self.sample_at_s[self._next_sample_idx]
@@ -247,16 +201,8 @@ class LoopWatchdog:
def _finish(self, duration: float) -> None:
samples = self._samples
frozen_s = self._stall_frozen_s
self._in_stall = False
self._samples = []
self._stall_frozen_s = 0.0
if frozen_s:
logger.debug(
"loop watchdog: discounted %dms of process freeze (CPU throttling) from a %dms gap",
int(frozen_s * 1000), int(duration * 1000),
)
duration = max(0.0, duration - frozen_s)
if duration < self.stall_threshold_s:
return
if samples and all(s.get("idle") for s in samples):
+10 -327
View File
@@ -52,16 +52,6 @@ logger = logging.getLogger(__name__)
POLICY_VERSION = 1
REPORT_PREFIX = "storage-retention/reports"
# Audit trail of every object deleted (kept forever; never touched by any purge
# or lifecycle rule — see docs/STORAGE-RETENTION.md).
DELETION_LOG_PREFIX = "storage-retention/deletion-logs"
MODE_JOB_PURGE = "job_purge"
MODE_ORPHAN = "orphan"
ORPHAN_QUIET_DAYS = 30
# Firestore collections whose doc id == the jobs/{id}/ folder name and that mean
# "this folder still belongs to something". encoding_worker_jobs is NOT one: it's
# the encoder's expiring result cache, left behind by deleted jobs.
ORPHAN_RECORD_COLLECTIONS = ("jobs", "jobs-dev", "youtube_upload_queue")
STATE_COLLECTION = "storage_retention"
STATE_DOC = "state"
SCAN_PAGE_SIZE = 200
@@ -244,7 +234,6 @@ class JobPlan:
stems_purgeable: bool = True
stems_note: Optional[str] = None
skip_reason: Optional[str] = None
generations: Dict[str, Any] = field(default_factory=dict)
@property
def purge_bytes(self) -> int:
@@ -265,26 +254,12 @@ class JobPlan:
return any(c in STEM_CATEGORIES for _, _, c in self.purge)
def _listing_entries(listing) -> List[Tuple[str, int, Any]]:
"""Normalise a listing of ``(name, size)``, ``(name, size, gen)`` or meta dicts."""
out = []
for item in listing:
if isinstance(item, dict):
out.append((item["name"], int(item.get("size") or 0), item.get("generation")))
elif len(item) >= 3:
out.append((item[0], int(item[1] or 0), item[2]))
else:
out.append((item[0], int(item[1] or 0), None))
return out
def plan_job(job: Dict[str, Any], listing) -> JobPlan:
def plan_job(job: Dict[str, Any], listing: List[Tuple[str, int]]) -> JobPlan:
"""Decide what to purge for one (already eligible) job from its GCS listing."""
job_id = job["job_id"]
prefix = f"jobs/{job_id}/"
plan = JobPlan(job_id=job_id)
entries = _listing_entries(listing)
names = {name for name, _, _ in entries}
names = {name for name, _ in listing}
# Re-rendering needs the input audio (render worker + separation). If it's
# gone (e.g. pre-persistence jobs whose input expired from uploads/), nothing
@@ -301,7 +276,7 @@ def plan_job(job: Dict[str, Any], listing) -> JobPlan:
plan.stems_purgeable = False
plan.stems_note = "existing_instrumental"
for name, size, generation in entries:
for name, size in listing:
if not name.startswith(prefix): # defence in depth: never outside jobs/{id}/
continue
action, category = classify_file(
@@ -309,152 +284,11 @@ def plan_job(job: Dict[str, Any], listing) -> JobPlan:
)
if action == PURGE:
plan.purge.append((name, size, category))
plan.generations[name] = generation
else:
plan.kept_bytes += size
return plan
def assert_deletable(path: str) -> None:
"""Hard guard: retention code only ever deletes inside a jobs/{id}/ folder."""
parts = path.split("/")
if len(parts) < 3 or parts[0] != "jobs" or not parts[1] or path.startswith(DELETION_LOG_PREFIX):
raise ValueError(f"refusing to delete outside jobs/{{id}}/: {path}")
def log_category(category: str) -> str:
"""Category label used in the deletion log (finals, review-audio, screens-mov, ...)."""
return category.replace("_", "-")
class DeletionLog:
"""Append-only JSONL audit log of one run's deletions, flushed to GCS in batches.
``storage-retention/deletion-logs/<run-ts>-<mode>.jsonl`` holds one line per
attempted delete; it is re-uploaded (whole) after every batch so a crash
mid-run still leaves a complete record of what was deleted up to the last
flush (the batch in flight is at most ``flush_every`` lines / one job).
"""
def __init__(self, storage, run_ts: datetime, mode: str, flush_every: int = 200):
self.storage = storage
self.mode = mode
self.run_id = f"{run_ts.strftime('%Y%m%dT%H%M%SZ')}-{mode}"
self.path = f"{DELETION_LOG_PREFIX}/{self.run_id}.jsonl"
self.summary_path = f"{DELETION_LOG_PREFIX}/{self.run_id}.summary.json"
self.flush_every = flush_every
self._lines: List[str] = []
self._unflushed = 0
self.totals: Counter = Counter()
self.counts: Counter = Counter()
self.failures = 0
self.jobs: set = set()
# Set when the audit log couldn't be written: callers stop deleting.
self.flush_error: Optional[str] = None
def record(self, job_id: str, path: str, size: int, generation, category: str,
result: str, error: Optional[str] = None) -> None:
import json
entry = {
"timestamp": datetime.now(timezone.utc).isoformat(),
"run_id": self.run_id,
"mode": self.mode,
"job_id": job_id,
"path": path,
"size_bytes": int(size or 0),
"generation": str(generation) if generation is not None else None,
"category": category,
"result": result,
}
if error:
entry["error"] = error[:500]
self._lines.append(json.dumps(entry, ensure_ascii=False))
self._unflushed += 1
if result == "deleted":
self.totals[category] += int(size or 0)
self.counts[category] += 1
self.jobs.add(job_id)
elif result == "failed":
self.failures += 1
if self._unflushed >= self.flush_every:
self.flush()
def flush(self) -> None:
if not self._lines:
return
try:
self.storage.upload_text(self.path, "\n".join(self._lines) + "\n", content_type="application/x-ndjson")
self._unflushed = 0
self.flush_error = None
except Exception as e: # noqa: BLE001 - recorded; the run stops deleting
self.flush_error = str(e)
logger.error(f"storage retention: deletion log flush failed ({self.path}): {e}")
def write_summary(self, extra: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
summary = {
"run_id": self.run_id,
"mode": self.mode,
"deletion_log": self.path,
"objects_deleted": sum(self.counts.values()),
"jobs": len(self.jobs),
"bytes_deleted": sum(self.totals.values()),
"gib_deleted": round(sum(self.totals.values()) / 2**30, 3),
"bytes_by_category": dict(self.totals),
"objects_by_category": dict(self.counts),
"failures": self.failures,
"log_flush_error": self.flush_error,
"written_at": datetime.now(timezone.utc).isoformat(),
**(extra or {}),
}
self.flush()
try:
self.storage.upload_json(self.summary_path, summary)
except Exception as e: # noqa: BLE001
logger.error(f"storage retention: summary write failed ({self.summary_path}): {e}")
return summary
def orphan_candidates(entries: Iterable[Dict[str, Any]], known_ids: set) -> Dict[str, List[Dict[str, Any]]]:
"""Group ``jobs/{id}/...`` objects whose id has no job record."""
folders: Dict[str, List[Dict[str, Any]]] = {}
for meta in entries:
parts = meta["name"].split("/")
if len(parts) < 3 or parts[0] != "jobs" or not parts[1]:
continue
if parts[1] in known_ids:
continue
folders.setdefault(parts[1], []).append(meta)
return folders
def plan_orphan_folder(job_id: str, objects: List[Dict[str, Any]], now: datetime,
quiet_days: int = ORPHAN_QUIET_DAYS) -> Dict[str, Any]:
"""Keep ``input/``; everything else in an orphan folder is deleted (if quiet)."""
prefix = f"jobs/{job_id}/"
latest = None
for meta in objects:
updated = _parse_ts(meta.get("updated"))
if updated and (latest is None or updated > latest):
latest = updated
keep, purge = [], []
for meta in objects:
if not meta["name"].startswith(prefix):
continue
(keep if meta["name"][len(prefix):].startswith("input/") else purge).append(meta)
skip = None
if latest is None or now - latest < timedelta(days=quiet_days):
skip = "recently_modified"
return {
"job_id": job_id,
"latest_update": latest.isoformat() if latest else None,
"skip_reason": skip,
"purge": purge,
"keep": keep,
"purge_bytes": sum(int(m.get("size") or 0) for m in purge),
"keep_bytes": sum(int(m.get("size") or 0) for m in keep),
}
def file_url_deletions(file_urls: Dict[str, Any], purged_paths: Iterable[str]) -> List[str]:
"""Firestore field paths under ``file_urls`` that reference purged blobs."""
purged = set(purged_paths)
@@ -561,10 +395,6 @@ class StorageRetentionService:
"errors": [],
}
totals: Counter = Counter()
deletion_log = None if dry_run else DeletionLog(self.storage, now, MODE_JOB_PURGE)
if deletion_log:
report["deletion_log"] = deletion_log.path
report["deletion_summary"] = deletion_log.summary_path
processed = 0
scanned = 0
last_id = None
@@ -583,7 +413,7 @@ class StorageRetentionService:
report["skipped"][reason] += 1
continue
try:
listing = self.storage.list_blob_meta(f"jobs/{job['job_id']}/")
listing = self.storage.list_files_with_sizes(f"jobs/{job['job_id']}/")
plan = plan_job(job, listing)
except Exception as e: # noqa: BLE001 - one bad job never stops the pass
logger.exception(f"[job:{job.get('job_id')}] storage retention: planning failed")
@@ -608,18 +438,12 @@ class StorageRetentionService:
}
if not dry_run:
try:
entry["result"] = self._execute(job["job_id"], plan, now, min_age, excluded, deletion_log)
entry["result"] = self._execute(job["job_id"], plan, now, min_age, excluded)
except Exception as e: # noqa: BLE001
logger.exception(f"[job:{plan.job_id}] storage retention: purge failed")
entry["result"] = {"status": "error", "error": str(e)}
report["errors"].append({"job_id": plan.job_id, "error": str(e)})
report["jobs"].append(entry)
if deletion_log and deletion_log.flush_error:
# The audit log is a required safety record: no more deletes.
report["errors"].append({"job_id": plan.job_id,
"error": f"deletion log not persisted, run stopped: {deletion_log.flush_error}"})
exhausted = False
break
if not dry_run and entry["result"].get("status") != "purged":
continue
processed += 1
@@ -628,9 +452,6 @@ class StorageRetentionService:
if use_cursor:
self._save_cursor(None if exhausted else last_id)
if deletion_log:
report["deletion_totals"] = deletion_log.write_summary(
{"report_path": report_path or self.default_report_path(now, dry_run)})
report["skipped"] = dict(report["skipped"])
report["summary"] = {
@@ -772,8 +593,7 @@ class StorageRetentionService:
return _run_in_transaction(self.db, claim)
def _execute(self, job_id: str, plan: JobPlan, now: datetime, min_age: int, excluded: List[str],
deletion_log: Optional["DeletionLog"] = None) -> Dict[str, Any]:
def _execute(self, job_id: str, plan: JobPlan, now: datetime, min_age: int, excluded: List[str]) -> Dict[str, Any]:
from google.cloud.firestore_v1 import DELETE_FIELD
if not self._claim(job_id, plan, now, min_age, excluded):
@@ -786,19 +606,11 @@ class StorageRetentionService:
for path, size, category in plan.purge:
if not path.startswith(f"jobs/{job_id}/"):
continue
generation = plan.generations.get(path)
try:
assert_deletable(path)
self.storage.delete_file(path, ignore_missing=True, if_generation_match=generation)
self.storage.delete_file(path, ignore_missing=True)
deleted.append((path, size, category))
if deletion_log:
deletion_log.record(job_id, path, size, generation, log_category(category), "deleted")
except Exception as e: # noqa: BLE001
failures.append({"path": path, "error": str(e)})
if deletion_log:
deletion_log.record(job_id, path, size, generation, log_category(category), "failed", str(e))
if deletion_log:
deletion_log.flush()
snap = ref.get()
file_urls = (snap.to_dict() or {}).get("file_urls") or {} if snap.exists else {}
@@ -818,11 +630,8 @@ class StorageRetentionService:
"policy_version": POLICY_VERSION,
"bytes": sum(by_category.values()),
"bytes_by_category": dict(by_category),
"files": [{"path": p, "bytes": s, "category": c,
"generation": str(plan.generations.get(p)) if plan.generations.get(p) is not None else None}
for p, s, c in deleted],
"files": [{"path": p, "bytes": s, "category": c} for p, s, c in deleted],
"failures": failures,
"deletion_log": deletion_log.path if deletion_log else None,
}
ref.update(update)
except Exception:
@@ -848,14 +657,11 @@ class StorageRetentionService:
"failures": failures,
}
# --- orphan folders -----------------------------------------------------------
def _known_job_ids(self) -> set:
return {snap.id for snap in self.jobs_collection.select(["status"]).stream()}
# --- orphans (report only, never deleted) -------------------------------------
def orphan_job_folders(self) -> Dict[str, Any]:
"""``jobs/{id}/`` folders with no Firestore job doc (report only)."""
known = self._known_job_ids()
known = {snap.id for snap in self.jobs_collection.select(["status"]).stream()}
sizes: Counter = Counter()
for name, size in self.storage.list_files_with_sizes("jobs/"):
parts = name.split("/")
@@ -867,126 +673,3 @@ class StorageRetentionService:
"gib_total": round(total / 2**30, 2),
"largest": [{"job_id": k, "gib": round(v / 2**30, 2)} for k, v in sizes.most_common(20)],
}
def _record_holder(self, job_id: str) -> Optional[str]:
"""Collection that (still) has a record for this folder id, checked live."""
for name in ORPHAN_RECORD_COLLECTIONS:
if self.db.collection(name).document(job_id).get().exists:
return name
return None
def purge_orphans(
self,
dry_run: bool = True,
max_folders: Optional[int] = None,
quiet_days: int = ORPHAN_QUIET_DAYS,
report_path: Optional[str] = None,
now: Optional[datetime] = None,
) -> Dict[str, Any]:
"""Delete everything but ``input/`` from job folders that have no job record.
Candidates come from one bucket listing vs. the ``jobs`` collection; each
folder is then re-checked LIVE before acting: no record in any of
ORPHAN_RECORD_COLLECTIONS, re-listed fresh, and no object modified in the
last ``quiet_days`` days. Dry-run by default.
"""
started = time.time()
now = now or datetime.now(timezone.utc)
known = self._known_job_ids()
candidates = orphan_candidates(self.storage.list_blob_meta("jobs/"), known)
deletion_log = None if dry_run else DeletionLog(self.storage, now, MODE_ORPHAN)
report: Dict[str, Any] = {
"mode": MODE_ORPHAN,
"dry_run": dry_run,
"started_at": now.isoformat(),
"quiet_days": quiet_days,
"record_collections": list(ORPHAN_RECORD_COLLECTIONS),
"candidates": len(candidates),
"folders": [],
"skipped": Counter(),
"not_orphans": [],
"errors": [],
}
if deletion_log:
report["deletion_log"] = deletion_log.path
report["deletion_summary"] = deletion_log.summary_path
acted = 0
purge_bytes = keep_bytes = skipped_bytes = 0
by_ext: Counter = Counter()
for job_id in sorted(candidates):
if max_folders is not None and acted >= max_folders:
report["skipped"]["batch_limit"] += 1
continue
try:
holder = self._record_holder(job_id)
if holder:
report["skipped"]["has_record"] += 1
report["not_orphans"].append({"job_id": job_id, "collection": holder})
continue
fresh = self.storage.list_blob_meta(f"jobs/{job_id}/")
plan = plan_orphan_folder(job_id, fresh, now, quiet_days)
except Exception as e: # noqa: BLE001
report["errors"].append({"job_id": job_id, "error": str(e)})
continue
if plan["skip_reason"]:
report["skipped"][plan["skip_reason"]] += 1
skipped_bytes += plan["purge_bytes"] + plan["keep_bytes"]
continue
if not plan["purge"]:
report["skipped"]["nothing_to_purge"] += 1
keep_bytes += plan["keep_bytes"]
continue
acted += 1
purge_bytes += plan["purge_bytes"]
keep_bytes += plan["keep_bytes"]
for meta in plan["purge"]:
rel = meta["name"].split("/", 2)[2]
by_ext[rel.split("/", 1)[0] if "/" in rel else "(root)"] += int(meta.get("size") or 0)
folder = {
"job_id": job_id, "latest_update": plan["latest_update"],
"purge_bytes": plan["purge_bytes"], "keep_bytes": plan["keep_bytes"],
"purge_objects": len(plan["purge"]), "kept_input_objects": len(plan["keep"]),
}
if not dry_run:
deleted = failed = 0
for meta in plan["purge"]:
path, size, gen = meta["name"], int(meta.get("size") or 0), meta.get("generation")
try:
assert_deletable(path)
self.storage.delete_file(path, ignore_missing=True, if_generation_match=gen)
deletion_log.record(job_id, path, size, gen, "orphan-nonInput", "deleted")
deleted += 1
except Exception as e: # noqa: BLE001
deletion_log.record(job_id, path, size, gen, "orphan-nonInput", "failed", str(e))
failed += 1
deletion_log.flush()
folder.update({"deleted": deleted, "failed": failed})
report["folders"].append(folder)
if deletion_log and deletion_log.flush_error:
report["errors"].append({"job_id": job_id,
"error": f"deletion log not persisted, run stopped: {deletion_log.flush_error}"})
break
report["skipped"] = dict(report["skipped"])
report["summary"] = {
"folders_acted" if not dry_run else "folders_to_purge": acted,
"gib_to_delete" if dry_run else "gib_deleted": round(purge_bytes / 2**30, 2),
"gib_input_kept": round(keep_bytes / 2**30, 2),
"gib_skipped_recent": round(skipped_bytes / 2**30, 2),
"gib_by_top_level_dir": {k: round(v / 2**30, 2) for k, v in by_ext.most_common()},
"duration_seconds": round(time.time() - started, 1),
}
report["report_path"] = report_path or (
f"{REPORT_PREFIX}/{now.strftime('%Y%m%dT%H%M%SZ')}-orphans-{'dry-run' if dry_run else 'run'}.json")
if deletion_log:
report["deletion_totals"] = deletion_log.write_summary({"report_path": report["report_path"]})
try:
self.storage.upload_json(report["report_path"], report)
except Exception as e: # noqa: BLE001
report["report_write_error"] = str(e)
logger.info(
f"STORAGE_RETENTION ORPHANS {'DRY-RUN' if dry_run else 'RUN'}: candidates={len(candidates)} "
f"summary={report['summary']} skipped={report['skipped']} errors={len(report['errors'])} "
f"report=gs://{self.settings.gcs_bucket_name}/{report['report_path']}"
)
return report
+2 -26
View File
@@ -298,8 +298,7 @@ class StorageService:
logger.error(f"Error generating signed {method} URL for {blob_path}: {e}")
raise
def delete_file(self, blob_path: str, ignore_missing: bool = False,
if_generation_match: Optional[int] = None) -> bool:
def delete_file(self, blob_path: str, ignore_missing: bool = False) -> bool:
"""Delete a file from GCS.
Args:
@@ -315,12 +314,7 @@ class StorageService:
"""
try:
blob = self.bucket.blob(blob_path)
if if_generation_match is not None:
# Only delete the exact version that was planned/logged; a newer
# write since then raises PreconditionFailed.
blob.delete(if_generation_match=if_generation_match)
else:
blob.delete()
blob.delete()
logger.info(f"Deleted gs://{settings.gcs_bucket_name}/{blob_path}")
return True
except NotFound:
@@ -379,24 +373,6 @@ class StorageService:
logger.error(f"Error listing files with prefix {prefix}: {e}")
raise
def list_blob_meta(self, prefix: str) -> list:
"""List ``{name, size, generation, updated}`` for every object under ``prefix``."""
try:
return [
{"name": b.name, "size": int(b.size or 0), "generation": b.generation, "updated": b.updated}
for b in self.bucket.list_blobs(prefix=prefix)
]
except Exception as e:
logger.error(f"Error listing files with prefix {prefix}: {e}")
raise
def upload_text(self, destination_path: str, text: str, content_type: str = "text/plain") -> str:
"""Upload a text object (overwrites)."""
blob = self.bucket.blob(destination_path)
blob.cache_control = NO_STORE_CACHE_CONTROL
blob.upload_from_string(text, content_type=content_type)
return destination_path
def get_file_size(self, blob_path: str) -> Optional[int]:
"""Size in bytes of a GCS object, or None if it doesn't exist."""
blob = self.bucket.get_blob(blob_path)
-3
View File
@@ -153,9 +153,6 @@ def sanitize_style_params(
for section in ("intro", "end"):
if "existing_image" in styles[section]:
styles[section]["existing_image"] = None
# Optional on/off switch for including the screen in videos (absent = on).
if "enabled" in styles[section] and not isinstance(styles[section]["enabled"], bool):
raise TenantValidationError(f"{section}.enabled must be true or false.")
for section, field in IMAGE_FIELDS:
value = styles[section].get(field)
-265
View File
@@ -1,265 +0,0 @@
"""
Keep a tenant's tracks in step with its theme after a theme edit.
A job snapshots its theme at creation (``jobs/{id}/style/style_params.json`` +
``style_assets``) and renders from that copy, so a theme edit used to reach only
jobs created afterwards — tracks already in progress (and Edits of finished
tracks) still came out in the old look.
On every theme save, tracks that haven't started rendering get the new theme:
* their style snapshot is replaced, so anything rendered from now on (lyrics
video, screens not yet generated) uses it;
* if their title/end screens may already exist, ``state_data.theme_screens_stale``
is set. When the render worker picks the job up it diverts once through the
screens worker (LYRICS_COMPLETE + ``regen_restore_status=review_complete``,
the same bounce the theme re-render uses), which regenerates the screens and
re-triggers the render. Doing this at render time — rather than right away —
never disturbs a user who is in the middle of reviewing.
Finished tracks can't be refreshed without re-rendering, so they are reported
as "outdated" (theme saved after their snapshot) for the UI to offer a
re-render (``outdated_jobs`` / ``rerender_outdated``).
"""
import logging
from datetime import datetime, timezone
from typing import Dict, List, Optional
from google.cloud.firestore_v1 import DELETE_FIELD, ArrayUnion
from backend.models.job import JobStatus
from backend.services.job_manager import JobManager
from backend.services.storage_service import StorageService
logger = logging.getLogger(__name__)
THEME_SCREENS_STALE_KEY = "theme_screens_stale"
# Not yet rendering: swapping the style snapshot is safe. RENDER_PENDING_CAPACITY
# re-enters the render worker from scratch on its auto-retry. REVIEW_COMPLETE is
# excluded — the render worker may already be loading the old style.
_PRE_SCREENS_STATUSES = frozenset({
JobStatus.PENDING, JobStatus.SEARCHING_AUDIO, JobStatus.AWAITING_AUDIO_SELECTION,
JobStatus.DOWNLOADING_AUDIO, JobStatus.DOWNLOAD_PENDING_RETRY, JobStatus.DOWNLOADING,
JobStatus.AWAITING_AUDIO_EDIT, JobStatus.IN_AUDIO_EDIT, JobStatus.AUDIO_EDIT_COMPLETE,
JobStatus.AWAITING_DURATION_CONFIRM, JobStatus.SEPARATING_STAGE1, JobStatus.SEPARATING_STAGE2,
JobStatus.AUDIO_COMPLETE, JobStatus.TRANSCRIBING, JobStatus.CORRECTING,
JobStatus.LYRICS_COMPLETE,
})
# Screens may already exist (or are being made from the old snapshot right now).
_SCREENS_MADE_STATUSES = frozenset({
JobStatus.GENERATING_SCREENS, JobStatus.APPLYING_PADDING, JobStatus.AWAITING_REVIEW,
JobStatus.IN_REVIEW, JobStatus.RENDER_PENDING_CAPACITY,
})
REFRESHABLE_STATUSES = _PRE_SCREENS_STATUSES | _SCREENS_MADE_STATUSES
def _status_value(status) -> str:
return status.value if hasattr(status, "value") else str(status)
def _as_utc(value) -> Optional[datetime]:
if value is None:
return None
if isinstance(value, str):
try:
value = datetime.fromisoformat(value.replace("Z", "+00:00"))
except ValueError:
return None
if value.tzinfo is None:
value = value.replace(tzinfo=timezone.utc)
return value
def theme_updated_at(theme_id: str, storage: Optional[StorageService] = None) -> Optional[datetime]:
"""When the theme's style was last saved (its style_params.json write time)."""
from backend.services.theme_service import THEMES_PREFIX
storage = storage or StorageService()
try:
blob = storage.bucket.get_blob(f"{THEMES_PREFIX}/{theme_id}/style_params.json")
except Exception as e:
logger.warning(f"Couldn't read theme '{theme_id}' timestamp: {e}")
return None
return _as_utc(blob.updated) if blob is not None else None
def job_theme_applied_at(job) -> Optional[datetime]:
"""When the job's style snapshot was taken (creation unless re-snapshotted)."""
return _as_utc(getattr(job, "theme_applied_at", None)) or _as_utc(getattr(job, "created_at", None))
def snapshot_theme_update(job, theme_id: str) -> Dict:
"""Copy ``theme_id``'s current style onto the job; return the Firestore fields to set.
Writes the job's style folder (GCS) immediately — callers apply the returned
fields themselves (often inside a larger update).
"""
from backend.api.routes.file_upload import _prepare_theme_for_job
style_params_path, style_assets, _ = _prepare_theme_for_job(
job.job_id, theme_id, getattr(job, "color_overrides", None) or None
)
if not style_params_path:
raise ValueError(f"Theme '{theme_id}' has no style to apply.")
return {
"theme_id": theme_id,
"style_params_gcs_path": style_params_path,
"style_assets": style_assets,
"theme_applied_at": datetime.now(timezone.utc),
}
def refresh_inflight_jobs(tenant_id: str, theme_id: str, job_manager: Optional[JobManager] = None) -> Dict[str, int]:
"""Apply the just-saved theme to every tenant track that hasn't started rendering.
Returns ``{"updated": n, "failed": m}``. Best-effort per job: one bad job
never blocks the save or the other jobs.
"""
job_manager = job_manager or JobManager()
updated = failed = 0
jobs = job_manager.list_jobs(tenant_id=tenant_id, limit=1000)
for job in jobs:
if job.status not in REFRESHABLE_STATUSES or getattr(job, "theme_id", None) != theme_id:
continue
try:
update = snapshot_theme_update(job, theme_id)
if job.status in _SCREENS_MADE_STATUSES:
update[f"state_data.{THEME_SCREENS_STALE_KEY}"] = True
update["timeline"] = ArrayUnion([{
"status": _status_value(job.status),
"timestamp": datetime.now(timezone.utc).isoformat(),
"message": "Theme updated: this track will use the new look",
}])
if _update_if_status(job_manager, job.job_id, update, REFRESHABLE_STATUSES):
updated += 1
except Exception as e:
failed += 1
logger.error(f"[job:{job.job_id}] Theme refresh failed: {e}", exc_info=True)
logger.info(f"Tenant '{tenant_id}' theme saved: refreshed {updated} in-progress tracks ({failed} failed)")
return {"updated": updated, "failed": failed}
def _update_if_status(job_manager: JobManager, job_id: str, update: Dict, allowed) -> bool:
"""Apply ``update`` iff the job is still in one of ``allowed`` statuses (transactional)."""
from backend.services.theme_rerender_service import RerenderConflictError, claim_for_rerender
try:
claim_for_rerender(job_manager.firestore.db, job_id, update, {_status_value(s) for s in allowed})
return True
except RerenderConflictError:
logger.info(f"[job:{job_id}] Theme refresh skipped: job moved on")
return False
async def divert_for_stale_screens(job, job_manager: JobManager, storage: Optional[StorageService] = None) -> bool:
"""Render-worker hook: regenerate theme-stale screens before rendering.
Returns True when the job was handed to the screens worker (the render worker
must stop; the screens worker re-triggers it). Returns False to render now.
"""
state_data = job.state_data or {}
if not state_data.get(THEME_SCREENS_STALE_KEY) or job.status != JobStatus.REVIEW_COMPLETE:
return False
from backend.services.theme_rerender_service import (
RerenderConflictError,
claim_for_rerender,
delete_regenerated_artifacts,
)
job_id = job.job_id
now = datetime.now(timezone.utc)
update = {
"status": JobStatus.LYRICS_COMPLETE.value,
f"state_data.{THEME_SCREENS_STALE_KEY}": DELETE_FIELD,
"state_data.regen_restore_status": JobStatus.REVIEW_COMPLETE.value,
"state_data.audio_complete": True,
"state_data.lyrics_complete": True,
"state_data.screens_progress": DELETE_FIELD,
"file_urls.screens": DELETE_FIELD,
"updated_at": now,
"timeline": ArrayUnion([{
"status": JobStatus.LYRICS_COMPLETE.value,
"timestamp": now.isoformat(),
"message": "Regenerating title and end screens with the updated theme",
}]),
}
try:
claim_for_rerender(job_manager.firestore.db, job_id, update, {JobStatus.REVIEW_COMPLETE.value})
except RerenderConflictError:
# Another trigger already moved the job on (e.g. a duplicate dispatch diverted it).
logger.info(f"[job:{job_id}] Stale-screens divert: job no longer review_complete, skipping render")
return True
# Old screens, and (for an Edit of a finished track) old finals MOVs the
# encoder would otherwise splice back in.
delete_regenerated_artifacts(storage or StorageService(), job_id)
from backend.services.worker_service import get_worker_service
if await get_worker_service().trigger_screens_worker(job_id):
logger.info(f"[job:{job_id}] Theme changed since screens were made: regenerating before render")
return True
# Couldn't hand off: put the job back and render with fresh screens on the
# next attempt (flag restored) rather than stranding it.
logger.error(f"[job:{job_id}] Stale-screens divert: failed to trigger screens worker, restoring review_complete")
job_manager.update_job(job_id, {
"status": JobStatus.REVIEW_COMPLETE.value,
"state_data.regen_restore_status": DELETE_FIELD,
f"state_data.{THEME_SCREENS_STALE_KEY}": True,
})
raise RuntimeError("Couldn't regenerate screens for the updated theme")
def outdated_jobs(tenant_id: str, theme_id: str, user_email: Optional[str],
job_manager: Optional[JobManager] = None,
storage: Optional[StorageService] = None) -> Dict:
"""Finished tracks made with an older version of the theme that can be re-rendered.
``user_email`` scopes to the caller's own tracks (None = all, for admins).
"""
from backend.services.theme_rerender_service import validate_rerender
job_manager = job_manager or JobManager()
updated_at = theme_updated_at(theme_id, storage)
result = {"theme_updated_at": updated_at.isoformat() if updated_at else None, "job_ids": []}
if updated_at is None:
return result
# Same (tenant_id, user_email) query shape as the portal's job list, so it
# needs no extra composite index; status is filtered here.
jobs = job_manager.list_jobs(tenant_id=tenant_id, user_email=user_email, limit=1000)
for job in jobs:
if job.status != JobStatus.COMPLETE or getattr(job, "theme_id", None) != theme_id:
continue
applied = job_theme_applied_at(job)
if applied is None or applied >= updated_at:
continue
if validate_rerender(job) is None:
result["job_ids"].append(job.job_id)
return result
def edit_theme_update(job, screens_regenerating: bool) -> Dict:
"""Fields that make an Edit of a finished tenant track use the current theme.
Empty for non-tenant jobs or when the track already has the current theme.
``screens_regenerating``: the Edit already regenerates the screens (metadata
change), which will pick up the new snapshot — no stale flag needed.
"""
tenant_id = getattr(job, "tenant_id", None)
if not tenant_id or not getattr(job, "theme_id", None):
return {}
from backend.services.tenant_admin_service import _theme_id_for
from backend.services.tenant_service import get_tenant_service
config = get_tenant_service().get_tenant_config(tenant_id)
if config is None:
return {}
theme_id = _theme_id_for(config)
if theme_id != job.theme_id:
return {}
updated_at = theme_updated_at(theme_id)
applied = job_theme_applied_at(job)
if updated_at is None or (applied is not None and applied >= updated_at):
return {}
update = snapshot_theme_update(job, theme_id)
if not screens_regenerating:
update[f"state_data.{THEME_SCREENS_STALE_KEY}"] = True
logger.info(f"[job:{job.job_id}] Edit: applying the current theme '{theme_id}'")
return update
+13 -49
View File
@@ -1,13 +1,11 @@
"""
Exact previews of a (draft) theme: the real title card, one karaoke-video frame and
the real end screen.
Exact previews of a (draft) theme: the real title card and one karaoke-video frame.
Used by the tenant theme editor. Both images come from the SAME renderers production
uses, fed the draft ``style_params`` exactly the way a render job would see them:
- **Title card**: ``karaoke_gen.video_generator.VideoGenerator.create_title_video``
with ``intro_video_duration=0`` (PNG only — what ``screens_worker`` does on Cloud Run).
- **End screen**: ``VideoGenerator.create_end_video`` the same way (``end_video_duration=0``).
- **Karaoke frame**: ``SegmentResizer`` → ``SubtitlesGenerator.generate_ass`` (the
generator's 4K layout: ``font_size`` default 250, ``line_height = font_size``,
``max_line_length`` default 36) → one frame burned with the same ffmpeg ``ass``
@@ -89,18 +87,12 @@ def font_family_name(font_file: str) -> str:
@dataclass
class PreviewImages:
# JPEGs. A screen the theme omits from videos (``enabled: false``) isn't rendered.
title_card: Optional[bytes]
karaoke_frame: bytes
end_screen: Optional[bytes] = None
title_card: bytes # JPEG
karaoke_frame: bytes # JPEG
def as_data_urls(self) -> Dict[str, Optional[str]]:
enc = lambda b: "data:image/jpeg;base64," + base64.b64encode(b).decode() if b else None # noqa: E731
return {
"title_card": enc(self.title_card),
"karaoke_frame": enc(self.karaoke_frame),
"end_screen": enc(self.end_screen),
}
def as_data_urls(self) -> Dict[str, str]:
enc = lambda b: "data:image/jpeg;base64," + base64.b64encode(b).decode() # noqa: E731
return {"title_card": enc(self.title_card), "karaoke_frame": enc(self.karaoke_frame)}
# ---------------------------------------------------------------------------
@@ -228,26 +220,22 @@ def _to_jpeg(png_path: str) -> bytes:
return buf.getvalue()
def _screen_generator():
def render_title_card(styles: Dict, artist: str, title: str, workdir: str) -> bytes:
"""Title card exactly as screens_worker renders it (PNG via PIL, no video)."""
from karaoke_gen.style_loader import DEFAULT_INTRO_STYLE
from karaoke_gen.video_generator import VideoGenerator
return VideoGenerator(
fmt = {**DEFAULT_INTRO_STYLE, **(styles.get("intro") or {})}
generator = VideoGenerator(
logger=logger,
ffmpeg_base_command="ffmpeg -hide_banner -nostats -loglevel error",
render_bounding_boxes=False,
output_png=True,
output_jpg=False,
)
def render_title_card(styles: Dict, artist: str, title: str, workdir: str) -> bytes:
"""Title card exactly as screens_worker renders it (PNG via PIL, no video)."""
from karaoke_gen.style_loader import DEFAULT_INTRO_STYLE
fmt = {**DEFAULT_INTRO_STYLE, **(styles.get("intro") or {})}
noext = os.path.join(workdir, "title")
try:
_screen_generator().create_title_video(
generator.create_title_video(
artist=artist,
title=title,
format=fmt,
@@ -261,27 +249,6 @@ def render_title_card(styles: Dict, artist: str, title: str, workdir: str) -> by
return _to_jpeg(f"{noext}.png")
def render_end_screen(styles: Dict, artist: str, title: str, workdir: str) -> bytes:
"""End screen exactly as screens_worker renders it (PNG via PIL, no video)."""
from karaoke_gen.style_loader import DEFAULT_END_STYLE
fmt = {**DEFAULT_END_STYLE, **(styles.get("end") or {})}
noext = os.path.join(workdir, "end")
try:
_screen_generator().create_end_video(
artist=artist,
title=title,
format=fmt,
output_image_filepath_noext=noext,
output_video_filepath=os.path.join(workdir, "end.mov"),
existing_end_image=fmt.get("existing_image"),
end_video_duration=0,
)
except Exception as exc:
raise ThemePreviewError(f"End screen render failed: {exc}") from exc
return _to_jpeg(f"{noext}.png")
def _sample_segments(lines: List[str], translations: Optional[List[str]] = None):
"""Evenly-timed segments: line i starts at 2+3i s, words spread over 2.5 s.
@@ -439,14 +406,11 @@ def render_theme_preview(
_CACHE.move_to_end(key)
return _CACHE[key]
from karaoke_gen.style_loader import screen_enabled
styles = resolve_assets(style_params, theme_id, storage)
with tempfile.TemporaryDirectory(prefix="theme-preview-") as workdir:
result = PreviewImages(
title_card=render_title_card(styles, artist, title, workdir) if screen_enabled(styles, "intro") else None,
title_card=render_title_card(styles, artist, title, workdir),
karaoke_frame=render_karaoke_frame(styles, lines, workdir),
end_screen=render_end_screen(styles, artist, title, workdir) if screen_enabled(styles, "end") else None,
)
with _cache_lock:
_CACHE[key] = result
+5 -11
View File
@@ -20,7 +20,6 @@ the job's existing brand code (see rerender_brand_code). Jobs published to
YouTube/GDrive are rejected — those would need the delete/redistribute dance of
the visibility flow, which tenants don't use.
"""
import asyncio
import logging
from datetime import datetime, timezone
from typing import Optional
@@ -181,7 +180,7 @@ class ThemeRerenderService:
self.job_manager = job_manager or JobManager()
self.storage = storage or StorageService()
async def start(self, job, theme_id: str, requested_by: str, notify_customer: bool = True) -> None:
async def start(self, job, theme_id: str, requested_by: str) -> None:
"""Re-snapshot ``theme_id`` onto the job and kick off the re-render.
Raises RerenderConflictError if the job stopped being COMPLETE (e.g. a
@@ -196,9 +195,8 @@ class ThemeRerenderService:
# claim so a failure here leaves the job untouched; overwriting the style
# copy of a still-complete job is harmless (its finals are already made).
from backend.api.routes.file_upload import _prepare_theme_for_job
# GCS / Firestore calls are blocking: keep them off the event loop.
style_params_path, style_assets, _ = await asyncio.to_thread(
_prepare_theme_for_job, job_id, theme_id, getattr(job, "color_overrides", None) or None
style_params_path, style_assets, _ = _prepare_theme_for_job(
job_id, theme_id, getattr(job, "color_overrides", None) or None
)
if not style_params_path:
raise RerenderError(f"Theme '{theme_id}' has no style to apply.", status_code=500)
@@ -210,15 +208,12 @@ class ThemeRerenderService:
"theme_id": theme_id,
"style_params_gcs_path": style_params_path,
"style_assets": style_assets,
"theme_applied_at": now,
"error_message": None,
"error_details": None,
"state_data.regen_restore_status": "review_complete",
"state_data.audio_complete": True,
"state_data.lyrics_complete": True,
"state_data.screens_progress": DELETE_FIELD,
# Screens are regenerated by this run anyway.
"state_data.theme_screens_stale": DELETE_FIELD,
"state_data.render_progress": DELETE_FIELD,
"state_data.video_progress": DELETE_FIELD,
"state_data.encoding_progress": DELETE_FIELD,
@@ -226,7 +221,6 @@ class ThemeRerenderService:
"requested_by": requested_by,
"requested_at": now.isoformat(),
"theme_id": theme_id,
"notify_customer": notify_customer,
"brand_code": (job.state_data or {}).get("brand_code")
or ((job.state_data or {}).get("theme_rerender") or {}).get("brand_code"),
},
@@ -241,9 +235,9 @@ class ThemeRerenderService:
"message": f"Re-render with current theme '{theme_id}' requested by {requested_by}",
}]),
}
await asyncio.to_thread(self._claim, job_id, update, _claimable_statuses(job))
self._claim(job_id, update, _claimable_statuses(job))
await asyncio.to_thread(self._delete_stale_artifacts, job_id)
self._delete_stale_artifacts(job_id)
from backend.services.worker_service import get_worker_service
triggered = await get_worker_service().trigger_screens_worker(job_id)
@@ -231,12 +231,6 @@ class VisibilityChangeService:
"state_data.render_progress": DELETE_FIELD,
"state_data.video_progress": DELETE_FIELD,
"state_data.encoding_progress": DELETE_FIELD,
# Their blobs were deleted above. A stale videos.with_vocals ref made
# a retry after a failed render skip the render and 404 on the
# missing MKV (job 82f48738); the workers re-add all three.
"file_urls.screens": DELETE_FIELD,
"file_urls.videos.with_vocals": DELETE_FIELD,
"file_urls.finals": DELETE_FIELD,
"outputs_deleted_at": None,
"outputs_deleted_by": None,
"updated_at": datetime.now(timezone.utc),
+3 -10
View File
@@ -459,8 +459,6 @@ class WorkerService:
report_path: str,
max_jobs: Optional[int] = None,
include_orphans: bool = False,
mode: str = "job_purge",
max_folders: Optional[int] = None,
) -> bool:
"""Start the storage-retention pass as the ``storage-retention-job`` Cloud Run Job.
@@ -472,10 +470,6 @@ class WorkerService:
args += ["--max-jobs", str(int(max_jobs))]
if include_orphans:
args.append("--include-orphans")
if mode != "job_purge":
args += ["--mode", mode]
if max_folders is not None:
args += ["--max-folders", str(int(max_folders))]
if not self._use_cloud_tasks and not is_production():
return self._run_worker_module_locally("storage_retention_worker", args, log_prefix="[storage-retention]")
try:
@@ -625,7 +619,7 @@ class WorkerService:
uses Cloud Run Jobs for execution (supports >30 min encoding).
Otherwise, uses Cloud Tasks or direct HTTP.
"""
await asyncio.to_thread(self._bump_worker_generation, job_id) # Firestore write
self._bump_worker_generation(job_id)
self._start_encoding_worker_warmup(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)
@@ -663,8 +657,7 @@ class WorkerService:
last_exc: Optional[Exception] = None
for attempt in range(1, _RUN_JOB_MAX_ATTEMPTS + 1):
try:
# Sync gRPC call (~1s) — keep it off the event loop.
return await asyncio.to_thread(client.run_job, request=request)
return client.run_job(request=request)
except _TRANSIENT_RUN_JOB_ERRORS as e:
last_exc = e
if attempt >= _RUN_JOB_MAX_ATTEMPTS:
@@ -796,7 +789,7 @@ class WorkerService:
rendering_video (incident 2026-09-13, job 41e06b90 — same class as
incident 2026-03-08 which migrated the video worker to Cloud Run Jobs).
"""
await asyncio.to_thread(self._bump_worker_generation, job_id) # Firestore write
self._bump_worker_generation(job_id)
self._start_encoding_worker_warmup(job_id)
if self._use_cloud_tasks and self.settings.use_cloud_run_jobs_for_render:
return await self._trigger_worker_cloud_run_job(
+10 -37
View File
@@ -13,7 +13,6 @@ This service handles:
import logging
import os
import time
from typing import Optional, Dict, Any, Tuple
from thefuzz import fuzz
@@ -33,15 +32,6 @@ class YouTubeUploadService:
YOUTUBE_URL_PREFIX = "https://www.youtube.com/watch?v="
SCOPES = ["https://www.googleapis.com/auth/youtube"]
# Resumable-upload robustness. Within one upload session, googleapiclient
# resumes chunks itself on 5xx/429/rate-limit responses (``num_retries``).
# A 404/410 means YouTube dropped the session entirely ("Gone") — nothing
# was created, so the only fix is a fresh session from byte 0.
UPLOAD_NUM_RETRIES = 3
UPLOAD_SESSION_ATTEMPTS = 3
UPLOAD_SESSION_LOST_STATUSES = (404, 410)
UPLOAD_RESTART_BACKOFF_SECONDS = 5
def __init__(
self,
credentials: Optional[Dict[str, Any]] = None,
@@ -382,7 +372,16 @@ class YouTubeUploadService:
}.get(ext, "video/*")
# Upload video
response = self._execute_resumable_insert(video_path, mime_type, body)
self.logger.info(f"Authenticating with YouTube...")
media_file = MediaFileUpload(video_path, mimetype=mime_type, resumable=True)
self.logger.info(f"Uploading video to YouTube...")
request = self.youtube_service.videos().insert(
part="snippet,status",
body=body,
media_body=media_file
)
response = request.execute()
video_id = response.get("id")
video_url = f"{self.YOUTUBE_URL_PREFIX}{video_id}"
@@ -409,32 +408,6 @@ class YouTubeUploadService:
return video_id, video_url
def _execute_resumable_insert(self, video_path: str, mime_type: str, body: Dict[str, Any]) -> Dict[str, Any]:
"""Run ``videos.insert`` as a resumable upload, restarting if the session is lost."""
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaFileUpload
for attempt in range(1, self.UPLOAD_SESSION_ATTEMPTS + 1):
media_file = MediaFileUpload(video_path, mimetype=mime_type, resumable=True)
self.logger.info(f"Uploading video to YouTube (attempt {attempt}/{self.UPLOAD_SESSION_ATTEMPTS})...")
request = self.youtube_service.videos().insert(
part="snippet,status",
body=body,
media_body=media_file
)
try:
return request.execute(num_retries=self.UPLOAD_NUM_RETRIES)
except HttpError as e:
status = getattr(e.resp, "status", None)
if status not in self.UPLOAD_SESSION_LOST_STATUSES or attempt == self.UPLOAD_SESSION_ATTEMPTS:
raise
delay = self.UPLOAD_RESTART_BACKOFF_SECONDS * attempt
self.logger.warning(
f"YouTube upload session lost (HTTP {status}), restarting upload in {delay}s: {e}"
)
time.sleep(delay)
raise RuntimeError("unreachable") # loop always returns or raises
# Singleton instance and factory function (following existing service pattern)
_youtube_upload_service: Optional[YouTubeUploadService] = None
-29
View File
@@ -263,35 +263,6 @@ class TestChangeToPublic:
assert style_update["is_private"] is False
assert style_update["status"] == "lyrics_complete"
@pytest.mark.asyncio
async def test_drops_file_urls_for_deleted_artifacts(self):
"""Screens, lyrics video and finals blobs are deleted, so their refs must go
too: a stale videos.with_vocals made retry skip the render and 404 (82f48738)."""
# The service's own sentinel: other tests may swap google.cloud.firestore_v1 for a mock.
from backend.services.visibility_change_service import DELETE_FIELD
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=("p.json", {}, None)), \
patch("backend.services.worker_service.get_worker_service") as mock_worker_svc:
mock_storage_cls.return_value = MagicMock()
mock_worker_svc.return_value.trigger_screens_worker = AsyncMock(return_value=True)
await service.change_to_public("test-123", job, "user@example.com")
payload = next(c.args[0] for c in mock_job_ref.update.call_args_list if "theme_id" in c.args[0])
assert payload["file_urls.screens"] is DELETE_FIELD
assert payload["file_urls.videos.with_vocals"] is DELETE_FIELD
assert payload["file_urls.finals"] is DELETE_FIELD
@pytest.mark.asyncio
async def test_rollback_on_worker_failure(self):
mock_job_manager = MagicMock()
+3 -38
View File
@@ -144,13 +144,11 @@ class TestCreditRefundOnJobFailure:
amount instead of a hard-coded 1.
"""
def _mock_job(self, credits_charged=1, credit_refunded=False, user_email="user@test.com",
edit_count=0):
def _mock_job(self, credits_charged=1, credit_refunded=False, user_email="user@test.com"):
"""Helper: build a minimal mock Job with state_data.credits_charged."""
job = Mock(spec=Job)
job.user_email = user_email
job.credit_refunded = credit_refunded
job.edit_count = edit_count
job.state_data = {"credits_charged": credits_charged}
return job
@@ -260,12 +258,11 @@ class TestCreditRefundOnJobCancellation:
"""
def _mock_job(self, credits_charged=1, credit_refunded=False,
user_email="user@test.com", status=None, edit_count=0):
user_email="user@test.com", status=None):
"""Helper: build a minimal mock Job with state_data.credits_charged."""
job = Mock(spec=Job)
job.user_email = user_email
job.credit_refunded = credit_refunded
job.edit_count = edit_count
job.state_data = {"credits_charged": credits_charged}
job.status = status or JobStatus.PENDING
return job
@@ -302,19 +299,6 @@ class TestCreditRefundOnJobCancellation:
"user@test.com", amount=4, reason="job_cancelled", job_id="job123"
)
def test_cancel_of_edited_track_skips_refund(
self, job_manager, mock_firestore_service, mock_user_service
):
"""Cancelling a re-edit of a delivered track doesn't refund the original credit."""
mock_job = self._mock_job(credits_charged=1, status=JobStatus.AWAITING_REVIEW, edit_count=2)
mock_firestore_service.get_job.return_value = mock_job
mock_firestore_service.update_job_status.return_value = True
with patch('backend.services.auth_service.is_admin_email', return_value=False):
job_manager.cancel_job("job123")
mock_user_service.add_credits.assert_not_called()
def test_cancel_guard_prevents_double_refund_when_credit_refunded(
self, job_manager, mock_firestore_service, mock_user_service
):
@@ -388,11 +372,10 @@ class TestCreditRefundOnJobDeletion:
"""
def _mock_job(self, credits_charged=1, credit_refunded=False,
user_email="user@test.com", status=None, edit_count=0):
user_email="user@test.com", status=None):
job = Mock(spec=Job)
job.user_email = user_email
job.credit_refunded = credit_refunded
job.edit_count = edit_count
job.state_data = {"credits_charged": credits_charged}
job.status = status or JobStatus.PENDING
job.output_files = {}
@@ -457,24 +440,6 @@ class TestCreditRefundOnJobDeletion:
mock_user_service.add_credits.assert_not_called()
@pytest.mark.parametrize("status", [JobStatus.AWAITING_REVIEW, JobStatus.LYRICS_COMPLETE])
def test_no_refund_on_delete_of_edited_track(
self, job_manager, mock_firestore_service, mock_user_service, status
):
"""Complete → Edit → Delete must not refund: the track was already delivered.
Edit reopens a completed job (AWAITING_REVIEW, or LYRICS_COMPLETE when
metadata changed), so its status alone looks "never completed".
"""
mock_job = self._mock_job(credits_charged=1, status=status, edit_count=1)
mock_firestore_service.get_job.return_value = mock_job
with patch('backend.services.auth_service.is_admin_email', return_value=False):
job_manager.delete_job("job123")
mock_user_service.add_credits.assert_not_called()
mock_firestore_service.delete_job.assert_called_once_with("job123")
def test_delete_refund_failure_does_not_block_deletion(
self, job_manager, mock_firestore_service, mock_user_service
):
@@ -806,42 +806,6 @@ class TestVideoWorkerDistribution:
# Should log warning about not configured
mock_job_log.warning.assert_called()
@pytest.mark.asyncio
async def test_handle_native_distribution_dropbox_skips_unchanged(self):
"""The second Dropbox pass only sends what the orchestrator didn't already upload."""
from backend.workers.video_worker import _handle_native_distribution
mock_job = MagicMock()
mock_job.dropbox_path = "/Tracks"
mock_job.brand_prefix = "NOMAD"
mock_job.gdrive_folder_id = None
mock_job.is_private = False
mock_job.keep_brand_code = None
mock_job.artist = "Eli"
mock_job.title = "The Comeback"
mock_job.state_data = {}
mock_dropbox = MagicMock()
mock_dropbox.is_configured = True
mock_dropbox.create_shared_link.return_value = "https://dropbox/link"
dist = MagicMock(dropbox_path="/Tracks", brand_prefix="NOMAD", gdrive_folder_id=None)
with patch('backend.services.dropbox_service.get_dropbox_service', return_value=mock_dropbox), \
patch('backend.services.job_defaults_service.get_effective_distribution_for_job', return_value=dist), \
patch('backend.services.theme_rerender_service.rerender_brand_code', return_value=None):
await _handle_native_distribution(
job_id="test-123",
job=mock_job,
job_log=MagicMock(),
job_manager=MagicMock(),
temp_dir="/tmp/test",
result={"brand_code": "NOMAD-1754", "dropbox_link": "https://dropbox/link"},
)
args, kwargs = mock_dropbox.upload_folder.call_args
assert args == ("/tmp/test", "/Tracks/NOMAD-1754 - Eli - The Comeback")
assert kwargs["skip_unchanged"] is True
@pytest.mark.asyncio
async def test_handle_native_distribution_gdrive_not_configured(self):
"""Test Google Drive upload skipped when service not configured."""
-119
View File
@@ -658,122 +658,3 @@ class TestEnsureFolderAndMissingPaths:
)
with pytest.raises(ApiError):
service.list_folders("/Tracks-New")
class TestUploadFolderSkipUnchanged:
"""The video worker's second Dropbox pass (after the orchestrator uploaded the
same folder) must only send new/changed files, not re-upload everything."""
def _service(self):
from backend.services.dropbox_service import DropboxService
service = DropboxService()
service._client = Mock()
return service
@staticmethod
def _file_entry(path_lower, content_hash):
from dropbox.files import FileMetadata
entry = Mock(spec=FileMetadata)
entry.path_lower = path_lower
entry.content_hash = content_hash
return entry
def _listing(self, entries, has_more=False, cursor="c1"):
result = Mock()
result.entries = entries
result.has_more = has_more
result.cursor = cursor
return result
def test_content_hash_matches_dropbox_algorithm(self, tmp_path):
import hashlib
from backend.services.dropbox_service import dropbox_content_hash
block = 4 * 1024 * 1024
data = b"a" * block + b"b" * 10 # two blocks
f = tmp_path / "x.bin"
f.write_bytes(data)
expected = hashlib.sha256(
hashlib.sha256(data[:block]).digest() + hashlib.sha256(data[block:]).digest()
).hexdigest()
assert dropbox_content_hash(str(f)) == expected
empty = tmp_path / "empty.bin"
empty.write_bytes(b"")
assert dropbox_content_hash(str(empty)) == hashlib.sha256(b"").hexdigest()
def test_skips_identical_uploads_new_and_changed(self, tmp_path):
from backend.services.dropbox_service import dropbox_content_hash
(tmp_path / "Song (Final Karaoke Lossy 4k).mp4").write_bytes(b"video")
(tmp_path / "Song (Karaoke).cdg").write_bytes(b"cdg-new")
(tmp_path / "stems").mkdir()
(tmp_path / "stems" / "Song (Vocals).flac").write_bytes(b"vocals")
service = self._service()
service._client.files_list_folder.return_value = self._listing([
self._file_entry(
"/tracks/nomad-1 - song/song (final karaoke lossy 4k).mp4",
dropbox_content_hash(str(tmp_path / "Song (Final Karaoke Lossy 4k).mp4")),
),
self._file_entry("/tracks/nomad-1 - song/song (karaoke).cdg", "stale-hash"),
])
with patch.object(service, "upload_file") as up:
service.upload_folder(str(tmp_path), "/Tracks/NOMAD-1 - Song", skip_unchanged=True)
uploaded = sorted(call.args[1] for call in up.call_args_list)
assert uploaded == [
"/Tracks/NOMAD-1 - Song/Song (Karaoke).cdg", # changed
"/Tracks/NOMAD-1 - Song/stems/Song (Vocals).flac", # new
]
service._client.files_list_folder.assert_called_once_with("/Tracks/NOMAD-1 - Song", recursive=True)
def test_listing_paginates(self, tmp_path):
from backend.services.dropbox_service import dropbox_content_hash
(tmp_path / "a.txt").write_bytes(b"a")
(tmp_path / "b.txt").write_bytes(b"b")
service = self._service()
service._client.files_list_folder.return_value = self._listing(
[self._file_entry("/f/a.txt", dropbox_content_hash(str(tmp_path / "a.txt")))], has_more=True
)
service._client.files_list_folder_continue.return_value = self._listing(
[self._file_entry("/f/b.txt", dropbox_content_hash(str(tmp_path / "b.txt")))]
)
with patch.object(service, "upload_file") as up:
service.upload_folder(str(tmp_path), "/f", skip_unchanged=True)
up.assert_not_called()
def test_missing_folder_uploads_everything(self, tmp_path):
from dropbox.exceptions import ApiError
from dropbox.files import ListFolderError, LookupError as DbxLookupError
(tmp_path / "a.txt").write_bytes(b"a")
service = self._service()
service._client.files_list_folder.side_effect = ApiError(
"req", ListFolderError.path(DbxLookupError.not_found), "msg", "hdr"
)
with patch.object(service, "upload_file") as up:
service.upload_folder(str(tmp_path), "/new", skip_unchanged=True)
up.assert_called_once()
def test_listing_failure_falls_back_to_full_upload(self, tmp_path):
(tmp_path / "a.txt").write_bytes(b"a")
(tmp_path / "b.txt").write_bytes(b"b")
service = self._service()
service._client.files_list_folder.side_effect = RuntimeError("network down")
with patch.object(service, "upload_file") as up:
service.upload_folder(str(tmp_path), "/f", skip_unchanged=True)
assert up.call_count == 2
def test_default_does_not_list_or_skip(self, tmp_path):
(tmp_path / "a.txt").write_bytes(b"a")
service = self._service()
with patch.object(service, "upload_file") as up:
service.upload_folder(str(tmp_path), "/f")
service._client.files_list_folder.assert_not_called()
up.assert_called_once()
@@ -1,246 +0,0 @@
"""Encoding worker self-heal (backend/services/gce_encoding/self_heal.py).
Incident 2026-10-06: the primary booted before its network was up, fell back to a
startup script that omitted ENCODING_API_KEY and GCE_METADATA_MTLS_MODE=none, and
then failed every job with CERTIFICATE_VERIFY_FAILED until restarted by hand.
"""
import threading
import pytest
from backend.services.gce_encoding import self_heal
INFRA_ERROR = (
"Failed to retrieve https://metadata.google.internal/computeMetadata/v1/instance/"
"service-accounts/default/?recursive=true from the Google Compute Engine metadata "
"service. Compute Engine Metadata server unavailable."
)
@pytest.fixture
def on_worker_vm(monkeypatch):
monkeypatch.setattr(self_heal, "running_on_worker_vm", lambda: True)
@pytest.fixture(autouse=True)
def reset_restart_flag():
self_heal._restart_pending = False
yield
self_heal._restart_pending = False
class TestRunningOnWorkerVm:
def test_requires_systemd_and_bootstrap(self, monkeypatch, tmp_path):
bootstrap = tmp_path / "bootstrap.sh"
monkeypatch.setattr(self_heal, "BOOTSTRAP_PATH", str(bootstrap))
monkeypatch.setenv("INVOCATION_ID", "abc")
assert self_heal.running_on_worker_vm() is False # no bootstrap.sh (e.g. CI runner)
bootstrap.touch()
assert self_heal.running_on_worker_vm() is True
monkeypatch.delenv("INVOCATION_ID")
assert self_heal.running_on_worker_vm() is False
class TestProbeCredentials:
def test_healthy(self):
assert self_heal.probe_credentials(refresh=lambda: None) is None
def test_retries_then_succeeds(self):
calls = {"n": 0}
def refresh():
calls["n"] += 1
if calls["n"] < 3:
raise RuntimeError("blip")
assert self_heal.probe_credentials(attempts=3, retry_seconds=0, refresh=refresh) is None
assert calls["n"] == 3
def test_returns_last_error_when_always_failing(self):
def refresh():
raise RuntimeError(INFRA_ERROR)
assert self_heal.probe_credentials(attempts=2, retry_seconds=0, refresh=refresh) == INFRA_ERROR
class TestBootHealthProblem:
def test_off_vm_never_reports(self, monkeypatch):
monkeypatch.setattr(self_heal, "running_on_worker_vm", lambda: False)
monkeypatch.delenv("ENCODING_API_KEY", raising=False)
assert self_heal.boot_health_problem(probe=lambda: "broken") is None
def test_healthy_boot(self, on_worker_vm, monkeypatch):
monkeypatch.setenv("ENCODING_API_KEY", "k")
assert self_heal.boot_health_problem(probe=lambda: None) is None
def test_missing_api_key(self, on_worker_vm, monkeypatch):
monkeypatch.delenv("ENCODING_API_KEY", raising=False)
problem = self_heal.boot_health_problem(probe=lambda: None)
assert "ENCODING_API_KEY" in problem
def test_credentials_failing(self, on_worker_vm, monkeypatch):
monkeypatch.setenv("ENCODING_API_KEY", "k")
problem = self_heal.boot_health_problem(probe=lambda: INFRA_ERROR)
assert "cannot obtain GCP credentials" in problem
def _wait_for(event, timeout=5):
assert event.wait(timeout), "self-heal thread did not finish"
class TestScheduleRestart:
def test_ignores_non_infra_errors(self, on_worker_vm):
exited = []
assert not self_heal.schedule_restart_if_unhealthy(
"ffmpeg: invalid codec", lambda: False, delay_seconds=0,
probe=lambda: INFRA_ERROR, exit_process=exited.append,
)
assert exited == []
def test_off_vm_does_nothing(self, monkeypatch):
monkeypatch.setattr(self_heal, "running_on_worker_vm", lambda: False)
assert not self_heal.schedule_restart_if_unhealthy(
INFRA_ERROR, lambda: False, delay_seconds=0,
probe=lambda: INFRA_ERROR, exit_process=lambda code: None,
)
def test_exits_when_still_broken_and_idle(self, on_worker_vm):
done = threading.Event()
exited = []
def exit_process(code):
exited.append(code)
done.set()
assert self_heal.schedule_restart_if_unhealthy(
INFRA_ERROR, lambda: False, delay_seconds=0,
probe=lambda: INFRA_ERROR, exit_process=exit_process,
)
_wait_for(done)
assert exited == [1]
def test_no_exit_when_credentials_recover(self, on_worker_vm):
done = threading.Event()
exited = []
def probe():
done.set()
return None
assert self_heal.schedule_restart_if_unhealthy(
INFRA_ERROR, lambda: False, delay_seconds=0,
probe=probe, exit_process=exited.append,
)
_wait_for(done)
# Let the thread finish and release the pending flag.
for _ in range(100):
if not self_heal._restart_pending:
break
threading.Event().wait(0.01)
assert exited == []
assert self_heal._restart_pending is False
def test_waits_for_in_flight_jobs_before_exiting(self, on_worker_vm):
done = threading.Event()
exited = []
active = iter([True, True, False])
def exit_process(code):
exited.append(code)
done.set()
self_heal.schedule_restart_if_unhealthy(
INFRA_ERROR, lambda: next(active), delay_seconds=0,
probe=lambda: INFRA_ERROR, exit_process=exit_process,
)
_wait_for(done)
assert exited == [1]
def test_only_one_check_at_a_time(self, on_worker_vm):
release = threading.Event()
def probe():
release.wait(5)
return None
assert self_heal.schedule_restart_if_unhealthy(
INFRA_ERROR, lambda: False, delay_seconds=0, probe=probe, exit_process=lambda c: None,
)
assert not self_heal.schedule_restart_if_unhealthy(
INFRA_ERROR, lambda: False, delay_seconds=0, probe=probe, exit_process=lambda c: None,
)
release.set()
# ---------------------------------------------------------------------------
# Wiring in gce_encoding/main.py
# ---------------------------------------------------------------------------
import asyncio
import os
import sys
from unittest.mock import MagicMock, patch
@pytest.fixture
def worker_module():
with patch.dict(os.environ, {}, clear=False):
os.environ.pop("GCE_METADATA_MTLS_MODE", None)
with patch("google.cloud.storage.Client", return_value=MagicMock()):
sys.modules.pop("backend.services.gce_encoding.main", None)
import backend.services.gce_encoding.main as m
yield m
sys.modules.pop("backend.services.gce_encoding.main", None)
def test_import_defaults_metadata_mtls_off(worker_module):
assert os.environ["GCE_METADATA_MTLS_MODE"] == "none"
def test_import_keeps_explicit_mtls_mode():
with patch.dict(os.environ, {"GCE_METADATA_MTLS_MODE": "strict"}, clear=False):
with patch("google.cloud.storage.Client", return_value=MagicMock()):
sys.modules.pop("backend.services.gce_encoding.main", None)
import backend.services.gce_encoding.main # noqa: F401
sys.modules.pop("backend.services.gce_encoding.main", None)
assert os.environ["GCE_METADATA_MTLS_MODE"] == "strict"
def _run_lifespan(m):
async def go():
async with m.lifespan(m.app):
pass
asyncio.run(go())
def test_lifespan_refuses_to_start_when_boot_unhealthy(worker_module, monkeypatch):
monkeypatch.setattr(worker_module.self_heal, "boot_health_problem", lambda: "no API key")
with pytest.raises(RuntimeError, match="booted unhealthy: no API key"):
_run_lifespan(worker_module)
def test_lifespan_starts_when_healthy(worker_module, monkeypatch):
monkeypatch.setattr(worker_module.self_heal, "boot_health_problem", lambda: None)
monkeypatch.setattr(worker_module.persister, "mark_orphans_failed_on_startup", lambda jobs: 0)
_run_lifespan(worker_module)
def test_failed_job_schedules_self_heal(worker_module, monkeypatch):
seen = []
monkeypatch.setattr(
worker_module.self_heal, "schedule_restart_if_unhealthy",
lambda error_text, has_active: seen.append((error_text, has_active())),
)
worker_module.jobs.clear()
worker_module._self_heal_after_failure(RuntimeError(INFRA_ERROR))
assert seen == [(INFRA_ERROR, False)]
def test_self_heal_scheduling_errors_never_propagate(worker_module, monkeypatch):
def boom(*a, **k):
raise RuntimeError("thread start failed")
monkeypatch.setattr(worker_module.self_heal, "schedule_restart_if_unhealthy", boom)
worker_module._self_heal_after_failure(RuntimeError(INFRA_ERROR)) # must not raise
@@ -1,62 +0,0 @@
"""Guards for the encoding-worker boot scripts' gcloud on-GCE cache handling.
A gcloud call made before DHCP finishes writes "False" to /root/.config/gcloud/gce,
so every later gcloud call in that boot has no credentials. The worker then had
no API key, self-heal refused to serve, and systemd re-ran startup.sh against the
same poisoned cache until the VM idle-stopped (jobs f4310aea 2026-10-09,
82f48738 2026-10-12). The scripts must drop that cache before fetching the key.
"""
import re
import subprocess
from pathlib import Path
REPO = Path(__file__).resolve().parents[2]
STARTUP = REPO / "infrastructure" / "encoding-worker" / "startup.sh"
PROVISION = REPO / "infrastructure" / "packer" / "scripts" / "provision.sh"
CACHE_RM = "rm -f /root/.config/gcloud/gce"
SECRET_FETCH = "gcloud secrets versions access latest --secret=encoding-worker-api-key"
def test_startup_script_is_valid_bash():
subprocess.run(["bash", "-n", str(STARTUP)], check=True)
def test_startup_clears_gce_cache_before_first_secret_fetch():
text = STARTUP.read_text()
assert CACHE_RM in text
assert text.index(CACHE_RM) < text.index(SECRET_FETCH)
def test_startup_waits_for_metadata_server_before_fetch():
text = STARTUP.read_text()
metadata_probe = text.index("computeMetadata/v1/instance/id")
assert metadata_probe < text.index(SECRET_FETCH)
def test_startup_retries_secret_fetch():
text = STARTUP.read_text()
loops = re.findall(r"for attempt in \$\(seq 1 \d+\); do\n(.*?)\ndone", text, re.S)
assert any(SECRET_FETCH in body and CACHE_RM in body for body in loops)
def test_packer_fallback_clears_gce_cache_before_secret_fetch():
text = PROVISION.read_text()
fallback = text[text.index("startup-fallback.sh << 'FALLBACK'"):]
assert CACHE_RM in fallback
assert fallback.index(CACHE_RM) < fallback.index(SECRET_FETCH)
def test_startup_metadata_probe_has_total_timeout():
text = STARTUP.read_text()
lines = text.splitlines()
url_idx = next(i for i, l in enumerate(lines) if "computeMetadata/v1/instance/id" in l)
# The curl flags sit on the line before the URL continuation.
assert "--max-time" in lines[url_idx - 1] + lines[url_idx]
def test_startup_exits_nonzero_without_api_key():
text = STARTUP.read_text()
block = text[text.index('if [ -z "$ENCODING_API_KEY" ]; then'):]
block = block[: block.index("fi")]
assert "exit 1" in block
@@ -161,211 +161,3 @@ def test_get_encoding_service_builds_once_under_concurrency():
t.join()
assert len(builds) == 1
assert len({id(r) for r in results}) == 1
# --- 2026-10-08: routes/cron stalls traced by the loop watchdog ---------------
# complete_review's corrections upload (21s), create_job_from_search's theme prep
# (5-9s), recover_stuck_jobs' Firestore scans (~260 stalls/week), the YouTube
# queue processor and upload-duration validation all ran sync I/O on the loop.
def test_run_on_loop_runs_coroutine_on_the_given_loop():
from backend.utils.loop_bridge import run_on_loop
async def main():
loop = asyncio.get_running_loop()
seen = {}
async def coro():
seen["loop"] = asyncio.get_running_loop()
return 42
result = await asyncio.to_thread(run_on_loop, loop, coro())
assert result == 42
assert seen["loop"] is loop
asyncio.run(main())
def test_run_on_loop_propagates_exceptions():
from backend.utils.loop_bridge import run_on_loop
async def main():
loop = asyncio.get_running_loop()
async def boom():
raise ValueError("nope")
with pytest.raises(ValueError, match="nope"):
await asyncio.to_thread(run_on_loop, loop, boom())
asyncio.run(main())
def test_run_on_loop_times_out_and_cancels():
from backend.utils.loop_bridge import run_on_loop
import concurrent.futures
async def main():
loop = asyncio.get_running_loop()
cancelled = asyncio.Event()
async def hangs():
try:
await asyncio.sleep(10)
except asyncio.CancelledError:
cancelled.set()
raise
with pytest.raises(concurrent.futures.TimeoutError):
await asyncio.to_thread(run_on_loop, loop, hangs(), 0.05)
await asyncio.wait_for(cancelled.wait(), 1)
asyncio.run(main())
def test_run_in_body_thread_copies_context_and_uses_own_pool():
import contextvars
import threading
from backend.utils.loop_bridge import run_in_body_thread
var = contextvars.ContextVar("v", default=None)
def body():
return var.get(), threading.current_thread().name
async def main():
var.set("request-ctx")
return await run_in_body_thread(body)
value, thread_name = asyncio.run(main())
assert value == "request-ctx"
assert thread_name.startswith("route-body")
@pytest.mark.asyncio
async def test_complete_review_saves_off_loop_and_triggers_render():
from unittest.mock import AsyncMock
from backend.api.routes import review
from backend.models.job import JobStatus
job = MagicMock()
job.status = JobStatus.AWAITING_REVIEW
job.file_urls = {}
job.existing_instrumental_gcs_path = None
job.state_data = {}
jm = MagicMock()
jm.get_job.return_value = job
jm.delete_state_data_keys.return_value = []
storage = MagicMock()
storage.upload_json.side_effect = _sleep
with patch.object(review, "JobManager", return_value=jm), \
patch.object(review, "StorageService", return_value=storage), \
patch("backend.services.worker_service.get_worker_service") as ws:
ws.return_value.trigger_render_video_worker = AsyncMock(return_value=True)
result = {}
async def call():
result.update(await review.complete_review(
job_id="j1",
updated_data={"corrections": [], "instrumental_selection": "clean"},
auth_info=("u@example.com", "job_owner"),
))
ticks = await _ticks_during(call())
storage.upload_json.assert_called_once()
ws.return_value.trigger_render_video_worker.assert_awaited_once_with("j1")
assert result == {"status": "success", "instrumental_selection": "clean"}
assert ticks >= MIN_TICKS
@pytest.mark.asyncio
async def test_create_job_from_search_runs_off_loop():
from backend.api.routes import jobs
with patch.object(jobs, "_create_job_from_search_sync", side_effect=_sleep) as body:
ticks = await _ticks_during(
jobs.create_job_from_search(MagicMock(), MagicMock(), MagicMock(), MagicMock())
)
body.assert_called_once()
assert isinstance(body.call_args.args[-1], asyncio.AbstractEventLoop)
assert ticks >= MIN_TICKS
@pytest.mark.asyncio
@pytest.mark.parametrize("route, body", [
("recover_stuck_jobs", "_recover_stuck_jobs_sync"),
("retry_pending_render_jobs", "_retry_pending_render_jobs_sync"),
])
async def test_internal_crons_run_off_loop(route, body):
from backend.api.routes import internal
with patch.object(internal, body, side_effect=_sleep) as mock_body:
ticks = await _ticks_during(getattr(internal, route)(MagicMock(), MagicMock()))
mock_body.assert_called_once()
assert ticks >= MIN_TICKS
@pytest.mark.asyncio
async def test_upload_duration_validation_runs_off_loop():
from backend.api.routes import file_upload
with patch.object(file_upload, "_validate_audio_durations_sync", side_effect=_sleep):
ticks = await _ticks_during(file_upload._validate_audio_durations(MagicMock(), "a.flac", "i.flac"))
assert ticks >= MIN_TICKS
@pytest.mark.asyncio
async def test_youtube_queue_single_upload_runs_off_loop():
from backend.workers import youtube_queue_processor as qp
with patch.object(qp, "_process_single_upload_sync", side_effect=_sleep):
ticks = await _ticks_during(qp._process_single_upload("j1", {}, MagicMock(), MagicMock()))
assert ticks >= MIN_TICKS
@pytest.mark.asyncio
async def test_youtube_queue_quota_and_queue_reads_run_off_loop():
from backend.workers import youtube_queue_processor as qp
quota = MagicMock()
quota.check_quota_available.side_effect = lambda: (_sleep(), (True, 100, "ok"))[1]
queue = MagicMock()
queue.get_queued_uploads.side_effect = lambda **_kw: (_sleep(), [])[1]
with patch.object(qp, "get_youtube_quota_service", return_value=quota), \
patch.object(qp, "get_youtube_upload_queue_service", return_value=queue):
ticks = await _ticks_during(qp.process_youtube_upload_queue())
# 2 x BLOCK_S of blocking work; offloaded it ticks through both.
assert ticks >= 2 * MIN_TICKS
@pytest.mark.asyncio
async def test_cloud_run_job_dispatch_runs_off_loop():
from backend.services.worker_service import WorkerService
client = MagicMock()
client.run_job.side_effect = _sleep
ws = WorkerService.__new__(WorkerService)
ticks = await _ticks_during(ws._run_job_with_retry(client, MagicMock(), log_prefix="[t]"))
client.run_job.assert_called_once()
assert ticks >= MIN_TICKS
@pytest.mark.asyncio
async def test_render_trigger_bumps_generation_off_loop():
from unittest.mock import AsyncMock
from backend.services.worker_service import WorkerService
ws = WorkerService.__new__(WorkerService)
ws._use_cloud_tasks = False
ws.settings = MagicMock(use_cloud_run_jobs_for_render=False)
with patch.object(WorkerService, "_bump_worker_generation", side_effect=_sleep), \
patch.object(WorkerService, "_start_encoding_worker_warmup"), \
patch.object(WorkerService, "trigger_worker", new=AsyncMock(return_value=True)):
ticks = await _ticks_during(ws.trigger_render_video_worker("j1"))
assert ticks >= MIN_TICKS
-255
View File
@@ -1,255 +0,0 @@
"""
User-uploaded inputs must outlive the uploads/ lifecycle delete.
2026-10-08: randy-vild jobs that skipped the audio worker's copy (bring-your-own
instrumental) or sat in review for >7 days lost their mix and instrumental, so
re-renders failed with a 404 on uploads/... . Every pipeline worker now copies
uploads/{job_id}/** to jobs/{job_id}/input/ on entry and repoints the job.
"""
import ast
import hashlib
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from backend.services.input_persistence import (
ensure_job_inputs_persisted,
persist_job_inputs,
persisted_path,
)
class FakeBlob:
def __init__(self, name, data):
self.name = name
self.data = data
self.size = len(data)
self.md5_hash = hashlib.md5(data).hexdigest()
class FakeBucket:
def __init__(self, objects):
self.objects = {n: FakeBlob(n, d) for n, d in objects.items()}
self.copies = []
def list_blobs(self, prefix=""):
return [b for n, b in sorted(self.objects.items()) if n.startswith(prefix)]
def get_blob(self, name):
return self.objects.get(name)
def copy_blob(self, blob, bucket, dest):
self.copies.append((blob.name, dest))
self.objects[dest] = FakeBlob(dest, blob.data)
def _job(**fields):
base = dict(
job_id="j1",
input_media_gcs_path="uploads/j1/audio/01-Song Mix.wav",
existing_instrumental_gcs_path="uploads/j1/conformed/existing_instrumental.flac",
style_params_gcs_path=None,
lyrics_file_gcs_path="uploads/j1/lyrics/user_lyrics.txt",
file_urls={"input": {"audio": "uploads/j1/audio/01-Song Mix.wav"}, "stems": {"x": "jobs/j1/stems/x.flac"}},
state_data={"instrumental_conformed": {"original_gcs_path": "uploads/j1/audio/existing_instrumental.wav", "correlation": 0.8}},
style_assets={},
)
base.update(fields)
return SimpleNamespace(**base)
UPLOADS = {
"uploads/j1/audio/01-Song Mix.wav": b"mix",
"uploads/j1/audio/existing_instrumental.wav": b"inst",
"uploads/j1/conformed/existing_instrumental.flac": b"conformed",
"uploads/j1/lyrics/user_lyrics.txt": b"la la",
"uploads/j10/audio/other.wav": b"another job", # prefix-sibling must not be touched
}
def test_persisted_path_keeps_relative_layout_and_only_maps_this_job():
assert persisted_path("j1", "uploads/j1/audio/a b.wav") == "jobs/j1/input/audio/a b.wav"
assert persisted_path("j1", "uploads/j10/audio/x.wav") is None
assert persisted_path("j1", "jobs/j1/input/x.wav") is None
assert persisted_path("j1", "uploads/j1/") is None
def test_copies_every_upload_and_repoints_every_reference():
bucket = FakeBucket(UPLOADS)
jm = MagicMock()
job = _job()
copied, updates = persist_job_inputs(job, SimpleNamespace(bucket=bucket), jm)
assert copied == 4
assert sorted(dest for _src, dest in bucket.copies) == [
"jobs/j1/input/audio/01-Song Mix.wav",
"jobs/j1/input/audio/existing_instrumental.wav",
"jobs/j1/input/conformed/existing_instrumental.flac",
"jobs/j1/input/lyrics/user_lyrics.txt",
]
assert updates == {
"input_media_gcs_path": "jobs/j1/input/audio/01-Song Mix.wav",
"existing_instrumental_gcs_path": "jobs/j1/input/conformed/existing_instrumental.flac",
"lyrics_file_gcs_path": "jobs/j1/input/lyrics/user_lyrics.txt",
"file_urls.input.audio": "jobs/j1/input/audio/01-Song Mix.wav",
"state_data.instrumental_conformed.original_gcs_path": "jobs/j1/input/audio/existing_instrumental.wav",
}
jm.update_job.assert_called_once_with("j1", updates)
# in-memory job follows, so the calling worker downloads from the kept copy
assert job.input_media_gcs_path == "jobs/j1/input/audio/01-Song Mix.wav"
assert job.existing_instrumental_gcs_path.startswith("jobs/j1/input/")
def test_idempotent_second_run_copies_nothing():
bucket = FakeBucket(UPLOADS)
jm = MagicMock()
persist_job_inputs(_job(), SimpleNamespace(bucket=bucket), jm)
bucket.copies.clear()
jm.reset_mock()
# Job already repointed (as Firestore would now hold)
job = _job(
input_media_gcs_path="jobs/j1/input/audio/01-Song Mix.wav",
existing_instrumental_gcs_path="jobs/j1/input/conformed/existing_instrumental.flac",
lyrics_file_gcs_path="jobs/j1/input/lyrics/user_lyrics.txt",
file_urls={"input": {"audio": "jobs/j1/input/audio/01-Song Mix.wav"}},
state_data={},
)
copied, updates = persist_job_inputs(job, SimpleNamespace(bucket=bucket), jm)
assert (copied, updates) == (0, {})
assert bucket.copies == []
jm.update_job.assert_not_called()
def test_recopies_when_the_kept_copy_differs():
"""A re-upload under the same name (e.g. a new conformed instrumental) replaces the kept copy."""
bucket = FakeBucket({**UPLOADS, "jobs/j1/input/conformed/existing_instrumental.flac": b"stale"})
persist_job_inputs(_job(), SimpleNamespace(bucket=bucket), MagicMock())
assert bucket.objects["jobs/j1/input/conformed/existing_instrumental.flac"].data == b"conformed"
def test_paths_to_already_expired_uploads_are_left_alone():
bucket = FakeBucket({}) # nothing left in uploads/
jm = MagicMock()
copied, updates = persist_job_inputs(_job(), SimpleNamespace(bucket=bucket), jm)
assert (copied, updates) == (0, {})
jm.update_job.assert_not_called()
def test_style_assets_and_style_params_are_repointed():
bucket = FakeBucket({"uploads/j1/style/style_params.json": b"{}", "uploads/j1/style/bg.png": b"png"})
job = _job(
input_media_gcs_path=None, existing_instrumental_gcs_path=None, lyrics_file_gcs_path=None,
file_urls={}, state_data={}, style_params_gcs_path="uploads/j1/style/style_params.json",
style_assets={"karaoke_background": "uploads/j1/style/bg.png", "font": "themes/nomad/assets/A.ttf"},
)
_copied, updates = persist_job_inputs(job, SimpleNamespace(bucket=bucket), MagicMock())
assert updates == {
"style_params_gcs_path": "jobs/j1/input/style/style_params.json",
"style_assets.karaoke_background": "jobs/j1/input/style/bg.png",
}
def test_worker_wrapper_never_raises_but_logs_an_error(caplog):
storage = SimpleNamespace(bucket=MagicMock(list_blobs=MagicMock(side_effect=RuntimeError("gcs down"))))
with caplog.at_level("ERROR"):
ensure_job_inputs_persisted(_job(), storage, MagicMock(), "lyrics")
assert any("failed to persist uploaded inputs" in r.message and "gcs down" in r.message for r in caplog.records)
@pytest.mark.parametrize(
"module",
["audio_worker", "lyrics_worker", "screens_worker", "render_video_worker", "video_worker"],
)
def test_every_pipeline_worker_persists_inputs_off_the_event_loop(module):
"""Each worker entry calls the persistence step via asyncio.to_thread (blocking GCS/Firestore I/O)."""
source = Path(__file__).resolve().parents[1].joinpath("workers", f"{module}.py").read_text()
calls = [
node for node in ast.walk(ast.parse(source))
if isinstance(node, ast.Call)
and getattr(node.func, "attr", None) == "to_thread"
and node.args and getattr(node.args[0], "id", None) == "ensure_job_inputs_persisted"
]
assert calls, f"{module} must call ensure_job_inputs_persisted on entry"
# --- admin backfill -------------------------------------------------------------------
def _admin_client():
from backend.api.dependencies import AuthResult, UserType, require_admin
from backend.api.routes.admin import router
app = FastAPI()
app.include_router(router, prefix="/api")
app.dependency_overrides[require_admin] = lambda: AuthResult(
is_valid=True, user_type=UserType.ADMIN, remaining_uses=999, message="ok",
user_email="admin@example.com", is_admin=True,
)
return TestClient(app)
def test_backfill_dry_run_reports_without_copying():
bucket = FakeBucket({**UPLOADS, "uploads/gone/audio/x.wav": b"orphan"})
jm = MagicMock()
jm.get_job.side_effect = lambda jid: _job() if jid == "j1" else (_job(job_id="j10") if jid == "j10" else None)
with patch("backend.api.routes.admin.StorageService", return_value=SimpleNamespace(bucket=bucket)), \
patch("backend.api.routes.admin.JobManager", return_value=jm):
resp = _admin_client().post("/api/admin/persist-uploads")
assert resp.status_code == 200
body = resp.json()
assert body["dry_run"] is True
assert body["jobs"]["gone"] == {"orphan": 1}
assert body["jobs"]["j1"]["would_copy"]["uploads/j1/lyrics/user_lyrics.txt"] == "jobs/j1/input/lyrics/user_lyrics.txt"
assert bucket.copies == []
jm.update_job.assert_not_called()
def test_backfill_apply_persists_each_job():
bucket = FakeBucket(UPLOADS)
jm = MagicMock()
jm.get_job.side_effect = lambda jid: _job(job_id=jid, input_media_gcs_path=f"uploads/{jid}/audio/other.wav",
existing_instrumental_gcs_path=None, lyrics_file_gcs_path=None,
file_urls={}, state_data={}) \
if jid == "j10" else _job()
with patch("backend.api.routes.admin.StorageService", return_value=SimpleNamespace(bucket=bucket)), \
patch("backend.api.routes.admin.JobManager", return_value=jm):
body = _admin_client().post("/api/admin/persist-uploads?dry_run=false").json()
assert body["jobs"]["j1"]["copied"] == 4
assert body["jobs"]["j10"] == {"copied": 1, "updated": {"input_media_gcs_path": "jobs/j10/input/audio/other.wav"}}
# --- GCE encoder picks the configured instrumental, not a persisted raw copy -----------
def test_encoder_prefers_the_downloaded_existing_instrumental(tmp_path):
from backend.services.gce_encoding.main import resolve_instrumental
(tmp_path / "input" / "audio").mkdir(parents=True)
(tmp_path / "input" / "conformed").mkdir(parents=True)
(tmp_path / "input" / "audio" / "existing_instrumental.wav").write_bytes(b"raw, unaligned")
(tmp_path / "input" / "conformed" / "existing_instrumental.flac").write_bytes(b"aligned")
(tmp_path / "existing_instrumental.flac").write_bytes(b"configured")
picked = resolve_instrumental(tmp_path, {"existing_instrumental": "jobs/j1/input/conformed/existing_instrumental.flac"})
assert picked == tmp_path / "existing_instrumental.flac"
def test_backfill_keeps_going_when_one_job_lookup_fails():
bucket = FakeBucket(UPLOADS)
jm = MagicMock()
def get_job(jid):
if jid == "j1":
raise RuntimeError("firestore hiccup")
return _job(job_id=jid, input_media_gcs_path=f"uploads/{jid}/audio/other.wav",
existing_instrumental_gcs_path=None, lyrics_file_gcs_path=None, file_urls={}, state_data={})
jm.get_job.side_effect = get_job
with patch("backend.api.routes.admin.StorageService", return_value=SimpleNamespace(bucket=bucket)), \
patch("backend.api.routes.admin.JobManager", return_value=jm):
body = _admin_client().post("/api/admin/persist-uploads?dry_run=false").json()
assert body["jobs"]["j1"] == {"error": "firestore hiccup"}
assert body["jobs"]["j10"]["copied"] == 1
+1 -103
View File
@@ -27,8 +27,6 @@ class TestCheckStateMachine:
def _wd(self, **kw):
clock = FakeClock()
recorded = []
# cpu_clock tracks wall time: the process was running (not throttled) between checks.
kw.setdefault("cpu_clock", clock)
wd = LoopWatchdog(clock=clock, recorder=recorded.append, **kw)
wd._loop_thread_id = None # no real frames in these tests
return wd, clock, recorded
@@ -134,7 +132,7 @@ class TestIdleGapSuppression:
caplog.set_level(logging.DEBUG, logger="backend.services.loop_watchdog")
clock = FakeClock()
recorded = []
wd = LoopWatchdog(clock=clock, recorder=recorded.append, cpu_clock=clock)
wd = LoopWatchdog(clock=clock, recorder=recorded.append)
wd._loop_thread_id = 12345
with patch("backend.services.loop_watchdog._is_idle_frame", return_value=idle), \
patch("backend.services.loop_watchdog.sys._current_frames", return_value={12345: None}):
@@ -159,106 +157,6 @@ class TestIdleGapSuppression:
assert "EVENT_LOOP_STALL ended" in caplog.text
class TestThrottledProcessFreeze:
"""Cloud Run CPU throttling freezes every thread: the watchdog oversleeps and the
process burns ~no CPU. That gap is not a loop stall (2026-10-08 false alert:
30s "stall" in asyncio get_debug with no request in flight)."""
def _wd(self):
clock = FakeClock()
cpu = FakeClock() # advances only when the test says the process ran
recorded = []
wd = LoopWatchdog(clock=clock, cpu_clock=cpu, recorder=recorded.append)
wd._loop_thread_id = 12345
return wd, clock, cpu, recorded
def _check(self, wd):
with patch("backend.services.loop_watchdog._is_idle_frame", return_value=False), \
patch("backend.services.loop_watchdog.sys._current_frames", return_value={12345: None}):
wd.check()
def test_frozen_gap_is_not_reported(self, caplog):
caplog.set_level(logging.DEBUG, logger="backend.services.loop_watchdog")
wd, clock, cpu, recorded = self._wd()
wd._last_tick = clock.t
self._check(wd) # baseline check
clock.t += 30.0 # whole process frozen 30s, no CPU used
self._check(wd)
clock.t += 0.25
cpu.t += 0.01
wd._last_tick = clock.t # thawed: heartbeat resumes
self._check(wd)
assert recorded == []
assert "EVENT_LOOP_STALL" not in caplog.text
assert "discounted 30000ms of process freeze" in caplog.text
def test_short_partial_throttle_freeze_is_not_reported(self, caplog):
"""Partial throttling: the watchdog gets a slice every ~1.5s, burning ~no CPU."""
caplog.set_level(logging.WARNING)
wd, clock, cpu, recorded = self._wd()
wd._last_tick = clock.t
self._check(wd)
for _ in range(2): # 2 x 1.5s sparse wake-ups, loop never ticks
clock.t += 1.5
cpu.t += 0.002
self._check(wd)
clock.t += 0.25
cpu.t += 0.01
wd._last_tick = clock.t
self._check(wd)
assert recorded == []
assert "EVENT_LOOP_STALL" not in caplog.text
def test_blocking_io_stall_still_reported(self, caplog):
"""Blocking I/O on the loop: the watchdog keeps waking on time (GIL released)."""
caplog.set_level(logging.WARNING)
wd, clock, cpu, recorded = self._wd()
wd._last_tick = clock.t
self._check(wd)
for _ in range(int(12 / 0.25)): # 12s stall, watchdog wakes every tick
clock.t += 0.25
cpu.t += 0.001
self._check(wd)
clock.t += 0.25
wd._last_tick = clock.t
self._check(wd)
assert len(recorded) == 1
assert "EVENT_LOOP_STALL ended duration_ms=12000" in caplog.text
def test_cpu_bound_gil_hog_still_reported(self, caplog):
"""GIL-holding CPU work also starves the watchdog, but the process burns CPU."""
caplog.set_level(logging.WARNING)
wd, clock, cpu, recorded = self._wd()
wd._last_tick = clock.t
self._check(wd)
clock.t += 20.0
cpu.t += 19.5
self._check(wd)
clock.t += 0.25
wd._last_tick = clock.t
self._check(wd)
assert len(recorded) == 1
assert "EVENT_LOOP_STALL ended duration_ms=20000" in caplog.text
def test_freeze_inside_real_stall_is_subtracted(self, caplog):
"""8s of real blocking then a 30s freeze reports ~8s, not 38s."""
caplog.set_level(logging.WARNING)
wd, clock, cpu, recorded = self._wd()
wd._last_tick = clock.t
self._check(wd)
for _ in range(int(8 / 0.25)):
clock.t += 0.25
cpu.t += 0.001
self._check(wd)
clock.t += 30.0 # frozen
self._check(wd)
clock.t += 0.25
wd._last_tick = clock.t
self._check(wd)
assert "EVENT_LOOP_STALL ended duration_ms=8000" in caplog.text
assert recorded[0]["duration_ms"] == 8000
def test_is_idle_frame_detects_parked_selector():
"""A thread blocked in selectors' select() is classified idle; a busy one isn't."""
import selectors
-44
View File
@@ -67,47 +67,3 @@ def test_lifespan_starts_warmup_thread_without_blocking_readiness():
assert not warmup_release.is_set()
finally:
warmup_release.set()
def test_lazy_route_modules_import_before_readiness_off_loop():
"""httpx & co. are imported in a worker thread during lifespan startup, before
the first request (cold-start importlib stalls, 2026-10-08)."""
import importlib
seen = []
real_import = importlib.import_module
def tracking_import(name, *a, **kw):
if name in main_module._LAZY_ROUTE_IMPORTS:
seen.append((name, threading.current_thread().name))
return real_import(name, *a, **kw)
with patch.object(main_module, "_run_background_warmup"), \
patch.object(importlib, "import_module", side_effect=tracking_import):
with TestClient(main_module.app):
pass
assert [name for name, _ in seen] == list(main_module._LAZY_ROUTE_IMPORTS)
# asyncio.to_thread's default-executor workers, i.e. not the event-loop thread.
assert all(thread.startswith("asyncio_") for _, thread in seen), seen
def test_lazy_route_import_failure_is_non_fatal():
import importlib
with patch.object(importlib, "import_module", side_effect=ImportError("nope")):
main_module._import_lazy_route_modules() # logs, doesn't raise
def test_slow_lazy_route_import_does_not_block_startup(caplog):
import logging
import time
caplog.set_level(logging.ERROR)
with patch.object(main_module, "_run_background_warmup"), \
patch.object(main_module, "LAZY_ROUTE_IMPORT_TIMEOUT_S", 0.05), \
patch.object(main_module, "_import_lazy_route_modules", side_effect=lambda: time.sleep(0.5)):
with TestClient(main_module.app):
pass
assert "exceeded 0.05s; continuing startup" in caplog.text
@@ -191,91 +191,3 @@ async def helper():
await client.sync_ok()
'''
assert find_awaited_sync_routes(caller) == ["sync_ok"]
# Known-blocking calls (network / Secret Manager I/O) that awaiting *something else*
# in the same handler doesn't excuse. On 2026-10-07 the routes below awaited
# request.json() etc. (so test_no_async_route_without_await passed) yet froze the
# loop 5-16s: a Dropbox token refresh (HTTP + Secret Manager write) inside
# check_dropbox_credentials, and the GDrive validator's OIDC fetch + POST.
# Pass these to asyncio.to_thread(fn, ...) — a reference, not a call — instead.
BLOCKING_CALLS = {
"check_youtube_credentials",
"check_dropbox_credentials",
"check_gdrive_credentials",
"check_all_credentials",
"trigger_gdrive_validation",
}
_BLOCKING_MODULE_CALLS = {("requests", "get"), ("requests", "post"), ("requests", "put"),
("requests", "delete"), ("requests", "request"), ("time", "sleep")}
def _blocking_call_name(call: ast.Call) -> str | None:
fn = call.func
if isinstance(fn, ast.Name) and fn.id in BLOCKING_CALLS:
return fn.id
if isinstance(fn, ast.Attribute):
if fn.attr in BLOCKING_CALLS:
return fn.attr
if isinstance(fn.value, ast.Name) and (fn.value.id, fn.attr) in _BLOCKING_MODULE_CALLS:
return f"{fn.value.id}.{fn.attr}"
return None
def find_blocking_calls_in_async_routes(source: str) -> list[str]:
"""`async def` routes that directly call a known-blocking function (excluding
nested sync helpers, which are presumably run via to_thread)."""
tree = ast.parse(source)
hits = []
for fn in ast.walk(tree):
if not (isinstance(fn, ast.AsyncFunctionDef) and _is_route(fn)):
continue
stack = list(fn.body)
while stack:
node = stack.pop()
if isinstance(node, (ast.FunctionDef, ast.Lambda, ast.ClassDef)):
continue
if isinstance(node, ast.Call) and (name := _blocking_call_name(node)):
hits.append(f"{fn.name}: {name}() line {node.lineno}")
stack.extend(ast.iter_child_nodes(node))
return hits
def test_no_known_blocking_calls_in_async_routes():
offenders = []
for path in ROUTE_FILES:
for hit in find_blocking_calls_in_async_routes(path.read_text()):
offenders.append(f"{path.relative_to(BACKEND.parent)}::{hit}")
assert not offenders, (
"These `async def` routes call known-blocking functions directly on the event "
"loop. Use `await asyncio.to_thread(fn, ...)`:\n " + "\n ".join(sorted(offenders))
)
def test_blocking_call_detector():
src = '''
@router.post("/a")
async def bad(request):
await request.json()
cm.check_dropbox_credentials()
requests.post(url)
@router.post("/b")
async def good(request):
await request.json()
await asyncio.to_thread(cm.check_dropbox_credentials)
await asyncio.to_thread(trigger_gdrive_validation, brand_code="X")
@router.post("/c")
def sync_ok():
cm.check_dropbox_credentials()
@router.post("/d")
async def helper_ok():
def _work():
return trigger_gdrive_validation()
await asyncio.to_thread(_work)
'''
hits = find_blocking_calls_in_async_routes(src)
assert sorted(h.split(" line")[0] for h in hits) == [
"bad: check_dropbox_credentials()", "bad: requests.post()"]
-41
View File
@@ -723,35 +723,6 @@ class TestInternalRetentionEndpoint:
assert kwargs["dry_run"] is True and kwargs["include_orphans"] is True
assert kwargs["report_path"] == body["report_path"].removeprefix("gs://bucket/")
def _orphans(self, client, url):
test_client, app = client
from backend.api.dependencies import require_admin
async def admin():
return _auth(email="admin@x.com", is_admin=True)
app.dependency_overrides[require_admin] = admin
ws = MagicMock()
ws.trigger_storage_retention_job = AsyncMock(return_value=True)
with patch("backend.services.worker_service.get_worker_service", return_value=ws):
return test_client.post(url), ws
def test_orphan_endpoint_defaults_to_dry_run(self, client):
resp, ws = self._orphans(client, "/api/internal/storage-retention/orphans")
assert resp.status_code == 200 and resp.json()["dry_run"] is True
kwargs = ws.trigger_storage_retention_job.await_args.kwargs
assert kwargs["mode"] == "orphans" and kwargs["dry_run"] is True
assert "-orphans-dry-run.json" in kwargs["report_path"]
def test_orphan_real_run_needs_confirmation(self, client):
resp, ws = self._orphans(client, "/api/internal/storage-retention/orphans?dry_run=false")
assert resp.status_code == 400
ws.trigger_storage_retention_job.assert_not_awaited()
resp, ws = self._orphans(
client, "/api/internal/storage-retention/orphans?dry_run=false&confirm=delete-orphan-job-folders")
assert resp.status_code == 200
assert ws.trigger_storage_retention_job.await_args.kwargs["dry_run"] is False
def test_job_trigger_failure_is_503(self, client):
ws = MagicMock()
ws.trigger_storage_retention_job = AsyncMock(return_value=False)
@@ -943,15 +914,6 @@ class TestStorageRetentionWorker:
assert svc.run.call_args.kwargs == {"dry_run": False, "max_jobs": 5, "include_orphans": True,
"report_path": "r.json"}
def test_cli_orphan_mode(self):
from backend.workers import storage_retention_worker
svc = MagicMock()
svc.purge_orphans.return_value = {}
with patch("backend.services.storage_retention.StorageRetentionService", return_value=svc):
assert storage_retention_worker.main(["--mode", "orphans", "--max-folders", "7"]) == 0
assert svc.purge_orphans.call_args.kwargs == {"dry_run": True, "max_folders": 7, "report_path": None}
svc.run.assert_not_called()
def test_cli_defaults_to_dry_run(self):
from backend.workers import storage_retention_worker
svc = MagicMock()
@@ -986,9 +948,6 @@ class TestStorageRetentionWorker:
args = list(request.overrides.container_overrides[0].args)
assert args[:3] == ["python", "-m", "backend.workers.storage_retention_worker"]
assert args[3:] == ["--dry-run", "false", "--report-path", "r.json", "--max-jobs", "3", "--include-orphans"]
await ws.trigger_storage_retention_job(True, "o.json", mode="orphans", max_folders=2)
args = list(ws._run_job_with_retry.await_args.args[1].overrides.container_overrides[0].args)
assert args[3:] == ["--dry-run", "true", "--report-path", "o.json", "--mode", "orphans", "--max-folders", "2"]
@@ -1,101 +0,0 @@
"""The "waiting for encoding server" marker is cleared once a retried render really runs.
Incident 2026-10-06 (job ebfe4344): after the encoding worker was fixed, the
retried render ran normally but the job card still said "(waiting for encoding
server availability)" because state_data.render_pending_capacity from the earlier
parked attempts was never removed.
"""
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from backend.models.job import JobStatus
def _job(state_data, status=JobStatus.REVIEW_COMPLETE):
job = MagicMock()
job.artist = "Randy Vild"
job.title = "We'll Never Die"
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": 1, "is_duet": False, **state_data}
job.file_urls = {}
job.status = status
return job
async def _run(state_data, ticks):
from backend.workers import render_video_worker as rvw
job_start = _job(state_data)
job_after = _job(state_data, status=JobStatus.RENDERING_VIDEO)
jm = MagicMock()
calls = {"n": 0}
def _get_job(_job_id):
calls["n"] += 1
return job_start if calls["n"] == 1 else job_after
jm.get_job.side_effect = _get_job
jm.transition_to_state.return_value = True
async def _render(_job_id, _config, progress_callback=None):
for tick in ticks:
progress_callback(tick)
return {"output_files": ["gs://b/jobs/test/videos/with_vocals.mkv"], "metadata": {}}
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("ebfe4344")
return result, jm
PENDING = {"render_pending_capacity": {"attempt_count": 7, "last_code": "worker_infra_failure"}}
@pytest.mark.asyncio
async def test_marker_cleared_once_on_first_real_progress():
result, jm = await _run(PENDING, ticks=[10, 50, 100])
assert result is True
clears = [
c for c in jm.delete_state_data_key.call_args_list
if c.args == ("ebfe4344", "render_pending_capacity")
]
assert len(clears) == 1
@pytest.mark.asyncio
async def test_marker_kept_until_worker_reports_progress():
# A zero-progress tick (queued on the worker) is not proof the render is running.
_, jm = await _run(PENDING, ticks=[0])
assert not any(
c.args == ("ebfe4344", "render_pending_capacity")
for c in jm.delete_state_data_key.call_args_list
)
@pytest.mark.asyncio
async def test_no_delete_when_job_was_never_parked():
_, jm = await _run({}, ticks=[10, 50])
assert not any(
c.args == ("ebfe4344", "render_pending_capacity")
for c in jm.delete_state_data_key.call_args_list
)
@@ -291,30 +291,3 @@ async def test_worker_skips_job_already_rendering():
mock_job_manager.transition_to_state.assert_not_called()
mock_job_manager.fail_job.assert_not_called()
assert worker_registry.get_active_workers() == {}
@pytest.mark.asyncio
@pytest.mark.parametrize("diverted, error, expected", [(True, None, True), (False, RuntimeError("x"), False)])
async def test_worker_hands_theme_stale_job_to_screens_worker(diverted, error, expected):
"""Theme edited after the screens were made: the worker diverts to the screens
worker (which re-triggers it) instead of rendering; a failed hand-off fails the job."""
from backend.workers import render_video_worker as rvw
mock_job_manager = MagicMock()
mock_job_manager.get_job.return_value = _build_minimal_job(JobStatus.REVIEW_COMPLETE)
divert = AsyncMock(return_value=diverted, side_effect=error)
with patch.object(rvw, "JobManager", return_value=mock_job_manager), \
patch.object(rvw, "StorageService"), \
patch.object(rvw, "get_settings"), \
patch.object(rvw, "create_job_logger", return_value=MagicMock()), \
patch.object(rvw, "setup_job_logging", return_value=MagicMock()), \
patch("backend.services.theme_change_service.divert_for_stale_screens", divert), \
patch.object(rvw, "get_encoding_service") as enc:
result = await rvw.process_render_video("stale-job")
assert result is expected
enc.assert_not_called() # never started rendering
mock_job_manager.transition_to_state.assert_not_called()
assert mock_job_manager.mark_job_failed.called is (error is not None)
assert worker_registry.get_active_workers() == {}
+7 -218
View File
@@ -310,25 +310,16 @@ class TestFileUrlDeletions:
# --- Service ----------------------------------------------------------------------
class FakeStorage:
def __init__(self, files, updated=None):
def __init__(self, files):
self.files = dict(files)
self.updated = dict(updated or {})
self.deleted = []
self.reports = {}
self.texts = {}
self.delete_generations = {}
def list_files_with_sizes(self, prefix):
return [(k, v) for k, v in sorted(self.files.items()) if k.startswith(prefix)]
def list_blob_meta(self, prefix):
old = datetime(2026, 1, 1, tzinfo=timezone.utc)
return [{"name": k, "size": v, "generation": 1000 + i, "updated": self.updated.get(k, old)}
for i, (k, v) in enumerate(sorted(self.files.items())) if k.startswith(prefix)]
def delete_file(self, path, ignore_missing=False, if_generation_match=None):
def delete_file(self, path, ignore_missing=False):
self.deleted.append(path)
self.delete_generations[path] = if_generation_match
self.files.pop(path, None)
return True
@@ -336,10 +327,6 @@ class FakeStorage:
self.reports[path] = data
return path
def upload_text(self, path, text, content_type="text/plain"):
self.texts[path] = text
return path
class FakeDoc:
def __init__(self, db, doc_id):
@@ -601,10 +588,10 @@ class TestServiceRealRun:
svc, db, storage = _service([_job(job_id="a")])
real_delete = storage.delete_file
def flaky(path, ignore_missing=False, if_generation_match=None):
def flaky(path, ignore_missing=False):
if path.endswith("lossy_4k_mp4.mp4"):
raise RuntimeError("boom")
return real_delete(path, ignore_missing, if_generation_match)
return real_delete(path, ignore_missing)
storage.delete_file = flaky
svc.run(dry_run=False, now=NOW)
@@ -656,7 +643,7 @@ class TestInterruptedPurge:
svc, db, storage = _service([_job(job_id="a")])
seen = {}
def delete(path, ignore_missing=False, if_generation_match=None):
def delete(path, ignore_missing=False):
# at the first delete the job must already say what's being purged
if not seen:
doc = db.data["a"]
@@ -675,11 +662,11 @@ class TestInterruptedPurge:
calls = {"n": 0}
real = storage.delete_file
def dies_after_two(path, ignore_missing=False, if_generation_match=None):
def dies_after_two(path, ignore_missing=False):
calls["n"] += 1
if calls["n"] > 2:
raise SystemExit("instance killed")
return real(path, ignore_missing, if_generation_match)
return real(path, ignore_missing)
storage.delete_file = dies_after_two
with pytest.raises(SystemExit):
@@ -692,201 +679,3 @@ class TestInterruptedPurge:
report = svc.run(dry_run=False, now=NOW + timedelta(hours=1))
assert report["summary"]["jobs_purged"] == 1
assert db.data["a"]["storage_purge"]["status"] == "complete"
# --- Deletion audit log -------------------------------------------------------------
import json as _json
def _log_lines(storage, path):
return [_json.loads(line) for line in storage.texts[path].splitlines() if line]
class TestDeletionLog:
def test_real_run_logs_every_deleted_object_with_generation(self):
svc, db, storage = _service([_job(job_id="a")])
report = svc.run(dry_run=False, now=NOW)
log_path = report["deletion_log"]
assert log_path == "storage-retention/deletion-logs/20261003T120000Z-job_purge.jsonl"
lines = _log_lines(storage, log_path)
assert {l["path"] for l in lines} == set(storage.deleted)
assert all(l["result"] == "deleted" and l["mode"] == "job_purge" and l["job_id"] == "a" for l in lines)
assert all(l["generation"] is not None for l in lines)
cats = {l["category"] for l in lines}
assert {"finals", "videos", "stems", "review-audio", "previews", "screens-mov"} == cats
# deletes are generation-pinned to exactly the logged version
for l in lines:
assert str(storage.delete_generations[l["path"]]) == l["generation"]
summary = storage.reports[report["deletion_summary"]]
assert summary["objects_deleted"] == len(lines)
assert summary["bytes_deleted"] == sum(l["size_bytes"] for l in lines)
assert summary["jobs"] == 1 and summary["failures"] == 0
# manifest on the job doc carries generations + log path
manifest = db.data["a"]["storage_purge"]
assert manifest["deletion_log"] == log_path
assert all(f["generation"] for f in manifest["files"])
def test_dry_run_writes_no_deletion_log(self):
svc, db, storage = _service([_job(job_id="a")])
report = svc.run(dry_run=True, now=NOW)
assert "deletion_log" not in report and storage.texts == {}
def test_failures_are_logged(self):
svc, db, storage = _service([_job(job_id="a")])
real = storage.delete_file
def flaky(path, ignore_missing=False, if_generation_match=None):
if path.endswith("lossy_4k_mp4.mp4"):
raise RuntimeError("412 precondition failed")
return real(path, ignore_missing, if_generation_match)
storage.delete_file = flaky
report = svc.run(dry_run=False, now=NOW)
failed = [l for l in _log_lines(storage, report["deletion_log"]) if l["result"] == "failed"]
assert len(failed) == 1 and "precondition" in failed[0]["error"]
assert storage.reports[report["deletion_summary"]]["failures"] == 1
def test_log_is_flushed_per_job_so_a_crash_keeps_the_record(self):
jobs = [_job(job_id="a"), _job(job_id="b")]
svc, db, storage = _service(jobs)
real = storage.delete_file
def die_on_b(path, ignore_missing=False, if_generation_match=None):
if path.startswith("jobs/b/"):
raise SystemExit("killed")
return real(path, ignore_missing, if_generation_match)
storage.delete_file = die_on_b
with pytest.raises(SystemExit):
svc.run(dry_run=False, now=NOW)
path = "storage-retention/deletion-logs/20261003T120000Z-job_purge.jsonl"
lines = _log_lines(storage, path)
assert lines and {l["job_id"] for l in lines} == {"a"}
assert {l["path"] for l in lines} == {p for p in storage.deleted if p.startswith("jobs/a/")}
@pytest.mark.parametrize("path", [
"storage-retention/deletion-logs/x.jsonl", "uploads/a/x.flac", "jobs/", "jobs//x", "temp/x",
])
def test_guard_refuses_paths_outside_job_folders(self, path):
with pytest.raises(ValueError):
sr.assert_deletable(path)
def test_guard_allows_job_files(self):
sr.assert_deletable("jobs/a/finals/x.mp4")
# --- Orphan folders ----------------------------------------------------------------
def _orphan_service(files, updated=None, records=None):
db = FakeDb([_job(job_id="live")])
for coll, ids in (records or {}).items():
db.extra = getattr(db, "extra", {})
db.extra.update({(coll, i): True for i in ids})
real_collection = db.collection
def collection(name):
if name in ("jobs-dev", "youtube_upload_queue"):
extra = getattr(db, "extra", {})
return SimpleNamespace(document=lambda i: SimpleNamespace(
get=lambda: SimpleNamespace(exists=extra.get((name, i), False))))
return real_collection(name)
db.collection = collection
storage = FakeStorage(files, updated)
return StorageRetentionService(db=db, storage=storage, settings=_settings()), db, storage
ORPHAN_FILES = {
"jobs/live/finals/lossy_4k_mp4.mp4": 10,
"jobs/ghost/input/song.flac": 100,
"jobs/ghost/finals/lossy_720p_mp4.mp4": 30,
"jobs/ghost/videos/with_vocals.mkv": 200,
"jobs/ghost/stems/custom_instrumental.flac": 40,
"jobs/ghost/custom_instrumental.mp3": 9,
"jobs/fresh/finals/x.mp4": 50,
"jobs/queued/finals/x.mp4": 70,
"jobs/_preview123/review-audio/mixed.ogg": 4,
"storage-retention/deletion-logs/old.jsonl": 1,
"uploads/ghost/audio/x.flac": 5,
}
class TestOrphans:
def _svc(self):
updated = {"jobs/fresh/finals/x.mp4": NOW - timedelta(days=2)}
return _orphan_service(ORPHAN_FILES, updated, records={"youtube_upload_queue": ["queued"]})
def test_plan_keeps_only_input(self):
objs = [{"name": k, "size": v, "updated": NOW - timedelta(days=90)}
for k, v in ORPHAN_FILES.items() if k.startswith("jobs/ghost/")]
plan = sr.plan_orphan_folder("ghost", objs, NOW)
assert [m["name"] for m in plan["keep"]] == ["jobs/ghost/input/song.flac"]
assert plan["purge_bytes"] == 30 + 200 + 40 + 9 and plan["skip_reason"] is None
def test_recent_folder_is_skipped(self):
plan = sr.plan_orphan_folder("x", [{"name": "jobs/x/a.mp4", "size": 1, "updated": NOW - timedelta(days=29)}], NOW)
assert plan["skip_reason"] == "recently_modified"
def test_dry_run_reports_without_deleting(self):
svc, db, storage = self._svc()
report = svc.purge_orphans(dry_run=True, now=NOW)
assert storage.deleted == [] and storage.texts == {}
assert report["candidates"] == 4 # ghost, fresh, queued, _preview123 (never "live")
assert sorted(f["job_id"] for f in report["folders"]) == ["_preview123", "ghost"]
assert report["skipped"] == {"recently_modified": 1, "has_record": 1}
assert report["not_orphans"] == [{"job_id": "queued", "collection": "youtube_upload_queue"}]
assert report["summary"]["gib_input_kept"] == round(100 / 2**30, 2)
assert report["report_path"].endswith("-orphans-dry-run.json")
def test_real_run_deletes_non_input_and_logs(self):
svc, db, storage = self._svc()
report = svc.purge_orphans(dry_run=False, now=NOW)
assert sorted(storage.deleted) == sorted([
"jobs/ghost/finals/lossy_720p_mp4.mp4", "jobs/ghost/videos/with_vocals.mkv",
"jobs/ghost/stems/custom_instrumental.flac", "jobs/ghost/custom_instrumental.mp3",
"jobs/_preview123/review-audio/mixed.ogg",
])
for kept in ("jobs/ghost/input/song.flac", "jobs/live/finals/lossy_4k_mp4.mp4",
"jobs/fresh/finals/x.mp4", "jobs/queued/finals/x.mp4",
"storage-retention/deletion-logs/old.jsonl", "uploads/ghost/audio/x.flac"):
assert kept in storage.files
lines = _log_lines(storage, report["deletion_log"])
assert report["deletion_log"].endswith("-orphan.jsonl")
assert {l["category"] for l in lines} == {"orphan-nonInput"} and {l["mode"] for l in lines} == {"orphan"}
assert storage.reports[report["deletion_summary"]]["objects_deleted"] == 5
def test_record_created_after_listing_is_respected(self):
svc, db, storage = self._svc()
db.extra = {("jobs-dev", "ghost"): True}
svc.purge_orphans(dry_run=False, now=NOW)
assert not any(p.startswith("jobs/ghost/") for p in storage.deleted)
def test_batch_limit(self):
svc, db, storage = self._svc()
report = svc.purge_orphans(dry_run=False, max_folders=1, now=NOW)
assert len(report["folders"]) == 1 and report["skipped"]["batch_limit"] == 3
class TestDeletionLogFlushFailure:
def test_run_stops_deleting_when_log_cannot_be_written(self):
svc, db, storage = _service([_job(job_id="a"), _job(job_id="b")])
def broken(path, text, content_type="text/plain"):
raise RuntimeError("gcs write denied")
storage.upload_text = broken
report = svc.run(dry_run=False, now=NOW)
assert not any(p.startswith("jobs/b/") for p in storage.deleted)
assert report["errors"] and "deletion log not persisted" in report["errors"][0]["error"]
assert storage.reports[report["deletion_summary"]]["log_flush_error"] == "gcs write denied"
def test_orphan_run_stops_too(self):
files = {"jobs/g1/finals/a.mp4": 1, "jobs/g2/finals/b.mp4": 1}
svc, db, storage = _orphan_service(files)
storage.upload_text = lambda *a, **k: (_ for _ in ()).throw(RuntimeError("denied"))
report = svc.purge_orphans(dry_run=False, now=NOW)
assert storage.deleted == ["jobs/g1/finals/a.mp4"]
assert "deletion log not persisted" in report["errors"][0]["error"]
+1 -14
View File
@@ -99,20 +99,9 @@ def test_preview_returns_data_urls(client_for):
assert resp.status_code == 200
body = resp.json()
assert body["title_card"].startswith("data:image/jpeg;base64,")
assert body["end_screen"] is None # not rendered (e.g. the theme omits it)
assert render.call_args.kwargs["artist"] == "Randy Vild"
def test_preview_returns_end_screen_and_null_for_omitted_title(client_for):
with patch.object(tenant_theme, "prepare_preview_styles", return_value={"intro": {}}), \
patch.object(tenant_theme, "render_theme_preview", return_value=PreviewImages(None, b"k", b"e")):
resp = client_for().post("/api/tenant/theme/preview", json={"style_params": {"intro": {}}})
assert resp.status_code == 200
body = resp.json()
assert body["title_card"] is None
assert body["end_screen"].startswith("data:image/jpeg;base64,")
def test_preview_validation_and_render_errors(client_for):
client = client_for()
with patch.object(tenant_theme, "prepare_preview_styles", side_effect=TenantValidationError("bad path")):
@@ -127,9 +116,7 @@ def test_preview_validation_and_render_errors(client_for):
def test_save_and_upload(client_for):
client = client_for()
with patch.object(tenant_theme, "save_tenant_theme") as save, \
patch.object(tenant_theme, "get_theme_for_editor", return_value=THEME), \
patch.object(tenant_theme, "refresh_inflight_jobs", return_value={"updated": 0, "failed": 0}), \
patch.object(tenant_theme, "outdated_jobs", return_value={"job_ids": []}):
patch.object(tenant_theme, "get_theme_for_editor", return_value=THEME):
resp = client.put("/api/tenant/theme", json={"style_params": {"intro": {"title_color": "#ffffff"}}})
assert resp.status_code == 200
assert save.call_args.args[0].id == "randy-vild"
@@ -264,15 +264,3 @@ def test_missing_theme_file_is_not_found():
storage.download_json = lambda path: (_ for _ in ()).throw(FileNotFoundError(path))
with pytest.raises(tts.ThemeNotFoundError):
tts.get_theme_for_editor(_config(), storage=storage)
@pytest.mark.parametrize("section", ["intro", "end"])
def test_screen_enabled_flag_must_be_boolean(section):
style = _style()
style[section]["enabled"] = False
styles, _ = tts.sanitize_style_params(style, available_assets=ASSETS)
assert styles[section]["enabled"] is False
style[section]["enabled"] = "no"
with pytest.raises(TenantValidationError, match=f"{section}.enabled"):
tts.sanitize_style_params(style, available_assets=ASSETS)
-378
View File
@@ -1,378 +0,0 @@
"""
Tests for keeping a tenant's tracks in step with its theme after a theme edit.
Covers the in-progress refresh on save (re-snapshot + stale-screens flag), the
render-worker divert that regenerates stale screens before rendering, outdated
finished-track detection, Edit picking up the current theme, the quiet bulk
re-render, and the /api/tenant/theme save / outdated-jobs / rerender-outdated
routes.
"""
from datetime import datetime, timedelta, timezone
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from fastapi.testclient import TestClient
from google.cloud.firestore_v1 import DELETE_FIELD
from backend.models.job import JobStatus
from backend.services import theme_change_service as svc
T0 = datetime(2026, 9, 29, 23, 0, tzinfo=timezone.utc)
THEME_SAVED = datetime(2026, 10, 6, 14, 35, tzinfo=timezone.utc)
def _job(job_id="job1", status=JobStatus.AWAITING_REVIEW, **overrides):
fields = dict(
job_id=job_id, status=status, tenant_id="randy-vild", theme_id="randy-vild",
user_email="randy@example.com", color_overrides={}, created_at=T0,
theme_applied_at=None, state_data={},
)
fields.update(overrides)
return SimpleNamespace(**fields)
def _passthrough_transactional(fn):
return fn
def _job_manager(claim_status=None):
"""JobManager whose Firestore transaction sees ``claim_status`` (None = job's own)."""
jm = MagicMock()
doc_ref = MagicMock()
jm.firestore.db.collection.return_value.document.return_value = doc_ref
jm._doc_ref = doc_ref
jm._claim_status = claim_status
return jm
def _set_claim_status(jm, status):
snap = MagicMock(exists=True)
snap.to_dict.return_value = {"status": status}
jm._doc_ref.get.return_value = snap
@pytest.fixture
def prepare():
fn = MagicMock(return_value=("jobs/x/style/style_params.json", {"intro_background": "themes/t/bg.jpg"}, None))
with patch("backend.api.routes.file_upload._prepare_theme_for_job", fn), \
patch("backend.services.theme_rerender_service.firestore.transactional", _passthrough_transactional):
yield fn
class TestRefreshInflightJobs:
def _run(self, jobs, prepare, claim_status_for=None):
jm = _job_manager()
jm.list_jobs.return_value = jobs
# The transactional claim re-reads the job's status: return the job's own.
statuses = iter([claim_status_for or j.status.value for j in jobs
if j.status in svc.REFRESHABLE_STATUSES and j.theme_id == "randy-vild"])
def get(transaction=None):
snap = MagicMock(exists=True)
snap.to_dict.return_value = {"status": next(statuses)}
return snap
jm._doc_ref.get.side_effect = get
result = svc.refresh_inflight_jobs("randy-vild", "randy-vild", job_manager=jm)
updates = [c.args[1] for c in jm.firestore.db.transaction.return_value.update.call_args_list]
return result, updates
def test_review_stage_job_resnapshotted_and_flagged(self, prepare):
result, updates = self._run([_job(status=JobStatus.IN_REVIEW)], prepare)
assert result == {"updated": 1, "failed": 0}
update = updates[0]
assert update["style_params_gcs_path"] == "jobs/x/style/style_params.json"
assert update["style_assets"] == {"intro_background": "themes/t/bg.jpg"}
assert update["state_data.theme_screens_stale"] is True
assert isinstance(update["theme_applied_at"], datetime)
prepare.assert_called_once_with("job1", "randy-vild", None)
def test_pre_screens_job_resnapshotted_without_flag(self, prepare):
_, updates = self._run([_job(status=JobStatus.TRANSCRIBING)], prepare)
assert "state_data.theme_screens_stale" not in updates[0]
assert updates[0]["style_params_gcs_path"]
def test_render_pending_capacity_is_flagged(self, prepare):
"""RVILD-0003 sat here while the theme was edited — it must pick up the change."""
_, updates = self._run([_job(status=JobStatus.RENDER_PENDING_CAPACITY)], prepare)
assert updates[0]["state_data.theme_screens_stale"] is True
@pytest.mark.parametrize("status", [
JobStatus.REVIEW_COMPLETE, JobStatus.RENDERING_VIDEO, JobStatus.ENCODING,
JobStatus.COMPLETE, JobStatus.FAILED, JobStatus.CANCELLED,
])
def test_rendering_and_terminal_jobs_untouched(self, prepare, status):
result, updates = self._run([_job(status=status)], prepare)
assert result == {"updated": 0, "failed": 0}
assert updates == []
prepare.assert_not_called()
def test_job_on_another_theme_untouched(self, prepare):
result, _ = self._run([_job(theme_id="nomad")], prepare)
assert result["updated"] == 0
prepare.assert_not_called()
def test_job_that_moved_on_is_skipped(self, prepare):
result, updates = self._run([_job(status=JobStatus.IN_REVIEW)], prepare, claim_status_for="rendering_video")
assert result == {"updated": 0, "failed": 0}
assert updates == []
def test_one_failure_does_not_block_others(self, prepare):
prepare.side_effect = [RuntimeError("gcs down"), ("p", {}, None)]
result, updates = self._run([_job("a"), _job("b")], prepare)
assert result == {"updated": 1, "failed": 1}
assert len(updates) == 1
class TestDivertForStaleScreens:
def _jm(self, status="review_complete"):
jm = _job_manager()
_set_claim_status(jm, status)
return jm
@pytest.mark.asyncio
async def test_no_flag_renders_normally(self):
jm = self._jm()
job = _job(status=JobStatus.REVIEW_COMPLETE)
assert await svc.divert_for_stale_screens(job, jm, MagicMock()) is False
jm.firestore.db.transaction.assert_not_called()
@pytest.mark.asyncio
async def test_flag_ignored_outside_review_complete(self):
job = _job(status=JobStatus.IN_REVIEW, state_data={"theme_screens_stale": True})
assert await svc.divert_for_stale_screens(job, self._jm(), MagicMock()) is False
@pytest.mark.asyncio
async def test_stale_screens_regenerated_before_render(self):
jm = self._jm()
storage = MagicMock()
storage.list_files.return_value = ["jobs/job1/finals/A - B (Title).mov", "jobs/job1/finals/x.mp4"]
worker_service = MagicMock(trigger_screens_worker=AsyncMock(return_value=True))
job = _job(status=JobStatus.REVIEW_COMPLETE, state_data={"theme_screens_stale": True})
with patch("backend.services.theme_rerender_service.firestore.transactional", _passthrough_transactional), \
patch("backend.services.worker_service.get_worker_service", return_value=worker_service):
assert await svc.divert_for_stale_screens(job, jm, storage) is True
update = jm.firestore.db.transaction.return_value.update.call_args.args[1]
assert update["status"] == "lyrics_complete"
assert update["state_data.regen_restore_status"] == "review_complete"
assert update["state_data.theme_screens_stale"] is DELETE_FIELD
assert update["file_urls.screens"] is DELETE_FIELD
deleted = {c.args[0] for c in storage.delete_file.call_args_list}
assert "jobs/job1/screens/title.png" in deleted
assert "jobs/job1/finals/A - B (Title).mov" in deleted
assert "jobs/job1/finals/x.mp4" not in deleted
worker_service.trigger_screens_worker.assert_awaited_once_with("job1")
@pytest.mark.asyncio
async def test_already_diverted_by_duplicate_trigger_skips_render(self):
jm = self._jm(status="generating_screens")
job = _job(status=JobStatus.REVIEW_COMPLETE, state_data={"theme_screens_stale": True})
with patch("backend.services.theme_rerender_service.firestore.transactional", _passthrough_transactional):
assert await svc.divert_for_stale_screens(job, jm, MagicMock()) is True
jm.firestore.db.transaction.return_value.update.assert_not_called()
@pytest.mark.asyncio
async def test_trigger_failure_restores_and_raises(self):
jm = self._jm()
worker_service = MagicMock(trigger_screens_worker=AsyncMock(return_value=False))
job = _job(status=JobStatus.REVIEW_COMPLETE, state_data={"theme_screens_stale": True})
with patch("backend.services.theme_rerender_service.firestore.transactional", _passthrough_transactional), \
patch("backend.services.worker_service.get_worker_service", return_value=worker_service):
with pytest.raises(RuntimeError):
await svc.divert_for_stale_screens(job, jm, MagicMock())
restore = jm.update_job.call_args.args[1]
assert restore["status"] == "review_complete"
assert restore["state_data.theme_screens_stale"] is True # a retry diverts again
class TestOutdatedJobs:
def _run(self, jobs, updated_at=THEME_SAVED, user_email=None):
jm = MagicMock()
jm.list_jobs.return_value = jobs
with patch.object(svc, "theme_updated_at", return_value=updated_at), \
patch("backend.services.theme_rerender_service.validate_rerender",
side_effect=lambda j: "nope" if j.job_id == "invalid" else None):
result = svc.outdated_jobs("randy-vild", "randy-vild", user_email, job_manager=jm)
return result, jm
def test_lists_finished_tracks_made_before_the_theme_save(self):
jobs = [
_job("old", status=JobStatus.COMPLETE),
_job("rerendered", status=JobStatus.COMPLETE, theme_applied_at=THEME_SAVED + timedelta(minutes=5)),
_job("new", status=JobStatus.COMPLETE, created_at=THEME_SAVED + timedelta(hours=1)),
_job("inreview", status=JobStatus.IN_REVIEW),
_job("othertheme", status=JobStatus.COMPLETE, theme_id="nomad"),
_job("invalid", status=JobStatus.COMPLETE),
]
result, _ = self._run(jobs)
assert result["job_ids"] == ["old"]
assert result["theme_updated_at"] == THEME_SAVED.isoformat()
def test_scoped_to_owner(self):
_, jm = self._run([], user_email="randy@example.com")
assert jm.list_jobs.call_args.kwargs["user_email"] == "randy@example.com"
assert jm.list_jobs.call_args.kwargs["tenant_id"] == "randy-vild"
def test_unknown_theme_time_means_nothing_outdated(self):
result, jm = self._run([_job(status=JobStatus.COMPLETE)], updated_at=None)
assert result["job_ids"] == []
jm.list_jobs.assert_not_called()
def test_string_and_naive_timestamps(self):
assert svc._as_utc("2026-10-06T14:35:00Z") == THEME_SAVED
assert svc._as_utc(datetime(2026, 10, 6, 14, 35)) == THEME_SAVED
assert svc._as_utc("garbage") is None
class TestThemeUpdatedAt:
def test_reads_style_blob_time(self):
storage = MagicMock()
storage.bucket.get_blob.return_value = SimpleNamespace(updated=THEME_SAVED)
assert svc.theme_updated_at("randy-vild", storage) == THEME_SAVED
storage.bucket.get_blob.assert_called_once_with("themes/randy-vild/style_params.json")
def test_missing_blob_or_error(self):
storage = MagicMock()
storage.bucket.get_blob.return_value = None
assert svc.theme_updated_at("t", storage) is None
storage.bucket.get_blob.side_effect = RuntimeError("boom")
assert svc.theme_updated_at("t", storage) is None
class TestEditThemeUpdate:
def _run(self, job, updated_at=THEME_SAVED, screens_regenerating=False, tenant_theme="randy-vild"):
config = SimpleNamespace(defaults=SimpleNamespace(locked_theme=tenant_theme, theme_id=tenant_theme), id="randy-vild")
with patch("backend.services.tenant_service.get_tenant_service") as gts, \
patch.object(svc, "theme_updated_at", return_value=updated_at):
gts.return_value.get_tenant_config.return_value = config
return svc.edit_theme_update(job, screens_regenerating=screens_regenerating)
def test_outdated_track_gets_current_theme_and_stale_flag(self, prepare):
update = self._run(_job(status=JobStatus.COMPLETE))
assert update["style_params_gcs_path"] == "jobs/x/style/style_params.json"
assert update["state_data.theme_screens_stale"] is True
def test_no_flag_when_edit_already_regenerates_screens(self, prepare):
update = self._run(_job(status=JobStatus.COMPLETE), screens_regenerating=True)
assert update["style_params_gcs_path"]
assert "state_data.theme_screens_stale" not in update
def test_current_track_unchanged(self, prepare):
job = _job(status=JobStatus.COMPLETE, theme_applied_at=THEME_SAVED + timedelta(minutes=1))
assert self._run(job) == {}
prepare.assert_not_called()
def test_non_tenant_and_theme_switched_jobs_unchanged(self, prepare):
assert self._run(_job(tenant_id="")) == {}
assert self._run(_job(), tenant_theme="other") == {}
prepare.assert_not_called()
class TestQuietBulkRerender:
def test_quiet_theme_rerender_suppresses_notifications(self):
from backend.services.admin_rerender_service import suppress_customer_notifications
quiet = SimpleNamespace(state_data={"theme_rerender": {"theme_id": "t", "notify_customer": False}})
loud = SimpleNamespace(state_data={"theme_rerender": {"theme_id": "t", "notify_customer": True}})
legacy = SimpleNamespace(state_data={"theme_rerender": {"theme_id": "t"}})
assert suppress_customer_notifications(quiet) is True
assert suppress_customer_notifications(loud) is False
assert suppress_customer_notifications(legacy) is False
@pytest.mark.asyncio
async def test_marker_records_notify_choice_and_clears_stale_flag(self, prepare):
from backend.services.theme_rerender_service import ThemeRerenderService
jm = _job_manager()
_set_claim_status(jm, "complete")
worker_service = MagicMock(trigger_screens_worker=AsyncMock(return_value=True))
job = SimpleNamespace(
job_id="job1", status="complete", tenant_id="randy-vild", theme_id="randy-vild",
color_overrides={}, outputs_deleted_at=None, prep_only=False, finalise_only=False,
state_data={"instrumental_selection": "custom"},
file_urls={"lyrics": {"corrections": "c.json"}}, progress=100,
)
with patch("backend.services.worker_service.get_worker_service", return_value=worker_service):
await ThemeRerenderService(job_manager=jm, storage=MagicMock()).start(
job, theme_id="randy-vild", requested_by="x", notify_customer=False)
update = jm.firestore.db.transaction.return_value.update.call_args.args[1]
assert update["state_data.theme_rerender"]["notify_customer"] is False
assert update["state_data.theme_screens_stale"] is DELETE_FIELD
assert isinstance(update["theme_applied_at"], datetime)
# --- Routes ------------------------------------------------------------------
from backend.api.routes import tenant_theme # noqa: E402
from backend.tests.test_tenant_theme_route import RANDY, THEME, app, client_for # noqa: E402,F401
def test_save_reports_refreshed_and_outdated(client_for):
client = client_for()
with patch.object(tenant_theme, "save_tenant_theme"), \
patch.object(tenant_theme, "get_theme_for_editor", return_value=THEME), \
patch.object(tenant_theme, "refresh_inflight_jobs", return_value={"updated": 3, "failed": 0}) as refresh, \
patch.object(tenant_theme, "outdated_jobs", return_value={"job_ids": ["a", "b"]}) as outdated:
resp = client.put("/api/tenant/theme", json={"style_params": {}})
assert resp.status_code == 200
body = resp.json()
assert body["refreshed_jobs"] == 3 and body["outdated_job_ids"] == ["a", "b"]
assert body["theme_id"] == "randy-vild"
refresh.assert_called_once_with("randy-vild", "randy-vild")
assert outdated.call_args.args == ("randy-vild", "randy-vild", "randyvild@gmail.com")
def test_save_succeeds_even_if_follow_up_work_fails(client_for):
client = client_for()
with patch.object(tenant_theme, "save_tenant_theme"), \
patch.object(tenant_theme, "get_theme_for_editor", return_value=THEME), \
patch.object(tenant_theme, "refresh_inflight_jobs", side_effect=RuntimeError("x")), \
patch.object(tenant_theme, "outdated_jobs", side_effect=RuntimeError("y")):
resp = client.put("/api/tenant/theme", json={"style_params": {}})
assert resp.status_code == 200
assert resp.json()["refreshed_jobs"] == 0 and resp.json()["outdated_job_ids"] == []
def test_outdated_jobs_scope_member_vs_admin(client_for):
with patch.object(tenant_theme, "outdated_jobs", return_value={"theme_updated_at": None, "job_ids": ["a"]}) as od:
assert client_for().get("/api/tenant/theme/outdated-jobs").json()["job_ids"] == ["a"]
assert od.call_args.args[2] == "randyvild@gmail.com"
client_for(email="andrew@nomadkaraoke.com").get("/api/tenant/theme/outdated-jobs")
assert od.call_args.args[2] is None
def test_rerender_outdated_is_quiet_and_reports_failures(client_for):
from backend.services.theme_rerender_service import RerenderError
service = MagicMock()
service.start = AsyncMock(side_effect=[None, RerenderError("published"), None])
jm = MagicMock()
jm.get_job.side_effect = lambda jid: None if jid == "gone" else SimpleNamespace(job_id=jid)
with patch.object(tenant_theme, "outdated_jobs", return_value={"job_ids": ["a", "b", "gone", "c"]}), \
patch("backend.services.job_manager.JobManager", return_value=jm), \
patch("backend.services.theme_rerender_service.ThemeRerenderService", return_value=service):
resp = client_for().post("/api/tenant/theme/rerender-outdated")
assert resp.status_code == 200
assert resp.json() == {"started": ["a", "c"], "failed": {"b": "published"}, "remaining": []}
assert all(c.kwargs["notify_customer"] is False for c in service.start.call_args_list)
def test_new_endpoints_reject_non_members(client_for):
client = client_for(email="stranger@example.com")
assert client.get("/api/tenant/theme/outdated-jobs").status_code == 403
assert client.post("/api/tenant/theme/rerender-outdated").status_code == 403
def test_rerender_outdated_caps_each_call(client_for):
"""Bounded per request; the rest come back as ``remaining`` for the UI to offer again."""
service = MagicMock()
service.start = AsyncMock(return_value=None)
jm = MagicMock()
jm.get_job.side_effect = lambda jid: SimpleNamespace(job_id=jid)
ids = [f"j{i}" for i in range(tenant_theme.MAX_BULK_RERENDER + 3)]
with patch.object(tenant_theme, "outdated_jobs", return_value={"job_ids": ids}), \
patch("backend.services.job_manager.JobManager", return_value=jm), \
patch("backend.services.theme_rerender_service.ThemeRerenderService", return_value=service):
body = client_for().post("/api/tenant/theme/rerender-outdated").json()
assert body["started"] == ids[:tenant_theme.MAX_BULK_RERENDER]
assert body["remaining"] == ids[tenant_theme.MAX_BULK_RERENDER:]
assert service.start.await_count == tenant_theme.MAX_BULK_RERENDER
@@ -139,59 +139,3 @@ def test_failed_download_leaves_no_partial_cache_file(tmp_path, monkeypatch):
with pytest.raises(IOError):
tps._local_theme_asset(Storage, "t1", "bg.jpg")
assert not any(f.is_file() for f in tmp_path.rglob("*"))
def _with_end(theme, **end):
theme["end"] = {
"background_color": "#301020",
"background_image": None,
"font": "AvenirNext-Bold.ttf",
"title_color": "#ffffff",
"artist_color": "#ffdf6b",
"title_region": "370,900,3100,350",
"artist_region": "370,1450,3100,200",
"extra_text": "THANK YOU FOR SINGING!",
"extra_text_color": "#ff7acc",
"extra_text_region": "370,400,3100,400",
**end,
}
return theme
def test_renders_the_end_screen_with_its_own_background_and_layout():
tps._CACHE.clear()
result = tps.render_theme_preview("t1", _with_end(_theme()), artist="Randy Vild", storage=_NoGcsAssets())
end = _img(result.end_screen)
assert end.size == (1280, 720)
r, g, b = end.getpixel((8, 8)) # the end section's own #301020, not the title card's
assert abs(r - 0x30) <= 6 and abs(g - 0x10) <= 6 and abs(b - 0x20) <= 6
assert result.as_data_urls()["end_screen"].startswith("data:image/jpeg;base64,")
def test_end_screen_text_size_changes_only_the_end_screen():
"""Randy Vild's report: the end screen's text size is its own setting."""
tps._CACHE.clear()
big = tps.render_theme_preview("t1", _with_end(_theme()), storage=_NoGcsAssets())
small = tps.render_theme_preview(
"t1", _with_end(_theme(), title_region="370,900,3100,120", extra_text_region="370,400,3100,120"),
storage=_NoGcsAssets(),
)
assert big.title_card == small.title_card
assert big.end_screen != small.end_screen
def text_pixels(data):
return sum(1 for r, g, b in _img(data).getdata() if r > 200 and g > 200 and b > 200)
assert text_pixels(small.end_screen) < text_pixels(big.end_screen) * 0.6
def test_omitted_screens_are_not_rendered():
tps._CACHE.clear()
theme = _with_end(_theme())
theme["intro"]["enabled"] = False
theme["end"]["enabled"] = False
result = tps.render_theme_preview("t1", theme, storage=_NoGcsAssets())
assert result.title_card is None and result.end_screen is None
assert _img(result.karaoke_frame).size == (1280, 720)
urls = result.as_data_urls()
assert urls["title_card"] is None and urls["end_screen"] is None
-331
View File
@@ -1,331 +0,0 @@
"""
Themes can leave the title and/or end screen out of rendered videos
(``intro.enabled`` / ``end.enabled`` = false).
Covers the cloud pipeline end to end: the screens worker records which screens
it made (``state_data.screens_included``), the render prerequisites and /retry
ladder accept a missing omitted screen, the orchestrator/encoding config carry
explicit include flags, and the encoders (GCE worker + LocalEncodingService)
concatenate only the included segments, without rebuilding an omitted screen
from a theme background PNG that the encoder's loose globs would match.
"""
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import pytest
from backend.workers.style_helper import SCREENS_INCLUDED_KEY, screen_included
# --- marker helper --------------------------------------------------------------
def test_screen_included_defaults_to_true_for_older_jobs():
assert screen_included({}, "title") and screen_included(None, "end")
assert screen_included({SCREENS_INCLUDED_KEY: {"title": True}}, "end")
assert not screen_included({SCREENS_INCLUDED_KEY: {"title": False, "end": True}}, "title")
# --- screens worker -------------------------------------------------------------
@pytest.mark.asyncio
@pytest.mark.parametrize("include_title,include_end", [(False, True), (True, False), (False, False), (True, True)])
async def test_screens_worker_skips_omitted_screens_and_records_them(tmp_path, include_title, include_end):
from datetime import datetime, timezone
from backend.models.job import Job, JobStatus
from backend.workers import screens_worker as sw
job = Job(
job_id="j1", artist="A", title="T", status=JobStatus.DOWNLOADING,
created_at=datetime.now(timezone.utc), updated_at=datetime.now(timezone.utc),
state_data={"lyrics_complete": True, "audio_complete": True},
)
jm = MagicMock()
jm.get_job.return_value = job
jm.transition_to_state.return_value = True
style_config = MagicMock(include_title_screen=include_title, include_end_screen=include_end)
async def load_style(*args, **kwargs):
return style_config
async def make_png(name):
png = tmp_path / f"{name}.png"
png.write_bytes(b"png")
return str(png)
async def noop(*args, **kwargs):
return {}
title_gen = MagicMock(side_effect=lambda **kw: make_png("title"))
end_gen = MagicMock(side_effect=lambda **kw: make_png("end"))
upload = MagicMock(side_effect=noop)
with patch.object(sw, "JobManager", return_value=jm), \
patch.object(sw, "StorageService"), \
patch.object(sw, "get_settings"), \
patch.object(sw, "create_job_logger"), \
patch.object(sw, "setup_job_logging"), \
patch.object(sw, "_validate_prerequisites", return_value=True), \
patch("backend.services.stems_restore.maybe_start_stems_restore", return_value="not_needed"), \
patch.object(sw, "load_style_config", side_effect=load_style), \
patch.object(sw, "_create_video_generator"), \
patch.object(sw, "_generate_title_screen", title_gen), \
patch.object(sw, "_generate_end_screen", end_gen), \
patch.object(sw, "_upload_screens", upload), \
patch.object(sw, "_apply_countdown_padding_if_needed", side_effect=noop), \
patch.object(sw, "_transcode_review_audio", side_effect=noop), \
patch("backend.services.auto_approval.executor.maybe_auto_complete_review", side_effect=noop), \
patch("backend.services.auto_approval.pre_apply.ensure_and_pre_apply", side_effect=noop):
result = await sw.generate_screens("j1")
assert result is True, jm.mark_job_failed.call_args
assert title_gen.called is include_title
assert end_gen.called is include_end
kwargs = upload.call_args.kwargs
assert (kwargs["title_screen_path"] is not None) is include_title
assert (kwargs["end_screen_path"] is not None) is include_end
jm.update_state_data.assert_any_call("j1", SCREENS_INCLUDED_KEY, {"title": include_title, "end": include_end})
def test_upload_screens_skips_an_omitted_screen(tmp_path):
from backend.workers.screens_worker import _upload_screens_sync
(tmp_path / "End.png").write_bytes(b"png")
(tmp_path / "End.jpg").write_bytes(b"jpg")
storage, jm = MagicMock(), MagicMock()
storage.upload_file.side_effect = lambda local, gcs: f"gs://b/{gcs}"
_upload_screens_sync("j1", jm, storage, None, str(tmp_path / "End.png"))
assert [c.args[1] for c in storage.upload_file.call_args_list] == ["jobs/j1/screens/end.png", "jobs/j1/screens/end.jpg"]
jm.update_file_url.assert_any_call("j1", "screens", "end_png", "gs://b/jobs/j1/screens/end.png")
jm.update_file_url.assert_any_call("j1", "screens", "end_jpg", "gs://b/jobs/j1/screens/end.jpg")
# --- render prerequisites + retry ladder -----------------------------------------
def _video_job(screens, included=None):
state = {"instrumental_selection": "clean"}
if included is not None:
state[SCREENS_INCLUDED_KEY] = included
return SimpleNamespace(
job_id="j1",
state_data=state,
file_urls={"screens": screens, "videos": {"with_vocals": "gs://v"}, "stems": {"instrumental_clean": "gs://i"}},
)
@pytest.mark.parametrize(
"screens,included,ok",
[
({"title_png": "x", "end_png": "y"}, None, True),
({"end_png": "y"}, None, False), # older job: a missing title is still an error
({"end_png": "y"}, {"title": False, "end": True}, True),
({"title_png": "x"}, {"title": True, "end": False}, True),
({}, {"title": False, "end": False}, True),
({}, {"title": True, "end": False}, False),
],
)
def test_video_prerequisites_accept_omitted_screens(screens, included, ok):
from backend.workers import video_worker
with patch.object(video_worker, "validate_worker_can_run", return_value=None):
assert video_worker._validate_prerequisites(_video_job(screens, included)) is ok
@pytest.mark.parametrize(
"file_urls,state_data,expected",
[
({"screens": {"title_jpg": "x"}}, {}, True),
({"screens": {}}, {}, False),
# Title omitted by the theme and the screens worker finished
({"screens": {"end_png": "y"}}, {SCREENS_INCLUDED_KEY: {"title": False}, "screens_progress": {"stage": "complete"}}, True),
# ...but a re-render cleared screens_progress: the stale marker alone isn't enough
({"screens": {}}, {SCREENS_INCLUDED_KEY: {"title": False}}, False),
],
)
def test_retry_screens_check_understands_omitted_title(file_urls, state_data, expected):
from backend.api.routes.jobs import _has_title_screen
assert _has_title_screen(file_urls, state_data) is expected
# --- orchestrator + encoding config ---------------------------------------------
def _orch_job(included):
return SimpleNamespace(
job_id="j1", artist="A", title="T",
state_data={"instrumental_selection": "clean", SCREENS_INCLUDED_KEY: included},
file_urls={"screens": {"end_png": "gs://b/jobs/j1/screens/end.png"}, "videos": {"with_vocals": "gs://b/v.mkv"}},
)
def test_orchestrator_config_drops_omitted_screen_paths(tmp_path):
from backend.workers import video_worker_orchestrator as vwo
dist = MagicMock(enable_youtube_upload=False, brand_prefix=None, discord_webhook_url=None,
youtube_description=None, dropbox_path=None, gdrive_folder_id=None)
with patch("backend.services.job_defaults_service.get_effective_distribution_for_job", return_value=dist):
config = vwo.create_orchestrator_config_from_job(_orch_job({"title": False, "end": True}), str(tmp_path))
assert config.title_video_path is None
assert config.end_video_path.endswith("A - T (End).png")
assert config.include_title_screen is False and config.include_end_screen is True
@pytest.mark.asyncio
async def test_orchestrator_passes_include_flags_to_the_encoder():
from backend.workers.video_worker_orchestrator import OrchestratorConfig, VideoWorkerOrchestrator
config = OrchestratorConfig(
job_id="j1", artist="A", title="T", title_video_path=None, karaoke_video_path="k.mkv",
instrumental_audio_path="i.flac", include_title_screen=False, include_end_screen=True,
)
orch = VideoWorkerOrchestrator(config=config, job_manager=MagicMock(), storage=MagicMock())
backend = MagicMock()
backend.name = "local"
backend.encode = MagicMock(side_effect=RuntimeError("stop"))
orch._get_encoding_backend = MagicMock(return_value=backend)
with pytest.raises(RuntimeError, match="stop"):
await orch._run_encoding()
encoding_input = backend.encode.call_args.args[0]
assert encoding_input.title_video_path is None
assert encoding_input.options["include_title_screen"] is False
assert encoding_input.options["include_end_screen"] is True
@pytest.mark.asyncio
async def test_original_vocals_guide_has_no_intro_offset_without_a_title_card():
from backend.workers.video_worker_orchestrator import OrchestratorConfig, VideoWorkerOrchestrator
config = OrchestratorConfig(
job_id="j1", artist="A", title="T", title_video_path=None, karaoke_video_path="k",
instrumental_audio_path="i", include_title_screen=False,
)
orch = VideoWorkerOrchestrator(config=config, job_manager=MagicMock(), storage=MagicMock())
assert await orch._resolve_intro_seconds() == 0.0
@pytest.mark.asyncio
async def test_gce_backend_sends_include_flags_only_when_a_screen_is_omitted():
from backend.services.encoding_interface import EncodingInput, GCEEncodingBackend
def make_input(**flags):
return EncodingInput(
title_video_path=None, karaoke_video_path="k", instrumental_audio_path="i", artist="A", title="T",
options={"job_id": "j1", "input_gcs_path": "gs://b/in/", "output_gcs_path": "gs://b/out/", **flags},
)
sent = []
async def encode_videos(job_id, input_gcs_path, output_gcs_path, encoding_config, **kwargs):
sent.append(encoding_config)
raise RuntimeError("stop")
gce = GCEEncodingBackend()
service = MagicMock()
service.is_enabled = True
service.encode_videos = encode_videos
gce._service = service
with patch.object(GCEEncodingBackend, "_get_service", return_value=service):
await gce.encode(make_input(include_title_screen=False, include_end_screen=True))
await gce.encode(make_input(include_title_screen=True, include_end_screen=True))
assert sent[0]["include_title_screen"] is False and "include_end_screen" not in sent[0]
assert "include_title_screen" not in sent[1] and "include_end_screen" not in sent[1]
# --- encoders -------------------------------------------------------------------
@pytest.mark.parametrize(
"with_title,with_end,n",
[(True, True, 3), (False, True, 2), (True, False, 2), (False, False, 1)],
)
def test_lossless_concat_includes_only_present_segments(tmp_path, with_title, with_end, n):
from backend.services.local_encoding_service import LocalEncodingService
end = tmp_path / "end.mov"
end.write_bytes(b"x")
service = LocalEncodingService(logger=MagicMock())
with patch.object(service, "_execute_command_with_fallback", return_value=True) as run:
assert service.encode_lossless_mp4(
str(tmp_path / "title.mov") if with_title else None,
str(tmp_path / "karaoke.mkv"),
str(tmp_path / "out.mp4"),
str(end) if with_end else None,
)
gpu, cpu = run.call_args.args[:2]
for cmd in (gpu, cpu):
assert f"concat=n={n}:v=1:a=1" in cmd
assert cmd.count(" -i ") == n
assert ("title.mov" in cmd) is with_title
assert ("end.mov" in cmd) is with_end
assert "karaoke.mkv" in cmd
# Segment order: title, karaoke, end
assert cpu.index("karaoke.mkv") > (cpu.index("title.mov") if with_title else -1)
if with_end:
assert cpu.index("end.mov") > cpu.index("karaoke.mkv")
def _gce_work_dir(tmp_path: Path) -> Path:
work = tmp_path / "work"
(work / "style").mkdir(parents=True)
(work / "videos").mkdir()
(work / "stems").mkdir()
# Theme assets the encoder's loose "*title*.png" / "*end*.png" globs would match
(work / "style" / "cdg_title_background.png").write_bytes(b"png" * 1000)
(work / "style" / "end_background.png").write_bytes(b"png" * 1000)
(work / "videos" / "with_vocals.mkv").write_bytes(b"mkv" * 1000)
(work / "stems" / "instrumental_clean.flac").write_bytes(b"flac" * 1000)
return work
@pytest.mark.parametrize("include_title,include_end", [(False, False), (False, True), (True, False)])
def test_gce_worker_never_rebuilds_an_omitted_screen_from_theme_pngs(tmp_path, include_title, include_end):
from backend.services.gce_encoding import main
work = _gce_work_dir(tmp_path)
(work / "screens").mkdir()
for screen, included in (("title", include_title), ("end", include_end)):
if included:
(work / "screens" / f"{screen}.png").write_bytes(b"png" * 1000)
made = []
def fake_mov(png, mov, duration=5):
made.append(png.name)
mov.write_bytes(b"mov" * 1000)
return mov
service = MagicMock()
service.encode_all_formats.return_value = MagicMock(success=True)
main.jobs["j1"] = {"status": "pending", "progress": 0}
with patch.object(main, "generate_mov_from_png", side_effect=fake_mov), \
patch.object(main, "render_portrait_into_outputs"), \
patch.object(main, "_persist"), \
patch("backend.services.local_encoding_service.LocalEncodingService", return_value=service):
main.run_encoding("j1", work, {
"artist": "A", "title": "T",
"include_title_screen": include_title, "include_end_screen": include_end,
})
config = service.encode_all_formats.call_args.args[0]
assert (config.title_video is not None) is include_title
assert (config.end_video is not None) is include_end
assert sorted(made) == sorted(f"{s}.png" for s, inc in (("title", include_title), ("end", include_end)) if inc)
staged = sorted(p.name for p in (work / "outputs").glob("*.mov"))
assert ("A - T (Title).mov" in staged) is include_title
assert ("A - T (End).mov" in staged) is include_end
def test_gce_worker_still_requires_a_title_when_included(tmp_path):
from backend.services.gce_encoding import main
work = _gce_work_dir(tmp_path)
(work / "style" / "cdg_title_background.png").unlink()
main.jobs["j2"] = {"status": "pending", "progress": 0}
with patch.object(main, "_persist"), \
patch.object(main, "generate_mov_from_png", side_effect=lambda png, mov, duration=5: mov), \
patch("backend.services.local_encoding_service.LocalEncodingService"):
with pytest.raises(Exception, match="No title video"):
main.run_encoding("j2", work, {"artist": "A", "title": "T"})
@@ -1311,60 +1311,6 @@ class TestVideoWorkerOrchestratorDistribution:
assert orchestrator.result.youtube_url is None
def _youtube_orchestrator(self, temp_dir):
video_file = os.path.join(temp_dir, "test.mp4")
with open(video_file, "w") as f:
f.write("dummy video")
config = OrchestratorConfig(
job_id="test-job",
artist="Eli",
title="The Comeback",
title_video_path="/path/title.mov",
karaoke_video_path="/path/karaoke.mov",
instrumental_audio_path="/path/audio.flac",
enable_youtube_upload=True,
youtube_credentials={"token": "test"},
)
orchestrator = VideoWorkerOrchestrator(config)
orchestrator.result.final_video_lossy = video_file
return orchestrator
@pytest.mark.asyncio
async def test_upload_to_youtube_failure_is_queued_for_retry(self):
"""A failed (non-quota) upload goes to the deferred queue instead of being lost."""
with tempfile.TemporaryDirectory() as temp_dir:
orchestrator = self._youtube_orchestrator(temp_dir)
with patch.object(orchestrator, "_get_youtube_service") as mock_get, \
patch("backend.services.youtube_upload_queue_service.get_youtube_upload_queue_service") as mock_queue_get:
mock_get.return_value.upload_video.side_effect = Exception('<HttpError 410 returned "Gone">')
await orchestrator._upload_to_youtube()
queue_kwargs = mock_queue_get.return_value.queue_upload.call_args.kwargs
assert queue_kwargs["job_id"] == "test-job"
assert queue_kwargs["reason"] == "upload_error"
assert orchestrator.result.youtube_upload_queued is True
assert orchestrator.result.youtube_url is None
assert len(orchestrator.result.distribution_warnings) == 1
assert "queued for automatic retry" in orchestrator.result.distribution_warnings[0]
@pytest.mark.asyncio
async def test_upload_to_youtube_failure_and_queue_failure_warns(self):
"""If queueing also fails, the warning names the upload error (not quota)."""
with tempfile.TemporaryDirectory() as temp_dir:
orchestrator = self._youtube_orchestrator(temp_dir)
with patch.object(orchestrator, "_get_youtube_service") as mock_get, \
patch("backend.services.youtube_upload_queue_service.get_youtube_upload_queue_service") as mock_queue_get:
mock_get.return_value.upload_video.side_effect = Exception("Gone")
mock_queue_get.return_value.queue_upload.side_effect = Exception("firestore down")
await orchestrator._upload_to_youtube()
assert orchestrator.result.youtube_upload_queued is False
assert orchestrator.result.distribution_warnings == [
"YouTube upload skipped (upload failed: Gone) and failed to queue: firestore down"
]
class TestVideoWorkerOrchestratorNotifications:
"""Test notifications stage."""
@@ -566,64 +566,3 @@ class TestGetYouTubeUploadService:
assert service is not None
assert service.client_secrets_file == "/path/to/secrets.json"
class TestYouTubeUploadSessionRestart:
"""A lost resumable session (404/410) restarts the upload; other errors don't."""
@staticmethod
def _http_error(status):
from googleapiclient.errors import HttpError
resp = MagicMock()
resp.status = status
resp.reason = "Gone"
return HttpError(resp, b'{"error": {"message": "Gone"}}', uri="https://youtube.googleapis.com/upload")
def _service(self, insert_execute_side_effect):
service = YouTubeUploadService(credentials={"token": "t"}, non_interactive=True, server_side_mode=True)
youtube = MagicMock()
youtube.videos.return_value.insert.return_value.execute.side_effect = insert_execute_side_effect
service._youtube_service = youtube
return service, youtube
@patch("time.sleep")
@patch("googleapiclient.http.MediaFileUpload")
def test_410_restarts_with_fresh_session(self, mock_media, mock_sleep):
service, youtube = self._service([self._http_error(410), {"id": "VID"}])
with patch.object(service, "check_duplicate", return_value=(False, None, None)):
video_id, video_url = service.upload_video(video_path="/v.mkv", title="A - B (Karaoke)", description="d")
assert video_id == "VID"
assert youtube.videos.return_value.insert.call_count == 2
assert mock_media.call_count == 2 # new MediaFileUpload per session
youtube.videos.return_value.insert.return_value.execute.assert_called_with(
num_retries=YouTubeUploadService.UPLOAD_NUM_RETRIES
)
mock_sleep.assert_called_once()
@patch("time.sleep")
@patch("googleapiclient.http.MediaFileUpload")
def test_410_on_every_attempt_raises(self, mock_media, mock_sleep):
attempts = YouTubeUploadService.UPLOAD_SESSION_ATTEMPTS
service, youtube = self._service([self._http_error(410)] * attempts)
with patch.object(service, "check_duplicate", return_value=(False, None, None)):
with pytest.raises(Exception, match="410"):
service.upload_video(video_path="/v.mkv", title="A - B (Karaoke)", description="d")
assert youtube.videos.return_value.insert.call_count == attempts
assert mock_sleep.call_count == attempts - 1
@patch("time.sleep")
@patch("googleapiclient.http.MediaFileUpload")
def test_quota_403_is_not_restarted(self, mock_media, mock_sleep):
service, youtube = self._service([self._http_error(403)])
with patch.object(service, "check_duplicate", return_value=(False, None, None)):
with pytest.raises(Exception, match="403"):
service.upload_video(video_path="/v.mkv", title="A - B (Karaoke)", description="d")
assert youtube.videos.return_value.insert.call_count == 1
mock_sleep.assert_not_called()
-58
View File
@@ -1,58 +0,0 @@
"""Run a blocking route body in a worker thread while its coroutines still run on the loop.
The API has one event loop per Cloud Run instance, so sync Firestore / GCS calls
inside an ``async def`` route freeze every request on the instance (see
``backend/services/loop_watchdog.py``). Routes that are mostly sync I/O but must
await a few coroutines (worker triggers) do::
return await run_in_body_thread(_do_work_sync, ..., asyncio.get_running_loop())
and, inside ``_do_work_sync``, ``run_on_loop(loop, worker_service.trigger_x(job_id))``.
The coroutine runs on the API loop (so loop APIs like ``create_task`` inside it
keep working) while the worker thread waits for its result.
"""
import asyncio
import concurrent.futures
import contextvars
import functools
from typing import Any, Callable, Coroutine, TypeVar
T = TypeVar("T")
# Route bodies block in run_on_loop while the coroutine they dispatched may itself
# need asyncio.to_thread (the loop's default executor). Running the bodies on
# their own pool means they can never use up the threads those coroutines wait for.
_BODY_EXECUTOR = concurrent.futures.ThreadPoolExecutor(max_workers=16, thread_name_prefix="route-body")
# Worker triggers finish in seconds (bounded run_job retries); anything this slow
# is hung, and the cron/route should fail rather than hold its thread forever.
RUN_ON_LOOP_TIMEOUT_SECONDS = 120
async def run_in_body_thread(func: Callable[..., T], *args: Any) -> T:
"""Run a sync route body on the dedicated route-body pool and await its result.
Like ``asyncio.to_thread``, the caller's contextvars (trace / tenant / request
context) are copied into the thread.
"""
loop = asyncio.get_running_loop()
ctx = contextvars.copy_context()
return await loop.run_in_executor(_BODY_EXECUTOR, functools.partial(ctx.run, func, *args))
def run_on_loop(
loop: asyncio.AbstractEventLoop,
coro: Coroutine[Any, Any, T],
timeout: float = RUN_ON_LOOP_TIMEOUT_SECONDS,
) -> T:
"""From a worker thread, run ``coro`` on ``loop`` and return (or raise) its result."""
try:
future = asyncio.run_coroutine_threadsafe(coro, loop)
except Exception:
coro.close() # loop closed (instance shutdown) — don't leak a never-awaited coroutine
raise
try:
return future.result(timeout=timeout)
except concurrent.futures.TimeoutError:
future.cancel()
raise
+1 -5
View File
@@ -24,7 +24,6 @@ import time
from typing import Optional, Dict, Any
from backend.services.job_manager import JobManager
from backend.services.input_persistence import ensure_job_inputs_persisted
from backend.services.storage_service import StorageService
from backend.services.audio_search_service import DownloadError
from backend.services.job_health_service import validate_worker_can_run
@@ -184,9 +183,6 @@ async def process_audio_separation(job_id: str) -> bool:
job_log.error(f"Job {job_id} not found in Firestore!")
return False
# Copy uploads/{job_id}/** into jobs/{job_id}/input/ (uploads/ expires) and repoint the job.
await asyncio.to_thread(ensure_job_inputs_persisted, job, storage, job_manager, "audio")
# Validate job status is appropriate for audio worker
# This helps catch bugs where the worker is triggered incorrectly
status_error = validate_worker_can_run("audio_worker", job)
@@ -523,7 +519,7 @@ async def download_audio(
storage.download_file(job.input_media_gcs_path, local_path)
logger.info(f"Job {job_id}: Downloaded uploaded file to {local_path}")
# Persist uploaded audio to jobs/ prefix (uploads/ is a lifecycle-expiring staging area; see input_persistence)
# Persist uploaded audio to jobs/ prefix (uploads/ has 7-day lifecycle)
if job.input_media_gcs_path.startswith("uploads/"):
try:
persistent_path = f"jobs/{job_id}/input/{safe_filename}"
-4
View File
@@ -30,7 +30,6 @@ from pathlib import Path
from backend.models.job import JobStatus
from backend.services.job_manager import JobManager
from backend.services.input_persistence import ensure_job_inputs_persisted
from backend.services.storage_service import StorageService
from backend.services.audio_search_service import DownloadError
from backend.services.job_health_service import validate_worker_can_run
@@ -258,9 +257,6 @@ async def process_lyrics_transcription(job_id: str) -> bool:
job_log.error(f"Job {job_id} not found in Firestore!")
return False
# Copy uploads/{job_id}/** into jobs/{job_id}/input/ (uploads/ expires) and repoint the job.
await asyncio.to_thread(ensure_job_inputs_persisted, job, storage, job_manager, "lyrics")
# Validate job status is appropriate for lyrics worker
# This helps catch bugs where the worker is triggered incorrectly
status_error = validate_worker_can_run("lyrics_worker", job)
-32
View File
@@ -39,7 +39,6 @@ from backend.models.job import JobStatus
from backend.exceptions import InvalidStateTransitionError
from backend.utils.audio_filenames import local_audio_filename
from backend.services.job_manager import JobManager
from backend.services.input_persistence import ensure_job_inputs_persisted
from backend.services.storage_service import StorageService
from backend.services.lyrics_translation import prepare_job_translations
from karaoke_gen.lyrics_transcriber.output.translations import apply_translations
@@ -131,9 +130,6 @@ async def process_render_video(job_id: str) -> bool:
await worker_registry.unregister(job_id, "render-video")
return False
# Copy uploads/{job_id}/** into jobs/{job_id}/input/ (uploads/ expires) and repoint the job.
await asyncio.to_thread(ensure_job_inputs_persisted, job, storage, job_manager, "render_video")
# Hard idempotency gate (worker-side). The legacy HTTP endpoint enforces
# this via _check_worker_idempotency at dispatch time, but the Cloud Run
# Job path invokes this worker directly — and Cloud Run may re-run the
@@ -174,25 +170,6 @@ async def process_render_video(job_id: str) -> bool:
await worker_registry.unregister(job_id, "render-video")
return False
# The tenant edited its theme after this job's screens were made: regenerate
# them first (the screens worker re-triggers this worker when done).
from backend.services.theme_change_service import divert_for_stale_screens
try:
diverted = await divert_for_stale_screens(job, job_manager, storage)
except Exception as e:
logger.error(f"[job:{job_id}] WORKER_END worker=render-video status=error error={e}")
job_manager.mark_job_failed(
job_id=job_id,
error_message=f"Screen regeneration for the updated theme failed: {e}",
error_details={"stage": "render_video", "error": str(e)},
)
await worker_registry.unregister(job_id, "render-video")
return False
if diverted:
logger.info(f"[job:{job_id}] WORKER_END worker=render-video status=skipped reason=theme_screens_regen")
await worker_registry.unregister(job_id, "render-video")
return True
# 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
@@ -285,8 +262,6 @@ async def process_render_video(job_id: str) -> bool:
for k, v in job.style_assets.items()
}
capacity_marker_cleared = [False]
def progress_callback(progress: int):
# Update progress in place — the job is already in
# RENDERING_VIDEO when this fires, and going through
@@ -310,13 +285,6 @@ async def process_render_video(job_id: str) -> bool:
'progress': scaled,
'updated_at': datetime.now(UTC),
})
# The worker is really rendering now, so drop the marker from
# earlier parked attempts; otherwise the job card keeps saying
# "waiting for encoding server availability" for the whole render.
if progress and not capacity_marker_cleared[0]:
capacity_marker_cleared[0] = True
if (job.state_data or {}).get('render_pending_capacity'):
job_manager.delete_state_data_key(job_id, 'render_pending_capacity')
with job_span("gce-render-video", job_id) as render_span:
render_start = time.time()
+56 -69
View File
@@ -33,11 +33,10 @@ from pathlib import Path
from backend.models.job import JobStatus
from backend.services.job_manager import JobManager
from backend.services.input_persistence import ensure_job_inputs_persisted
from backend.services.storage_service import StorageService
from backend.services.job_health_service import validate_worker_can_run
from backend.config import get_settings
from backend.workers.style_helper import SCREENS_INCLUDED_KEY, load_style_config, StyleConfig
from backend.workers.style_helper import load_style_config, StyleConfig
from backend.workers.worker_logging import create_job_logger, setup_job_logging, job_logging_context
from backend.services.tracing import job_span, add_span_event, add_span_attribute
@@ -101,9 +100,6 @@ async def generate_screens(job_id: str) -> bool:
logger.error(f"[job:{job_id}] Job not found")
return False
# Copy uploads/{job_id}/** into jobs/{job_id}/input/ (uploads/ expires) and repoint the job.
await asyncio.to_thread(ensure_job_inputs_persisted, job, storage, job_manager, "screens")
# Idempotency guard: this worker may be dispatched twice (lyrics primary +
# audio fallback triggers, or a Cloud Tasks redelivery). Once the job has
# advanced past the pre-screens stage, a second dispatch is a duplicate — no-op
@@ -191,49 +187,38 @@ async def generate_screens(job_id: str) -> bool:
# Initialize video generator
video_generator = _create_video_generator(temp_dir)
# A theme may leave either screen out of its videos (intro/end.enabled=false).
include_title = style_config.include_title_screen
include_end = style_config.include_end_screen
title_screen_path = end_screen_path = None
# Generate title screen with style config
if include_title:
with job_span("generate-title-screen", job_id):
job_log.info("Generating title screen...")
title_screen_path = await _generate_title_screen(
job_id=job_id,
job=job,
video_generator=video_generator,
style_config=style_config,
temp_dir=temp_dir,
job_log=job_log
)
if not title_screen_path:
raise Exception("Title screen generation failed")
job_log.info(f"Title screen generated: {title_screen_path}")
else:
job_log.info("Theme omits the title screen — skipping it")
with job_span("generate-title-screen", job_id):
job_log.info("Generating title screen...")
title_screen_path = await _generate_title_screen(
job_id=job_id,
job=job,
video_generator=video_generator,
style_config=style_config,
temp_dir=temp_dir,
job_log=job_log
)
if not title_screen_path:
raise Exception("Title screen generation failed")
job_log.info(f"Title screen generated: {title_screen_path}")
# Generate end screen with style config
if include_end:
with job_span("generate-end-screen", job_id):
job_log.info("Generating end screen...")
end_screen_path = await _generate_end_screen(
job_id=job_id,
job=job,
video_generator=video_generator,
style_config=style_config,
temp_dir=temp_dir,
job_log=job_log
)
if not end_screen_path:
raise Exception("End screen generation failed")
job_log.info(f"End screen generated: {end_screen_path}")
else:
job_log.info("Theme omits the end screen — skipping it")
with job_span("generate-end-screen", job_id):
job_log.info("Generating end screen...")
end_screen_path = await _generate_end_screen(
job_id=job_id,
job=job,
video_generator=video_generator,
style_config=style_config,
temp_dir=temp_dir,
job_log=job_log
)
if not end_screen_path:
raise Exception("End screen generation failed")
job_log.info(f"End screen generated: {end_screen_path}")
# Upload screens to GCS
with job_span("upload-screens", job_id):
await _upload_screens(
@@ -243,12 +228,7 @@ async def generate_screens(job_id: str) -> bool:
title_screen_path=title_screen_path,
end_screen_path=end_screen_path
)
# Read by the render/encode stages (which run before the style is
# loaded) so an omitted screen isn't treated as missing.
job_manager.update_state_data(
job_id, SCREENS_INCLUDED_KEY, {"title": include_title, "end": include_end}
)
# Apply countdown padding if needed
await _apply_countdown_padding_if_needed(job_id, job_manager, job)
@@ -598,11 +578,11 @@ async def _upload_screens(
job_id: str,
job_manager: JobManager,
storage: StorageService,
title_screen_path: Optional[str],
end_screen_path: Optional[str]
title_screen_path: str,
end_screen_path: str
) -> None:
"""
Upload title and end screen images to GCS (None = screen omitted by the theme).
Upload title and end screen images to GCS.
Single Responsibility: Only handles uploads.
@@ -627,21 +607,28 @@ def _upload_screens_sync(
job_id: str,
job_manager: JobManager,
storage: StorageService,
title_screen_path: Optional[str],
end_screen_path: Optional[str]
title_screen_path: str,
end_screen_path: str
) -> None:
for screen, path in (("title", title_screen_path), ("end", end_screen_path)):
if not path:
continue
# Upload the screen's images (.png and .jpg)
base = path.replace('.png', '')
for ext in ('.png', '.jpg'):
image_path = f"{base}{ext}"
if os.path.exists(image_path):
gcs_path = f"jobs/{job_id}/screens/{screen}{ext}"
url = storage.upload_file(image_path, gcs_path)
job_manager.update_file_url(job_id, 'screens', f"{screen}_{ext[1:]}", url)
logger.info(f"Job {job_id}: Uploaded {screen} screen image ({ext})")
# Upload title screen images (.png and .jpg)
title_base = title_screen_path.replace('.png', '')
for ext, key in [('.png', 'title_png'), ('.jpg', 'title_jpg')]:
image_path = f"{title_base}{ext}"
if os.path.exists(image_path):
gcs_path = f"jobs/{job_id}/screens/title{ext}"
url = storage.upload_file(image_path, gcs_path)
job_manager.update_file_url(job_id, 'screens', key, url)
logger.info(f"Job {job_id}: Uploaded title screen image ({ext})")
# Upload end screen images (.png and .jpg)
end_base = end_screen_path.replace('.png', '')
for ext, key in [('.png', 'end_png'), ('.jpg', 'end_jpg')]:
image_path = f"{end_base}{ext}"
if os.path.exists(image_path):
gcs_path = f"jobs/{job_id}/screens/end{ext}"
url = storage.upload_file(image_path, gcs_path)
job_manager.update_file_url(job_id, 'screens', key, url)
logger.info(f"Job {job_id}: Uploaded end screen image ({ext})")
async def _analyze_backing_vocals(
+4 -11
View File
@@ -25,23 +25,16 @@ def main(argv=None) -> int:
parser.add_argument("--max-jobs", type=int, default=None)
parser.add_argument("--include-orphans", action="store_true")
parser.add_argument("--report-path", default=None)
parser.add_argument("--mode", choices=["job_purge", "orphans"], default="job_purge")
parser.add_argument("--max-folders", type=int, default=None)
args = parser.parse_args(argv)
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
from backend.services.storage_retention import StorageRetentionService
try:
if args.mode == "orphans":
report = StorageRetentionService().purge_orphans(
dry_run=args.dry_run, max_folders=args.max_folders, report_path=args.report_path,
)
else:
report = StorageRetentionService().run(
dry_run=args.dry_run, max_jobs=args.max_jobs,
include_orphans=args.include_orphans, report_path=args.report_path,
)
report = StorageRetentionService().run(
dry_run=args.dry_run, max_jobs=args.max_jobs,
include_orphans=args.include_orphans, report_path=args.report_path,
)
except Exception:
logging.getLogger(__name__).exception("STORAGE_RETENTION job crashed")
return 1
-22
View File
@@ -31,23 +31,11 @@ from karaoke_gen.style_loader import (
get_end_format,
get_karaoke_format,
get_cdg_format,
screen_enabled,
)
logger = logging.getLogger(__name__)
# state_data key the screens worker writes: {"title": bool, "end": bool} — which
# screens the job's theme includes. Absent (jobs screened before themes could omit
# screens) means both were made.
SCREENS_INCLUDED_KEY = "screens_included"
def screen_included(state_data: Optional[Dict[str, Any]], screen: str) -> bool:
"""Whether the job's videos include its "title" or "end" screen."""
included = (state_data or {}).get(SCREENS_INCLUDED_KEY) or {}
return included.get(screen, True) is not False
# Re-export defaults for backwards compatibility with existing code
DEFAULT_INTRO_FORMAT = DEFAULT_INTRO_STYLE
@@ -201,16 +189,6 @@ class StyleConfig:
"""Check if custom styles were provided (not using defaults)."""
return self._has_custom_styles
@property
def include_title_screen(self) -> bool:
"""Whether the theme puts a title screen at the start of the video."""
return screen_enabled(self._style_params, "intro")
@property
def include_end_screen(self) -> bool:
"""Whether the theme puts an end screen at the end of the video."""
return screen_enabled(self._style_params, "end")
@property
def intro_video_duration(self) -> int:
"""
+4 -17
View File
@@ -22,7 +22,6 @@ Observability:
- Logs include [job:ID] prefix for easy filtering in Cloud Logging
- Worker start/end timing logged with WORKER_START/WORKER_END markers
"""
import asyncio
import logging
import os
import shutil
@@ -37,7 +36,6 @@ from google.cloud.firestore_v1 import DELETE_FIELD
from backend.models.job import JobStatus
from backend.exceptions import InvalidStateTransitionError
from backend.services.job_manager import JobManager
from backend.services.input_persistence import ensure_job_inputs_persisted
from backend.services.storage_service import StorageService
from backend.services.admin_rerender_service import (
active_admin_rerender,
@@ -52,7 +50,7 @@ from backend.services.youtube_service import get_youtube_service
from backend.services.youtube_description import translated_language_name
from backend.services.encoding_service import get_encoding_service, run_with_lost_job_resubmit
from backend.config import get_settings
from backend.workers.style_helper import load_style_config, screen_included
from backend.workers.style_helper import load_style_config
from backend.workers.worker_logging import create_job_logger, setup_job_logging, job_logging_context
from backend.services.tracing import job_span, add_span_event, add_span_attribute
@@ -140,9 +138,6 @@ async def _encode_via_gce(
"base_name": base_name,
"instrumental_selection": instrumental_selection,
"existing_instrumental": existing_instrumental,
# Screens the theme leaves out (the encoder must not rebuild them from other PNGs).
"include_title_screen": screen_included(job.state_data, "title"),
"include_end_screen": screen_included(job.state_data, "end"),
# NOTE: intentionally no "ffmpeg_threads" — finalization ffmpeg commands in
# LocalEncodingService carry no -threads flag, so x264 uses its all-core auto
# default (measured ~66-78% of a 32-vCPU worker busy during the heavy libx264
@@ -263,9 +258,6 @@ async def generate_video_orchestrated(job_id: str) -> bool:
logger.error(f"[job:{job_id}] Job not found")
return False
# Copy uploads/{job_id}/** into jobs/{job_id}/input/ (uploads/ expires) and repoint the job.
await asyncio.to_thread(ensure_job_inputs_persisted, job, storage, job_manager, "video")
# Validate prerequisites
if not _validate_prerequisites(job):
logger.error(f"[job:{job_id}] Prerequisites not met for video generation")
@@ -279,7 +271,7 @@ async def generate_video_orchestrated(job_id: str) -> bool:
job_log.warning(status_error)
return False
# A user-supplied instrumental recorded under uploads/ expires (bucket lifecycle);
# A user-supplied instrumental recorded under uploads/ expires after 7 days;
# fall back to (and repoint the job at) its staged copy under jobs/{id}/.
if getattr(job, 'existing_instrumental_gcs_path', None):
job.existing_instrumental_gcs_path = resolve_existing_instrumental(
@@ -1305,13 +1297,9 @@ async def _handle_native_distribution(
job_log.info(f"Uploading to Dropbox folder: {remote_folder}")
from backend.services.dropbox_service import dropbox_skip_suffixes_for
# The orchestrator already uploaded this folder minus stems/ and
# lyrics/ (prepared just above) — only send what's new or changed
# instead of re-uploading every file a second time.
dropbox.upload_folder(
temp_dir, remote_folder,
exclude_suffixes=dropbox_skip_suffixes_for(dropbox_path),
skip_unchanged=True,
)
# Create sharing link
@@ -1513,9 +1501,8 @@ def _validate_prerequisites(job) -> bool:
# Check screens exist (MOV or PNG — MOV is no longer uploaded, PNG is the new default)
screens = job.file_urls.get('screens', {})
# A screen the theme omits (state_data.screens_included) isn't needed.
has_title = screens.get('title') or screens.get('title_png') or not screen_included(job.state_data, 'title')
has_end = screens.get('end') or screens.get('end_png') or not screen_included(job.state_data, 'end')
has_title = screens.get('title') or screens.get('title_png')
has_end = screens.get('end') or screens.get('end_png')
if not has_title or not has_end:
logger.error(f"Job {job.job_id}: Missing title or end screen")
return False
+11 -38
View File
@@ -49,18 +49,14 @@ class OrchestratorConfig:
artist: str
title: str
# Input file paths (in temp_dir). None = the theme leaves that screen out.
title_video_path: Optional[str]
# Input file paths (in temp_dir)
title_video_path: str
karaoke_video_path: str
instrumental_audio_path: str
end_video_path: Optional[str] = None
lrc_file_path: Optional[str] = None
title_jpg_path: Optional[str] = None
# Whether the theme includes the title / end screen (state_data.screens_included)
include_title_screen: bool = True
include_end_screen: bool = True
# Output directory
output_dir: str = ""
@@ -525,8 +521,6 @@ class VideoWorkerOrchestrator:
"output_gcs_path": output_gcs_path,
"countdown_padding_seconds": self.config.countdown_padding_seconds,
"existing_instrumental": self.config.existing_instrumental_gcs_path,
"include_title_screen": self.config.include_title_screen,
"include_end_screen": self.config.include_end_screen,
},
)
@@ -557,7 +551,7 @@ class VideoWorkerOrchestrator:
if src != dest:
self.storage.copy_blob(src, dest)
self.job_log.info(f"Staged custom instrumental for GCE encoder: {dest}")
# uploads/ expires (bucket lifecycle): point the job at the
# uploads/ expires after 7 days: point the job at the
# kept job-root copy for future re-renders/regenerates.
if src.startswith("uploads/") and self.job_manager:
self.job_manager.update_job(
@@ -898,19 +892,12 @@ class VideoWorkerOrchestrator:
self._queue_youtube_upload(user_email, reason="quota_exceeded_api")
return
# Transient failures (e.g. a dropped resumable session that outlived the
# in-process restarts) must not lose the upload: hand it to the deferred
# queue, which retries from the GCS finals (bounded by max_attempts).
self.job_log.error(f"YouTube upload failed, queueing for retry: {e}")
self._queue_youtube_upload(user_email, reason="upload_error", error=error_str)
if self.result.youtube_upload_queued:
self.result.distribution_warnings.append(
f"YouTube upload failed, queued for automatic retry: {e}"
)
self.job_log.error(f"YouTube upload failed: {e}")
self.result.distribution_warnings.append(f"YouTube upload failed: {e}")
# Don't fail the pipeline - YouTube is optional
def _queue_youtube_upload(self, user_email: str, reason: str = "quota_exceeded", error: Optional[str] = None):
"""Queue a YouTube upload for later processing (insufficient quota or a failed upload)."""
def _queue_youtube_upload(self, user_email: str, reason: str = "quota_exceeded"):
"""Queue a YouTube upload for later processing when quota is insufficient."""
try:
from backend.services.youtube_upload_queue_service import get_youtube_upload_queue_service
queue_service = get_youtube_upload_queue_service()
@@ -927,9 +914,8 @@ class VideoWorkerOrchestrator:
self.job_log.info(f"YouTube upload queued for later processing (reason: {reason})")
except Exception as e:
self.job_log.error(f"Failed to queue YouTube upload: {e}")
cause = f"upload failed: {error}" if error else "quota exceeded"
self.result.distribution_warnings.append(
f"YouTube upload skipped ({cause}) and failed to queue: {e}"
f"YouTube upload skipped (quota exceeded) and failed to queue: {e}"
)
def _stage_original_audio_for_upload(self):
@@ -1102,10 +1088,7 @@ class VideoWorkerOrchestrator:
async def _resolve_intro_seconds(self) -> float:
"""The master's silent title-card length = the job's style intro ``video_duration``
(default 5s). Read the *actual* value — long-intro styles exist. Falls back to 5s
(``get_intro_format`` raises when no theme is loaded — that's the fallback path).
0 when the theme leaves the title card out (the master starts with the song)."""
if not self.config.include_title_screen:
return 0.0
(``get_intro_format`` raises when no theme is loaded — that's the fallback path)."""
try:
from backend.workers.style_helper import load_style_config
import tempfile
@@ -1263,12 +1246,6 @@ def create_orchestrator_config_from_job(
duet_corrections_json_path = candidate
break
# Screens the theme leaves out (recorded by the screens worker).
from backend.workers.style_helper import screen_included
include_title = screen_included(job.state_data, "title")
include_end = screen_included(job.state_data, "end")
return OrchestratorConfig(
worker_generation=capture_generation(job),
job_id=job.job_id,
@@ -1276,15 +1253,11 @@ def create_orchestrator_config_from_job(
title=job.title,
# Input files — use actual extension from GCS (PNG for new jobs, MOV for legacy)
title_video_path=(
os.path.join(temp_dir, f"{base_name} (Title){_screen_ext(job, 'title')}") if include_title else None
),
title_video_path=os.path.join(temp_dir, f"{base_name} (Title){_screen_ext(job, 'title')}"),
# Use actual extension from GCS path (typically .mkv) instead of hardcoding .mov
karaoke_video_path=os.path.join(temp_dir, f"{base_name} (With Vocals){os.path.splitext(job.file_urls.get('videos', {}).get('with_vocals', '.mkv'))[1] or '.mkv'}"),
instrumental_audio_path=instrumental_path,
end_video_path=os.path.join(temp_dir, f"{base_name} (End){_screen_ext(job, 'end')}") if include_end else None,
include_title_screen=include_title,
include_end_screen=include_end,
end_video_path=os.path.join(temp_dir, f"{base_name} (End){_screen_ext(job, 'end')}"),
lrc_file_path=os.path.join(temp_dir, f"{base_name} (Karaoke).lrc"),
title_jpg_path=os.path.join(temp_dir, f"{base_name} (Title).jpg"),
+12 -25
View File
@@ -43,9 +43,7 @@ async def process_youtube_upload_queue() -> Dict[str, Any]:
queue_service = get_youtube_upload_queue_service()
# Check if any quota is available
# Every quota/queue call below is sync Firestore (+ Cloud Monitoring) I/O —
# each goes through asyncio.to_thread so this coroutine never blocks the loop.
allowed, remaining, message = await asyncio.to_thread(quota_service.check_quota_available)
allowed, remaining, message = quota_service.check_quota_available()
if not allowed:
logger.info(f"YouTube queue processor: no quota available, skipping. {message}")
return {
@@ -54,12 +52,12 @@ async def process_youtube_upload_queue() -> Dict[str, Any]:
"message": message,
"processed": 0,
"failed": 0,
"remaining": len(await asyncio.to_thread(queue_service.get_queued_uploads)),
"remaining": len(queue_service.get_queued_uploads()),
}
# Get queued uploads. Fetch more than we'll upload so entries whose claim is
# refused (job mid admin re-render) can't fill the page and starve others.
queued = await asyncio.to_thread(queue_service.get_queued_uploads, limit=QUEUE_FETCH_LIMIT)
queued = queue_service.get_queued_uploads(limit=QUEUE_FETCH_LIMIT)
if not queued:
logger.info("YouTube queue processor: no uploads queued")
return {
@@ -86,7 +84,7 @@ async def process_youtube_upload_queue() -> Dict[str, Any]:
break
# Re-check quota before each upload
allowed, remaining, message = await asyncio.to_thread(quota_service.check_quota_available)
allowed, remaining, message = quota_service.check_quota_available()
if not allowed:
logger.info(f"YouTube queue processor: quota exhausted after {processed} uploads")
break
@@ -94,7 +92,7 @@ async def process_youtube_upload_queue() -> Dict[str, Any]:
# Claim the entry. The claim transaction also reads the job and refuses
# while an admin re-render is active on it (the re-render's claim in turn
# refuses while an upload is processing), so the two never overlap.
if not await asyncio.to_thread(queue_service.mark_processing, job_id):
if not queue_service.mark_processing(job_id):
logger.info(f"YouTube queue processor: could not claim job {job_id}, skipping")
continue
attempted += 1
@@ -106,11 +104,11 @@ async def process_youtube_upload_queue() -> Dict[str, Any]:
uploaded_url = youtube_url
# Record completion FIRST: from here on the entry must never go
# back to "queued" (that would upload the video a second time).
await asyncio.to_thread(queue_service.mark_completed, job_id, youtube_url)
queue_service.mark_completed(job_id, youtube_url)
await _after_successful_upload(job_id, entry, youtube_url, jobs.get(job_id), queue_service)
processed += 1
else:
await asyncio.to_thread(queue_service.mark_failed, job_id, "Upload returned no URL")
queue_service.mark_failed(job_id, "Upload returned no URL")
failed += 1
except Exception as e:
@@ -120,21 +118,21 @@ async def process_youtube_upload_queue() -> Dict[str, Any]:
if uploaded_url:
# The video IS on YouTube; only recording it failed. Never
# re-queue — flag for attention instead.
await asyncio.to_thread(_flag_post_upload_error, queue_service, job_id, uploaded_url, error_str)
_flag_post_upload_error(queue_service, job_id, uploaded_url, error_str)
processed += 1
continue
# If quota exceeded, stop processing entirely
if "quotaExceeded" in error_str:
await asyncio.to_thread(queue_service.mark_failed, job_id, f"Quota exceeded: {error_str}")
queue_service.mark_failed(job_id, f"Quota exceeded: {error_str}")
logger.warning("YouTube queue processor: quota exceeded, stopping")
failed += 1
break
await asyncio.to_thread(queue_service.mark_failed, job_id, error_str)
queue_service.mark_failed(job_id, error_str)
failed += 1
remaining_count = len(await asyncio.to_thread(queue_service.get_queued_uploads))
remaining_count = len(queue_service.get_queued_uploads())
logger.info(
f"YouTube queue processor: done. processed={processed} failed={failed} remaining={remaining_count}"
)
@@ -152,7 +150,7 @@ async def _after_successful_upload(job_id: str, entry: Dict[str, Any], youtube_u
entry flagged for attention, never re-queued (the upload already happened)."""
try:
# Update job state_data with the YouTube URL
await asyncio.to_thread(_update_job_youtube_url, job_id, youtube_url)
_update_job_youtube_url(job_id, youtube_url)
except Exception as e:
logger.exception(f"YouTube queue processor: failed to record URL for job {job_id}")
_flag_post_upload_error(queue_service, job_id, youtube_url, f"update job: {e}")
@@ -229,17 +227,6 @@ async def _process_single_upload(
Returns:
YouTube URL if successful, None otherwise
"""
# GCS download + the whole YouTube upload are blocking, and this runs inside
# the API process (internal/admin queue routes) — keep it off the event loop.
return await asyncio.to_thread(_process_single_upload_sync, job_id, entry, quota_service, settings)
def _process_single_upload_sync(
job_id: str,
entry: Dict[str, Any],
quota_service,
settings,
) -> Optional[str]:
job_manager = JobManager()
storage = StorageService()
+7 -41
View File
@@ -344,7 +344,7 @@ Response:
### Re-render With Current Theme (tenant jobs)
Re-render a finished tenant track with the tenant's **current** theme, e.g. after editing it in "Theme & style". Jobs snapshot the theme at creation. A theme save re-applies the theme to tracks that haven't started rendering (see Tenant Theme Editor → Save), but finished tracks keep the old look until they are re-rendered.
Re-render a finished tenant track with the tenant's **current** theme, e.g. after editing it in "Theme & style". Jobs snapshot the theme at creation, so theme edits otherwise apply only to new jobs.
```http
POST /api/jobs/{job_id}/rerender
@@ -378,8 +378,6 @@ Downloads of archived files (`GET /api/jobs/{id}/download/{category}/{key}`) ret
Admin variant (optional quiet run, no rate limit): `POST /api/admin/jobs/{job_id}/regenerate` with `{"notify_customer": false}`.
**User inputs** (what regenerate/re-render needs) live in `jobs/{id}/input/**`: every pipeline worker copies `uploads/{id}/**` there on entry and repoints the job (`backend/services/input_persistence.py`; `uploads/` expires after 180 days). Backfill for jobs no worker will touch again: `POST /api/admin/persist-uploads` (admin; `?dry_run=false` to apply) → `{dry_run, jobs: {job_id: {copied, updated} | {would_copy} | {orphan: n} | {error}}}`; folders without a job document are reported as `orphan` and left in place.
A public → private visibility change on a track whose finals were archived regenerates them first (`after: "change_to_private"`), then runs the redistribution automatically.
### Review
@@ -576,8 +574,6 @@ Content-Type: application/json
```
Reopens a completed track for editing. Cleans up all distributed outputs (YouTube, Dropbox, GDrive, GCS finals), recycles the brand code, and resets the job to `awaiting_review`. A new review token is issued automatically. No additional credits consumed.
Because the track was already delivered, an edited job (`edit_count > 0`) is never refunded if it is later
deleted, cancelled or fails (closes the complete → edit → delete credit loop, v0.268.1).
If `artist` or `title` are provided and differ from current values, title/end screens are deleted and the screens worker is triggered to regenerate them in the background.
@@ -1389,10 +1385,8 @@ table, then submits each confirmed row through the standard signed-URL upload fl
```
GET /api/tenant/theme → {theme_id, style_params, images[], fonts[]}
POST /api/tenant/theme/assets (multipart `file`) → {name}
POST /api/tenant/theme/preview {style_params, sample?: {artist, title, lyrics[]}} → {title_card, karaoke_frame, end_screen}
PUT /api/tenant/theme {style_params} → GET fields + {refreshed_jobs, outdated_job_ids[]}
GET /api/tenant/theme/outdated-jobs → {theme_updated_at, job_ids[]}
POST /api/tenant/theme/rerender-outdated → {started[], failed: {job_id: reason}}
POST /api/tenant/theme/preview {style_params, sample?: {artist, title, lyrics[]}} → {title_card, karaoke_frame}
PUT /api/tenant/theme {style_params} → same as GET
Authorization: Bearer <session/token> (on the tenant portal: subdomain or X-Tenant-ID)
```
@@ -1405,46 +1399,18 @@ re-checks membership (`require_tenant_member`): non-members/spoofed headers →
`<stem>-<sha8>.<ext>` under `themes/<id>/assets/` (`no-store`), so they never overwrite an asset
existing jobs use.
- **Preview** renders the draft with the production renderers (`services/theme_preview_service.py`):
title card via `VideoGenerator.create_title_video(duration=0)`, end screen via
`VideoGenerator.create_end_video(duration=0)`, karaoke frame via
title card via `VideoGenerator.create_title_video(duration=0)`, karaoke frame via
`SegmentResizer` → `SubtitlesGenerator.generate_ass` → one ffmpeg frame (same `ass` filter/background
as the real render) with the first line half-sung. Returns 1280×720 JPEG data URLs (~2 s; ≤2
concurrent; identical drafts cached). A screen the theme leaves out is `null`. 400 invalid draft,
422 render failure, 504 timeout.
- **Leaving out the title card / end screen**: `intro.enabled` / `end.enabled` (optional bool, absent
= included; deliberately not in `DEFAULT_INTRO_STYLE`/`DEFAULT_END_STYLE`, which double as the
required-field lists). Read via `style_loader.screen_enabled`. The screens worker skips an omitted
screen and records `state_data.screens_included = {title, end}`; the render prerequisites, `/retry`
ladder (`_has_title_screen`), orchestrator and encoding config read that marker. The GCE encoder gets
explicit `include_title_screen` / `include_end_screen` = false (its loose `*title*.png` /
`*end*.png` globs would otherwise rebuild an omitted screen from `style/*_background.png`), and
`LocalEncodingService.encode_lossless_mp4` / the portrait renderer concat only the included segments.
No `(Title).mov` / `(End).mov` is delivered and the original-vocals guide gets no intro offset.
- **Save** applies to new jobs **and to the tenant's tracks that haven't started rendering**
(`services/theme_change_service.py`). Each such job's style snapshot is replaced
(`theme_applied_at` set). Jobs whose screens may already exist (`generating_screens` →
`in_review`, `render_pending_capacity`) also get `state_data.theme_screens_stale`. When the render
worker picks one up, it diverts once through the screens worker (`LYRICS_COMPLETE` +
`regen_restore_status=review_complete`), which regenerates the title/end screens and re-triggers the
render, so a user who is mid-review is never interrupted. `review_complete` and later jobs are left
alone. `refreshed_jobs` counts the jobs updated. `outdated_job_ids` lists the caller's finished tracks
made with an older theme, where "older" means the theme's `style_params.json` write time is later
than `theme_applied_at`, falling back to `created_at`. Members see their own tracks; admins see all
of the tenant's tracks. Editing a finished tenant track (`POST /api/jobs/{id}/edit`) also re-applies
the current theme when the track's copy is outdated.
- **Rerender-outdated** starts `POST /api/jobs/{id}/rerender` for every outdated track, **quietly**:
the `theme_rerender.notify_customer=false` marker suppresses the per-track completion email/push.
- **Save validation** is stricter than the admin console: asset fields must
concurrent; identical drafts cached). 400 invalid draft, 422 render failure, 504 timeout.
- **Save** (applies to jobs created afterwards). Stricter than the admin console: asset fields must
be basenames already in the theme's assets (no paths / `gs://`), numeric/colour/region bounds are
checked, and the font is made consistent with the render pipeline — `intro.font` is applied to
`karaoke.font_path`/`end.font`/`cdg.font_path`, `karaoke.font` is set to the TTF family name libass
matches, and a chosen bundled font is copied into the theme's assets. Tenants can't change their
config/allowlist through this API.
UI: user menu → **Theme & style** on tenant portals (`components/tenant-theme/`). After a save, the
editor says how many in-progress tracks were updated and offers **Re-render all N** for outdated
finished tracks. Their job cards show an **Older theme** badge on Re-render
(`lib/tenant-theme-outdated.ts`). On portal cards, admins see only this Re-render, not the admin one.
UI: user menu → **Theme & style** on tenant portals (`components/tenant-theme/`).
#### Tenant Provisioning (Admin Only)
+2 -5
View File
@@ -253,11 +253,8 @@ jobs completed (newest `complete` timeline entry) more than `STORAGE_RETENTION_M
(regenerate, admin/theme re-render, private→public, Edit, retry) passes the screens worker, whose
**stems gate** (`backend/services/stems_restore.py`) re-runs the audio-separation job in restore mode
when `stems_purged_at` is set; the audio worker re-triggers screens when the stems are back.
- Bucket: versioning on, noncurrent (overwritten or deleted) versions kept 7 days, soft delete 7 days —
purged bytes remain recoverable for about two weeks.
- Every deleted object is logged (path, size, generation) under
`storage-retention/deletion-logs/`; review/restore commands and the one-off orphan-folder cleanup are in
`docs/STORAGE-RETENTION.md`.
- Bucket: versioning on, overwritten versions kept 7 days, soft delete 7 days — purged bytes remain
recoverable for about a week.
## LyricsTranscriber Integration
+2 -3
View File
@@ -1,6 +1,6 @@
# Disaster Recovery Runbook
**Last updated:** 2026-10-08
**Last updated:** 2026-10-01
**Design doc:** `docs/archive/2026-03-27-business-continuity-design.md`
**Implementation plan:** `docs/archive/2026-03-29-business-continuity-plan.md`
**External services reference:** `docs/archive/2026-03-29-external-services-config.md`
@@ -13,8 +13,7 @@
| BigQuery (weekly) | S3 `bigquery/daily-refresh/` | Load Parquet files | 7 days |
| BigQuery (monthly) | S3 `bigquery/musicbrainz/` | Load Parquet files | 30 days |
| BigQuery (Spotify) | S3 `bigquery/spotify/` | Load from Glacier Deep Archive | N/A (static) |
| GCS job files | **GCS only** — object versioning (non-current kept 7d since 2026-10-03) + soft-delete (7d). Off-site S3 copy **stopped 2026-10-01**; S3 `gcs/job-files/` is a frozen snapshot up to 2026-09-30 | Restore non-current/soft-deleted generation in GCS | N/A off-site (frozen); in-GCS recovery window 7–30d |
| User-uploaded inputs (mix, own instrumental, lyrics, style uploads) | `jobs/{id}/input/**` (KEEP forever; copied from `uploads/{id}/` by every pipeline worker, `backend/services/input_persistence.py`). `uploads/` expires after **180 days** (was 7 until 2026-10-08) | Read from `jobs/{id}/input/`; backfill stragglers with `POST /api/admin/persist-uploads?dry_run=false` | Irreplaceable: no off-site copy. Lost for 64 Jan–Feb 2026 consumer jobs + BYO-instrumental jobs before the fix |
| GCS job files | **GCS only** — object versioning (non-current kept 30d) + soft-delete (7d). Off-site S3 copy **stopped 2026-10-01**; S3 `gcs/job-files/` is a frozen snapshot up to 2026-09-30 | Restore non-current/soft-deleted generation in GCS | N/A off-site (frozen); in-GCS recovery window 7–30d |
| Git repos (code) | S3 `git-repos/{owner}/{repo}.bundle` (+ `manifest.json`) | `git clone <bundle>` then push to a new remote | 7 days (weekly, Sundays; incremental) |
| Secret Manager | S3 `secrets/YYYY-MM-DD.bin` (sealed-box encrypted) | Decrypt with private key from KeepassXC | 24h |
| AWS credentials (function) | GCP Secret Manager `aws-backup-credentials` | Read directly | On-change |
-71
View File
@@ -6,44 +6,6 @@ Key insights for future AI agents working on this codebase.
---
## User uploads sat under a 7-day-expiring prefix — inputs are irreplaceable (Oct 2026, v0.268.2)
Every upload lands in `uploads/{job_id}/`, which had a bucket lifecycle **delete after 7 days**. Only
the audio worker (stem separation) copied the mix to `jobs/{id}/input/`, best-effort. Bring-your-own-
instrumental jobs (all tenant jobs) skip separation, the uploaded instrumental was only staged at
render time, and lyrics/style uploads were never copied — so a job left in review >7 days, or
re-rendered after 7 days, 404'd on its own input (randy-vild re-renders, 2026-10-08). Firestore also
showed 64 completed Jan–Feb 2026 consumer jobs whose mix is gone for good (no S3 copy: the off-site
sync only ever covered `jobs/`, `tenants/`, `themes/`).
- **Rule:** anything a user gave us is never under an expiring prefix once a job exists. Every
pipeline worker calls `input_persistence.ensure_job_inputs_persisted` on entry (server-side copy of
`uploads/{id}/**` → `jobs/{id}/input/**` + repoint every job field); `uploads/` now expires after
180 days as a pure staging area. `jobs/{id}/input/` is KEEP-forever in `storage_retention`.
- **Don't confine persistence to one stage**: inputs arrive late (conformed instrumentals, style
uploads) and stages get skipped per job type. Make it idempotent and call it everywhere.
- **Lifecycle rules are data-retention policy**: review them like deletes — a `matches_prefixes`
entry is a silent `rm -rf` on a timer.
- Recovery that worked: originals in Andrew's Dropbox, pulled GCP-side (Cloud Shell) via the
folder's existing shared link (the backend Dropbox app lacks `files.content.read`, but
`sharing.read` + `sharing_get_shared_link_file` works), conformed instrumentals re-derived
deterministically with `conform_instrumental` and checked against `state_data.instrumental_conformed`.
## Public-repo CI artifacts published the real test card and the admin token (Oct 2026)
Investigating E2E Daily #200 ("Stage 1 failed", Stripe self-heal "not needed") showed two things:
- **The failure was the issuer declining the card** (`confirm` → 402 `card_error/generic_decline`,
likely a fraud hold after ~8 live $0.50 charges in a day), but the self-healing runner treated it
like a layout change: 90s verify wait, then 6 Gemini calls "re-entering" a correct form. Detect
non-recoverable outcomes from the network (the confirm response), not from the UI, and abort.
- **Every run's artifacts held the full card number/expiry/CVC** (manual screenshots, Playwright
auto-screenshots, videos, `error-context.md` ARIA snapshot, DOM dump) **and `X-Admin-Token`**
(trace network logs) — in a public repo, downloadable by anyone signed in to GitHub. `::add-mask::`
only protects *logs*, never artifacts. Fix: scrub before every upload (`e2e/scripts/scrub-artifacts.mjs`),
traces off on CI, masked screenshots. All 140 existing e2e artifacts were deleted; the exposed admin token
and test card must be rotated.
## One event loop per instance: `async def` without `await` is a whole-instance freeze (Oct 2026, v0.264.0)
The "servers unavailable" banner (49 episodes in 2 weeks) was mostly the API's own event loop freezing for 20-45s. Each episode hit 2-3 browsers in the same second, and only ~7 of 28 were near a deploy. Signature in the request logs: every request on the instance, `/api/health` included, completes at the same moment.
@@ -55,21 +17,10 @@ The "servers unavailable" banner (49 episodes in 2 weeks) was mostly the API's o
- The inverse also fails: a `def` route that calls `asyncio.create_task`/`get_running_loop`. In the threadpool, that raises, or silently does nothing if the `RuntimeError` is swallowed (`rate_limits.trigger_youtube_queue_processing` did exactly that).
- **Moving a handler into the threadpool removes the implicit per-instance serialization.** A never-awaiting `async def` used to run start-to-finish uninterrupted, so non-transactional check-then-write code (a double-clicked Cancel refunding twice, a double Complete) was safe on one instance. `backend/utils/keyed_lock.py` restores that: `JobManager.transition_to_state`/`cancel_job` lock per job, `UserService.add_credits` per user. Also grep for `await <converted handler>(`; the guard test checks this now (it found `admin.update_job` awaiting `delete_job_outputs`).
- **Watchdog vs `--cpu-throttling`:** an idle instance gets no CPU between requests, so a gap with the loop parked in `select()` is not a stall. The watchdog drops all-idle samples.
- Throttling can also freeze the process **mid-callback** (v0.268.1). On 2026-10-08 that produced a 30s ERROR "stall" in asyncio's `get_debug` on an instance with no request in flight. The signature: the watchdog thread itself oversleeps (≥2s) while the process uses almost no CPU (`time.process_time`). A blocking I/O call releases the GIL, so the watchdog still wakes on time. GIL-hogging CPU work burns CPU. So that frozen time is subtracted from the stall, and no sample is logged for it. A stall whose culprit is pure asyncio internals, with no app frame, is usually this.
- Partial throttling gives the watchdog an occasional time slice, so its wake gap stayed under the original 2s threshold. In 24h, 126 of 128 asyncio-internal stalls (mostly 1-2.5s) had no request waiting on them. Overlapping requests took milliseconds, because they were the requests that brought the CPU back. The threshold is now 0.75s (3 missed 0.25s ticks; v0.268.2). Measured wake gaps stay ≤0.27s with the loop blocked on sync I/O, Python CPU work or C-extension CPU work. To check that a stall class is harmless, compare each stall window with that instance's request logs. A request waited if it **started before the stall really ended**. The `ended` log lags the real end by up to one watchdog tick (0.25s), so harmless "overlaps" show up as a request starting ~0.26s before the logged end and finishing in ~4ms: it's the request that brought the CPU back.
- The 2 user-felt ones were cold-start `importlib` stalls (4-15s) from routes that lazily import modules pulling in `httpx`. Lifespan startup now imports `main._LAZY_ROUTE_IMPORTS` in a worker thread before readiness. A background warmup thread alone would still race the first request.
- **An `await` somewhere in the handler doesn't make its other calls safe** (v0.267.1). `mark_uploads_complete`, `create_job_with_upload_urls` and others awaited `request.json()`, so they passed the guard, yet called `check_dropbox_credentials()` inline. When the Dropbox token had expired, that did an HTTP refresh plus a Secret Manager write and version cleanup on the loop, a 16s freeze. `trigger_gdrive_validation_endpoint` froze 5-10s after every job (OIDC fetch + POST). Both are now behind `asyncio.to_thread`, and the guard's `BLOCKING_CALLS` denylist fails CI if a known-blocking function is called directly in an `async def` route. Add to the denylist when the watchdog names a new culprit.
- **Mostly-sync routes that await one trigger** (v0.268.1). `complete_review` (21s corrections `upload_json`), `create_job_from_search` (theme prep), and the `recover_stuck_jobs` / `retry_pending_render_jobs` crons (~260 stalls/week from Firestore scans) each awaited a worker trigger, so the guard passed them. Their bodies now run in a worker thread, and the trigger coroutines go back to the API loop with `backend/utils/loop_bridge.run_on_loop` (`run_coroutine_threadsafe`, 120s timeout), so loop APIs inside the triggers still work. Bodies that call `run_on_loop` run on their own pool (`run_in_body_thread`), not the default executor. Otherwise they could hold every default-pool thread while the coroutines they wait on need one, a deadlock. Watch out for an `async def` helper with no awaits inside, such as `_validate_audio_durations` (2 downloads + 2 decodes) or the YouTube queue's `_process_single_upload` (a whole upload): it's sync work on the loop with an async signature. To rank culprits, group `EVENT_LOOP_STALL in progress` stacks by their first `api/routes/` frame.
- **Detection:** `backend/services/loop_watchdog.py` logs `EVENT_LOOP_STALL` with the loop thread's stack and a `culprit=file:line`. Grep for it before guessing.
---
## Every job was uploaded to Dropbox twice (Oct 2026, v0.268.2)
`generate_video_orchestrated` runs the orchestrator's Dropbox upload (output folder minus `stems/` and `lyrics/`), then `_handle_native_distribution` builds those subfolders and re-uploaded the **whole** folder, about 400 MB again per job. The orchestrator's pass can't simply be dropped: its `result.dropbox_link` is what gets written to the job. And the subfolders can't be built before the orchestrator runs, because building them deletes simplified instrumentals that the orchestrator needs. The second pass now uses `upload_folder(..., skip_unchanged=True)`. It lists the folder once (recursively) and skips files whose Dropbox `content_hash` (SHA-256 of 4 MiB block hashes) already matches, so only the new `stems/`, `lyrics/` and model-named instrumentals go up. If the listing fails, it falls back to a full upload.
---
## Re-running the render pipeline: three ways the OLD output sneaks back in (Sep 2026, v0.253.0)
Building "re-render with the current theme" turned up three traps. Any path that re-runs screens/render/encode on a finished job (edit, visibility change, admin reset, theme re-render) has to handle all three.
@@ -2308,25 +2259,3 @@ added another selector variant — and each next change still needed a human. Le
masked screenshots; tests assert the prompt contains no secrets.
See `docs/TESTING.md` § Self-Healing Stripe Checkout.
## Encoding worker: a degraded fallback that "works" is worse than a crash (2026-10-06)
The primary encoding VM booted before its network was up. The bootstrap's one GCS download
failed and it silently ran the image's fallback startup script, which wrote an env file
missing both the API key and `GCE_METADATA_MTLS_MODE=none`. The worker came up, passed
`/health`, and failed every job on the metadata-server SSL handshake for an hour. The
backend deliberately retries the *primary* on infra errors (only fallbacks get demoted), so
nothing broke the loop until a manual `systemctl restart`. Lessons:
- **Put critical config in code, not only in the deploy script.** `GCE_METADATA_MTLS_MODE`
is now defaulted in `gce_encoding/main.py`, so every boot path (GCS startup, image
fallback, a hand-run uvicorn) gets it.
- **Fail closed and let the supervisor retry.** Missing API key or no GCP credentials →
refuse to start; systemd (`Restart=always`) re-runs the bootstrap, which works once the
network is up. Gate this on "really a worker VM" (`INVOCATION_ID` **and**
`/opt/encoding-worker/bootstrap.sh`), because CI runners can be systemd services too.
- **"Bounded retry on the primary" needs a bound.** The backend now logs primary infra
failures at ERROR, and the worker restarts itself, so the retry loop can't run silently.
- **Worker app logs only reach the serial console**, not Cloud Logging. Check
`get-serial-port-output` first when the worker misbehaves.
-10
View File
@@ -57,13 +57,6 @@
## Recent Changes
- **Encoding worker heals itself after a bad boot** (2026-10-06, v0.266.4). The primary encoding VM booted before its network was up, so `bootstrap.sh` couldn't download `startup.sh` and fell back to the image's `startup-fallback.sh`. That script left out `ENCODING_API_KEY` and `GCE_METADATA_MTLS_MODE=none`, so every render and preview failed with `CERTIFICATE_VERIFY_FAILED` on the metadata server. A Randy Vild render looped in `render_pending_capacity` for an hour until the service was restarted by hand. Fixes:
- The worker defaults `GCE_METADATA_MTLS_MODE=none` itself (`gce_encoding/main.py`), so every boot path gets it.
- The worker refuses to start when the API key is missing or it can't get GCP credentials, and exits after an infra/auth job failure once idle. systemd then re-runs the bootstrap (`gce_encoding/self_heal.py`; only on worker VMs).
- The Packer bootstrap retries the GCS download for about 2 minutes. The fallback writes the mTLS setting and exits if it can't fetch the API key. This needs the new image.
- An infra failure on the primary now logs at ERROR, so it alerts.
- The job card stops showing "(waiting for encoding server availability)" once a retried render reports progress: `state_data.render_pending_capacity` is cleared.
- **Encoding-service construction moved off the event loop** (2026-10-03, v0.264.1). The new loop watchdog's first prod catch was a 9.9s stall in `/api/health/detailed`. A cold `get_encoding_service()` imports `google.cloud.compute_v1` (~10s). It's now built in the startup warmup thread, is thread-safe, and async callers use `asyncio.to_thread`. (v0.264.0 was shipped by both #1120 and #1122.)
- **API event-loop freezes fixed + degradation telemetry identifies users** (2026-10-03, v0.264.0). The "Reconnecting" pill and "servers unavailable" banner were mostly caused by the single API instance freezing for 20-45s. Plan + evidence: `docs/archive/2026-10-03-backend-loop-freezes-telemetry-plan.md`.
@@ -83,9 +76,6 @@
- Lyrics review Waveforms toggle: shows a spinner and tooltip while audio separation is still producing the vocal stem (the peaks endpoint returns 202). Previously the rows were just empty (`VocalsAudioDataLoaderContext.status`).
- **Translated lyrics: Japanese/Chinese translations no longer split mid-word** (2026-10-01, v0.260.1): when a long lyric line is split across rows, its translation is shared between them. Unspaced scripts were cut at an arbitrary character, so prod job ca2e881a showed 無|駄 ("waste") across two rows. `split_text_proportionally` now prefers punctuation, then a break after a Japanese particle or before a kanji/katakana word start, and only cuts mid-word as a last resort; it no longer leaves a piece empty when there are enough characters. Thai can still split inside a word (no word-boundary data).
- **Translated lyrics for language learners** (2026-10-01, v0.260.0): an "Add translated lyrics" option at job creation (any job, free for now) with a language picker (33 UI locales) and a live preview of the real video frame (`GET /api/themes/translation-preview`). After review, the render worker translates the final lyrics line by line with Gemini (`backend/services/lyrics_translation.py`, GCS-cached so re-renders are free) into `lyrics/translations.json`; the landscape and portrait videos draw each translation in smaller unsung-colour text beneath its line, 3 lines per screen (`ass/config.py:translation_layout`, `LyricsLine._create_translation_event`). Translations are their own ASS events with auto paragraph direction, so mixed scripts work (a Hebrew song keeps its right-to-left highlight with an English translation beneath, and vice versa); long translations wrap/scale to fit; a line split by the resizer shares its translation across the pieces. Not editable; a translation failure renders without it (`state_data.lyrics_translation`). See [archive/2026-10-01-translated-lyrics-plan.md](archive/2026-10-01-translated-lyrics-plan.md).
- **User-uploaded inputs kept forever** (2026-10-08, v0.268.2): `uploads/` had a 7-day lifecycle delete and only the audio worker copied the mix out, so bring-your-own-instrumental/tenant jobs (and any job left in review >7 days) lost their mix and instrumental; re-renders 404'd. Every pipeline worker now copies `uploads/{id}/**` to `jobs/{id}/input/**` and repoints the job (`backend/services/input_persistence.py`); `POST /api/admin/persist-uploads` backfills; `uploads/` now expires after 180 days. randy-vild inputs were restored from Dropbox. See [LESSONS-LEARNED.md](LESSONS-LEARNED.md).
- **End screen fully editable + previewed; title card / end screen can be left out** (2026-10-08, v0.268.0): Randy Vild reported "large text at the end even though I have in my settings smaller text like in my beginning". The theme editor's sizes/positions only edited `intro.*`; the end screen keeps its own `end.*` layout (title/artist regions, artist colour, capitals), and the editor neither showed it nor previewed it. The End screen tab now has its own colours, size/position sliders, show/hide for the song title and artist name, capitals toggles, and **Copy title card layout** (matches the title card and moves the closing message above the title so nothing overlaps). The preview renders the real end screen (`create_end_video`). Both tabs have an "Include …" switch (`intro.enabled` / `end.enabled`); leaving a screen out flows through the screens worker, `/retry`, the orchestrator, the GCE encoder, `LocalEncodingService` and the portrait render (see [API.md](API.md#tenant-theme-editor-tenant-users)).
- **Theme edits reach tracks in progress; outdated finished tracks get a re-render prompt** (2026-10-06, v0.267.0): Randy Vild edited his theme and the next video still had the old title card. Its job had copied the theme at creation, 30 minutes before the edit, and was waiting for encoding capacity when he saved. A theme save now re-applies the theme to every tenant track that hasn't started rendering. If a track's screens were already made, the render worker regenerates them first, at render time, so nobody is interrupted mid-review. Editing a finished tenant track also picks up the current theme. After saving, the theme editor lists finished tracks that still have the old look and offers a quiet **Re-render all N** (no per-track emails). Those tracks' cards show an "Older theme" badge. Admins no longer see two identical Re-render buttons on portal tracks (`backend/services/theme_change_service.py`).
- **Re-render works for tenants that archive to Dropbox** (2026-09-30, v0.254.1): randy-vild jobs get a brand code and a Dropbox archive folder (`RVILD-0001 - …`), so v0.253.0's "never distributed" guard rejected the very jobs the button was for. A re-render now reuses the job's brand code and overwrites the same folder instead of allocating a new code. YouTube/GDrive-published jobs are still rejected.
- **Tenant "Re-render" with the current theme + edited tenant tracks no longer lose their downloads** (2026-09-30, v0.253.0): Finished portal tracks have a **Re-render** button (`POST /api/jobs/{id}/rerender`). It re-applies the tenant's current theme and rebuilds the screens, lyrics video, encodes and CDG/TXT from the already-reviewed lyrics, with no review step (`backend/services/theme_rerender_service.py`, same mechanism as the private→public visibility change). The encoding worker caches finished jobs by id in memory, so a re-run submitted while the VM was still up could get the previous render back. Render and encode now submit as `{job_id}_g{worker_generation}` (`encoding_worker_job_id`). Separately, `outputs_deleted_at` (set by Edit) was only cleared when the re-render uploaded to YouTube/Dropbox/GDrive, so edited tenant jobs re-rendered but hid every download (job 2579a1ea). Every successful render now clears it.
- **Hold a word's resize handle at the row edge to keep extending it** (2026-09-30, v0.252.0): in the lyrics review Waveforms rows (and the Edit Segment timeline) the view is the segment ±1s and was fixed during a drag, so a word ending 5s+ too early took several drag-release cycles. Holding a resize handle within 24px of the edge it's heading toward (or past it) now keeps growing the word at 1–4 s/s (faster nearer the edge), zooming the view out so the handle stays under the cursor. It stops when the pointer leaves the zone, on release, or at the neighbouring word, including the next/previous line's first/last word (`computeNeighbourBoundsBySegment`), else the audio bounds. Drags are tracked on `window`, so leaving the row no longer abandons them, and resizes clamp to the neighbour instead of freezing short of it (`TimelineEditor.tsx`).
-73
View File
@@ -1,73 +0,0 @@
# Storage retention: operations
Policy + design: `docs/ARCHITECTURE.md` § Storage Retention. Code:
`backend/services/storage_retention.py`, `backend/workers/storage_retention_worker.py`.
## Runs
| Mode | Trigger | Deletes |
|---|---|---|
| `job_purge` | Cloud Scheduler `storage-retention-daily` (10:30 UTC) → `POST /api/internal/storage-retention/run` → Cloud Run Job `storage-retention-job` (us-east4) | Regenerable files of jobs completed >30 days ago, up to `STORAGE_RETENTION_MAX_JOBS_PER_RUN` (50) per run. Real deletion is on (`STORAGE_RETENTION_DRY_RUN=false` in the CI `--set-env-vars` of the backend deploy — the API passes the flag to the job; that's the only place it's set). |
| `orphan` | Manual: `POST /api/internal/storage-retention/orphans` (dry-run) / `?dry_run=false&confirm=delete-orphan-job-folders` | Everything except `input/` in `jobs/{id}/` folders with no record in `jobs`, `jobs-dev` or `youtube_upload_queue` (checked live per folder) and nothing modified in the last 30 days. |
Manual trigger (admin token):
```bash
TOK=$(gcloud secrets versions access latest --secret=admin-tokens --project=nomadkaraoke | cut -d, -f1)
curl -X POST https://api.nomadkaraoke.com/api/internal/storage-retention/run -H "X-Admin-Token: $TOK"
curl -X POST https://api.nomadkaraoke.com/api/internal/storage-retention/orphans -H "X-Admin-Token: $TOK" # dry-run
```
## Where the record is
- `gs://karaoke-gen-storage-nomadkaraoke/storage-retention/reports/<ts>-{dry-run,run}.json`,
`<ts>-orphans-{dry-run,run}.json`: the plan/outcome of each pass (dry-runs included).
- `gs://karaoke-gen-storage-nomadkaraoke/storage-retention/deletion-logs/<ts>-<mode>.jsonl`: **one line
per object a real run deleted (or failed to)**:
`timestamp, run_id, mode (job_purge|orphan), job_id, path, size_bytes, generation, category
(finals|videos|stems|review-audio|previews|screens-mov|encoded|quick|orphan-nonInput), result
(deleted|failed), error`. Rewritten after every job/folder, so a crash leaves a complete record up to
the last finished job.
- `.../deletion-logs/<ts>-<mode>.summary.json`: totals by category, job count, GiB, failures.
- Each purged job's Firestore doc: `storage_purge` (files + generations + `deletion_log`),
`renders_purged_at`, `stems_purged_at`.
The `storage-retention/` prefix is never touched by retention code (it only deletes inside
`jobs/{id}/`, enforced by `assert_deletable`) and no lifecycle rule matches live objects there
(the rules are: age 7 on `temp/`+`uploads/`, and noncurrent versions after 7 days). Logs are kept
forever.
## Reviewing
```bash
B=gs://karaoke-gen-storage-nomadkaraoke/storage-retention/deletion-logs
gcloud storage ls "$B/" # all runs
RUN=20261004T150000Z-job_purge # pick one from the listing
gcloud storage cat "$B/$RUN.summary.json" | jq . # one run's totals
gcloud storage cat "$B/$RUN.jsonl" | jq -s 'map(select(.result=="deleted")) | group_by(.category)
| map({category: .[0].category, objects: length, gib: (map(.size_bytes)|add/1073741824)})'
gcloud storage cat "$B/$RUN.jsonl" | jq -s 'group_by(.job_id) | map({job: .[0].job_id,
gib: (map(.size_bytes)|add/1073741824)}) | sort_by(-.gib)' # per job
gcloud storage cat "$B/$RUN.jsonl" | jq -c 'select(.result=="failed")'
JOB=abc12345
gcloud storage cat "$B/*.jsonl" | jq -c --arg j "$JOB" 'select(.job_id==$j)' # everything deleted for a job
```
Or: `python scripts/storage_retention_report.py` (all runs), `... <run_id>` (one run, per category and
job), `... --find <job_id|path>` (which run deleted it, with a restore command).
## Restoring
The bucket keeps deleted objects as noncurrent versions for 7 days, then soft delete keeps them 7 more
days. With the `generation` from the log:
```bash
OBJ='jobs/abc12345/finals/lossy_4k_mp4.mp4'; GEN=1790000000000000 # from a result=="deleted" log line
# within ~7 days (noncurrent version):
gcloud storage cp --no-clobber "gs://karaoke-gen-storage-nomadkaraoke/$OBJ#$GEN" "gs://karaoke-gen-storage-nomadkaraoke/$OBJ"
# days 7-14 (soft-deleted):
gcloud storage restore "gs://karaoke-gen-storage-nomadkaraoke/$OBJ#$GEN"
```
After restoring a purged job's files, prefer simply using "Regenerate video" (or
`POST /api/admin/jobs/{id}/regenerate`) — it rebuilds everything and clears the purge markers.
-33
View File
@@ -482,14 +482,6 @@ The production tests cover:
## Self-Healing Stripe Checkout (daily E2E Stage 1)
> **Payment mode (repo variable `E2E_REAL_PAYMENT`).** Unset/anything but `true` →
> `E2E_PAYMENT_MODE=checkout-only` (current default since 2026-10-05, no working test card):
> Stage 1 signs up via the referral link, creates a real Checkout session, fills it with Stripe's
> public test card `4242…` (`NO_CHARGE_CARD`), asserts the $0.50 price + Pay button, and **stops
> before Pay** — no charge, no credit grant, no self-heal PR. Stage 2 uses the new account's signup
> credit. Set `E2E_REAL_PAYMENT=true` (Settings → Variables) to resume buying a real credit with
> the `E2E_STRIPE_CARD_*` card.
Stripe changes its hosted checkout page without notice (5 breaking changes Apr–Oct 2026),
so `frontend/e2e/helpers/stripe-checkout.ts` runs the checkout as **verified sub-goals**
(`selectCard`, `fillCardNumber`, `fillCardExpiry`, `fillCardCvc`, `fillCardholderName`,
@@ -526,13 +518,6 @@ defaults it to `true` (server-side, ~Aug 2026), which silently blocks bot-author
update ever omits the key, GitHub resets it to `true` — set it explicitly. Discord + the daily email
report 🩹 when this happens. Only one open self-heal PR at a time.
**Declined card ≠ layout change.** The helper watches Stripe's
`/v1/payment_pages/<id>/confirm` response; a `card_error` (e.g. `card_declined/generic_decline`)
fails `submitPayment` immediately with `STRIPE_CARD_DECLINED: …` — no LLM calls, no second Pay
click. The workflow surfaces it as the Stage 1 `failure_reason` in Discord and the daily email
("Test card declined, not a checkout bug"). Fix it on the card side (issuer fraud hold — e.g.
after many live $0.50 runs in a day — or an expired/replaced card), then re-run.
The Gemini key is the AI Studio `gemini-api-key` (billed outside the nomadkaraoke project):
a `GEMINI_API_KEY` repo secret if set, else read from Secret Manager via keyless auth (the
credential file is deleted before tests run). No key → deterministic-only, as before.
@@ -545,24 +530,6 @@ npx playwright test --config=playwright.selfheal.config.ts
# self_heal_force_llm = selectCard (forces that step through Gemini; opens a PR)
```
## E2E Artifacts Are Public — Scrub Before Upload
karaoke-gen is a **public** repo: any signed-in GitHub user can download Actions artifacts.
Every workflow that uploads production-E2E output runs `frontend/e2e/scripts/scrub-artifacts.mjs`
first and only uploads if the scrub succeeded:
- deletes Playwright traces (`*.zip` — they contain every request header incl. `X-Admin-Token`
and every typed value) and `e2e-session-token.txt`;
- replaces literal secret values (admin token, testmail key, card number, session tokens…) and
card-number-shaped digit runs in text files; deletes any text file still containing a secret;
- Stage 1 also passes `--drop-videos --blank-inputs` (videos of the Stripe page; `<input value>`
and ARIA-snapshot textbox values in DOM dumps / `error-context.md`).
In addition, `playwright.production.config.ts` turns traces **off on CI** (`E2E_TRACE=on` to
override), the credit-purchase spec disables trace/video/auto-screenshots, and the Stripe helper's
own screenshots mask every input. When adding a new secret to a production E2E job, add its env
var to `SECRET_ENV_VARS` in the scrubber and to the job's scrub step.
## Concurrent-Load Regression Test (review pages)
`scripts/load-test-review.py` replays the 2026-09-18 "10 tabs melt the backend"
-34
View File
@@ -493,40 +493,6 @@ gcloud compute instances describe encoding-worker-a \
---
## Every render/preview fails with `CERTIFICATE_VERIFY_FAILED` on `metadata.google.internal`
**Symptoms:** Jobs park in `render_pending_capacity` with `last_code: worker_infra_failure` and empty `last_vm`/`last_zone`, and retry every 10 min without recovering. Backend logs show `Worker reported an infrastructure/auth failure` with `Failed to retrieve https://metadata.google.internal/...` / `SSLCertVerificationError`. The worker still answers `/health`.
**Cause (2026-10-06):** the VM booted before its network was up. `bootstrap.sh` couldn't download `startup.sh` from GCS and used the image's `startup-fallback.sh`, which (on images built before v0.266.4) writes an env file without `ENCODING_API_KEY` or `GCE_METADATA_MTLS_MODE=none`. google-auth then uses mTLS to the metadata server and fails.
**Diagnose:** worker app logs are not in Cloud Logging; read the serial console (journald goes there):
```bash
gcloud compute instances get-serial-port-output encoding-worker-b --zone=us-central1-c --project=nomadkaraoke \
| grep -E "Bootstrap|FALLBACK|Network is unreachable|No API key configured|SSLCertVerificationError" | tail -20
```
`No API key configured - authentication disabled` on every request is the tell.
**Fix:** since v0.266.4 the worker exits on its own (boot check + post-failure credential probe) and systemd re-runs the bootstrap. If that isn't happening, restart it by hand. Network is up by then, so the real `startup.sh` runs:
```bash
gcloud compute ssh encoding-worker-b --zone=us-central1-c --project=nomadkaraoke \
--command='sudo systemctl restart encoding-worker'
```
(Stale host key error → `ssh-keygen -R compute.<instance_id> -f ~/.ssh/google_compute_known_hosts`.) Parked jobs pick up on the next scheduler tick, or force it with `retry-pending-render-jobs` (see `render_pending_capacity` below).
---
## Render fails "Cannot connect to host <worker-ip>:8080" and the VM never answers `/health`
**Symptoms:** a render that cold-started the primary VM retries 8 times (~90s) and fails with `ClientConnectorError ... Connect call failed`. The backend keeps logging `encoding-worker-b /health unconfirmed; keeping alive (fail-safe)` until the VM idle-stops.
**Cause (2026-10-09 `f4310aea`, 2026-10-12 `82f48738`):** `startup.sh`'s first gcloud call ran before DHCP, so gcloud cached "not on GCE" (`/root/.config/gcloud/gce` = `False`). Every later gcloud call in that boot had no credentials: no API key, the self-heal refuses to serve, systemd re-runs `startup.sh`, and it hits the same cache forever.
**Diagnose:** the serial log shows repeated `WARNING: No API key found in Secret Manager`, and on the VM `sudo cat /root/.config/gcloud/gce` prints `False`.
**Fix:** since v0.268.3 `startup.sh` deletes that cache, waits for the metadata server and retries the secret fetch, so the next restart recovers by itself. By hand: `sudo rm -f /root/.config/gcloud/gce && sudo systemctl restart encoding-worker`.
---
## 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`).
@@ -40,9 +40,6 @@ jest.mock('@/lib/api', () => ({
sendCompletionEmail: jest.fn(),
rerenderJob: jest.fn(() => Promise.resolve({ status: 'processing' })),
},
tenantThemeApi: {
outdatedJobs: jest.fn(() => Promise.resolve({ theme_updated_at: null, job_ids: [] })),
},
}))
describe('OutputLinks', () => {
@@ -447,57 +444,6 @@ describe('OutputLinks', () => {
})
})
describe('theme changed since a portal track was made', () => {
const tenantJob: Job = { ...baseJob, state_data: {} }
beforeEach(() => {
require('@/lib/tenant-theme-outdated').resetOutdatedThemeJobs()
const { useTenant } = require('@/lib/tenant')
useTenant.mockReturnValue({ tenantId: 'randy-vild', features: { youtube_upload: false, dropbox_upload: false } })
})
it('admins see one Re-render on portal tracks, not the theme one plus the admin one', () => {
const { useAuth } = require('@/lib/auth')
useAuth.mockReturnValue({ user: { role: 'admin' } })
render(<OutputLinks job={tenantJob} />)
expect(screen.getAllByRole('button', { name: /Re-render/ })).toHaveLength(1)
expect(screen.getByTestId('rerender-button')).toBeInTheDocument()
expect(screen.queryByTestId('admin-rerender-button')).not.toBeInTheDocument()
})
it('flags outdated tracks and clears the flag once a re-render starts', async () => {
const { tenantThemeApi, api } = require('@/lib/api')
tenantThemeApi.outdatedJobs.mockResolvedValueOnce({ theme_updated_at: '2026-10-06T14:35:00Z', job_ids: ['test-123'] })
render(<OutputLinks job={tenantJob} />)
expect(await screen.findByTestId('outdated-theme-badge')).toHaveTextContent('Older theme')
expect(screen.getByTestId('rerender-button')).toHaveAttribute(
'title', 'This video was made before your latest theme change. Re-render it to update its look.')
fireEvent.click(screen.getByTestId('rerender-button'))
const buttons = screen.getAllByRole('button', { name: 'Re-render' })
fireEvent.click(buttons[buttons.length - 1])
await waitFor(() => expect(api.rerenderWithCurrentTheme).toHaveBeenCalledWith('test-123'))
await waitFor(() => expect(screen.queryByTestId('outdated-theme-badge')).not.toBeInTheDocument())
})
it('fetches the outdated list once for all cards', async () => {
const { tenantThemeApi } = require('@/lib/api')
tenantThemeApi.outdatedJobs.mockClear()
render(<><OutputLinks job={tenantJob} /><OutputLinks job={{ ...tenantJob, job_id: 'other' }} /></>)
await waitFor(() => expect(tenantThemeApi.outdatedJobs).toHaveBeenCalledTimes(1))
})
it('does not fetch outside tenant portals', () => {
const { useTenant } = require('@/lib/tenant')
useTenant.mockReturnValue({ tenantId: null, features: { youtube_upload: true, dropbox_upload: true } })
const { tenantThemeApi } = require('@/lib/api')
tenantThemeApi.outdatedJobs.mockClear()
render(<OutputLinks job={tenantJob} />)
expect(tenantThemeApi.outdatedJobs).not.toHaveBeenCalled()
})
})
describe('admin re-render (any completed job)', () => {
const asAdmin = (isAdmin: boolean) => {
const { useAuth } = require('@/lib/auth')
+4 -17
View File
@@ -4,7 +4,6 @@ import { useRef, useCallback, useEffect, useState } from "react"
import { useTranslations } from 'next-intl'
import { api, adminApi, Job } from "@/lib/api"
import { useTenant } from "@/lib/tenant"
import { clearOutdatedThemeJobs, useOutdatedThemeJobs } from "@/lib/tenant-theme-outdated"
import { Button } from "@/components/ui/button"
import { Download, Loader2, ExternalLink, FolderOpen, Copy, Mail, Settings, Lock, Globe, Pencil, RefreshCw, RotateCcw, Sparkles } from "lucide-react"
import { canRegenerate as canRegenerateJob } from "@/lib/job-status"
@@ -205,7 +204,6 @@ export function OutputLinks({ job, onJobUpdated }: OutputLinksProps) {
setShowRerenderDialog(false)
try {
await api.rerenderWithCurrentTheme(job.job_id)
clearOutdatedThemeJobs([job.job_id])
onJobUpdated?.()
} catch (err) {
console.error("Failed to start re-render:", err)
@@ -282,16 +280,11 @@ export function OutputLinks({ job, onJobUpdated }: OutputLinksProps) {
// portal only; the backend enforces the rest (ownership, allowlist, not
// published to YouTube/Drive — a tenant Dropbox archive is refreshed in place).
const canRerender = !!tenantId && job.status === "complete" && !!hasDownloads && !showYoutubeLink
// Made before the latest theme save: nudge towards Re-render.
const outdatedThemeJobs = useOutdatedThemeJobs(!!tenantId)
const themeOutdated = canRerender && outdatedThemeJobs.has(job.job_id)
// Admin re-render of ANY completed job with the current renderer (existing
// style, no review). The backend enforces the rest (reviewed lyrics +
// instrumental selection present, not mid visibility change). Hidden where
// the portal's own Re-render is offered, so tenant cards don't show two
// identical "Re-render" buttons.
const canAdminRerender = isAdmin && !canRerender && job.status === "complete" && !outputsDeleted && !visibilityChangeInProgress
// instrumental selection present, not mid visibility change).
const canAdminRerender = isAdmin && job.status === "complete" && !outputsDeleted && !visibilityChangeInProgress
const brandCode = job.state_data?.brand_code || null
return (
@@ -464,17 +457,11 @@ export function OutputLinks({ job, onJobUpdated }: OutputLinksProps) {
type="button"
onClick={(e) => { e.stopPropagation(); setShowRerenderDialog(true) }}
disabled={isStartingRerender}
data-testid="rerender-button"
className={`inline-flex items-center gap-1 text-xs px-3 py-1.5 rounded bg-[#252525] hover:bg-[#333333] text-[var(--text)] border transition-colors disabled:opacity-50 ${themeOutdated ? "border-amber-500/70" : "border-[var(--card-border)]"}`}
title={themeOutdated ? t('outdatedThemeTooltip') : t('rerenderTooltip')}
className="inline-flex items-center gap-1 text-xs px-3 py-1.5 rounded bg-[#252525] hover:bg-[#333333] text-[var(--text)] border border-[var(--card-border)] transition-colors disabled:opacity-50"
title={t('rerenderTooltip')}
>
{isStartingRerender ? <Loader2 className="w-3 h-3 animate-spin" /> : <RefreshCw className="w-3 h-3" />}
{t('rerender')}
{themeOutdated && (
<span className="ml-1 rounded bg-amber-500/20 px-1.5 text-[10px] text-amber-400" data-testid="outdated-theme-badge">
{t('outdatedTheme')}
</span>
)}
</button>
)}
@@ -2,7 +2,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react"
import { useTranslations } from "next-intl"
import { AlertTriangle, CheckCircle2, ImageIcon, Loader2, Palette, RefreshCw, Upload } from "lucide-react"
import { AlertTriangle, ImageIcon, Loader2, Palette, Upload } from "lucide-react"
import {
Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle,
} from "@/components/ui/dialog"
@@ -12,17 +12,12 @@ import { Label } from "@/components/ui/label"
import { useToast } from "@/hooks/use-toast"
import { tenantThemeApi, type ThemePreviewImages, type ThemeStyleParams } from "@/lib/api"
import { useTenant } from "@/lib/tenant"
import { clearOutdatedThemeJobs, setOutdatedThemeJobs } from "@/lib/tenant-theme-outdated"
import {
KARAOKE_DEFAULTS, copyTitleCardLayoutToEnd, formatRegion, getField, hexToRgba, parseRegion, rgbaToHex, setField, stableStringify,
KARAOKE_DEFAULTS, formatRegion, getField, hexToRgba, parseRegion, rgbaToHex, setField, stableStringify,
type Region,
} from "./theme-utils"
const PREVIEW_DEBOUNCE_MS = 700
// End-screen text positions used when a theme has none (matches the stock end screen).
const END_EXTRA_FALLBACK: Region = { x: 370, y: 400, w: 3100, h: 400 }
const END_TITLE_FALLBACK: Region = { x: 370, y: 900, w: 3100, h: 350 }
const END_ARTIST_FALLBACK: Region = { x: 370, y: 1450, w: 3100, h: 200 }
const selectClass =
"h-9 w-full rounded-md border border-input bg-transparent px-2 text-sm focus:outline-none focus:ring-1 focus:ring-ring"
@@ -101,10 +96,6 @@ export function TenantThemeEditorDialog({ open, onClose }: Props) {
const [previewError, setPreviewError] = useState<string | null>(null)
const [uploading, setUploading] = useState<string | null>(null)
const [saving, setSaving] = useState(false)
// What the last save did to existing tracks (shown until the next save).
const [saveResult, setSaveResult] = useState<{ refreshed: number; outdated: string[] } | null>(null)
const [rerenderingAll, setRerenderingAll] = useState(false)
const [rerenderStarted, setRerenderStarted] = useState<number | null>(null)
const abortRef = useRef<AbortController | null>(null)
// Load the current theme each time the dialog opens.
@@ -229,10 +220,7 @@ export function TenantThemeEditorDialog({ open, onClose }: Props) {
)
setImages(data.images)
setFonts(data.fonts)
setSaveResult({ refreshed: data.refreshed_jobs ?? 0, outdated: data.outdated_job_ids ?? [] })
setRerenderStarted(null)
setOutdatedThemeJobs(data.outdated_job_ids ?? [])
toast({ title: t("savedTitle"), description: t("savedBodyInProgress") })
toast({ title: t("savedTitle"), description: t("savedBody") })
} catch (err: any) {
toast({ title: t("saveFailed"), description: err?.message, variant: "destructive" })
} finally {
@@ -240,28 +228,6 @@ export function TenantThemeEditorDialog({ open, onClose }: Props) {
}
}
const handleRerenderAll = async () => {
setRerenderingAll(true)
try {
const result = await tenantThemeApi.rerenderOutdated()
clearOutdatedThemeJobs(result.started)
setRerenderStarted((n) => (n ?? 0) + result.started.length)
// Still outdated: failures, plus any beyond the server's per-call cap.
setSaveResult((r) => r && { ...r, outdated: [...Object.keys(result.failed), ...(result.remaining ?? [])] })
if (Object.keys(result.failed).length) {
toast({
title: t("rerenderAllSomeFailed", { count: Object.keys(result.failed).length }),
description: Object.values(result.failed)[0],
variant: "destructive",
})
}
} catch (err: any) {
toast({ title: t("rerenderAllFailed"), description: err?.message, variant: "destructive" })
} finally {
setRerenderingAll(false)
}
}
const handleClose = () => {
if (dirty && !window.confirm(t("discardConfirm"))) return
abortRef.current?.abort()
@@ -324,36 +290,6 @@ export function TenantThemeEditorDialog({ open, onClose }: Props) {
)
}
// A text item on the end screen is hidden when its region is null.
const regionToggle = (field: "title_region" | "artist_region", label: string, fallback: Region) => (
<label className="flex items-center gap-2 text-sm">
<input
type="checkbox"
checked={!!getField(draft!, "end", field)}
onChange={(e) => update("end", field, e.target.checked ? formatRegion(parseRegion(getField(draft!, "intro", field), fallback)) : null)}
/>
{label}
</label>
)
// Absent = included (older themes have no "enabled" key).
const screenToggle = (section: "intro" | "end", label: string) => (
<label className="flex items-center gap-2 rounded-md border p-3 text-sm font-medium">
<input
type="checkbox"
data-testid={`${section}-enabled`}
checked={getField(draft!, section, "enabled") !== false}
onChange={(e) => update(section, "enabled", e.target.checked)}
/>
{label}
</label>
)
// The end screen's song title / artist name take the title card's look.
const copyTitleCardLayout = () => {
setDraft((d) => (d ? copyTitleCardLayoutToEnd(d, END_EXTRA_FALLBACK) : d))
}
const upperToggle = (section: "intro" | "end", field: string, label: string) => (
<label className="flex items-center gap-2 text-sm">
<input
@@ -411,15 +347,6 @@ export function TenantThemeEditorDialog({ open, onClose }: Props) {
const tabs: Tab[] = ["titleCard", "karaoke", "endScreen", "advanced"]
// The screen being edited, then the lyrics frame (Advanced shows all three).
type PreviewKind = "title_card" | "karaoke_frame" | "end_screen"
const previewKinds: PreviewKind[] =
tab === "endScreen" ? ["end_screen", "karaoke_frame"]
: tab === "advanced" ? ["title_card", "karaoke_frame", "end_screen"]
: ["title_card", "karaoke_frame"]
const previewLabel = (kind: PreviewKind) =>
kind === "title_card" ? t("previewTitleCard") : kind === "end_screen" ? t("previewEndScreen") : t("previewKaraoke")
return (
<Dialog open={open} onOpenChange={(o) => { if (!o) handleClose() }}>
<DialogContent className="max-w-6xl max-h-[92vh] overflow-y-auto" data-testid="tenant-theme-editor">
@@ -455,27 +382,20 @@ export function TenantThemeEditorDialog({ open, onClose }: Props) {
{tab === "titleCard" && (
<div className="space-y-4">
{screenToggle("intro", t("includeTitleCard"))}
{getField(draft!, "intro", "enabled") === false ? (
<p className="text-sm text-muted-foreground">{t("titleCardOff")}</p>
) : (
<>
{bgField("intro")}
<div className="grid grid-cols-2 gap-3">
<ColorInput id="intro-title-colour" label={t("titleColour")} value={getField<string>(draft!, "intro", "title_color") || "#ffffff"}
onChange={(v) => update("intro", "title_color", v)} />
<ColorInput id="intro-artist-colour" label={t("artistColour")} value={getField<string>(draft!, "intro", "artist_color") || "#ffdf6b"}
onChange={(v) => update("intro", "artist_color", v)} />
</div>
{regionSliders("intro", "title_region", t("songTitle"), { x: 370, y: 980, w: 3100, h: 350 })}
{regionSliders("intro", "artist_region", t("artistName"), { x: 370, y: 1400, w: 3100, h: 450 })}
<div className="flex flex-wrap gap-4">
{upperToggle("intro", "title_text_transform", t("uppercaseTitle"))}
{upperToggle("intro", "artist_text_transform", t("uppercaseArtist"))}
</div>
{fontField()}
</>
)}
{bgField("intro")}
<div className="grid grid-cols-2 gap-3">
<ColorInput id="intro-title-colour" label={t("titleColour")} value={getField<string>(draft!, "intro", "title_color") || "#ffffff"}
onChange={(v) => update("intro", "title_color", v)} />
<ColorInput id="intro-artist-colour" label={t("artistColour")} value={getField<string>(draft!, "intro", "artist_color") || "#ffdf6b"}
onChange={(v) => update("intro", "artist_color", v)} />
</div>
{regionSliders("intro", "title_region", t("songTitle"), { x: 370, y: 980, w: 3100, h: 350 })}
{regionSliders("intro", "artist_region", t("artistName"), { x: 370, y: 1400, w: 3100, h: 450 })}
<div className="flex flex-wrap gap-4">
{upperToggle("intro", "title_text_transform", t("uppercaseTitle"))}
{upperToggle("intro", "artist_text_transform", t("uppercaseArtist"))}
</div>
{fontField()}
</div>
)}
@@ -502,55 +422,19 @@ export function TenantThemeEditorDialog({ open, onClose }: Props) {
{tab === "endScreen" && (
<div className="space-y-4">
{screenToggle("end", t("includeEndScreen"))}
{getField(draft!, "end", "enabled") === false ? (
<p className="text-sm text-muted-foreground">{t("endScreenOff")}</p>
) : (
<>
{bgField("end")}
<div className="space-y-1">
<Label htmlFor="end-extra-text">{t("closingMessage")}</Label>
<Input id="end-extra-text" value={getField<string>(draft!, "end", "extra_text") || ""}
onChange={(e) => {
update("end", "extra_text", e.target.value || null)
// The renderer skips text without a region — give a new message one.
if (e.target.value && !getField(draft!, "end", "extra_text_region")) {
update("end", "extra_text_region", formatRegion(END_EXTRA_FALLBACK))
}
}} />
</div>
{!!getField(draft!, "end", "extra_text") && (
<>
<ColorInput id="end-extra-colour" label={t("closingMessageColour")} value={getField<string>(draft!, "end", "extra_text_color") || "#ffffff"}
onChange={(v) => update("end", "extra_text_color", v)} />
{regionSliders("end", "extra_text_region", t("closingMessage"), END_EXTRA_FALLBACK)}
</>
)}
<div className="flex flex-wrap items-center justify-between gap-2 rounded-md border p-3">
<p className="text-xs text-muted-foreground">{t("copyTitleCardLayoutHint")}</p>
<Button size="sm" variant="secondary" onClick={copyTitleCardLayout} data-testid="end-copy-title-layout">
{t("copyTitleCardLayout")}
</Button>
</div>
<div className="grid grid-cols-2 gap-3">
<ColorInput id="end-title-colour" label={t("titleColour")} value={getField<string>(draft!, "end", "title_color") || "#ffffff"}
onChange={(v) => update("end", "title_color", v)} />
<ColorInput id="end-artist-colour" label={t("artistColour")} value={getField<string>(draft!, "end", "artist_color") || "#ffdf6b"}
onChange={(v) => update("end", "artist_color", v)} />
</div>
{regionToggle("title_region", t("showSongTitle"), END_TITLE_FALLBACK)}
{!!getField(draft!, "end", "title_region") &&
regionSliders("end", "title_region", t("songTitle"), END_TITLE_FALLBACK)}
{regionToggle("artist_region", t("showArtistName"), END_ARTIST_FALLBACK)}
{!!getField(draft!, "end", "artist_region") &&
regionSliders("end", "artist_region", t("artistName"), END_ARTIST_FALLBACK)}
<div className="flex flex-wrap gap-4">
{upperToggle("end", "title_text_transform", t("uppercaseTitle"))}
{upperToggle("end", "artist_text_transform", t("uppercaseArtist"))}
</div>
<p className="text-xs text-muted-foreground">{t("endScreenFontHint")}</p>
</>
)}
{bgField("end")}
<div className="space-y-1">
<Label htmlFor="end-extra-text">{t("closingMessage")}</Label>
<Input id="end-extra-text" value={getField<string>(draft!, "end", "extra_text") || ""}
onChange={(e) => update("end", "extra_text", e.target.value || null)} />
</div>
<div className="grid grid-cols-2 gap-3">
<ColorInput id="end-extra-colour" label={t("closingMessageColour")} value={getField<string>(draft!, "end", "extra_text_color") || "#ffffff"}
onChange={(v) => update("end", "extra_text_color", v)} />
<ColorInput id="end-title-colour" label={t("titleColour")} value={getField<string>(draft!, "end", "title_color") || "#ffffff"}
onChange={(v) => update("end", "title_color", v)} />
</div>
<p className="text-xs text-muted-foreground">{t("endScreenHint")}</p>
</div>
)}
@@ -582,18 +466,16 @@ export function TenantThemeEditorDialog({ open, onClose }: Props) {
<Input id="sample-title" value={sampleTitle} onChange={(e) => setSampleTitle(e.target.value)} />
</div>
</div>
{previewKinds.map((kind) => (
{(["title_card", "karaoke_frame"] as const).map((kind) => (
<figure key={kind} className="space-y-1">
<figcaption className="text-xs font-medium text-muted-foreground">{previewLabel(kind)}</figcaption>
<figcaption className="text-xs font-medium text-muted-foreground">
{kind === "title_card" ? t("previewTitleCard") : t("previewKaraoke")}
</figcaption>
<div className="relative aspect-video overflow-hidden rounded-md border bg-black">
{preview?.[kind] ? (
{preview?.[kind] && (
// eslint-disable-next-line @next/next/no-img-element
<img src={preview[kind]!} alt={previewLabel(kind)}
<img src={preview[kind]} alt={kind === "title_card" ? t("previewTitleCard") : t("previewKaraoke")}
data-testid={`preview-${kind}`} className="h-full w-full object-contain" />
) : preview && kind !== "karaoke_frame" && !previewing && (
<div className="flex h-full items-center justify-center text-sm text-muted-foreground" data-testid={`preview-${kind}-omitted`}>
{t("screenOmitted")}
</div>
)}
{previewing && (
<div className="absolute inset-0 flex items-center justify-center bg-black/40">
@@ -613,38 +495,8 @@ export function TenantThemeEditorDialog({ open, onClose }: Props) {
</div>
)}
{saveResult && (saveResult.refreshed > 0 || saveResult.outdated.length > 0 || rerenderStarted !== null) && (
<div className="rounded-md border border-border bg-muted/40 p-3 text-sm space-y-2" data-testid="theme-save-result">
{saveResult.refreshed > 0 && (
<p className="flex items-start gap-2">
<CheckCircle2 className="h-4 w-4 mt-0.5 shrink-0 text-green-500" />
{t("refreshedInProgress", { count: saveResult.refreshed })}
</p>
)}
{rerenderStarted !== null && rerenderStarted > 0 && (
<p className="flex items-start gap-2" data-testid="theme-rerender-started">
<RefreshCw className="h-4 w-4 mt-0.5 shrink-0 text-primary" />
{t("rerenderAllStarted", { count: rerenderStarted })}
</p>
)}
{saveResult.outdated.length > 0 && (
<div className="flex flex-wrap items-center justify-between gap-2">
<p className="flex items-start gap-2">
<AlertTriangle className="h-4 w-4 mt-0.5 shrink-0 text-amber-500" />
{t("outdatedFinished", { count: saveResult.outdated.length })}
</p>
<Button size="sm" onClick={handleRerenderAll} disabled={rerenderingAll} data-testid="theme-rerender-all">
{rerenderingAll
? <><Loader2 className="h-4 w-4 mr-2 animate-spin" /> {t("rerenderAllStarting")}</>
: t("rerenderAll", { count: saveResult.outdated.length })}
</Button>
</div>
)}
</div>
)}
<DialogFooter className="flex items-center gap-2 sm:justify-between">
<p className="text-xs text-muted-foreground">{t("appliesToInProgress")} {t("finishedKeepOldLook")}</p>
<p className="text-xs text-muted-foreground">{t("appliesToNewJobs")} {t("rerenderHint")}</p>
<div className="flex gap-2">
<Button variant="ghost" onClick={() => { if (saved) { setDraft(saved); setJsonText(JSON.stringify(saved, null, 2)); setJsonError(null) } }}
disabled={!dirty || saving}>
@@ -12,7 +12,6 @@ const get = jest.fn()
const preview = jest.fn()
const save = jest.fn()
const uploadAsset = jest.fn()
const rerenderOutdated = jest.fn()
const toast = jest.fn()
jest.mock("@/lib/api", () => ({
@@ -21,8 +20,6 @@ jest.mock("@/lib/api", () => ({
preview: (...a: unknown[]) => preview(...a),
save: (...a: unknown[]) => save(...a),
uploadAsset: (...a: unknown[]) => uploadAsset(...a),
rerenderOutdated: (...a: unknown[]) => rerenderOutdated(...a),
outdatedJobs: async () => ({ theme_updated_at: null, job_ids: [] }),
},
}))
jest.mock("@/hooks/use-toast", () => ({ useToast: () => ({ toast }) }))
@@ -177,160 +174,3 @@ it("treats invalid Advanced JSON as unsaved work when closing", async () => {
expect(onClose).not.toHaveBeenCalled()
confirm.mockRestore()
})
describe("after saving: what happens to existing tracks", () => {
async function editAndSave() {
await openEditor()
fireEvent.click(screen.getByRole("tab", { name: "tabs.endScreen" }))
fireEvent.change(screen.getByLabelText("closingMessage"), { target: { value: "BYE" } })
await act(async () => { fireEvent.click(screen.getByRole("button", { name: "save" })) })
}
it("says in-progress tracks were updated and offers to re-render outdated finished ones", async () => {
save.mockImplementation(async (sp) => ({ ...DATA, style_params: sp, refreshed_jobs: 3, outdated_job_ids: ["a", "b"] }))
rerenderOutdated.mockResolvedValue({ started: ["a", "b"], failed: {} })
await editAndSave()
expect(screen.getByText("refreshedInProgress(3)")).toBeInTheDocument()
expect(screen.getByText("outdatedFinished(2)")).toBeInTheDocument()
await act(async () => { fireEvent.click(screen.getByTestId("theme-rerender-all")) })
expect(rerenderOutdated).toHaveBeenCalledTimes(1)
expect(screen.getByTestId("theme-rerender-started")).toHaveTextContent("rerenderAllStarted(2)")
expect(screen.queryByTestId("theme-rerender-all")).not.toBeInTheDocument()
})
it("keeps the offer for tracks that couldn't be re-rendered", async () => {
save.mockImplementation(async (sp) => ({ ...DATA, style_params: sp, refreshed_jobs: 0, outdated_job_ids: ["a", "b"] }))
rerenderOutdated.mockResolvedValue({ started: ["a"], failed: { b: "published" } })
await editAndSave()
await act(async () => { fireEvent.click(screen.getByTestId("theme-rerender-all")) })
expect(toast).toHaveBeenCalledWith(expect.objectContaining({ title: "rerenderAllSomeFailed(1)", variant: "destructive" }))
expect(screen.getByText("outdatedFinished(1)")).toBeInTheDocument()
expect(screen.queryByText("refreshedInProgress(0)")).not.toBeInTheDocument()
})
it("shows nothing extra when no existing track was affected", async () => {
save.mockImplementation(async (sp) => ({ ...DATA, style_params: sp, refreshed_jobs: 0, outdated_job_ids: [] }))
await editAndSave()
expect(screen.queryByTestId("theme-save-result")).not.toBeInTheDocument()
})
})
it("offers the tracks beyond the server's per-call cap again", async () => {
save.mockImplementation(async (sp) => ({ ...DATA, style_params: sp, refreshed_jobs: 0, outdated_job_ids: ["a", "b", "c"] }))
rerenderOutdated
.mockResolvedValueOnce({ started: ["a"], failed: {}, remaining: ["b", "c"] })
.mockResolvedValueOnce({ started: ["b", "c"], failed: {}, remaining: [] })
await openEditor()
fireEvent.click(screen.getByRole("tab", { name: "tabs.endScreen" }))
fireEvent.change(screen.getByLabelText("closingMessage"), { target: { value: "BYE" } })
await act(async () => { fireEvent.click(screen.getByRole("button", { name: "save" })) })
await act(async () => { fireEvent.click(screen.getByTestId("theme-rerender-all")) })
expect(screen.getByText("outdatedFinished(2)")).toBeInTheDocument()
await act(async () => { fireEvent.click(screen.getByTestId("theme-rerender-all")) })
expect(screen.getByTestId("theme-rerender-started")).toHaveTextContent("rerenderAllStarted(3)")
expect(screen.queryByTestId("theme-rerender-all")).not.toBeInTheDocument()
})
describe("end screen", () => {
const END_IMAGES = { ...IMAGES, end_screen: "data:image/jpeg;base64,CCC" }
async function openEndTab() {
preview.mockResolvedValue(END_IMAGES)
await openEditor()
fireEvent.click(screen.getByRole("tab", { name: "tabs.endScreen" }))
await flushPreview()
}
function advancedJson() {
fireEvent.click(screen.getByRole("tab", { name: "tabs.advanced" }))
return JSON.parse((screen.getByLabelText("advancedJson") as HTMLTextAreaElement).value)
}
it("previews the end screen (instead of the title card) on its tab", async () => {
await openEndTab()
expect(await screen.findByTestId("preview-end_screen")).toHaveAttribute("src", END_IMAGES.end_screen)
expect(screen.queryByTestId("preview-title_card")).toBeNull()
expect(screen.getByTestId("preview-karaoke_frame")).toBeInTheDocument()
})
it("copies the title card's layout onto the end screen (smaller text like the title card)", async () => {
await openEndTab()
fireEvent.click(screen.getByTestId("end-copy-title-layout"))
const json = advancedJson()
expect(json.end).toMatchObject({
title_region: THEME.intro.title_region,
artist_region: THEME.intro.artist_region,
title_color: "#ffffff",
artist_color: "#ffdf6b",
title_text_transform: null,
artist_text_transform: null,
})
expect(json.end.extra_text).toBe("THANK YOU FOR SINGING!") // message text untouched
expect(json.end.extra_text_region).toBe("370,570,3100,350") // moved just above the song title
})
it("end-screen sliders edit the end section, not the title card", async () => {
await openEndTab()
fireEvent.click(screen.getByLabelText("showSongTitle"))
fireEvent.change(screen.getByLabelText("textSize(songTitle)"), { target: { value: "200" } })
fireEvent.change(screen.getByLabelText("textSize(closingMessage)"), { target: { value: "250" } })
const json = advancedJson()
expect(json.end.title_region).toBe("370,980,3100,200") // turned on from the title card's position
expect(json.end.extra_text_region).toBe("370,400,3100,250")
expect(json.intro.title_region).toBe(THEME.intro.title_region)
})
it("hiding the song title clears its end-screen region", async () => {
preview.mockResolvedValue(END_IMAGES)
get.mockResolvedValue({ ...DATA, style_params: { ...THEME, end: { ...THEME.end, title_region: "370,900,3100,350" } } })
await openEditor()
fireEvent.click(screen.getByRole("tab", { name: "tabs.endScreen" }))
expect(screen.getByLabelText("textSize(songTitle)")).toBeInTheDocument()
fireEvent.click(screen.getByLabelText("showSongTitle"))
expect(screen.queryByLabelText("textSize(songTitle)")).toBeNull()
expect(advancedJson().end.title_region).toBeNull()
})
it("a new closing message gets a region so it actually renders", async () => {
get.mockResolvedValue({ ...DATA, style_params: { ...THEME, end: { extra_text: null } } })
await openEndTab()
fireEvent.change(screen.getByLabelText("closingMessage"), { target: { value: "BYE" } })
expect(advancedJson().end).toMatchObject({ extra_text: "BYE", extra_text_region: "370,400,3100,400" })
})
})
describe("leaving out the title card / end screen", () => {
it("unticking the end screen saves enabled=false and shows it as not included", async () => {
await openEditor()
fireEvent.click(screen.getByRole("tab", { name: "tabs.endScreen" }))
preview.mockResolvedValue({ ...IMAGES, end_screen: null })
fireEvent.click(screen.getByTestId("end-enabled"))
expect(screen.getByText("endScreenOff")).toBeInTheDocument()
expect(screen.queryByLabelText("closingMessage")).toBeNull()
await flushPreview()
await waitFor(() => expect(preview.mock.calls.at(-1)[0].end.enabled).toBe(false))
expect(await screen.findByTestId("preview-end_screen-omitted")).toHaveTextContent("screenOmitted")
await act(async () => { fireEvent.click(screen.getByRole("button", { name: "save" })) })
expect(save.mock.calls[0][0].end.enabled).toBe(false)
})
it("unticking the title card hides its settings; ticking it again restores them", async () => {
await openEditor()
fireEvent.click(screen.getByTestId("intro-enabled"))
expect(screen.getByText("titleCardOff")).toBeInTheDocument()
expect(screen.queryByLabelText("positionFromTop(songTitle)")).toBeNull()
fireEvent.click(screen.getByTestId("intro-enabled"))
expect(screen.getByLabelText("positionFromTop(songTitle)")).toBeInTheDocument()
})
it("treats a theme without an enabled key as including both screens", async () => {
await openEditor()
expect(screen.getByTestId("intro-enabled")).toBeChecked()
fireEvent.click(screen.getByRole("tab", { name: "tabs.endScreen" }))
expect(screen.getByTestId("end-enabled")).toBeChecked()
})
})
@@ -1,4 +1,4 @@
import { copyTitleCardLayoutToEnd, formatRegion, getField, hexToRgba, parseRegion, rgbaToHex, setField, stableStringify } from "../theme-utils"
import { formatRegion, getField, hexToRgba, parseRegion, rgbaToHex, setField, stableStringify } from "../theme-utils"
describe("theme-utils", () => {
it("converts between hex and karaoke 'r, g, b, a' keeping alpha", () => {
@@ -25,42 +25,3 @@ describe("theme-utils", () => {
expect(stableStringify({ b: 1, a: [1, { d: 2, c: 3 }] })).toBe(stableStringify({ a: [1, { c: 3, d: 2 }], b: 1 }))
})
})
describe("copyTitleCardLayoutToEnd", () => {
const FALLBACK = { x: 370, y: 400, w: 3100, h: 400 }
// Randy Vild's theme: small title card text, stock (large) end screen.
const randy = {
intro: {
title_color: "#ffffff", artist_color: "#5093ce", title_text_transform: "uppercase", artist_text_transform: null,
title_region: "370,620,3100,200", artist_region: "370,880,3100,200",
},
end: {
title_color: "#ffffff", artist_color: "#ffdf6b", title_text_transform: "uppercase", artist_text_transform: "uppercase",
title_region: "370,900,3100,350", artist_region: "370,1450,3100,200",
extra_text: "THANK YOU FOR SINGING!", extra_text_region: "370,400,3100,400", extra_text_color: "#ff7acc",
},
}
it("matches the title card and puts the closing message just above the title at the same size", () => {
const end = copyTitleCardLayoutToEnd(randy, FALLBACK).end
expect(end).toMatchObject({
title_region: "370,620,3100,200", artist_region: "370,880,3100,200",
artist_color: "#5093ce", artist_text_transform: null, title_text_transform: "uppercase",
extra_text_region: "370,360,3100,200", extra_text: "THANK YOU FOR SINGING!", extra_text_color: "#ff7acc",
})
})
it("puts the closing message below the artist when there's no room above the title", () => {
const top = { ...randy, intro: { ...randy.intro, title_region: "370,100,3100,200", artist_region: "370,350,3100,200" } }
expect(copyTitleCardLayoutToEnd(top, FALLBACK).end.extra_text_region).toBe("370,610,3100,200")
})
it("leaves the closing message alone when there is none or the title is hidden", () => {
const noMessage = { ...randy, end: { ...randy.end, extra_text: null } }
expect(copyTitleCardLayoutToEnd(noMessage, FALLBACK).end.extra_text_region).toBe("370,400,3100,400")
const noTitle = { ...randy, intro: { ...randy.intro, title_region: undefined } }
const end = copyTitleCardLayoutToEnd(noTitle, FALLBACK).end
expect(end.title_region).toBeNull()
expect(end.extra_text_region).toBe("370,400,3100,400")
})
})
@@ -73,32 +73,3 @@ export function stableStringify(value: unknown): string {
}
return JSON.stringify(value)
}
/** Fields "Copy title card layout" takes from the title card for the end screen. */
const TITLE_CARD_LAYOUT_FIELDS = [
"title_color", "artist_color", "title_region", "artist_region", "title_text_transform", "artist_text_transform",
] as const
const END_TEXT_GAP = 60
/**
* Give the end screen's song title / artist name the title card's look, and move the
* closing message (at the same text size, at most) so it doesn't overlap them:
* just above the song title, or below the artist name if there's no room above.
*/
export function copyTitleCardLayoutToEnd(styles: ThemeStyleParams, extraFallback: Region): ThemeStyleParams {
let next = styles
for (const field of TITLE_CARD_LAYOUT_FIELDS) {
next = setField(next, "end", field, getField(styles, "intro", field) ?? null)
}
const titleRaw = getField(next, "end", "title_region")
if (!getField(next, "end", "extra_text") || typeof titleRaw !== "string") return next
const none: Region = { x: 0, y: 0, w: 0, h: 0 }
const title = parseRegion(titleRaw, none)
const artist = parseRegion(getField(next, "end", "artist_region"), none)
const extra = parseRegion(getField(next, "end", "extra_text_region"), extraFallback)
const h = Math.min(extra.h, title.h || extra.h)
let y = title.y - h - END_TEXT_GAP
if (y < 0) y = Math.max(title.y + title.h, artist.y + artist.h) + END_TEXT_GAP
return setField(next, "end", "extra_text_region", formatRegion({ ...extra, y, h }))
}
@@ -152,7 +152,6 @@ export async function pollVerify(step: CheckoutStep, ctx: StepContext, timeoutMs
const deadline = Date.now() + timeoutMs;
do {
if (await step.verify(ctx).catch(() => false)) return true;
if (step.abortReason?.()) return false;
await ctx.page.waitForTimeout(500);
} while (Date.now() < deadline);
return false;
@@ -166,8 +165,6 @@ export async function healStep(step: CheckoutStep, ctx: StepContext, planner: Pl
let model = '';
for (let i = 0; i < MAX_ITERATIONS; i++) {
const aborted = step.abortReason?.();
if (aborted) return { success: false, actions: executed, model, llmCalls, reason: aborted };
const observation = await observe(ctx.page, ctx.secrets);
let decision: LlmDecision;
try {
@@ -52,10 +52,6 @@ export class SelfHealingRunner {
const forced = this.forceLlm.has(step.id);
if (forced) console.log(` ⚙️ step ${step.id}: E2E_SELF_HEAL_FORCE_LLM — skipping deterministic variants`);
const aborted = (): StepOutcome | null => {
const reason = step.abortReason?.();
return reason ? { stepId: step.id, status: 'failed', reason, llmCalls: 0 } : null;
};
if (!forced) {
for (const v of this.learned.steps[step.id] || []) {
@@ -70,8 +66,6 @@ export class SelfHealingRunner {
} catch (e) {
console.log(` learned variant ${v.id} failed: ${(e as Error).message.split('\n')[0]}`);
}
const stop = aborted();
if (stop) return stop;
}
for (const b of step.builtins) {
try {
@@ -82,8 +76,6 @@ export class SelfHealingRunner {
} catch (e) {
console.log(` builtin "${b.name}" failed: ${(e as Error).message.split('\n')[0]}`);
}
const stop = aborted();
if (stop) return stop;
}
}
@@ -103,8 +95,7 @@ export class SelfHealingRunner {
// Verified with zero actions (e.g. it only needed time) — nothing to learn.
return { stepId: step.id, status: 'ok', via: 'builtin', variant: 'verified-after-wait' };
}
const reason = step.abortReason?.() || heal.reason || 'LLM fallback failed';
return { stepId: step.id, status: 'failed', reason, llmCalls: heal.llmCalls };
return { stepId: step.id, status: 'failed', reason: heal.reason || 'LLM fallback failed', llmCalls: heal.llmCalls };
}
get healed() {
@@ -69,11 +69,6 @@ export interface CheckoutStep {
allowSubmit?: boolean;
/** Placeholders the LLM may use in this step, e.g. ['CARD_NUMBER']. */
placeholders?: string[];
/**
* Non-recoverable condition that no variant or LLM can fix (e.g. the issuer
* declined the card). Returns a reason to fail the step immediately, or null.
*/
abortReason?: () => string | null;
}
export interface LearnedVariant {
+14 -112
View File
@@ -1,8 +1,7 @@
// frontend/e2e/helpers/stripe-checkout.ts
import { Page, Frame, Locator, Response } from '@playwright/test';
import { Page, Frame, Locator } from '@playwright/test';
import * as fs from 'fs';
import { GeminiPlanner, type Planner } from './self-healing/llm-agent';
import { redact } from './self-healing/observe';
import { SelfHealingRunner } from './self-healing/step-runner';
import type { CheckoutStep, LearnedVariantsFile, Secrets, StepContext } from './self-healing/types';
@@ -33,13 +32,6 @@ import type { CheckoutStep, LearnedVariantsFile, Secrets, StepContext } from './
*
* You can still add builtin variants by hand, but you shouldn't need to.
*
* A *declined card* is not a layout change: Stripe's confirm call returns a
* `card_error`, and the submit step fails immediately with a message starting
* `STRIPE_CARD_DECLINED` (no LLM retries, no further Pay clicks).
*
* Artifacts: test-results/ is uploaded from a PUBLIC repo, so every screenshot
* here masks inputs and the DOM dump has field values redacted.
*
* Environment variables:
* E2E_STRIPE_CARD_NUMBER, E2E_STRIPE_CARD_EXPIRY, E2E_STRIPE_CARD_CVC,
* E2E_STRIPE_CARDHOLDER_NAME (optional), E2E_STRIPE_ZIP (optional)
@@ -48,7 +40,7 @@ import type { CheckoutStep, LearnedVariantsFile, Secrets, StepContext } from './
* E2E_SELF_HEAL_FORCE_LLM — comma-separated step ids to force through the LLM (testing)
*/
export interface CardDetails {
interface CardDetails {
number: string;
expiry: string;
cvc: string;
@@ -217,49 +209,7 @@ function throttled(check: () => Promise<boolean>, intervalMs = 5_000): () => Pro
};
}
/** Marker the daily workflow greps for to report "card declined" instead of "checkout broken". */
export const CARD_DECLINED_MARKER = 'STRIPE_CARD_DECLINED';
/**
* Turn a failed Stripe Checkout `/payment_pages/<id>/confirm` response body
* into an abort reason — only for `card_error`s (declines, incorrect CVC,
* expired card…), which no UI retry can fix. Other errors (e.g. a missing
* required field) return null so the LLM fallback can still repair the form.
*/
export function cardErrorReason(status: number, body: unknown): string | null {
const err = (body as { error?: Record<string, unknown> } | null)?.error;
if (!err || err.type !== 'card_error') return null;
const codes = [err.code, err.decline_code].filter(Boolean).join('/');
return (
`${CARD_DECLINED_MARKER}: Stripe rejected the test card (HTTP ${status}, ${codes || 'card_error'}): ` +
`${err.message || 'no message'} — the issuer/card needs attention; this is not a Checkout layout change`
);
}
export function isCheckoutConfirmUrl(url: string): boolean {
try {
return /\/v1\/payment_pages\/[^/]+\/confirm$/.test(new URL(url).pathname);
} catch {
return false;
}
}
/** Screenshot with every input in every frame masked (artifacts are public). */
async function maskedScreenshot(page: Page, file: string): Promise<void> {
await page
.screenshot({
path: file,
mask: page.frames().filter((f) => !f.isDetached()).map((f) => f.locator('input, textarea, select')),
maskColor: '#888888',
})
.catch(() => {});
}
function buildSteps(
card: CardDetails,
verifyPaid?: () => Promise<boolean>,
cardError?: () => string | null
): CheckoutStep[] {
function buildSteps(card: CardDetails, verifyPaid?: () => Promise<boolean>): CheckoutStep[] {
const paidCheck = verifyPaid ? throttled(verifyPaid) : undefined;
const cardNumberVisible = (ctx: StepContext) =>
anyVisible(ctx.page, (f) => cardFieldLocator(f, 'cardNumber'));
@@ -370,7 +320,6 @@ function buildSteps(
// Long: the Stripe→site redirect and webhook grant can each take a while,
// and a premature LLM fallback risks a second submit.
verifyTimeoutMs: 90_000,
abortReason: cardError,
verify: async ({ page }) => {
if (isSuccessRedirect(page.url())) return true;
return paidCheck ? paidCheck() : false;
@@ -389,16 +338,14 @@ function buildSteps(
];
}
async function dumpFrames(page: Page, file: string, secrets: Secrets): Promise<void> {
async function dumpFrames(page: Page, file: string): Promise<void> {
// page.content() only covers the main frame; the Payment Element usually
// lives in a nested iframe, so dump every frame.
const dumps: string[] = [];
for (const frame of page.frames()) {
if (frame.isDetached()) continue;
const html = (await frame.content().catch(() => ''))
// Typed card data lives in value="…" attributes.
.replace(/(<input\b[^>]*?\bvalue=)("[^"]*"|'[^']*')/gi, '$1"[redacted]"');
dumps.push(`<!-- ===== frame: ${frame.url()} ===== -->\n${redact(html, secrets)}`);
const html = await frame.content().catch(() => '');
dumps.push(`<!-- ===== frame: ${frame.url()} ===== -->\n${html}`);
}
fs.mkdirSync('test-results', { recursive: true });
fs.writeFileSync(file, dumps.join('\n\n'));
@@ -417,24 +364,8 @@ export interface StripeCheckoutOptions {
planner?: Planner | null;
/** Override learned variants (tests). Default: self-healing/learned-variants.json. */
learned?: LearnedVariantsFile;
/**
* No-charge mode: run every step up to (not including) submitPayment, then
* check the Pay button is present. Uses NO_CHARGE_CARD instead of the
* E2E_STRIPE_CARD_* secrets — Stripe's public test card, which live mode
* always rejects, so even an accidental Pay click cannot charge anything.
*/
stopBeforeSubmit?: boolean;
}
/** Stripe's public test card (no secret). Live-mode Checkout declines it on submit. */
export const NO_CHARGE_CARD: CardDetails = {
number: '4242424242424242',
expiry: '12/34',
cvc: '123',
name: 'E2E Test',
zip: '10001',
};
/**
* Complete the Stripe Checkout page with card details from environment.
*
@@ -449,7 +380,7 @@ export async function completeStripeCheckout(
page: Page,
opts: StripeCheckoutOptions = {}
): Promise<{ redirected: boolean; selfHeal: SelfHealingRunner }> {
const card = opts.stopBeforeSubmit ? NO_CHARGE_CARD : getCardDetailsFromEnv();
const card = getCardDetailsFromEnv();
const secrets: Secrets = {
CARD_NUMBER: card.number,
CARD_EXPIRY: card.expiry,
@@ -461,22 +392,6 @@ export async function completeStripeCheckout(
if (!planner) console.log(' (no LLM planner — GEMINI_API_KEY unset; self-healing fallback disabled)');
const runner = new SelfHealingRunner(page, secrets, planner, opts.learned);
// Watch Stripe's confirm call so a declined card fails fast with a clear reason
// instead of sending the LLM fallback to "fix" a form that is already correct.
let cardError: string | null = null;
const onResponse = async (res: Response) => {
if (res.status() < 400 || !isCheckoutConfirmUrl(res.url())) return;
const body = await res.json().catch(() => null);
const reason = cardErrorReason(res.status(), body);
if (reason) {
cardError = reason;
console.log(` ✘ ${reason}`);
} else {
console.log(` ⚠️ Stripe confirm returned HTTP ${res.status()} (not a card error — self-healing continues)`);
}
};
page.on('response', onResponse);
console.log(' Waiting for Stripe Checkout page...');
await page.waitForURL(/checkout\.stripe\.com/, { timeout: 30_000 });
// Readiness: any of the Pay button, the card form or a Card chooser. Don't
@@ -490,40 +405,27 @@ export async function completeStripeCheckout(
.or(f.getByText('Card', { exact: true })),
30_000
);
await maskedScreenshot(page, 'test-results/stripe-checkout-loaded.png');
await page.screenshot({ path: 'test-results/stripe-checkout-loaded.png' });
console.log(ready ? ' Stripe Checkout loaded' : ' ⚠️ Stripe Checkout readiness signal not seen — continuing with self-healing steps');
try {
const steps = buildSteps(card, opts.verifyPaid, () => cardError).filter(
(step) => !(opts.stopBeforeSubmit && step.id === 'submitPayment')
);
for (const step of steps) {
for (const step of buildSteps(card, opts.verifyPaid)) {
const outcome = await runner.run(step);
if (step.id === 'selectCard') await maskedScreenshot(page, 'test-results/stripe-card-selected.png');
if (step.id === 'uncheckSaveInfo') await maskedScreenshot(page, 'test-results/stripe-checkout-filled.png');
if (step.id === 'selectCard') await page.screenshot({ path: 'test-results/stripe-card-selected.png' });
if (step.id === 'uncheckSaveInfo') await page.screenshot({ path: 'test-results/stripe-checkout-filled.png' });
if (outcome.status === 'failed') {
await maskedScreenshot(page, `test-results/stripe-step-failed-${step.id}.png`);
await dumpFrames(page, 'test-results/stripe-checkout-dom.html', secrets);
await page.screenshot({ path: `test-results/stripe-step-failed-${step.id}.png` }).catch(() => {});
await dumpFrames(page, 'test-results/stripe-checkout-dom.html');
throw new Error(`Stripe Checkout step "${step.id}" failed: ${outcome.reason}`);
}
}
} catch (e) {
runner.writeArtifacts(SELF_HEAL_ARTIFACT_DIR, { flowVerified: false });
throw e;
} finally {
page.off('response', onResponse);
}
if (opts.stopBeforeSubmit) {
const pay = await locateVisibleInFrames(page, (f) => f.getByRole('button', { name: /^Pay$/i }), 10_000);
await maskedScreenshot(page, 'test-results/stripe-checkout-ready-no-charge.png');
if (!pay) throw new Error('No-charge mode: card form filled but the Pay button is not visible');
console.log(' Stripe Checkout filled and ready to pay — stopping before submit (no-charge mode)');
return { redirected: false, selfHeal: runner };
}
const redirected = isSuccessRedirect(page.url());
await maskedScreenshot(page, `test-results/stripe-checkout-${redirected ? 'complete' : 'no-redirect'}.png`);
await page.screenshot({ path: `test-results/stripe-checkout-${redirected ? 'complete' : 'no-redirect'}.png` }).catch(() => {});
if (redirected) {
console.log(' Stripe Checkout complete — redirected to our site');
} else {
@@ -79,29 +79,13 @@ async function waitForCreditIncrease(
* for Stage 2 (happy path) to consume
*/
/**
* E2E_PAYMENT_MODE:
* 'real' (default) — pay with the E2E_STRIPE_CARD_* card and verify the credit grant.
* 'checkout-only' — no charge: everything up to Stripe's Pay button (session
* creation, referral price, card form) with Stripe's public test
* card, then hand the new user's signup credit to Stage 2.
*/
const CHECKOUT_ONLY = process.env.E2E_PAYMENT_MODE === 'checkout-only';
const PROD_URL = URLS.production.frontend;
const API_URL = URLS.production.api;
// The real card is typed into Stripe's page: traces (every typed value +
// X-Admin-Token headers), videos and Playwright's automatic screenshots would
// all capture it, and test-results/ is uploaded from a PUBLIC repo. The
// checkout helper takes its own input-masked screenshots instead.
// (Must be top-level: these options force a new worker, so describe-level use() fails to load.)
test.use({ trace: 'off', video: 'off', screenshot: 'off' });
test.describe('Real Credit Purchase Flow', () => {
test('purchase 1 credit via Stripe Checkout with referral discount', async ({ page, request }) => {
// ===== PREREQUISITES =====
test.skip(!CHECKOUT_ONLY && !process.env.E2E_STRIPE_CARD_NUMBER, 'E2E_STRIPE_CARD_NUMBER not set');
test.skip(!process.env.E2E_STRIPE_CARD_NUMBER, 'E2E_STRIPE_CARD_NUMBER not set');
test.skip(!isEmailTestingAvailable(), 'Testmail credentials not set');
const adminToken = process.env.E2E_ADMIN_TOKEN;
@@ -243,27 +227,6 @@ test.describe('Real Credit Purchase Flow', () => {
console.log('\n=== STEP 5: Stripe Checkout ===');
await checkoutButton.click();
if (CHECKOUT_ONLY) {
console.log(' 💳 E2E_PAYMENT_MODE=checkout-only — filling with Stripe test card, NOT paying');
await completeStripeCheckout(page, { stopBeforeSubmit: true });
// The discounted price must be what Stripe will charge.
await expect(page.getByText('$0.50').first()).toBeVisible({ timeout: TIMEOUTS.action });
console.log(' ✅ Checkout session shows the $0.50 referral price and is ready to pay');
// Stage 2 spends one credit; the new account's signup credit covers it.
expect(
baselineCredits,
'No-charge mode hands the signup credit to Stage 2, but the new account has 0 credits'
).toBeGreaterThanOrEqual(1);
const outputDir = path.join(process.cwd(), 'test-results');
fs.mkdirSync(outputDir, { recursive: true });
fs.writeFileSync(path.join(outputDir, 'e2e-session-token.txt'), sessionToken);
console.log(` Token saved for Stage 2 (user has ${baselineCredits} signup credit(s))`);
console.log('\n✅ CHECKOUT-ONLY TEST PASSED (no payment made)');
return;
}
// Complete Stripe Checkout with real card. The redirect back to our site
// is best-effort — the authoritative signal is the server-side credit grant.
// verifyPaid lets the submit step confirm success server-side when the
-142
View File
@@ -1,142 +0,0 @@
#!/usr/bin/env node
// frontend/e2e/scripts/scrub-artifacts.mjs
/**
* Scrub secrets from Playwright output before it is uploaded as a GitHub
* Actions artifact. karaoke-gen is a PUBLIC repo, so any signed-in GitHub user
* can download run artifacts — anything left in test-results/ is published.
*
* What it does, recursively under each given path:
* - deletes Playwright traces (any *.zip — trace.zip, or <sha>.zip inside an
* HTML report): they hold every request header
* (X-Admin-Token) and every typed value, and can't be scrubbed in place;
* - deletes e2e-session-token.txt (a live bearer token for the test user);
* - with --drop-videos, deletes *.webm (videos of the Stripe page show the card);
* - in text files, replaces the literal values of known secret env vars and
* card-number-shaped digit runs; with --blank-inputs also blanks <input
* value="…"> attributes and ARIA-snapshot textbox values (error-context.md);
* - finally deletes any text file that still contains a secret value.
*
* Usage (CI): node e2e/scripts/scrub-artifacts.mjs [--drop-videos] [--blank-inputs] <path>...
* Secret values are read from the env vars in SECRET_ENV_VARS (unset ones are ignored).
*/
import * as fs from 'node:fs';
import * as path from 'node:path';
import { fileURLToPath } from 'node:url';
export const SECRET_ENV_VARS = [
'E2E_ADMIN_TOKEN',
'KARAOKE_ADMIN_TOKEN',
'KARAOKE_ACCESS_TOKEN',
'TESTMAIL_API_KEY',
'GEMINI_API_KEY',
'E2E_STRIPE_CARD_NUMBER',
'E2E_STRIPE_CARD_EXPIRY',
'E2E_STRIPE_CARD_CVC',
'E2E_SESSION_TOKEN',
'E2E_TEST_TOKEN',
'E2E_BYPASS_KEY',
];
// Everything else is treated as text and checked (unknown/no extension included).
const BINARY_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.webm', '.mp4', '.woff', '.woff2', '.ttf']);
const ALWAYS_DELETE = new Set(['e2e-session-token.txt']);
// Short values (CVC "123", "09/29") would scrub unrelated text everywhere;
// --blank-inputs covers them where they actually appear (form fields).
const MIN_LITERAL_LENGTH = 5;
/** Literal variants of a secret worth searching for (card numbers appear grouped in 4s in the UI). */
export function secretVariants(value) {
const v = (value || '').trim();
if (v.replace(/\s/g, '').length < MIN_LITERAL_LENGTH) return [];
const out = new Set([v]);
const digits = v.replace(/[\s-]/g, '');
if (/^\d{12,19}$/.test(digits)) {
out.add(digits);
out.add(digits.replace(/(\d{4})(?=\d)/g, '$1 '));
out.add(digits.replace(/(\d{4})(?=\d)/g, '$1-'));
}
return [...out];
}
export function scrubText(text, secretValues, { blankInputs = false } = {}) {
let out = text;
if (blankInputs) {
out = out
// HTML dumps: <input ... value="4242 ...">
.replace(/(<input\b[^>]*?\bvalue=)("[^"]*"|'[^']*')/gi, '$1"[redacted]"')
// Playwright error-context.md ARIA snapshot: `- textbox "Card number" [ref=e1]:` then `- text: 4242…` on the next line,
// or the value inline after the colon.
.replace(/^(\s*- (?:textbox|combobox|spinbutton|searchbox)\b[^\n]*?):[ \t]+\S.*$/gm, '$1: [value redacted]')
.replace(/^(\s*- (?:textbox|combobox|spinbutton|searchbox)\b[^\n]*:\n(?:\s*- \/placeholder:[^\n]*\n)?\s*- text:)[^\n]*$/gm, '$1 [value redacted]');
}
// Anything shaped like a card number (13-19 digits, optional space/dash separators)
out = out.replace(/\b(?:\d[ -]?){12,18}\d\b/g, '[redacted-digits]');
for (const secret of secretValues) {
for (const variant of secretVariants(secret)) out = out.split(variant).join('[redacted]');
}
return out;
}
export function containsSecret(text, secretValues) {
return secretValues.some((s) => secretVariants(s).some((v) => text.includes(v)));
}
function* walk(p) {
if (!fs.existsSync(p)) return;
const st = fs.statSync(p);
if (st.isFile()) {
yield p;
return;
}
for (const entry of fs.readdirSync(p)) yield* walk(path.join(p, entry));
}
export function scrubPaths(paths, secretValues, { dropVideos = false, blankInputs = false } = {}) {
const stats = { deleted: 0, scrubbed: 0, deletedUnscrubbable: 0 };
for (const root of paths) {
for (const file of walk(root)) {
const base = path.basename(file);
const ext = path.extname(file).toLowerCase();
if (ALWAYS_DELETE.has(base) || ext === '.zip' || (dropVideos && ext === '.webm')) {
fs.rmSync(file);
stats.deleted++;
continue;
}
if (BINARY_EXTENSIONS.has(ext)) continue;
const original = fs.readFileSync(file, 'utf8');
const cleaned = scrubText(original, secretValues, { blankInputs });
if (containsSecret(cleaned, secretValues)) {
fs.rmSync(file);
stats.deletedUnscrubbable++;
continue;
}
if (cleaned !== original) {
fs.writeFileSync(file, cleaned);
stats.scrubbed++;
}
}
}
return stats;
}
function main(argv) {
const flags = new Set(argv.filter((a) => a.startsWith('--')));
const paths = argv.filter((a) => !a.startsWith('--'));
if (!paths.length) {
console.error('usage: scrub-artifacts.mjs [--drop-videos] [--blank-inputs] <path>...');
process.exit(2);
}
const secretValues = SECRET_ENV_VARS.map((k) => process.env[k]).filter(Boolean);
const stats = scrubPaths(paths, secretValues, {
dropVideos: flags.has('--drop-videos'),
blankInputs: flags.has('--blank-inputs'),
});
console.log(
`scrub-artifacts: ${secretValues.length} secret value(s) checked; deleted ${stats.deleted} trace/token/video file(s), ` +
`scrubbed ${stats.scrubbed} text file(s), deleted ${stats.deletedUnscrubbable} unscrubbable file(s)`
);
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
main(process.argv.slice(2));
}
@@ -7,7 +7,6 @@ import { completeStripeCheckout } from '../helpers/stripe-checkout';
import { emptyFile } from '../helpers/self-healing/learned-store';
import type { LearnedVariantsFile } from '../helpers/self-healing/types';
import {
CARD_DECLINED_RESPONSE,
CHECKOUT_URL,
ELEMENTS_FUTURE,
ELEMENTS_OCT2026,
@@ -157,57 +156,3 @@ test('without a planner, an unknown layout fails with a clear reason (determinis
await expect(completeStripeCheckout(page, { planner: null, learned: emptyFile() })).rejects.toThrow(/no LLM planner/);
expect(fs.existsSync('test-results/stripe-checkout-dom.html')).toBe(true);
});
test('declined card fails fast with STRIPE_CARD_DECLINED — no LLM calls, no second Pay click', async ({ page }) => {
await serveCheckout(page, ELEMENTS_OCT2026, CARD_DECLINED_RESPONSE);
let confirmCalls = 0;
page.on('request', (r) => {
if (r.url().endsWith('/confirm') && r.method() === 'POST') confirmCalls++;
});
await page.goto(CHECKOUT_URL);
const planner = new ScriptedPlanner([]);
const started = Date.now();
await expect(completeStripeCheckout(page, { planner, learned: emptyFile() })).rejects.toThrow(
/STRIPE_CARD_DECLINED: .*card_declined\/generic_decline.*Your card was declined/
);
// Without the abort the submit step would poll its full 90s verify, then hand off to the LLM.
expect(Date.now() - started).toBeLessThan(60_000);
expect(planner.inputs).toHaveLength(0);
expect(confirmCalls).toBe(1);
});
test('failure artifacts never contain typed card data', async ({ page }) => {
await serveCheckout(page, ELEMENTS_OCT2026, CARD_DECLINED_RESPONSE);
await page.goto(CHECKOUT_URL);
await expect(completeStripeCheckout(page, { planner: null, learned: emptyFile() })).rejects.toThrow(/STRIPE_CARD_DECLINED/);
const dom = fs.readFileSync('test-results/stripe-checkout-dom.html', 'utf8');
expect(dom).toContain('id="cardNumber"');
for (const value of [TEST_CARD.E2E_STRIPE_CARD_NUMBER, TEST_CARD.E2E_STRIPE_CARD_EXPIRY, TEST_CARD.E2E_STRIPE_CARD_CVC]) {
expect(dom).not.toContain(`value="${value}"`);
}
expect(dom).not.toContain(TEST_CARD.E2E_STRIPE_CARD_NUMBER);
});
test('no-charge mode (stopBeforeSubmit) fills the form with the public test card and never clicks Pay', async ({ page }) => {
await serveCheckout(page, ELEMENTS_OCT2026);
let confirmCalls = 0;
page.on('request', (r) => {
if (r.url().endsWith('/confirm')) confirmCalls++;
});
await page.goto(CHECKOUT_URL);
const saved = process.env.E2E_STRIPE_CARD_NUMBER;
delete process.env.E2E_STRIPE_CARD_NUMBER; // no real card needed in this mode
try {
const result = await completeStripeCheckout(page, { planner: new ScriptedPlanner([]), learned: emptyFile(), stopBeforeSubmit: true });
expect(result.redirected).toBe(false);
expect(result.selfHeal.outcomes.map((o) => o.stepId)).not.toContain('submitPayment');
expect(result.selfHeal.outcomes.every((o) => o.status === 'ok')).toBe(true);
} finally {
process.env.E2E_STRIPE_CARD_NUMBER = saved;
}
const frame = page.frames().find((f) => f.url().includes('js.stripe.com'))!;
await expect(frame.locator('#cardNumber')).toHaveValue('4242424242424242');
expect(confirmCalls).toBe(0);
expect(page.url()).toContain('checkout.stripe.com');
});
+3 -30
View File
@@ -5,7 +5,6 @@ import type { LlmDecision, Planner, PlannerInput } from '../helpers/self-healing
export const CHECKOUT_URL = 'https://checkout.stripe.com/c/pay/cs_test_fixture#frag';
export const ELEMENTS_URL = 'https://js.stripe.com/v3/elements-inner-payment.html?id=abc';
export const SUCCESS_URL = 'https://gen.nomadkaraoke.com/payment/success?session_id=cs_test_fixture';
export const CONFIRM_URL = 'https://api.stripe.com/v1/payment_pages/cs_test_fixture/confirm';
export const TEST_CARD = {
E2E_STRIPE_CARD_NUMBER: '4242424242424242',
@@ -63,39 +62,13 @@ const TOP_PAGE = `<!doctype html><html><body>
<iframe src="${ELEMENTS_URL}" style="width:600px;height:500px"></iframe>
<script>
window.addEventListener('message', (e) => {
// Like real Checkout: Pay → confirm API call → redirect only if it succeeded.
if (e.data === 'pay') {
fetch('${CONFIRM_URL}', { method: 'POST' }).then((r) => {
if (r.ok) window.location.href = '${SUCCESS_URL}';
});
}
if (e.data === 'pay') window.location.href = '${SUCCESS_URL}';
});
</script>
</body></html>`;
/** Stripe's confirm response for a declined card. */
export const CARD_DECLINED_RESPONSE = {
status: 402,
body: { error: { type: 'card_error', code: 'card_declined', decline_code: 'generic_decline', message: 'Your card was declined.' } },
};
/**
* Serve a fake Stripe Checkout (top page + Payment Element iframe) and our
* success page. `confirm` overrides the confirm API response (default 200).
*/
export async function serveCheckout(
page: Page,
elementsHtml: string,
confirm: { status: number; body: unknown } = { status: 200, body: { status: 'complete' } }
): Promise<void> {
await page.route(CONFIRM_URL, (r) =>
r.fulfill({
status: confirm.status,
contentType: 'application/json',
headers: { 'Access-Control-Allow-Origin': '*' },
body: JSON.stringify(confirm.body),
})
);
/** Serve a fake Stripe Checkout (top page + Payment Element iframe) and our success page. */
export async function serveCheckout(page: Page, elementsHtml: string): Promise<void> {
await page.route('https://checkout.stripe.com/**', (r) => r.fulfill({ contentType: 'text/html', body: TOP_PAGE }));
await page.route('https://js.stripe.com/**', (r) => r.fulfill({ contentType: 'text/html', body: elementsHtml }));
await page.route('https://gen.nomadkaraoke.com/**', (r) =>
@@ -1,70 +0,0 @@
// frontend/e2e/self-healing/scrub-artifacts.spec.ts — tests for e2e/scripts/scrub-artifacts.mjs
import { test, expect } from '@playwright/test';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
let scrub: any;
test.beforeAll(async () => {
scrub = await import('../scripts/scrub-artifacts.mjs');
});
const CARD = '4242424242424242';
const ADMIN = 'admin-token-0123456789abcdef';
const SECRETS = [CARD, ADMIN, '12/34', '123'];
test('scrubText removes literal secrets, grouped card numbers and PAN-shaped digits', () => {
const out = scrub.scrubText(`X-Admin-Token: ${ADMIN}\ncard 4242 4242 4242 4242 and 4242-4242-4242-4242 and 5555555555554444`, SECRETS);
expect(out).not.toContain(ADMIN);
expect(out).not.toMatch(/4242/);
expect(out).not.toContain('5555555555554444');
expect(out).toContain('X-Admin-Token: [redacted]');
});
test('short secrets (CVC/expiry) are not scrubbed globally, only in inputs with --blank-inputs', () => {
const text = [
'took 123ms',
'<input id="cardCvc" value="123"><input id="exp" value=\'12/34\'>',
'- textbox "Credit or debit card CVC/CVV" [ref=e162]:',
' - /placeholder: CVC',
' - text: "123"',
'- textbox "Expiration" [ref=e157]: 12 / 34',
].join('\n');
expect(scrub.scrubText(text, SECRETS)).toContain('value="123"');
const blanked = scrub.scrubText(text, SECRETS, { blankInputs: true });
expect(blanked).toContain('took 123ms');
expect(blanked).not.toContain('value="123"');
expect(blanked).not.toContain("12/34");
expect(blanked).toContain('- text: [value redacted]');
expect(blanked).toContain('- textbox "Expiration" [ref=e157]: [value redacted]');
});
test('scrubPaths deletes traces/tokens/videos, scrubs text, leaves images', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'scrub-'));
const sub = path.join(dir, 'spec-chromium');
fs.mkdirSync(path.join(dir, 'report', 'data'), { recursive: true });
fs.mkdirSync(sub);
fs.writeFileSync(path.join(sub, 'trace.zip'), 'zip');
fs.writeFileSync(path.join(dir, 'report', 'data', 'abc123.zip'), 'zip');
fs.writeFileSync(path.join(sub, 'video.webm'), 'webm');
fs.writeFileSync(path.join(dir, 'e2e-session-token.txt'), 'tok');
fs.writeFileSync(path.join(sub, 'error-context.md'), `- textbox "Card number" [ref=e1]:\n - text: ${CARD}\n`);
fs.writeFileSync(path.join(sub, 'shot.png'), 'png');
const stats = scrub.scrubPaths([dir, path.join(dir, 'missing.log')], SECRETS, { dropVideos: true, blankInputs: true });
expect(fs.existsSync(path.join(sub, 'trace.zip'))).toBe(false);
expect(fs.existsSync(path.join(dir, 'report', 'data', 'abc123.zip'))).toBe(false);
expect(fs.existsSync(path.join(sub, 'video.webm'))).toBe(false);
expect(fs.existsSync(path.join(dir, 'e2e-session-token.txt'))).toBe(false);
expect(fs.existsSync(path.join(sub, 'shot.png'))).toBe(true);
expect(fs.readFileSync(path.join(sub, 'error-context.md'), 'utf8')).not.toContain(CARD);
expect(stats).toEqual({ deleted: 4, scrubbed: 1, deletedUnscrubbable: 0 });
});
test('videos are kept without --drop-videos', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'scrub-'));
fs.writeFileSync(path.join(dir, 'video.webm'), 'webm');
scrub.scrubPaths([dir], SECRETS);
expect(fs.existsSync(path.join(dir, 'video.webm'))).toBe(true);
});
+1 -25
View File
@@ -4,7 +4,7 @@ import { frameUrlKey, substitutePlaceholders } from '../helpers/self-healing/act
import { buildPrompt, checkGuards, checkResolvedClick, toTargetSpec } from '../helpers/self-healing/llm-agent';
import { MAX_LEARNED_PER_STEP, emptyFile, mergeLearned, variantId } from '../helpers/self-healing/learned-store';
import { redact } from '../helpers/self-healing/observe';
import { cardErrorReason, isCheckoutConfirmUrl, isSuccessRedirect } from '../helpers/stripe-checkout';
import { isSuccessRedirect } from '../helpers/stripe-checkout';
import type { Action } from '../helpers/self-healing/types';
const secrets = { CARD_NUMBER: '4242424242424242', CARD_EXPIRY: '12/34', CARD_CVC: '123', CARDHOLDER_NAME: 'Fixture Tester', POSTAL_CODE: '10001' };
@@ -146,27 +146,3 @@ test('isSuccessRedirect accepts success/app URLs but not the cancel link', () =>
expect(isSuccessRedirect('https://gen.nomadkaraoke.com?cancelled=true')).toBe(false);
expect(isSuccessRedirect('https://checkout.stripe.com/c/pay/x')).toBe(false);
});
test.describe('card decline detection', () => {
test('card_error → abort reason with marker, codes and message', () => {
const reason = cardErrorReason(402, {
error: { type: 'card_error', code: 'card_declined', decline_code: 'generic_decline', message: 'Your card was declined.' },
});
expect(reason).toMatch(/^STRIPE_CARD_DECLINED: /);
expect(reason).toContain('HTTP 402, card_declined/generic_decline');
expect(reason).toContain('Your card was declined.');
});
test('non-card errors and junk bodies do not abort (the LLM may still fix the form)', () => {
expect(cardErrorReason(400, { error: { type: 'invalid_request_error', message: 'Missing postal code' } })).toBeNull();
expect(cardErrorReason(500, null)).toBeNull();
expect(cardErrorReason(402, 'not json')).toBeNull();
});
test('isCheckoutConfirmUrl matches only the payment page confirm endpoint', () => {
expect(isCheckoutConfirmUrl('https://api.stripe.com/v1/payment_pages/cs_live_abc/confirm')).toBe(true);
expect(isCheckoutConfirmUrl('https://api.stripe.com/v1/payment_pages/cs_live_abc/init')).toBe(false);
expect(isCheckoutConfirmUrl('https://api.stripe.com/v1/payment_methods')).toBe(false);
expect(isCheckoutConfirmUrl('not a url')).toBe(false);
});
});
+4 -30
View File
@@ -2764,11 +2764,6 @@ export interface TenantThemeData {
fonts: string[]
}
export interface TenantThemeSaveResult extends TenantThemeData {
refreshed_jobs: number
outdated_job_ids: string[]
}
export interface ThemePreviewSample {
artist?: string
title?: string
@@ -2776,10 +2771,8 @@ export interface ThemePreviewSample {
}
export interface ThemePreviewImages {
// data:image/jpeg;base64,... — null for a screen the theme leaves out of videos
title_card: string | null
title_card: string // data:image/jpeg;base64,...
karaoke_frame: string
end_screen: string | null
}
export const tenantThemeApi = {
@@ -2816,33 +2809,14 @@ export const tenantThemeApi = {
return handleResponse<ThemePreviewImages>(response)
},
/**
* Save the theme. Applies to new tracks and to tracks still in progress
* (`refreshed_jobs`); finished tracks made with the old theme are listed in
* `outdated_job_ids` (re-render to update them).
*/
async save(styleParams: ThemeStyleParams): Promise<TenantThemeSaveResult> {
/** Save the theme — applies to jobs created from now on. */
async save(styleParams: ThemeStyleParams): Promise<TenantThemeData> {
const response = await apiFetch(`${API_BASE_URL}/api/tenant/theme`, {
method: 'PUT',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({ style_params: styleParams }),
})
return handleResponse<TenantThemeSaveResult>(response)
},
/** The caller's finished tracks made with an older version of the theme. */
async outdatedJobs(): Promise<{ theme_updated_at: string | null; job_ids: string[] }> {
const response = await apiFetch(`${API_BASE_URL}/api/tenant/theme/outdated-jobs`, { headers: getAuthHeaders() })
return handleResponse<{ theme_updated_at: string | null; job_ids: string[] }>(response)
},
/** Re-render every outdated finished track with the current theme (no per-track emails). */
async rerenderOutdated(): Promise<{ started: string[]; failed: Record<string, string>; remaining?: string[] }> {
const response = await apiFetch(`${API_BASE_URL}/api/tenant/theme/rerender-outdated`, {
method: 'POST',
headers: getAuthHeaders(),
})
return handleResponse<{ started: string[]; failed: Record<string, string>; remaining?: string[] }>(response)
return handleResponse<TenantThemeData>(response)
},
}
-66
View File
@@ -1,66 +0,0 @@
/**
* Which of the signed-in user's finished portal tracks were made with an older
* version of the tenant theme (so their job cards can suggest a re-render).
*
* One shared set per page: fetched once when the first job card on a tenant
* portal asks for it, replaced after a theme save, and trimmed as re-renders
* start (a re-rendered track picks up the current theme).
*/
import { useEffect, useSyncExternalStore } from 'react'
import { tenantThemeApi } from './api'
const EMPTY: ReadonlySet<string> = new Set()
let outdated: ReadonlySet<string> = EMPTY
let fetchStarted = false
let version = 0 // bumped on every update, so a slow initial fetch can't clobber a newer list
const listeners = new Set<() => void>()
function emit() {
listeners.forEach((l) => l())
}
function subscribe(listener: () => void) {
listeners.add(listener)
return () => {
listeners.delete(listener)
}
}
export function setOutdatedThemeJobs(jobIds: string[]) {
outdated = new Set(jobIds)
fetchStarted = true
version++
emit()
}
export function clearOutdatedThemeJobs(jobIds: string[]) {
if (!jobIds.some((id) => outdated.has(id))) return
const next = new Set(outdated)
jobIds.forEach((id) => next.delete(id))
outdated = next
version++
emit()
}
/** Test hook: forget everything (module state survives between tests). */
export function resetOutdatedThemeJobs() {
outdated = EMPTY
fetchStarted = false
emit()
}
export function useOutdatedThemeJobs(enabled: boolean): ReadonlySet<string> {
useEffect(() => {
if (!enabled || fetchStarted) return
fetchStarted = true
const startedAt = version
tenantThemeApi
.outdatedJobs()
.then((r) => {
if (version === startedAt) setOutdatedThemeJobs(r.job_ids)
})
// Not on a member's portal / transient error: just show no hints.
.catch(() => {})
}, [enabled])
return useSyncExternalStore(subscribe, () => outdated, () => EMPTY)
}
+5 -24
View File
@@ -764,9 +764,7 @@
"regenerateStarted": "جارٍ إعادة إنشاء الفيديو الخاص بك. سنرسل لك بريداً إلكترونياً عندما يصبح جاهزاً.",
"regenerateTime": "يستغرق هذا عادةً من 10 إلى 30 دقيقة. سنرسل لك بريداً إلكترونياً عندما يصبح جاهزاً.",
"regenerateTitle": "هل تريد إعادة إنشاء هذا الفيديو؟",
"regenerateTooltip": "لتوفير المساحة، تحتفظ الأغاني القديمة بفيديو 720p وحزم الكاريوكي فقط. أعد إنشاء الصيغ الأخرى من هنا.",
"outdatedTheme": "سمة قديمة",
"outdatedThemeTooltip": "تم إنشاء هذا الفيديو قبل آخر تغيير في السمة. أعد معالجته لتحديث مظهره."
"regenerateTooltip": "لتوفير المساحة، تحتفظ الأغاني القديمة بفيديو 720p وحزم الكاريوكي فقط. أعد إنشاء الصيغ الأخرى من هنا."
},
"themeSelector": {
"videoTheme": "سمة الفيديو",
@@ -1978,6 +1976,7 @@
"tenantTheme": {
"advancedHint": "عدّل أي إعداد في السمة مباشرةً. يتم التحقق من التغييرات عند الحفظ.",
"advancedJson": "JSON الكامل للسمة",
"appliesToNewJobs": "تنطبق التغييرات المحفوظة على مقاطع الفيديو التي تنشئها من الآن فصاعداً.",
"artistColour": "لون اسم الفنان",
"artistName": "اسم الفنان",
"background": "الخلفية",
@@ -1988,6 +1987,7 @@
"description": "خصّص مظهر مقاطع فيديو الكاريوكي الخاصة بك. تظهر المعاينات على اليمين تماماً كما ستكون في مقاطع الفيديو النهائية.",
"discard": "تجاهل التغييرات",
"discardConfirm": "لديك تغييرات غير محفوظة في السمة. هل تريد الإغلاق دون حفظ؟",
"endScreenHint": "لا تتوفر معاينة لشاشة النهاية؛ فهي تستخدم نفس الخط ونمط التنسيق المستخدمين في بطاقة العنوان.",
"font": "الخط",
"fontHint": "يُستخدم خط واحد لبطاقة العنوان والكلمات وشاشة النهاية.",
"jsonInvalid": "صيغة JSON غير صالحة",
@@ -2011,6 +2011,7 @@
"sampleTitleDefault": "عنوان الأغنية",
"save": "حفظ السمة",
"saveFailed": "تعذّر حفظ سمتك",
"savedBody": "ستستخدم مقاطع الفيديو الجديدة سمتك المحدّثة.",
"savedTitle": "تم حفظ السمة",
"solidColour": "لون خالص (بدون صورة)",
"sungColour": "لون الكلمات المغنّاة",
@@ -2032,27 +2033,7 @@
"close": "إغلاق",
"saving": "جارٍ الحفظ…",
"songTitle": "عنوان الأغنية",
"appliesToInProgress": "تنطبق التغييرات المحفوظة على مقاطع الفيديو الجديدة ومقاطع الفيديو التي لا تزال قيد الإنشاء.",
"finishedKeepOldLook": "تحتفظ مقاطع الفيديو المكتملة بمظهرها القديم حتى تعيد معالجتها.",
"outdatedFinished": "{count, plural, zero {لا توجد مقاطع فيديو مكتملة لا تزال بالمظهر القديم.} one {لا يزال هناك فيديو مكتمل واحد بالمظهر القديم.} two {لا يزال هناك فيديوهان مكتملان بالمظهر القديم.} few {لا تزال هناك # مقاطع فيديو مكتملة بالمظهر القديم.} many {لا يزال هناك # مقطع فيديو مكتمل بالمظهر القديم.} other {لا يزال هناك # مقطع فيديو مكتمل بالمظهر القديم.}}",
"refreshedInProgress": "{count, plural, zero {لا توجد مقاطع فيديو قيد الإنشاء ستستخدم المظهر الجديد.} one {سيستخدم فيديو واحد قيد الإنشاء المظهر الجديد تلقائيًا.} two {سيستخدم فيديوهان قيد الإنشاء المظهر الجديد تلقائيًا.} few {ستستخدم # مقاطع فيديو قيد الإنشاء المظهر الجديد تلقائيًا.} many {سيستخدم # مقطع فيديو قيد الإنشاء المظهر الجديد تلقائيًا.} other {سيستخدم # مقطع فيديو قيد الإنشاء المظهر الجديد تلقائيًا.}}",
"rerenderAll": "{count, plural, zero {إعادة المعالجة} one {إعادة معالجته الآن} two {إعادة معالجة الاثنين الآن} few {إعادة معالجة الـ # جميعها} many {إعادة معالجة الـ # جميعها} other {إعادة معالجة الـ # جميعها}}",
"rerenderAllFailed": "تعذر بدء إعادة المعالجة",
"rerenderAllSomeFailed": "{count, plural, zero {تمت إعادة معالجة جميع الفيديوهات بنجاح} one {تعذرت إعادة معالجة فيديو واحد} two {تعذرت إعادة معالجة فيديوهين} few {تعذرت إعادة معالجة # مقاطع فيديو} many {تعذرت إعادة معالجة # مقطع فيديو} other {تعذرت إعادة معالجة # مقطع فيديو}}",
"rerenderAllStarted": "{count, plural, zero {جارٍ إعادة معالجة الفيديوهات بسمتك الجديدة.} one {جارٍ إعادة معالجة فيديو واحد بسمتك الجديدة. يستغرق الأمر من 10 إلى 15 دقيقة تقريبًا؛ يمكنك متابعة تقدمه من المسار.} two {جارٍ إعادة معالجة فيديوهين بسمتك الجديدة. يستغرق كل منهما من 10 إلى 15 دقيقة تقريبًا؛ يمكنك متابعة تقدمهما من كل مسار.} few {جارٍ إعادة معالجة # مقاطع فيديو بسمتك الجديدة. يستغرق كل منها من 10 إلى 15 دقيقة تقريبًا؛ يمكنك متابعة تقدمها من كل مسار.} many {جارٍ إعادة معالجة # مقطع فيديو بسمتك الجديدة. يستغرق كل منها من 10 إلى 15 دقيقة تقريبًا؛ يمكنك متابعة تقدمها من كل مسار.} other {جارٍ إعادة معالجة # مقطع فيديو بسمتك الجديدة. يستغرق كل منها من 10 إلى 15 دقيقة تقريبًا؛ يمكنك متابعة تقدمها من كل مسار.}}",
"rerenderAllStarting": "جارٍ البدء…",
"savedBodyInProgress": "ستستخدم مقاطع الفيديو الجديدة، وكذلك المقاطع التي لا تزال قيد الإنشاء، سمتك المحدّثة.",
"copyTitleCardLayout": "نسخ تنسيق بطاقة العنوان",
"copyTitleCardLayoutHint": "تطبيق نفس الحجم والموضع والألوان وحالة الأحرف لعنوان الأغنية واسم الفنان كما في بطاقة العنوان لديك.",
"endScreenFontHint": "تستخدم شاشة النهاية نفس خط بطاقة العنوان (يمكنك تغييره من علامة تبويب \"بطاقة العنوان\").",
"endScreenOff": "ستنتهي مقاطع الفيديو عند انتهاء الأغنية.",
"includeEndScreen": "تضمين شاشة نهاية في ختام كل مقطع فيديو",
"includeTitleCard": "تضمين بطاقة عنوان في بداية كل مقطع فيديو",
"previewEndScreen": "معاينة شاشة النهاية",
"screenOmitted": "غير مُدرجة في مقاطع الفيديو الخاصة بك",
"showArtistName": "إظهار اسم الفنان",
"showSongTitle": "إظهار عنوان الأغنية",
"titleCardOff": "ستبدأ مقاطع الفيديو مباشرةً مع فيديو كلمات الأغنية."
"rerenderHint": "لتحديث تراك أنشأته بالفعل، استخدم خيار \"إعادة التصيير\" من بطاقته."
},
"stalledDownload": {
"actionFailedDesc": "يُرجى المحاولة مرة أخرى بعد قليل.",
+5 -24
View File
@@ -764,9 +764,7 @@
"regenerateStarted": "S'està regenerant el teu vídeo. T'enviarem un correu electrònic quan estigui a punt.",
"regenerateTime": "Normalment triga entre 10 i 30 minuts. T'enviarem un correu electrònic quan estigui a punt.",
"regenerateTitle": "Vols regenerar aquest vídeo?",
"regenerateTooltip": "Per estalviar espai, a les cançons més antigues només s'hi conserva el vídeo en 720p i els paquets de karaoke. Regenera els altres formats.",
"outdatedTheme": "Tema antic",
"outdatedThemeTooltip": "Aquest vídeo es va fer abans del teu últim canvi de tema. Torna'l a renderitzar per actualitzar-ne l'aspecte."
"regenerateTooltip": "Per estalviar espai, a les cançons més antigues només s'hi conserva el vídeo en 720p i els paquets de karaoke. Regenera els altres formats."
},
"themeSelector": {
"videoTheme": "Tema del vídeo",
@@ -1978,6 +1976,7 @@
"tenantTheme": {
"advancedHint": "Edita qualsevol paràmetre del tema directament. Els canvis es comproven en desar.",
"advancedJson": "JSON complet del tema",
"appliesToNewJobs": "Els canvis desats s'aplicaran als vídeos que creïs a partir d'ara.",
"artistColour": "Color del nom de l'artista",
"artistName": "Nom de l'artista",
"background": "Fons",
@@ -1988,6 +1987,7 @@
"description": "Personalitza l'aparença dels teus vídeos de karaoke. Les previsualitzacions de la dreta es renderitzen exactament com els teus vídeos acabats.",
"discard": "Descarta els canvis",
"discardConfirm": "Tens canvis al tema sense desar. Vols tancar sense desar?",
"endScreenHint": "La pantalla final no es previsualitza; utilitza la mateixa font i estil de disseny que la targeta de títol.",
"font": "Font",
"fontHint": "S'utilitza una sola font per a la targeta de títol, la lletra i la pantalla final.",
"jsonInvalid": "JSON no vàlid",
@@ -2011,6 +2011,7 @@
"sampleTitleDefault": "Títol de la cançó",
"save": "Desa el tema",
"saveFailed": "No s'ha pogut desar el teu tema",
"savedBody": "Els vídeos nous utilitzaran el teu tema actualitzat.",
"savedTitle": "Tema desat",
"solidColour": "Color sòlid (sense imatge)",
"sungColour": "Color de la lletra cantada",
@@ -2032,27 +2033,7 @@
"close": "Tanca",
"saving": "Desant…",
"songTitle": "Títol de la cançó",
"appliesToInProgress": "Els canvis desats s'apliquen als vídeos nous i als vídeos que encara s'estan creant.",
"finishedKeepOldLook": "Els vídeos acabats mantenen l'aspecte antic fins que els tornis a renderitzar.",
"outdatedFinished": "{count, plural, one {# vídeo acabat encara té l'aspecte antic.} other {# vídeos acabats encara tenen l'aspecte antic.}}",
"refreshedInProgress": "{count, plural, one {# vídeo que encara s'està fent tindrà el nou aspecte automàticament.} other {# vídeos que encara s'estan fent tindran el nou aspecte automàticament.}}",
"rerenderAll": "{count, plural, one {Torna'l a renderitzar ara} other {Torna'ls a renderitzar tots (#)}}",
"rerenderAllFailed": "No s'ha pogut iniciar la nova renderització",
"rerenderAllSomeFailed": "{count, plural, one {No s'ha pogut tornar a renderitzar # vídeo} other {No s'han pogut tornar a renderitzar # vídeos}}",
"rerenderAllStarted": "{count, plural, one {S'està tornant a renderitzar # vídeo amb el teu tema nou. Triga uns 10-15 minuts; en pots seguir el progrés a la cançó.} other {S'estan tornant a renderitzar # vídeos amb el teu tema nou. Cadascun triga uns 10-15 minuts; en pots seguir el progrés a cada cançó.}}",
"rerenderAllStarting": "S'està iniciant…",
"savedBodyInProgress": "Els vídeos nous i els vídeos que encara s'estan fent utilitzaran el teu tema actualitzat.",
"copyTitleCardLayout": "Copia el disseny de la targeta de títol",
"copyTitleCardLayoutHint": "Posa aquí el títol de la cançó i el nom de l'artista amb la mateixa mida, posició, colors i majúscules que a la teva targeta de títol.",
"endScreenFontHint": "La pantalla final utilitza el mateix tipus de lletra que la targeta de títol (canvia'l a la pestanya Targeta de títol).",
"endScreenOff": "Els vídeos s'acabaran quan s'acabi la cançó.",
"includeEndScreen": "Inclou una pantalla final al final de cada vídeo",
"includeTitleCard": "Inclou una targeta de títol a l'inici de cada vídeo",
"previewEndScreen": "Previsualització de la pantalla final",
"screenOmitted": "No s'inclou als teus vídeos",
"showArtistName": "Mostra el nom de l'artista",
"showSongTitle": "Mostra el títol de la cançó",
"titleCardOff": "Els vídeos començaran directament amb el vídeo amb la lletra."
"rerenderHint": "Per actualitzar una pista que ja has creat, utilitza «Tornar a renderitzar» a la seva targeta."
},
"stalledDownload": {
"actionFailedDesc": "Torna-ho a provar d'aquí a un moment.",
+5 -24
View File
@@ -764,9 +764,7 @@
"regenerateStarted": "Přegenerováváme tvé video. Jakmile bude hotové, pošleme ti e-mail.",
"regenerateTime": "Obvykle to trvá 10–30 minut. Jakmile bude hotové, pošleme ti e-mail.",
"regenerateTitle": "Přegenerovat toto video?",
"regenerateTooltip": "Abychom šetřili místo, u starších skladeb uchováváme pouze 720p video a karaoke balíčky. Přegeneruj ostatní formáty.",
"outdatedTheme": "Starší motiv",
"outdatedThemeTooltip": "Toto video bylo vytvořeno před tvou poslední změnou motivu. Pokud chceš aktualizovat jeho vzhled, přerenderuj ho."
"regenerateTooltip": "Abychom šetřili místo, u starších skladeb uchováváme pouze 720p video a karaoke balíčky. Přegeneruj ostatní formáty."
},
"themeSelector": {
"videoTheme": "Motiv videa",
@@ -1978,6 +1976,7 @@
"tenantTheme": {
"advancedHint": "Uprav jakékoli nastavení motivu přímo. Změny se zkontrolují při uložení.",
"advancedJson": "Kompletní JSON motivu",
"appliesToNewJobs": "Uložené změny se použijí na videa, která odteď vytvoříš.",
"artistColour": "Barva jména interpreta",
"artistName": "Jméno interpreta",
"background": "Pozadí",
@@ -1988,6 +1987,7 @@
"description": "Přizpůsob si vzhled svých karaoke videí. Náhledy vpravo se vykreslují přesně tak, jak budou vypadat tvá hotová videa.",
"discard": "Zahodit změny",
"discardConfirm": "Máš neuložené změny motivu. Zavřít bez uložení?",
"endScreenHint": "Závěrečná obrazovka nemá náhled; používá stejné písmo a styl rozvržení jako úvodní karta.",
"font": "Písmo",
"fontHint": "Pro úvodní kartu, text písně i závěrečnou obrazovku se používá jedno písmo.",
"jsonInvalid": "Neplatný JSON",
@@ -2011,6 +2011,7 @@
"sampleTitleDefault": "Název skladby",
"save": "Uložit motiv",
"saveFailed": "Nepodařilo se uložit motiv",
"savedBody": "Nová videa budou používat tvůj aktualizovaný motiv.",
"savedTitle": "Motiv uložen",
"solidColour": "Jednolitá barva (bez obrázku)",
"sungColour": "Barva odzpívaného textu",
@@ -2032,27 +2033,7 @@
"close": "Zavřít",
"saving": "Ukládám…",
"songTitle": "Název písně",
"appliesToInProgress": "Uložené změny se projeví u nových videí i u videí, která se právě vytvářejí.",
"finishedKeepOldLook": "Dokončená videa si zachovají starý vzhled, dokud je nepřerenderuješ.",
"outdatedFinished": "{count, plural, one {# dokončené video má stále starý vzhled.} few {# dokončená videa mají stále starý vzhled.} other {# dokončených videí má stále starý vzhled.}}",
"refreshedInProgress": "{count, plural, one {# video, které se právě vytváří, automaticky použije nový vzhled.} few {# videa, která se právě vytvářejí, automaticky použijí nový vzhled.} other {# videí, která se právě vytvářejí, automaticky použije nový vzhled.}}",
"rerenderAll": "{count, plural, one {Přerenderovat hned} few {Přerenderovat všechna #} other {Přerenderovat všech #}}",
"rerenderAllFailed": "Přerenderování se nepodařilo spustit",
"rerenderAllSomeFailed": "{count, plural, one {# video se nepodařilo přerenderovat} few {# videa se nepodařilo přerenderovat} other {# videí se nepodařilo přerenderovat}}",
"rerenderAllStarted": "{count, plural, one {Přerenderovává se # video s tvým novým motivem. Trvá to asi 10–15 minut; průběh můžeš sledovat u skladby.} few {Přerenderovávají se # videa s tvým novým motivem. Každé trvá asi 10–15 minut; průběh můžeš sledovat u jednotlivých skladeb.} other {Přerenderovává se # videí s tvým novým motivem. Každé trvá asi 10–15 minut; průběh můžeš sledovat u jednotlivých skladeb.}}",
"rerenderAllStarting": "Spouští se…",
"savedBodyInProgress": "Nová videa a videa, která se právě vytvářejí, použijí tvůj aktualizovaný motiv.",
"copyTitleCardLayout": "Zkopírovat rozvržení úvodní karty",
"copyTitleCardLayoutHint": "Nastav názvu skladby a jménu interpreta stejnou velikost, pozici, barvy a velká písmena jako na úvodní kartě.",
"endScreenFontHint": "Závěrečná obrazovka používá stejné písmo jako úvodní karta (můžeš ho změnit na záložce Úvodní karta).",
"endScreenOff": "Videa skončí hned, jakmile skončí skladba.",
"includeEndScreen": "Přidat závěrečnou obrazovku na konec každého videa",
"includeTitleCard": "Přidat úvodní kartu na začátek každého videa",
"previewEndScreen": "Náhled závěrečné obrazovky",
"screenOmitted": "Není součástí tvých videí",
"showArtistName": "Zobrazit jméno interpreta",
"showSongTitle": "Zobrazit název skladby",
"titleCardOff": "Videa začnou rovnou videem s textem."
"rerenderHint": "Pokud chceš aktualizovat skladbu, kterou už máš hotovou, použij na její kartě možnost Znovu vyrenderovat."
},
"stalledDownload": {
"actionFailedDesc": "Zkus to prosím za chvilku znovu.",
+5 -24
View File
@@ -764,9 +764,7 @@
"regenerateStarted": "Gendanner din video. Vi sender dig en e-mail, når den er klar.",
"regenerateTime": "Det tager normalt 10–30 minutter. Vi sender dig en e-mail, når den er klar.",
"regenerateTitle": "Vil du gendanne denne video?",
"regenerateTooltip": "For at spare plads beholder ældre numre kun 720p-videoen og karaokepakkerne. Gendan de andre formater.",
"outdatedTheme": "Ældre tema",
"outdatedThemeTooltip": "Denne video blev lavet før din seneste temaændring. Genrender den for at opdatere dens udseende."
"regenerateTooltip": "For at spare plads beholder ældre numre kun 720p-videoen og karaokepakkerne. Gendan de andre formater."
},
"themeSelector": {
"videoTheme": "Videotema",
@@ -1978,6 +1976,7 @@
"tenantTheme": {
"advancedHint": "Rediger enhver temaindstilling direkte. Ændringer tjekkes, når du gemmer.",
"advancedJson": "Fuld tema-JSON",
"appliesToNewJobs": "Gemte ændringer gælder for videoer, du opretter fra nu af.",
"artistColour": "Farve på kunstnernavn",
"artistName": "Kunstnernavn",
"background": "Baggrund",
@@ -1988,6 +1987,7 @@
"description": "Tilpas, hvordan dine karaokevideoer ser ud. Forhåndsvisningerne til højre gengives præcis som dine færdige videoer.",
"discard": "Forkast ændringer",
"discardConfirm": "Du har ugemte temaændringer. Vil du lukke uden at gemme?",
"endScreenHint": "Slutskærmen forhåndsvises ikke; den bruger samme skrifttype og layoutstil som titelkortet.",
"font": "Skrifttype",
"fontHint": "Én skrifttype bruges til titelkortet, sangteksten og slutskærmen.",
"jsonInvalid": "Ugyldig JSON",
@@ -2011,6 +2011,7 @@
"sampleTitleDefault": "Sangtitel",
"save": "Gem tema",
"saveFailed": "Kunne ikke gemme dit tema",
"savedBody": "Nye videoer vil bruge dit opdaterede tema.",
"savedTitle": "Tema gemt",
"solidColour": "Ensfarvet (intet billede)",
"sungColour": "Farve på sunget tekst",
@@ -2032,27 +2033,7 @@
"close": "Luk",
"saving": "Gemmer…",
"songTitle": "Sangtitel",
"appliesToInProgress": "Gemte ændringer gælder for nye videoer og videoer, der stadig er i gang med at blive lavet.",
"finishedKeepOldLook": "Færdige videoer beholder deres gamle udseende, indtil du genrenderer dem.",
"outdatedFinished": "{count, plural, one {# færdig video har stadig det gamle udseende.} other {# færdige videoer har stadig det gamle udseende.}}",
"refreshedInProgress": "{count, plural, one {# video, der stadig er i gang med at blive lavet, bruger automatisk det nye udseende.} other {# videoer, der stadig er i gang med at blive lavet, bruger automatisk det nye udseende.}}",
"rerenderAll": "{count, plural, one {Genrender den nu} other {Genrender alle #}}",
"rerenderAllFailed": "Kunne ikke starte genrendering",
"rerenderAllSomeFailed": "{count, plural, one {# video kunne ikke genrenderes} other {# videoer kunne ikke genrenderes}}",
"rerenderAllStarted": "{count, plural, one {Genrenderer # video med dit nye tema. Det tager ca. 10-15 minutter; du kan følge status på nummeret.} other {Genrenderer # videoer med dit nye tema. Hver video tager ca. 10-15 minutter; du kan følge status på de enkelte numre.}}",
"rerenderAllStarting": "Starter…",
"savedBodyInProgress": "Nye videoer og videoer, der stadig er i gang med at blive lavet, vil bruge dit opdaterede tema.",
"copyTitleCardLayout": "Kopiér titelkortets layout",
"copyTitleCardLayoutHint": "Giv sangtitlen og kunstnernavnet her samme størrelse, placering, farver og store/små bogstaver som på dit titelkort.",
"endScreenFontHint": "Slutskærmen bruger samme skrifttype som titelkortet (skift den under fanen Titelkort).",
"endScreenOff": "Videoer slutter, når sangen slutter.",
"includeEndScreen": "Inkludér en slutskærm i slutningen af hver video",
"includeTitleCard": "Inkludér et titelkort i starten af hver video",
"previewEndScreen": "Forhåndsvisning af slutskærm",
"screenOmitted": "Ikke inkluderet i dine videoer",
"showArtistName": "Vis kunstnernavn",
"showSongTitle": "Vis sangtitel",
"titleCardOff": "Videoer starter med det samme med sangtekstvideoen."
"rerenderHint": "For at opdatere et nummer, du allerede har lavet, skal du bruge Render igen på dets kort."
},
"stalledDownload": {
"actionFailedDesc": "Prøv igen om et øjeblik.",
+5 -24
View File
@@ -764,9 +764,7 @@
"regenerateStarted": "Dein Video wird neu generiert. Wir benachrichtigen dich per E-Mail, sobald es fertig ist.",
"regenerateTime": "Das dauert normalerweise 10–30 Minuten. Wir benachrichtigen dich per E-Mail, sobald es fertig ist.",
"regenerateTitle": "Dieses Video neu generieren?",
"regenerateTooltip": "Um Speicherplatz zu sparen, behalten ältere Titel nur das 720p-Video und Karaoke-Pakete. Generiere die anderen Formate neu.",
"outdatedTheme": "Älteres Theme",
"outdatedThemeTooltip": "Dieses Video wurde vor deiner letzten Theme-Änderung erstellt. Rendere es erneut, um das Design zu aktualisieren."
"regenerateTooltip": "Um Speicherplatz zu sparen, behalten ältere Titel nur das 720p-Video und Karaoke-Pakete. Generiere die anderen Formate neu."
},
"themeSelector": {
"videoTheme": "Video-Theme",
@@ -1978,6 +1976,7 @@
"tenantTheme": {
"advancedHint": "Bearbeite jede Theme-Einstellung direkt. Änderungen werden beim Speichern überprüft.",
"advancedJson": "Vollständiges Theme-JSON",
"appliesToNewJobs": "Gespeicherte Änderungen gelten für Videos, die du ab jetzt erstellst.",
"artistColour": "Farbe des Künstlernamens",
"artistName": "Künstlername",
"background": "Hintergrund",
@@ -1988,6 +1987,7 @@
"description": "Passe das Aussehen deiner Karaoke-Videos an. Die Vorschauen auf der rechten Seite werden genau wie deine fertigen Videos gerendert.",
"discard": "Änderungen verwerfen",
"discardConfirm": "Du hast ungespeicherte Theme-Änderungen. Ohne Speichern schließen?",
"endScreenHint": "Für den Endbildschirm gibt es keine Vorschau; er verwendet dieselbe Schriftart und denselben Layout-Stil wie die Titelkarte.",
"font": "Schriftart",
"fontHint": "Für die Titelkarte, den Text und den Endbildschirm wird dieselbe Schriftart verwendet.",
"jsonInvalid": "Ungültiges JSON",
@@ -2011,6 +2011,7 @@
"sampleTitleDefault": "Songtitel",
"save": "Theme speichern",
"saveFailed": "Dein Theme konnte nicht gespeichert werden",
"savedBody": "Neue Videos werden dein aktualisiertes Theme verwenden.",
"savedTitle": "Theme gespeichert",
"solidColour": "Einfarbig (kein Bild)",
"sungColour": "Farbe für gesungenen Text",
@@ -2032,27 +2033,7 @@
"close": "Schließen",
"saving": "Speichere…",
"songTitle": "Songtitel",
"appliesToInProgress": "Gespeicherte Änderungen gelten für neue Videos und für Videos, die noch in Bearbeitung sind.",
"finishedKeepOldLook": "Fertige Videos behalten ihr altes Design, bis du sie erneut renderst.",
"outdatedFinished": "{count, plural, one {# fertiges Video hat noch das alte Design.} other {# fertige Videos haben noch das alte Design.}}",
"refreshedInProgress": "{count, plural, one {# Video, das noch in Bearbeitung ist, verwendet automatisch das neue Design.} other {# Videos, die noch in Bearbeitung sind, verwenden automatisch das neue Design.}}",
"rerenderAll": "{count, plural, one {Jetzt erneut rendern} other {Alle # erneut rendern}}",
"rerenderAllFailed": "Das erneute Rendern konnte nicht gestartet werden",
"rerenderAllSomeFailed": "{count, plural, one {# Video konnte nicht erneut gerendert werden} other {# Videos konnten nicht erneut gerendert werden}}",
"rerenderAllStarted": "{count, plural, one {# Video wird mit deinem neuen Theme erneut gerendert. Es dauert etwa 10–15 Minuten; du kannst den Fortschritt beim Track mitverfolgen.} other {# Videos werden mit deinem neuen Theme erneut gerendert. Jedes dauert etwa 10–15 Minuten; du kannst den Fortschritt bei jedem Track mitverfolgen.}}",
"rerenderAllStarting": "Wird gestartet…",
"savedBodyInProgress": "Neue Videos und Videos, die noch in Bearbeitung sind, verwenden dein aktualisiertes Theme.",
"copyTitleCardLayout": "Titelkarten-Layout kopieren",
"copyTitleCardLayoutHint": "Gib Songtitel und Interpretenname hier dieselbe Größe, Position, Farben und Großschreibung wie auf deiner Titelkarte.",
"endScreenFontHint": "Der Endbildschirm verwendet dieselbe Schriftart wie die Titelkarte (ändere sie im Reiter „Titelkarte“).",
"endScreenOff": "Videos enden, wenn der Song endet.",
"includeEndScreen": "Einen Endbildschirm am Ende jedes Videos einfügen",
"includeTitleCard": "Eine Titelkarte am Anfang jedes Videos einfügen",
"previewEndScreen": "Endbildschirm-Vorschau",
"screenOmitted": "Nicht in deinen Videos enthalten",
"showArtistName": "Interpretenname anzeigen",
"showSongTitle": "Songtitel anzeigen",
"titleCardOff": "Videos starten direkt mit dem Songtext-Video."
"rerenderHint": "Um einen Track zu aktualisieren, den du bereits erstellt hast, verwende „Neu rendern“ auf dessen Karte."
},
"stalledDownload": {
"actionFailedDesc": "Bitte versuche es gleich noch einmal.",
+5 -24
View File
@@ -764,9 +764,7 @@
"regenerateStarted": "Γίνεται αναδημιουργία του βίντεό σου. Θα σου στείλουμε email μόλις είναι έτοιμο.",
"regenerateTime": "Συνήθως διαρκεί 10–30 λεπτά. Θα σου στείλουμε email μόλις είναι έτοιμο.",
"regenerateTitle": "Αναδημιουργία αυτού του βίντεο;",
"regenerateTooltip": "Για εξοικονόμηση χώρου, για τα παλαιότερα κομμάτια διατηρούνται μόνο το βίντεο 720p και τα πακέτα καραόκε. Αναδημιούργησε τις υπόλοιπες μορφές.",
"outdatedTheme": "Παλαιότερο θέμα",
"outdatedThemeTooltip": "Αυτό το βίντεο δημιουργήθηκε πριν από την τελευταία αλλαγή θέματος. Κάνε εκ νέου απόδοση (re-render) για να ανανεώσεις την εμφάνισή του."
"regenerateTooltip": "Για εξοικονόμηση χώρου, για τα παλαιότερα κομμάτια διατηρούνται μόνο το βίντεο 720p και τα πακέτα καραόκε. Αναδημιούργησε τις υπόλοιπες μορφές."
},
"themeSelector": {
"videoTheme": "Θέμα Βίντεο",
@@ -1978,6 +1976,7 @@
"tenantTheme": {
"advancedHint": "Επεξεργάσου απευθείας οποιαδήποτε ρύθμιση θέματος. Οι αλλαγές ελέγχονται όταν αποθηκεύεις.",
"advancedJson": "Πλήρες JSON θέματος",
"appliesToNewJobs": "Οι αποθηκευμένες αλλαγές ισχύουν για τα βίντεο που δημιουργείς από εδώ και στο εξής.",
"artistColour": "Χρώμα ονόματος καλλιτέχνη",
"artistName": "Όνομα καλλιτέχνη",
"background": "Φόντο",
@@ -1988,6 +1987,7 @@
"description": "Προσάρμοσε την εμφάνιση των βίντεο καραόκε σου. Οι προεπισκοπήσεις στα δεξιά αποδίδονται ακριβώς όπως τα τελικά σου βίντεο.",
"discard": "Απόρριψη αλλαγών",
"discardConfirm": "Έχεις μη αποθηκευμένες αλλαγές θέματος. Κλείσιμο χωρίς αποθήκευση;",
"endScreenHint": "Δεν υπάρχει προεπισκόπηση της τελικής οθόνης· χρησιμοποιεί την ίδια γραμματοσειρά και στυλ διάταξης με την κάρτα τίτλου.",
"font": "Γραμματοσειρά",
"fontHint": "Μία γραμματοσειρά χρησιμοποιείται για την κάρτα τίτλου, τους στίχους και την τελική οθόνη.",
"jsonInvalid": "Μη έγκυρο JSON",
@@ -2011,6 +2011,7 @@
"sampleTitleDefault": "Τίτλος τραγουδιού",
"save": "Αποθήκευση θέματος",
"saveFailed": "Δεν ήταν δυνατή η αποθήκευση του θέματός σου",
"savedBody": "Τα νέα βίντεο θα χρησιμοποιούν το ενημερωμένο θέμα σου.",
"savedTitle": "Το θέμα αποθηκεύτηκε",
"solidColour": "Μονόχρωμο (χωρίς εικόνα)",
"sungColour": "Χρώμα τραγουδισμένων στίχων",
@@ -2032,27 +2033,7 @@
"close": "Κλείσιμο",
"saving": "Αποθήκευση…",
"songTitle": "Τίτλος τραγουδιού",
"appliesToInProgress": "Οι αποθηκευμένες αλλαγές εφαρμόζονται σε νέα βίντεο και σε βίντεο που βρίσκονται ακόμη υπό δημιουργία.",
"finishedKeepOldLook": "Τα ολοκληρωμένα βίντεο διατηρούν την παλιά τους εμφάνιση μέχρι να κάνεις εκ νέου απόδοση.",
"outdatedFinished": "{count, plural, one {# ολοκληρωμένο βίντεο έχει ακόμα την παλιά εμφάνιση.} other {# ολοκληρωμένα βίντεο έχουν ακόμα την παλιά εμφάνιση.}}",
"refreshedInProgress": "{count, plural, one {# βίντεο που βρίσκεται ακόμη υπό δημιουργία θα αποκτήσει αυτόματα τη νέα εμφάνιση.} other {# βίντεο που βρίσκονται ακόμη υπό δημιουργία θα αποκτήσουν αυτόματα τη νέα εμφάνιση.}}",
"rerenderAll": "{count, plural, one {Εκ νέου απόδοση τώρα} other {Εκ νέου απόδοση και για τα #}}",
"rerenderAllFailed": "Δεν ήταν δυνατή η έναρξη της εκ νέου απόδοσης",
"rerenderAllSomeFailed": "{count, plural, one {Δεν ήταν δυνατή η εκ νέου απόδοση # βίντεο} other {Δεν ήταν δυνατή η εκ νέου απόδοση # βίντεο}}",
"rerenderAllStarted": "{count, plural, one {Γίνεται εκ νέου απόδοση σε # βίντεο με το νέο σου θέμα. Χρειάζονται περίπου 10-15 λεπτά· μπορείς να παρακολουθείς την πρόοδό του στο κομμάτι.} other {Γίνεται εκ νέου απόδοση σε # βίντεο με το νέο σου θέμα. Το καθένα χρειάζεται περίπου 10-15 λεπτά· μπορείς να παρακολουθείς την πρόοδό τους σε κάθε κομμάτι.}}",
"rerenderAllStarting": "Έναρξη…",
"savedBodyInProgress": "Τα νέα βίντεο, καθώς και τα βίντεο που βρίσκονται ακόμη υπό δημιουργία, θα χρησιμοποιούν το ανανεωμένο σου θέμα.",
"copyTitleCardLayout": "Αντιγραφή διάταξης κάρτας τίτλου",
"copyTitleCardLayoutHint": "Εφάρμοσε στον τίτλο του τραγουδιού και στο όνομα του καλλιτέχνη εδώ το ίδιο μέγεθος, θέση, χρώματα και κεφαλαία όπως στην κάρτα τίτλου σου.",
"endScreenFontHint": "Η τελική οθόνη χρησιμοποιεί την ίδια γραμματοσειρά με την κάρτα τίτλου (άλλαξέ την στην καρτέλα «Κάρτα τίτλου»).",
"endScreenOff": "Τα βίντεο θα τελειώνουν όταν τελειώνει το τραγούδι.",
"includeEndScreen": "Συμπερίληψη τελικής οθόνης στο τέλος κάθε βίντεο",
"includeTitleCard": "Συμπερίληψη κάρτας τίτλου στην αρχή κάθε βίντεο",
"previewEndScreen": "Προεπισκόπηση τελικής οθόνης",
"screenOmitted": "Δεν περιλαμβάνεται στα βίντεό σου",
"showArtistName": "Εμφάνιση ονόματος καλλιτέχνη",
"showSongTitle": "Εμφάνιση τίτλου τραγουδιού",
"titleCardOff": "Τα βίντεο θα ξεκινούν αμέσως με το βίντεο των στίχων."
"rerenderHint": "Για να ενημερώσεις ένα κομμάτι που έχεις ήδη φτιάξει, χρησιμοποίησε την επιλογή «Επαναδημιουργία» στην κάρτα του."
},
"stalledDownload": {
"actionFailedDesc": "Δοκίμασε ξανά σε λίγο.",
+5 -24
View File
@@ -777,9 +777,7 @@
"regenerateNoRepublish": "Your YouTube, Dropbox and Google Drive links stay as they are.",
"regenerateTime": "It usually takes 10–30 minutes. We'll email you when it's ready.",
"regenerateStarted": "Regenerating your video. We'll email you when it's ready.",
"regenerateFailed": "Couldn't start regenerating: {error}",
"outdatedTheme": "Older theme",
"outdatedThemeTooltip": "This video was made before your latest theme change. Re-render it to update its look."
"regenerateFailed": "Couldn't start regenerating: {error}"
},
"themeSelector": {
"videoTheme": "Video Theme",
@@ -1987,10 +1985,6 @@
"endScreen": "End screen",
"advanced": "Advanced"
},
"includeTitleCard": "Include a title card at the start of each video",
"titleCardOff": "Videos will start straight away with the lyrics video.",
"includeEndScreen": "Include an end screen at the end of each video",
"endScreenOff": "Videos will end when the song ends.",
"background": "Background",
"backgroundImage": "Background image",
"solidColour": "Solid colour (no image)",
@@ -2016,11 +2010,7 @@
"lineLength": "Max characters per line",
"closingMessage": "Closing message",
"closingMessageColour": "Closing message colour",
"showSongTitle": "Show the song title",
"showArtistName": "Show the artist name",
"copyTitleCardLayout": "Copy title card layout",
"copyTitleCardLayoutHint": "Give the song title and artist name here the same size, position, colours and capitals as on your title card.",
"endScreenFontHint": "The end screen uses the same font as the title card (change it on the Title card tab).",
"endScreenHint": "The end screen isn't previewed; it uses the same font and layout style as the title card.",
"advancedJson": "Full theme JSON",
"advancedHint": "Edit any theme setting directly. Changes are checked when you save.",
"jsonInvalid": "Invalid JSON",
@@ -2031,28 +2021,19 @@
"sampleTitleDefault": "Song Title",
"previewTitleCard": "Title card preview",
"previewKaraoke": "Lyrics video preview",
"previewEndScreen": "End screen preview",
"screenOmitted": "Not included in your videos",
"rendering": "Rendering preview",
"previewFailed": "The preview couldn't be rendered.",
"previewHint": "Previews update a moment after each change. Nothing is saved until you click Save.",
"appliesToNewJobs": "Saved changes apply to videos you create from now on.",
"discard": "Discard changes",
"close": "Close",
"save": "Save theme",
"saving": "Saving…",
"savedTitle": "Theme saved",
"savedBody": "New videos will use your updated theme.",
"saveFailed": "Couldn't save your theme",
"discardConfirm": "You have unsaved theme changes. Close without saving?",
"appliesToInProgress": "Saved changes apply to new videos and to videos that are still being made.",
"finishedKeepOldLook": "Finished videos keep their old look until you re-render them.",
"savedBodyInProgress": "New videos, and videos still being made, will use your updated theme.",
"refreshedInProgress": "{count, plural, one {# video that's still being made will use the new look automatically.} other {# videos that are still being made will use the new look automatically.}}",
"outdatedFinished": "{count, plural, one {# finished video still has the old look.} other {# finished videos still have the old look.}}",
"rerenderAll": "{count, plural, one {Re-render it now} other {Re-render all #}}",
"rerenderAllStarting": "Starting…",
"rerenderAllStarted": "{count, plural, one {Re-rendering # video with your new theme. It takes about 10-15 minutes; you can follow its progress on the track.} other {Re-rendering # videos with your new theme. Each takes about 10-15 minutes; you can follow their progress on each track.}}",
"rerenderAllSomeFailed": "{count, plural, one {# video couldn't be re-rendered} other {# videos couldn't be re-rendered}}",
"rerenderAllFailed": "Couldn't start the re-render"
"rerenderHint": "To update a track you've already made, use Re-render on its card."
},
"stalledDownload": {
"title": "Your audio hasn't started downloading after {minutes} minutes",
+5 -24
View File
@@ -764,9 +764,7 @@
"regenerateStarted": "Regenerando tu video. Te enviaremos un correo electrónico cuando esté listo.",
"regenerateTime": "Suele tardar entre 10 y 30 minutos. Te enviaremos un correo electrónico cuando esté listo.",
"regenerateTitle": "¿Regenerar este video?",
"regenerateTooltip": "Para ahorrar espacio, las pistas más antiguas solo conservan el video en 720p y los paquetes de karaoke. Regenera los demás formatos.",
"outdatedTheme": "Tema anterior",
"outdatedThemeTooltip": "Este video se creó antes de tu último cambio de tema. Vuelve a renderizarlo para actualizar su aspecto."
"regenerateTooltip": "Para ahorrar espacio, las pistas más antiguas solo conservan el video en 720p y los paquetes de karaoke. Regenera los demás formatos."
},
"themeSelector": {
"videoTheme": "Tema de video",
@@ -1978,6 +1976,7 @@
"tenantTheme": {
"advancedHint": "Edita cualquier ajuste del tema directamente. Los cambios se comprueban al guardar.",
"advancedJson": "JSON completo del tema",
"appliesToNewJobs": "Los cambios guardados se aplican a los videos que crees a partir de ahora.",
"artistColour": "Color del nombre del artista",
"artistName": "Nombre del artista",
"background": "Fondo",
@@ -1988,6 +1987,7 @@
"description": "Personaliza el aspecto de tus videos de karaoke. Las vistas previas de la derecha se renderizan exactamente igual que tus videos terminados.",
"discard": "Descartar cambios",
"discardConfirm": "Tienes cambios sin guardar en el tema. ¿Cerrar sin guardar?",
"endScreenHint": "La pantalla final no tiene vista previa; usa la misma fuente y estilo de diseño que la tarjeta de título.",
"font": "Fuente",
"fontHint": "Se usa una sola fuente para la tarjeta de título, las letras y la pantalla final.",
"jsonInvalid": "JSON no válido",
@@ -2011,6 +2011,7 @@
"sampleTitleDefault": "Título de la canción",
"save": "Guardar tema",
"saveFailed": "No se pudo guardar tu tema",
"savedBody": "Los nuevos videos usarán tu tema actualizado.",
"savedTitle": "Tema guardado",
"solidColour": "Color sólido (sin imagen)",
"sungColour": "Color de las letras cantadas",
@@ -2032,27 +2033,7 @@
"close": "Cerrar",
"saving": "Guardando…",
"songTitle": "Título de la canción",
"appliesToInProgress": "Los cambios guardados se aplican a los videos nuevos y a los videos que aún se están creando.",
"finishedKeepOldLook": "Los videos finalizados mantienen su aspecto anterior hasta que los vuelvas a renderizar.",
"outdatedFinished": "{count, plural, one {# video finalizado todavía tiene el aspecto anterior.} other {# videos finalizados todavía tienen el aspecto anterior.}}",
"refreshedInProgress": "{count, plural, one {# video que aún se está creando usará el aspecto nuevo automáticamente.} other {# videos que aún se están creando usarán el aspecto nuevo automáticamente.}}",
"rerenderAll": "{count, plural, one {Volver a renderizarlo ahora} other {Volver a renderizar los #}}",
"rerenderAllFailed": "No se pudo iniciar el nuevo renderizado",
"rerenderAllSomeFailed": "{count, plural, one {No se pudo volver a renderizar # video} other {No se pudieron volver a renderizar # videos}}",
"rerenderAllStarted": "{count, plural, one {Renderizando # video con tu nuevo tema. Tarda unos 10-15 minutos; puedes seguir su progreso en la pista.} other {Renderizando # videos con tu nuevo tema. Cada uno tarda unos 10-15 minutos; puedes seguir su progreso en cada pista.}}",
"rerenderAllStarting": "Iniciando…",
"savedBodyInProgress": "Los videos nuevos y los videos que aún se están creando usarán tu tema actualizado.",
"copyTitleCardLayout": "Copiar diseño de la tarjeta de título",
"copyTitleCardLayoutHint": "Aplica aquí al título de la canción y al nombre del artista el mismo tamaño, posición, colores y mayúsculas que en tu tarjeta de título.",
"endScreenFontHint": "La pantalla final usa la misma fuente que la tarjeta de título (cámbiala en la pestaña Tarjeta de título).",
"endScreenOff": "Los videos terminarán cuando termine la canción.",
"includeEndScreen": "Incluir una pantalla final al final de cada video",
"includeTitleCard": "Incluir una tarjeta de título al inicio de cada video",
"previewEndScreen": "Vista previa de la pantalla final",
"screenOmitted": "No incluido en tus videos",
"showArtistName": "Mostrar el nombre del artista",
"showSongTitle": "Mostrar el título de la canción",
"titleCardOff": "Los videos comenzarán directamente con el video de letras."
"rerenderHint": "Para actualizar una pista que ya creaste, usa Volver a renderizar en su tarjeta."
},
"stalledDownload": {
"actionFailedDesc": "Por favor, inténtalo de nuevo en un momento.",
+5 -24
View File
@@ -764,9 +764,7 @@
"regenerateStarted": "Videotasi luodaan uudelleen. Saat sähköpostia, kun se on valmis.",
"regenerateTime": "Tähän menee yleensä 10–30 minuuttia. Saat sähköpostia, kun se on valmis.",
"regenerateTitle": "Luodaanko tämä video uudelleen?",
"regenerateTooltip": "Tilan säästämiseksi vanhemmista kappaleista säilytetään vain 720p-video ja karaokepaketit. Luo muut tiedostomuodot uudelleen.",
"outdatedTheme": "Vanhempi teema",
"outdatedThemeTooltip": "Tämä video on luotu ennen viimeisintä teemamuutostasi. Renderöi se uudelleen päivittääksesi sen ulkoasun."
"regenerateTooltip": "Tilan säästämiseksi vanhemmista kappaleista säilytetään vain 720p-video ja karaokepaketit. Luo muut tiedostomuodot uudelleen."
},
"themeSelector": {
"videoTheme": "Videoteema",
@@ -1978,6 +1976,7 @@
"tenantTheme": {
"advancedHint": "Muokkaa mitä tahansa teema-asetusta suoraan. Muutokset tarkistetaan tallentaessasi.",
"advancedJson": "Koko teeman JSON",
"appliesToNewJobs": "Tallennetut muutokset koskevat videoita, joita luot tästä eteenpäin.",
"artistColour": "Esittäjän nimen väri",
"artistName": "Esittäjän nimi",
"background": "Tausta",
@@ -1988,6 +1987,7 @@
"description": "Mukauta karaokevideoidesi ulkoasua. Oikealla olevat esikatselut renderöidään täsmälleen kuten valmiit videosi.",
"discard": "Hylkää muutokset",
"discardConfirm": "Sinulla on tallentamattomia teemamuutoksia. Haluatko sulkea tallentamatta?",
"endScreenHint": "Loppuruutua ei esikatsella; se käyttää samaa fonttia ja asettelutyyliä kuin otsikkoruutu.",
"font": "Fontti",
"fontHint": "Samaa fonttia käytetään otsikkoruudussa, sanoituksissa ja loppuruudussa.",
"jsonInvalid": "Virheellinen JSON",
@@ -2011,6 +2011,7 @@
"sampleTitleDefault": "Kappaleen nimi",
"save": "Tallenna teema",
"saveFailed": "Teemasi tallentaminen epäonnistui",
"savedBody": "Uudet videot käyttävät päivitettyä teemaasi.",
"savedTitle": "Teema tallennettu",
"solidColour": "Yksivärinen (ei kuvaa)",
"sungColour": "Laulettujen sanoitusten väri",
@@ -2032,27 +2033,7 @@
"close": "Sulje",
"saving": "Tallennetaan…",
"songTitle": "Kappaleen nimi",
"appliesToInProgress": "Tallennetut muutokset koskevat uusia videoita sekä tekeillä olevia videoita.",
"finishedKeepOldLook": "Valmiit videot säilyttävät vanhan ulkoasunsa, kunnes renderöit ne uudelleen.",
"outdatedFinished": "{count, plural, one {# valmiissa videossa on vielä vanha ulkoasu.} other {# valmiissa videossa on vielä vanha ulkoasu.}}",
"refreshedInProgress": "{count, plural, one {# tekeillä oleva video käyttää uutta ulkoasua automaattisesti.} other {# tekeillä olevaa videota käyttää uutta ulkoasua automaattisesti.}}",
"rerenderAll": "{count, plural, one {Renderöi se uudelleen nyt} other {Renderöi kaikki # uudelleen}}",
"rerenderAllFailed": "Uudelleenrenderöintiä ei voitu aloittaa",
"rerenderAllSomeFailed": "{count, plural, one {# videota ei voitu renderöidä uudelleen} other {# videota ei voitu renderöidä uudelleen}}",
"rerenderAllStarted": "{count, plural, one {Renderöidään # video uudelleen uudella teemallasi. Siinä kestää noin 10–15 minuuttia, ja voit seurata edistymistä kappaleen tiedoissa.} other {Renderöidään # videota uudelleen uudella teemallasi. Kussakin kestää noin 10–15 minuuttia, ja voit seurata edistymistä kunkin kappaleen tiedoissa.}}",
"rerenderAllStarting": "Aloitetaan…",
"savedBodyInProgress": "Uudet ja tekeillä olevat videot käyttävät päivitettyä teemaasi.",
"copyTitleCardLayout": "Kopioi nimikortin asettelu",
"copyTitleCardLayoutHint": "Käytä kappaleen nimeen ja esittäjään samaa kokoa, sijaintia, värejä ja kirjainkokoa kuin nimikortissasi.",
"endScreenFontHint": "Loppuruudussa käytetään samaa fonttia kuin nimikortissa (vaihda se Nimikortti-välilehdellä).",
"endScreenOff": "Videot päättyvät heti, kun kappale päättyy.",
"includeEndScreen": "Lisää loppuruutu jokaisen videon loppuun",
"includeTitleCard": "Lisää nimikortti jokaisen videon alkuun",
"previewEndScreen": "Loppuruudun esikatselu",
"screenOmitted": "Ei mukana videoissasi",
"showArtistName": "Näytä esittäjän nimi",
"showSongTitle": "Näytä kappaleen nimi",
"titleCardOff": "Videot alkavat heti sanoituksilla."
"rerenderHint": "Jos haluat päivittää jo tekemäsi kappaleen, käytä sen kortissa olevaa Renderöi uudelleen -toimintoa."
},
"stalledDownload": {
"actionFailedDesc": "Yritä hetken kuluttua uudelleen.",
+5 -24
View File
@@ -764,9 +764,7 @@
"regenerateStarted": "Régénération de ta vidéo en cours. Nous t'enverrons un e-mail dès qu'elle sera prête.",
"regenerateTime": "Cela prend généralement de 10 à 30 minutes. Nous t'enverrons un e-mail dès que ce sera prêt.",
"regenerateTitle": "Régénérer cette vidéo ?",
"regenerateTooltip": "Pour économiser de l'espace, les anciens morceaux ne conservent que la vidéo 720p et les packages karaoké. Régénère les autres formats.",
"outdatedTheme": "Ancien thème",
"outdatedThemeTooltip": "Cette vidéo a été créée avant ton dernier changement de thème. Relance le rendu pour actualiser son apparence."
"regenerateTooltip": "Pour économiser de l'espace, les anciens morceaux ne conservent que la vidéo 720p et les packages karaoké. Régénère les autres formats."
},
"themeSelector": {
"videoTheme": "Thème vidéo",
@@ -1978,6 +1976,7 @@
"tenantTheme": {
"advancedHint": "Modifie directement n'importe quel paramètre du thème. Les modifications sont vérifiées lorsque tu enregistres.",
"advancedJson": "JSON complet du thème",
"appliesToNewJobs": "Les modifications enregistrées s'appliquent aux vidéos que tu créeras à partir de maintenant.",
"artistColour": "Couleur du nom de l'artiste",
"artistName": "Nom de l'artiste",
"background": "Arrière-plan",
@@ -1988,6 +1987,7 @@
"description": "Personnalise l'apparence de tes vidéos karaoké. Les aperçus à droite sont générés exactement comme tes vidéos finales.",
"discard": "Abandonner les modifications",
"discardConfirm": "Tu as des modifications non enregistrées sur ce thème. Fermer sans enregistrer ?",
"endScreenHint": "L'écran de fin n'a pas d'aperçu ; il utilise la même police et la même mise en page que l'écran de titre.",
"font": "Police",
"fontHint": "Une seule et même police est utilisée pour l'écran de titre, les paroles et l'écran de fin.",
"jsonInvalid": "JSON non valide",
@@ -2011,6 +2011,7 @@
"sampleTitleDefault": "Titre du morceau",
"save": "Enregistrer le thème",
"saveFailed": "Impossible d'enregistrer ton thème",
"savedBody": "Les nouvelles vidéos utiliseront ton thème mis à jour.",
"savedTitle": "Thème enregistré",
"solidColour": "Couleur unie (sans image)",
"sungColour": "Couleur des paroles chantées",
@@ -2032,27 +2033,7 @@
"close": "Fermer",
"saving": "Enregistrement…",
"songTitle": "Titre de la chanson",
"appliesToInProgress": "Les modifications enregistrées s'appliquent aux nouvelles vidéos et à celles qui sont encore en cours de création.",
"finishedKeepOldLook": "Les vidéos terminées conservent leur ancienne apparence jusqu'à ce que tu relances leur rendu.",
"outdatedFinished": "{count, plural, one {# vidéo terminée a encore l'ancienne apparence.} other {# vidéos terminées ont encore l'ancienne apparence.}}",
"refreshedInProgress": "{count, plural, one {# vidéo encore en cours de création utilisera automatiquement la nouvelle apparence.} other {# vidéos encore en cours de création utiliseront automatiquement la nouvelle apparence.}}",
"rerenderAll": "{count, plural, one {Relancer le rendu maintenant} other {Tout relancer (#)}}",
"rerenderAllFailed": "Impossible de lancer le nouveau rendu",
"rerenderAllSomeFailed": "{count, plural, one {# vidéo n'a pas pu être recalculée} other {# vidéos n'ont pas pu être recalculées}}",
"rerenderAllStarted": "{count, plural, one {Nouveau rendu en cours pour # vidéo avec ton nouveau thème. Cela prend environ 10 à 15 minutes ; tu peux suivre sa progression sur le morceau.} other {Nouveau rendu en cours pour # vidéos avec ton nouveau thème. Chaque vidéo prend environ 10 à 15 minutes ; tu peux suivre leur progression sur chaque morceau.}}",
"rerenderAllStarting": "Démarrage…",
"savedBodyInProgress": "Les nouvelles vidéos, ainsi que celles encore en cours de création, utiliseront ton thème mis à jour.",
"copyTitleCardLayout": "Copier la mise en page du carton de titre",
"copyTitleCardLayoutHint": "Applique ici au titre du morceau et au nom de l'artiste les mêmes taille, position, couleurs et majuscules que sur ton carton de titre.",
"endScreenFontHint": "L'écran de fin utilise la même police que le carton de titre (modifie-la dans l'onglet Carton de titre).",
"endScreenOff": "Les vidéos se termineront à la fin de la chanson.",
"includeEndScreen": "Inclure un écran de fin à la fin de chaque vidéo",
"includeTitleCard": "Inclure un carton de titre au début de chaque vidéo",
"previewEndScreen": "Aperçu de l'écran de fin",
"screenOmitted": "Non inclus dans tes vidéos",
"showArtistName": "Afficher le nom de l'artiste",
"showSongTitle": "Afficher le titre de la chanson",
"titleCardOff": "Les vidéos commenceront directement avec les paroles."
"rerenderHint": "Pour mettre à jour un morceau que tu as déjà créé, utilise « Relancer le rendu » sur sa carte."
},
"stalledDownload": {
"actionFailedDesc": "Réessaie dans un instant.",
+5 -24
View File
@@ -764,9 +764,7 @@
"regenerateStarted": "מייצר את הווידאו שלך מחדש. נשלח לך אימייל כשהוא יהיה מוכן.",
"regenerateTime": "בדרך כלל זה לוקח 10–30 דקות. נשלח לך אימייל כשהוא יהיה מוכן.",
"regenerateTitle": "ליצור מחדש את הווידאו הזה?",
"regenerateTooltip": "כדי לחסוך במקום, עבור שירים ישנים יותר נשמרים רק הווידאו ב-720p וחבילות הקריוקי. ניתן ליצור מחדש את שאר הפורמטים.",
"outdatedTheme": "ערכת נושא קודמת",
"outdatedThemeTooltip": "הסרטון הזה נוצר לפני השינוי האחרון בערכת הנושא. אפשר לרנדר אותו מחדש כדי לעדכן את המראה שלו."
"regenerateTooltip": "כדי לחסוך במקום, עבור שירים ישנים יותר נשמרים רק הווידאו ב-720p וחבילות הקריוקי. ניתן ליצור מחדש את שאר הפורמטים."
},
"themeSelector": {
"videoTheme": "ערכת נושא לוידאו",
@@ -1978,6 +1976,7 @@
"tenantTheme": {
"advancedHint": "ערכו כל הגדרה בערכת הנושא ישירות. השינויים ייבדקו בעת השמירה.",
"advancedJson": "JSON מלא של ערכת הנושא",
"appliesToNewJobs": "השינויים שנשמרו יחולו על סרטונים שתיצרו מעכשיו והלאה.",
"artistColour": "צבע שם האמן",
"artistName": "שם האמן",
"background": "רקע",
@@ -1988,6 +1987,7 @@
"description": "התאימו אישית את המראה של סרטוני הקריוקי שלכם. התצוגות המקדימות בצד מוצגות בדיוק כפי שייראו הסרטונים המוכנים שלכם.",
"discard": "ביטול שינויים",
"discardConfirm": "יש לכם שינויים שלא נשמרו בערכת הנושא. לסגור מבלי לשמור?",
"endScreenHint": "אין תצוגה מקדימה למסך הסיום; הוא משתמש באותו גופן וסגנון פריסה כמו מסך הפתיחה.",
"font": "גופן",
"fontHint": "אותו גופן משמש עבור מסך הפתיחה, המילים ומסך הסיום.",
"jsonInvalid": "JSON לא תקין",
@@ -2011,6 +2011,7 @@
"sampleTitleDefault": "שם השיר",
"save": "שמירת ערכת הנושא",
"saveFailed": "לא ניתן היה לשמור את ערכת הנושא",
"savedBody": "סרטונים חדשים ישתמשו בערכת הנושא המעודכנת שלכם.",
"savedTitle": "ערכת הנושא נשמרה",
"solidColour": "צבע אחיד (ללא תמונה)",
"sungColour": "צבע מילים שהושרו",
@@ -2032,27 +2033,7 @@
"close": "סגירה",
"saving": "שומר…",
"songTitle": "שם השיר",
"appliesToInProgress": "שינויים שנשמרו יחולו על סרטונים חדשים ועל סרטונים שעדיין נמצאים בהכנה.",
"finishedKeepOldLook": "סרטונים מוכנים ישמרו על המראה הישן שלהם עד שתרנדרו אותם מחדש.",
"outdatedFinished": "{count, plural, one {סרטון מוכן אחד (#) עדיין נשאר עם המראה הישן.} other {# סרטונים מוכנים עדיין נשארים עם המראה הישן.}}",
"refreshedInProgress": "{count, plural, one {סרטון אחד (#) שעדיין נמצא בהכנה ישתמש במראה החדש באופן אוטומטי.} other {# סרטונים שעדיין נמצאים בהכנה ישתמשו במראה החדש באופן אוטומטי.}}",
"rerenderAll": "{count, plural, one {רינדור מחדש עכשיו} other {רינדור מחדש של כל ה-#}}",
"rerenderAllFailed": "לא הצלחנו להתחיל את הרינדור מחדש",
"rerenderAllSomeFailed": "{count, plural, one {לא הצלחנו לרנדר מחדש סרטון אחד (#)} other {לא הצלחנו לרנדר מחדש # סרטונים}}",
"rerenderAllStarted": "{count, plural, one {מרנדרים מחדש סרטון אחד (#) עם ערכת הנושא החדשה. זה לוקח בערך 10–15 דקות; אפשר לעקוב אחר ההתקדמות ברצועה.} other {מרנדרים מחדש # סרטונים עם ערכת הנושא החדשה. כל סרטון לוקח בערך 10–15 דקות; אפשר לעקוב אחר ההתקדמות בכל רצועה.}}",
"rerenderAllStarting": "מתחיל…",
"savedBodyInProgress": "סרטונים חדשים, וסרטונים שעדיין נמצאים בהכנה, ישתמשו בערכת הנושא המעודכנת.",
"copyTitleCardLayout": "העתקת פריסת כרטיסיית הכותרת",
"copyTitleCardLayoutHint": "החלת אותו גודל, מיקום, צבעים ואותיות רישיות על שם השיר ושם האמן כאן, בדיוק כמו בכרטיסיית הכותרת שלך.",
"endScreenFontHint": "מסך הסיום משתמש באותו גופן כמו כרטיסיית הכותרת (ניתן לשנות זאת בלשונית 'כרטיסיית כותרת').",
"endScreenOff": "הסרטונים יסתיימו כשהשיר מסתיים.",
"includeEndScreen": "הוספת מסך סיום בסוף כל סרטון",
"includeTitleCard": "הוספת כרטיסיית כותרת בתחילת כל סרטון",
"previewEndScreen": "תצוגה מקדימה של מסך הסיום",
"screenOmitted": "לא נכלל בסרטונים שלך",
"showArtistName": "הצגת שם האמן",
"showSongTitle": "הצגת שם השיר",
"titleCardOff": "הסרטונים יתחילו מיד עם סרטון המילים."
"rerenderHint": "כדי לעדכן רצועה שכבר יצרת, אפשר להשתמש ב״רינדור מחדש״ בכרטיס שלה."
},
"stalledDownload": {
"actionFailedDesc": "אנא נסו שוב בעוד רגע.",
Loaded 100 of 133 files, more files were not shown because too many files have changed in this diff. Show more