Compare commits

...
13 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 4.6 105a5b28fd fix: default dashboard to all jobs, fix E2E completion detection (#655)
## Summary
- Default the dashboard status filter from "active" to "all" so
completed jobs remain visible (existing localStorage preferences
preserved)
- Add recovery logic to E2E happy path test: after 10 consecutive "card
unavailable" polls, automatically switch the filter dropdown to "All
statuses"
- Bump version to 0.157.4

**Root cause:** The daily E2E test (run #126) timed out at Step 9
because the "active" filter uses `hide_completed: true` at the API level
— when the job completed, the card vanished from the DOM and the test
retried for ~25 min until timeout. The generator itself was working
fine.

## Test plan
- [x] All 707 tests pass (`make test`)
- [x] CodeRabbit review clean (1 finding fixed)
- [ ] Next scheduled E2E run should pass with these changes

@coderabbitai ignore

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

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-03 11:41:48 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 a0e6448e7b fix: make E2E job card polling resilient to transient DOM changes (#654)
## Summary
- E2E happy path test failed because the job card DOM element briefly
disappeared during a status transition (step 9/10 "Packaging files"),
causing an unhandled `TimeoutError` on `jobCard.textContent()`
- Wrapped all `textContent()` calls in polling loops with try/catch and
a 15s explicit timeout so transient DOM disappearances retry instead of
crashing the test
- Applied fix to both `happy-path-real-user.spec.ts` and
`demo-recording.spec.ts`

Fixes:
https://github.com/nomadkaraoke/karaoke-gen/actions/runs/23887007717

## Test plan
- [x] Verified TypeScript has no new errors (all existing errors are
pre-existing Playwright type issues)
- [ ] Next scheduled E2E run will validate the fix against production

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-02 03:11:12 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 fbe3edceec fix: video worker downloads PNG instead of MOV for screens (#650)
## Summary

Follow-up to #647. The video worker was hardcoded to download
`title.mov`/`end.mov` from GCS, but those no longer exist after the
screens_worker change. 404 error on all job retries.

- `video_worker.py`: download PNG (or MOV for legacy), validate with PNG
fallback
- `video_worker_orchestrator.py`: `_screen_ext()` helper for dynamic
file extension

## Test plan

- [x] All video unit tests pass
- [ ] Retry job f0d51a0a after deploy

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 23:39:57 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 ead074505b fix: skip files >3GB in divebar sync to prevent OOM kills (#653)
## Summary

- Skip files larger than 3GB in divebar file sync — the VM has 4GB RAM
and buffers files in memory, so a 4.3GB MKV was causing OOM kills every
run
- Sets `gcs_path = 'skipped:too_large'` so the file won't be retried
nightly (the `WHERE gcs_path IS NULL` query excludes it)
- Only 1 file currently affected: `IMBK-0068 - Zolas - Ancient Mars.mkv`
(4.3 GB)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 23:24:56 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 7e93d62457 fix: thread-safe Drive service in divebar file sync (#651)
## Summary

- Use `threading.local()` for Drive API service — `googleapiclient` is
not thread-safe and sharing across `ThreadPoolExecutor` workers caused
SSL errors, bad file descriptors, and heap corruption (`free():
corrupted unsorted chunks`)
- This is why ~200 files were permanently stuck with `gcs_path=NULL` —
different files failed each run depending on thread timing

**Evidence from VM logs:**
```
ERROR Failed files/NOMAD-1346.zip: 'email'
ERROR Failed files/Shark Attack.zip: [Errno 9] Bad file descriptor
ERROR Failed files/KGAL-0004.zip: [SSL: DECRYPTION_FAILED_OR_BAD_RECORD_MAC]
ERROR Failed files/LSWK-0024.zip: [SSL: WRONG_VERSION_NUMBER]
free(): corrupted unsorted chunks
```

## Test plan

- [x] Existing unit tests pass
- [ ] Next nightly file sync run should have 0 failures (was ~200/run)
- [ ] Monitor `gcs_path IS NULL` count — should drop to only genuinely
new files

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 23:04:54 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 1c846ebae7 fix: preserve gcs_path in divebar catalog sync (#649)
## Summary

- **index_builder.py**: replaced `WRITE_TRUNCATE` with staging table +
`MERGE` SQL to preserve `gcs_path` values during daily catalog index
updates
- **divebar_file_sync.py**: added `blob.exists()` check before
downloading from Drive — if a file is already in GCS, just updates
`gcs_path` in BigQuery without re-downloading
- Added unit tests verifying the MERGE approach preserves `gcs_path`
correctly

**Root cause**: The daily 2 AM index sync was atomically replacing the
entire `divebar_catalog` BigQuery table, wiping all `gcs_path` values.
The 3 AM file sync then saw all ~48K files as unsynced and re-downloaded
the entire ~779 GB catalog from Google Drive every night.

## Test plan

- [x] Unit tests for staging+MERGE behavior (5 tests pass)
- [ ] Verify staging table auto-creates on first run (BigQuery creates
on WRITE_TRUNCATE with schema)
- [ ] Monitor next nightly sync — file_sync should report "recovered
from GCS" instead of downloading
- [ ] Confirm gcs_path values persist across consecutive index runs

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 22:31:42 +00:00
Andrew Beveridge ☄️andClaude Sonnet 4.6 c02fdc8d9f Fix GCE cache invalidation and empty corrections handling (#648)
## Summary
- **GCE style asset disk cache** now validates file size against GCS on
cache hit, re-downloading when content has changed at the same URI.
Transient GCS errors gracefully fall back to cached version.
- **Review complete endpoint** no longer writes
`corrections_updated.json` when no corrections data is present (root
cause fix for KeyError in render workers).
- **Both GCE and Cloud Run render workers** validate
`corrections_updated.json` has a `corrections` key before processing,
falling back to base result gracefully (defensive fix).

## Test plan
- [x] Added `test_cache_hit_redownloads_on_size_mismatch` — verifies
stale cache replaced
- [x] Updated `test_cache_hit_skips_download` for size validation flow
- [x] Added `test_gce_worker_skips_empty_corrections` — verifies empty
dict doesn't crash
- [x] Added `TestCompleteReviewSkipsEmptyCorrections` — 4 tests covering
guard conditions
- [x] All 2875 tests pass (8 pre-existing emulator failures unrelated)

<!-- @coderabbitai ignore -->

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

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-31 18:03:26 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 3bc1fcb250 fix: move screen video generation to GCE encoding worker (#647)
## Summary

- Screen MOV generation (4K H.264) was silently failing on Cloud Run
after right-sizing to 2Gi (PR #640), producing 36-byte empty shells that
broke all downstream encoding
- `screens_worker` now only generates PNG/JPG images (Pillow, no FFmpeg)
- GCE encoding worker generates MOV from PNG before encoding, with
proper `subprocess.run()` error handling
- Fixed `os.system()` in `video_generator.py` to use `subprocess.run()`
so failures are no longer silent

## Root Cause

PR #640 reduced Cloud Run from 8CPU/16Gi to 2CPU/2Gi. The
`VideoGenerator._create_video_from_image()` used `os.system(ffmpeg ...)`
which OOMs silently for 4K H.264 encoding, producing 36-byte empty MOV
shells. All jobs since March 31 are affected.

## Test plan

- [x] 2875 tests pass (8 pre-existing emulator failures unrelated)
- [x] CodeRabbit: no findings
- [ ] Re-run failed job f0d51a0a after deploy to verify fix
- [ ] Verify admin "Regen screens" button works (tested flow: deletes
old screens → worker generates PNG/JPG only → GCE generates MOV from
PNG)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 21:44:53 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 adae022fbf Fix encoding progress callback causing invalid state transition (#646)
## Summary
- Fix `encoding -> encoding` invalid state transition that caused job
7bbd0d9d to fail
- The GCE encoding `progress_callback` was using `transition_to_state()`
to update progress while already in ENCODING state, which the state
machine correctly rejects as a self-transition
- Changed to `update_job()` which updates progress/message without
validating state transitions

## Test plan
- [x] All 2875 backend tests pass (8 pre-existing emulator failures
unrelated to change)
- [x] State machine integration tests pass
- [x] Encoding interface contract tests pass

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 21:19:47 +00:00
Andrew Beveridge ☄️andClaude Opus 4.6 9ccad7c6d3 feat: service health status modal with blue-green deploy details (#645)
## Summary
- Clickable footer opens a modal showing all service health, versions,
deploy times, and PR links
- Progressive disclosure: basic info for everyone, blue-green encoder
details for admins
- New aggregated `/api/health/system-status` endpoint (single fetch
instead of 4 separate calls)
- CI captures git SHA and PR info, passes to frontend and backend builds

## Changes
- **Backend**: New `/api/health/system-status` endpoint with optional
admin auth for blue-green Firestore config
- **Backend**: Build metadata env vars (COMMIT_SHA, PR_NUMBER, PR_TITLE,
STARTUP_TIME) in version module
- **Frontend**: New `SystemStatusModal` component with service cards and
expandable blue-green section
- **Frontend**: Footer version line is now clickable to open the modal
- **Frontend**: Build metadata env vars passed through next.config.mjs
- **CI**: Both frontend and backend deploy jobs capture and pass git SHA
+ PR info

## Testing
- [x] 3 unit tests for system-status endpoint (public, offline, admin
blue-green)
- [x] TypeScript compilation clean (no new errors)
- [x] CodeRabbit CLI reviewed

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 15:42:58 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 8e2a949a29 fix: complete blue-green deploy test payload and status check (#644)
## Summary
- Fix the deploy health check test payload and status value mismatches
that prevented blue-green swaps from ever completing
- Follow-up to #642 which fixed the error handling / rollback conditions

## Changes
- **Missing required fields**: `encode-preview` requires
`audio_gcs_path` and `output_gcs_path` but the health check only sent
`job_id`, `ass_gcs_path`, and `duration_seconds` (caused HTTP 422).
Added a 3-second test audio file and proper output path.
- **Status polling mismatch**: Polling checked for `"completed"` but the
GCE worker returns `"complete"` — would always time out even on success.
- **Submit response mismatch**: Validated against `"completed"` which is
never returned — endpoint returns `"accepted"`, `"cached"`, or
`"in_progress"`.

## Root Cause
The test payload was written based on the plan doc which had an
incomplete request schema. The `audio_gcs_path` and `output_gcs_path`
fields have been required since the endpoint was first created (PR #200,
Jan 2026). The status string mismatch (`"completed"` vs `"complete"`)
was likely a typo that was never caught because the request always
failed before reaching the polling stage.

## Testing
- Previous deploy (#642) confirmed the 422 error and verified rollback
now triggers correctly
- This fix addresses the payload so the encode test can actually succeed
and the swap can complete
- Real validation: next deploy after merge

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 14:07:38 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 0464d3edb3 Fix render_video GCE endpoint import paths (#643)
@coderabbitai ignore

## Summary

- Fix broken import paths in GCE worker's `/render-video` endpoint that
caused `ImportError: No module named 'backend.output_generator'` in
production
- Fix incorrect API signatures for OutputGenerator, CountdownProcessor,
CorrectionResult, load_styles_from_gcs
- Update tests to mock correct module paths

## Root cause

The subagent that implemented Task 2 (PR #641) used invented module
paths (`backend.output_generator`,
`backend.services.countdown_processor`, etc.) instead of the actual
karaoke-gen wheel paths
(`karaoke_gen.lyrics_transcriber.output.generator`, etc.). The tests
also mocked the wrong paths, so they passed locally but the code failed
in production.

## Changes

- `backend/services/gce_encoding/main.py` — Rewrote `run_render_video()`
to use correct imports and API calls matching `render_video_worker.py`
- `tests/unit/test_gce_render_video_endpoint.py` — Rewrote
TestRunRenderVideo to mock correct module paths

## Test plan

- [ ] 18 unit tests pass (verified locally with
`GOOGLE_CLOUD_PROJECT=""` to simulate CI)
- [ ] E2E happy path test after merge validates full pipeline

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 14:01:36 -04:00
Andrew Beveridge ☄️andClaude Opus 4.6 5dfaa3f73f fix: blue-green deploy health check and rollback conditions (#642)
## Summary
- Fix blue-green deploy workflow that has been silently failing since
v0.151.0 (March 25)
- Every deploy has fallen through to `ensure_latest_wheel()` hot-update
instead of tested blue-green swap

## Changes
- **Health check curl**: Replace `curl -sf` (which exits immediately on
HTTP errors before setting output) with `curl -s -o file -w
'%{http_code}'` to capture HTTP status without early exit
- **Status polling curl**: Remove `-f` flag and add fallback for failed
status checks
- **Rollback condition**: Change `passed == 'false'` to `passed !=
'true'` to catch unset/skipped cases (defense in depth)

## Root Cause
`curl -sf` with `-f` (fail silently) exits non-zero on HTTP errors.
Combined with GitHub Actions' `set -e`, the script exits before writing
`passed=false` to `$GITHUB_OUTPUT`. Both the rollback (`== 'false'`) and
swap (`== 'true'`) conditions evaluate false against the unset output,
creating a silent no-op.

## Testing
- [x] CI workflow syntax validated
- [x] CodeRabbit CLI review completed locally (no issues in changed
file)
- Real validation: next deploy will exercise the fixed workflow

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-31 13:46:30 -04:00
31 changed files with 3021 additions and 495 deletions

No files matched your search

+68 -14
View File
@@ -902,6 +902,22 @@ jobs:
# - / (main app)
# - /app/jobs/{id}/lyrics (lyrics review)
# - /app/jobs/{id}/instrumental (instrumental review)
- name: Capture build metadata
id: frontend-meta
run: |
echo "sha=${GITHUB_SHA::8}" >> $GITHUB_OUTPUT
PR_NUM=$(git log -1 --format=%s | grep -oP '\(#\K[0-9]+' | head -1 || echo "")
if [ -n "$PR_NUM" ]; then
PR_TITLE=$(gh pr view "$PR_NUM" --json title -q .title 2>/dev/null || echo "")
else
PR_NUM=""
PR_TITLE=""
fi
echo "pr_number=${PR_NUM}" >> $GITHUB_OUTPUT
echo "pr_title=${PR_TITLE}" >> $GITHUB_OUTPUT
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Install frontend dependencies
working-directory: frontend
run: npm ci --legacy-peer-deps
@@ -911,6 +927,10 @@ jobs:
working-directory: frontend
env:
NEXT_PUBLIC_API_URL: https://api.nomadkaraoke.com
NEXT_PUBLIC_COMMIT_SHA: ${{ steps.frontend-meta.outputs.sha }}
NEXT_PUBLIC_PR_NUMBER: ${{ steps.frontend-meta.outputs.pr_number }}
NEXT_PUBLIC_PR_TITLE: ${{ steps.frontend-meta.outputs.pr_title }}
NEXT_PUBLIC_BUILD_TIME: ${{ github.event.head_commit.timestamp }}
run: npm run build
- name: Deploy consumer to Cloudflare Pages
@@ -929,6 +949,10 @@ jobs:
env:
NEXT_PUBLIC_API_URL: https://api.nomadkaraoke.com
NEXT_PUBLIC_TENANT_PORTAL: "true"
NEXT_PUBLIC_COMMIT_SHA: ${{ steps.frontend-meta.outputs.sha }}
NEXT_PUBLIC_PR_NUMBER: ${{ steps.frontend-meta.outputs.pr_number }}
NEXT_PUBLIC_PR_TITLE: ${{ steps.frontend-meta.outputs.pr_title }}
NEXT_PUBLIC_BUILD_TIME: ${{ github.event.head_commit.timestamp }}
run: npm run build
- name: Deploy tenant portal to Cloudflare Pages
@@ -1008,6 +1032,23 @@ jobs:
echo "📋 Current version: $VERSION"
echo "🚀 Deploying on every push to main"
- name: Capture build metadata
id: build-meta
run: |
echo "sha=${GITHUB_SHA::8}" >> $GITHUB_OUTPUT
# For squash-merge commits, PR number is in the commit message as (#NNN)
PR_NUM=$(git log -1 --format=%s | grep -oP '\(#\K[0-9]+' | head -1 || echo "")
if [ -n "$PR_NUM" ]; then
PR_TITLE=$(gh pr view "$PR_NUM" --json title -q .title 2>/dev/null || echo "")
else
PR_NUM=""
PR_TITLE=""
fi
echo "pr_number=${PR_NUM}" >> $GITHUB_OUTPUT
echo "pr_title=${PR_TITLE}" >> $GITHUB_OUTPUT
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Authenticate to Google Cloud (Workload Identity)
id: auth
uses: google-github-actions/auth@v2
@@ -1186,24 +1227,37 @@ jobs:
API_KEY=$(gcloud secrets versions access latest \
--secret=encoding-worker-api-key --project=nomadkaraoke)
DEPLOY_TEST_PATH="gs://karaoke-gen-storage-nomadkaraoke/deploy-test"
echo "Uploading test assets to GCS..."
gsutil cp infrastructure/encoding-worker/test-assets/test-preview.ass \
gs://karaoke-gen-storage-nomadkaraoke/deploy-test/test-preview.ass
"${DEPLOY_TEST_PATH}/test-preview.ass"
gsutil cp infrastructure/encoding-worker/test-assets/test-audio.flac \
"${DEPLOY_TEST_PATH}/test-audio.flac"
echo "Submitting test encode to $SECONDARY_IP..."
RESPONSE=$(curl -sf -X POST "http://${SECONDARY_IP}:8080/encode-preview" \
HTTP_CODE=$(curl -s -o /tmp/encode-response.json -w '%{http_code}' \
-X POST "http://${SECONDARY_IP}:8080/encode-preview" \
-H "X-API-Key: $API_KEY" \
-H "Content-Type: application/json" \
-d '{
"job_id": "deploy-health-check",
"ass_gcs_path": "gs://karaoke-gen-storage-nomadkaraoke/deploy-test/test-preview.ass",
"duration_seconds": 10
}')
-d "{
\"job_id\": \"deploy-health-check\",
\"ass_gcs_path\": \"${DEPLOY_TEST_PATH}/test-preview.ass\",
\"audio_gcs_path\": \"${DEPLOY_TEST_PATH}/test-audio.flac\",
\"output_gcs_path\": \"${DEPLOY_TEST_PATH}/output-preview.mp4\"
}") || HTTP_CODE="000"
RESPONSE=$(cat /tmp/encode-response.json 2>/dev/null || echo "{}")
echo "Encode response (HTTP $HTTP_CODE): $RESPONSE"
if [ "$HTTP_CODE" != "200" ] && [ "$HTTP_CODE" != "202" ]; then
echo "::error::Encode request failed with HTTP $HTTP_CODE"
echo "passed=false" >> $GITHUB_OUTPUT
exit 1
fi
echo "Encode response: $RESPONSE"
STATUS=$(echo "$RESPONSE" | jq -r '.status // "unknown"')
if [ "$STATUS" != "accepted" ] && [ "$STATUS" != "completed" ]; then
if [ "$STATUS" != "accepted" ] && [ "$STATUS" != "cached" ] && [ "$STATUS" != "in_progress" ]; then
echo "::error::Encode test failed with status: $STATUS"
echo "passed=false" >> $GITHUB_OUTPUT
exit 1
@@ -1211,11 +1265,11 @@ jobs:
for i in $(seq 1 12); do
sleep 5
JOB_STATUS=$(curl -sf \
JOB_STATUS=$(curl -s \
"http://${SECONDARY_IP}:8080/status/deploy-health-check" \
-H "X-API-Key: $API_KEY" | jq -r '.status // "unknown"')
-H "X-API-Key: $API_KEY" 2>/dev/null | jq -r '.status // "unknown"' 2>/dev/null) || JOB_STATUS="unknown"
echo "Encode status: $JOB_STATUS (attempt $i/12)"
if [ "$JOB_STATUS" = "completed" ]; then
if [ "$JOB_STATUS" = "complete" ]; then
echo "Encode test passed!"
echo "passed=true" >> $GITHUB_OUTPUT
gsutil rm -f gs://karaoke-gen-storage-nomadkaraoke/deploy-test/** || true
@@ -1232,7 +1286,7 @@ jobs:
exit 1
- name: Rollback on failure
if: steps.health.outputs.healthy != 'true' || steps.encode-test.outputs.passed == 'false'
if: steps.health.outputs.healthy != 'true' || steps.encode-test.outputs.passed != 'true'
run: |
SECONDARY_VM="${{ steps.config.outputs.secondary_vm }}"
if [ -n "$SECONDARY_VM" ]; then
@@ -1556,7 +1610,7 @@ jobs:
--min-instances 1 \
--vpc-connector projects/nomadkaraoke/locations/us-central1/connectors/cloud-run-connector \
--vpc-egress private-ranges-only \
--set-env-vars "GOOGLE_CLOUD_PROJECT=${{ env.PROJECT_ID }},GCS_BUCKET_NAME=karaoke-gen-storage-${{ env.PROJECT_ID }},FIRESTORE_COLLECTION=jobs,ENVIRONMENT=production,KARAOKE_GEN_VERSION=$VERSION,DEFAULT_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-Organized,DEFAULT_GDRIVE_FOLDER_ID=1laRKAyxo0v817SstfM5XkpbWiNKNAMSX,ENABLE_CLOUD_TASKS=true,CLOUD_RUN_SERVICE_URL=https://api.nomadkaraoke.com,GCP_REGION=us-central1,DEFAULT_ENABLE_YOUTUBE_UPLOAD=true,DEFAULT_BRAND_PREFIX=NOMAD,DEFAULT_PRIVATE_DROPBOX_PATH=/MediaUnsynced/Karaoke/Tracks-NonPublished,DEFAULT_PRIVATE_BRAND_PREFIX=NOMADNP,USE_GCE_ENCODING=true,USE_GCE_PREVIEW_ENCODING=true,ENABLE_PUSH_NOTIFICATIONS=true,USE_CLOUD_RUN_JOBS_FOR_VIDEO=true" \
--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,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 "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,SENDGRID_API_KEY=sendgrid-api-key: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,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"
- name: Update Cloud Run Jobs with new image
+141 -3
View File
@@ -5,10 +5,12 @@ import os
import logging
import subprocess
import platform
from fastapi import APIRouter
from typing import Dict, Any, Optional
from fastapi import APIRouter, Depends
from typing import Dict, Any, Optional, Tuple
from backend.version import VERSION
from backend.version import VERSION, COMMIT_SHA, PR_NUMBER, PR_TITLE, STARTUP_TIME
from backend.api.dependencies import optional_auth
from backend.services.auth_service import UserType
from backend.services.flacfetch_client import get_flacfetch_client
from backend.services.email_service import get_email_service
from backend.services.stripe_service import get_stripe_service
@@ -308,6 +310,30 @@ async def flacfetch_health() -> Dict[str, Any]:
}
def check_audio_separator_status() -> Dict[str, Any]:
"""Check audio separator availability without calling the remote GPU service."""
from backend.config import get_settings
settings = get_settings()
if not settings.audio_separator_api_url:
return {
"available": False,
"status": "not_configured",
}
try:
from importlib.metadata import version
pkg_version = version("audio-separator")
except Exception:
pkg_version = None
return {
"available": True,
"status": "ok",
"version": pkg_version,
}
@router.get("/health/audio-separator")
async def audio_separator_health() -> Dict[str, Any]:
"""
@@ -341,6 +367,118 @@ async def audio_separator_health() -> Dict[str, Any]:
}
def _get_encoding_worker_manager():
"""Get the EncodingWorkerManager instance. Separated for testability."""
try:
encoding_service = get_encoding_service()
if hasattr(encoding_service, '_worker_manager') and encoding_service._worker_manager:
return encoding_service._worker_manager
except Exception:
pass
return None
@router.get("/health/system-status")
async def system_status(
auth: Optional[Tuple] = Depends(optional_auth),
) -> Dict[str, Any]:
"""
Aggregated system status for all services.
Returns basic info for everyone. Admin users get additional
blue-green deployment details for the encoder.
"""
is_admin = auth is not None and len(auth) >= 2 and auth[1] == UserType.ADMIN
# Fetch all health statuses concurrently
import asyncio
encoding_task = check_encoding_worker_status()
flacfetch_task = check_flacfetch_service_status()
encoding_status, flacfetch_status = await asyncio.gather(
encoding_task, flacfetch_task
)
separator_status = check_audio_separator_status()
# Build frontend service info (from env vars baked at build time — returned as-is)
frontend_svc = {
"status": "ok",
"version": VERSION, # Frontend and backend share the same version from pyproject.toml
}
# Build backend service info
backend_svc = {
"status": "ok",
"version": VERSION,
"deployed_at": STARTUP_TIME,
}
if COMMIT_SHA:
backend_svc["commit_sha"] = COMMIT_SHA
if PR_NUMBER:
backend_svc["pr_number"] = PR_NUMBER
if PR_TITLE:
backend_svc["pr_title"] = PR_TITLE
# Build encoder service info
encoder_svc = {
"status": "ok" if encoding_status.get("available") else "offline",
"version": encoding_status.get("wheel_version"),
"active_jobs": encoding_status.get("active_jobs", 0),
}
# Build flacfetch service info
flacfetch_svc = {
"status": "ok" if flacfetch_status.get("available") else "offline",
"version": flacfetch_status.get("version"),
}
# Build separator service info
separator_svc = {
"status": "ok" if separator_status.get("available") else "offline",
"version": separator_status.get("version"),
}
# Admin-only: blue-green encoder details from Firestore
if is_admin:
manager = _get_encoding_worker_manager()
if manager:
try:
config = manager.get_config()
encoder_svc["admin_details"] = {
"primary_vm": config.primary_vm,
"primary_ip": config.primary_ip,
"primary_version": config.primary_version,
"primary_deployed_at": config.primary_deployed_at,
"secondary_vm": config.secondary_vm,
"secondary_ip": config.secondary_ip,
"secondary_version": config.secondary_version,
"secondary_deployed_at": config.secondary_deployed_at,
"last_swap_at": config.last_swap_at,
"deploy_in_progress": config.deploy_in_progress,
"active_jobs": encoding_status.get("active_jobs", 0),
"queue_length": encoding_status.get("queue_length", 0),
}
except Exception as e:
logger.warning(f"Failed to get blue-green config: {e}")
# Add error details for offline services
if not flacfetch_status.get("available"):
flacfetch_svc["admin_details"] = {"error": flacfetch_status.get("error")}
if not separator_status.get("available"):
separator_svc["admin_details"] = {"error": separator_status.get("error")}
if not encoding_status.get("available") and "admin_details" not in encoder_svc:
encoder_svc["admin_details"] = {"error": encoding_status.get("error")}
return {
"services": {
"frontend": frontend_svc,
"backend": backend_svc,
"encoder": encoder_svc,
"flacfetch": flacfetch_svc,
"separator": separator_svc,
}
}
@router.get("/health/detailed")
async def detailed_health_check() -> Dict[str, Any]:
"""
+10 -6
View File
@@ -331,12 +331,16 @@ async def complete_review(
# (it's stored separately in state_data)
corrections_to_save = {k: v for k, v in updated_data.items() if k != "instrumental_selection"}
# Save updated corrections to GCS
corrections_gcs_path = f"jobs/{job_id}/lyrics/corrections_updated.json"
storage.upload_json(corrections_gcs_path, corrections_to_save)
job_manager.update_file_url(job_id, 'lyrics', 'corrections_updated', corrections_gcs_path)
logger.info(f"Job {job_id}: Saved updated corrections")
# Only write corrections_updated.json if there's actual correction data.
# Writing an empty dict causes KeyError downstream when render workers
# try to access updated_data["corrections"].
if corrections_to_save and "corrections" in corrections_to_save:
corrections_gcs_path = f"jobs/{job_id}/lyrics/corrections_updated.json"
storage.upload_json(corrections_gcs_path, corrections_to_save)
job_manager.update_file_url(job_id, 'lyrics', 'corrections_updated', corrections_gcs_path)
logger.info(f"Job {job_id}: Saved updated corrections")
else:
logger.info(f"Job {job_id}: No corrections data in request, skipping corrections_updated.json")
# === Store instrumental selection in state_data ===
# This will be used by render_video_worker to skip AWAITING_INSTRUMENTAL_SELECTION
+220 -99
View File
@@ -161,8 +161,10 @@ STYLE_CACHE_DIR = Path("/var/cache/karaoke-gen/styles")
def download_with_cache(gcs_uri: str, local_path: Path, cache_dir: Optional[Path] = STYLE_CACHE_DIR):
"""Download a file from GCS, using a local disk cache to skip repeated downloads.
Cache key is SHA-256 of the GCS URI. Cache hits copy from disk instead of
downloading. When cache_dir is None, downloads directly (no caching).
Cache key is SHA-256 of the GCS URI. Cache hits are validated by comparing
the cached file size against the GCS object size (via a lightweight metadata
call). On size mismatch the stale entry is replaced.
When cache_dir is None, downloads directly (no caching).
"""
if cache_dir is None:
download_single_file_from_gcs(gcs_uri, local_path)
@@ -173,9 +175,30 @@ def download_with_cache(gcs_uri: str, local_path: Path, cache_dir: Optional[Path
cached_path = cache_dir / cache_key
if cached_path.exists():
logger.info(f"Cache hit for {gcs_uri} -> {cached_path}")
shutil.copy2(str(cached_path), str(local_path))
return
# Validate cached file against GCS object size
try:
parts = gcs_uri.replace("gs://", "").split("/", 1)
bucket_name = parts[0]
blob_name = parts[1] if len(parts) > 1 else ""
blob = storage_client.bucket(bucket_name).blob(blob_name)
blob.reload() # Fetch metadata (lightweight HEAD request)
gcs_size = blob.size
cached_size = cached_path.stat().st_size
if gcs_size is not None and cached_size != gcs_size:
logger.warning(
f"Cache stale for {gcs_uri}: cached={cached_size}B, GCS={gcs_size}B. Re-downloading."
)
cached_path.unlink()
else:
logger.info(f"Cache hit for {gcs_uri} -> {cached_path}")
shutil.copy2(str(cached_path), str(local_path))
return
except Exception as e:
# On transient GCS errors, serve from cache rather than failing the job
logger.warning(f"Cache validation failed for {gcs_uri}: {e}. Serving from cache.")
shutil.copy2(str(cached_path), str(local_path))
return
logger.info(f"Cache miss for {gcs_uri}, downloading...")
download_single_file_from_gcs(gcs_uri, local_path)
@@ -287,143 +310,178 @@ def run_preview_encoding(job_id: str, work_dir: Path, request: "EncodePreviewReq
def run_render_video(job_id: str, work_dir: Path, request: "RenderVideoRequest"):
'''Run video rendering using OutputGenerator from the karaoke-gen wheel.
"""Run video rendering using OutputGenerator from the karaoke-gen wheel.
Downloads corrections, audio, and style assets, then uses OutputGenerator
to render karaoke video with synchronized lyrics. Uploads video and lyrics
output files to GCS.
'''
Downloads corrections, audio, and style assets from GCS, runs OutputGenerator
to produce with_vocals.mkv and subtitle files, then uploads results.
Style assets use disk cache to avoid repeated downloads of the same theme.
This mirrors the logic in render_video_worker.py but runs on the GCE VM
instead of Cloud Run, providing more memory and CPU for ffmpeg/libass.
"""
jobs[job_id]["status"] = "running"
jobs[job_id]["progress"] = 5
jobs[job_id]["output_files"] = []
try:
# Import from karaoke-gen wheel (installed by ensure_latest_wheel)
from backend.output_generator import OutputGenerator, OutputConfig
from backend.services.countdown_processor import CountdownProcessor
from backend.models.correction_result import CorrectionResult
from backend.services.correction_operations import CorrectionOperations
from backend.utils.style_utils import load_styles_from_gcs
from backend.utils.filename_utils import sanitize_filename
logger.info("Imported karaoke-gen wheel modules for render-video")
# Import from installed karaoke-gen wheel
from karaoke_gen.lyrics_transcriber.output.generator import OutputGenerator
from karaoke_gen.lyrics_transcriber.output.countdown_processor import CountdownProcessor
from karaoke_gen.lyrics_transcriber.types import CorrectionResult
from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations
from karaoke_gen.lyrics_transcriber.core.config import OutputConfig
from karaoke_gen.style_loader import load_styles_from_gcs
from karaoke_gen.utils import sanitize_filename
# Download original corrections
# 1. Download original corrections
corrections_path = work_dir / "corrections.json"
download_single_file_from_gcs(request.original_corrections_gcs_path, corrections_path)
correction_result = CorrectionResult.from_json(corrections_path.read_text())
jobs[job_id]["progress"] = 15
logger.info(f"Loaded corrections from {request.original_corrections_gcs_path}")
# Apply updated corrections if provided
with open(corrections_path, 'r', encoding='utf-8') as f:
original_data = json.load(f)
base_result = CorrectionResult.from_dict(original_data)
# 2. Apply user corrections if available
if request.updated_corrections_gcs_path:
updated_path = work_dir / "updated_corrections.json"
updated_path = work_dir / "corrections_updated.json"
download_single_file_from_gcs(request.updated_corrections_gcs_path, updated_path)
updated_data = json.loads(updated_path.read_text())
correction_result = CorrectionOperations.update_correction_result_with_data(
correction_result, updated_data
)
logger.info(f"Applied updated corrections from {request.updated_corrections_gcs_path}")
jobs[job_id]["progress"] = 20
with open(updated_path, 'r', encoding='utf-8') as f:
updated_data = json.load(f)
if isinstance(updated_data, dict) and "corrections" in updated_data:
correction_result = CorrectionOperations.update_correction_result_with_data(
base_result, updated_data
)
logger.info(f"[job:{job_id}] Applied user corrections")
else:
logger.warning(f"[job:{job_id}] corrections_updated.json exists but has no 'corrections' key, using base result")
correction_result = base_result
else:
correction_result = base_result
# Download audio
jobs[job_id]["progress"] = 25
# 3. Download audio
audio_path = work_dir / "audio.flac"
download_single_file_from_gcs(request.audio_gcs_path, audio_path)
jobs[job_id]["progress"] = 30
logger.info(f"Downloaded audio from {request.audio_gcs_path}")
jobs[job_id]["progress"] = 35
# Run countdown processor
countdown_processor = CountdownProcessor()
correction_result, countdown_added, countdown_seconds = countdown_processor.process(
correction_result, audio_path
# 4. Process countdown intro
countdown_processor = CountdownProcessor(cache_dir=str(work_dir), logger=logger)
correction_result, audio_path_str, padding_added, padding_seconds = countdown_processor.process(
correction_result=correction_result,
audio_filepath=str(audio_path),
)
audio_path = Path(audio_path_str)
jobs[job_id]["progress"] = 40
logger.info(f"Countdown processing: added={countdown_added}, seconds={countdown_seconds}")
# Download style assets via load_styles_from_gcs (with caching)
style_config, font_assets = load_styles_from_gcs(
# 5. Download style assets (with disk cache for repeated themes)
def cached_download(gcs_path, local_path):
download_with_cache(gcs_path, Path(local_path), STYLE_CACHE_DIR)
styles_path, style_data = load_styles_from_gcs(
style_params_gcs_path=request.style_params_gcs_path,
style_assets=request.style_assets,
download_fn=download_with_cache,
work_dir=work_dir,
temp_dir=str(work_dir),
download_func=cached_download,
logger=logger,
)
# Register any downloaded fonts with fontconfig
for asset_key, gcs_path in (request.style_assets or {}).items():
if 'font' in asset_key.lower() and gcs_path.endswith(('.ttf', '.otf', '.woff', '.woff2')):
fonts_dir = Path("/usr/local/share/fonts/custom")
fonts_dir.mkdir(parents=True, exist_ok=True)
font_filename = gcs_path.split("/")[-1]
font_dest = fonts_dir / font_filename
if not font_dest.exists():
ext = os.path.splitext(gcs_path)[1]
style_font = work_dir / "style" / f"{asset_key}{ext}"
if style_font.exists():
shutil.copy2(str(style_font), str(font_dest))
subprocess.run(["fc-cache", "-fv"], capture_output=True)
logger.info(f"Registered font: {font_filename}")
jobs[job_id]["progress"] = 50
logger.info(f"Loaded style config with {len(font_assets)} font assets")
# Register font assets with fontconfig
if font_assets:
fonts_dir = Path("/usr/local/share/fonts/custom")
fonts_dir.mkdir(parents=True, exist_ok=True)
for font_path in font_assets:
font_file = Path(font_path)
if font_file.exists():
dest_font = fonts_dir / font_file.name
shutil.copy2(str(font_file), str(dest_font))
logger.info(f"Installed font: {dest_font}")
subprocess.run(["fc-cache", "-fv"], capture_output=True)
logger.info("Updated fontconfig cache with style fonts")
jobs[job_id]["progress"] = 55
# 6. Configure and run OutputGenerator
output_dir = work_dir / "output"
cache_dir = work_dir / "cache"
output_dir.mkdir(exist_ok=True)
cache_dir.mkdir(exist_ok=True)
# Configure OutputGenerator
output_config = OutputConfig(
config = OutputConfig(
output_dir=str(output_dir),
cache_dir=str(cache_dir),
output_styles_json=styles_path,
render_video=True,
generate_cdg=False,
generate_plain_text=True,
generate_lrc=True,
)
output_generator = OutputGenerator(
correction_result=correction_result,
audio_path=str(audio_path),
output_dir=str(work_dir),
artist=request.artist,
title=request.title,
config=output_config,
style_config=style_config,
video_resolution=request.video_resolution,
subtitle_offset_ms=request.subtitle_offset_ms,
)
jobs[job_id]["progress"] = 60
logger.info("Starting OutputGenerator.generate_outputs()")
output_generator.generate_outputs()
output_generator = OutputGenerator(config, logger)
safe_artist = sanitize_filename(request.artist) if request.artist else "Unknown"
safe_title = sanitize_filename(request.title) if request.title else "Unknown"
output_prefix = f"{safe_artist} - {safe_title}"
logger.info(f"[job:{job_id}] Generating outputs with prefix '{output_prefix}'")
jobs[job_id]["progress"] = 55
outputs = output_generator.generate_outputs(
transcription_corrected=correction_result,
lyrics_results={},
output_prefix=output_prefix,
audio_filepath=str(audio_path),
artist=request.artist,
title=request.title,
)
jobs[job_id]["progress"] = 85
logger.info("OutputGenerator.generate_outputs() complete")
# Upload outputs to GCS
output_prefix = request.output_gcs_prefix.rstrip("/")
output_mappings = [
(work_dir / "videos" / "with_vocals.mkv", f"{output_prefix}/videos/with_vocals.mkv"),
(work_dir / "lyrics" / "karaoke.ass", f"{output_prefix}/lyrics/karaoke.ass"),
(work_dir / "lyrics" / "karaoke.lrc", f"{output_prefix}/lyrics/karaoke.lrc"),
(work_dir / "lyrics" / "corrected.txt", f"{output_prefix}/lyrics/corrected.txt"),
]
# 7. Upload outputs to GCS
output_prefix_gcs = request.output_gcs_prefix.rstrip("/")
output_files = []
uploaded_files = []
for local_file, gcs_path in output_mappings:
if local_file.exists():
upload_single_file_to_gcs(local_file, gcs_path)
uploaded_files.append(gcs_path)
logger.info(f"Uploaded {local_file.name} to {gcs_path}")
else:
logger.warning(f"Expected output file not found: {local_file}")
if outputs.video and os.path.exists(outputs.video):
gcs_path = f"{output_prefix_gcs}/videos/with_vocals.mkv"
upload_single_file_to_gcs(Path(outputs.video), gcs_path)
output_files.append(gcs_path)
logger.info(f"[job:{job_id}] Uploaded with_vocals.mkv ({os.path.getsize(outputs.video)} bytes)")
else:
raise RuntimeError("Video generation failed - no output file produced")
if outputs.ass and os.path.exists(outputs.ass):
gcs_path = f"{output_prefix_gcs}/lyrics/karaoke.ass"
upload_single_file_to_gcs(Path(outputs.ass), gcs_path)
output_files.append(gcs_path)
if outputs.lrc and os.path.exists(outputs.lrc):
gcs_path = f"{output_prefix_gcs}/lyrics/karaoke.lrc"
upload_single_file_to_gcs(Path(outputs.lrc), gcs_path)
output_files.append(gcs_path)
if outputs.corrected_txt and os.path.exists(outputs.corrected_txt):
gcs_path = f"{output_prefix_gcs}/lyrics/corrected.txt"
upload_single_file_to_gcs(Path(outputs.corrected_txt), gcs_path)
output_files.append(gcs_path)
jobs[job_id]["output_files"] = uploaded_files
jobs[job_id]["progress"] = 95
# Store metadata about countdown processing
jobs[job_id]["output_files"] = output_files
jobs[job_id]["metadata"] = {
"countdown_padding_added": countdown_added,
"countdown_padding_seconds": countdown_seconds,
"countdown_padding_added": padding_added,
"countdown_padding_seconds": padding_seconds if padding_added else 0,
}
logger.info(f"Render video complete for job {job_id}. Uploaded {len(uploaded_files)} files.")
return work_dir
logger.info(f"[job:{job_id}] Render video complete. Output files: {output_files}")
except ImportError as e:
error_msg = (
f"Karaoke-gen wheel modules not available: {e}. "
f"OutputGenerator not available: {e}. "
"The karaoke-gen wheel must be installed. "
"Check that ensure_latest_wheel() succeeded and wheel exists in GCS."
"Check that ensure_latest_wheel() succeeded."
)
logger.error(error_msg)
jobs[job_id]["status"] = "failed"
@@ -431,7 +489,7 @@ def run_render_video(job_id: str, work_dir: Path, request: "RenderVideoRequest")
raise RuntimeError(error_msg) from e
except Exception as e:
logger.error(f"Render video failed for job {job_id}: {e}")
logger.error(f"[job:{job_id}] Render video failed: {e}")
jobs[job_id]["status"] = "failed"
jobs[job_id]["error"] = str(e)
raise
@@ -505,6 +563,43 @@ def find_file(work_dir: Path, *patterns):
return None
def generate_mov_from_png(png_path: Path, mov_path: Path, duration: int = 5) -> Path:
"""Generate a MOV video from a static PNG image using FFmpeg.
This runs on the GCE encoding worker (not Cloud Run) because 4K H.264
encoding requires more memory than the right-sized Cloud Run container
provides (2Gi). See PR #640 / #647.
Args:
png_path: Path to input PNG image
mov_path: Path for output MOV video
duration: Video duration in seconds (default 5)
Returns:
Path to generated MOV file
Raises:
RuntimeError: If FFmpeg fails
"""
command = [
"ffmpeg", "-hide_banner", "-loglevel", "error", "-nostats", "-y",
"-loop", "1", "-framerate", "30", "-i", str(png_path),
"-f", "lavfi", "-i", "anullsrc",
"-c:v", "libx264", "-r", "30", "-t", str(duration),
"-pix_fmt", "yuv420p", "-vf", "scale=3840:2160",
"-c:a", "aac", "-shortest",
str(mov_path),
]
logger.info(f"Generating MOV from PNG: {png_path.name} -> {mov_path.name}")
result = subprocess.run(command, capture_output=True, text=True, timeout=120)
if result.returncode != 0:
raise RuntimeError(f"FFmpeg failed to generate {mov_path.name}: {result.stderr}")
if not mov_path.exists() or mov_path.stat().st_size < 1024:
raise RuntimeError(f"FFmpeg produced invalid output for {mov_path.name}")
logger.info(f"Generated MOV: {mov_path.name} ({mov_path.stat().st_size} bytes)")
return mov_path
def run_encoding(job_id: str, work_dir: Path, config: dict):
'''Run encoding using LocalEncodingService (single source of truth).
@@ -534,10 +629,36 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
logger.info(f"Encoding for: {base_name}")
# Find input files in work_dir
# Title/end screens are in screens/ subdirectory
# 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.
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 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"
logger.info(f"Title MOV missing/invalid, generating from PNG: {title_png}")
title_video = generate_mov_from_png(title_png, title_mov_path, duration=intro_duration)
elif title_video:
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 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"
logger.info(f"End MOV missing/invalid, generating from PNG: {end_png}")
end_video = generate_mov_from_png(end_png, end_mov_path, duration=end_duration)
elif end_video:
logger.warning(f"End MOV is only {end_video.stat().st_size} bytes and no PNG found")
# Karaoke video - search for With Vocals or main karaoke video
# IMPORTANT: Search order matters! Search specific paths first to avoid picking up
# old encoding outputs from finals/ directory when re-encoding after reset
@@ -319,3 +319,59 @@ class TestRenderVideoWorkerUsesCorrectedData:
# Metadata and original_segments preserved
assert original_data['metadata']['preserved'] is True
assert original_data['original_segments'][0]['id'] == 1
class TestCompleteReviewSkipsEmptyCorrections:
"""Test that complete_review doesn't write corrections_updated.json when no corrections.
Bug scenario: Completing review via admin API without corrections payload writes
an empty {} to corrections_updated.json. Downstream render workers then get
KeyError: 'corrections' when processing it.
"""
def test_no_corrections_key_skips_upload(self):
"""When updated_data has only instrumental_selection, no corrections file is written."""
# Simulate what the endpoint does with the corrections_to_save logic
updated_data = {"instrumental_selection": "clean"}
corrections_to_save = {k: v for k, v in updated_data.items() if k != "instrumental_selection"}
# This is the guard we added
should_write = corrections_to_save and "corrections" in corrections_to_save
assert not should_write, "Should not write corrections_updated.json for empty payload"
def test_with_corrections_key_allows_upload(self):
"""When updated_data has corrections, the file should be written."""
updated_data = {
"corrections": [{"id": 1, "type": "edit"}],
"corrected_segments": [{"id": 1, "text": "fixed"}],
"instrumental_selection": "with_backing",
}
corrections_to_save = {k: v for k, v in updated_data.items() if k != "instrumental_selection"}
should_write = corrections_to_save and "corrections" in corrections_to_save
assert should_write, "Should write corrections_updated.json when corrections present"
def test_empty_dict_payload_skips_upload(self):
"""When updated_data is effectively empty after removing instrumental_selection."""
updated_data = {"instrumental_selection": "clean", "some_other_key": "value"}
corrections_to_save = {k: v for k, v in updated_data.items() if k != "instrumental_selection"}
# Has content but no "corrections" key
should_write = corrections_to_save and "corrections" in corrections_to_save
assert not should_write, "Should not write without corrections key"
def test_render_worker_handles_empty_corrections_gracefully(self):
"""Document that render workers skip empty corrections_updated.json.
Both GCE and Cloud Run workers now check for 'corrections' key
before passing to CorrectionOperations.update_correction_result_with_data().
"""
# Simulates what the workers do on download
empty_updated_data = {}
has_valid_corrections = empty_updated_data and "corrections" in empty_updated_data
assert not has_valid_corrections, "Empty dict should not be treated as valid corrections"
# Dict with irrelevant keys
bad_updated_data = {"some_key": "value"}
has_valid_corrections = bad_updated_data and "corrections" in bad_updated_data
assert not has_valid_corrections, "Dict without corrections key should not be valid"
@@ -0,0 +1,157 @@
"""Tests for the /api/health/system-status endpoint."""
import pytest
from unittest.mock import patch, MagicMock, AsyncMock
@pytest.fixture
def mock_encoding_status():
return {
"configured": True,
"enabled": True,
"available": True,
"status": "ok",
"active_jobs": 0,
"queue_length": 0,
"wheel_version": "0.155.3",
}
@pytest.fixture
def mock_flacfetch_status():
return {
"configured": True,
"available": True,
"status": "ok",
"version": "0.19.1",
}
@pytest.fixture
def mock_separator_status():
return {
"available": True,
"status": "ok",
"version": "0.4.3",
}
@pytest.fixture
def mock_encoding_worker_config():
"""Mock EncodingWorkerConfig dataclass."""
config = MagicMock()
config.primary_vm = "encoding-worker-b"
config.primary_ip = "34.10.189.118"
config.primary_version = "0.155.3"
config.primary_deployed_at = "2026-03-31T18:10:00Z"
config.secondary_vm = "encoding-worker-a"
config.secondary_ip = "34.57.78.246"
config.secondary_version = "0.155.2"
config.secondary_deployed_at = "2026-03-29T14:00:00Z"
config.last_swap_at = "2026-03-31T18:10:00Z"
config.deploy_in_progress = False
config.deploy_in_progress_since = None
config.last_activity_at = None
return config
class TestSystemStatusPublic:
"""Tests for unauthenticated /api/health/system-status."""
@pytest.mark.asyncio
async def test_returns_all_services(
self, mock_encoding_status, mock_flacfetch_status, mock_separator_status
):
from backend.api.routes.health import system_status
with patch("backend.api.routes.health.check_encoding_worker_status", new_callable=AsyncMock, return_value=mock_encoding_status), \
patch("backend.api.routes.health.check_flacfetch_service_status", new_callable=AsyncMock, return_value=mock_flacfetch_status), \
patch("backend.api.routes.health.check_audio_separator_status", return_value=mock_separator_status), \
patch("backend.api.routes.health.VERSION", "0.155.3"), \
patch("backend.api.routes.health.COMMIT_SHA", "8e2a949a"), \
patch("backend.api.routes.health.PR_NUMBER", "644"), \
patch("backend.api.routes.health.PR_TITLE", "fix: blue-green deploy"), \
patch("backend.api.routes.health.STARTUP_TIME", "2026-03-31T18:10:00Z"):
result = await system_status(auth=None)
assert "services" in result
services = result["services"]
# All 5 services present
assert "frontend" in services
assert "backend" in services
assert "encoder" in services
assert "flacfetch" in services
assert "separator" in services
# Backend has build metadata
backend_svc = services["backend"]
assert backend_svc["version"] == "0.155.3"
assert backend_svc["commit_sha"] == "8e2a949a"
assert backend_svc["pr_number"] == "644"
# Encoder has status
assert services["encoder"]["status"] == "ok"
assert services["encoder"]["version"] == "0.155.3"
# No admin_details without auth
assert "admin_details" not in services["encoder"]
@pytest.mark.asyncio
async def test_offline_service(self, mock_flacfetch_status, mock_separator_status):
from backend.api.routes.health import system_status
offline_encoding = {
"configured": True,
"enabled": True,
"available": False,
"error": "Connection refused",
}
with patch("backend.api.routes.health.check_encoding_worker_status", new_callable=AsyncMock, return_value=offline_encoding), \
patch("backend.api.routes.health.check_flacfetch_service_status", new_callable=AsyncMock, return_value=mock_flacfetch_status), \
patch("backend.api.routes.health.check_audio_separator_status", return_value=mock_separator_status), \
patch("backend.api.routes.health.VERSION", "0.155.3"), \
patch("backend.api.routes.health.COMMIT_SHA", ""), \
patch("backend.api.routes.health.PR_NUMBER", ""), \
patch("backend.api.routes.health.PR_TITLE", ""), \
patch("backend.api.routes.health.STARTUP_TIME", "2026-03-31T18:10:00Z"):
result = await system_status(auth=None)
assert result["services"]["encoder"]["status"] == "offline"
class TestSystemStatusAdmin:
"""Tests for admin-authenticated /api/health/system-status."""
@pytest.mark.asyncio
async def test_admin_gets_bluegreen_details(
self, mock_encoding_status, mock_flacfetch_status, mock_separator_status, mock_encoding_worker_config
):
from backend.api.routes.health import system_status
from backend.services.auth_service import UserType
mock_auth = ("token123", UserType.ADMIN, -1)
mock_manager = MagicMock()
mock_manager.get_config.return_value = mock_encoding_worker_config
with patch("backend.api.routes.health.check_encoding_worker_status", new_callable=AsyncMock, return_value=mock_encoding_status), \
patch("backend.api.routes.health.check_flacfetch_service_status", new_callable=AsyncMock, return_value=mock_flacfetch_status), \
patch("backend.api.routes.health.check_audio_separator_status", return_value=mock_separator_status), \
patch("backend.api.routes.health.VERSION", "0.155.3"), \
patch("backend.api.routes.health.COMMIT_SHA", ""), \
patch("backend.api.routes.health.PR_NUMBER", ""), \
patch("backend.api.routes.health.PR_TITLE", ""), \
patch("backend.api.routes.health.STARTUP_TIME", "2026-03-31T18:10:00Z"), \
patch("backend.api.routes.health._get_encoding_worker_manager", return_value=mock_manager):
result = await system_status(auth=mock_auth)
encoder = result["services"]["encoder"]
assert "admin_details" in encoder
admin = encoder["admin_details"]
assert admin["primary_vm"] == "encoding-worker-b"
assert admin["secondary_vm"] == "encoding-worker-a"
assert admin["last_swap_at"] == "2026-03-31T18:10:00Z"
assert admin["deploy_in_progress"] is False
@@ -1256,6 +1256,7 @@ class TestCreateOrchestratorConfigFromJob:
job.gdrive_folder_id = None
job.keep_brand_code = None
job.existing_instrumental_gcs_path = None
job.file_urls = {'screens': {'title_png': 'jobs/test-123/screens/title.png', 'end_png': 'jobs/test-123/screens/end.png'}}
config = create_orchestrator_config_from_job(
job=job,
@@ -1269,7 +1270,7 @@ class TestCreateOrchestratorConfigFromJob:
assert config.title == "Test Title"
assert config.enable_cdg is True
assert config.enable_youtube_upload is True
assert config.title_video_path == "/tmp/test/Test Artist - Test Title (Title).mov"
assert config.title_video_path == "/tmp/test/Test Artist - Test Title (Title).png"
assert config.instrumental_audio_path == "/tmp/test/Test Artist - Test Title (Instrumental Clean).flac"
def test_create_config_from_job_with_existing_instrumental(self):
@@ -1290,6 +1291,7 @@ class TestCreateOrchestratorConfigFromJob:
job.gdrive_folder_id = None
job.keep_brand_code = None
job.existing_instrumental_gcs_path = "gs://bucket/instrumental.mp3"
job.file_urls = {'screens': {'title_png': 'screens/title.png', 'end_png': 'screens/end.png'}}
config = create_orchestrator_config_from_job(
job=job,
@@ -1329,6 +1331,7 @@ class TestCreateOrchestratorConfigFromJob:
job.gdrive_folder_id = None
job.keep_brand_code = None
job.existing_instrumental_gcs_path = None
job.file_urls = {'screens': {'title_png': 'screens/title.png', 'end_png': 'screens/end.png'}}
config = create_orchestrator_config_from_job(
job=job,
+15
View File
@@ -25,3 +25,18 @@ def get_version() -> str:
VERSION = get_version()
# Build metadata — set by CI during deployment
COMMIT_SHA = os.environ.get("COMMIT_SHA", "")
PR_NUMBER = os.environ.get("PR_NUMBER", "")
PR_TITLE = os.environ.get("PR_TITLE", "")
STARTUP_TIME = None # Set on first import
def _get_startup_time() -> str:
"""Record when the backend process started (proxy for deploy time)."""
from datetime import datetime, timezone
return datetime.now(timezone.utc).isoformat()
STARTUP_TIME = _get_startup_time()
+11 -6
View File
@@ -319,12 +319,17 @@ async def process_render_video(job_id: str) -> bool:
with open(updated_path, 'r', encoding='utf-8') as f:
updated_data = json.load(f)
# Same construction path as preview — prevents divergence
correction_result = CorrectionOperations.update_correction_result_with_data(
base_result, updated_data
)
job_log.info("Applied user corrections via CorrectionOperations")
logger.info(f"Job {job_id}: Applied user corrections via CorrectionOperations")
if isinstance(updated_data, dict) and "corrections" in updated_data:
# Same construction path as preview — prevents divergence
correction_result = CorrectionOperations.update_correction_result_with_data(
base_result, updated_data
)
job_log.info("Applied user corrections via CorrectionOperations")
logger.info(f"Job {job_id}: Applied user corrections via CorrectionOperations")
else:
job_log.warning("corrections_updated.json exists but has no 'corrections' key, using base result")
logger.warning(f"Job {job_id}: corrections_updated.json has no 'corrections' key, using base result")
correction_result = base_result
else:
correction_result = base_result
+34 -40
View File
@@ -385,7 +385,9 @@ async def _generate_title_screen(
logger.info(f"Job {job_id}: Title format - bg_image: {title_format.get('background_image')}, font: {title_format.get('font')}")
# Generate title screen (synchronous method)
# Generate title screen images only (MOV video is generated on GCE encoding worker)
# Pass duration=0 to skip FFmpeg video creation — Cloud Run doesn't have enough
# memory for 4K H.264 encoding after right-sizing to 2Gi (PR #640).
video_generator.create_title_video(
artist=job.artist,
title=job.title,
@@ -393,12 +395,13 @@ async def _generate_title_screen(
output_image_filepath_noext=output_image_filepath_noext,
output_video_filepath=output_video_filepath,
existing_title_image=title_format.get('existing_image'),
intro_video_duration=intro_duration
intro_video_duration=0,
)
if os.path.exists(output_video_filepath):
logger.info(f"Job {job_id}: Title screen generated at {output_video_filepath}")
return output_video_filepath
output_png = f"{output_image_filepath_noext}.png"
if os.path.exists(output_png):
logger.info(f"Job {job_id}: Title screen image generated at {output_png}")
return output_png
else:
logger.error(f"Job {job_id}: Title screen generation returned no file")
return None
@@ -457,7 +460,9 @@ async def _generate_end_screen(
logger.info(f"Job {job_id}: End format - bg_image: {end_format.get('background_image')}, font: {end_format.get('font')}")
# Generate end screen (synchronous method)
# Generate end screen images only (MOV video is generated on GCE encoding worker)
# Pass duration=0 to skip FFmpeg video creation — Cloud Run doesn't have enough
# memory for 4K H.264 encoding after right-sizing to 2Gi (PR #640).
video_generator.create_end_video(
artist=job.artist,
title=job.title,
@@ -465,12 +470,13 @@ async def _generate_end_screen(
output_image_filepath_noext=output_image_filepath_noext,
output_video_filepath=output_video_filepath,
existing_end_image=end_format.get('existing_image'),
end_video_duration=end_duration
end_video_duration=0,
)
if os.path.exists(output_video_filepath):
logger.info(f"Job {job_id}: End screen generated at {output_video_filepath}")
return output_video_filepath
output_png = f"{output_image_filepath_noext}.png"
if os.path.exists(output_png):
logger.info(f"Job {job_id}: End screen image generated at {output_png}")
return output_png
else:
logger.error(f"Job {job_id}: End screen generation returned no file")
return None
@@ -488,46 +494,34 @@ async def _upload_screens(
end_screen_path: str
) -> None:
"""
Upload title and end screens to GCS (video + images).
Upload title and end screen images to GCS.
Single Responsibility: Only handles uploads.
VideoGenerator creates .mov, .jpg, and .png files when configured with
output_png=True and output_jpg=True. We upload all three formats
for feature parity with the local CLI.
VideoGenerator creates .jpg and .png files when configured with
output_png=True and output_jpg=True. MOV video generation is handled
by the GCE encoding worker (not Cloud Run) to avoid OOM with 4K H.264.
Args:
job_id: Job ID
job_manager: Job manager instance
storage: Storage service instance
title_screen_path: Path to title screen video (.mov)
end_screen_path: Path to end screen video (.mov)
title_screen_path: Path to title screen image (.png)
end_screen_path: Path to end screen image (.png)
"""
# Upload title screen video
title_gcs_path = f"jobs/{job_id}/screens/title.mov"
title_url = storage.upload_file(title_screen_path, title_gcs_path)
job_manager.update_file_url(job_id, 'screens', 'title', title_url)
logger.info(f"Job {job_id}: Uploaded title screen video")
# Upload title screen images (.jpg and .png - created by VideoGenerator)
title_base = title_screen_path.replace('.mov', '')
for ext, key in [('.jpg', 'title_jpg'), ('.png', 'title_png')]:
# 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 video
end_gcs_path = f"jobs/{job_id}/screens/end.mov"
end_url = storage.upload_file(end_screen_path, end_gcs_path)
job_manager.update_file_url(job_id, 'screens', 'end', end_url)
logger.info(f"Job {job_id}: Uploaded end screen video")
# Upload end screen images (.jpg and .png - created by VideoGenerator)
end_base = end_screen_path.replace('.mov', '')
for ext, key in [('.jpg', 'end_jpg'), ('.png', 'end_png')]:
# 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}"
+27 -21
View File
@@ -121,13 +121,12 @@ async def _encode_via_gce(
def progress_callback(progress: int):
# Update job progress (encoding is 75-95% of total)
# Use update_job instead of transition_to_state since job is already in ENCODING state
scaled_progress = 75 + int(progress * 0.2) # Map 0-100 to 75-95
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.ENCODING,
progress=scaled_progress,
message=f"Encoding videos ({progress}%)"
)
job_manager.update_job(job_id, {
'progress': scaled_progress,
'message': f"Encoding videos ({progress}%)",
})
try:
# Submit and wait for encoding
@@ -1232,9 +1231,11 @@ def _validate_prerequisites(job) -> bool:
logger.error(f"Job {job.job_id}: Invalid instrumental selection: {instrumental_selection}")
return False
# Check screens exist
# Check screens exist (MOV or PNG — MOV is no longer uploaded, PNG is the new default)
screens = job.file_urls.get('screens', {})
if not screens.get('title') or not screens.get('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
@@ -1288,19 +1289,24 @@ async def _setup_working_directory(
log_progress("Setting up working directory")
# Download title screen
log_progress("Downloading title screen...")
title_url = job.file_urls['screens']['title']
title_path = os.path.join(temp_dir, f"{base_name} (Title).mov")
storage.download_file(title_url, title_path)
log_progress("Downloaded title screen")
# Download end screen
log_progress("Downloading end screen...")
end_url = job.file_urls['screens']['end']
end_path = os.path.join(temp_dir, f"{base_name} (End).mov")
storage.download_file(end_url, end_path)
log_progress("Downloaded end screen")
# Download title screen (PNG — MOV video is generated by the GCE encoding worker)
screens = job.file_urls.get('screens', {})
title_url = screens.get('title') or screens.get('title_png')
if title_url:
ext = os.path.splitext(title_url)[1] or '.png'
title_path = os.path.join(temp_dir, f"{base_name} (Title){ext}")
log_progress(f"Downloading title screen ({ext})...")
storage.download_file(title_url, title_path)
log_progress("Downloaded title screen")
# Download end screen (PNG — MOV video is generated by the GCE encoding worker)
end_url = screens.get('end') or screens.get('end_png')
if end_url:
ext = os.path.splitext(end_url)[1] or '.png'
end_path = os.path.join(temp_dir, f"{base_name} (End){ext}")
log_progress(f"Downloading end screen ({ext})...")
storage.download_file(end_url, end_path)
log_progress("Downloaded end screen")
# Download lyrics video (with vocals) - this is the largest file, ~1-2GB
log_progress("Downloading karaoke video (largest file, may take 1-2 minutes)...")
+19 -3
View File
@@ -836,6 +836,22 @@ class VideoWorkerOrchestrator:
# Never fail the pipeline for validation
def _screen_ext(job, screen_type: str) -> str:
"""Get the file extension for a screen (title/end) based on what's in GCS.
New jobs have only PNG (MOV is generated by GCE encoding worker).
Legacy jobs may still have MOV uploaded by the old screens_worker.
"""
screens = job.file_urls.get('screens', {})
# Check for MOV first (legacy), then fall back to PNG (new)
url = screens.get(screen_type) or screens.get(f'{screen_type}_png')
if url:
ext = os.path.splitext(url)[1]
if ext:
return ext
return '.png'
def create_orchestrator_config_from_job(
job,
temp_dir: str,
@@ -893,12 +909,12 @@ def create_orchestrator_config_from_job(
artist=job.artist,
title=job.title,
# Input files
title_video_path=os.path.join(temp_dir, f"{base_name} (Title).mov"),
# 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')}"),
# 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).mov"),
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"),
+15
View File
@@ -1055,3 +1055,18 @@ For this bug, the missing test was: "does `transcribe_lyrics()` return `lyrics_d
**Key insight:** Background cron jobs need monitoring for auth failures — a 401 from a scheduler is silent by default. When adding new Cloud Scheduler endpoints, verify the auth flow end-to-end (check Cloud Logging for 200s after deployment). Don't assume OIDC "just works" with custom auth middleware — Cloud Tasks uses `X-Admin-Token` (custom header) for a reason, while Cloud Scheduler only sends OIDC.
### GCE Disk Cache Must Validate Content, Not Just URI (Mar 2026)
**Problem:** The GCE encoding worker's style asset disk cache (`/var/cache/karaoke-gen/styles/`) keyed on `SHA-256(GCS URI)`. When a file at a GCS path was replaced with different content (e.g., fixing corrupt 106-byte placeholder PNGs with correct 2.8MB files), the cache served the stale version indefinitely.
**Fix:** On cache hit, do a lightweight `blob.reload()` (HEAD request) to get the GCS object's current size. Compare with cached file size — re-download on mismatch. One metadata call per cache hit is a small price vs serving corrupt assets.
**Key insight:** Any local disk cache of remote objects needs a staleness check. URI-only cache keys assume content is immutable at that path — which is rarely guaranteed in GCS/S3. Size is the cheapest validation; for stronger guarantees, compare ETags or generation numbers.
### Don't Write Empty Sentinel Files to GCS (Mar 2026)
**Problem:** The review complete endpoint wrote `corrections_updated.json` to GCS even when no corrections were provided (e.g., admin API reset + complete without correction data). It wrote `{}` (empty dict). Downstream, render workers check `file_exists("corrections_updated.json")` — if present, they download and pass it to `CorrectionOperations.update_correction_result_with_data()` which does `updated_data["corrections"]`, causing `KeyError`.
**Fix:** (1) Root cause: Don't write `corrections_updated.json` unless the payload actually contains a `"corrections"` key. (2) Defensive: Both GCE and Cloud Run workers validate the downloaded JSON has the expected structure before processing, falling back to base result if not.
**Key insight:** When a file's existence is used as a boolean signal ("corrections were updated"), never write it with empty/invalid content. The existence check and content processing must agree on what constitutes a valid file. Apply defense in depth: fix the writer AND validate in readers.
@@ -0,0 +1,66 @@
# Plan: Move Screen Video Generation to GCE Encoding Worker
**Created:** 2026-03-31
**Branch:** feat/sess-20260331-1619-investigate-render-failure
**Status:** Draft
## Overview
Screen video generation (title.mov, end.mov) currently runs FFmpeg in the Cloud Run API container via `VideoGenerator._create_video_from_image()`. After PR #640 right-sized Cloud Run to 2CPU/2Gi, the 4K H.264 encoding OOMs silently (producing 36-byte empty MOV shells). This breaks all downstream encoding since `encode_lossless_mp4` can't concatenate corrupt inputs.
Fix: Stop generating MOV in screens_worker. Generate them on the GCE encoding worker (which has adequate resources) just before the encoding step.
## Root Cause
- `VideoGenerator._create_video_from_image()` uses `os.system()` — silently swallows FFmpeg failures
- 4K H.264 encoding needs more than 2Gi RAM
- screens_worker checks `os.path.exists(output_video_filepath)` — the 36-byte shell passes this check
- All jobs since the Cloud Run right-sizing (March 31) are affected
## Implementation Steps
### 1. screens_worker.py — Stop generating MOV videos
**Changes:**
- In `_generate_title_screen`: pass `intro_video_duration=0` to skip MOV creation, return PNG path
- In `_generate_end_screen`: pass `end_video_duration=0` to skip MOV creation, return PNG path
- In `_upload_screens`: only upload PNG and JPG (remove MOV upload logic)
- Update function return types/docstrings to reflect image-only output
**Why duration=0 works:** `VideoGenerator._save_output_files` already has `if duration > 0:` guard around `_create_video_from_image`.
### 2. gce_encoding/main.py — Generate MOV from PNG before encoding
**Changes in `run_encoding()`:**
- After `find_file` for title/end videos, check if they're missing or invalid (< 1KB)
- If missing/invalid, look for corresponding PNG: `screens/title.png`, `screens/end.png`
- Generate MOV from PNG using `subprocess.run()` with proper error handling
- Use same FFmpeg command as `_create_video_from_image` but with error checking
- Log clearly when generating MOV from PNG vs using existing MOV
**Backwards compatible:** Old jobs with valid MOVs still work. New jobs with only PNGs get MOVs generated on GCE.
### 3. Fix `_create_video_from_image` error handling (defensive)
**Changes in `karaoke_gen/video_generator.py`:**
- Replace `os.system()` with `subprocess.run(check=True)`
- Log stderr on failure
- This protects the local CLI path too
## Files to Create/Modify
| File | Action | Description |
|------|--------|-------------|
| `backend/workers/screens_worker.py` | Modify | Stop generating MOV, return/upload images only |
| `backend/services/gce_encoding/main.py` | Modify | Generate MOV from PNG in `run_encoding()` |
| `karaoke_gen/video_generator.py` | Modify | Replace `os.system()` with `subprocess.run()` |
## Testing Strategy
- Unit tests for GCE worker MOV generation helper
- Verify existing encoding tests still pass
- Manually re-run job f0d51a0a after deploy to confirm fix
## Rollback Plan
Revert the 3 files. The old behavior (generating MOV in Cloud Run) would still fail with 2Gi, but increasing memory to 4Gi would restore it.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,213 @@
# Service Health Status Modal — Design Spec
## Overview
Replace the static footer version/status line with a clickable element that opens a modal showing detailed system status. Non-admin users see service health, versions, and deploy info. Admin users additionally see blue-green encoder deployment details. Each service links to the PR that produced its current version.
## Footer Changes
The existing footer line (`Frontend: v0.155.3 | Backend: v0.155.3 | ● Encoder: v0.155.3 | ...`) becomes a single clickable element. On hover: `cursor: pointer`, slight opacity change. No other visual changes to the footer layout.
Clicking anywhere on the version/status line opens the modal.
## Modal — Public View (everyone)
### Layout
- Standard modal: dark backdrop (click to dismiss), X close button, title "System Status"
- Responsive card grid: 2 columns on desktop, 1 column on mobile
- 5 service cards: **Frontend**, **Backend**, **Encoder**, **Flacfetch**, **Separator**
### Card Contents
Each card shows:
| Element | Example |
|---------|---------|
| Status indicator | Green dot (●) + "Healthy" or red dot (○) + "Offline" |
| Version | `v0.155.3` |
| Deploy time | "Deployed 2 hours ago" (relative) |
| Latest change | `#644 — fix blue-green deploy` (clickable link to GitHub PR) |
The "Latest change" line links to the GitHub PR that produced the currently deployed version. If unavailable, this line is omitted.
## Modal — Admin View (additional detail)
When the user has an admin token (stored in localStorage from login), the modal request includes it and the response includes extra data.
### Encoder Blue-Green Section
Inside the Encoder card, below the standard info, an expandable section labeled "Blue-Green Deployment" shows:
- **Two side-by-side mini-cards**: Primary (green-tinted border) and Secondary (muted/grey)
- Each mini-card shows:
- VM name (e.g., `encoding-worker-b`)
- Version (e.g., `v0.155.3`)
- Role label: "PRIMARY" (green) or "SECONDARY (stopped)" (muted)
- **Deploy status line**: "Last swap: 2 hours ago" or "⚠ Deploy in progress..." (amber)
- **Active jobs**: count on primary, if > 0
### Admin Detail on Other Cards
For Backend, Flacfetch, and Separator cards, admin view additionally shows:
- Error message if status is offline (from the health check error field)
No extra admin detail needed for Frontend (it's a static site).
## New Backend Endpoint
### `GET /api/health/system-status`
Single endpoint that aggregates all service health data. Avoids the current pattern of 4 separate fetches.
**Authentication**: Optional `X-Admin-Token` header. If valid admin token, response includes `admin_details`. If omitted or invalid, those fields are absent.
**Response (public fields)**:
```json
{
"services": {
"frontend": {
"status": "ok",
"version": "0.155.3",
"deployed_at": "2026-03-31T18:10:00Z",
"commit_sha": "8e2a949a",
"pr_number": 644,
"pr_title": "fix: complete blue-green deploy test payload and status check"
},
"backend": {
"status": "ok",
"version": "0.155.3",
"deployed_at": "2026-03-31T18:10:00Z",
"commit_sha": "8e2a949a",
"pr_number": 644,
"pr_title": "fix: complete blue-green deploy test payload and status check"
},
"encoder": {
"status": "ok",
"version": "0.155.3",
"deployed_at": "2026-03-31T18:10:00Z",
"active_jobs": 0
},
"flacfetch": {
"status": "ok",
"version": "0.19.1"
},
"separator": {
"status": "ok",
"version": "0.4.3"
}
}
}
```
**Additional fields when admin token is valid**:
```json
{
"services": {
"encoder": {
"admin_details": {
"primary_vm": "encoding-worker-b",
"primary_ip": "34.10.189.118",
"primary_version": "0.155.3",
"primary_deployed_at": "2026-03-31T18:10:00Z",
"secondary_vm": "encoding-worker-a",
"secondary_ip": "34.57.78.246",
"secondary_version": "0.155.2",
"secondary_deployed_at": "2026-03-29T14:00:00Z",
"last_swap_at": "2026-03-31T18:10:00Z",
"deploy_in_progress": false,
"active_jobs": 0,
"queue_length": 0
}
},
"flacfetch": {
"admin_details": {
"error": null
}
},
"separator": {
"admin_details": {
"error": null
}
}
}
}
```
## Build Metadata — Git SHA and PR Info
Currently no git metadata is baked into builds. We need to add this.
### CI Changes (`.github/workflows/ci.yml`)
Add a step early in the deploy job that captures git info:
```yaml
- name: Capture build metadata
id: build-meta
run: |
echo "sha=${GITHUB_SHA::8}" >> $GITHUB_OUTPUT
# For merge commits, extract PR number from commit message
PR_NUM=$(git log -1 --format=%s | grep -oP '#\K[0-9]+' | head -1)
PR_TITLE=$(gh pr view "$PR_NUM" --json title -q .title 2>/dev/null || echo "")
echo "pr_number=${PR_NUM}" >> $GITHUB_OUTPUT
echo "pr_title=${PR_TITLE}" >> $GITHUB_OUTPUT
```
### Where metadata is stored
| Service | Storage mechanism |
|---------|------------------|
| **Frontend** | New env vars `NEXT_PUBLIC_COMMIT_SHA`, `NEXT_PUBLIC_PR_NUMBER`, `NEXT_PUBLIC_PR_TITLE`, `NEXT_PUBLIC_BUILD_TIME` set in CI before `npm run build`. Baked into the static bundle at build time via `next.config.mjs`. The `deployed_at` for frontend is the build timestamp (close enough to deploy time for Cloudflare Pages). |
| **Backend** | New env vars `COMMIT_SHA`, `PR_NUMBER`, `PR_TITLE` set on the Cloud Run service. Read at runtime in `backend/version.py`. |
| **Encoder** | Written to GCS version manifest alongside the existing `version.txt`. The GCE worker reads it on startup and includes in `/health` response. |
| **Flacfetch / Separator** | These are separate repos with their own CI. PR info can be added later — for now, omit the "Latest change" line for these services. |
### GitHub PR Link Format
The frontend constructs the PR link as:
```
https://github.com/nomadkaraoke/karaoke-gen/pull/{pr_number}
```
Displayed as: `#{pr_number} — {pr_title}` (truncated to ~60 chars if needed).
## Frontend Components
### New files
- `frontend/components/system-status-modal.tsx` — the modal component
### Modified files
- `frontend/components/version-footer.tsx` — make status line clickable, add modal toggle state
- `frontend/lib/api.ts` — add `SystemStatus` types and `getSystemStatus()` method
- `frontend/next.config.mjs` — pass through new `NEXT_PUBLIC_COMMIT_SHA`, `NEXT_PUBLIC_PR_NUMBER`, `NEXT_PUBLIC_PR_TITLE` env vars
### Modified backend files
- `backend/api/routes/health.py` — new `/api/health/system-status` endpoint
- `backend/version.py` — read `COMMIT_SHA`, `PR_NUMBER`, `PR_TITLE` env vars
- `.github/workflows/ci.yml` — capture build metadata, pass to builds/deploys
### Data Flow
1. User clicks footer → modal opens, state set to loading
2. Modal calls `GET /api/health/system-status` (with admin token header if available in localStorage)
3. Endpoint aggregates: existing health checks + Firestore blue-green config + build metadata env vars
4. Frontend renders cards from response
5. No auto-refresh — data is fresh on each open
## Styling
- Follow existing project design patterns (Tailwind, CSS variables for theming)
- Modal uses the same dark theme as the rest of the app
- Cards use `var(--card-border)`, `var(--card-bg)` etc. for consistency
- Green: `text-green-500` for healthy, red: `text-red-500` for offline
- Blue-green section uses amber accent (`text-amber-500`, `border-amber-500/30`) to distinguish it as an operational detail
## Out of Scope
- Auto-refresh / polling in the modal (can be added later)
- Flacfetch and Separator PR info (separate repos, separate CI)
- Historical deploy data or deploy log
- Notifications or alerts for status changes
+4 -4
View File
@@ -64,8 +64,8 @@ function AppPageContent() {
return saved ? Number(saved) : 10
})
const [statusFilter, setStatusFilter] = useState<string>(() => {
if (typeof window === "undefined") return "active"
return localStorage.getItem("nomad-karaoke-status-filter") || "active"
if (typeof window === "undefined") return "all"
return localStorage.getItem("nomad-karaoke-status-filter") || "all"
})
const [searchInput, setSearchInput] = useState("")
const [searchQuery, setSearchQuery] = useState("")
@@ -453,7 +453,7 @@ function AppPageContent() {
<CardDescription style={{ color: 'var(--text-muted)' }}>
{!hasFetchedSuccessfully
? 'Loading...'
: searchQuery || statusFilter !== 'active'
: searchQuery || (statusFilter !== 'all' && statusFilter !== 'active')
? `${jobs.length} job${jobs.length !== 1 ? 's' : ''} matching filters`
: `${jobs.length} job${jobs.length !== 1 ? 's' : ''}`}
</CardDescription>
@@ -466,7 +466,7 @@ function AppPageContent() {
<Loader2 className="w-12 h-12 mx-auto mb-3 opacity-50 animate-spin" />
<p>Loading jobs...</p>
</>
) : searchQuery || statusFilter !== 'active' ? (
) : searchQuery || (statusFilter !== 'all' && statusFilter !== 'active') ? (
<>
<Search className="w-12 h-12 mx-auto mb-3 opacity-50" />
<p>No jobs match your filters.</p>
+244
View File
@@ -0,0 +1,244 @@
"use client";
import { useEffect, useState } from "react";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { api, SystemStatus, ServiceStatus } from "@/lib/api";
interface SystemStatusModalProps {
open: boolean;
onClose: () => void;
}
function formatRelativeTime(isoString: string | null | undefined): string {
if (!isoString) return "";
const date = new Date(isoString);
const now = new Date();
const diffMs = now.getTime() - date.getTime();
const diffMin = Math.floor(diffMs / 60000);
if (diffMin < 1) return "just now";
if (diffMin < 60) return `${diffMin}m ago`;
const diffHours = Math.floor(diffMin / 60);
if (diffHours < 24) return `${diffHours}h ago`;
const diffDays = Math.floor(diffHours / 24);
return `${diffDays}d ago`;
}
function truncate(str: string, maxLen: number): string {
if (str.length <= maxLen) return str;
return str.slice(0, maxLen - 1) + "\u2026";
}
function StatusDot({ status }: { status: string }) {
const isOk = status === "ok";
return (
<span className={isOk ? "text-green-500" : "text-red-500"}>
{isOk ? "\u25CF" : "\u25CB"}
</span>
);
}
function ServiceCard({
name,
service,
children,
}: {
name: string;
service: ServiceStatus;
children?: React.ReactNode;
}) {
const isOk = service.status === "ok";
return (
<div
className="rounded-lg border p-4"
style={{
borderColor: "var(--card-border)",
backgroundColor: "var(--card-bg)",
}}
>
<div className="flex items-center justify-between mb-1">
<div className="flex items-center gap-2">
<StatusDot status={service.status} />
<span className="font-medium text-sm">{name}</span>
</div>
<span className="text-xs opacity-60">
{isOk ? "Healthy" : "Offline"}
</span>
</div>
{service.version && (
<div className="text-xs opacity-75 mt-1">v{service.version}</div>
)}
{service.deployed_at && (
<div className="text-xs opacity-50 mt-0.5">
Deployed {formatRelativeTime(service.deployed_at)}
</div>
)}
{service.pr_number && (
<div className="text-xs mt-1">
<a
href={`https://github.com/nomadkaraoke/karaoke-gen/pull/${service.pr_number}`}
target="_blank"
rel="noopener noreferrer"
className="text-amber-500 hover:underline"
>
#{service.pr_number}
</a>
{service.pr_title && (
<span className="opacity-60">
{" \u2014 "}
{truncate(service.pr_title, 50)}
</span>
)}
</div>
)}
{children}
</div>
);
}
function BlueGreenSection({ details }: { details: NonNullable<ServiceStatus["admin_details"]> }) {
const [expanded, setExpanded] = useState(false);
return (
<div className="mt-3">
<button
onClick={() => setExpanded(!expanded)}
className="text-xs text-amber-500 hover:text-amber-400 flex items-center gap-1"
>
<span>{expanded ? "\u25BE" : "\u25B8"}</span>
Blue-Green Deployment
{details.deploy_in_progress && (
<span className="text-amber-400 animate-pulse ml-1">\u26A0 deploying...</span>
)}
</button>
{expanded && (
<div className="mt-2 grid grid-cols-2 gap-2">
{/* Primary */}
<div
className="rounded p-2 text-xs border"
style={{
borderColor: "rgba(74,222,128,0.3)",
backgroundColor: "rgba(74,222,128,0.05)",
}}
>
<div className="text-green-500 text-[10px] font-semibold uppercase tracking-wider">
Primary
</div>
<div className="mt-1 font-mono">{details.primary_vm}</div>
<div className="opacity-60">v{details.primary_version}</div>
{details.primary_deployed_at && (
<div className="opacity-40">
{formatRelativeTime(details.primary_deployed_at)}
</div>
)}
</div>
{/* Secondary */}
<div
className="rounded p-2 text-xs border"
style={{
borderColor: "var(--card-border)",
backgroundColor: "rgba(255,255,255,0.02)",
}}
>
<div className="text-[10px] font-semibold uppercase tracking-wider opacity-50">
Secondary (stopped)
</div>
<div className="mt-1 font-mono">{details.secondary_vm}</div>
{details.secondary_version && (
<div className="opacity-60">v{details.secondary_version}</div>
)}
</div>
{/* Metadata row */}
<div className="col-span-2 text-[10px] opacity-40 mt-1">
{details.last_swap_at && (
<span>Last swap: {formatRelativeTime(details.last_swap_at)}</span>
)}
{details.active_jobs != null && details.active_jobs > 0 && (
<span className="ml-3">Active jobs: {details.active_jobs}</span>
)}
</div>
</div>
)}
</div>
);
}
export function SystemStatusModal({ open, onClose }: SystemStatusModalProps) {
const [status, setStatus] = useState<SystemStatus | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!open) return;
setLoading(true);
setError(null);
api
.getSystemStatus()
.then(setStatus)
.catch((e) => setError(e.message || "Failed to fetch status"))
.finally(() => setLoading(false));
}, [open]);
const frontendVersion = process.env.NEXT_PUBLIC_APP_VERSION || "dev";
const frontendCommitSha = process.env.NEXT_PUBLIC_COMMIT_SHA || "";
const frontendPrNumber = process.env.NEXT_PUBLIC_PR_NUMBER || "";
const frontendPrTitle = process.env.NEXT_PUBLIC_PR_TITLE || "";
const frontendBuildTime = process.env.NEXT_PUBLIC_BUILD_TIME || "";
// Override frontend service with build-time values
const services = status?.services;
const frontendService: ServiceStatus = {
status: "ok",
version: frontendVersion,
deployed_at: frontendBuildTime || undefined,
commit_sha: frontendCommitSha || undefined,
pr_number: frontendPrNumber || undefined,
pr_title: frontendPrTitle || undefined,
};
return (
<Dialog open={open} onOpenChange={(isOpen) => !isOpen && onClose()}>
<DialogContent className="sm:max-w-lg" style={{ backgroundColor: "var(--card-bg)", borderColor: "var(--card-border)" }}>
<DialogHeader>
<DialogTitle className="text-foreground">System Status</DialogTitle>
</DialogHeader>
{loading && (
<div className="py-8 text-center text-sm opacity-60">Loading...</div>
)}
{error && (
<div className="py-8 text-center text-sm text-red-500">{error}</div>
)}
{services && !loading && (
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 mt-2">
<ServiceCard name="Frontend" service={frontendService} />
<ServiceCard name="Backend" service={services.backend} />
<ServiceCard name="Encoder" service={services.encoder}>
{services.encoder.admin_details &&
services.encoder.admin_details.primary_vm && (
<BlueGreenSection details={services.encoder.admin_details} />
)}
</ServiceCard>
<ServiceCard name="Flacfetch" service={services.flacfetch} />
<ServiceCard name="Separator" service={services.separator} />
</div>
)}
</DialogContent>
</Dialog>
);
}
+47 -66
View File
@@ -2,13 +2,14 @@
import { useEffect, useState } from "react";
import { api, EncodingWorkerHealth, FlacfetchHealth, AudioSeparatorHealth } from "@/lib/api";
import { SystemStatusModal } from "./system-status-modal";
export function VersionFooter() {
const [backendVersion, setBackendVersion] = useState<string | null>(null);
const [encodingWorker, setEncodingWorker] = useState<EncodingWorkerHealth | null>(null);
const [flacfetch, setFlacfetch] = useState<FlacfetchHealth | null>(null);
const [audioSeparator, setAudioSeparator] = useState<AudioSeparatorHealth | null>(null);
// Frontend version is injected at build time from pyproject.toml
const [modalOpen, setModalOpen] = useState(false);
const frontendVersion = process.env.NEXT_PUBLIC_APP_VERSION || "dev";
useEffect(() => {
@@ -58,27 +59,18 @@ export function VersionFooter() {
fetchAudioSeparatorHealth();
}, []);
// Render encoding worker status indicator
const renderEncodingWorkerStatus = () => {
if (!encodingWorker) {
return null;
}
if (encodingWorker.status === "not_configured") {
return null; // Don't show if not configured
}
if (!encodingWorker) return null;
if (encodingWorker.status === "not_configured") return null;
const isHealthy = encodingWorker.available && encodingWorker.status === "ok";
const statusColor = isHealthy ? "text-green-500" : "text-red-500";
const statusDot = isHealthy ? "●" : "○";
const statusDot = isHealthy ? "\u25CF" : "\u25CB";
// Build status text
let statusText = isHealthy ? "Encoder" : "Encoder offline";
if (isHealthy && encodingWorker.version) {
statusText = `Encoder: v${encodingWorker.version}`;
}
// Add active jobs indicator if there are any
if (isHealthy && encodingWorker.active_jobs && encodingWorker.active_jobs > 0) {
statusText += ` (${encodingWorker.active_jobs} active)`;
}
@@ -86,29 +78,19 @@ export function VersionFooter() {
return (
<>
{" | "}
<span className={statusColor} title={isHealthy ? "Encoding worker healthy" : encodingWorker.error || "Encoding worker offline"}>
{statusDot}
</span>{" "}
{statusText}
<span className={statusColor}>{statusDot}</span> {statusText}
</>
);
};
// Render flacfetch status indicator
const renderFlacfetchStatus = () => {
if (!flacfetch) {
return null;
}
if (flacfetch.status === "not_configured") {
return null; // Don't show if not configured
}
if (!flacfetch) return null;
if (flacfetch.status === "not_configured") return null;
const isHealthy = flacfetch.available && flacfetch.status === "ok";
const statusColor = isHealthy ? "text-green-500" : "text-red-500";
const statusDot = isHealthy ? "●" : "○";
const statusDot = isHealthy ? "\u25CF" : "\u25CB";
// Build status text
let statusText = isHealthy ? "Flacfetch" : "Flacfetch offline";
if (isHealthy && flacfetch.version) {
statusText = `Flacfetch: v${flacfetch.version}`;
@@ -117,27 +99,18 @@ export function VersionFooter() {
return (
<>
{" | "}
<span className={statusColor} title={isHealthy ? "Flacfetch service healthy" : flacfetch.error || "Flacfetch service offline"}>
{statusDot}
</span>{" "}
{statusText}
<span className={statusColor}>{statusDot}</span> {statusText}
</>
);
};
// Render audio separator status indicator
const renderAudioSeparatorStatus = () => {
if (!audioSeparator) {
return null;
}
if (audioSeparator.status === "not_configured") {
return null;
}
if (!audioSeparator) return null;
if (audioSeparator.status === "not_configured") return null;
const isHealthy = audioSeparator.available && audioSeparator.status === "ok";
const statusColor = isHealthy ? "text-green-500" : "text-red-500";
const statusDot = isHealthy ? "●" : "○";
const statusDot = isHealthy ? "\u25CF" : "\u25CB";
let statusText = isHealthy ? "Separator" : "Separator offline";
if (isHealthy && audioSeparator.version) {
@@ -147,36 +120,44 @@ export function VersionFooter() {
return (
<>
{" | "}
<span className={statusColor} title={isHealthy ? "Audio separator healthy" : audioSeparator.error || "Audio separator offline"}>
{statusDot}
</span>{" "}
{statusText}
<span className={statusColor}>{statusDot}</span> {statusText}
</>
);
};
return (
<footer className="border-t mt-12 py-6" style={{ borderColor: 'var(--card-border)' }}>
<div className="px-4 text-center text-sm" style={{ color: 'var(--text-muted)' }}>
<p>
Powered by{" "}
<a href="https://github.com/nomadkaraoke/karaoke-gen" className="text-amber-500 hover:underline">
karaoke-gen
</a>
</p>
<p className="mt-1 text-xs opacity-75">
Frontend: v{frontendVersion}
{backendVersion && (
<>
{" | "}
Backend: v{backendVersion}
</>
)}
{renderEncodingWorkerStatus()}
{renderFlacfetchStatus()}
{renderAudioSeparatorStatus()}
</p>
</div>
</footer>
<>
<footer className="border-t mt-12 py-6" style={{ borderColor: 'var(--card-border)' }}>
<div className="px-4 text-center text-sm" style={{ color: 'var(--text-muted)' }}>
<p>
Powered by{" "}
<a href="https://github.com/nomadkaraoke/karaoke-gen" className="text-amber-500 hover:underline">
karaoke-gen
</a>
</p>
<p
className="mt-1 text-xs opacity-75 cursor-pointer hover:opacity-100 transition-opacity"
onClick={() => setModalOpen(true)}
title="Click for detailed system status"
>
Frontend: v{frontendVersion}
{backendVersion && (
<>
{" | "}
Backend: v{backendVersion}
</>
)}
{renderEncodingWorkerStatus()}
{renderFlacfetchStatus()}
{renderAudioSeparatorStatus()}
</p>
</div>
</footer>
<SystemStatusModal
open={modalOpen}
onClose={() => setModalOpen(false)}
/>
</>
);
}
+16 -2
View File
@@ -300,7 +300,14 @@ test.describe('Demo Video Recording', () => {
break;
}
const statusText = await jobCard.textContent() || '';
let statusText: string;
try {
statusText = await jobCard.textContent({ timeout: 15000 }) || '';
} catch {
console.log(' Job card temporarily unavailable, retrying...');
await page.waitForTimeout(5000);
continue;
}
if (statusText.toLowerCase().includes('failed')) {
throw new Error('Job failed during processing');
}
@@ -456,7 +463,14 @@ test.describe('Demo Video Recording', () => {
await page.waitForTimeout(2000);
}
const statusText = await jobCard.textContent() || '';
let statusText: string;
try {
statusText = await jobCard.textContent({ timeout: 15000 }) || '';
} catch {
console.log(' Job card temporarily unavailable, retrying...');
await page.waitForTimeout(5000);
continue;
}
if (statusText.toLowerCase().includes('complete') && !statusText.toLowerCase().includes('prep')) {
isComplete = true;
break;
@@ -568,7 +568,15 @@ test.describe('E2E Happy Path - Real User with Full UI Interactions', () => {
}
// Check job card status text
const statusText = await jobCard.textContent() || '';
// Job card may briefly disappear during re-renders; retry on next poll if so
let statusText: string;
try {
statusText = await jobCard.textContent({ timeout: 15000 }) || '';
} catch {
console.log(` [${elapsedMin}m ${elapsedSec}s] Job card temporarily unavailable, retrying...`);
await page.waitForTimeout(5000);
continue;
}
// Check if the "Review Lyrics" link is visible (most reliable indicator)
const reviewLink = jobCard.getByRole('link', { name: /review lyrics/i });
@@ -825,13 +833,49 @@ test.describe('E2E Happy Path - Real User with Full UI Interactions', () => {
// Add extra buffer for variable processing times
const completionTimeout = TIMEOUTS.videoRendering + TIMEOUTS.finalEncoding + 600_000; // 35 minutes total
let consecutiveUnavailable = 0;
const maxConsecutiveUnavailable = 10; // ~2 minutes of retries before trying recovery
while (Date.now() - encodeStartTime < completionTimeout) {
if (await refreshBtn.isVisible().catch(() => false)) {
await refreshBtn.click();
await page.waitForTimeout(2000);
}
const statusText = await jobCard.textContent() || '';
// Job card may briefly disappear during re-renders (e.g., status transitions).
// Catch timeout errors and retry on next poll iteration instead of failing the test.
let statusText: string;
try {
statusText = await jobCard.textContent({ timeout: 15000 }) || '';
consecutiveUnavailable = 0; // Reset counter on success
} catch {
consecutiveUnavailable++;
console.log(` Job card temporarily unavailable (${consecutiveUnavailable}/${maxConsecutiveUnavailable}), retrying...`);
if (consecutiveUnavailable >= maxConsecutiveUnavailable) {
// Card has been gone too long — the job likely completed and the status filter
// is hiding it. Switch filter to "All statuses" to make it visible again.
console.log(' Card missing too long — switching status filter to "All statuses"...');
const filterSelect = page.getByRole('combobox', { name: /filter by status/i });
if (await filterSelect.isVisible().catch(() => false)) {
await filterSelect.click();
await page.waitForTimeout(500);
const listbox = page.getByRole('listbox');
const allOption = listbox.getByRole('option', { name: /all statuses/i });
if (await allOption.isVisible().catch(() => false)) {
await allOption.click();
await page.waitForTimeout(3000);
consecutiveUnavailable = 0; // Reset and try again with new filter
continue;
}
}
// If we couldn't change the filter, throw a descriptive error
throw new Error('Job card disappeared for too long — job may have completed but status filter is hiding it');
}
await page.waitForTimeout(5000);
continue;
}
if (statusText.toLowerCase().includes('complete') && !statusText.toLowerCase().includes('prep')) {
isComplete = true;
@@ -949,7 +993,7 @@ test.describe('E2E Happy Path - Real User with Full UI Interactions', () => {
console.log('========================================');
// Private mode skips public distribution (YouTube, GDrive) — only Dropbox may be present
const cardText = await jobCard.textContent() || '';
const cardText = await jobCard.textContent({ timeout: 15000 }).catch(() => '') || '';
if (cardText.toLowerCase().includes('youtube') ||
cardText.toLowerCase().includes('drive')) {
+47
View File
@@ -304,6 +304,43 @@ export interface AudioSeparatorHealth {
error?: string;
}
export interface ServiceStatus {
status: string; // 'ok' | 'offline'
version?: string | null;
deployed_at?: string | null;
commit_sha?: string | null;
pr_number?: string | null;
pr_title?: string | null;
active_jobs?: number;
admin_details?: {
// Encoder blue-green
primary_vm?: string;
primary_ip?: string;
primary_version?: string;
primary_deployed_at?: string;
secondary_vm?: string;
secondary_ip?: string;
secondary_version?: string;
secondary_deployed_at?: string;
last_swap_at?: string;
deploy_in_progress?: boolean;
active_jobs?: number;
queue_length?: number;
// Error details for offline services
error?: string | null;
};
}
export interface SystemStatus {
services: {
frontend: ServiceStatus;
backend: ServiceStatus;
encoder: ServiceStatus;
flacfetch: ServiceStatus;
separator: ServiceStatus;
};
}
// Signed URL upload types
export interface SignedUploadUrl {
file_type: string;
@@ -1322,6 +1359,16 @@ export const api = {
return handleResponse(response);
},
/**
* Get aggregated system status for all services
*/
async getSystemStatus(): Promise<SystemStatus> {
const response = await fetch(`${API_BASE_URL}/api/health/system-status`, {
headers: getAuthHeaders(),
});
return handleResponse(response);
},
// ==========================================================================
// Credits/Payment API endpoints
// ==========================================================================
+4
View File
@@ -20,6 +20,10 @@ try {
const nextConfig = {
env: {
NEXT_PUBLIC_APP_VERSION: appVersion,
NEXT_PUBLIC_COMMIT_SHA: process.env.NEXT_PUBLIC_COMMIT_SHA || '',
NEXT_PUBLIC_PR_NUMBER: process.env.NEXT_PUBLIC_PR_NUMBER || '',
NEXT_PUBLIC_PR_TITLE: process.env.NEXT_PUBLIC_PR_TITLE || '',
NEXT_PUBLIC_BUILD_TIME: process.env.NEXT_PUBLIC_BUILD_TIME || new Date().toISOString(),
},
// Only use static export for production builds (not dev)
output: process.env.NODE_ENV === 'production' ? 'export' : undefined,
@@ -3,6 +3,9 @@ Build and upload the Divebar catalog index to BigQuery.
Takes the flat file listing from drive_client and the parsed metadata
from filename_parser, and loads it into a BigQuery table.
Uses a staging table + MERGE to preserve gcs_path values set by the
file sync script (divebar_file_sync.py).
"""
import logging
@@ -17,8 +20,10 @@ logger = logging.getLogger(__name__)
# BigQuery table reference
DATASET_ID = "karaoke_decide"
TABLE_ID = "divebar_catalog"
STAGING_TABLE_ID = "divebar_catalog_staging"
SCHEMA = [
# Schema for the staging table (no gcs_path — that lives only in the main table)
STAGING_SCHEMA = [
bigquery.SchemaField("file_id", "STRING", mode="REQUIRED"),
bigquery.SchemaField("brand", "STRING", mode="REQUIRED"),
bigquery.SchemaField("brand_code", "STRING"),
@@ -78,31 +83,84 @@ def load_to_bigquery(project_id: str, rows: list[dict]) -> int:
"""
Load rows into the BigQuery divebar_catalog table.
Uses WRITE_TRUNCATE to atomically replace the entire table contents.
Returns the number of rows loaded.
Uses a staging table + MERGE to update the catalog without losing
gcs_path values set by the file sync script. Steps:
1. WRITE_TRUNCATE the staging table with fresh Drive data
2. MERGE staging into main table:
- UPDATE existing rows (by file_id) with fresh metadata
- INSERT new rows
- DELETE rows no longer in Drive
gcs_path is preserved on updates and defaults to NULL on inserts.
Returns the number of rows in the main table after merge.
"""
if not rows:
logger.warning("No rows to load")
return 0
client = bigquery.Client(project=project_id)
table_ref = f"{project_id}.{DATASET_ID}.{TABLE_ID}"
staging_ref = f"{project_id}.{DATASET_ID}.{STAGING_TABLE_ID}"
main_ref = f"{project_id}.{DATASET_ID}.{TABLE_ID}"
# Step 1: Load fresh data into staging table (TRUNCATE is fine here)
job_config = bigquery.LoadJobConfig(
schema=SCHEMA,
schema=STAGING_SCHEMA,
write_disposition=bigquery.WriteDisposition.WRITE_TRUNCATE,
source_format=bigquery.SourceFormat.NEWLINE_DELIMITED_JSON,
)
# BigQuery load from in-memory rows
load_job = client.load_table_from_json(
rows,
table_ref,
job_config=job_config,
)
# Wait for completion
load_job = client.load_table_from_json(rows, staging_ref, job_config=job_config)
load_job.result()
logger.info("Loaded %d rows to staging table", load_job.output_rows)
logger.info("Loaded %d rows to %s", load_job.output_rows, table_ref)
return load_job.output_rows
# Step 2: MERGE staging into main table, preserving gcs_path
merge_sql = f"""
MERGE `{main_ref}` AS main
USING `{staging_ref}` AS staging
ON main.file_id = staging.file_id
WHEN MATCHED THEN UPDATE SET
brand = staging.brand,
brand_code = staging.brand_code,
artist = staging.artist,
title = staging.title,
disc_id = staging.disc_id,
filename = staging.filename,
format = staging.format,
subfolder = staging.subfolder,
file_size = staging.file_size,
drive_path = staging.drive_path,
drive_md5 = staging.drive_md5,
artist_normalized = staging.artist_normalized,
title_normalized = staging.title_normalized,
synced_at = staging.synced_at
WHEN NOT MATCHED BY TARGET THEN INSERT (
file_id, brand, brand_code, artist, title, disc_id,
filename, format, subfolder, file_size, drive_path,
drive_md5, artist_normalized, title_normalized, synced_at,
gcs_path
) VALUES (
staging.file_id, staging.brand, staging.brand_code,
staging.artist, staging.title, staging.disc_id,
staging.filename, staging.format, staging.subfolder,
staging.file_size, staging.drive_path, staging.drive_md5,
staging.artist_normalized, staging.title_normalized,
staging.synced_at, NULL
)
WHEN NOT MATCHED BY SOURCE THEN DELETE
"""
logger.info("Merging staging into main table (preserving gcs_path)...")
merge_job = client.query(merge_sql)
merge_job.result()
# Get final row count
count_result = list(client.query(
f"SELECT COUNT(*) as cnt FROM `{main_ref}`"
).result())
final_count = count_result[0].cnt if count_result else 0
logger.info("Merge complete. Main table has %d rows", final_count)
return final_count
+75 -40
View File
@@ -35,6 +35,7 @@ import io
import logging
import os
import sys
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
@@ -55,11 +56,26 @@ GCS_BUCKET = os.environ.get("GCS_BUCKET", "nomadkaraoke-divebar-files")
DATASET = "karaoke_decide"
TABLE = "divebar_catalog"
# Files larger than this are skipped (would OOM the sync VM)
MAX_FILE_SIZE = 3 * 1024 * 1024 * 1024 # 3 GB
_thread_local = threading.local()
def get_drive_service():
"""Create Google Drive API service."""
credentials, _ = default(scopes=["https://www.googleapis.com/auth/drive.readonly"])
return build("drive", "v3", credentials=credentials)
"""Get a thread-local Google Drive API service.
googleapiclient is NOT thread-safe — sharing a single service object
across threads causes SSL errors, bad file descriptors, and heap
corruption. Each thread gets its own instance.
"""
svc = getattr(_thread_local, "drive_service", None)
if svc is None:
credentials, _ = default(scopes=["https://www.googleapis.com/auth/drive.readonly"])
svc = build("drive", "v3", credentials=credentials)
_thread_local.drive_service = svc
return svc
def get_unsynced_files(bq_client, brand=None, limit=None):
@@ -149,16 +165,37 @@ def update_gcs_path(bq_client, file_id, gcs_path):
bq_client.query(query, job_config=job_config).result()
def sync_file(drive_service, gcs_bucket, bq_client, row):
"""Sync a single file from Drive to GCS."""
def sync_file(gcs_bucket, bq_client, row):
"""Sync a single file from Drive to GCS.
Uses a thread-local Drive service (googleapiclient is not thread-safe).
Checks if the file already exists in GCS before downloading from Drive.
If it exists, just updates gcs_path in BigQuery (no re-download needed).
"""
file_id = row.file_id
drive_path = row.drive_path
gcs_path = f"files/{drive_path}"
size_mb = (row.file_size or 0) / 1024 / 1024
full_gcs_path = f"gs://{GCS_BUCKET}/{gcs_path}"
file_size = row.file_size or 0
size_mb = file_size / 1024 / 1024
# Skip files too large to buffer in memory (would OOM the VM)
if file_size > MAX_FILE_SIZE:
update_gcs_path(bq_client, file_id, "skipped:too_large")
logger.warning(" ⏭ %s skipped (%.0f MB > 3 GB limit)", drive_path, size_mb)
return True, 0
# Check if file already exists in GCS (avoids re-downloading)
blob = gcs_bucket.blob(gcs_path)
if blob.exists():
update_gcs_path(bq_client, file_id, full_gcs_path)
logger.info(" ⏭ %s already in GCS, updated gcs_path", drive_path)
return True, 0
logger.info("Downloading %s (%.1f MB)...", drive_path, size_mb)
start = time.time()
drive_service = get_drive_service()
ok, actual_size = download_and_upload(
drive_service, gcs_bucket, file_id, gcs_path, row.file_size
)
@@ -166,7 +203,6 @@ def sync_file(drive_service, gcs_bucket, bq_client, row):
if ok:
duration = time.time() - start
speed = actual_size / 1024 / 1024 / duration if duration > 0 else 0
full_gcs_path = f"gs://{GCS_BUCKET}/{gcs_path}"
update_gcs_path(bq_client, file_id, full_gcs_path)
logger.info(
" ✓ %s (%.1f MB in %.1fs, %.1f MB/s)",
@@ -218,56 +254,55 @@ def main():
return
gcs_bucket = gcs_client.bucket(GCS_BUCKET)
drive_service = get_drive_service()
synced = 0
# Warm up the main thread's Drive service (also validates credentials early)
get_drive_service()
downloaded = 0
recovered = 0
failed = 0
bytes_synced = 0
overall_start = time.time()
def _tally(ok, size):
nonlocal downloaded, recovered, failed, bytes_synced
if ok:
if size > 0:
downloaded += 1
bytes_synced += size
else:
recovered += 1
else:
failed += 1
def _log_progress():
elapsed = time.time() - overall_start
logger.info(
"Progress: %d downloaded, %d recovered, %d failed (of %d), %.1f GB, %.0f s",
downloaded, recovered, failed, len(files),
bytes_synced / 1024 / 1024 / 1024, elapsed,
)
if args.workers > 1:
# Parallel downloads
with ThreadPoolExecutor(max_workers=args.workers) as executor:
futures = {
executor.submit(sync_file, drive_service, gcs_bucket, bq_client, row): row
executor.submit(sync_file, gcs_bucket, bq_client, row): row
for row in files
}
for future in as_completed(futures):
ok, size = future.result()
if ok:
synced += 1
bytes_synced += size
else:
failed += 1
if (synced + failed) % 50 == 0:
elapsed = time.time() - overall_start
logger.info(
"Progress: %d/%d synced, %d failed, %.1f GB, %.0f s elapsed",
synced, len(files), failed, bytes_synced / 1024 / 1024 / 1024, elapsed,
)
_tally(*future.result())
if (downloaded + recovered + failed) % 50 == 0:
_log_progress()
else:
# Sequential downloads
for i, row in enumerate(files):
ok, size = sync_file(drive_service, gcs_bucket, bq_client, row)
if ok:
synced += 1
bytes_synced += size
else:
failed += 1
_tally(*sync_file(gcs_bucket, bq_client, row))
if (i + 1) % 50 == 0:
elapsed = time.time() - overall_start
logger.info(
"Progress: %d/%d synced, %d failed, %.1f GB, %.0f s elapsed",
synced, len(files), failed, bytes_synced / 1024 / 1024 / 1024, elapsed,
)
_log_progress()
elapsed = time.time() - overall_start
logger.info(
"Done: %d synced, %d failed, %.1f GB in %.0f s (%.1f MB/s avg)",
synced, failed, bytes_synced / 1024 / 1024 / 1024, elapsed,
bytes_synced / 1024 / 1024 / elapsed if elapsed > 0 else 0,
"Done: %d downloaded, %d recovered from GCS, %d failed, %.1f GB in %.0f s",
downloaded, recovered, failed, bytes_synced / 1024 / 1024 / 1024, elapsed,
)
+6 -1
View File
@@ -452,6 +452,8 @@ class VideoGenerator:
def _create_video_from_image(self, image_path, video_path, duration, resolution=(3840, 2160)):
"""Create a video from a static image."""
import subprocess as _subprocess
ffmpeg_command = (
f'{self.ffmpeg_base_command} -y -loop 1 -framerate 30 -i "{image_path}" '
f"-f lavfi -i anullsrc -c:v libx264 -r 30 -t {duration} -pix_fmt yuv420p "
@@ -460,7 +462,10 @@ class VideoGenerator:
self.logger.info("Generating video...")
self.logger.debug(f"Running command: {ffmpeg_command}")
os.system(ffmpeg_command)
result = _subprocess.run(ffmpeg_command, shell=True, capture_output=True, text=True, timeout=300)
if result.returncode != 0:
self.logger.error(f"FFmpeg video generation failed: {result.stderr}")
raise RuntimeError(f"Failed to create video from image: {result.stderr}")
def _transform_text(self, text, transform_type):
"""Helper method to transform text based on specified type."""
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.155.2"
version = "0.157.4"
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
license = "MIT"
+142
View File
@@ -0,0 +1,142 @@
"""Tests for divebar mirror index_builder — staging+MERGE approach.
The Cloud Function has its own deps (google-cloud-bigquery, filename_parser)
that aren't in the main project's poetry env. We mock them at the module level
before importing index_builder.
"""
import importlib
import sys
import types
from pathlib import Path
from unittest.mock import MagicMock, patch
import pytest
# ---------------------------------------------------------------------------
# Pre-import mocking: google.cloud.bigquery and filename_parser are not
# available in the CI test environment (they're Cloud Function deps).
# ---------------------------------------------------------------------------
_mock_bigquery = MagicMock()
# SchemaField needs to be callable and return a mock
_mock_bigquery.SchemaField = MagicMock
_mock_google = types.ModuleType("google")
_mock_google.cloud = types.ModuleType("google.cloud")
_mock_google.cloud.bigquery = _mock_bigquery
_mock_filename_parser = MagicMock()
@pytest.fixture(autouse=True)
def _import_index_builder(monkeypatch):
"""Import index_builder with mocked external deps."""
monkeypatch.setitem(sys.modules, "google", _mock_google)
monkeypatch.setitem(sys.modules, "google.cloud", _mock_google.cloud)
monkeypatch.setitem(sys.modules, "google.cloud.bigquery", _mock_bigquery)
monkeypatch.setitem(sys.modules, "filename_parser", _mock_filename_parser)
func_dir = str(
Path(__file__).resolve().parents[2]
/ "infrastructure"
/ "functions"
/ "divebar_mirror"
)
monkeypatch.syspath_prepend(func_dir)
if "index_builder" in sys.modules:
importlib.reload(sys.modules["index_builder"])
else:
importlib.import_module("index_builder")
def _mod():
return sys.modules["index_builder"]
class TestLoadToBigquery:
"""Verify load_to_bigquery uses staging+MERGE instead of WRITE_TRUNCATE on main table."""
def _setup_client_mock(self):
"""Set up a mock BigQuery client with staging load + merge + count."""
client = MagicMock()
load_job = MagicMock()
load_job.output_rows = 1
client.load_table_from_json.return_value = load_job
merge_job = MagicMock()
count_row = MagicMock()
count_row.cnt = 1
count_result = MagicMock()
count_result.result.return_value = [count_row]
client.query.side_effect = [merge_job, count_result]
return client
def test_empty_rows_returns_zero(self):
assert _mod().load_to_bigquery("proj", []) == 0
def test_loads_to_staging_table_not_main(self):
"""The load job must target the staging table, not the main table."""
mod = _mod()
client = self._setup_client_mock()
with patch.object(mod.bigquery, "Client", return_value=client):
mod.load_to_bigquery("proj", [{"file_id": "abc"}])
load_target = client.load_table_from_json.call_args[0][1]
assert mod.STAGING_TABLE_ID in load_target
assert load_target == f"proj.{mod.DATASET_ID}.{mod.STAGING_TABLE_ID}"
merge_sql = client.query.call_args_list[0][0][0]
assert "MERGE" in merge_sql
assert f"{mod.DATASET_ID}.{mod.TABLE_ID}" in merge_sql
assert f"{mod.DATASET_ID}.{mod.STAGING_TABLE_ID}" in merge_sql
def test_merge_preserves_gcs_path(self):
"""The MERGE SQL must preserve gcs_path on UPDATE and set NULL on INSERT."""
mod = _mod()
client = self._setup_client_mock()
with patch.object(mod.bigquery, "Client", return_value=client):
mod.load_to_bigquery("proj", [{"file_id": "x"}])
merge_sql = client.query.call_args_list[0][0][0]
# gcs_path must NOT appear in the UPDATE SET clause
update_section = merge_sql.split("WHEN MATCHED THEN UPDATE SET")[1].split(
"WHEN NOT MATCHED"
)[0]
assert "gcs_path" not in update_section
# gcs_path must appear in INSERT with NULL default
insert_section = merge_sql.split("WHEN NOT MATCHED BY TARGET THEN INSERT")[
1
].split("WHEN NOT MATCHED BY SOURCE")[0]
assert "gcs_path" in insert_section
assert "NULL" in insert_section
def test_merge_deletes_removed_files(self):
"""Files no longer in Drive should be deleted from the main table."""
mod = _mod()
client = self._setup_client_mock()
with patch.object(mod.bigquery, "Client", return_value=client):
mod.load_to_bigquery("proj", [{"file_id": "x"}])
merge_sql = client.query.call_args_list[0][0][0]
assert "WHEN NOT MATCHED BY SOURCE THEN DELETE" in merge_sql
def test_no_write_truncate_on_main_table(self):
"""WRITE_TRUNCATE must only target the staging table, never the main table."""
mod = _mod()
client = self._setup_client_mock()
with patch.object(mod.bigquery, "Client", return_value=client):
mod.load_to_bigquery("proj", [{"file_id": "x"}])
load_calls = client.load_table_from_json.call_args_list
assert len(load_calls) == 1
target = load_calls[0][0][1]
assert mod.STAGING_TABLE_ID in target
assert target != f"proj.{mod.DATASET_ID}.{mod.TABLE_ID}"
+205 -165
View File
@@ -39,7 +39,7 @@ class TestDownloadWithCache:
assert cached.read_bytes() == b"font-data"
def test_cache_hit_skips_download(self, tmp_path):
"""On cache hit, copies from cache without downloading."""
"""On cache hit with matching size, copies from cache without downloading."""
from backend.services.gce_encoding.main import download_with_cache
cache_dir = tmp_path / "cache"
@@ -52,12 +52,55 @@ class TestDownloadWithCache:
cached = cache_dir / cache_key
cached.write_bytes(b"cached-font-data")
with patch("backend.services.gce_encoding.main.download_single_file_from_gcs") as mock_dl:
# Mock blob.reload() to return matching size
mock_blob = MagicMock()
mock_blob.size = len(b"cached-font-data")
mock_bucket = MagicMock()
mock_bucket.blob.return_value = mock_blob
with patch("backend.services.gce_encoding.main.download_single_file_from_gcs") as mock_dl, \
patch("backend.services.gce_encoding.main.storage_client") as mock_sc:
mock_sc.bucket.return_value = mock_bucket
download_with_cache(gcs_uri, dest, cache_dir)
mock_dl.assert_not_called()
assert dest.read_bytes() == b"cached-font-data"
def test_cache_hit_redownloads_on_size_mismatch(self, tmp_path):
"""On cache hit with different size, re-downloads and updates cache."""
from backend.services.gce_encoding.main import download_with_cache
cache_dir = tmp_path / "cache"
cache_dir.mkdir()
dest = tmp_path / "output.png"
gcs_uri = "gs://bucket/jobs/abc123/style/karaoke_background.png"
# Pre-populate cache with stale small file (simulates corrupt placeholder)
cache_key = hashlib.sha256(gcs_uri.encode()).hexdigest()
cached = cache_dir / cache_key
cached.write_bytes(b"x" * 106) # 106 bytes like the corrupt placeholder
# GCS reports the correct larger size
mock_blob = MagicMock()
mock_blob.size = 2_800_000 # 2.8MB correct file
mock_bucket = MagicMock()
mock_bucket.blob.return_value = mock_blob
new_content = b"correct-large-image-data"
def fake_download(uri, path):
Path(path).write_bytes(new_content)
with patch("backend.services.gce_encoding.main.download_single_file_from_gcs", side_effect=fake_download) as mock_dl, \
patch("backend.services.gce_encoding.main.storage_client") as mock_sc:
mock_sc.bucket.return_value = mock_bucket
download_with_cache(gcs_uri, dest, cache_dir)
mock_dl.assert_called_once()
assert dest.read_bytes() == new_content
# Cache should be updated with new content
assert cached.read_bytes() == new_content
def test_cache_dir_none_downloads_directly(self, tmp_path):
"""When cache_dir is None, downloads without caching."""
from backend.services.gce_encoding.main import download_with_cache
@@ -77,192 +120,189 @@ class TestDownloadWithCache:
class TestRunRenderVideo:
"""Tests for the run_render_video processing function."""
def _make_request(self):
def _make_request(self, job_id="rv-test-001", output_prefix="gs://bucket/jobs/rv-test-001/output"):
from backend.services.gce_encoding.main import RenderVideoRequest
return RenderVideoRequest(
job_id="rv-test-001",
original_corrections_gcs_path="gs://bucket/jobs/rv-test-001/corrections.json",
updated_corrections_gcs_path=None,
audio_gcs_path="gs://bucket/jobs/rv-test-001/audio.flac",
style_params_gcs_path=None,
style_assets=None,
output_gcs_prefix="gs://bucket/jobs/rv-test-001/output",
job_id=job_id,
original_corrections_gcs_path="gs://bucket/jobs/test/lyrics/corrections.json",
audio_gcs_path="gs://bucket/jobs/test/audio.flac",
output_gcs_prefix=output_prefix,
artist="Test Artist",
title="Test Song",
subtitle_offset_ms=0,
video_resolution="4k",
)
@patch("backend.services.gce_encoding.main.upload_single_file_to_gcs")
@patch("backend.services.gce_encoding.main.download_with_cache")
@patch("backend.services.gce_encoding.main.download_single_file_from_gcs")
@patch("backend.services.gce_encoding.main.subprocess")
def test_sets_job_status_to_running(
self, mock_subprocess, mock_dl, mock_cache_dl, mock_upload, tmp_path
):
"""Verifies run_render_video sets job status to running and populates output_files."""
def _make_mock_outputs(self, tmp_path):
"""Create mock OutputGenerator outputs with real files."""
mock_outputs = MagicMock()
mock_outputs.video = str(tmp_path / "with_vocals.mkv")
mock_outputs.ass = str(tmp_path / "karaoke.ass")
mock_outputs.lrc = str(tmp_path / "karaoke.lrc")
mock_outputs.corrected_txt = str(tmp_path / "corrected.txt")
for attr in ["video", "ass", "lrc", "corrected_txt"]:
Path(getattr(mock_outputs, attr)).write_bytes(b"fake")
return mock_outputs
def _run_with_mocks(self, job_id, work_dir, request, mock_outputs, tmp_path):
"""Run run_render_video with all karaoke-gen wheel imports mocked."""
from backend.services.gce_encoding.main import run_render_video, jobs
mock_subprocess.run.return_value = MagicMock(returncode=0)
jobs[job_id] = {
"job_id": job_id, "status": "pending", "progress": 0,
"error": None, "output_files": None, "metadata": None,
}
mock_correction_result = MagicMock(corrected_segments=[])
mock_gen = MagicMock()
mock_gen.generate_outputs.return_value = mock_outputs
import sys as _sys
fake_modules = {
"karaoke_gen.lyrics_transcriber.output.generator": MagicMock(
OutputGenerator=MagicMock(return_value=mock_gen),
),
"karaoke_gen.lyrics_transcriber.output.countdown_processor": MagicMock(
CountdownProcessor=MagicMock(return_value=MagicMock(
process=MagicMock(return_value=(mock_correction_result, str(work_dir / "audio.flac"), False, 0))
)),
),
"karaoke_gen.lyrics_transcriber.types": MagicMock(
CorrectionResult=MagicMock(from_dict=MagicMock(return_value=mock_correction_result)),
),
"karaoke_gen.lyrics_transcriber.correction.operations": MagicMock(),
"karaoke_gen.lyrics_transcriber.core.config": MagicMock(),
"karaoke_gen.style_loader": MagicMock(
load_styles_from_gcs=MagicMock(return_value=(str(tmp_path / "styles.json"), {})),
),
"karaoke_gen.utils": MagicMock(
sanitize_filename=MagicMock(side_effect=lambda x: x.replace(" ", "_")),
),
}
def fake_download(uri, path):
Path(path).parent.mkdir(parents=True, exist_ok=True)
Path(path).write_text("{}")
with patch("backend.services.gce_encoding.main.download_single_file_from_gcs", side_effect=fake_download):
with patch("backend.services.gce_encoding.main.download_with_cache"):
with patch("backend.services.gce_encoding.main.upload_single_file_to_gcs") as mock_upload:
with patch("backend.services.gce_encoding.main.subprocess"):
with patch.dict(_sys.modules, fake_modules):
run_render_video(job_id, work_dir, request)
return mock_upload
def test_sets_job_status_and_populates_output_files(self, tmp_path):
"""run_render_video sets output_files and metadata."""
from backend.services.gce_encoding.main import jobs
job_id = "rv-test-001"
jobs[job_id] = {
"job_id": job_id,
"status": "pending",
"progress": 0,
"error": None,
"output_files": None,
"metadata": None,
}
request = self._make_request()
work_dir = tmp_path / "work"
work_dir.mkdir()
request = self._make_request(job_id)
mock_outputs = self._make_mock_outputs(tmp_path)
# Mock downloads to create dummy files
def fake_download(uri, path):
Path(path).parent.mkdir(parents=True, exist_ok=True)
Path(path).write_text("{}")
self._run_with_mocks(job_id, work_dir, request, mock_outputs, tmp_path)
mock_dl.side_effect = fake_download
# Mock karaoke-gen wheel imports
mock_correction_result = MagicMock()
mock_correction_result.events = []
mock_countdown_processor = MagicMock()
mock_countdown_processor.return_value.process.return_value = (mock_correction_result, False, 0)
mock_output_generator_cls = MagicMock()
mock_output_generator = MagicMock()
mock_output_generator_cls.return_value = mock_output_generator
mock_output_config = MagicMock()
def fake_generate(*args, **kwargs):
videos_dir = work_dir / "videos"
lyrics_dir = work_dir / "lyrics"
videos_dir.mkdir(parents=True, exist_ok=True)
lyrics_dir.mkdir(parents=True, exist_ok=True)
(videos_dir / "with_vocals.mkv").write_bytes(b"video")
(lyrics_dir / "karaoke.ass").write_text("ass content")
(lyrics_dir / "karaoke.lrc").write_text("lrc content")
(lyrics_dir / "corrected.txt").write_text("text content")
mock_output_generator.generate_outputs.side_effect = fake_generate
import sys as _sys
fake_modules = {
"backend.output_generator": MagicMock(
OutputGenerator=mock_output_generator_cls,
OutputConfig=mock_output_config,
),
"backend.services.countdown_processor": MagicMock(
CountdownProcessor=mock_countdown_processor,
),
"backend.models.correction_result": MagicMock(
CorrectionResult=MagicMock(from_json=MagicMock(return_value=mock_correction_result)),
),
"backend.services.correction_operations": MagicMock(
CorrectionOperations=MagicMock(),
),
"backend.utils.style_utils": MagicMock(
load_styles_from_gcs=MagicMock(return_value=({}, [])),
),
"backend.utils.filename_utils": MagicMock(
sanitize_filename=MagicMock(side_effect=lambda x: x.replace(" ", "_")),
),
}
with patch.dict(_sys.modules, fake_modules):
run_render_video(job_id, work_dir, request)
# Verify status was set to running (then completed by caller)
# and output_files were populated
assert jobs[job_id]["output_files"] is not None
assert len(jobs[job_id]["output_files"]) == 4
assert jobs[job_id]["metadata"]["countdown_padding_added"] is False
@patch("backend.services.gce_encoding.main.upload_single_file_to_gcs")
@patch("backend.services.gce_encoding.main.download_with_cache")
@patch("backend.services.gce_encoding.main.download_single_file_from_gcs")
@patch("backend.services.gce_encoding.main.subprocess")
def test_uploads_all_output_files(
self, mock_subprocess, mock_dl, mock_cache_dl, mock_upload, tmp_path
):
"""Verifies all 4 output files are uploaded to correct GCS paths."""
from backend.services.gce_encoding.main import run_render_video, jobs
mock_subprocess.run.return_value = MagicMock(returncode=0)
def test_uploads_all_output_files(self, tmp_path):
"""run_render_video uploads video, ass, lrc, and txt to correct GCS paths."""
job_id = "rv-test-002"
jobs[job_id] = {
"job_id": job_id,
"status": "pending",
"progress": 0,
"error": None,
"output_files": None,
"metadata": None,
}
request = self._make_request()
request.job_id = job_id
request.output_gcs_prefix = "gs://bucket/jobs/rv-test-002/output"
work_dir = tmp_path / "work"
work_dir.mkdir()
request = self._make_request(job_id, "gs://bucket/jobs/rv-test-002/output")
mock_outputs = self._make_mock_outputs(tmp_path)
def fake_download(uri, path):
Path(path).parent.mkdir(parents=True, exist_ok=True)
Path(path).write_text("{}")
mock_dl.side_effect = fake_download
mock_correction_result = MagicMock()
mock_correction_result.events = []
mock_countdown_processor = MagicMock()
mock_countdown_processor.return_value.process.return_value = (mock_correction_result, False, 0)
mock_output_generator_cls = MagicMock()
mock_output_generator = MagicMock()
mock_output_generator_cls.return_value = mock_output_generator
mock_output_config = MagicMock()
def fake_generate(*args, **kwargs):
videos_dir = work_dir / "videos"
lyrics_dir = work_dir / "lyrics"
videos_dir.mkdir(parents=True, exist_ok=True)
lyrics_dir.mkdir(parents=True, exist_ok=True)
(videos_dir / "with_vocals.mkv").write_bytes(b"video")
(lyrics_dir / "karaoke.ass").write_text("ass content")
(lyrics_dir / "karaoke.lrc").write_text("lrc content")
(lyrics_dir / "corrected.txt").write_text("text content")
mock_output_generator.generate_outputs.side_effect = fake_generate
import sys as _sys
fake_modules = {
"backend.output_generator": MagicMock(
OutputGenerator=mock_output_generator_cls,
OutputConfig=mock_output_config,
),
"backend.services.countdown_processor": MagicMock(
CountdownProcessor=mock_countdown_processor,
),
"backend.models.correction_result": MagicMock(
CorrectionResult=MagicMock(from_json=MagicMock(return_value=mock_correction_result)),
),
"backend.services.correction_operations": MagicMock(
CorrectionOperations=MagicMock(),
),
"backend.utils.style_utils": MagicMock(
load_styles_from_gcs=MagicMock(return_value=({}, [])),
),
"backend.utils.filename_utils": MagicMock(
sanitize_filename=MagicMock(side_effect=lambda x: x.replace(" ", "_")),
),
}
with patch.dict(_sys.modules, fake_modules):
run_render_video(job_id, work_dir, request)
# Check all 4 uploads happened with correct GCS paths
upload_calls = mock_upload.call_args_list
uploaded_gcs_paths = [call[0][1] for call in upload_calls]
mock_upload = self._run_with_mocks(job_id, work_dir, request, mock_outputs, tmp_path)
uploaded_gcs_paths = [call[0][1] for call in mock_upload.call_args_list]
assert "gs://bucket/jobs/rv-test-002/output/videos/with_vocals.mkv" in uploaded_gcs_paths
assert "gs://bucket/jobs/rv-test-002/output/lyrics/karaoke.ass" in uploaded_gcs_paths
assert "gs://bucket/jobs/rv-test-002/output/lyrics/karaoke.lrc" in uploaded_gcs_paths
assert "gs://bucket/jobs/rv-test-002/output/lyrics/corrected.txt" in uploaded_gcs_paths
class TestEmptyCorrectionsValidation:
"""Tests that empty/malformed corrections_updated.json is handled gracefully."""
def test_gce_worker_skips_empty_corrections(self, tmp_path):
"""GCE worker falls back to base_result when corrections_updated.json is empty."""
import json
import sys as _sys
from backend.services.gce_encoding.main import RenderVideoRequest, run_render_video, jobs
job_id = "empty-corr-001"
work_dir = tmp_path / "work"
work_dir.mkdir()
request = RenderVideoRequest(
job_id=job_id,
original_corrections_gcs_path="gs://bucket/jobs/test/lyrics/corrections.json",
updated_corrections_gcs_path="gs://bucket/jobs/test/lyrics/corrections_updated.json",
audio_gcs_path="gs://bucket/jobs/test/audio.flac",
output_gcs_prefix="gs://bucket/jobs/test/output",
artist="Test",
title="Song",
)
jobs[job_id] = {
"job_id": job_id, "status": "pending", "progress": 0,
"error": None, "output_files": None, "metadata": None,
}
mock_correction_result = MagicMock(corrected_segments=[])
mock_gen = MagicMock()
mock_outputs = MagicMock()
mock_outputs.video = str(tmp_path / "v.mkv")
mock_outputs.ass = str(tmp_path / "k.ass")
mock_outputs.lrc = str(tmp_path / "k.lrc")
mock_outputs.corrected_txt = str(tmp_path / "c.txt")
for attr in ["video", "ass", "lrc", "corrected_txt"]:
Path(getattr(mock_outputs, attr)).write_bytes(b"fake")
mock_gen.generate_outputs.return_value = mock_outputs
mock_update = MagicMock()
fake_modules = {
"karaoke_gen.lyrics_transcriber.output.generator": MagicMock(
OutputGenerator=MagicMock(return_value=mock_gen),
),
"karaoke_gen.lyrics_transcriber.output.countdown_processor": MagicMock(
CountdownProcessor=MagicMock(return_value=MagicMock(
process=MagicMock(return_value=(mock_correction_result, str(work_dir / "audio.flac"), False, 0))
)),
),
"karaoke_gen.lyrics_transcriber.types": MagicMock(
CorrectionResult=MagicMock(from_dict=MagicMock(return_value=mock_correction_result)),
),
"karaoke_gen.lyrics_transcriber.correction.operations": MagicMock(
CorrectionOperations=MagicMock(update_correction_result_with_data=mock_update),
),
"karaoke_gen.lyrics_transcriber.core.config": MagicMock(),
"karaoke_gen.style_loader": MagicMock(
load_styles_from_gcs=MagicMock(return_value=(str(tmp_path / "styles.json"), {})),
),
"karaoke_gen.utils": MagicMock(
sanitize_filename=MagicMock(side_effect=lambda x: x.replace(" ", "_")),
),
}
def fake_download(uri, path):
Path(path).parent.mkdir(parents=True, exist_ok=True)
if "corrections_updated" in uri:
# Empty dict — no "corrections" key (the bug scenario)
Path(path).write_text("{}")
else:
Path(path).write_text(json.dumps({"corrections": [], "corrected_segments": []}))
with patch("backend.services.gce_encoding.main.download_single_file_from_gcs", side_effect=fake_download):
with patch("backend.services.gce_encoding.main.download_with_cache"):
with patch("backend.services.gce_encoding.main.upload_single_file_to_gcs"):
with patch("backend.services.gce_encoding.main.subprocess"):
with patch.dict(_sys.modules, fake_modules):
run_render_video(job_id, work_dir, request)
# update_correction_result_with_data should NOT have been called
mock_update.assert_not_called()
+5 -5
View File
@@ -17,7 +17,7 @@ class TestVideo:
patch('PIL.ImageDraw.Draw') as mock_draw, \
patch('PIL.Image.open'), \
patch('PIL.ImageFont.truetype') as mock_truetype, \
patch('os.system'):
patch('subprocess.run', return_value=MagicMock(returncode=0)):
# Configure mock font
mock_font = MagicMock()
@@ -79,7 +79,7 @@ class TestVideo:
# Mock dependencies
with patch('PIL.Image.open') as mock_image_open, \
patch('shutil.copy2') as mock_copy, \
patch('os.system') as mock_os_system: # Assign patch to variable
patch('subprocess.run', return_value=MagicMock(returncode=0)) as mock_os_system: # Assign patch to variable
# Configure mock_image_open to return a mock image
mock_image = MagicMock()
@@ -124,7 +124,7 @@ class TestVideo:
patch('PIL.ImageDraw.Draw') as mock_draw, \
patch('PIL.ImageFont.truetype') as mock_truetype, \
patch('os.path.exists', return_value=True), \
patch('os.system') as mock_os_system: # Assign patch
patch('subprocess.run', return_value=MagicMock(returncode=0)) as mock_os_system: # Assign patch
# Configure mock font
mock_font = MagicMock()
@@ -175,7 +175,7 @@ class TestVideo:
with patch('PIL.Image.new') as mock_image_new, \
patch('PIL.ImageDraw.Draw') as mock_draw, \
patch('PIL.ImageFont.truetype') as mock_truetype, \
patch('os.system') as mock_os_system: # Assign patch
patch('subprocess.run', return_value=MagicMock(returncode=0)) as mock_os_system: # Assign patch
# Configure mock font
mock_font = MagicMock()
@@ -220,7 +220,7 @@ class TestVideo:
with patch('PIL.Image.new') as mock_image_new, \
patch('PIL.ImageDraw.Draw') as mock_draw, \
patch('PIL.ImageFont.truetype') as mock_truetype, \
patch('os.system') as mock_os_system: # Assign patch
patch('subprocess.run', return_value=MagicMock(returncode=0)) as mock_os_system: # Assign patch
# Configure mock font
mock_font = MagicMock()