Compare commits

...
Author SHA1 Message Date
Andrew BeveridgeandClaude Opus 4.8 0539479281 docs: address CodeRabbit review on #913
- handoff: made self-contained (dropped agent-memory refs); reframed around the
  confirmed static finding that `ffmpeg_threads` is DEAD CONFIG (video_worker sets
  it but EncodingConfig/LocalEncodingService never read it, and the finalization
  ffmpeg commands omit -threads → default all-core), so it's a narrower
  efficiency+cleanup task, not "fix an 8-core cap"; strengthened measurement
  guidance to process-level (ffmpeg argv, per-thread CPU/RSS, per-format timings)
  and bound the encode+probes to one observed worker IP; fixed a wrong file
  pointer (backend/services/local_encoding_service.py, not the wheel).
- plan doc: c2df/n4db are now provisioned (secret v5, all 8 fallbacks live) — the
  autonomous retry loop finished them 2026-08-16; replaced the ellipsis
  `--target …` with full executable URNs.
- ARCHITECTURE: deploy-flow steps now cover the fallback-green/active_override
  branch, override clearing, drain+stop, and the no-green in-place-restart path.
- TROUBLESHOOTING: replaced the obsolete `encoding-worker` ssh host with
  active-worker (primary_vm / active_override_vm) guidance.
- GCP-COST-OPTIMIZATION: recommendation now matches the updated state (stay
  on-demand + idle-shutdown; Spot only as a future experiment).

Docs-only; no version bump.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-16 14:08:34 -04:00
Andrew BeveridgeandClaude Opus 4.8 b7c4edc7fc docs: reflect multi-instance-type encode pool + add finalization-CPU handoff
Bring all live docs in line with the v0.195.0 encode-worker mechanism (ranked
6-family pool, shared encoding_worker_preference ordering, capacity_state
cooldown, dep-baked image) and add a handoff for the next investigation.

- ARCHITECTURE.md: rewrite the "Encoding Worker" section — primary pair + 6-family
  fallback pool, shared preference module (runtime + deploy), capacity_state,
  is_primary override routing, self-sufficient dep-baked image; update the topology
  diagram + intro.
- TROUBLESHOOTING.md: capacity runbook now lists all 6 families / 8 fallbacks +
  cooldown; capacity-probe loop covers the 4 new VMs; deploy green-selection points
  at the ranked pool; "No module named" section notes the dep-bake largely fixed it
  (+ the create-time-stockout caveat).
- DEVELOPMENT.md + CLAUDE.md: fix "two VMs" framing; CLAUDE.md ssh example uses a
  real VM name (there is no VM literally named `encoding-worker`).
- GCP-COST-OPTIMIZATION.md: correct the stale "c4d running 24/7 ~$700/mo" current
  state (now on-demand pool + idle-shutdown, largely the shipped opportunities).
- LESSONS-LEARNED.md: mark the Aug-2026 2-family diversification lesson as
  superseded by the v0.195.0 pool (preserve history, redirect to current).
- NEW docs/archive/2026-08-16-finalization-cpu-efficiency-handoff.md: grounded
  handoff to investigate whether prod finalization is CPU-underutilized
  (ffmpeg_threads:8 on 32-vCPU workers), with repro + constraints.

Docs-only; no version bump.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-16 13:47:05 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 824e4f9e6b fix(packer): verify baked deps via canary imports (unbreak encoding-worker image build) (#912)
## Summary
The v0.195.0 dep-bake (#911) broke the **Build Encoding Worker Image**
workflow: the build-time verify step imported
`backend.services.gce_encoding.main`, which constructs GCP clients at
import and needs `GOOGLE_CLOUD_PROJECT` + auth that only exist at
runtime. Packer failed with *"Project was not passed and could not be
determined from the environment"* — even though the full dep tree (torch
2.13.0+cpu, tenacity, langchain, …) installed cleanly.

No prod impact: the failed build left the `encoding-worker` image family
unchanged, so VMs kept using the prior image + the runtime
`ensure_latest_wheel` backstop.

## Fix
Verify the dependency **tree** via heavy transitive library imports
(`tenacity` + the langchain chain +
`transformers`/`librosa`/`onnxruntime`) — the exact modules whose
absence broke fresh fallback VMs — instead of the app module. Proves
install completeness without app-level GCP-init fragility. Keeps the
CPU-only torch assertion (`torch.version.cuda is None`).

## Testing
- [x] `bash -n provision.sh`
- [x] Confirmed all canary libs present in the failed build's install
log
- [ ] Re-run of Build Encoding Worker Image (auto-triggers on merge)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-15 21:20:40 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 c7959ea2d5 feat(encoding): mature multi-instance-type pool with availability-aware selection (#911)
## Summary
- Replaces "c4d primary + single n2 fallback family" with a **ranked
pool of 6 x86_64 / 32-vCPU / ≥32 GB highcpu types** across 4 silicon
lineages (c4d, c4, n4d, c2d, n2d, n2), selected **fastest-first** but
**availability-aware** — a type that stocks out is demoted for a 15-min
cooldown then re-probed. c4d stays the top pick whenever it can start; a
render no longer stalls even if 2+ types are fully stocked out in
us-central1.
- One **pure preference module**
(`encoding_worker_preference.ordered_candidates`) is now the single
source of truth for candidate ranking, driving **both** runtime
selection and deploy green selection so they can't drift.
- Keeps the per-VM start/stop model (MIG deferred with documented
triggers; no reservation). Full plan + rollout in
`docs/archive/2026-08-15-encoding-instance-type-diversity-plan.md`.

## Changes
- **New** `backend/services/encoding_worker_preference.py` — speed-rank
+ Firestore `capacity_state` cooldown; stdlib-only so `deploy_promote`
imports it (with a shadow-proof by-path fallback).
- **Runtime** (`encoding_service`, `encoding_worker_manager`): builder
ranks primary + fallbacks; manager records/clears per-(type,zone)
stockout; override routing now keys off an explicit `is_primary` flag
instead of list position.
- **Deploy** (`deploy_promote`, `ci.yml`): green selection uses the
shared ranker + threads `capacity_state`.
- **IaC** (`config.py`, tests): `FALLBACKS` broadened to 6 types
(additive-only) with family-correct disk types (Titanium c4/c4d/n4/n4d =
hyperdisk-balanced; c2d/n2/n2d = pd-balanced); secret schema gains
optional `machine_type`.
- **Packer** (`provision.sh`, `startup.sh`): bake full dep tree with
**CPU-only torch** so fresh type VMs boot self-sufficient; build-time
import verify.
- **New** `benchmark_types.py` to measure per-type encode wall-time and
refine the seeded `SPEED_RANK`.

## Testing
- [x] Full backend unit suite: **3871 passed, 36 skipped** (emulator
tests need external services)
- [x] New/updated tests: preference module (16), capacity_state +
`is_primary` manager tests, builder-ordering + non-list-JSON service
tests, deploy ranking tests, infra disk-capability + pool-breadth
invariants
- [ ] Operator rollout (needs write creds): `pulumi up` (verify +8
create, 0 replace) → rebuild image (dep-bake) → grow fallback secret
with `machine_type` → run `benchmark_types.py`

## Review
- [x] Local CodeRabbit review completed (4 major findings fixed; cycle 2
clean)
- [x] Review feedback addressed

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-15 20:52:56 -04:00
Andrew Beveridge ☄️ 9a752ab3eb fix(deploy): capacity-aware encoding-worker deploy (reach serving fallback in c4d stockout) (#910)
## Problem

Follow-up to #908/#909. The CI encoding-worker deploy is a blue-green
over the **c4d primary/secondary** VMs. us-central1 is in a persistent
**c4d Spot stockout**, so both are down and all traffic runs on an n2
fallback recorded as `active_override_vm`. The deploy can't start the
c4d secondary → rolls back → **never refreshes the serving fallback**,
so worker-side `main.py` changes (the #908/#909 fixes) never reach prod
until a manual restart. Evidence: the config doc's `primary_version` was
stuck at `0.192.9`, and I had to hand-start the n2f fallback to get
0.194.0 live.

## Fix — validate on a fresh green, then promote it (zero-downtime,
stockout-proof)

Decision logic is a pure, unit-tested module
(`infrastructure/encoding-worker/deploy_promote.py`) since the branching
can't be exercised in CI:
- **`select_green_candidates`** — try the c4d `secondary` first, else a
fresh n2 fallback (n2 before c4d), **excluding the current override** so
it keeps serving while we validate a *different* fresh worker.
- **`promote_plan`** — for a c4d green, the classic primary/secondary
swap **and clear any stale override**; for a fallback green, set it as
`active_override`. Returns the exact Firestore update + which retired
VM(s) to drain/stop (**never the just-promoted green**).

Workflow (`.github/workflows/ci.yml`):
- "Select & start green target" (capacity-aware, `continue-on-error`,
emits `green_ok`), health + real-encode-test on the green IP, then
"Promote green to serving" (apply plan + drained stop of retired VMs,
non-RUNNING skipped, one shared 20-min drain budget).
- Rollback uses `always()` so `deploy_in_progress` is always cleared;
only stops a green we started fresh, and **recovers the serving
override** (starts it back up) if a last-resort in-place restart left it
down.

## Testing
- `backend/tests/test_deploy_promote.py` — 10 cases: candidate ordering
(secondary-first, n2-before-c4d, override excluded), both promote
branches, and never-drain-the-green guard.
- `actionlint` clean on the new steps; YAML validated.
- Two full local CodeRabbit cycles; all 7 findings addressed (self-drain
guard, stuck `deploy_in_progress`, None-IP guard, drain time-bound,
override recovery).

## Deploy note
This PR's own merge is the first live run of the new logic (deploy runs
on every push to main). Expected: it selects an n2 fallback as green
(c4d won't start), validates it, sets `active_override` to the fresh
one, and drains the old override. Will be watched closely.

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

* **New Features**
* Improved encoding-worker deployments with capacity-aware green worker
selection and fallback support.
* Added safer blue-green promotion, health validation, job draining, and
rollback handling.
* Prevented active jobs from being interrupted during worker
replacement.

* **Bug Fixes**
* Added recovery for capacity shortages, including validated in-place
restarts as a last resort.
* Automatically clears stale deployment overrides and deployment locks.

* **Documentation**
* Updated troubleshooting guidance for worker restarts and
capacity-related recovery.

* **Tests**
* Added coverage for worker selection, promotion, fallback handling, and
draining behavior.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

@coderabbitai ignore
2026-08-15 18:09:51 -04:00
Andrew Beveridge ☄️ 329a0944c8 fix(encoding): race-free ensure_latest_wheel + skip redundant installs (#909)
## Problem

Follow-up to #908. During the OOM-fix verification, a fresh n2 fallback
booted and three renders hit it at once; one (`374dec26`) failed with
`karaoke-gen wheel/dependencies not ready on this worker after retries;
job should be retried on a healthy worker`.

**Root cause:** `ensure_latest_wheel()` runs on the **light** executor
(>1 thread) at the start of every job — the heavy-lane serialization
(`ENCODING_HEAVY_CONCURRENCY=1`) does **not** cover it. So concurrent
jobs on a fresh boot raced on the shared `/tmp/karaoke_gen-<v>.whl` path
(`gsutil cp` clobbered mid-copy) and the venv (two `pip install`s at
once). It also re-downloaded + re-installed the wheel on **every** job
even when the installed version already matched.

## Fix (`backend/services/gce_encoding/main.py`)
- **Process-wide lock** (`threading.Lock`) around the whole
check/download/install/verify so only one caller does the work; the rest
wait.
- **"Already current" fast path:** compare the installed `karaoke-gen`
version to the latest GCS wheel; if they match (the common case —
`startup.sh` installs it at boot), skip download/install entirely. A
per-process verified-version cache makes repeat calls a no-op. Only the
*first* job after a new wheel actually installs.

Net effect: on a fresh boot, the first job installs (under the lock) and
the rest take the fast path — no clobbering, no redundant installs, no
spurious "wheel not ready" failures.

## Testing
- New tests: fast path (already-verified / installed-matches → zero
`cp`/`pip`), full install when the version differs, and **3 concurrent
callers install exactly once** (`cp==1`, `pip==1`).
- Existing wheel-verification tests get an autouse cache reset so the
new module global can't leak between tests.
- Encoding suite: 163 passed.
- Local CodeRabbit review completed; feedback addressed.

## Deploy note
Same as #908: the worker picks this up on a fresh boot / service restart
(it ships in the wheel). No infra changes.

@coderabbitai ignore
2026-08-15 16:42:24 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 51dbf1cbfd fix(encoding): serialize heavy encodes (OOM-proof) + auto-resubmit lost renders (#908)
## Problem

Three Arctic Monkeys renders (`a3f340a2`, `374dec26`, `590630c0`) failed
within ~2 min on 2026-08-15 with `lost contact with worker after 5
consecutive poll failures: Encoding job … not found`.

**Root cause (confirmed from live forensics):** Both 60 GB c4d primary
encoding workers were down (Spot stockout), so all render traffic
funneled onto the single 32 GB `n2-highcpu-32` fallback. The worker ran
`ThreadPoolExecutor(max_workers=4)`, so the batch put **3 concurrent 4K
ffmpeg encodes** (~30 GB) on it → **kernel OOM-killer fired** →
`encoding-worker` service restarted → in-memory `jobs` registry wiped →
every poll `404`'d → all three failed. ffmpeg already saturates all
cores for one job, so the parallelism bought **no throughput**, only
multiplied peak RAM.

## Fix

**Worker — serialize the heavy lane**
(`backend/services/gce_encoding/main.py`)
- Split the single pool into `heavy_executor`
(`max_workers=ENCODING_HEAVY_CONCURRENCY`, default **1**, clamped to
`[1,4]`) for renders/encodes and `light_executor` (previews + wheel
installs). One heavy ffmpeg at a time = OOM-proof on any machine type;
extras queue as `pending`.
- `/status` now exposes `queue_position` (+ `restart_failure_code`);
jobs tagged by `kind`.

**Client + workers — auto-resubmit a lost job**
- `wait_for_completion` raises the typed `EncodingJobLostError` on a
**404-after-the-job-was-seen** (a pinned poll can only 404 if the worker
lost it) or a terminal failure carrying `restart_failure_code`. 404 is
now a typed `EncodingJobNotFoundError` (no message parsing).
- Time spent `pending` counts against a generous `queue_timeout`, not
the per-run `timeout`.
- `run_with_lost_job_resubmit` resubmits a lost job as
`<id>_retry_<hex8>` (bounded, `ENCODING_RESUBMIT_MAX=2`), wired into
`render_video_worker`, `video_worker`, and `video_worker_orchestrator`
(incl. the stale-cache path). Idempotent by deterministic output paths
(overwrite, no dupes).
- `GCEEncodingBackend.encode` re-raises the lost error instead of
flattening it to `success=False`, so the resubmit actually fires.

## Testing
- New tests: worker lane serialization + `queue_position`;
concurrency-clamp matrix; client lost-job detection (404-after-seen,
restart code, pending-not-timeout); resubmit wrapper (fresh id, bounded,
non-retry of other errors); backend re-raise; preview queue-timeout cap.
- Full backend suite: **3766 passed, 139 skipped**.
- Local CodeRabbit review completed; feedback addressed (typed 404,
bounded env parsing, preview queue cap, idempotency doc).

## Deploy note
`main.py` ships in the wheel, but the running uvicorn process only picks
up worker-side changes on a **service restart** — the CI deploy /
blue-green swap handles this. Post-deploy verification: re-render the 3
failed jobs **concurrently** (the exact OOM trigger) and confirm no OOM
(`journalctl -k`), `NRestarts` doesn't increase, and all three complete.

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-15 15:26:25 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 3f4b7550ab feat(portrait): 9:16 karaoke video output (GCS + Dropbox) (#890)
## Summary

Adds a **portrait 1080×1920 karaoke video** as an additional output of
every finalised job — for phone viewing / social sharing — distributed
to **GCS + the Dropbox brand-code folder only** (never Google Drive or
YouTube). Default-on, gated by `PORTRAIT_RENDER_ENABLED`, and fully
**non-fatal**.

It is a genuine **re-render** at portrait resolution with re-wrapped
lyrics — *not* a transform of the finished landscape video. The design
experiments proved transforms are unusable: letterboxing leaves the
lyrics tiny (~32% of the frame); centre-cropping slices the start/end
off **every** line. See the comparison in
`docs/archive/2026-06-14-portrait-video-experiments/comparison.png`.

## What's included

**New `karaoke_gen/portrait/` module** (reuses the existing
`SubtitlesGenerator` engine + the job's corrected-lyrics data, so
word-by-word timing is identical to the landscape video):
- `wrap.py` — orphan-merging balanced wrapper (no stranded "No," lines),
timing-preserving
- `background.py` — branded portrait background (wordmark/header +
song/artist + footer) + "thank you" end card
- `renderer.py` — portrait ASS + title/end cards + single-pass ffmpeg
assembly (title + lyrics body + end)

**Backend integration** (minimal, low-risk):
- `gce_encoding/main.py::render_portrait_into_outputs` — renders on the
GCE encoder inside `run_encoding`, using the un-padded instrumental +
un-countdown-processed segments (inherently in sync). Writes into
`output_dir`, so it rides the existing `finals/` GCS upload + Dropbox
folder upload.
- `EncodingOutput.portrait_mp4_path` + filename classification +
orchestrator download-allowlist mapping + admin files-manifest entry.
YouTube/Drive use their own allowlists, so the portrait is naturally
excluded from them.

## Testing

- 17 new tests in `tests/unit/portrait/` (balanced wrapping,
background/layout, guard + non-fatal wiring, and a real end-to-end
ffmpeg render on a synthetic fixture).
- Existing GCE/encoding/orchestration/lyrics-output suites green (116
tests total across touched areas).
- **Verified end-to-end on real prod job piri – dog (`052b94ab`)** via
the backend integration function: produced a valid, on-brand 1080×1920
portrait with live word-highlighting, correct title/end cards, correct
duration.

## Safety / rollout

- Additive + `PORTRAIT_RENDER_ENABLED` (default on) + wrapped in
try/except: a portrait failure logs and returns `None` — it never fails
the job or blocks landscape outputs/distribution.
- Subprocess timeouts on ffprobe/ffmpeg so a stalled render can't hang
the worker.
- ~15–30s + ~10 MB per job.

Design: `docs/archive/2026-06-14-portrait-video-design.md` · Plan:
`docs/archive/2026-07-13-portrait-video-plan.md`

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

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-14 21:01:08 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 1b6833b182 fix(jobs): show job/log timestamps in the viewer's local timezone (#907)
## Problem

Job dates on the dashboard displayed the raw UTC wall-clock instead of
the viewer's local time. e.g. a job submitted at ~4:10 PM local (viewer
at UTC-2) showed as `8/14/2026, 6:10:25 PM`.

## Root cause

`created_at` (and timeline/log timestamps) were built from naive
`datetime.utcnow()` and serialized via `model_dump(mode='json')` /
`.isoformat()`, producing ISO strings with **no timezone offset**
(`"2026-08-14T18:10:25.123456"`). Firestore stored them as plain strings
and returned them verbatim. The frontend's `new Date(str)` parses an
offset-less ISO date-time as **local** time, so the UTC value was shown
unconverted — off by the viewer's UTC offset.

## Fix

**Frontend (fixes all existing + new data, no migration):**
- New `parseServerDate()` util in `frontend/lib/utils.ts` — treats
offset-less ISO date-times as UTC (appends `Z`); passes through strings
that already carry `Z`/`±HH:MM`, plus `Date`/epoch inputs.
- Applied at every customer-facing server-timestamp display: `JobCard`
created-at, `JobLogs` timestamps, referral payout dates, and
referral-discount expiry (`BuyCreditsDialog` + dashboard).
- 8 unit tests covering
naive/`Z`/`+00:00`/non-UTC-offset/date-only/epoch/`Date` cases.

**Backend (makes stored timestamps unambiguous going forward):**
- `create_job` and timeline events now use `datetime.now(timezone.utc)`,
so serialized ISO strings carry a `+00:00` offset. Arithmetic consumers
(`job_health_service`) already guard for both naive and aware datetimes.

## Testing
- Backend: 210 targeted tests pass (job_manager / firestore / timeline /
job_health / countdown).
- Frontend: full suite 1108 tests pass (85 suites), including the new
util tests.

## Notes
- `/admin/*` pages (English-only, internal) still use `new Date()`
directly; they benefit from the backend change for new jobs but were
left otherwise untouched as out of scope.
- CodeRabbit local review was rate-limited (free OSS quota), so this PR
intentionally omits `@coderabbitai ignore` to let the bot review.

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-14 17:40:11 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 84b0683cba fix(audio-search): recover parked jobs — edit + re-search + own-audio fallback (#906)
## Problem

In Bulk Mode (and single jobs), the "Choose audio" dialog was a **hard
dead-end**. When a search returned nothing usable — 0 results, a
transient flacfetch failure, or an auto-picked source that's unusable —
the bulk worker parks the job in `AWAITING_AUDIO_SELECTION` with
**empty** cached results. The dialog then showed "No audio sources
found" with **no retry, no way to edit the title, and no manual
source**, so the user was trapped.

Real-world trigger (batch `4af58968a64a`): two Arctic Monkeys tracks
parked with 0 results (one a transient miss on a common track, one an
over-long title), and three more stuck downloading the **same dead RED
torrent** — all with no path forward.

## What this does

Adds a full recovery path to the shared `AudioSearchDialog` (used by
bulk **and** single jobs):

- **Edit + Search again** — always-available editable artist/title with
a re-search button. Edits apply to the job's search terms *and* display
metadata.
- **Provide your own audio** — paste a YouTube/yt-dlp URL, or upload a
file.
- **Graceful empty state** — a 400 (no cached results) renders as the
empty state with the refine bar, not a red error; real network/5xx
errors still surface.

### Backend (`audio_search.py`) — all guarded to
`AWAITING_AUDIO_SELECTION`, tenant-gated, no new job, no double-charge
(final duration billing reconciles post-download)
- `POST /{job_id}/research` — retry / edit-and-re-search. Empty results
are a normal `200`.
- `POST /{job_id}/provide-url` — YouTube URLs go through the **async**
audio-download worker; generic yt-dlp URLs download inline, bounded by a
timeout (never strands a job).
- `POST /{job_id}/attach-upload-url` + `/attach-upload-complete` —
signed-URL upload of the user's own file (extension allow-list +
traversal-safe; the complete step pins the exact uploaded object).
- Factored the triplicated result serialization into
`_build_result_response`.

## Testing
- 20 backend endpoint tests + 5 frontend dialog tests (all green);
broader audio/jobs sweeps pass.
- i18n: 15 new `audioSearch` keys across all 33 locales.

## Review
Local CodeRabbit review completed (2 cycles, all 6 findings addressed,
final pass 0 findings).

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-14 02:50:53 -04:00
101 changed files with 7011 additions and 407 deletions

No files matched your search

+282 -100
View File
@@ -1188,10 +1188,15 @@ jobs:
data = doc.to_dict()
with open(os.environ["GITHUB_OUTPUT"], "a") as f:
for key in ["primary_vm", "primary_ip", "primary_version",
"secondary_vm", "secondary_ip"]:
"secondary_vm", "secondary_ip",
"active_override_vm", "active_override_ip", "active_override_zone"]:
f.write(f"{key}={data.get(key, '')}\n")
f.write(f"deploy_in_progress={str(data.get('deploy_in_progress', False)).lower()}\n")
print(f"Config: primary={data['primary_vm']}, secondary={data['secondary_vm']}")
# capacity_state is a map — emit as single-line JSON so the green
# selection step can demote recently-stocked-out machine types.
f.write(f"capacity_state={json.dumps(data.get('capacity_state') or {})}\n")
print(f"Config: primary={data.get('primary_vm')}, secondary={data.get('secondary_vm')}, "
f"active_override={data.get('active_override_vm')}")
PYEOF
- name: Wait for concurrent deploy
@@ -1226,29 +1231,159 @@ jobs:
print("Set deploy_in_progress=true")
PYEOF
- name: Start secondary VM
# Capacity-aware green (staging) target. us-central1 is often in a c4d Spot
# stockout, so the c4d secondary can't start and the serving worker is an n2
# fallback recorded as active_override. We validate the new wheel on a FRESH
# green — the c4d secondary if it starts, else a different n2 fallback (never
# the current override, so it keeps serving) — then promote the green. See
# infrastructure/encoding-worker/deploy_promote.py.
- name: Select & start green target
id: green
# Never hard-fail the whole backend deploy just because no encoding
# worker could be validated — emit green_ok=false and let the gated
# health/encode/promote steps skip while the Cloud Run deploy proceeds.
continue-on-error: true
run: |
SECONDARY_VM="${{ steps.config.outputs.secondary_vm }}"
echo "Starting secondary VM: $SECONDARY_VM"
gcloud compute instances start "$SECONDARY_VM" \
--zone=us-central1-c --project=nomadkaraoke || true
python3 << 'PYEOF'
import json, os, subprocess, sys, time
sys.path.insert(0, "infrastructure/encoding-worker")
import deploy_promote
for i in $(seq 1 12); do
STATUS=$(gcloud compute instances describe "$SECONDARY_VM" \
--zone=us-central1-c --project=nomadkaraoke \
--format='value(status)')
echo "VM status: $STATUS (attempt $i/12)"
if [ "$STATUS" = "RUNNING" ]; then
break
fi
sleep 10
done
try:
capacity_state = json.loads(os.environ.get("CAPACITY_STATE") or "{}")
except Exception:
capacity_state = {}
config = {
"primary_vm": os.environ.get("PRIMARY_VM") or None,
"primary_ip": os.environ.get("PRIMARY_IP") or None,
"secondary_vm": os.environ.get("SECONDARY_VM") or None,
"secondary_ip": os.environ.get("SECONDARY_IP") or None,
"secondary_zone": "us-central1-c",
"active_override_vm": os.environ.get("OVERRIDE_VM") or None,
"capacity_state": capacity_state,
}
raw = subprocess.run(
["gcloud", "secrets", "versions", "access", "latest",
"--secret=encoding-worker-fallback-vms", "--project=nomadkaraoke"],
capture_output=True, text=True)
try:
fallbacks = json.loads(raw.stdout) if raw.returncode == 0 and raw.stdout.strip() else []
except Exception as e:
print(f"::warning::Could not parse fallback VM secret: {e}")
fallbacks = []
candidates = deploy_promote.select_green_candidates(config, fallbacks)
print("Green candidates (in order):", [f"{c['vm']}({c['kind']})" for c in candidates])
def vm_status(vm, zone):
r = subprocess.run(
["gcloud", "compute", "instances", "describe", vm,
f"--zone={zone}", "--project=nomadkaraoke", "--format=value(status)"],
capture_output=True, text=True)
return r.stdout.strip()
green = None
started = [] # every VM we issued `start` to — so we can stop losers
for c in candidates:
vm, zone = c["vm"], c["zone"]
print(f"Trying green candidate: {vm} ({zone}, kind={c['kind']})")
subprocess.run(["gcloud", "compute", "instances", "start", vm,
f"--zone={zone}", "--project=nomadkaraoke"], check=False)
started.append((vm, zone))
for i in range(12):
st = vm_status(vm, zone)
print(f" {vm} status={st} ({i+1}/12)")
if st == "RUNNING":
green = c
break
time.sleep(10)
if green:
break
# Stop every candidate we started but did NOT select, so a slow-booting
# loser can't come up later unmanaged (and billed) after the deploy.
selected_vm = green["vm"] if green else None
for vm, zone in started:
if vm != selected_vm:
print(f"Stopping unselected candidate {vm} ({zone})")
subprocess.run(["gcloud", "compute", "instances", "stop", vm,
f"--zone={zone}", "--project=nomadkaraoke"], check=False)
started_fresh = "true"
inplace_failed = False
if green is None:
# Last resort: no separate green could start. Restart the current
# serving override in place (accepts a brief blip; auto-resubmit
# covers any in-flight render). If there's no override either, fail.
ov = os.environ.get("OVERRIDE_VM")
if ov:
zone = os.environ.get("OVERRIDE_ZONE") or "us-central1-f"
print(f"::warning::No separate green could start; restarting serving override {ov} in place")
subprocess.run(["gcloud", "compute", "instances", "stop", ov,
f"--zone={zone}", "--project=nomadkaraoke"], check=False)
for _ in range(18):
if vm_status(ov, zone) in ("TERMINATED", "STOPPED", ""):
break
time.sleep(5)
subprocess.run(["gcloud", "compute", "instances", "start", ov,
f"--zone={zone}", "--project=nomadkaraoke"], check=False)
final_status = ""
for _ in range(18):
final_status = vm_status(ov, zone)
if final_status == "RUNNING":
break
time.sleep(10)
# Record it either way so rollback can recover it (we stopped it,
# so if it didn't come back we must be able to start it again).
green = {"vm": ov, "ip": os.environ.get("OVERRIDE_IP"),
"zone": zone, "kind": "fallback"}
started_fresh = "false" # it's the serving worker — never stop on rollback
if final_status != "RUNNING":
inplace_failed = True
print(f"::error::In-place restart of {ov} did not reach RUNNING (status={final_status or 'unknown'})")
else:
print("::error::No green target could be started and no active override exists")
def _out(**kv):
with open(os.environ["GITHUB_OUTPUT"], "a") as f:
for k, v in kv.items():
f.write(f"{k}={v}\n")
# green_ok gates the downstream health/encode/promote steps. A missing
# green, a green with no IP, or an in-place restart that didn't come back
# RUNNING is "not ok" — the deploy skips the encoding-worker promote but
# does NOT fail; when a serving override is involved we still emit its
# vm/zone so the (always-run) rollback step can recover it.
if green is None:
_out(green_ok="false")
print("::warning::No green target selected; skipping encoding-worker promote")
elif not green.get("ip") or inplace_failed:
_out(green_ok="false", green_vm=green["vm"], green_zone=green["zone"],
green_started_fresh=started_fresh)
reason = "has no IP" if not green.get("ip") else "did not return to RUNNING"
print(f"::error::Green {green['vm']} {reason}; skipping promote")
else:
_out(green_ok="true", green_vm=green["vm"], green_ip=green["ip"],
green_zone=green["zone"], green_kind=green["kind"],
green_started_fresh=started_fresh)
print(f"Green: {green['vm']} ({green['zone']}, kind={green['kind']}, started_fresh={started_fresh})")
PYEOF
env:
PRIMARY_VM: ${{ steps.config.outputs.primary_vm }}
PRIMARY_IP: ${{ steps.config.outputs.primary_ip }}
SECONDARY_VM: ${{ steps.config.outputs.secondary_vm }}
SECONDARY_IP: ${{ steps.config.outputs.secondary_ip }}
OVERRIDE_VM: ${{ steps.config.outputs.active_override_vm }}
OVERRIDE_IP: ${{ steps.config.outputs.active_override_ip }}
OVERRIDE_ZONE: ${{ steps.config.outputs.active_override_zone }}
CAPACITY_STATE: ${{ steps.config.outputs.capacity_state }}
- name: Wait for service health
id: health
if: steps.green.outputs.green_ok == 'true'
continue-on-error: true
run: |
SECONDARY_IP="${{ steps.config.outputs.secondary_ip }}"
SECONDARY_IP="${{ steps.green.outputs.green_ip }}"
EXPECTED_VERSION="${{ steps.version_check.outputs.version }}"
HEALTH_URL="http://${SECONDARY_IP}:8080/health"
@@ -1277,7 +1412,7 @@ jobs:
id: encode-test
continue-on-error: true
run: |
SECONDARY_IP="${{ steps.config.outputs.secondary_ip }}"
SECONDARY_IP="${{ steps.green.outputs.green_ip }}"
API_KEY=$(gcloud secrets versions access latest \
--secret=encoding-worker-api-key --project=nomadkaraoke)
@@ -1341,13 +1476,35 @@ jobs:
exit 1
- name: Rollback on failure
if: steps.health.outputs.healthy != 'true' || steps.encode-test.outputs.passed != 'true'
# always() so the deploy_in_progress flag is ALWAYS cleared, even when the
# green step found no worker (its downstream steps skip, but the flag was
# already set). Skips only on a fully successful promote (passed == true).
if: always() && steps.encode-test.outputs.passed != 'true'
run: |
SECONDARY_VM="${{ steps.config.outputs.secondary_vm }}"
if [ -n "$SECONDARY_VM" ]; then
echo "Stopping secondary VM $SECONDARY_VM due to failed deploy"
gcloud compute instances stop "$SECONDARY_VM" \
--zone=us-central1-c --project=nomadkaraoke || true
GREEN_VM="${{ steps.green.outputs.green_vm }}"
GREEN_ZONE="${{ steps.green.outputs.green_zone }}"
STARTED_FRESH="${{ steps.green.outputs.green_started_fresh }}"
# Only stop a green we started fresh. If green is the serving override
# (last-resort in-place restart), leave it running — it's serving
# known-good code and stopping it would take production down.
if [ "$STARTED_FRESH" = "true" ] && [ -n "$GREEN_VM" ]; then
echo "Stopping fresh green $GREEN_VM ($GREEN_ZONE) due to failed deploy"
gcloud compute instances stop "$GREEN_VM" \
--zone="$GREEN_ZONE" --project=nomadkaraoke || true
elif [ -n "$GREEN_VM" ] && [ -n "$GREEN_ZONE" ]; then
# Serving override (last-resort in-place restart). We stopped it during
# the restart, so if it isn't RUNNING we must bring it back — otherwise
# production stays down after a failed deploy.
echo "Green is the serving worker; ensuring $GREEN_VM is RUNNING"
STATUS=$(gcloud compute instances describe "$GREEN_VM" \
--zone="$GREEN_ZONE" --project=nomadkaraoke --format='value(status)' 2>/dev/null || echo "")
if [ "$STATUS" != "RUNNING" ]; then
echo "::warning::Serving worker $GREEN_VM is '${STATUS:-unknown}'; starting it back up"
gcloud compute instances start "$GREEN_VM" \
--zone="$GREEN_ZONE" --project=nomadkaraoke || true
fi
else
echo "No green VM recorded; nothing to stop or recover"
fi
python3 -c "
@@ -1360,95 +1517,120 @@ jobs:
print('Cleared deploy_in_progress flag')
" || true
- name: Swap primary in Firestore
# Promote the validated green to serving. For a c4d secondary green this is
# the classic primary/secondary swap (and clears any stale override); for a
# fallback green it becomes the active_override. Then drain + stop whatever
# VM(s) the promote plan says are no longer serving. See deploy_promote.py.
- name: Promote green to serving
if: steps.encode-test.outputs.passed == 'true'
timeout-minutes: 25
env:
NEW_PRIMARY: ${{ steps.config.outputs.secondary_vm }}
NEW_PRIMARY_IP: ${{ steps.config.outputs.secondary_ip }}
GREEN_VM: ${{ steps.green.outputs.green_vm }}
GREEN_IP: ${{ steps.green.outputs.green_ip }}
GREEN_ZONE: ${{ steps.green.outputs.green_zone }}
GREEN_KIND: ${{ steps.green.outputs.green_kind }}
NEW_VERSION: ${{ steps.version_check.outputs.version }}
OLD_PRIMARY: ${{ steps.config.outputs.primary_vm }}
OLD_PRIMARY_IP: ${{ steps.config.outputs.primary_ip }}
OLD_VERSION: ${{ steps.config.outputs.primary_version }}
PRIMARY_VM: ${{ steps.config.outputs.primary_vm }}
PRIMARY_IP: ${{ steps.config.outputs.primary_ip }}
PRIMARY_VERSION: ${{ steps.config.outputs.primary_version }}
OVERRIDE_VM: ${{ steps.config.outputs.active_override_vm }}
OVERRIDE_IP: ${{ steps.config.outputs.active_override_ip }}
OVERRIDE_ZONE: ${{ steps.config.outputs.active_override_zone }}
run: |
echo "Swapping: $OLD_PRIMARY -> secondary, $NEW_PRIMARY -> primary"
python3 << 'PYEOF'
import os
import json, os, subprocess, sys, time, urllib.request
from datetime import datetime, timezone
sys.path.insert(0, "infrastructure/encoding-worker")
import deploy_promote
from google.cloud import firestore
db = firestore.Client(project="nomadkaraoke")
doc_ref = db.collection("config").document("encoding-worker")
green = {"vm": os.environ["GREEN_VM"], "ip": os.environ["GREEN_IP"],
"zone": os.environ["GREEN_ZONE"], "kind": os.environ["GREEN_KIND"]}
config = {
"primary_vm": os.environ.get("PRIMARY_VM") or None,
"primary_ip": os.environ.get("PRIMARY_IP") or None,
"primary_version": os.environ.get("PRIMARY_VERSION") or None,
"primary_zone": "us-central1-c",
"active_override_vm": os.environ.get("OVERRIDE_VM") or None,
"active_override_ip": os.environ.get("OVERRIDE_IP") or None,
"active_override_zone": os.environ.get("OVERRIDE_ZONE") or None,
}
now = datetime.now(timezone.utc).isoformat()
plan = deploy_promote.promote_plan(green, config, now=now, version=os.environ["NEW_VERSION"])
@firestore.transactional
def swap(transaction):
transaction.update(doc_ref, {
"primary_vm": os.environ["NEW_PRIMARY"],
"primary_ip": os.environ["NEW_PRIMARY_IP"],
"primary_version": os.environ["NEW_VERSION"],
"primary_deployed_at": now,
"secondary_vm": os.environ["OLD_PRIMARY"],
"secondary_ip": os.environ["OLD_PRIMARY_IP"],
"secondary_version": os.environ["OLD_VERSION"],
"secondary_deployed_at": now,
"last_swap_at": now,
"deploy_in_progress": False,
"deploy_in_progress_since": None,
})
db = firestore.Client(project="nomadkaraoke")
db.collection("config").document("encoding-worker").update(plan["firestore_updates"])
print("Applied config update:", json.dumps(plan["firestore_updates"], default=str))
print(f"Green {green['vm']} ({green['kind']}) is now serving")
transaction = db.transaction()
swap(transaction)
print(f"Swapped: {os.environ['NEW_PRIMARY']} is now primary")
def active_jobs(ip):
# /health is unauthenticated; None == "unknown / maybe busy".
if not ip:
return None
try:
with urllib.request.urlopen(f"http://{ip}:8080/health", timeout=5) as r:
return json.load(r).get("active_jobs")
except Exception:
return None
def vm_status(vm, zone):
r = subprocess.run(
["gcloud", "compute", "instances", "describe", vm,
f"--zone={zone}", "--project=nomadkaraoke", "--format=value(status)"],
capture_output=True, text=True)
return r.stdout.strip()
# Drain (bounded) then stop each VM the plan retired. A non-RUNNING target
# is already gone — stop it (idempotent) without waiting. For a RUNNING one
# we wait for a confirmed 0 active_jobs so we never stop mid-render (#908
# resubmit would cover a loss, but we still avoid it). The drain budget is
# SHARED across all targets (one 20-min deadline, not per-target) so a slow
# or unreachable target can't stretch the step to N×20 min; the step also
# has a hard timeout-minutes. New renders already route to the promoted green.
deadline = time.monotonic() + 1200
for tgt in plan["drain_and_stop"]:
vm, ip, zone = tgt["vm"], tgt.get("ip"), tgt.get("zone")
if not vm or not zone:
print(f"::warning::Skipping drain/stop with incomplete target: {tgt}")
continue
status = vm_status(vm, zone)
if status != "RUNNING" or not ip:
why = f"status={status or 'unknown'}" if status != "RUNNING" else "no IP to probe"
print(f"{vm} ({why}); stopping without drain")
subprocess.run(["gcloud", "compute", "instances", "stop", vm,
f"--zone={zone}", "--project=nomadkaraoke"], check=False)
continue
print(f"Draining {vm} ({zone}) before stop...")
n = active_jobs(ip)
while n != 0 and time.monotonic() < deadline:
time.sleep(15)
n = active_jobs(ip)
print(f" {vm} active_jobs={n} ({int(deadline - time.monotonic())}s budget left)")
if n == 0:
print(f"Drain confirmed for {vm}; stopping")
else:
print(f"::warning::Drain budget exhausted for {vm} (last={n}); stopping anyway")
subprocess.run(["gcloud", "compute", "instances", "stop", vm,
f"--zone={zone}", "--project=nomadkaraoke"], check=False)
PYEOF
- name: Drain and stop old primary
if: steps.encode-test.outputs.passed == 'true'
# Safety net: the deploy_in_progress lock is set unconditionally earlier, and
# both Rollback (on failure) and Promote (on success) clear it — but if the
# Promote step itself errors or hits its timeout, neither runs. This always()
# step guarantees the lock is released so the next deploy doesn't stall 10 min
# in "Wait for concurrent deploy". Idempotent with the other clears.
- name: Clear encoding-worker deploy lock
if: always()
run: |
OLD_PRIMARY="${{ steps.config.outputs.primary_vm }}"
OLD_PRIMARY_IP="${{ steps.config.outputs.primary_ip }}"
# Probe the worker's active_jobs. Echoes a non-negative integer on a
# successful /health response, or "unknown" if /health can't be
# reached or parsed. We must NOT conflate "unknown" with "0": a busy
# encoder running a 4K render pins all 32 cores and can miss the 5s
# health window, and treating that as idle previously let us stop the
# VM mid-render — orphaning the job and surfacing as "lost contact
# with worker ... not found" (incident 2026-06-15).
probe_active_jobs() {
local body n
body=$(curl -sf --connect-timeout 3 --max-time 5 \
"http://${OLD_PRIMARY_IP}:8080/health" 2>/dev/null) || { echo "unknown"; return; }
n=$(printf '%s' "$body" | jq -r '.active_jobs // empty' 2>/dev/null)
case "$n" in
''|*[!0-9]*) echo "unknown" ;;
*) echo "$n" ;;
esac
}
# Drain: wait until /health CONFIRMS 0 active jobs, or the bounded
# timeout elapses. "unknown" is treated as "maybe busy" and keeps us
# waiting — we only stop on a definitive 0 (or after the timeout, so
# a wedged worker can't block the deploy forever). 20 min comfortably
# covers a full 4K render; the old primary only drains in-flight work
# since new renders already route to the just-swapped new primary.
DRAIN_TIMEOUT=1200
ELAPSED=0
ACTIVE_JOBS=$(probe_active_jobs)
echo "Initial active_jobs: $ACTIVE_JOBS"
while [ "$ACTIVE_JOBS" != "0" ] && [ $ELAPSED -lt $DRAIN_TIMEOUT ]; do
sleep 15
ELAPSED=$((ELAPSED + 15))
ACTIVE_JOBS=$(probe_active_jobs)
echo "active_jobs: $ACTIVE_JOBS (${ELAPSED}s elapsed)"
done
if [ "$ACTIVE_JOBS" = "0" ]; then
echo "Drain confirmed (0 active jobs). Stopping old primary: $OLD_PRIMARY"
else
echo "::warning::Drain not confirmed after ${DRAIN_TIMEOUT}s (last='${ACTIVE_JOBS}'); stopping anyway to avoid a stuck deploy"
fi
gcloud compute instances stop "$OLD_PRIMARY" \
--zone=us-central1-c --project=nomadkaraoke || true
python3 -c "
from google.cloud import firestore
db = firestore.Client(project='nomadkaraoke')
db.collection('config').document('encoding-worker').update({
'deploy_in_progress': False,
'deploy_in_progress_since': None,
})
print('Ensured deploy_in_progress is cleared')
" || true
- name: Configure Docker for Artifact Registry
run: |
+9 -4
View File
@@ -145,13 +145,18 @@ EOF
```
### GCE Encoding Worker
The worker is a c4d blue-green primary pair (`encoding-worker-a`/`-b`, us-central1-c)
plus 8 stopped fallback VMs across 6 machine families for stockout resilience
(`encoding-worker-fallback-{a,b,n2c,n2f,c4a,n4db,c2df,n2da}`). The currently-serving
VM is `active_override_vm` in `config/encoding-worker` if set, else `primary_vm`.
Use that VM name + its zone below (there is no VM literally named `encoding-worker`):
```bash
# Check health (includes wheel_version)
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
# Check health (includes wheel_version). Example uses the primary pair's VM.
gcloud compute ssh encoding-worker-a --zone=us-central1-c --project=nomadkaraoke \
--command="curl -s http://localhost:8080/health"
# Restart service (pick up new wheel after a deploy)
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
# Restart the service (pick up new worker-side code after a deploy)
gcloud compute ssh encoding-worker-a --zone=us-central1-c --project=nomadkaraoke \
--command="sudo systemctl restart encoding-worker"
```
+491 -97
View File
@@ -235,6 +235,54 @@ class AudioSelectRequest(BaseModel):
acknowledged_credits: Optional[int] = Field(None, description="Expected total credits after this selection (anti-mismatch guard)")
class ProvideUrlRequest(BaseModel):
"""Request to attach a YouTube/yt-dlp URL to an existing parked job."""
url: str = Field(..., description="Audio source URL (YouTube, SoundCloud, or other yt-dlp supported site)")
class AttachUploadUrlsRequest(BaseModel):
"""Request for a signed upload URL to attach a file to an existing parked job."""
filename: str = Field(..., description="Original filename with extension")
content_type: str = Field("application/octet-stream", description="MIME type of the file")
class AttachUploadUrlsResponse(BaseModel):
"""Signed URL to upload an audio file for an existing job."""
job_id: str
gcs_path: str
upload_url: str
class AttachUploadCompleteRequest(BaseModel):
"""Finalise an upload; gcs_path (from attach-upload-url) pins the exact file."""
gcs_path: Optional[str] = Field(None, description="The gcs_path returned by attach-upload-url")
class AttachResponse(BaseModel):
"""Response after attaching a URL/file source to a parked job."""
status: str
job_id: str
message: str
class ResearchRequest(BaseModel):
"""Request to re-run the audio search for an existing parked job.
Both fields are optional: when a caller edits the artist/title (e.g. to fix
a typo or shorten an over-long title that returned nothing), the corrected
values are used for the search AND applied to the job. When omitted, the
job's existing search terms are re-used (a plain retry of a failed search).
"""
artist: Optional[str] = Field(None, description="Corrected artist to search + apply (blank = keep existing)")
title: Optional[str] = Field(None, description="Corrected title to search + apply (blank = keep existing)")
@validator('artist', 'title')
def normalize_text_fields(cls, v):
if v is not None and isinstance(v, str):
return normalize_text(v)
return v
class AudioSelectResponse(BaseModel):
"""Response from audio source selection."""
status: str
@@ -580,6 +628,55 @@ async def _download_audio_and_trigger_workers(
job_manager.fail_job(job_id, f"Audio download failed: {e}")
def _build_result_response(r: AudioSearchResult) -> AudioSearchResultResponse:
"""Serialize an AudioSearchResult into the rich API response shape.
raw_result may be a dict (remote flacfetch API) or a Release object
(local flacfetch); both expose the same enriched display fields.
Shared by the search, standalone-search, and re-search endpoints so the
result shape stays identical across all three.
"""
raw_dict: Dict[str, Any] = {}
if r.raw_result:
if isinstance(r.raw_result, dict):
raw_dict = r.raw_result
else:
try:
raw_dict = r.raw_result.to_dict()
except AttributeError:
pass # Not a Release object
return AudioSearchResultResponse(
index=r.index,
title=r.title,
artist=r.artist,
provider=r.provider,
url=r.url,
duration=r.duration,
quality=r.quality,
source_id=r.source_id,
seeders=raw_dict.get('seeders') or r.seeders,
target_file=raw_dict.get('target_file') or r.target_file,
year=raw_dict.get('year'),
label=raw_dict.get('label'),
edition_info=raw_dict.get('edition_info'),
release_type=raw_dict.get('release_type'),
channel=raw_dict.get('channel'),
view_count=raw_dict.get('view_count'),
size_bytes=raw_dict.get('size_bytes'),
target_file_size=raw_dict.get('target_file_size'),
track_pattern=raw_dict.get('track_pattern'),
match_score=raw_dict.get('match_score'),
formatted_size=raw_dict.get('formatted_size'),
formatted_duration=raw_dict.get('formatted_duration'),
formatted_views=raw_dict.get('formatted_views'),
is_lossless=raw_dict.get('is_lossless'),
quality_str=raw_dict.get('quality_str'),
# Remote API uses 'quality_data', local uses 'quality' for the dict
quality_data=raw_dict.get('quality_data') or raw_dict.get('quality'),
)
@router.post("/audio-search/search", response_model=AudioSearchResponse)
async def search_audio(
request: Request,
@@ -886,59 +983,8 @@ async def search_audio(
)
# Convert to response format with full Release data for rich display
result_responses = []
for r in search_results:
# Get full serialized data from raw_result if available
# raw_result can be either:
# - A dict (from remote flacfetch API)
# - A Release object (from local flacfetch)
raw_dict = {}
if r.raw_result:
if isinstance(r.raw_result, dict):
# Remote flacfetch API returns dicts directly
raw_dict = r.raw_result
else:
# Local flacfetch returns Release objects
try:
raw_dict = r.raw_result.to_dict()
except AttributeError:
pass # Not a Release object
result_responses.append(
AudioSearchResultResponse(
index=r.index,
title=r.title,
artist=r.artist,
provider=r.provider,
url=r.url,
duration=r.duration,
quality=r.quality,
source_id=r.source_id,
seeders=raw_dict.get('seeders') or r.seeders,
target_file=raw_dict.get('target_file') or r.target_file,
# Additional fields for rich display
year=raw_dict.get('year'),
label=raw_dict.get('label'),
edition_info=raw_dict.get('edition_info'),
release_type=raw_dict.get('release_type'),
channel=raw_dict.get('channel'),
view_count=raw_dict.get('view_count'),
size_bytes=raw_dict.get('size_bytes'),
target_file_size=raw_dict.get('target_file_size'),
track_pattern=raw_dict.get('track_pattern'),
match_score=raw_dict.get('match_score'),
# Pre-computed display fields
formatted_size=raw_dict.get('formatted_size'),
formatted_duration=raw_dict.get('formatted_duration'),
formatted_views=raw_dict.get('formatted_views'),
is_lossless=raw_dict.get('is_lossless'),
quality_str=raw_dict.get('quality_str'),
# Full quality object for Release.from_dict()
# Remote API uses 'quality_data', local uses 'quality' for the dict
quality_data=raw_dict.get('quality_data') or raw_dict.get('quality'),
)
)
result_responses = [_build_result_response(r) for r in search_results]
return AudioSearchResponse(
status="awaiting_selection",
job_id=job_id,
@@ -1012,50 +1058,10 @@ async def search_audio_standalone(
raise HTTPException(status_code=500, detail=f"Search failed: {e}")
# Build result response objects
result_responses: List[AudioSearchResultResponse] = []
results_dicts: List[Dict[str, Any]] = []
for r in search_results:
raw_dict: Dict[str, Any] = {}
if r.raw_result:
if isinstance(r.raw_result, dict):
raw_dict = r.raw_result
else:
try:
raw_dict = r.raw_result.to_dict()
except AttributeError:
pass
result_responses.append(
AudioSearchResultResponse(
index=r.index,
title=r.title,
artist=r.artist,
provider=r.provider,
url=r.url,
duration=r.duration,
quality=r.quality,
source_id=r.source_id,
seeders=raw_dict.get('seeders') or r.seeders,
target_file=raw_dict.get('target_file') or r.target_file,
year=raw_dict.get('year'),
label=raw_dict.get('label'),
edition_info=raw_dict.get('edition_info'),
release_type=raw_dict.get('release_type'),
channel=raw_dict.get('channel'),
view_count=raw_dict.get('view_count'),
size_bytes=raw_dict.get('size_bytes'),
target_file_size=raw_dict.get('target_file_size'),
track_pattern=raw_dict.get('track_pattern'),
match_score=raw_dict.get('match_score'),
formatted_size=raw_dict.get('formatted_size'),
formatted_duration=raw_dict.get('formatted_duration'),
formatted_views=raw_dict.get('formatted_views'),
is_lossless=raw_dict.get('is_lossless'),
quality_str=raw_dict.get('quality_str'),
quality_data=raw_dict.get('quality_data') or raw_dict.get('quality'),
)
)
results_dicts.append(r.to_dict())
result_responses: List[AudioSearchResultResponse] = [
_build_result_response(r) for r in search_results
]
results_dicts: List[Dict[str, Any]] = [r.to_dict() for r in search_results]
# Store session in Firestore (TTL: 7 days)
# Long TTL so users who leave a tab open mid-flow don't hit "Search expired".
@@ -1129,6 +1135,394 @@ async def get_audio_search_results(
}
@router.post("/audio-search/{job_id}/research", response_model=AudioSearchResponse)
async def research_audio(
job_id: str,
request: Request,
body: ResearchRequest,
auth_result: AuthResult = Depends(require_auth),
):
"""
Re-run the audio search for an existing job that is awaiting selection.
Handles the dead-end where a search returned nothing (or a transient
failure parked the job with no sources): the user can retry, or edit the
artist/title and search again. The job stays in AWAITING_AUDIO_SELECTION;
its cached results are replaced with the fresh ones (which may be empty —
that is a normal outcome, returned as a 200 with an empty list, not an
error, so the UI can offer the manual fallback).
Editing the artist/title also applies the correction to the job's display
artist/title (used for title screens, filenames, lyrics), so the whole
pipeline runs on the corrected metadata.
"""
locale = get_locale_from_request(request)
_require_audio_search_enabled(request, locale)
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail=t(locale, "audioSearch.jobNotFound", job_id=job_id))
if job.status != JobStatus.AWAITING_AUDIO_SELECTION:
raise HTTPException(
status_code=400,
detail=f"Job is not awaiting audio selection (status: {job.status})"
)
# Resolve the terms to search. A non-blank edited value overrides; otherwise
# fall back to the job's existing search terms (then its display fields).
edited_artist = (body.artist or "").strip()
edited_title = (body.title or "").strip()
artist = edited_artist or job.audio_search_artist or job.artist or ""
title = edited_title or job.audio_search_title or job.title or ""
if not artist or not title:
raise HTTPException(status_code=400, detail="Both artist and title are required to search")
# Apply the edit to the job before searching so a corrected typo/title flows
# through the rest of the pipeline (search terms + display metadata).
prev_artist = job.audio_search_artist or job.artist
prev_title = job.audio_search_title or job.title
if artist != prev_artist or title != prev_title:
job_manager.update_job(job_id, {
'audio_search_artist': artist,
'audio_search_title': title,
'artist': artist,
'title': title,
})
logger.info(f"[job:{job_id}] Re-search with edited terms: {artist} - {title}")
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.SEARCHING_AUDIO,
progress=5,
message=f"Searching for: {artist} - {title}",
raise_on_invalid=False,
)
audio_search_service = get_audio_search_service()
try:
search_results = await audio_search_service.search_async(artist, title)
except NoResultsError:
search_results = []
except AudioSearchError as e:
# Restore the awaiting state so the job isn't stranded, then surface the error.
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.AWAITING_AUDIO_SELECTION,
progress=10,
message="Search failed. Please try again or provide your own audio.",
raise_on_invalid=False,
)
raise HTTPException(status_code=502, detail=f"Search failed: {e}")
# Replace cached results (empty is fine — the UI offers the manual fallback).
results_dicts = [r.to_dict() for r in search_results]
remote_id = getattr(audio_search_service, "last_remote_search_id", None)
job_manager.update_job(job_id, {
'state_data.audio_search_results': results_dicts,
'state_data.audio_search_count': len(results_dicts),
# Overwrite (or clear) the stale remote_search_id from the prior search.
'state_data.remote_search_id': remote_id,
})
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.AWAITING_AUDIO_SELECTION,
progress=10,
message=(
f"Found {len(results_dicts)} audio sources. Waiting for selection."
if results_dicts else
"No audio sources found. Edit the details and search again, or provide your own audio."
),
raise_on_invalid=False,
)
return AudioSearchResponse(
status="awaiting_selection",
job_id=job_id,
message=f"Re-search complete: {len(results_dicts)} audio sources.",
results=[_build_result_response(r) for r in search_results],
results_count=len(results_dicts),
auto_download=False,
server_version=VERSION,
)
# Audio formats accepted by the manual file-upload fallback (case-insensitive).
_AUDIO_UPLOAD_EXTENSIONS = {".mp3", ".wav", ".flac", ".m4a", ".ogg"}
# Upper bound on an inline (non-YouTube) URL download so a hung yt-dlp fetch can
# never leave a parked job stuck in DOWNLOADING_AUDIO. Kept under typical proxy
# request timeouts; YouTube URLs bypass this via the async download worker.
URL_DOWNLOAD_TIMEOUT_SECONDS = 240
def _require_audio_search_enabled(request: Request, locale: str) -> None:
"""Apply the tenant `audio_search` feature gate (mirrors /search).
White-label portals that don't offer audio search must not be able to drive
the recovery endpoints (re-search / provide-url / upload) either.
"""
tenant_config = get_tenant_config_from_request(request)
if tenant_config and not tenant_config.features.audio_search:
raise HTTPException(status_code=403, detail=t(locale, "audioSearch.notEnabled"))
def _require_awaiting_selection(job_id: str, locale: str):
"""Load a job and assert it is parked awaiting audio selection.
Shared guard for the manual-fallback endpoints (URL / file upload). Returns
the job or raises 404 (missing) / 400 (wrong state).
Note: like the sibling /select endpoint (which Bulk Mode already relies on),
this does not enforce per-user job ownership — bulk jobs are owned by a
service account, so a per-user check here would lock the real submitter out
of recovering their own parked job. Ownership hardening, if desired, must be
applied uniformly across the whole audio-search surface, not just here.
"""
job = job_manager.get_job(job_id)
if not job:
raise HTTPException(status_code=404, detail=t(locale, "audioSearch.jobNotFound", job_id=job_id))
if job.status != JobStatus.AWAITING_AUDIO_SELECTION:
raise HTTPException(
status_code=400,
detail=f"Job is not awaiting audio selection (status: {job.status})"
)
return job
@router.post("/audio-search/{job_id}/provide-url", response_model=AttachResponse)
async def provide_url_for_job(
job_id: str,
request: Request,
background_tasks: BackgroundTasks,
body: ProvideUrlRequest,
auth_result: AuthResult = Depends(require_auth),
):
"""
Attach a YouTube/yt-dlp URL to a parked job and start processing.
The manual escape hatch when audio search finds nothing usable: the user
pastes a source URL for a job already in AWAITING_AUDIO_SELECTION. The job
was already created and charged, so we do NOT create a new job or deduct
base credits — the post-download duration reconcile handles final billing.
YouTube URLs are handed to the async audio-download Cloud Run Job (survives
request/instance shutdown, no long-blocking request). Generic yt-dlp URLs are
downloaded inline (the worker has no generic path) but bounded by a timeout so
a slow/hung download can never strand the job in DOWNLOADING_AUDIO.
"""
locale = get_locale_from_request(request)
_require_audio_search_enabled(request, locale)
# Validation helpers live in file_upload; import lazily to avoid a heavy
# import at module load (and any import cycle).
from backend.api.routes.file_upload import (
_is_youtube_url,
_validate_url,
_unsupported_url_platform,
_drm_unsupported_detail,
)
job = _require_awaiting_selection(job_id, locale)
url = (body.url or "").strip()
# Reject DRM-protected streaming links (Apple Music, Spotify, Tidal, …) upfront.
unsupported_platform = _unsupported_url_platform(url)
if unsupported_platform:
raise HTTPException(status_code=400, detail=_drm_unsupported_detail(locale, unsupported_platform))
if not _validate_url(url):
raise HTTPException(
status_code=400,
detail="Invalid URL. Please provide a valid YouTube, Vimeo, SoundCloud, or other supported video URL."
)
youtube_service = get_youtube_download_service()
is_youtube = _is_youtube_url(url)
# For YouTube URLs, check availability early (geo/private/removed/bot/age).
if is_youtube:
availability = await youtube_service.check_availability(url)
if availability and not availability.get("available"):
if availability.get("is_geo_restricted"):
detail = ("This YouTube video is not available in our server's region. "
"Try using a different source for this song.")
elif availability.get("is_private"):
detail = "This YouTube video is private and cannot be downloaded."
elif availability.get("is_removed"):
detail = "This YouTube video has been removed and cannot be downloaded."
elif availability.get("is_bot_blocked"):
detail = ("We're temporarily unable to access YouTube to download this video. "
"Please try again in a few minutes, or search for this song from another source.")
elif availability.get("is_age_restricted"):
detail = "This YouTube video is age-restricted and cannot be downloaded."
else:
detail = f"This YouTube video is unavailable: {availability.get('error', 'unknown error')}"
raise HTTPException(status_code=400, detail=detail)
# Point the job at the URL source and enter the download state. The
# audio-download worker (and generic inline path below) read these fields
# when selected_audio_index is unset (which it is for a parked job).
job_manager.update_job(job_id, {
'audio_source_type': 'url',
'url': url,
'source_name': 'YouTube' if is_youtube else 'url',
'download_url': url,
})
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.DOWNLOADING_AUDIO,
progress=10,
message=f"Downloading from provided URL: {job.artist} - {job.title}",
raise_on_invalid=False,
)
def _requeue(msg: str) -> None:
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.AWAITING_AUDIO_SELECTION,
progress=10,
message=msg,
raise_on_invalid=False,
)
if is_youtube:
# Async: the Cloud Run download job downloads + reconciles + triggers
# workers itself, so the request returns immediately.
worker_service = get_worker_service()
triggered = await worker_service.trigger_audio_download_worker(job_id)
if not triggered:
_requeue("Couldn't start the download. Please try again.")
raise HTTPException(status_code=502, detail="Failed to trigger audio download worker")
return AttachResponse(status="success", job_id=job_id, message="URL accepted, download started")
# Generic yt-dlp URL: no async worker path exists, so download inline —
# bounded so a hung download can't strand the job in DOWNLOADING_AUDIO.
try:
audio_gcs_path = await asyncio.wait_for(
youtube_service.download(url=url, job_id=job_id, artist=job.artist, title=job.title),
timeout=URL_DOWNLOAD_TIMEOUT_SECONDS,
)
except asyncio.TimeoutError:
_requeue("That download took too long. Try another URL or search again.")
raise HTTPException(status_code=504, detail="Download timed out")
except YouTubeDownloadError as e:
_requeue("Download from that URL failed. Try another URL or search again.")
raise HTTPException(status_code=502, detail=f"Download failed: {e}")
job_manager.update_job(job_id, {
'input_media_gcs_path': audio_gcs_path,
'filename': os.path.basename(audio_gcs_path),
})
# start_job_processing transitions DOWNLOADING_AUDIO → DOWNLOADING, runs the
# duration reconcile (final billing), and triggers audio + lyrics workers.
background_tasks.add_task(
job_manager.start_job_processing, job_id, 15,
"Audio downloaded, starting processing",
)
return AttachResponse(status="success", job_id=job_id, message="URL accepted, download complete, processing started")
@router.post("/audio-search/{job_id}/attach-upload-url", response_model=AttachUploadUrlsResponse)
async def attach_upload_url(
job_id: str,
request: Request,
body: AttachUploadUrlsRequest,
auth_result: AuthResult = Depends(require_auth),
):
"""
Issue a signed GCS upload URL to attach an audio file to a parked job.
Step 1 of the manual file-upload fallback: the client PUTs the file to the
returned URL, then calls /attach-upload-complete. No job is created here.
"""
locale = get_locale_from_request(request)
_require_audio_search_enabled(request, locale)
_require_awaiting_selection(job_id, locale)
# Normalise Windows separators before basename so "..\\evil.exe" can't be
# stored verbatim, then validate the extension against the audio allow-list.
raw = (body.filename or "").strip().replace("\\", "/")
filename = os.path.basename(raw) or "audio"
ext = os.path.splitext(filename)[1].lower()
if ext not in _AUDIO_UPLOAD_EXTENSIONS:
raise HTTPException(
status_code=400,
detail="Unsupported audio format. Use MP3, WAV, FLAC, M4A, or OGG.",
)
gcs_path = f"uploads/{job_id}/audio/{filename}"
upload_url = storage_service.generate_signed_upload_url(
gcs_path, content_type=body.content_type or "application/octet-stream", expiration_minutes=60,
)
return AttachUploadUrlsResponse(job_id=job_id, gcs_path=gcs_path, upload_url=upload_url)
@router.post("/audio-search/{job_id}/attach-upload-complete", response_model=AttachResponse)
async def attach_upload_complete(
job_id: str,
request: Request,
background_tasks: BackgroundTasks,
body: AttachUploadCompleteRequest = AttachUploadCompleteRequest(),
auth_result: AuthResult = Depends(require_auth),
):
"""
Finalise a file upload attached to a parked job and start processing.
Step 2 of the manual file-upload fallback: verifies the uploaded audio landed
in GCS, points the job at it, and starts processing. Like the URL path, the
job was already created/charged, so no new job and no base-credit deduction.
"""
locale = get_locale_from_request(request)
_require_audio_search_enabled(request, locale)
from backend.api.routes.file_upload import _select_mixed_audio_files
job = _require_awaiting_selection(job_id, locale)
prefix = f"uploads/{job_id}/audio/"
files = storage_service.list_files(prefix)
audio_files = [f for f in files if not f.rstrip("/").endswith("/")]
if not audio_files:
raise HTTPException(status_code=400, detail="No uploaded audio file found. Upload the file first.")
# Prefer the exact object the client uploaded to (from attach-upload-url),
# validated to live under this job's prefix and to actually exist — never
# trust an arbitrary client path, and don't depend on list ordering.
requested = (body.gcs_path or "").strip()
if requested:
if not requested.startswith(prefix) or requested not in audio_files:
raise HTTPException(status_code=400, detail="Uploaded file not found for this job.")
audio_gcs_path = requested
else:
selected = _select_mixed_audio_files(audio_files)
audio_gcs_path = selected[0] if isinstance(selected, list) and selected else (selected or audio_files[0])
job_manager.update_job(job_id, {
'audio_source_type': 'upload',
'input_media_gcs_path': audio_gcs_path,
'filename': os.path.basename(audio_gcs_path),
})
job_manager.transition_to_state(
job_id=job_id,
new_status=JobStatus.DOWNLOADING_AUDIO,
progress=10,
message=f"File uploaded: {job.artist} - {job.title}",
raise_on_invalid=False,
)
background_tasks.add_task(
job_manager.start_job_processing, job_id, 15,
"File uploaded, starting processing",
)
return AttachResponse(status="success", job_id=job_id, message="Upload accepted, processing started")
@router.post("/audio-search/{job_id}/select", response_model=AudioSelectResponse)
async def select_audio_source(
job_id: str,
+31
View File
@@ -44,6 +44,37 @@ class EncodingWorkerCapacityError(EncodingWorkerStartError):
"""
# Marker the encoding worker writes into a job's status when it was interrupted
# by a worker-process restart (OOM, deploy, crash). Kept in sync with
# gce_encoding/persistence.py `_RESTART_FAIL_CODE`.
ENCODING_RESTART_FAILURE_CODE = "encoding_worker_restart"
class EncodingJobNotFoundError(RuntimeError):
"""The encoding worker returned HTTP 404 for a job status poll.
Subclasses RuntimeError so existing `except RuntimeError` handlers and
`"not found" in str(e)` checks keep working, while giving callers a precise
type to branch on (e.g. distinguishing a lost job from other RuntimeErrors)
without parsing the message text. Keep the message containing "not found".
"""
class EncodingJobLostError(Exception):
"""The encoding worker lost a job mid-run (restart wiped its in-memory state).
Distinct from a transient poll blip: the ffmpeg process and temp work dir
are gone, so the *same* job will never complete. The only recovery is to
resubmit the work as a fresh job. Deliberately NOT a subclass of
RuntimeError so it escapes the poll-failure tolerance in
`wait_for_completion` instead of being swallowed as a retryable blip.
"""
def __init__(self, message: str, *, job_id: str = "") -> None:
super().__init__(message)
self.job_id = job_id
def classify_gce_error(code: str, message: str, *, vm_name: str, zone: str) -> EncodingWorkerStartError:
"""Wrap a GCE error code/message in the appropriate typed exception."""
if code in CAPACITY_ERROR_CODES:
+16
View File
@@ -14,6 +14,8 @@ from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Any
from backend.services.encoding_errors import EncodingJobLostError
logger = logging.getLogger(__name__)
@@ -71,6 +73,11 @@ class EncodingOutput:
title_mov_path: Optional[str] = None # "<artist> - <title> (Title).mov"
end_mov_path: Optional[str] = None # "<artist> - <title> (End).mov"
# Portrait (9:16) karaoke video for phone viewing / social sharing. Additive;
# distributed to GCS + Dropbox only (never Drive/YouTube). May be absent when the
# portrait render is disabled or fails (it is best-effort).
portrait_mp4_path: Optional[str] = None # "<artist> - <title> (Final Karaoke Portrait 1080x1920).mp4"
# All output files as a dict for convenience
output_files: Dict[str, str] = field(default_factory=dict)
@@ -387,6 +394,8 @@ class GCEEncodingBackend(EncodingBackend):
output_files["mp4_4k_lossless"] = path
elif "lossy 4k" in filename_lower:
output_files["mp4_4k_lossy"] = path
elif "portrait" in filename_lower:
output_files["portrait_mp4"] = path
elif "720p" in filename_lower:
output_files["mp4_720p"] = path
elif "with vocals" in filename_lower and filename.endswith(".mp4"):
@@ -408,11 +417,18 @@ class GCEEncodingBackend(EncodingBackend):
with_vocals_mp4_path=output_files.get("with_vocals_mp4"),
title_mov_path=output_files.get("title_mov"),
end_mov_path=output_files.get("end_mov"),
portrait_mp4_path=output_files.get("portrait_mp4"),
output_files=output_files,
encoding_time_seconds=encoding_time,
encoding_backend=self.name
)
except EncodingJobLostError:
# The worker lost this job mid-run (OOM/deploy restart). This is
# recoverable by resubmitting a fresh job id, so let the orchestrator
# decide — do NOT flatten it into success=False (which would fail the
# whole render). See video_worker_orchestrator's resubmit wrapper.
raise
except Exception as e:
encoding_time = time.time() - start_time
self.logger.error(f"GCE encoding failed: {e}")
+214 -42
View File
@@ -19,13 +19,17 @@ import asyncio
import logging
import os
import time
import uuid
from contextlib import asynccontextmanager
from typing import Optional, Dict, Any, AsyncIterator
from typing import Awaitable, Callable, Optional, Dict, Any, AsyncIterator
import aiohttp
from backend.config import get_settings
from backend.services.encoding_errors import (
ENCODING_RESTART_FAILURE_CODE,
EncodingJobLostError,
EncodingJobNotFoundError,
EncodingWorkerCapacityError,
EncodingWorkerStartError,
)
@@ -65,6 +69,94 @@ MAX_BACKOFF_SECONDS = 15.0
# long-running encoding job. Similar pattern to flacfetch status polling (PR #446).
MAX_CONSECUTIVE_POLL_FAILURES = 5
_DEFAULT_QUEUE_TIMEOUT_SECONDS = float(4 * 3600)
def _parse_queue_timeout() -> float:
"""How long a job may sit *queued* (status "pending") before we give up.
Parsed defensively: a malformed / non-finite / non-positive value must not
crash the module at import nor make pending jobs fail immediately — fall back
to the generous default. Separate from the per-run `timeout`, which only
starts once the job is actually "running".
"""
raw = os.environ.get("ENCODING_QUEUE_TIMEOUT")
if raw is None:
return _DEFAULT_QUEUE_TIMEOUT_SECONDS
try:
value = float(raw)
except (TypeError, ValueError):
logger.warning("Invalid ENCODING_QUEUE_TIMEOUT=%r; using default", raw)
return _DEFAULT_QUEUE_TIMEOUT_SECONDS
if not (value > 0) or value == float("inf"):
logger.warning("ENCODING_QUEUE_TIMEOUT=%r not a positive finite number; using default", raw)
return _DEFAULT_QUEUE_TIMEOUT_SECONDS
return value
def _parse_resubmit_max() -> int:
"""Bounded automatic resubmits when the worker loses a job mid-run.
Each resubmit is a fresh job id; see `run_with_lost_job_resubmit`. A bad
value falls back to 2; negatives clamp to 0 (no resubmits).
"""
raw = os.environ.get("ENCODING_RESUBMIT_MAX", "2")
try:
return max(0, int(raw))
except (TypeError, ValueError):
logger.warning("Invalid ENCODING_RESUBMIT_MAX=%r; using 2", raw)
return 2
QUEUE_TIMEOUT_SECONDS = _parse_queue_timeout()
ENCODING_RESUBMIT_MAX = _parse_resubmit_max()
async def run_with_lost_job_resubmit(
operation: Callable[[str], Awaitable[Any]],
base_job_id: str,
*,
log: logging.Logger = logger,
max_resubmits: int = ENCODING_RESUBMIT_MAX,
) -> Any:
"""Run a submit+wait `operation(job_id)`, resubmitting if the worker loses it.
The encoding worker keeps job state in memory; an OOM/deploy restart wipes it
and the in-flight ffmpeg, so the original job id can never complete. When
`wait_for_completion` detects that (via `EncodingJobLostError`), we resubmit
the same work under a fresh `<base>_retry_<hex8>` id (the worker treats a new
id as a brand-new job). Bounded by `max_resubmits`.
`operation` must be an async callable taking the job id to use and performing
the whole submit-and-wait, returning the encode result. It should raise
`EncodingJobLostError` (propagated from `wait_for_completion`) when the job is
lost; any other exception aborts immediately.
Idempotency: only the *worker-side* job id changes between attempts — output
GCS paths are keyed by the real job (fixed input/output prefixes), so a
resubmit re-encodes and *overwrites* the same objects rather than producing
duplicates. Downstream side effects (uploads, distribution) run in the
orchestrator only after a successful encode, so a resubmit before "complete"
cannot double them.
"""
attempt = 0
while True:
job_id = base_job_id if attempt == 0 else f"{base_job_id}_retry_{uuid.uuid4().hex[:8]}"
try:
return await operation(job_id)
except EncodingJobLostError as e:
attempt += 1
if attempt > max_resubmits:
log.error(
f"[job:{base_job_id}] Encoding worker lost the job {attempt} time(s); "
f"giving up after {max_resubmits} resubmit(s): {e}"
)
raise
log.warning(
f"[job:{base_job_id}] Encoding worker lost the job (restart/OOM); "
f"resubmitting as a fresh job (attempt {attempt + 1}/{max_resubmits + 1})"
)
def _format_exception(e: BaseException) -> str:
"""Render an exception with type info.
@@ -173,12 +265,15 @@ class EncodingService:
yield
def _build_worker_candidates(self) -> list:
"""Build the ordered candidate list for ensure_any_running.
"""Build the ranked candidate list for ensure_any_running.
Reads optional fallback VMs from settings (env var
ENCODING_WORKER_FALLBACK_VMS, JSON list of {vm, zone, ip}). Returns
an empty list when no worker manager / no configured fallbacks —
caller falls back to the single-VM ensure_primary_running path.
ENCODING_WORKER_FALLBACK_VMS, JSON list of {vm, zone, ip, machine_type?}).
The primary + all fallbacks are ranked by the shared preference logic
(fastest-first, demoting recently-stocked-out types) so runtime selection
stays in lock-step with the deploy green selection. Returns an empty list
when no worker manager / no configured fallbacks — caller falls back to
the single-VM ensure_primary_running path.
"""
if not self._worker_manager:
return []
@@ -189,42 +284,69 @@ class EncodingService:
return []
from backend.services.encoding_worker_manager import EncodingWorkerCandidate
from backend.services.encoding_worker_preference import (
PRIMARY_MACHINE_TYPE,
ordered_candidates,
)
# Primary always goes first. Single-zone deployments stop here.
candidates = [
EncodingWorkerCandidate(
vm_name=config.primary_vm,
zone=self._worker_manager._zone,
ip=config.primary_ip,
)
]
# Build a dict pool (primary + fallbacks), each tagged with machine_type so
# the shared preference logic can rank them. The primary/secondary pair is
# always c4d; the config may override via primary_machine_type.
primary_mt = getattr(config, "primary_machine_type", None) or PRIMARY_MACHINE_TYPE
pool = [{
"vm": config.primary_vm,
"zone": self._worker_manager._zone,
"ip": config.primary_ip,
"machine_type": primary_mt,
"kind": "primary",
"is_primary": True,
}]
# Optional capacity-fallback VMs in alternate zones, configured via
# env var. Schema: '[{"vm":"encoding-worker-fallback-a","zone":"us-central1-a","ip":"34.x.x.x"}, ...]'
# The list is empty by default; user populates after `pulumi up`
# provisions the fallback VMs.
# Optional capacity-fallback VMs in alternate zones/families, configured via
# env var. Schema: '[{"vm":"encoding-worker-fallback-c4a","zone":"us-central1-a",
# "ip":"34.x.x.x","machine_type":"c4-highcpu-32"}, ...]'. machine_type is
# optional (inferred from the VM name for legacy entries). Empty by default;
# populated after `pulumi up` provisions the fallback VMs.
import json as _json
raw = self.settings.encoding_worker_fallback_vms
if not raw:
return candidates
try:
parsed = _json.loads(raw)
except (ValueError, TypeError) as e:
logger.warning(f"Invalid ENCODING_WORKER_FALLBACK_VMS JSON: {e}")
return candidates
for item in parsed:
if raw:
try:
candidates.append(EncodingWorkerCandidate(
vm_name=item["vm"],
zone=item["zone"],
ip=item["ip"],
))
except (KeyError, TypeError) as e:
logger.warning(f"Skipping malformed fallback candidate {item}: {e}")
continue
parsed = _json.loads(raw)
except (ValueError, TypeError) as e:
logger.warning(f"Invalid ENCODING_WORKER_FALLBACK_VMS JSON: {e}")
parsed = []
# A non-list root (null, dict, scalar) parses fine but would blow up
# `for item in parsed` and escape this method during connection
# recovery — degrade to no fallbacks instead.
if not isinstance(parsed, list):
logger.warning("ENCODING_WORKER_FALLBACK_VMS must be a JSON list; ignoring")
parsed = []
for item in parsed:
try:
pool.append({
"vm": item["vm"],
"zone": item["zone"],
"ip": item["ip"],
"machine_type": item.get("machine_type"),
"kind": "fallback",
})
except (KeyError, TypeError) as e:
logger.warning(f"Skipping malformed fallback candidate {item}: {e}")
continue
return candidates
# Rank fastest-first, demoting types that recently stocked out. Keeps the
# primary (c4d) at the top whenever it has capacity.
ranked = ordered_candidates(pool, capacity_state=config.capacity_state)
return [
EncodingWorkerCandidate(
vm_name=c["vm"],
zone=c["zone"],
ip=c["ip"],
machine_type=c.get("machine_type"),
is_primary=c.get("is_primary", False),
)
for c in ranked
]
def _load_credentials(self):
"""Load encoding worker URL and API key from config/secrets."""
@@ -586,7 +708,7 @@ class EncodingService:
if resp["status"] == 401:
raise RuntimeError("Invalid API key for encoding worker")
if resp["status"] == 404:
raise RuntimeError(f"Encoding job {job_id} not found")
raise EncodingJobNotFoundError(f"Encoding job {job_id} not found")
if resp["status"] != 200:
raise RuntimeError(f"Failed to get job status: {resp['status']} - {resp['text']}")
@@ -599,6 +721,7 @@ class EncodingService:
timeout: float = 3600.0,
progress_callback=None,
worker_url: Optional[str] = None,
queue_timeout: float = QUEUE_TIMEOUT_SECONDS,
) -> Dict[str, Any]:
"""
Poll for encoding job completion with tolerance for transient failures.
@@ -631,11 +754,25 @@ class EncodingService:
start_time = asyncio.get_event_loop().time()
last_progress = 0
consecutive_failures = 0
# Set to True after the first successful poll. Once we've seen the job,
# a later 404 means the worker LOST it (restart wiped in-memory state),
# not that it never existed — that is unrecoverable for this job id, so
# we resubmit rather than burn the transient-blip tolerance.
job_seen = False
# Set once the job is actually "running". The per-run `timeout` only
# counts from here; time spent "pending" in the worker's serialized
# heavy queue counts against `queue_timeout` instead.
run_started_at: Optional[float] = None
while True:
elapsed = asyncio.get_event_loop().time() - start_time
if elapsed > timeout:
raise TimeoutError(f"Encoding job {job_id} timed out after {timeout}s")
now = asyncio.get_event_loop().time()
if run_started_at is not None:
if now - run_started_at > timeout:
raise TimeoutError(f"Encoding job {job_id} timed out after {timeout}s")
elif now - start_time > queue_timeout:
raise TimeoutError(
f"Encoding job {job_id} stuck in worker queue longer than {queue_timeout}s"
)
try:
status = await self.get_job_status(job_id, worker_url=worker_url)
@@ -643,6 +780,20 @@ class EncodingService:
consecutive_failures = 0
except (aiohttp.ClientConnectorError, aiohttp.ServerDisconnectedError,
asyncio.TimeoutError, RuntimeError) as e:
# A 404 *after* we've already seen the job = the worker lost it
# (OOM/deploy restart wiped its in-memory registry). Resubmitting
# the same id can never recover it, so surface a distinct signal
# immediately instead of polling 4 more times and mislabelling it
# "lost contact" (which callers treat as unrecoverable).
if job_seen and isinstance(e, EncodingJobNotFoundError):
logger.warning(
f"[job:{job_id}] Worker no longer has this job after previously "
f"reporting it — treating as lost (worker restart): {e}"
)
raise EncodingJobLostError(
f"Encoding job {job_id} was lost by the worker (restarted mid-run)",
job_id=job_id,
) from e
consecutive_failures += 1
if consecutive_failures >= MAX_CONSECUTIVE_POLL_FAILURES:
logger.error(
@@ -667,12 +818,19 @@ class EncodingService:
logger.error(f"[job:{job_id}] Unexpected status type: {type(status)}")
status = {}
job_seen = True
job_status = status.get("status", "unknown")
progress = status.get("progress", 0)
if run_started_at is None and (job_status == "running" or progress):
run_started_at = now
# Report progress
if progress != last_progress:
logger.info(f"[job:{job_id}] Encoding progress: {progress}%")
queue_position = status.get("queue_position")
if job_status == "pending" and queue_position:
logger.info(f"[job:{job_id}] Queued on worker (position {queue_position})")
else:
logger.info(f"[job:{job_id}] Encoding progress: {progress}%")
last_progress = progress
if progress_callback:
try:
@@ -681,11 +839,21 @@ class EncodingService:
logger.warning(f"Progress callback failed: {e}")
if job_status == "complete":
logger.info(f"[job:{job_id}] GCE encoding complete in {elapsed:.1f}s")
logger.info(f"[job:{job_id}] GCE encoding complete in {now - start_time:.1f}s")
return status
if job_status == "failed":
error = status.get("error", "Unknown error")
# A restart-marked failure is recoverable by resubmission, same
# as a mid-run vanish — surface the typed signal so callers retry.
if status.get("restart_failure_code") == ENCODING_RESTART_FAILURE_CODE:
logger.warning(
f"[job:{job_id}] Worker marked job failed after a restart — treating as lost: {error}"
)
raise EncodingJobLostError(
f"Encoding job {job_id} was lost by the worker (restarted mid-run)",
job_id=job_id,
)
raise RuntimeError(f"Encoding job {job_id} failed: {error}")
await asyncio.sleep(poll_interval)
@@ -874,12 +1042,16 @@ class EncodingService:
# Pin polls to the worker the job landed on (see render_video_on_gce).
pinned_url = self._get_worker_url()
# Wait for completion with shorter timeout
# Wait for completion with a short timeout. Previews are interactive
# (a user is waiting in the review UI), so cap the *total* wait at the
# same short bound — don't let a queued preview sit for the long default
# queue_timeout before its per-run timeout even starts.
return await self.wait_for_completion(
job_id=job_id,
poll_interval=poll_interval,
timeout=timeout,
worker_url=pinned_url,
queue_timeout=timeout,
)
async def submit_render_video_job(
+71 -3
View File
@@ -28,7 +28,7 @@ Usage:
import asyncio
import logging
import time
from dataclasses import dataclass
from dataclasses import dataclass, field
from datetime import datetime, UTC
from typing import Any, Optional
@@ -106,6 +106,11 @@ class EncodingWorkerConfig:
active_override_ip: Optional[str] = None
active_override_zone: Optional[str] = None
active_override_set_at: Optional[str] = None
# Availability-awareness state: {"<machine_type>@<zone>": last_stockout_iso}.
# Written when a candidate start hits a capacity/stockout error, read by the
# shared preference logic to demote recently-exhausted types. See
# backend/services/encoding_worker_preference.py.
capacity_state: dict = field(default_factory=dict)
@property
def primary_url(self) -> str:
@@ -135,17 +140,29 @@ class EncodingWorkerCandidate:
Carries everything needed to talk to the worker: VM name + zone (so the
GCE compute client targets the right zone) and external IP (so successful
starts can be persisted as the active URL override).
starts can be persisted as the active URL override). ``machine_type`` (e.g.
"c4d-highcpu-32") lets the manager record/clear per-(type,zone) capacity
state so the shared preference logic can demote a stocked-out type.
"""
vm_name: str
zone: str
ip: str
machine_type: Optional[str] = None
# True iff this candidate is the blue-green PRIMARY VM. The override routing
# (set on fallback, clear on primary) keys off this flag, NOT list position —
# the preference logic may rank a fallback ahead of a stocked-out primary, so
# "first candidate" is no longer synonymous with "primary".
is_primary: bool = False
@property
def url(self) -> str:
return f"http://{self.ip}:{ENCODING_WORKER_PORT}"
def _cooldown_dict(self) -> dict:
"""Dict view for the shared preference helpers (cooldown_key)."""
return {"vm": self.vm_name, "zone": self.zone, "machine_type": self.machine_type}
class EncodingWorkerManager:
"""Manages blue-green encoding worker VMs via Firestore config and Compute API."""
@@ -190,6 +207,7 @@ class EncodingWorkerManager:
active_override_ip=data.get("active_override_ip"),
active_override_zone=data.get("active_override_zone"),
active_override_set_at=data.get("active_override_set_at"),
capacity_state=data.get("capacity_state") or {},
)
def update_activity(self) -> None:
@@ -421,6 +439,9 @@ class EncodingWorkerManager:
last_capacity_error: Optional[EncodingWorkerCapacityError] = None
last_start_error: Optional[EncodingWorkerStartError] = None
last_non_transient_error: Optional[EncodingWorkerStartError] = None
# When the caller marks a primary explicitly, route override off that flag;
# otherwise preserve the legacy "index 0 is the primary" behaviour.
has_explicit_primary = any(getattr(c, "is_primary", False) for c in candidates)
for index, candidate in enumerate(candidates):
try:
status = self.get_vm_status(candidate.vm_name, zone=candidate.zone)
@@ -435,7 +456,15 @@ class EncodingWorkerManager:
started = True
self.update_activity()
fell_back = index > 0
# A clean start means this type/zone has capacity again — clear
# any stale cooldown so the preference logic stops demoting it.
self._clear_stockout(candidate)
# "Fell back" = we did NOT land on the primary VM. Keyed off the
# explicit flag when present (ordering can rank a fallback ahead of
# a stocked-out primary, so it may not be index 0); otherwise the
# legacy position-based rule.
is_primary = candidate.is_primary if has_explicit_primary else (index == 0)
fell_back = not is_primary
if fell_back:
self._set_active_override(candidate)
else:
@@ -453,6 +482,9 @@ class EncodingWorkerManager:
"Candidate %s in %s exhausted (%s), trying next candidate",
candidate.vm_name, candidate.zone, cap_err.code,
)
# Record the stockout so the shared preference logic demotes this
# (type,zone) for a cooldown window instead of re-probing it first.
self._record_stockout(candidate)
last_capacity_error = cap_err
last_start_error = cap_err
continue
@@ -485,6 +517,42 @@ class EncodingWorkerManager:
assert last_start_error is not None
raise last_start_error
def _record_stockout(self, candidate) -> None:
"""Mark a candidate's (machine_type, zone) as recently stocked out.
Merges a single key into the ``capacity_state`` map so concurrent starts
don't clobber each other's entries. Best-effort — a Firestore hiccup here
must never break the start path, so failures are logged and swallowed.
"""
from backend.services.encoding_worker_preference import cooldown_key
key = cooldown_key(candidate._cooldown_dict())
if not key:
return
try:
self._doc_ref().set(
{"capacity_state": {key: datetime.now(UTC).isoformat()}}, merge=True
)
logger.info("Recorded stockout for %s", key)
except Exception as e: # noqa: BLE001 — never fail the start path on telemetry
logger.warning("Could not record stockout for %s: %s", key, e)
def _clear_stockout(self, candidate) -> None:
"""Clear a candidate's (machine_type, zone) cooldown after a clean start.
Sets the key to None (parsed as "not stocked out") via a merge so other
keys are untouched. Best-effort, like _record_stockout.
"""
from backend.services.encoding_worker_preference import cooldown_key
key = cooldown_key(candidate._cooldown_dict())
if not key:
return
try:
self._doc_ref().set({"capacity_state": {key: None}}, merge=True)
except Exception as e: # noqa: BLE001
logger.warning("Could not clear stockout for %s: %s", key, e)
def _set_active_override(self, candidate) -> None:
"""Record a fallback VM as the active worker URL in Firestore."""
now = datetime.now(UTC).isoformat()
@@ -0,0 +1,178 @@
"""Shared, pure preference logic for encoding-worker candidate ordering.
This is the SINGLE SOURCE OF TRUTH for how encode-worker VM candidates are ranked,
used by BOTH:
* runtime worker selection —
``backend/services/encoding_service._build_worker_candidates`` →
``encoding_worker_manager.ensure_any_running``
* deploy green (staging) selection —
``infrastructure/encoding-worker/deploy_promote.select_green_candidates``
Keeping the ordering in one place stops the two call-sites from drifting (they
previously used different ad-hoc heuristics: runtime = secret order, deploy =
"n2 before c4d").
Design:
* **Fastest-first base order.** Candidates sort by ``SPEED_RANK`` (lower =
faster), so the fastest available type (c4d) is always preferred when it can
start — the whole reason c4d was chosen. No behaviour change on a healthy day.
* **Availability-aware cooldown.** A type that recently failed to start with a
capacity/stockout error (recorded in Firestore ``capacity_state``) is
*demoted to the back* for ``COOLDOWN_SECONDS`` — long enough to stop paying
the ~2-min-per-attempt probe cost on a known-dead type, short enough to
re-probe and snap back to the faster type the moment capacity returns. It is
demoted, never dropped, so the pool always stays fully available.
This module is intentionally **dependency-free (stdlib only)** so that
``deploy_promote`` — which is loaded by path in CI with no backend package deps —
can import it without pulling the heavy backend tree.
"""
from __future__ import annotations
from datetime import datetime, timezone
from typing import Any, Dict, List, Optional
# Lower rank = faster = preferred. Seeded from CPU architecture; refine with the
# measured medians from infrastructure/encoding-worker/benchmark_types.py.
# c4d AMD EPYC Turin (Zen5) — current primary, fastest
# c4 Intel Emerald Rapids — newest Intel perf tier
# n4d AMD (Titanium) — flexible/deep AMD
# c2d AMD Milan (Zen3) — mature, deep pool
# n2d AMD Rome/Milan — deep pool (32 GB floor)
# n2 Intel Cascade/Ice Lake — current fallback (32 GB floor)
SPEED_RANK: Dict[str, int] = {
"c4d-highcpu-32": 10,
"c4-highcpu-32": 20,
"n4d-highcpu-32": 30,
"c2d-highcpu-32": 50,
"n2d-highcpu-32": 60,
"n2-highcpu-32": 70,
}
# Rank for a candidate whose machine type is unknown and cannot be inferred:
# treat as slowest-but-usable so it sorts LAST without ever being dropped.
UNKNOWN_RANK = 1000
# How long a type that just stocked out is demoted before it is re-probed.
COOLDOWN_SECONDS = 900 # 15 minutes
# Machine type of the blue-green primary/secondary pair (encoding-worker-a/-b).
# They are always c4d; used when a candidate carries no explicit machine_type.
PRIMARY_MACHINE_TYPE = "c4d-highcpu-32"
# vm-name substring → machine type, for backward-compat inference when a fallback
# entry predates the machine_type field. Checked in order — longer / more-specific
# family tokens FIRST so "n2d" is not shadowed by "n2", nor "c4d" by "c4".
_NAME_TOKEN_TO_TYPE = (
("c4d", "c4d-highcpu-32"),
("n4d", "n4d-highcpu-32"),
("n2d", "n2d-highcpu-32"),
("c2d", "c2d-highcpu-32"),
("c4", "c4-highcpu-32"),
("n2", "n2-highcpu-32"),
)
def _candidate_name(candidate: Dict[str, Any]) -> str:
"""VM name from either dict shape ({"vm"} for deploy, {"vm_name"} for runtime)."""
return (candidate.get("vm") or candidate.get("vm_name") or "")
def infer_machine_type(candidate: Dict[str, Any]) -> Optional[str]:
"""Best-effort machine type: explicit ``machine_type`` field, else vm-name token.
Fallback secret entries created before the ``machine_type`` field carry only
vm/zone/ip; the VM-name family token (…-fallback-n2c, …-fallback-c4a) is the
only hint. Returns None when nothing matches (caller treats as UNKNOWN_RANK).
"""
explicit = candidate.get("machine_type")
if explicit:
return explicit
name = _candidate_name(candidate).lower()
for token, mtype in _NAME_TOKEN_TO_TYPE:
if token in name:
return mtype
return None
def _speed_rank(candidate: Dict[str, Any]) -> int:
return SPEED_RANK.get(infer_machine_type(candidate), UNKNOWN_RANK)
def cooldown_key(candidate: Dict[str, Any]) -> Optional[str]:
"""Firestore ``capacity_state`` key for a candidate: ``"<machine_type>@<zone>"``.
Zone-scoped because a stockout is per (machine family × zone). Returns None
when the machine type can't be determined (no cooldown tracking possible).
NOTE: keys deliberately avoid ``.`` so they are safe as Firestore map keys.
"""
mtype = infer_machine_type(candidate)
if not mtype:
return None
zone = candidate.get("zone")
return f"{mtype}@{zone}" if zone else mtype
def _parse_iso(value: Any) -> Optional[datetime]:
if not value:
return None
try:
dt = datetime.fromisoformat(value)
except (ValueError, TypeError):
return None
if dt.tzinfo is None: # tolerate naive timestamps — assume UTC
dt = dt.replace(tzinfo=timezone.utc)
return dt
def _recently_stocked_out(
candidate: Dict[str, Any],
capacity_state: Optional[Dict[str, Any]],
now: datetime,
cooldown_seconds: float,
) -> bool:
"""True if this candidate's (type@zone) — or its coarser type-only key — is in cooldown."""
if not capacity_state:
return False
key = cooldown_key(candidate)
if not key:
return False
ts = _parse_iso(capacity_state.get(key))
if ts is None:
# Fall back to a type-only signal (a coarser "this family is short").
mtype = infer_machine_type(candidate)
if mtype:
ts = _parse_iso(capacity_state.get(mtype))
if ts is None:
return False
return (now - ts).total_seconds() < cooldown_seconds
def ordered_candidates(
pool: List[Dict[str, Any]],
capacity_state: Optional[Dict[str, Any]] = None,
now: Optional[datetime] = None,
cooldown_seconds: float = COOLDOWN_SECONDS,
) -> List[Dict[str, Any]]:
"""Rank ``pool`` fastest-first, demoting recently-stocked-out types to the back.
Args:
pool: candidate dicts, each ``{vm|vm_name, zone, ip, machine_type?, kind?}``.
Objects are returned as-is (not copied), only reordered — so callers can
round-trip their own richer objects through a dict view.
capacity_state: Firestore map ``{"<type>@<zone>"|"<type>": last_stockout_iso}``.
Absent/empty ⇒ pure fastest-first order (today's behaviour).
now: current UTC time (injectable for tests); defaults to ``datetime.now(UTC)``.
cooldown_seconds: demotion window; defaults to ``COOLDOWN_SECONDS``.
The speed sort is STABLE, so equal-rank candidates keep their input order —
callers express a secondary preference (e.g. zone spread) purely via input
ordering. The hot/cold partition is likewise stable within each group.
"""
if now is None:
now = datetime.now(timezone.utc)
ranked = sorted(pool, key=_speed_rank) # stable: fastest first
hot = [c for c in ranked if not _recently_stocked_out(c, capacity_state, now, cooldown_seconds)]
cold = [c for c in ranked if _recently_stocked_out(c, capacity_state, now, cooldown_seconds)]
return hot + cold
+4 -2
View File
@@ -3,7 +3,7 @@ Firestore database operations for job management.
"""
import logging
from typing import Optional, Dict, Any, List
from datetime import datetime
from datetime import datetime, timezone
from google.cloud import firestore
from google.cloud.firestore_v1 import FieldFilter
@@ -87,7 +87,9 @@ class FirestoreService:
# Create timeline event
timeline_event = TimelineEvent(
status=status.value,
timestamp=datetime.utcnow().isoformat(),
# Timezone-aware UTC so the serialized ISO string carries a
# "+00:00" offset (see job_manager.create_job for rationale).
timestamp=datetime.now(timezone.utc).isoformat(),
progress=progress,
message=message,
metadata=timeline_metadata,
+266 -13
View File
@@ -8,6 +8,7 @@ import shutil
import subprocess
import sys
import tempfile
import threading
import uuid
from concurrent.futures import ThreadPoolExecutor
from contextlib import asynccontextmanager
@@ -29,7 +30,50 @@ logger = logging.getLogger(__name__)
# so polls after a worker restart return the *last known* status instead of
# 404. Hot path stays in-memory; persistence is best-effort.
jobs: dict[str, dict] = {}
executor = ThreadPoolExecutor(max_workers=4) # 4 parallel encoding jobs
# Two execution lanes with very different memory profiles:
#
# heavy_executor — full renders (`run_render_video`) and final encodes
# (`run_encoding`). Each of these spawns an ffmpeg that already saturates
# every core, so running two in parallel gains no throughput but doubles
# peak RAM (a single 4K encode can use ~18 GB). Three concurrent encodes
# OOM-killed the 32 GB n2 fallback worker on 2026-08-15, which restarted
# the service and lost every in-flight job. Default to ONE heavy job at a
# time so the worker is OOM-proof on any machine type; the rest queue as
# `status="pending"` (surfaced via /health `queue_length` and /status
# `queue_position`). Override with ENCODING_HEAVY_CONCURRENCY only on
# boxes with headroom to spare.
#
# light_executor — wheel installs (`ensure_latest_wheel`) and interactive
# review previews (`run_preview_encoding`). These are small/fast and
# latency-sensitive, so they get their own lane and never wait behind a
# multi-minute encode.
def _heavy_concurrency() -> int:
"""Parse ENCODING_HEAVY_CONCURRENCY, clamped to a sane [1, 4] range.
A malformed/zero/negative value must never crash the worker at boot or
(via max_workers=0) wedge every encode — fall back to the OOM-safe default
of 1. The upper bound guards against an operator accidentally reintroducing
the concurrent-encode OOM on a small box.
"""
raw = os.environ.get("ENCODING_HEAVY_CONCURRENCY", "1")
try:
value = int(raw)
except (TypeError, ValueError):
logger.warning("Invalid ENCODING_HEAVY_CONCURRENCY=%r; defaulting to 1", raw)
return 1
if value < 1:
logger.warning("ENCODING_HEAVY_CONCURRENCY=%d < 1; clamping to 1", value)
return 1
if value > 4:
logger.warning("ENCODING_HEAVY_CONCURRENCY=%d > 4; clamping to 4", value)
return 4
return value
HEAVY_CONCURRENCY = _heavy_concurrency()
heavy_executor = ThreadPoolExecutor(max_workers=HEAVY_CONCURRENCY)
light_executor = ThreadPoolExecutor(max_workers=2)
# Persister is initialized lazily — see persistence.py — so import-time
# stays free of GCP creds. Tests can monkey-patch this attribute.
@@ -119,6 +163,15 @@ class JobStatus(BaseModel):
error: Optional[str] = None
output_files: Optional[list[str]] = None
metadata: Optional[dict] = None
# Set when a job was interrupted by a worker-process restart (OOM, deploy,
# crash). Its work_dir is gone, so the client should resubmit rather than
# treat this as a permanent failure. See persistence.mark_orphans_failed_on_startup.
restart_failure_code: Optional[str] = None
# How many heavy jobs (renders/encodes) are ahead of this one in the
# serialized heavy lane (0 = running or next up). None for previews /
# terminal jobs. Lets the client wait through a deep queue without
# tripping the encode timeout.
queue_position: Optional[int] = None
def download_from_gcs(gcs_uri: str, local_path: Path):
@@ -552,6 +605,30 @@ def run_render_video(job_id: str, work_dir: Path, request: "RenderVideoRequest")
WHEEL_INSTALL_TIMEOUT = int(os.environ.get("WHEEL_INSTALL_TIMEOUT", "900"))
WHEEL_INSTALL_ATTEMPTS = int(os.environ.get("WHEEL_INSTALL_ATTEMPTS", "3"))
# Serialize wheel checks. ensure_latest_wheel() runs on the light executor
# (>1 thread) and is invoked at the start of every job, so without a lock two
# concurrent jobs race on the same /tmp wheel path (`gsutil cp` clobbers the
# file mid-copy) and the same venv (`pip install` runs twice at once) —
# corrupting each other so one job fails with "wheel/dependencies not ready"
# (incident 2026-08-15, job 374dec26, three jobs hitting a fresh fallback boot).
# The lock makes the first caller do the work while the rest wait, then take the
# already-verified fast path below.
_wheel_lock = threading.Lock()
# Version we've already downloaded+installed+verified in THIS process. Lets a
# job skip the whole download/install/verify when the environment is already
# current — the common case, since startup.sh installs the wheel at boot and
# only the first job after a new deploy actually needs to install.
_verified_wheel_version: Optional[str] = None
def _installed_karaoke_gen_version() -> Optional[str]:
'''Return the karaoke-gen version currently importable in this venv, or None.'''
try:
from importlib.metadata import version as _get_version
return _get_version("karaoke-gen")
except Exception:
return None
# Modules exercised by the render (OutputGenerator) and encode
# (LocalEncodingService) code paths. Importing these confirms the whole
# dependency tree they pull in — including transitive deps like tenacity — is
@@ -587,16 +664,29 @@ def verify_wheel_imports():
def ensure_latest_wheel():
'''Download, install, and verify the latest karaoke-gen wheel from GCS.
'''Ensure the latest karaoke-gen wheel is installed & verified (thread-safe).
Called at the start of each job to enable hot code updates without restart.
In-progress jobs continue with their version, new jobs get latest code.
Serialized via `_wheel_lock` so concurrent jobs can't race on the shared
/tmp wheel path or venv; the first caller installs/verifies while the rest
wait and then hit the already-verified fast path.
'''
with _wheel_lock:
return _ensure_latest_wheel_locked()
def _ensure_latest_wheel_locked():
'''Download, install, and verify the latest karaoke-gen wheel from GCS.
MUST be called holding `_wheel_lock`. In-progress jobs continue with their
version, new jobs get latest code.
Retries the install and verifies the full import chain before returning, so
a transient/partial dependency install can't leave the worker running jobs
against a broken environment. Returns True only when the wheel is installed
AND its render/encode imports succeed.
'''
global _verified_wheel_version
try:
logger.info("Checking for latest karaoke-gen wheel in GCS...")
@@ -629,8 +719,29 @@ def ensure_latest_wheel():
wheel_uris.sort(key=extract_version)
latest_uri = wheel_uris[-1]
latest_version = str(extract_version(latest_uri))
wheel_path = os.path.join("/tmp", latest_uri.rsplit("/", 1)[-1])
# Fast path: if the environment is already at the latest version, skip
# the download/install entirely. This is the common case (startup.sh
# installs the wheel at boot) and — together with `_wheel_lock` — is what
# stops concurrent jobs from re-downloading/re-installing and racing.
if _verified_wheel_version == latest_version:
# Already validated in this process — nothing to do.
return True
installed_version = _installed_karaoke_gen_version()
if installed_version == latest_version:
# Right version is present but not yet verified in this process.
# Confirm the import chain (cheap) rather than reinstalling; only
# fall through to a full reinstall if a prior install was partial.
if verify_wheel_imports():
_verified_wheel_version = latest_version
logger.info(f"karaoke-gen {latest_version} already installed and verified; skipping wheel install")
return True
logger.warning(
f"karaoke-gen {latest_version} present but import chain incomplete; reinstalling"
)
cp_result = subprocess.run(
["gsutil", "cp", latest_uri, wheel_path],
capture_output=True, text=True, timeout=120
@@ -668,6 +779,7 @@ def ensure_latest_wheel():
# the render/encode paths need are actually importable before we let
# a job run against this environment.
if verify_wheel_imports():
_verified_wheel_version = latest_version
logger.info(f"Successfully installed and verified wheel: {wheel_path}")
return True
@@ -736,6 +848,110 @@ def generate_mov_from_png(png_path: Path, mov_path: Path, duration: int = 5) ->
return mov_path
# Portrait (9:16) karaoke render is default-on; set PORTRAIT_RENDER_ENABLED=false to disable.
PORTRAIT_RENDER_ENABLED = os.environ.get("PORTRAIT_RENDER_ENABLED", "true").lower() == "true"
PORTRAIT_SUFFIX = "(Final Karaoke Portrait 1080x1920)"
def _resolve_portrait_font(styles: dict, work_dir: Path) -> Optional[str]:
"""Resolve a usable .ttf file for the portrait header (PIL needs a file path).
libass resolves the lyrics font via fontconfig (the theme font is registered by
the earlier render step on the same VM), but PIL needs an actual file. Ask
fontconfig for the theme font family's file; fall back to any bundled style font.
"""
family = (styles.get("karaoke", {}) or {}).get("font") or "Avenir Next Bold"
try:
res = subprocess.run(
["fc-match", "--format=%{file}", family],
capture_output=True, text=True, timeout=5,
)
if res.returncode == 0 and res.stdout and os.path.isfile(res.stdout.strip()):
return res.stdout.strip()
except (FileNotFoundError, subprocess.TimeoutExpired):
pass
for pattern in ("style/*.ttf", "style/*.otf", "*.ttf"):
hit = next(iter(work_dir.glob(pattern)), None)
if hit:
return str(hit)
return None
def render_portrait_into_outputs(
job_id: str, work_dir: Path, output_dir: Path, base_name: str,
artist: str, title: str, instrumental: Path, config: dict,
) -> Optional[str]:
"""Render the portrait (9:16) karaoke video into ``output_dir`` (best-effort).
Reuses the same corrected-lyrics data + theme as the landscape render. Uses the
un-padded instrumental and un-countdown-processed segments so the two stay in
sync without the countdown offset (the portrait title card provides lead-in).
This is additive and non-fatal: any failure logs and returns ``None`` so the
landscape outputs and distribution proceed unaffected.
"""
if not PORTRAIT_RENDER_ENABLED:
logger.info(f"[job:{job_id}] Portrait render disabled via PORTRAIT_RENDER_ENABLED")
return None
try:
from karaoke_gen.lyrics_transcriber.types import CorrectionResult
from karaoke_gen.portrait import render_portrait_video, PortraitBrandConfig
# Corrected lyrics: prefer the reviewed corrections_updated.json.
corrections_file = None
for candidate in ("lyrics/corrections_updated.json", "lyrics/corrections.json"):
p = work_dir / candidate
if p.is_file():
corrections_file = p
break
if corrections_file is None:
found = next(iter(work_dir.glob("**/corrections*.json")), None)
corrections_file = found
if corrections_file is None:
logger.warning(f"[job:{job_id}] Portrait skipped: no corrections JSON found")
return None
with open(corrections_file, "r", encoding="utf-8") as f:
correction_result = CorrectionResult.from_dict(json.load(f))
# Theme styles (optional — renderer fills defaults).
styles = {}
style_params = work_dir / "style" / "style_params.json"
if not style_params.is_file():
style_params = next(iter(work_dir.glob("**/style_params.json")), None)
if style_params and Path(style_params).is_file():
with open(style_params, "r", encoding="utf-8") as f:
styles = json.load(f)
font_path = _resolve_portrait_font(styles, work_dir)
brand = PortraitBrandConfig(
brand_text=config.get("portrait_brand_text", "NOMAD KARAOKE"),
footer_text=config.get("portrait_footer_text", "nomadkaraoke.com"),
font_path=font_path,
)
out_path = output_dir / f"{base_name} {PORTRAIT_SUFFIX}.mp4"
logger.info(f"[job:{job_id}] Rendering portrait karaoke video -> {out_path.name}")
render_portrait_video(
correction_result=correction_result,
instrumental_path=str(instrumental),
styles=styles,
artist=artist,
title=title,
output_path=str(out_path),
brand=brand,
font_path=font_path,
work_dir=str(work_dir / "portrait_tmp"),
logger=logger,
)
if out_path.is_file():
logger.info(f"[job:{job_id}] Portrait render complete ({out_path.stat().st_size} bytes)")
return str(out_path)
logger.warning(f"[job:{job_id}] Portrait render produced no file")
return None
except Exception as e:
logger.error(f"[job:{job_id}] Portrait render failed (non-fatal): {e}", exc_info=True)
return None
def run_encoding(job_id: str, work_dir: Path, config: dict):
'''Run encoding using LocalEncodingService (single source of truth).
@@ -933,6 +1149,13 @@ def run_encoding(job_id: str, work_dir: Path, config: dict):
except Exception as e:
logger.warning(f"Failed to stage {suffix} MOV into outputs: {e}")
# Portrait (9:16) karaoke render — additive, non-fatal. Written into output_dir
# so it rides the same GCS upload + Dropbox distribution as the other finals.
jobs[job_id]["progress"] = 92
render_portrait_into_outputs(
job_id, work_dir, output_dir, base_name, artist, title, instrumental, config,
)
# Collect output files
output_files = [str(f) for f in output_dir.glob("*") if f.is_file()]
jobs[job_id]["output_files"] = output_files
@@ -972,7 +1195,7 @@ async def process_job(job_id: str, request: EncodeRequest):
# minutes) — run it in the thread pool so the async event loop keeps serving health
# checks and status polls.
loop = asyncio.get_event_loop()
if not await loop.run_in_executor(executor, ensure_latest_wheel):
if not await loop.run_in_executor(light_executor, ensure_latest_wheel):
raise RuntimeError(
"karaoke-gen wheel/dependencies not ready on this worker after retries; "
"job should be retried on a healthy worker"
@@ -998,10 +1221,11 @@ async def process_job(job_id: str, request: EncodeRequest):
logger.info(f"Downloading existing instrumental: {gcs_uri} -> {dest}")
download_single_file_from_gcs(gcs_uri, dest)
# Run encoding in thread pool (CPU-bound)
# Run encoding in the heavy lane (CPU/RAM-bound; serialized to
# avoid OOM — see heavy_executor comment).
loop = asyncio.get_event_loop()
output_dir = await loop.run_in_executor(
executor,
heavy_executor,
run_encoding,
job_id,
work_dir,
@@ -1047,11 +1271,11 @@ async def process_preview_job(job_id: str, request: EncodePreviewRequest):
work_dir = Path(temp_dir) / "work"
work_dir.mkdir()
# Run preview encoding in thread pool (CPU-bound)
# Note: run_preview_encoding handles download/upload internally
# Run preview encoding in the light lane so interactive review
# previews never queue behind a multi-minute full encode.
loop = asyncio.get_event_loop()
await loop.run_in_executor(
executor,
light_executor,
run_preview_encoding,
job_id,
work_dir,
@@ -1079,7 +1303,7 @@ async def process_render_video_job(job_id: str, request: RenderVideoRequest):
# Run in the thread pool: ensure_latest_wheel() blocks on subprocess installs (which
# can retry for many minutes) and must not stall the async event loop.
loop = asyncio.get_event_loop()
if not await loop.run_in_executor(executor, ensure_latest_wheel):
if not await loop.run_in_executor(light_executor, ensure_latest_wheel):
raise RuntimeError(
"karaoke-gen wheel/dependencies not ready on this worker after retries; "
"job should be retried on a healthy worker"
@@ -1089,10 +1313,11 @@ async def process_render_video_job(job_id: str, request: RenderVideoRequest):
work_dir = Path(temp_dir) / "work"
work_dir.mkdir()
# Run render-video in thread pool (CPU-bound)
# Run render-video in the heavy lane (CPU/RAM-bound; serialized to
# avoid OOM — see heavy_executor comment).
loop = asyncio.get_event_loop()
await loop.run_in_executor(
executor,
heavy_executor,
run_render_video,
job_id,
work_dir,
@@ -1135,6 +1360,7 @@ async def submit_preview_encode_job(request: EncodePreviewRequest, background_ta
"progress": 0,
"error": None,
"output_files": None,
"kind": "preview", # light lane — never counted in the heavy queue
}
_persist(job_id)
@@ -1167,6 +1393,7 @@ async def submit_render_video_job(request: RenderVideoRequest, background_tasks:
"error": None,
"output_files": None,
"metadata": None,
"kind": "render", # heavy lane
}
_persist(job_id)
@@ -1199,6 +1426,7 @@ async def submit_encode_job(request: EncodeRequest, background_tasks: Background
"progress": 0,
"error": None,
"output_files": None,
"kind": "encode", # heavy lane
}
_persist(job_id)
@@ -1207,12 +1435,37 @@ async def submit_encode_job(request: EncodeRequest, background_tasks: Background
return {"status": "accepted", "job_id": job_id}
_HEAVY_KINDS = frozenset({"encode", "render"})
def _heavy_queue_position(job_id: str) -> Optional[int]:
"""Number of heavy jobs ahead of `job_id` in the serialized heavy lane.
0 means this job is running or next up; None means it isn't a queued heavy
job (a preview, a terminal job, or unknown-kind). Relies on `jobs` being
insertion-ordered (dict order) so "ahead" == submitted earlier and still
pending/running.
"""
job = jobs.get(job_id)
if job is None or job.get("kind") not in _HEAVY_KINDS:
return None
if job.get("status") not in ("pending", "running"):
return None
ahead = 0
for other_id, other in jobs.items():
if other_id == job_id:
break
if other.get("kind") in _HEAVY_KINDS and other.get("status") in ("pending", "running"):
ahead += 1
return ahead
@app.get("/status/{job_id}")
async def get_job_status(job_id: str, _auth: bool = Depends(verify_api_key)) -> JobStatus:
# Get the status of an encoding job
if job_id not in jobs:
raise HTTPException(status_code=404, detail=f"Job {job_id} not found")
return JobStatus(**jobs[job_id])
return JobStatus(**jobs[job_id], queue_position=_heavy_queue_position(job_id))
@app.get("/health")
+5 -2
View File
@@ -10,7 +10,7 @@ This module handles the complete job lifecycle including:
"""
import logging
import uuid
from datetime import datetime
from datetime import datetime, timezone
from typing import Optional, Dict, Any, List
from backend.config import settings
@@ -80,7 +80,10 @@ class JobManager:
job_id = str(uuid.uuid4())[:8]
now = datetime.utcnow()
# Timezone-aware UTC so the serialized ISO string carries a "+00:00"
# offset. A naive datetime.utcnow() serializes with no offset, and the
# frontend's Date() parser then mis-reads it as local time.
now = datetime.now(timezone.utc)
job = Job(
job_id=job_id,
status=JobStatus.PENDING, # New state machine starts with PENDING
@@ -0,0 +1,436 @@
"""
Tests for the parked-job recovery endpoints on audio-search:
- POST /api/audio-search/{job_id}/research — retry / edit-and-re-search
- POST /api/audio-search/{job_id}/provide-url — attach a YouTube/yt-dlp URL
- POST /api/audio-search/{job_id}/attach-upload-url — signed URL for upload
- POST /api/audio-search/{job_id}/attach-upload-complete — finalise an upload
These cover the "0 results / dead-end" bulk-mode scenario where a job is parked
in AWAITING_AUDIO_SELECTION with no usable sources and the user needs a way out.
"""
from __future__ import annotations
from datetime import datetime, UTC
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from backend.models.job import Job, JobStatus
from backend.services.audio_search_service import AudioSearchResult, NoResultsError, AudioSearchError
from backend.services.auth_service import UserType, AuthResult
from backend.services.youtube_download_service import YouTubeDownloadError
NOW = datetime.now(UTC)
@pytest.fixture(autouse=True)
def _auth_overrides():
from backend.api.dependencies import require_auth, require_admin
from backend.main import app
async def mock_require_auth():
return AuthResult(
is_valid=True, user_type=UserType.STRIPE, remaining_uses=5,
message="test", is_admin=False, user_email="buyer@example.com",
)
app.dependency_overrides[require_auth] = mock_require_auth
app.dependency_overrides[require_admin] = mock_require_auth
yield
app.dependency_overrides.pop(require_auth, None)
app.dependency_overrides.pop(require_admin, None)
def _parked_job(job_id="park-1", artist="Arctic Monkeys", title="The View From the Afternoon",
status=JobStatus.AWAITING_AUDIO_SELECTION) -> Job:
return Job(
job_id=job_id, status=status, created_at=NOW, updated_at=NOW,
user_email="buyer@example.com", artist=artist, title=title,
audio_search_artist=artist, audio_search_title=title,
state_data={"credits_charged": 1, "audio_search_results": []},
)
def _result(idx=0, title="The View From the Afternoon", artist="Arctic Monkeys"):
r = AudioSearchResult(
index=idx, title=title, artist=artist, provider="RED",
url="", duration=180, quality="FLAC", source_id=f"id{idx}",
)
r.raw_result = {"target_file": f"{title}.flac", "is_lossless": True, "seeders": 20}
return r
@pytest.fixture
def mock_job_manager():
jm = MagicMock()
jm.get_job.return_value = _parked_job()
jm.update_job.return_value = None
jm.transition_to_state.return_value = True
jm.start_job_processing = AsyncMock(return_value=None)
return jm
# ---------------------------------------------------------------------------
# research (re-search)
# ---------------------------------------------------------------------------
class TestResearch:
def _patched(self, jm, search_mock):
return patch.multiple(
"backend.api.routes.audio_search",
job_manager=jm,
), patch(
"backend.api.routes.audio_search.get_audio_search_service",
return_value=search_mock,
)
def test_research_returns_results(self, mock_job_manager):
from fastapi.testclient import TestClient
from backend.main import app
search = MagicMock()
search.search_async = AsyncMock(return_value=[_result(0), _result(1)])
search.last_remote_search_id = "remote-xyz"
p1, p2 = self._patched(mock_job_manager, search)
with p1, p2:
client = TestClient(app)
resp = client.post("/api/audio-search/park-1/research", json={})
assert resp.status_code == 200, resp.text
data = resp.json()
assert data["results_count"] == 2
assert len(data["results"]) == 2
# results were cached back onto the job
cached = [c for c in mock_job_manager.update_job.call_args_list
if "state_data.audio_search_results" in c.args[1]]
assert cached, "expected results to be cached on the job"
def test_research_empty_is_200_not_error(self, mock_job_manager):
from fastapi.testclient import TestClient
from backend.main import app
search = MagicMock()
search.search_async = AsyncMock(side_effect=NoResultsError("nothing"))
search.last_remote_search_id = None
p1, p2 = self._patched(mock_job_manager, search)
with p1, p2:
client = TestClient(app)
resp = client.post("/api/audio-search/park-1/research", json={})
assert resp.status_code == 200, resp.text
assert resp.json()["results_count"] == 0
def test_research_applies_edited_terms(self, mock_job_manager):
from fastapi.testclient import TestClient
from backend.main import app
search = MagicMock()
search.search_async = AsyncMock(return_value=[_result(0)])
search.last_remote_search_id = None
p1, p2 = self._patched(mock_job_manager, search)
with p1, p2:
client = TestClient(app)
resp = client.post(
"/api/audio-search/park-1/research",
json={"artist": "Arctic Monkeys", "title": "The View from the Afternoon"},
)
assert resp.status_code == 200, resp.text
# search ran with the edited (normalized) title
search.search_async.assert_awaited_once()
args = search.search_async.await_args.args
assert args[0] == "Arctic Monkeys"
assert args[1] == "The View from the Afternoon"
# edit applied to the job (search terms + display metadata)
applied = [c for c in mock_job_manager.update_job.call_args_list
if c.args[1].get("title") == "The View from the Afternoon"]
assert applied, "expected edited title applied to job"
def test_research_502_on_search_error(self, mock_job_manager):
from fastapi.testclient import TestClient
from backend.main import app
search = MagicMock()
search.search_async = AsyncMock(side_effect=AudioSearchError("boom"))
p1, p2 = self._patched(mock_job_manager, search)
with p1, p2:
client = TestClient(app)
resp = client.post("/api/audio-search/park-1/research", json={})
assert resp.status_code == 502
def test_research_rejects_wrong_status(self, mock_job_manager):
from fastapi.testclient import TestClient
from backend.main import app
mock_job_manager.get_job.return_value = _parked_job(status=JobStatus.DOWNLOADING)
search = MagicMock()
search.search_async = AsyncMock(return_value=[])
p1, p2 = self._patched(mock_job_manager, search)
with p1, p2:
client = TestClient(app)
resp = client.post("/api/audio-search/park-1/research", json={})
assert resp.status_code == 400
search.search_async.assert_not_awaited()
def test_research_404_missing_job(self, mock_job_manager):
from fastapi.testclient import TestClient
from backend.main import app
mock_job_manager.get_job.return_value = None
search = MagicMock()
p1, p2 = self._patched(mock_job_manager, search)
with p1, p2:
client = TestClient(app)
resp = client.post("/api/audio-search/nope/research", json={})
assert resp.status_code == 404
# ---------------------------------------------------------------------------
# provide-url
# ---------------------------------------------------------------------------
class TestProvideUrl:
def test_youtube_url_uses_async_worker(self, mock_job_manager):
"""YouTube URLs go through the async download worker (no blocking request)."""
from fastapi.testclient import TestClient
from backend.main import app
yt = MagicMock()
yt.check_availability = AsyncMock(return_value={"available": True})
yt.download = AsyncMock()
ws = MagicMock()
ws.trigger_audio_download_worker = AsyncMock(return_value=True)
with patch.multiple("backend.api.routes.audio_search", job_manager=mock_job_manager), \
patch("backend.api.routes.audio_search.get_youtube_download_service", return_value=yt), \
patch("backend.api.routes.audio_search.get_worker_service", return_value=ws):
client = TestClient(app)
resp = client.post(
"/api/audio-search/park-1/provide-url",
json={"url": "https://www.youtube.com/watch?v=abcdefghijk"},
)
assert resp.status_code == 200, resp.text
ws.trigger_audio_download_worker.assert_awaited_once_with("park-1")
yt.download.assert_not_awaited() # async worker does the download, not inline
# job pointed at the URL source for the worker's job-level fallback
srcd = [c for c in mock_job_manager.update_job.call_args_list
if c.args[1].get("source_name") == "YouTube" and c.args[1].get("download_url")]
assert srcd
def test_youtube_worker_trigger_failure_requeues(self, mock_job_manager):
from fastapi.testclient import TestClient
from backend.main import app
yt = MagicMock()
yt.check_availability = AsyncMock(return_value={"available": True})
ws = MagicMock()
ws.trigger_audio_download_worker = AsyncMock(return_value=False)
with patch.multiple("backend.api.routes.audio_search", job_manager=mock_job_manager), \
patch("backend.api.routes.audio_search.get_youtube_download_service", return_value=yt), \
patch("backend.api.routes.audio_search.get_worker_service", return_value=ws):
client = TestClient(app)
resp = client.post(
"/api/audio-search/park-1/provide-url",
json={"url": "https://www.youtube.com/watch?v=abcdefghijk"},
)
assert resp.status_code == 502
statuses = [c.kwargs.get("new_status") for c in mock_job_manager.transition_to_state.call_args_list]
assert JobStatus.AWAITING_AUDIO_SELECTION in statuses
def test_generic_url_downloads_inline_and_starts(self, mock_job_manager):
"""Non-YouTube (yt-dlp) URLs download inline, then start processing."""
from fastapi.testclient import TestClient
from backend.main import app
yt = MagicMock()
yt.download = AsyncMock(return_value="uploads/park-1/audio/song.opus")
with patch.multiple("backend.api.routes.audio_search", job_manager=mock_job_manager), \
patch("backend.api.routes.audio_search.get_youtube_download_service", return_value=yt):
client = TestClient(app)
resp = client.post(
"/api/audio-search/park-1/provide-url",
json={"url": "https://soundcloud.com/artist/track"},
)
assert resp.status_code == 200, resp.text
yt.download.assert_awaited_once()
pathed = [c for c in mock_job_manager.update_job.call_args_list
if c.args[1].get("input_media_gcs_path") == "uploads/park-1/audio/song.opus"]
assert pathed
mock_job_manager.start_job_processing.assert_awaited()
def test_drm_url_rejected(self, mock_job_manager):
from fastapi.testclient import TestClient
from backend.main import app
yt = MagicMock()
with patch.multiple("backend.api.routes.audio_search", job_manager=mock_job_manager), \
patch("backend.api.routes.audio_search.get_youtube_download_service", return_value=yt):
client = TestClient(app)
resp = client.post(
"/api/audio-search/park-1/provide-url",
json={"url": "https://open.spotify.com/track/xyz"},
)
assert resp.status_code == 400
def test_unavailable_youtube_rejected(self, mock_job_manager):
from fastapi.testclient import TestClient
from backend.main import app
yt = MagicMock()
yt.check_availability = AsyncMock(return_value={"available": False, "is_private": True})
ws = MagicMock()
ws.trigger_audio_download_worker = AsyncMock(return_value=True)
with patch.multiple("backend.api.routes.audio_search", job_manager=mock_job_manager), \
patch("backend.api.routes.audio_search.get_youtube_download_service", return_value=yt), \
patch("backend.api.routes.audio_search.get_worker_service", return_value=ws):
client = TestClient(app)
resp = client.post(
"/api/audio-search/park-1/provide-url",
json={"url": "https://www.youtube.com/watch?v=abcdefghijk"},
)
assert resp.status_code == 400
ws.trigger_audio_download_worker.assert_not_awaited()
def test_generic_download_failure_requeues_and_502(self, mock_job_manager):
from fastapi.testclient import TestClient
from backend.main import app
yt = MagicMock()
yt.download = AsyncMock(side_effect=YouTubeDownloadError("dead"))
with patch.multiple("backend.api.routes.audio_search", job_manager=mock_job_manager), \
patch("backend.api.routes.audio_search.get_youtube_download_service", return_value=yt):
client = TestClient(app)
resp = client.post(
"/api/audio-search/park-1/provide-url",
json={"url": "https://soundcloud.com/artist/track"},
)
assert resp.status_code == 502
# restored to awaiting so the user can retry
statuses = [c.kwargs.get("new_status") for c in mock_job_manager.transition_to_state.call_args_list]
assert JobStatus.AWAITING_AUDIO_SELECTION in statuses
def test_provide_url_rejects_wrong_status(self, mock_job_manager):
from fastapi.testclient import TestClient
from backend.main import app
mock_job_manager.get_job.return_value = _parked_job(status=JobStatus.DOWNLOADING)
yt = MagicMock()
with patch.multiple("backend.api.routes.audio_search", job_manager=mock_job_manager), \
patch("backend.api.routes.audio_search.get_youtube_download_service", return_value=yt):
client = TestClient(app)
resp = client.post(
"/api/audio-search/park-1/provide-url",
json={"url": "https://www.youtube.com/watch?v=abcdefghijk"},
)
assert resp.status_code == 400
# ---------------------------------------------------------------------------
# attach upload
# ---------------------------------------------------------------------------
class TestAttachUpload:
def test_attach_upload_url_returns_signed_url(self, mock_job_manager):
from fastapi.testclient import TestClient
from backend.main import app
storage = MagicMock()
storage.generate_signed_upload_url.return_value = "https://signed.example/put"
with patch.multiple("backend.api.routes.audio_search",
job_manager=mock_job_manager, storage_service=storage):
client = TestClient(app)
resp = client.post(
"/api/audio-search/park-1/attach-upload-url",
json={"filename": "my song.flac", "content_type": "audio/flac"},
)
assert resp.status_code == 200, resp.text
data = resp.json()
assert data["gcs_path"] == "uploads/park-1/audio/my song.flac"
assert data["upload_url"] == "https://signed.example/put"
def test_attach_upload_url_rejects_bad_extension(self, mock_job_manager):
from fastapi.testclient import TestClient
from backend.main import app
storage = MagicMock()
storage.generate_signed_upload_url.return_value = "https://signed.example/put"
with patch.multiple("backend.api.routes.audio_search",
job_manager=mock_job_manager, storage_service=storage):
client = TestClient(app)
resp = client.post(
"/api/audio-search/park-1/attach-upload-url",
json={"filename": "..\\evil.exe", "content_type": "application/octet-stream"},
)
assert resp.status_code == 400
storage.generate_signed_upload_url.assert_not_called()
def test_attach_complete_starts_processing(self, mock_job_manager):
from fastapi.testclient import TestClient
from backend.main import app
storage = MagicMock()
storage.list_files.return_value = ["uploads/park-1/audio/my_song.flac"]
with patch.multiple("backend.api.routes.audio_search",
job_manager=mock_job_manager, storage_service=storage):
client = TestClient(app)
resp = client.post(
"/api/audio-search/park-1/attach-upload-complete",
json={"gcs_path": "uploads/park-1/audio/my_song.flac"},
)
assert resp.status_code == 200, resp.text
pathed = [c for c in mock_job_manager.update_job.call_args_list
if c.args[1].get("input_media_gcs_path") == "uploads/park-1/audio/my_song.flac"]
assert pathed
mock_job_manager.start_job_processing.assert_awaited()
def test_attach_complete_rejects_gcs_path_outside_prefix(self, mock_job_manager):
from fastapi.testclient import TestClient
from backend.main import app
storage = MagicMock()
storage.list_files.return_value = ["uploads/park-1/audio/my_song.flac"]
with patch.multiple("backend.api.routes.audio_search",
job_manager=mock_job_manager, storage_service=storage):
client = TestClient(app)
resp = client.post(
"/api/audio-search/park-1/attach-upload-complete",
json={"gcs_path": "uploads/other-job/audio/steal.flac"},
)
assert resp.status_code == 400
mock_job_manager.start_job_processing.assert_not_awaited()
def test_attach_complete_400_when_no_file(self, mock_job_manager):
from fastapi.testclient import TestClient
from backend.main import app
storage = MagicMock()
storage.list_files.return_value = []
with patch.multiple("backend.api.routes.audio_search",
job_manager=mock_job_manager, storage_service=storage):
client = TestClient(app)
resp = client.post("/api/audio-search/park-1/attach-upload-complete", json={})
assert resp.status_code == 400
mock_job_manager.start_job_processing.assert_not_awaited()
+221
View File
@@ -0,0 +1,221 @@
"""Unit tests for the encoding-worker deploy decision logic.
The module lives under infrastructure/ (not an importable package), so we load
it by path. Covers the two things the CI workflow can't test itself: which VMs
to try as a fresh green target, and how to promote a validated green to serving.
"""
import importlib.util
from pathlib import Path
import pytest
_MODULE_PATH = (
Path(__file__).resolve().parents[2]
/ "infrastructure" / "encoding-worker" / "deploy_promote.py"
)
_spec = importlib.util.spec_from_file_location("deploy_promote", _MODULE_PATH)
deploy_promote = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(deploy_promote)
select_green_candidates = deploy_promote.select_green_candidates
promote_plan = deploy_promote.promote_plan
FALLBACKS = [
{"vm": "encoding-worker-fallback-a", "zone": "us-central1-a", "ip": "34.55.231.54"},
{"vm": "encoding-worker-fallback-b", "zone": "us-central1-b", "ip": "35.193.127.24"},
{"vm": "encoding-worker-fallback-n2c", "zone": "us-central1-c", "ip": "35.226.119.227"},
{"vm": "encoding-worker-fallback-n2f", "zone": "us-central1-f", "ip": "35.254.152.14"},
]
def _config(**over):
base = {
"primary_vm": "encoding-worker-b", "primary_ip": "34.10.189.118",
"primary_version": "0.192.9",
"secondary_vm": "encoding-worker-a", "secondary_ip": "34.57.78.246",
"active_override_vm": "encoding-worker-fallback-n2f",
"active_override_ip": "35.254.152.14", "active_override_zone": "us-central1-f",
}
base.update(over)
return base
class TestSelectGreenCandidates:
def test_secondary_first_then_n2_before_c4d_excluding_override(self):
# LEGACY secret shape (no machine_type). The shared ranking infers n2 from
# the n2c/n2f names (rank 70) but CANNOT infer the bare c4d fallbacks a/b
# (no family token) → they get UNKNOWN_RANK and sort last. Net order here
# matches the pre-refactor "secondary, then n2, then c4d" result. Once the
# secret carries machine_type (post-rollout), a/b rank as c4d — see
# TestSelectGreenRankingSharedWithRuntime.
cands = select_green_candidates(_config(), FALLBACKS)
vms = [c["vm"] for c in cands]
# c4d secondary leads; current override (n2f) excluded; n2c (n2) before c4d fallbacks.
assert vms[0] == "encoding-worker-a"
assert cands[0]["kind"] == "secondary"
assert "encoding-worker-fallback-n2f" not in vms # the serving override is excluded
assert vms[1] == "encoding-worker-fallback-n2c" # remaining n2 preferred
assert vms[1:] == [
"encoding-worker-fallback-n2c",
"encoding-worker-fallback-a",
"encoding-worker-fallback-b",
]
assert all(c["kind"] == "fallback" for c in cands[1:])
def test_candidate_carries_zone_and_ip(self):
cands = select_green_candidates(_config(), FALLBACKS)
n2c = next(c for c in cands if c["vm"] == "encoding-worker-fallback-n2c")
assert n2c["zone"] == "us-central1-c"
assert n2c["ip"] == "35.226.119.227"
def test_no_secondary_still_lists_fallbacks(self):
cands = select_green_candidates(_config(secondary_vm=None), FALLBACKS)
assert all(c["kind"] == "fallback" for c in cands)
assert cands[0]["vm"] == "encoding-worker-fallback-n2c"
def test_malformed_fallback_entries_are_dropped(self):
fbs = [
{"vm": "encoding-worker-fallback-n2c", "zone": "us-central1-c", "ip": "35.226.119.227"},
{"vm": "encoding-worker-fallback-broken", "ip": "1.2.3.4"}, # no zone
{"zone": "us-central1-a", "ip": "5.6.7.8"}, # no vm
{"vm": "encoding-worker-fallback-noip", "zone": "us-central1-b"}, # no ip
]
cands = select_green_candidates(_config(active_override_vm=None), fbs)
vms = [c["vm"] for c in cands]
assert vms.count("encoding-worker-fallback-n2c") == 1
assert "encoding-worker-fallback-broken" not in vms
assert "encoding-worker-fallback-noip" not in vms
assert None not in vms # the entry with no "vm" is dropped, not emitted as vm=None
def test_no_override_keeps_all_fallbacks(self):
cands = select_green_candidates(_config(active_override_vm=None), FALLBACKS)
fb_vms = [c["vm"] for c in cands if c["kind"] == "fallback"]
# n2 fallbacks first (either order among the two n2s is fine — assert as a set head)
assert set(fb_vms[:2]) == {"encoding-worker-fallback-n2c", "encoding-worker-fallback-n2f"}
assert set(fb_vms) == {f["vm"] for f in FALLBACKS}
class TestPromotePlanFallbackBranch:
def test_fallback_green_becomes_override_and_drains_old(self):
green = {"vm": "encoding-worker-fallback-n2c", "ip": "35.226.119.227",
"zone": "us-central1-c", "kind": "fallback"}
plan = promote_plan(green, _config(), now="NOW", version="0.194.1")
u = plan["firestore_updates"]
assert u["active_override_vm"] == "encoding-worker-fallback-n2c"
assert u["active_override_ip"] == "35.226.119.227"
assert u["active_override_zone"] == "us-central1-c"
assert u["active_override_version"] == "0.194.1"
assert u["deploy_in_progress"] is False
# primary/secondary untouched (c4d resumes when capacity returns)
assert "primary_vm" not in u and "secondary_vm" not in u
# old override (n2f) drained + stopped
assert plan["drain_and_stop"] == [
{"vm": "encoding-worker-fallback-n2f", "ip": "35.254.152.14", "zone": "us-central1-f"}
]
def test_no_drain_when_no_previous_override(self):
green = {"vm": "encoding-worker-fallback-n2c", "ip": "35.226.119.227",
"zone": "us-central1-c", "kind": "fallback"}
plan = promote_plan(green, _config(active_override_vm=None), now="NOW", version="0.194.1")
assert plan["drain_and_stop"] == []
def test_no_self_drain_when_green_is_current_override(self):
# Degenerate (shouldn't happen since candidates exclude the override), but
# must never drain-stop the worker we just promoted.
green = {"vm": "encoding-worker-fallback-n2f", "ip": "35.254.152.14",
"zone": "us-central1-f", "kind": "fallback"}
plan = promote_plan(green, _config(), now="NOW", version="0.194.1")
assert plan["drain_and_stop"] == []
class TestPromotePlanSecondaryBranch:
def test_secondary_green_swaps_and_clears_stale_override(self):
green = {"vm": "encoding-worker-a", "ip": "34.57.78.246",
"zone": "us-central1-c", "kind": "secondary"}
plan = promote_plan(green, _config(), now="NOW", version="0.194.1")
u = plan["firestore_updates"]
# green -> primary, old primary -> secondary
assert u["primary_vm"] == "encoding-worker-a"
assert u["primary_version"] == "0.194.1"
assert u["secondary_vm"] == "encoding-worker-b"
assert u["secondary_version"] == "0.192.9"
# stale override cleared so active_url follows the fresh primary
assert u["active_override_vm"] is None
assert u["active_override_version"] is None
assert u["deploy_in_progress"] is False
# both the old primary and the old override get drained + stopped
drained = {d["vm"] for d in plan["drain_and_stop"]}
assert drained == {"encoding-worker-b", "encoding-worker-fallback-n2f"}
def test_secondary_never_drains_the_promoted_green(self):
# Pathological config where a stale override (or primary) names the green
# VM — the plan must never tell the workflow to stop what it just promoted.
green = {"vm": "encoding-worker-a", "ip": "34.57.78.246",
"zone": "us-central1-c", "kind": "secondary"}
cfg = _config(active_override_vm="encoding-worker-a",
active_override_ip="34.57.78.246",
active_override_zone="us-central1-c")
plan = promote_plan(green, cfg, now="NOW", version="0.194.2")
assert all(d["vm"] != "encoding-worker-a" for d in plan["drain_and_stop"])
# The override is still cleared in config even though we don't stop that VM.
assert plan["firestore_updates"]["active_override_vm"] is None
def test_secondary_swap_without_override(self):
green = {"vm": "encoding-worker-a", "ip": "34.57.78.246",
"zone": "us-central1-c", "kind": "secondary"}
plan = promote_plan(green, _config(active_override_vm=None), now="NOW", version="0.194.1")
u = plan["firestore_updates"]
assert "active_override_vm" not in u # nothing to clear
assert [d["vm"] for d in plan["drain_and_stop"]] == ["encoding-worker-b"]
class TestSelectGreenRankingSharedWithRuntime:
"""Green selection now ranks via the shared preference (machine_type + cooldown)."""
# 6-type pool with explicit machine_type (mirrors the post-rollout secret).
POOL = [
{"vm": "encoding-worker-fallback-c4a", "zone": "us-central1-a", "ip": "10.0.0.1",
"machine_type": "c4-highcpu-32"},
{"vm": "encoding-worker-fallback-n4db", "zone": "us-central1-b", "ip": "10.0.0.2",
"machine_type": "n4d-highcpu-32"},
{"vm": "encoding-worker-fallback-c2df", "zone": "us-central1-f", "ip": "10.0.0.3",
"machine_type": "c2d-highcpu-32"},
{"vm": "encoding-worker-fallback-n2da", "zone": "us-central1-a", "ip": "10.0.0.4",
"machine_type": "n2d-highcpu-32"},
{"vm": "encoding-worker-fallback-n2c", "zone": "us-central1-c", "ip": "10.0.0.5",
"machine_type": "n2-highcpu-32"},
]
def test_secondary_c4d_leads_then_fastest_fallbacks(self):
cfg = _config(active_override_vm=None)
vms = [c["vm"] for c in select_green_candidates(cfg, self.POOL)]
# c4d secondary (rank 10) first, then c4 > n4d > c2d > n2d > n2.
assert vms == [
"encoding-worker-a", # secondary, c4d
"encoding-worker-fallback-c4a", # c4
"encoding-worker-fallback-n4db", # n4d
"encoding-worker-fallback-c2df", # c2d
"encoding-worker-fallback-n2da", # n2d
"encoding-worker-fallback-n2c", # n2
]
def test_c4d_stockout_demotes_secondary_below_deep_pool(self):
# c4d@us-central1-c (the secondary's zone) recently stocked out.
from datetime import datetime, timezone
cfg = _config(
active_override_vm=None,
capacity_state={"c4d-highcpu-32@us-central1-c": datetime.now(timezone.utc).isoformat()},
)
cands = select_green_candidates(cfg, self.POOL)
vms = [c["vm"] for c in cands]
# The c4d secondary is demoted to the back; a fast fallback (c4) now leads.
assert vms[0] == "encoding-worker-fallback-c4a"
assert vms[-1] == "encoding-worker-a" # demoted secondary re-probed last
# kind survives the reordering so promote_plan still treats it correctly.
assert cands[-1]["kind"] == "secondary"
def test_machine_type_carried_through(self):
cands = select_green_candidates(_config(active_override_vm=None), self.POOL)
c4 = next(c for c in cands if c["vm"] == "encoding-worker-fallback-c4a")
assert c4["machine_type"] == "c4-highcpu-32"
+31
View File
@@ -313,6 +313,37 @@ class TestGCEEncodingBackend:
assert output.success is False
assert "GCE worker error" in output.error_message
@patch.object(GCEEncodingBackend, "_get_service")
@pytest.mark.asyncio
async def test_encode_reraises_lost_job_error(self, mock_get_service):
"""A lost-job error (worker restart) must propagate, NOT become success=False.
The orchestrator's resubmit wrapper only fires on the typed exception; if
the backend flattened it into success=False the render would just fail
instead of being retried."""
from backend.services.encoding_errors import EncodingJobLostError
mock_service = MagicMock()
mock_service.encode_videos = AsyncMock(
side_effect=EncodingJobLostError("worker lost the job", job_id="test-job")
)
mock_get_service.return_value = mock_service
backend = GCEEncodingBackend()
input_config = EncodingInput(
title_video_path="/input/title.mov",
karaoke_video_path="/input/karaoke.mov",
instrumental_audio_path="/input/audio.flac",
options={
"job_id": "test-job",
"input_gcs_path": "gs://bucket/input/",
"output_gcs_path": "gs://bucket/output/",
}
)
with pytest.raises(EncodingJobLostError):
await backend.encode(input_config)
@patch.object(GCEEncodingBackend, "_get_service")
@pytest.mark.asyncio
async def test_encode_handles_list_result(self, mock_get_service):
+274
View File
@@ -16,7 +16,9 @@ from backend.services.encoding_service import (
INITIAL_BACKOFF_SECONDS,
MAX_BACKOFF_SECONDS,
MAX_CONSECUTIVE_POLL_FAILURES,
run_with_lost_job_resubmit,
)
from backend.services.encoding_errors import EncodingJobLostError, EncodingJobNotFoundError
@pytest.fixture
@@ -666,6 +668,193 @@ class TestWaitForCompletionPollTolerance:
assert call_count == 6 # 2 fail + 1 success + 2 fail + 1 success
class TestWaitForCompletionLostJob:
"""A worker restart (OOM/deploy) that wipes an in-flight job must surface a
distinct, recoverable signal instead of the generic poll-failure timeout."""
@pytest.mark.asyncio
async def test_404_after_job_seen_raises_lost_error(self, encoding_service):
"""Once we've seen the job run, a later 404 = the worker lost it → resubmit."""
call_count = 0
async def mock_get_status(job_id, worker_url=None):
nonlocal call_count
call_count += 1
if call_count == 1:
return {"status": "running", "progress": 30}
raise EncodingJobNotFoundError(f"Encoding job {job_id} not found")
with patch.object(encoding_service, "get_job_status", side_effect=mock_get_status), \
patch("asyncio.sleep", new_callable=AsyncMock), \
patch("asyncio.get_event_loop") as mock_loop:
mock_loop.return_value.time.return_value = 0
with pytest.raises(EncodingJobLostError):
await encoding_service.wait_for_completion("j1")
# Should bail on the FIRST 404, not burn the full poll tolerance.
assert call_count == 2
@pytest.mark.asyncio
async def test_404_before_job_seen_is_tolerated(self, encoding_service):
"""A 404 before the job is ever seen is a submit/poll race, not a lost job —
keep the transient tolerance (avoids false resubmits)."""
async def always_404(job_id, worker_url=None):
raise EncodingJobNotFoundError(f"Encoding job {job_id} not found")
with patch.object(encoding_service, "get_job_status", side_effect=always_404), \
patch("asyncio.sleep", new_callable=AsyncMock), \
patch("asyncio.get_event_loop") as mock_loop:
mock_loop.return_value.time.return_value = 0
# Falls through to the generic tolerance, NOT EncodingJobLostError.
with pytest.raises(RuntimeError, match="consecutive poll failures"):
await encoding_service.wait_for_completion("j1")
@pytest.mark.asyncio
async def test_restart_failure_code_raises_lost_error(self, encoding_service):
"""A terminal failure carrying the restart marker is recoverable → lost error."""
async def mock_get_status(job_id, worker_url=None):
return {
"status": "failed",
"error": "Encoding worker restarted mid-job",
"restart_failure_code": "encoding_worker_restart",
}
with patch.object(encoding_service, "get_job_status", side_effect=mock_get_status), \
patch("asyncio.sleep", new_callable=AsyncMock), \
patch("asyncio.get_event_loop") as mock_loop:
mock_loop.return_value.time.return_value = 0
with pytest.raises(EncodingJobLostError):
await encoding_service.wait_for_completion("j1")
@pytest.mark.asyncio
async def test_plain_failure_still_raises_runtimeerror(self, encoding_service):
"""A normal (non-restart) failure stays a hard RuntimeError, not a resubmit."""
async def mock_get_status(job_id, worker_url=None):
return {"status": "failed", "error": "ffmpeg exploded"}
with patch.object(encoding_service, "get_job_status", side_effect=mock_get_status), \
patch("asyncio.sleep", new_callable=AsyncMock), \
patch("asyncio.get_event_loop") as mock_loop:
mock_loop.return_value.time.return_value = 0
with pytest.raises(RuntimeError, match="ffmpeg exploded"):
await encoding_service.wait_for_completion("j1")
# And it must not be the recoverable subtype.
try:
await encoding_service.wait_for_completion("j1")
except EncodingJobLostError: # pragma: no cover
pytest.fail("plain failure should not be EncodingJobLostError")
except RuntimeError:
pass
@pytest.mark.asyncio
async def test_pending_does_not_count_toward_run_timeout(self, encoding_service):
"""Time spent queued (pending) is bounded by queue_timeout, not the per-run
timeout — a burst can wait in the serialized heavy queue and still succeed."""
statuses = [
{"status": "pending", "progress": 0, "queue_position": 3},
{"status": "pending", "progress": 0, "queue_position": 2},
{"status": "pending", "progress": 0, "queue_position": 1},
{"status": "running", "progress": 10},
{"status": "complete", "output_files": ["a.mp4"]},
]
idx = 0
async def mock_get_status(job_id, worker_url=None):
nonlocal idx
s = statuses[idx]
idx += 1
return s
# start_time read, then one read per loop iteration. Job is pending until
# t=300 (>> timeout=50) then runs and completes at t=310 (10s of run time).
seq = [0, 0, 100, 200, 300, 310]
def fake_time():
return seq.pop(0) if len(seq) > 1 else seq[0]
with patch.object(encoding_service, "get_job_status", side_effect=mock_get_status), \
patch("asyncio.sleep", new_callable=AsyncMock), \
patch("asyncio.get_event_loop") as mock_loop:
mock_loop.return_value.time.side_effect = fake_time
result = await encoding_service.wait_for_completion(
"j1", timeout=50, queue_timeout=1000
)
assert result["status"] == "complete"
class TestPreviewQueueTimeout:
"""A queued preview must not wait the long default queue_timeout — an
interactive user is waiting, so total wait is capped at the short timeout."""
@pytest.mark.asyncio
async def test_preview_caps_queue_timeout_to_timeout(self, encoding_service):
submit = AsyncMock(return_value={"status": "accepted", "job_id": "p1"})
wait = AsyncMock(return_value={"status": "complete"})
with patch.object(encoding_service, "submit_preview_encoding_job", submit), \
patch.object(encoding_service, "wait_for_completion", wait):
await encoding_service.encode_preview_video(
job_id="p1",
ass_gcs_path="gs://b/x.ass",
audio_gcs_path="gs://b/a.flac",
output_gcs_path="gs://b/out.mp4",
timeout=90.0,
)
_, kwargs = wait.call_args
assert kwargs["timeout"] == 90.0
assert kwargs["queue_timeout"] == 90.0
class TestRunWithLostJobResubmit:
"""The bounded resubmit wrapper used by the render + encode workers."""
@pytest.mark.asyncio
async def test_resubmits_with_fresh_id_then_succeeds(self):
seen_ids = []
async def op(job_id):
seen_ids.append(job_id)
if len(seen_ids) == 1:
raise EncodingJobLostError("lost", job_id=job_id)
return {"status": "complete"}
result = await run_with_lost_job_resubmit(op, "base123", max_resubmits=2)
assert result["status"] == "complete"
assert seen_ids[0] == "base123"
assert seen_ids[1].startswith("base123_retry_")
assert len(seen_ids) == 2
@pytest.mark.asyncio
async def test_gives_up_after_max_resubmits(self):
attempts = []
async def op(job_id):
attempts.append(job_id)
raise EncodingJobLostError("lost", job_id=job_id)
with pytest.raises(EncodingJobLostError):
await run_with_lost_job_resubmit(op, "base", max_resubmits=2)
# 1 initial + 2 resubmits = 3 attempts.
assert len(attempts) == 3
assert attempts[0] == "base"
assert all(a.startswith("base_retry_") for a in attempts[1:])
@pytest.mark.asyncio
async def test_other_errors_are_not_retried(self):
attempts = []
async def op(job_id):
attempts.append(job_id)
raise RuntimeError("some other failure")
with pytest.raises(RuntimeError, match="some other failure"):
await run_with_lost_job_resubmit(op, "base", max_resubmits=2)
assert len(attempts) == 1 # not retried
class TestDynamicURLResolution:
"""Tests that EncodingService reads URL from Firestore, not static config."""
@@ -877,3 +1066,88 @@ class TestWorkerUrlPinning:
assert result["status"] == "complete"
assert result["output_files"] == ["4k.mp4"]
class TestBuildWorkerCandidates:
"""_build_worker_candidates ranks primary + fallbacks via the shared preference."""
def _config(self, capacity_state=None):
cfg = MagicMock()
cfg.primary_vm = "encoding-worker-a"
cfg.primary_ip = "10.0.0.1"
cfg.primary_machine_type = None # → defaults to c4d
cfg.capacity_state = capacity_state or {}
return cfg
def _service_with_fallbacks(self, encoding_service, fallbacks_json, capacity_state=None):
mgr = MagicMock()
mgr._zone = "us-central1-c"
mgr.get_config.return_value = self._config(capacity_state)
encoding_service._worker_manager = mgr
encoding_service.settings.encoding_worker_fallback_vms = fallbacks_json
return encoding_service
def test_primary_first_and_flagged(self, encoding_service):
svc = self._service_with_fallbacks(encoding_service, None)
cands = svc._build_worker_candidates()
assert cands[0].vm_name == "encoding-worker-a"
assert cands[0].is_primary is True
assert cands[0].machine_type == "c4d-highcpu-32"
def test_fallbacks_ranked_fastest_first(self, encoding_service):
import json
fallbacks = json.dumps([
{"vm": "encoding-worker-fallback-n2f", "zone": "us-central1-f", "ip": "10.0.0.5",
"machine_type": "n2-highcpu-32"},
{"vm": "encoding-worker-fallback-c4a", "zone": "us-central1-a", "ip": "10.0.0.6",
"machine_type": "c4-highcpu-32"},
])
svc = self._service_with_fallbacks(encoding_service, fallbacks)
order = [c.vm_name for c in svc._build_worker_candidates()]
# c4d primary, then c4 (faster), then n2.
assert order == ["encoding-worker-a", "encoding-worker-fallback-c4a",
"encoding-worker-fallback-n2f"]
def test_stocked_out_primary_demoted(self, encoding_service):
import json
from datetime import datetime, timezone
fallbacks = json.dumps([
{"vm": "encoding-worker-fallback-c4a", "zone": "us-central1-a", "ip": "10.0.0.6",
"machine_type": "c4-highcpu-32"},
])
# c4d@us-central1-c stocked out "now" → demoted below c4.
cap = {"c4d-highcpu-32@us-central1-c": datetime.now(timezone.utc).isoformat()}
svc = self._service_with_fallbacks(encoding_service, fallbacks, capacity_state=cap)
cands = svc._build_worker_candidates()
order = [c.vm_name for c in cands]
assert order == ["encoding-worker-fallback-c4a", "encoding-worker-a"]
# is_primary still correctly attached to the demoted c4d.
primary = [c for c in cands if c.is_primary][0]
assert primary.vm_name == "encoding-worker-a"
def test_legacy_fallback_without_machine_type_inferred(self, encoding_service):
import json
fallbacks = json.dumps([
{"vm": "encoding-worker-fallback-n2c", "zone": "us-central1-c", "ip": "10.0.0.7"},
])
svc = self._service_with_fallbacks(encoding_service, fallbacks)
cands = svc._build_worker_candidates()
n2 = [c for c in cands if "n2c" in c.vm_name][0]
assert n2.machine_type is None # not fabricated on the object…
# …but inference placed it after the c4d primary.
assert [c.vm_name for c in cands] == ["encoding-worker-a", "encoding-worker-fallback-n2c"]
def test_no_worker_manager_returns_empty(self, encoding_service):
encoding_service._worker_manager = None
assert encoding_service._build_worker_candidates() == []
def test_non_list_fallback_json_degrades_to_primary_only(self, encoding_service):
# A JSON scalar (e.g. "null") parses fine but must not blow up iteration.
svc = self._service_with_fallbacks(encoding_service, "null")
cands = svc._build_worker_candidates()
assert [c.vm_name for c in cands] == ["encoding-worker-a"]
def test_dict_fallback_json_degrades_to_primary_only(self, encoding_service):
svc = self._service_with_fallbacks(encoding_service, '{"vm": "x"}')
cands = svc._build_worker_candidates()
assert [c.vm_name for c in cands] == ["encoding-worker-a"]
@@ -934,3 +934,141 @@ class TestWaitForWorkerReady:
)
assert call_count["n"] == 3
# ---------------------------------------------------------------------------
# capacity_state (availability awareness) + is_primary override routing
# ---------------------------------------------------------------------------
class TestCapacityStateFeedback:
"""ensure_any_running records/clears per-(type,zone) stockout state."""
def test_records_stockout_on_capacity_error(self, manager, mock_db, mock_compute):
mock_instance = MagicMock()
mock_instance.status = "TERMINATED"
mock_compute.get.return_value = mock_instance
# Primary c4d hits capacity; fallback n2 succeeds.
mock_compute.start.side_effect = [_capacity_op(), _ok_op()]
candidates = [
EncodingWorkerCandidate(vm_name="encoding-worker-a", zone="us-central1-c",
ip="10.0.0.1", machine_type="c4d-highcpu-32", is_primary=True),
EncodingWorkerCandidate(vm_name="encoding-worker-fallback-n2f", zone="us-central1-f",
ip="10.0.0.2", machine_type="n2-highcpu-32"),
]
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
mock_dt.now.return_value = datetime(2026, 5, 5, 9, 0, 0, tzinfo=UTC)
mock_dt.side_effect = lambda *a, **kw: datetime(*a, **kw)
manager.ensure_any_running(candidates)
doc_ref = mock_db.collection.return_value.document.return_value
# A merge-set recorded the c4d stockout under its type@zone key.
set_calls = [c for c in doc_ref.set.call_args_list
if "capacity_state" in (c.args[0] if c.args else {})]
recorded = {}
for c in set_calls:
recorded.update(c.args[0]["capacity_state"])
assert recorded.get("c4d-highcpu-32@us-central1-c") == "2026-05-05T09:00:00+00:00"
def test_clears_stockout_for_type_on_clean_start(self, manager, mock_db, mock_compute):
mock_instance = MagicMock()
mock_instance.status = "TERMINATED"
mock_compute.get.return_value = mock_instance
mock_compute.start.return_value = _ok_op()
candidates = [
EncodingWorkerCandidate(vm_name="encoding-worker-a", zone="us-central1-c",
ip="10.0.0.1", machine_type="c4d-highcpu-32", is_primary=True),
]
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
mock_dt.now.return_value = datetime(2026, 5, 5, 9, 0, 0, tzinfo=UTC)
mock_dt.side_effect = lambda *a, **kw: datetime(*a, **kw)
manager.ensure_any_running(candidates)
doc_ref = mock_db.collection.return_value.document.return_value
cleared = {}
for c in doc_ref.set.call_args_list:
payload = c.args[0] if c.args else {}
if "capacity_state" in payload:
cleared.update(payload["capacity_state"])
assert cleared.get("c4d-highcpu-32@us-central1-c") is None
def test_stockout_write_failure_does_not_break_start(self, manager, mock_db, mock_compute):
"""A Firestore error while recording a stockout must not abort failover."""
mock_instance = MagicMock()
mock_instance.status = "TERMINATED"
mock_compute.get.return_value = mock_instance
mock_compute.start.side_effect = [_capacity_op(), _ok_op()]
doc_ref = mock_db.collection.return_value.document.return_value
doc_ref.set.side_effect = RuntimeError("firestore down")
candidates = [
EncodingWorkerCandidate(vm_name="encoding-worker-a", zone="us-central1-c",
ip="10.0.0.1", machine_type="c4d-highcpu-32", is_primary=True),
EncodingWorkerCandidate(vm_name="encoding-worker-fallback-n2f", zone="us-central1-f",
ip="10.0.0.2", machine_type="n2-highcpu-32"),
]
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
mock_dt.now.return_value = datetime(2026, 5, 5, 9, 0, 0, tzinfo=UTC)
mock_dt.side_effect = lambda *a, **kw: datetime(*a, **kw)
result = manager.ensure_any_running(candidates)
assert result["vm_name"] == "encoding-worker-fallback-n2f"
assert result["fell_back"] is True
def test_is_primary_flag_routes_override_regardless_of_position(self, manager, mock_db, mock_compute):
"""A fallback ranked FIRST (is_primary=False) must still set active_override.
When the preference logic demotes a stocked-out primary, the fallback can be
candidate index 0 — the override must key off is_primary, not position.
"""
mock_instance = MagicMock()
mock_instance.status = "TERMINATED"
mock_compute.get.return_value = mock_instance
mock_compute.start.return_value = _ok_op()
# Fallback is first (primary demoted), primary flagged but ranked second.
candidates = [
EncodingWorkerCandidate(vm_name="encoding-worker-fallback-c2df", zone="us-central1-f",
ip="10.0.0.9", machine_type="c2d-highcpu-32", is_primary=False),
EncodingWorkerCandidate(vm_name="encoding-worker-a", zone="us-central1-c",
ip="10.0.0.1", machine_type="c4d-highcpu-32", is_primary=True),
]
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
mock_dt.now.return_value = datetime(2026, 5, 5, 9, 0, 0, tzinfo=UTC)
mock_dt.side_effect = lambda *a, **kw: datetime(*a, **kw)
result = manager.ensure_any_running(candidates)
assert result["vm_name"] == "encoding-worker-fallback-c2df"
assert result["fell_back"] is True
doc_ref = mock_db.collection.return_value.document.return_value
override_calls = [c for c in doc_ref.update.call_args_list
if "active_override_vm" in c.args[0]]
assert override_calls, "Fallback at index 0 must still set the override"
assert override_calls[0].args[0]["active_override_vm"] == "encoding-worker-fallback-c2df"
def test_legacy_candidates_without_flag_use_position(self, manager, mock_db, mock_compute):
"""No is_primary flag anywhere → first candidate is treated as primary (legacy)."""
mock_instance = MagicMock()
mock_instance.status = "TERMINATED"
mock_compute.get.return_value = mock_instance
mock_compute.start.return_value = _ok_op()
candidates = [
EncodingWorkerCandidate(vm_name="encoding-worker-blue", zone="us-central1-c", ip="10.0.0.1"),
EncodingWorkerCandidate(vm_name="encoding-worker-fb-a", zone="us-central1-a", ip="10.0.0.2"),
]
with patch("backend.services.encoding_worker_manager.datetime") as mock_dt:
mock_dt.now.return_value = datetime(2026, 5, 5, 9, 0, 0, tzinfo=UTC)
mock_dt.side_effect = lambda *a, **kw: datetime(*a, **kw)
result = manager.ensure_any_running(candidates)
assert result["fell_back"] is False
assert result["vm_name"] == "encoding-worker-blue"
@@ -0,0 +1,172 @@
"""Unit tests for the shared encoding-worker candidate preference logic.
This pure module drives BOTH runtime selection and deploy green selection, so its
ordering guarantees (fastest-first, cooldown demotion, machine_type inference) are
the contract both call-sites rely on.
"""
from datetime import datetime, timedelta, timezone
from backend.services.encoding_worker_preference import (
COOLDOWN_SECONDS,
SPEED_RANK,
UNKNOWN_RANK,
cooldown_key,
infer_machine_type,
ordered_candidates,
)
NOW = datetime(2026, 8, 15, 19, 0, 0, tzinfo=timezone.utc)
def _c(vm, zone, machine_type=None, **extra):
d = {"vm": vm, "zone": zone, "ip": f"10.0.0.{hash(vm) % 250 + 1}"}
if machine_type is not None:
d["machine_type"] = machine_type
d.update(extra)
return d
# ---------------------------------------------------------------------------
# machine_type inference
# ---------------------------------------------------------------------------
def test_explicit_machine_type_wins():
assert infer_machine_type(_c("whatever", "z", "c2d-highcpu-32")) == "c2d-highcpu-32"
def test_infer_from_vm_name_specific_before_generic():
# "n2d"/"c4d" must not be shadowed by "n2"/"c4".
assert infer_machine_type(_c("encoding-worker-fallback-n2da", "z")) == "n2d-highcpu-32"
assert infer_machine_type(_c("encoding-worker-fallback-n2f", "z")) == "n2-highcpu-32"
assert infer_machine_type(_c("encoding-worker-fallback-c4x", "z")) == "c4-highcpu-32"
def test_infer_unknown_returns_none():
# Bare a/b c4d fallbacks (no family token) can't be inferred from the name.
assert infer_machine_type(_c("encoding-worker-fallback-a", "z")) is None
def test_runtime_dict_shape_uses_vm_name_key():
assert infer_machine_type({"vm_name": "x-n2d-y", "zone": "z"}) == "n2d-highcpu-32"
# ---------------------------------------------------------------------------
# fastest-first ordering
# ---------------------------------------------------------------------------
def test_orders_fastest_first():
pool = [
_c("n2", "us-central1-c", "n2-highcpu-32"),
_c("c4d", "us-central1-c", "c4d-highcpu-32"),
_c("c2d", "us-central1-f", "c2d-highcpu-32"),
_c("c4", "us-central1-a", "c4-highcpu-32"),
]
got = [c["vm"] for c in ordered_candidates(pool, now=NOW)]
assert got == ["c4d", "c4", "c2d", "n2"]
def test_unknown_type_sorts_last_but_kept():
pool = [
_c("mystery", "z"), # no machine_type, unknown name
_c("c4d", "z", "c4d-highcpu-32"),
]
got = [c["vm"] for c in ordered_candidates(pool, now=NOW)]
assert got == ["c4d", "mystery"]
assert SPEED_RANK["c4d-highcpu-32"] < UNKNOWN_RANK
def test_stable_within_equal_rank_preserves_zone_spread():
# Two n2 in different zones keep input order (caller's secondary preference).
pool = [
_c("n2f", "us-central1-f", "n2-highcpu-32"),
_c("n2c", "us-central1-c", "n2-highcpu-32"),
]
got = [c["vm"] for c in ordered_candidates(pool, now=NOW)]
assert got == ["n2f", "n2c"]
# ---------------------------------------------------------------------------
# cooldown / availability awareness
# ---------------------------------------------------------------------------
def test_recent_stockout_demotes_type_to_back():
pool = [
_c("c4d", "us-central1-c", "c4d-highcpu-32"),
_c("c4", "us-central1-a", "c4-highcpu-32"),
_c("n2", "us-central1-c", "n2-highcpu-32"),
]
# c4d stocked out 1 minute ago → demoted behind the still-healthy types.
capacity_state = {"c4d-highcpu-32@us-central1-c": (NOW - timedelta(minutes=1)).isoformat()}
got = [c["vm"] for c in ordered_candidates(pool, capacity_state, now=NOW)]
assert got == ["c4", "n2", "c4d"]
def test_cooldown_expires_and_snaps_back_to_fastest():
pool = [
_c("c4d", "us-central1-c", "c4d-highcpu-32"),
_c("c4", "us-central1-a", "c4-highcpu-32"),
]
# Stockout older than COOLDOWN → c4d is hot again and returns to the top.
old = (NOW - timedelta(seconds=COOLDOWN_SECONDS + 60)).isoformat()
capacity_state = {"c4d-highcpu-32@us-central1-c": old}
got = [c["vm"] for c in ordered_candidates(pool, capacity_state, now=NOW)]
assert got == ["c4d", "c4"]
def test_two_types_stocked_out_still_serves_from_deep_pool():
# Both newest-gen types (c4d, c4) exhausted; deep pools keep serving in order.
pool = [
_c("c4d", "us-central1-c", "c4d-highcpu-32"),
_c("c4", "us-central1-a", "c4-highcpu-32"),
_c("c2d", "us-central1-f", "c2d-highcpu-32"),
_c("n2d", "us-central1-a", "n2d-highcpu-32"),
]
recent = (NOW - timedelta(minutes=2)).isoformat()
capacity_state = {
"c4d-highcpu-32@us-central1-c": recent,
"c4-highcpu-32@us-central1-a": recent,
}
got = [c["vm"] for c in ordered_candidates(pool, capacity_state, now=NOW)]
# Hot deep pools first (fastest-first among them), then the two cold types.
assert got == ["c2d", "n2d", "c4d", "c4"]
def test_type_only_capacity_key_demotes_all_zones():
pool = [
_c("c4d-c", "us-central1-c", "c4d-highcpu-32"),
_c("n2", "us-central1-c", "n2-highcpu-32"),
]
capacity_state = {"c4d-highcpu-32": (NOW - timedelta(minutes=1)).isoformat()}
got = [c["vm"] for c in ordered_candidates(pool, capacity_state, now=NOW)]
assert got == ["n2", "c4d-c"]
def test_empty_capacity_state_is_pure_speed_order():
pool = [_c("n2", "z", "n2-highcpu-32"), _c("c4d", "z", "c4d-highcpu-32")]
assert [c["vm"] for c in ordered_candidates(pool, {}, now=NOW)] == ["c4d", "n2"]
assert [c["vm"] for c in ordered_candidates(pool, None, now=NOW)] == ["c4d", "n2"]
def test_naive_timestamp_tolerated():
pool = [_c("c4d", "us-central1-c", "c4d-highcpu-32"), _c("n2", "z", "n2-highcpu-32")]
naive = (NOW - timedelta(minutes=1)).replace(tzinfo=None).isoformat()
capacity_state = {"c4d-highcpu-32@us-central1-c": naive}
got = [c["vm"] for c in ordered_candidates(pool, capacity_state, now=NOW)]
assert got == ["n2", "c4d"]
def test_malformed_timestamp_ignored():
pool = [_c("c4d", "us-central1-c", "c4d-highcpu-32"), _c("n2", "z", "n2-highcpu-32")]
capacity_state = {"c4d-highcpu-32@us-central1-c": "not-a-date"}
got = [c["vm"] for c in ordered_candidates(pool, capacity_state, now=NOW)]
assert got == ["c4d", "n2"] # unparseable → not in cooldown
def test_empty_pool():
assert ordered_candidates([], now=NOW) == []
def test_cooldown_key_shape():
assert cooldown_key(_c("x", "us-central1-c", "c4d-highcpu-32")) == "c4d-highcpu-32@us-central1-c"
assert cooldown_key(_c("x", None, "n2-highcpu-32")) == "n2-highcpu-32"
assert cooldown_key(_c("no-token", "z")) is None
@@ -0,0 +1,215 @@
"""
Tests for the encoding worker's two-lane execution model (gce_encoding/main.py).
The worker serializes heavy jobs (renders/encodes) into a single lane so it can
never OOM from running multiple 4K ffmpeg encodes at once (incident 2026-08-15:
3 concurrent encodes OOM-killed the 32 GB fallback worker). Light jobs (previews,
wheel installs) run on their own lane. `/status` also exposes a queue position so
the client can wait through a deep queue.
Importing main.py constructs a storage.Client() at module load, so we patch it.
"""
import os
import sys
from unittest.mock import MagicMock, patch
import pytest
@pytest.fixture(scope="module")
def worker():
"""Import the GCE worker module with GCS creds mocked out.
Clear ENCODING_HEAVY_CONCURRENCY during import so the default-behavior
assertions hold regardless of the CI environment.
"""
with patch.dict(os.environ, {}, clear=False):
os.environ.pop("ENCODING_HEAVY_CONCURRENCY", None)
with patch("google.cloud.storage.Client", return_value=MagicMock()):
sys.modules.pop("backend.services.gce_encoding.main", None)
import backend.services.gce_encoding.main as m
yield m
sys.modules.pop("backend.services.gce_encoding.main", None)
class TestHeavyLaneSerialization:
def test_heavy_concurrency_defaults_to_one(self, worker):
# One heavy ffmpeg at a time → OOM-proof on any machine type.
assert worker.HEAVY_CONCURRENCY == 1
assert worker.heavy_executor._max_workers == 1
def test_heavy_and_light_are_separate_lanes(self, worker):
# Previews / wheel installs must not queue behind a multi-minute encode.
assert worker.heavy_executor is not worker.light_executor
assert worker.light_executor._max_workers >= 2
class TestHeavyConcurrencyParsing:
@pytest.mark.parametrize("val,expected", [
("1", 1), ("2", 2), ("4", 4), # valid
("0", 1), ("-3", 1), # too low → clamp up to 1
("9", 4), # too high → clamp down to 4
("abc", 1), ("", 1), # malformed → default 1
])
def test_clamped_to_sane_range(self, worker, val, expected):
with patch.dict("os.environ", {"ENCODING_HEAVY_CONCURRENCY": val}):
assert worker._heavy_concurrency() == expected
def test_missing_env_defaults_to_one(self, worker):
import os
with patch.dict(os.environ, {}, clear=False):
os.environ.pop("ENCODING_HEAVY_CONCURRENCY", None)
assert worker._heavy_concurrency() == 1
class TestHeavyQueuePosition:
def _reset_jobs(self, worker, entries):
worker.jobs.clear()
for job_id, kind, status in entries:
worker.jobs[job_id] = {
"job_id": job_id,
"status": status,
"progress": 0,
"kind": kind,
}
def test_orders_heavy_jobs_ignoring_previews_and_terminal(self, worker):
# Insertion order == submission order (dict is ordered).
self._reset_jobs(worker, [
("e0done", "encode", "complete"), # terminal — not counted, position None
("e1", "encode", "running"), # front of the lane
("e2", "render", "pending"), # one heavy job (e1) ahead
("p1", "preview", "running"), # light lane — never counted
("e3", "encode", "pending"), # e1 + e2 ahead (preview + terminal excluded)
])
assert worker._heavy_queue_position("e0done") is None
assert worker._heavy_queue_position("e1") == 0
assert worker._heavy_queue_position("e2") == 1
assert worker._heavy_queue_position("p1") is None
assert worker._heavy_queue_position("e3") == 2
def test_preview_has_no_queue_position(self, worker):
self._reset_jobs(worker, [("p1", "preview", "running")])
assert worker._heavy_queue_position("p1") is None
def test_unknown_job_is_none(self, worker):
worker.jobs.clear()
assert worker._heavy_queue_position("nope") is None
class TestJobStatusModel:
def test_new_fields_present_and_optional(self, worker):
# Old-shaped payloads still validate (fields default to None)...
s = worker.JobStatus(job_id="j", status="running", progress=10)
assert s.restart_failure_code is None
assert s.queue_position is None
# ...and the new fields round-trip.
s2 = worker.JobStatus(
job_id="j", status="failed", progress=0,
restart_failure_code="encoding_worker_restart", queue_position=3,
)
assert s2.restart_failure_code == "encoding_worker_restart"
assert s2.queue_position == 3
def test_extra_keys_like_kind_are_ignored(self, worker):
# get_job_status spreads the whole job dict (which now carries "kind").
s = worker.JobStatus(
**{"job_id": "j", "status": "pending", "progress": 0, "kind": "encode"},
queue_position=worker._heavy_queue_position("missing"),
)
assert s.status == "pending"
_LATEST_WHEEL_URI = (
"gs://karaoke-gen-storage-nomadkaraoke/wheels/karaoke_gen-0.194.0-py3-none-any.whl"
)
def _fake_subprocess(counter):
"""subprocess.run stub that dispatches by command and counts cp/pip calls."""
from types import SimpleNamespace
def _run(cmd, **kwargs):
head = cmd[:2]
if head == ["gsutil", "ls"]:
return SimpleNamespace(returncode=0, stdout=_LATEST_WHEEL_URI + "\n", stderr="")
if head == ["gsutil", "cp"]:
counter["cp"] += 1
return SimpleNamespace(returncode=0, stdout="", stderr="")
if "pip" in cmd:
counter["pip"] += 1
return SimpleNamespace(returncode=0, stdout="", stderr="")
return SimpleNamespace(returncode=0, stdout="", stderr="")
return _run
class TestEnsureLatestWheelConcurrency:
"""ensure_latest_wheel must be idempotent + race-free: it runs on the light
lane (>1 thread) at the start of every job, so concurrent calls used to
clobber the shared /tmp wheel path and venv (incident 2026-08-15, 374dec26)."""
def test_fast_path_when_already_verified_this_process(self, worker):
worker._verified_wheel_version = "0.194.0"
counter = {"cp": 0, "pip": 0}
with patch.object(worker.subprocess, "run", _fake_subprocess(counter)), \
patch.object(worker, "verify_wheel_imports", return_value=True) as vwi:
assert worker.ensure_latest_wheel() is True
assert counter == {"cp": 0, "pip": 0} # no download, no install
vwi.assert_not_called() # no reverify either
def test_installed_version_verifies_without_reinstall(self, worker):
worker._verified_wheel_version = None
counter = {"cp": 0, "pip": 0}
with patch.object(worker.subprocess, "run", _fake_subprocess(counter)), \
patch.object(worker, "_installed_karaoke_gen_version", return_value="0.194.0"), \
patch.object(worker, "verify_wheel_imports", return_value=True):
assert worker.ensure_latest_wheel() is True
# Right version already present → verify only, no cp/pip.
assert counter == {"cp": 0, "pip": 0}
assert worker._verified_wheel_version == "0.194.0"
def test_installs_when_version_differs(self, worker):
worker._verified_wheel_version = None
counter = {"cp": 0, "pip": 0}
with patch.object(worker.subprocess, "run", _fake_subprocess(counter)), \
patch.object(worker, "_installed_karaoke_gen_version", return_value="0.193.0"), \
patch.object(worker, "verify_wheel_imports", return_value=True):
assert worker.ensure_latest_wheel() is True
assert counter["cp"] == 1 and counter["pip"] >= 1
assert worker._verified_wheel_version == "0.194.0"
def test_concurrent_calls_install_at_most_once(self, worker):
"""The lock + version cache guarantee only ONE thread installs even when
several race in on a fresh boot; the rest hit the verified fast path."""
import threading
import time
worker._verified_wheel_version = None
counter = {"cp": 0, "pip": 0}
base = _fake_subprocess(counter)
def slow_run(cmd, **kwargs):
if cmd[:2] == ["gsutil", "cp"]:
time.sleep(0.2) # widen the race window
return base(cmd, **kwargs)
results = []
barrier = threading.Barrier(3)
def call():
barrier.wait()
results.append(worker.ensure_latest_wheel())
with patch.object(worker.subprocess, "run", slow_run), \
patch.object(worker, "_installed_karaoke_gen_version", return_value="0.193.0"), \
patch.object(worker, "verify_wheel_imports", return_value=True):
threads = [threading.Thread(target=call) for _ in range(3)]
for t in threads:
t.start()
for t in threads:
t.join()
assert results == [True, True, True]
assert counter["cp"] == 1 # exactly one download despite 3 concurrent callers
assert counter["pip"] == 1 # and exactly one install (no concurrent venv writes)
+13
View File
@@ -571,6 +571,19 @@ class TestEnsureLatestWheelVerification:
True when it imports; retry a failed/partial install; callers fail fast.
"""
@pytest.fixture(autouse=True)
def _reset_wheel_cache(self, monkeypatch):
"""ensure_latest_wheel caches the verified version in a module global and
can fast-path when the installed version already matches. Reset the cache
and pin the "installed" version to None around each test so these
download/install-flow tests run deterministically regardless of the test
venv's real karaoke-gen version."""
from backend.services.gce_encoding import main
main._verified_wheel_version = None
monkeypatch.setattr(main, "_installed_karaoke_gen_version", lambda: None)
yield
main._verified_wheel_version = None
# A couple of versioned wheels plus the (filtered-out) current wheel, as
# `gsutil ls` would emit them.
DEFAULT_LS = (
+13 -3
View File
@@ -44,7 +44,7 @@ from backend.config import get_settings
from backend.workers.registry import worker_registry
from backend.workers.worker_logging import create_job_logger, setup_job_logging, job_logging_context
from backend.services.tracing import job_span, add_span_event, add_span_attribute
from backend.services.encoding_service import get_encoding_service
from backend.services.encoding_service import get_encoding_service, run_with_lost_job_resubmit
from backend.services.encoding_errors import (
EncodingWorkerCapacityError,
EncodingWorkerStartError,
@@ -225,8 +225,18 @@ async def process_render_video(job_id: str) -> bool:
with job_span("gce-render-video", job_id) as render_span:
render_start = time.time()
result = await encoding_service.render_video_on_gce(
job_id, render_config, progress_callback=progress_callback
# Resubmit under a fresh worker job id if the encoding
# worker loses the render mid-run (OOM/deploy restart wipes
# its in-memory registry). The output GCS prefix is fixed in
# render_config, so a new worker id doesn't move outputs.
async def _submit_render(render_job_id: str):
return await encoding_service.render_video_on_gce(
render_job_id, render_config, progress_callback=progress_callback
)
result = await run_with_lost_job_resubmit(
_submit_render, job_id, log=job_log
)
render_duration = time.time() - render_start
render_span.set_attribute("duration_seconds", render_duration)
+17 -7
View File
@@ -38,7 +38,7 @@ from backend.services.storage_service import StorageService
from backend.services.job_health_service import validate_worker_can_run
from backend.services.rclone_service import get_rclone_service
from backend.services.youtube_service import get_youtube_service
from backend.services.encoding_service import get_encoding_service
from backend.services.encoding_service import get_encoding_service, run_with_lost_job_resubmit
from backend.config import get_settings
from backend.workers.style_helper import load_style_config
from backend.workers.worker_logging import create_job_logger, setup_job_logging, job_logging_context
@@ -150,12 +150,19 @@ async def _encode_via_gce(
encode_start = time.time()
add_span_event("gce_encoding_started")
result = await encoding_service.encode_videos(
job_id=job_id,
input_gcs_path=input_gcs_path,
output_gcs_path=output_gcs_path,
encoding_config=encoding_config,
progress_callback=progress_callback,
# Resubmit under a fresh id if the worker loses the job mid-run
# (OOM/deploy restart wipes its in-memory registry).
async def _submit_encode(encode_job_id: str):
return await encoding_service.encode_videos(
job_id=encode_job_id,
input_gcs_path=input_gcs_path,
output_gcs_path=output_gcs_path,
encoding_config=encoding_config,
progress_callback=progress_callback,
)
result = await run_with_lost_job_resubmit(
_submit_encode, job_id, log=job_log
)
encode_duration = time.time() - encode_start
@@ -362,6 +369,7 @@ async def generate_video_orchestrated(job_id: str) -> bool:
'final_karaoke_txt_zip': result.final_karaoke_txt_zip,
'title_mov': result.title_mov,
'end_mov': result.end_mov,
'portrait_video': result.portrait_video,
})
# Store result metadata in job BEFORE transitioning to COMPLETE
@@ -1635,6 +1643,8 @@ async def _upload_results(
# manifest and are verifiable (regression: missing from Dropbox folders)
('title_mov', 'finals', 'title_mov'),
('end_mov', 'finals', 'end_mov'),
# Portrait (9:16) karaoke — recorded in the admin files manifest.
('portrait_video', 'finals', 'portrait_1080x1920'),
]
for result_key, category, file_key in file_mappings:
+25 -5
View File
@@ -126,6 +126,10 @@ class OrchestratorResult:
title_mov: Optional[str] = None
end_mov: Optional[str] = None
# Portrait (9:16) karaoke video. Downloaded so it lands in the Dropbox folder;
# intentionally excluded from YouTube/Drive uploads. Best-effort — may be None.
portrait_video: Optional[str] = None
# Organization
brand_code: Optional[str] = None
@@ -487,11 +491,23 @@ class VideoWorkerOrchestrator:
except Exception as e:
self.job_log.warning(f"Failed to stage custom instrumental for GCE encoder: {e}")
# Submit the encode under `encode_job_id`, resubmitting under a fresh id
# if the worker loses the job mid-run (OOM/deploy restart wipes its
# in-memory registry — the original id can never complete). See
# run_with_lost_job_resubmit.
from backend.services.encoding_service import run_with_lost_job_resubmit
async def _submit_encode(encode_job_id: str):
encoding_input.options["job_id"] = encode_job_id
return await encoding_backend.encode(encoding_input)
# Run encoding
with job_span("encoding", self.config.job_id) as span:
add_span_event("encoding_started", {"backend": encoding_backend.name})
output = await encoding_backend.encode(encoding_input)
output = await run_with_lost_job_resubmit(
_submit_encode, self.config.job_id, log=self.job_log
)
add_span_event("encoding_completed", {
"success": output.success,
@@ -525,10 +541,11 @@ class VideoWorkerOrchestrator:
f"Stale GCE cache detected, re-encoding as {retry_job_id}: {e}"
)
# Update the encoding input with the retry job ID
encoding_input.options["job_id"] = retry_job_id
output = await encoding_backend.encode(encoding_input)
# Re-encode under the fresh id, still resubmitting if the worker
# loses the job mid-run.
output = await run_with_lost_job_resubmit(
_submit_encode, retry_job_id, log=self.job_log
)
if not output.success:
raise Exception(f"Encoding failed on retry: {output.error_message}")
@@ -570,6 +587,9 @@ class VideoWorkerOrchestrator:
# Standalone screen videos — pulled back so they reach the Dropbox folder
('title_mov_path', 'title_mov'),
('end_mov_path', 'end_mov'),
# Portrait karaoke — pulled back so it reaches the Dropbox folder (upload_folder
# sweeps the whole output dir); excluded from YouTube/Drive by design.
('portrait_mp4_path', 'portrait_video'),
]
downloaded_count = 0
+43 -1
View File
@@ -956,6 +956,46 @@ post-download and may trigger an `AWAITING_DURATION_CONFIRM` pause if the actual
server-computed credit total and returns 409 on mismatch. If omitted, the server deducts the
computed cost without client confirmation.
#### Recover a Parked Job (re-search / provide own audio)
When a search returns nothing usable (0 results, a transient failure, or the auto-picked
source is unusable) the job stays in `AWAITING_AUDIO_SELECTION` with no selectable sources.
These endpoints let the user out of that dead-end without creating a new job or re-charging
base credits (the job was already charged at creation; final duration billing is reconciled
post-download). All require the job to be in `AWAITING_AUDIO_SELECTION` (else `400`).
```http
POST /api/audio-search/{job_id}/research
Content-Type: application/json
{ "artist": "Arctic Monkeys", "title": "The View From the Afternoon" } // both optional
```
Re-runs the audio search. Blank/omitted fields re-use the job's existing search terms (a plain
retry); provided values are applied to the job's search terms **and** display artist/title, then
searched. Returns the same shape as `/search` (`results`, `results_count`). An empty result set is
a normal `200` (not an error) so the client can offer the manual fallback below. `502` on a hard
search-service error.
```http
POST /api/audio-search/{job_id}/provide-url
Content-Type: application/json
{ "url": "https://youtube.com/watch?v=..." }
```
Attaches a YouTube/yt-dlp URL to the parked job, downloads it, and starts processing
(`AWAITING_AUDIO_SELECTION → DOWNLOADING_AUDIO → DOWNLOADING`). Rejects DRM/streaming links and
unavailable videos with `400`; `502` if the download fails (the job is returned to the queue).
```http
POST /api/audio-search/{job_id}/attach-upload-url // → { upload_url, gcs_path }
POST /api/audio-search/{job_id}/attach-upload-complete // after PUTting the file
```
Two-step manual file upload for a parked job: request a signed GCS upload URL, `PUT` the audio
file to it, then call `attach-upload-complete` to point the job at the file and start processing.
#### Standalone Search (Guided Flow — Step 2)
```http
@@ -2302,7 +2342,9 @@ routes require auth.
### Progress
- `GET /api/bulk/{batch_id}` → `{batch_id,total,counts:{searching,awaiting_selection,processing,complete,failed},jobs:[{job_id,artist,title,status,auto_selected}]}`. Ownership-scoped (admins see any); `404` for another user's batch. Parked jobs are completed via the existing `/api/audio-search/{job_id}/select` flow.
- `GET /api/bulk/{batch_id}` → `{batch_id,total,counts:{searching,awaiting_selection,processing,complete,failed},jobs:[{job_id,artist,title,status,auto_selected}]}`. Ownership-scoped (admins see any); `404` for another user's batch. Parked jobs are completed via the existing `/api/audio-search/{job_id}/select` flow, or recovered
via `/research` (re-search / edit terms) and `/provide-url` · `/attach-upload-*` (own audio) when a
search returned nothing usable.
## Webhooks
+87 -20
View File
@@ -38,10 +38,13 @@
│ (jobs) │ │ (files) │ │ (API keys) │ │ Worker (*) │
└──────────┘ └──────────┘ └──────────────┘ └──────────────┘
(*) GCE Encoding Worker: c4d-highcpu-32 VM with AMD EPYC 9B45 (Turin) for
high-performance FFmpeg encoding (4.92x faster than previous c4-standard-8).
(*) GCE Encoding Worker: a ranked pool of 6 x86_64 32-vCPU highcpu machine
families (c4d/c4/n4d/c2d/n2d/n2). c4d-highcpu-32 (AMD EPYC Turin) is the
fastest and stays the primary/preferred pick; the other families are
stockout-resilience fallbacks selected fastest-first with a capacity cooldown.
Used for both final video encoding and preview video generation.
Uses immutable deployment pattern - see infrastructure/encoding-worker/README.md.
Uses immutable deployment pattern - see infrastructure/encoding-worker/README.md
and the "Encoding Worker" section below.
```
### Error Monitor
@@ -292,33 +295,82 @@ karaoke-gen shares a GCP project (`nomadkaraoke`) with karaoke-decide, but uses
**Worker Logs**: Stored in subcollection (`jobs/{job_id}/logs`) instead of embedded array to avoid Firestore's 1MB document size limit. TTL policy auto-deletes logs after 30 days. Feature flag: `USE_LOG_SUBCOLLECTION` (default: true). See [LESSONS-LEARNED.md](LESSONS-LEARNED.md#firestore-document-1mb-limit-with-embedded-arrays).
## Encoding Worker Blue-Green Deployment
## Encoding Worker: blue-green primary pair + multi-family fallback pool
The GCE encoding worker uses a blue-green deployment pattern with two named VMs (`encoding-worker-a` and `encoding-worker-b`).
The GCE encoding worker is a **blue-green primary pair** (`encoding-worker-a`/`-b`,
both c4d-highcpu-32 in us-central1-c) plus a **ranked pool of stockout-resilience
fallback VMs** spanning 6 x86_64 machine families (see "Multi-instance-type pool"
below). **10 VMs total**, all TERMINATED by default and started on demand.
### Architecture
```text
Frontend → Backend (Cloud Run) → Firestore config → Primary VM (encoding-worker-a or b)
↑
Frontend → Backend (Cloud Run) → Firestore config → active worker (primary, or a
↑ capacity-fallback "override")
Cloud Scheduler (5 min) → Cloud Function → checks idle + stops VMs
↑
CI (GitHub Actions) → deploys to secondary → health check → swap Firestore → stop old
CI (GitHub Actions) → selects a fresh "green" (ranked pool) → health + encode test
→ promote (swap primary OR set active_override) → stop old
```
### Multi-instance-type pool (stockout resilience, v0.195.0)
A single machine family can hit a region-wide `ZONE_RESOURCE_POOL_EXHAUSTED`
stockout across every zone at once. To survive that, the fallback fleet spans
**6 families** (c4d, c4, n4d, c2d, n2d, n2 — all `-highcpu-32`, ≥32 GB) across
zones a/b/c/f: `encoding-worker-fallback-a`/`-b` (c4d), `-n2c`/`-n2f` (n2),
`-c4a` (c4), `-n4db` (n4d), `-c2df` (c2d), `-n2da` (n2d).
**Candidate ordering is one shared pure module**,
`backend/services/encoding_worker_preference.py::ordered_candidates(pool, capacity_state)`,
used by BOTH runtime selection and deploy green selection so they can't drift:
- **Fastest-first** by `SPEED_RANK` (c4d preferred whenever it can start).
- **Availability-aware**: a family that recently hit a capacity/stockout error is
recorded in the Firestore `capacity_state` map and **demoted for a 15-min
cooldown**, then re-probed — so we stop wasting ~2 min probing a dead family but
snap back to c4d the moment capacity returns.
The fallback fleet is defined in `infrastructure/config.py::EncodingWorkerConfig.FALLBACKS`
and published to the backend/idle-fn via the `encoding-worker-fallback-vms` secret
(entries: `{vm, zone, ip, machine_type}`).
### Key Components
**Two VMs (a/b)**: Both VMs are TERMINATED by default. One is designated "primary" and serves all encoding traffic. The secondary VM exists solely to receive new deployments before they go live.
**Primary pair + fallback fleet**: All VMs TERMINATED by default. The primary pair
(a/b) does blue-green deploys; the 8 fallbacks absorb capacity stockouts. Runtime
warmup (`encoding_worker_manager.ensure_any_running`) tries the ranked candidates
in order, falling through on stockout and recording an `active_override` when it
lands on a fallback.
**Firestore config doc** (`config/encoding-worker`): Single source of truth for routing. Fields: `primary` (a or b), `ip_a`, `ip_b`, `deploy_in_progress` flag, `activity_a`/`activity_b` timestamps.
**Firestore config doc** (`config/encoding-worker`): source of truth for routing.
Fields: `primary_vm`/`primary_ip`/`primary_version`, `secondary_vm`/…, the
capacity-fallback pointer `active_override_vm`/`_ip`/`_zone`/`_version` (set when a
fallback is serving), `deploy_in_progress`, `last_activity_at`, and the
`capacity_state` map (`{"<machine_type>@<zone>": last_stockout_iso}`). `active_url`
= override IP if set, else primary IP.
**Backend routing** (`encoding_interface.py`): Reads the primary IP from the Firestore config doc with a 30-second TTL cache. All encoding requests route to the current primary.
**Backend routing** (`encoding_interface.py`): reads the active worker IP from the
config doc with a 30-second TTL cache.
**JIT startup**: When a user enters the lyrics review page, the backend starts the primary VM on demand. This gives ~60 seconds of natural warmup time before encoding is needed, avoiding both 24/7 costs and noticeable cold-start latency for the user.
**JIT startup**: entering the lyrics-review page starts the worker on demand
(~60 s natural warmup), avoiding 24/7 cost and cold-start latency.
**Idle auto-shutdown**: A Cloud Function (triggered every 5 minutes by Cloud Scheduler) checks the `activity_*` timestamps in Firestore and stops any VM that has been idle for more than 15 minutes. This is external to the VM — if the encoding worker code itself has a bug, the Cloud Function still shuts it down.
**Idle auto-shutdown**: a Cloud Function (every 5 min) stops idle VMs (primary,
secondary, and every fallback in the secret) based on Firestore activity — external
to the VM so a sick worker still gets stopped.
**Blue-green deploys**: CI builds a new wheel, deploys it to the secondary VM (not the live primary), runs a real encode test against the secondary, then atomically swaps the `primary` field in Firestore to point to the secondary. The old primary is stopped after the swap. If the health check fails, the primary is never updated.
**Capacity-aware deploys**: CI selects a FRESH "green" from the ranked pool via
`deploy_promote.select_green_candidates` (the same preference module) — the c4d
secondary if it can start, else a fallback family, never the currently-serving
override. After a real encode test on the green, it promotes: a c4d-secondary green
does the classic primary swap (and clears any stale override); a fallback green
becomes the `active_override`. The retired VM is drained + stopped; a failed health
check never promotes. Override routing keys off an explicit `is_primary` flag, not
list position. See `infrastructure/encoding-worker/deploy_promote.py`.
**Self-sufficient image**: the Packer image (`infrastructure/packer/scripts/provision.sh`)
bakes the full karaoke-gen dependency tree with **CPU-only torch**, so a fresh VM of
any family boots ready to encode (no first-job dependency install).
### Seeding the Config
@@ -327,17 +379,32 @@ Initial setup or reset:
python scripts/seed-encoding-worker-config.py <ip-a> <ip-b>
```
### Deploy Flow
### Deploy Flow (capacity-aware, v0.194.2+)
```text
1. CI builds new karaoke-gen wheel + pushes to GCS
2. CI starts secondary VM, waits for /health to respond
3. CI runs real encode test against secondary VM
4. If test passes: CI writes secondary name to Firestore `primary` field
5. CI stops the old primary VM
6. If test fails: CI stops secondary VM, primary unchanged
2. CI picks a FRESH "green" from the ranked pool (select_green_candidates →
ordered_candidates): the c4d secondary if it can start, else the fastest
available fallback family — never the currently-serving active_override.
3. CI starts the green, waits for /health, runs a real encode test against it.
4. If the test FAILS: CI stops the green; primary/override unchanged (no promote).
5. If the test PASSES: CI promotes the green:
- green is the c4d secondary → swap it to `primary_vm` (classic blue-green)
AND clear any stale `active_override_*` so
traffic returns to the fresh c4d primary.
- green is a fallback family → set it as `active_override_*` (the serving
worker); leave primary/secondary so c4d
resumes as primary when its capacity returns.
6. CI drains (waits active_jobs==0, bounded) + stops the retired VM — never the
promoted green.
7. Last resort (no separate green can start, e.g. deep stockout): in-place restart
of the current serving override — a brief blip, covered by client auto-resubmit.
```
Override routing keys off an explicit `is_primary` flag (not list position), so a
fallback ranked ahead of a stocked-out primary is still routed correctly. Pure
decision logic + unit tests: `infrastructure/encoding-worker/deploy_promote.py`.
## Video Worker Orchestrator
The Video Worker uses an orchestrator pattern to ensure all features work regardless of encoding backend (local Cloud Run or GCE VM).
+1 -1
View File
@@ -209,7 +209,7 @@ TESTMAIL_NAMESPACE=... # testmail.app namespace
## Encoding Worker Operations
The encoding worker uses a blue-green deployment with two GCE VMs (`encoding-worker-a`, `encoding-worker-b`). See [ARCHITECTURE.md](ARCHITECTURE.md#encoding-worker-blue-green-deployment) for the full design.
The encoding worker is a blue-green primary pair (`encoding-worker-a`/`-b`, c4d) plus a ranked pool of 8 stopped fallback VMs spanning 6 machine families (c4d/c4/n4d/c2d/n2d/n2) for stockout resilience — 10 VMs total. Candidate ordering (runtime + deploy) is the shared `backend/services/encoding_worker_preference.py`. See [ARCHITECTURE.md](ARCHITECTURE.md#encoding-worker-blue-green-primary-pair--multi-family-fallback-pool) for the full design.
### Seed Firestore config (initial setup or reset)
+18 -11
View File
@@ -79,19 +79,26 @@ The `concurrency=1` setting may have been added deliberately for performance rea
### 🔍 GCE Encoding Worker
**Current State:**
- c4d-highcpu-32 VM running 24/7
- Cost: ~$700/month
**Current State (updated v0.195.0 — the opportunities below are largely SHIPPED):**
- No longer a single 24/7 VM. It is a pool of **on-demand** VMs: a c4d-highcpu-32
blue-green primary pair + 8 stopped fallbacks across 6 machine families
(c4d/c4/n4d/c2d/n2d/n2) for stockout resilience.
- **Idle auto-shutdown is live** (JIT start on the lyrics-review page; a Cloud
Function stops idle VMs after 15 min). When idle, cost is just boot disks
(~$10/VM/mo); compute is billed only while encoding — so the historical
"~$700/mo running 24/7" no longer applies.
**Opportunities:**
1. **Spot Instance:** Could save 60-91% (~$420-630/month savings)
- Risk: May be preempted during video encoding jobs
- Mitigation: Implement job restart logic
2. **Auto-scaling:** Start/stop based on video queue depth
- Could scale to zero when no jobs queued
- Startup time: ~2-3 minutes (acceptable for async processing)
**Opportunities (status):**
1. **Spot Instance:** Could save 60-91% — NOT adopted; on-demand chosen so a
fallback can always be *started* when needed (Spot preemption would undermine
the anti-stockout pool during the industry-wide crunch). Kept as a future lever.
2. **Auto-scaling / scale-to-zero:** ✅ IMPLEMENTED via JIT start + idle-shutdown
Cloud Function (start/stop on demand rather than queue-depth-based).
**Recommendation:** Test Spot instance first (lower risk), then consider auto-scaling
**Recommendation:** Stay on-demand (already scales to zero via idle-shutdown, which
captured most of the savings). Do NOT move to Spot for now — Spot preemption plus
the industry-wide stockout would undermine the anti-stockout fallback pool. Revisit
Spot only as a future experiment once capacity/resiliency is validated.
### 🔧 Artifact Registry Cleanup (Quick Win)
+148
View File
@@ -6,6 +6,142 @@ Key insights for future AI agents working on this codebase.
---
## Multi-instance-type encode pool: one shared speed-rank, availability-aware (Aug 2026, v0.195.0)
"c4d primary + a single n2 fallback family" is not resilient — a stockout is per
**(machine family × region)** and can exhaust every zone of a family at once. The
fix is a **ranked pool of ≥5 x86_64, 32-vCPU, ≥32 GB highcpu types across ≥3
independent silicon lineages** (c4d/c4/n4d + c2d/n2d/n2), tried fastest-first.
Three things that made this clean:
- **One pure preference module is the single source of truth.** Runtime selection
(`encoding_service._build_worker_candidates` → `ensure_any_running`) and deploy
green selection (`deploy_promote.select_green_candidates`) both call
`backend/services/encoding_worker_preference.ordered_candidates`. Two call-sites
computing "candidate order" independently WILL drift (they already had — runtime
used secret order, deploy used "n2-first"). `deploy_promote` is loaded by path in
CI, so it imports the module with a **by-path fallback** (an installed `backend`
package can otherwise shadow the repo working tree).
- **Prefer fastest, but be availability-aware.** Base order is speed-rank (c4d
stays top when it can start). A type that raises `ZONE_RESOURCE_POOL_EXHAUSTED`
is recorded in Firestore `capacity_state` and **demoted for a 15-min cooldown,
not dropped** — stops wasting ~2 min/attempt probing a known-dead type, then
re-probes so we snap back to c4d the moment capacity returns.
- **Override routing must key off an explicit `is_primary` flag, not list
position.** Once the ranker can put a fallback ahead of a stocked-out primary,
"candidate index 0 == primary" is false and the active-override set/clear logic
breaks silently (routes to the primary IP while a fallback is actually running).
- **Disk-type is family-specific:** next-gen Titanium families (c4/c4d/n4/n4d)
support **hyperdisk-balanced only**; older families (c2d/n2/n2d) use
**pd-balanced**. Wrong disk type = GCE rejects the instance at create.
- **Bake the full dep tree (CPU-only torch) into the image.** Each new fresh type
VM otherwise hits the fragile first-render `ensure_latest_wheel` full-tree
install; baking it (CPU torch via `--index-url` the PyTorch CPU index) makes all
types boot self-sufficient. CPU torch avoids multi-GB CUDA wheels the encode path
never uses. Verify `torch.version.cuda is None` — NOT `cuda.is_available()`,
which is False on the GPU-less builder even for a CUDA build.
## Concurrent encodes OOM-killed the worker → lost renders (Aug 2026, v0.194.0)
Three renders submitted at once ran as **3 concurrent 4K ffmpeg encodes** on the
single 32 GB `n2-highcpu-32` fallback worker (both 60 GB c4d primaries were down
in a Spot stockout). Combined RSS ~30 GB tripped the kernel OOM-killer, which
killed ffmpeg and restarted the `encoding-worker` service, wiping its in-memory
`jobs` registry. Every client poll then got `404 not found` → `lost contact with
worker after 5 consecutive poll failures` → all three jobs failed.
**Root cause:** the worker used `ThreadPoolExecutor(max_workers=4)` — up to 4
heavy encodes in parallel. ffmpeg already saturates every core for one job, so
parallelism bought **no throughput**, only multiplied peak memory.
**Fix:**
- **Serialize the heavy lane.** Split into `heavy_executor`
(`max_workers=ENCODING_HEAVY_CONCURRENCY`, default **1**) for renders/encodes
and `light_executor` (previews + wheel installs). One heavy ffmpeg at a time =
OOM-proof on any machine type; extras queue as `pending` (surfaced via
`queue_position`). `backend/services/gce_encoding/main.py`.
- **Resubmit on a lost job.** `wait_for_completion` now raises
`EncodingJobLostError` on a 404 *after the job was already seen* (a pinned poll
can only 404 if the worker lost it) or a terminal failure carrying
`restart_failure_code`. The render/encode workers wrap their submit+wait in
`run_with_lost_job_resubmit`, which resubmits as a fresh `<id>_retry_<hex8>`
(bounded). Backend must **re-raise** the typed error, not flatten it to
`success=False` (`encoding_interface.py`).
- **Queue vs run timeout.** Time spent `pending` counts against a generous
`queue_timeout`, not the per-run `timeout`, so a burst can wait in the queue
and still succeed.
**Principles for next time:**
- CPU-bound work that already uses all cores should run **one at a time** per
box; add throughput with more workers, not more per-worker threads.
- On a *pinned* poll, a `404` means the job is gone — treat "never existed"
(before first success) and "vanished mid-run" (after) differently.
- A restart-recovery that persists jobs is not enough if the reload skips
*terminal* states — the client-side lost detection is the real safety net.
---
## Naive `datetime.utcnow()` → wrong timezone in the UI (Aug 2026)
Job `created_at` and timeline/log timestamps were built from naive
`datetime.utcnow()` and serialized via `model_dump(mode='json')` /
`.isoformat()`, producing ISO strings with **no timezone offset**
(`"2026-08-14T18:10:25.123456"`). Firestore stored them as plain strings and
returned them verbatim. The frontend's `new Date(str)` parses an offset-less
ISO date-time as **local** time, so the raw UTC wall-clock was shown
unconverted — off by the viewer's UTC offset.
Two-part fix:
- **Display layer (`frontend/lib/utils.ts` → `parseServerDate`)**: treat
offset-less ISO date-times as UTC (append `Z`). This corrects *all* existing
data immediately, no migration. Use it for any backend timestamp before
`new Date()`/`toLocaleString()`.
- **Write layer**: `datetime.now(timezone.utc)` so new strings carry `+00:00`.
Takeaways: (1) never serialize a naive datetime to the client — always
timezone-aware UTC; (2) fixing at the display layer beats a data migration when
old rows are already ambiguous; (3) datetime arithmetic must guard for both
naive and aware (`if dt.tzinfo is None: dt = dt.replace(tzinfo=timezone.utc)`),
as `job_health_service` already did.
---
## Portrait (9:16) video: re-render, never transform the finished video (Jul 2026)
The karaoke video is `ffmpeg` compositing a background + audio + an `ass=` **subtitle
filter**, and the generated ASS bakes **absolute pixel coordinates at 3840×2160**
(`{\an8}{\pos(1920,Y)}` per line). That has a hard consequence for portrait output:
you cannot post-process the finished 16:9 video into a good 9:16 one — letterboxing
leaves the lyrics tiny in ~32% of the frame, and centre-cropping slices the start/end
off **every** line. The only good option is to **re-render at portrait resolution with
the lyrics re-wrapped** for the narrow frame.
This is cheap because the generator is already parameterized: `SubtitlesGenerator` /
`VideoGenerator` take a resolution tuple + font/line-height, and `SegmentResizer` wraps
lines via `max_line_length`. The portrait module (`karaoke_gen/portrait/`) drives them
directly at 1080×1920 from the same `corrections_updated.json` — so word-by-word timing
is identical to the landscape video; only layout changes. Gotchas found while building it:
- **Wrapping orphans:** `SegmentResizer` splits at natural breaks (commas), which in a
narrow frame can strand a one-word line ("No,"). A small merge-back pass
(`portrait/wrap.py`) fixes it without re-splitting (preserves per-word timing).
- **Sync without countdown:** use the **un-padded** instrumental + **un-countdown-processed**
segments — they're inherently in sync (original transcription timing); the portrait
title card provides the lead-in. Don't reuse the landscape's padded instrumental with
un-shifted segments or they drift by the padding amount.
- **Fonts on the GCE encoder:** libass resolves the lyrics font via fontconfig (the render
step registers the theme font on the VM), but the PIL-drawn header needs an actual
**file** — resolve it with `fc-match --format=%{file} "<family>"`.
- **Integration is zero-plumbing on the distribution side:** the portrait file is written
into the encoder's `output_dir`, so it rides the existing `finals/` GCS upload, and
`_upload_to_dropbox` uploads the whole local output dir. Only the orchestrator's
explicit **download allowlist** (`_download_gce_encoded_files`) needed a new mapping —
YouTube/Drive use their own allowlists, which is exactly why the portrait file is
naturally excluded from them.
Whole feature is additive + `PORTRAIT_RENDER_ENABLED`-gated + non-fatal: a portrait render
failure logs and returns `None`, never blocking the landscape outputs or distribution.
## Cloudflare edge in front of Cloud Run — the SSL "dragon" (Jul 2026)
Putting `api.nomadkaraoke.com` behind Cloudflare (WAF/rate-limit/origin-lock)
@@ -138,6 +274,8 @@ When a metadata key is missing, don't set it to "now" and skip the action — th
**Why not a Managed Instance Group?** MIG rolling updates don't support deep health checks — you can verify HTTP liveness but not "did a real encode actually work?". PR #587 showed that the service can respond to `/health` while failing all encode jobs (pip resolution error had broken the wheel). A real encode test catches this; a simple HTTP check does not. At two VMs, the operational complexity of a MIG (instance template management, rolling update policies, drain configuration) adds no value over two named VMs with a Firestore pointer.
**Still true after the multi-type pool (Aug 2026, v0.195.0).** Broadening to a 6-type fallback pool (see the v0.195.0 lesson above) is a stockout-resilience play and stays on the named-VM model: static IPs, IP-addressed blue-green, on-demand start/stop, deep encode-test-before-swap. A regional MIG with instance flexibility is GCP's textbook answer to stockouts, but it would replace IP addressing with service discovery / an internal LB and turn blue-green into rolling recreate — high blast radius for a system just hardened. **Revisit MIG only when we need horizontal autoscaling (>1 concurrent worker per burst) or VM sprawl becomes unmanageable (>~10 types).**
**Deep health check pattern**: After deploying to the secondary VM, CI runs a real encode job end-to-end before swapping traffic. This has caught broken deploys that passed all unit tests and liveness probes.
**JIT startup**: Tying VM startup to a user workflow event (entering the lyrics review page) gives ~60 seconds of natural warmup time before encoding is actually needed. Users are reading and editing lyrics while the VM starts — they never experience a cold-start stall. This avoids both 24/7 costs (~$400/mo) and noticeable latency.
@@ -268,6 +406,16 @@ When two sequential human review steps can be combined into one, do it. We origi
### Machine-family diversification (August 2026)
> **Superseded by v0.195.0** — the "Multi-instance-type encode pool" lesson at the
> top of this file. The 2-family fallback fleet (c4d + n2) described below was
> broadened to a **ranked 6-family pool** (c4d/c4/n4d/c2d/n2d/n2), and runtime +
> deploy selection now route through the shared
> `backend/services/encoding_worker_preference.py` (fastest-first + 15-min capacity
> cooldown), not "primary first, fallbacks in declared order". The incident + root
> lesson below remain accurate history; the "Fix (Option B)" and "Architecture
> summary" specifics (2 families / 6 VMs / declared-order iteration) are outdated —
> see the v0.195.0 lesson for the current mechanism.
**Incident 2026-08-12:** `c4d-highcpu-32` hit a **region-wide `ZONE_RESOURCE_POOL_EXHAUSTED` stockout across `us-central1-a`, `-b` AND `-c` simultaneously.** Because the primary pair *and* both fallbacks were all the same machine family, every lane in `ensure_any_running` failed at once. Effects:
- **Preview** (`POST /api/review/{id}/preview-video`) fell through to slow local Cloud-Run encoding (~130–160 s), which **exceeds Cloudflare's ~100 s edge timeout** → browser got a **524 / "NetworkError when attempting to fetch resource"** even though the backend actually returned 200. The 524 and the NetworkError are the same event; backend logs showing 200 are misleading because the client was already disconnected.
- **Render** parked in `RENDER_PENDING_CAPACITY` and auto-retried (safe only if capacity returns within 24 h).
+2
View File
@@ -55,6 +55,8 @@
## Recent Changes
- **Portrait (9:16) Karaoke Video Output** (2026-07-13): When enabled (`PORTRAIT_RENDER_ENABLED`, default on), every finalised job also gets a portrait 1080×1920 karaoke video for phone viewing / social sharing, distributed to **GCS + the Dropbox brand-code folder only** (never Drive/YouTube). It is a genuine **re-render** at portrait resolution with re-wrapped lyrics — not a transform of the finished landscape video (letterbox = tiny lyrics, crop = cuts the ends off every line; proven in the design experiments). The new `karaoke_gen/portrait/` module reuses the same `SubtitlesGenerator` engine + corrected-lyrics data, so word-by-word timing is identical; it adds an orphan-merging wrapper, a branded portrait background (wordmark/header + song/artist + footer), and title/end cards. Rendered on the GCE encoder inside `run_encoding` (best-effort + `PORTRAIT_RENDER_ENABLED` flag; a failure never fails the job) and carried to Dropbox via the existing `finals/` upload path. ~15–30s + ~10 MB per job. See [archive/2026-06-14-portrait-video-design.md](archive/2026-06-14-portrait-video-design.md) and [archive/2026-07-13-portrait-video-plan.md](archive/2026-07-13-portrait-video-plan.md).
- **Cloudflare Edge Security for the Backend API** (2026-07-20): `api.nomadkaraoke.com` is now proxied through Cloudflare (WAF + rate limiting + origin lock), after a vuln-scanner hammered the previously directly-exposed Cloud Run origin. WAF blocks exploit/secret-exposure paths (`contains` operator — regex needs a Business plan); per-IP rate limiting excludes `/api/internal/*`; a Transform Rule injects a secret `X-Edge-Auth` header that the backend's `EdgeAuthMiddleware` (`EDGE_AUTH_MODE=enforce`) requires, blocking direct-to-`*.run.app` bypass (health/root exempt). Key finding: the Cloud Run managed cert can't provision behind Cloudflare, but zone SSL mode "full" (not strict) doesn't validate the origin cert, so it works and is renewal-safe — **never switch the zone to "full (strict)".** Managed as IaC in `infrastructure/modules/edge_security.py`. Also retuned the "High Error Rate" alert to 5xx-only (scanner 404s no longer page). See [ARCHITECTURE.md § Edge Security](ARCHITECTURE.md#edge-security-cloudflare), [LESSONS-LEARNED.md](LESSONS-LEARNED.md#cloudflare-edge-in-front-of-cloud-run--the-ssl-dragon-jul-2026), and [archive/2026-07-20-edge-security-cutover-runbook.md](archive/2026-07-20-edge-security-cutover-runbook.md).
- **AI Auto-Correct Suggestions** (2026-06-11): Opt-in AI correction suggestions in the lyrics review UI — the third attempt at lyrics auto-correction, redesigned around the failures that led to disabling it in PR #321 (Jan 2026). One whole-song LLM call (default Gemini 3.1 Pro via Vertex, `AUTO_CORRECT_MODEL` env) compares the working transcription against reference lyrics and returns word-id-keyed suggestions; nothing is applied until the reviewer accepts each one (or accept-all) in a dedicated panel with per-row undo. New `POST /api/review/{job_id}/auto-correct` endpoint + `backend/services/auto_correct/`; frontend `useAutoCorrect` hook, `AutoCorrectModal` (knobs: adlib removal, insertions, confidence filter), `AutoCorrectPanel`. Accept/reject decisions land in the EditLog (`ai_suggestion_*` ops) to measure real accept rates. 5-model offline eval over 30 real jobs with human ground truth picked the default (Fable 5 ≈ Gemini 3.1 Pro ≫ GPT-5.2, which made lyrics worse). See [archive/2026-06-10-lyrics-auto-correction-reeval-plan.md](archive/2026-06-10-lyrics-auto-correction-reeval-plan.md).
+24 -7
View File
@@ -62,6 +62,10 @@ curl -X POST "https://api.nomadkaraoke.com/api/internal/workers/video" \
Since v0.184.2, in-flight status polls are also **pinned to the worker that accepted the job** (`get_job_status(..., worker_url=)`), so a blue-green deploy that swaps the `active_url` primary pointer mid-render no longer migrates the poll to a worker that never received the job. If you still see `lost contact with worker after 5 consecutive poll failures: Encoding job <ID> not found`, confirm via step 2 above that the worker the job was submitted to (not necessarily the current primary) still has the job — a `not found` from the *current* primary while the job is alive on the old primary was the pre-v0.184.2 failure mode (incident 2026-06-16, job d3af33ae).
Since **v0.194.0**, a mid-run job loss is also **auto-recovered**: the encoding worker processes heavy renders/encodes **one at a time** (`heavy_executor`, `ENCODING_HEAVY_CONCURRENCY=1`) so it can no longer OOM from concurrent 4K encodes (the trigger for the 2026-08-15 Arctic Monkeys batch failure — 3 concurrent encodes OOM-killed the 32 GB fallback worker and restarted it, wiping its in-memory jobs). If the worker *does* restart mid-render (deploy/crash), `wait_for_completion` now raises `EncodingJobLostError` and the render/encode worker **resubmits the job under a fresh `<id>_retry_<hex8>`** (bounded by `ENCODING_RESUBMIT_MAX=2`) instead of failing. To confirm serialization is live on a worker: `curl -s localhost:8080/health` shows `queue_length` growing while `active_jobs` stays 1 under load. **Note:** `main.py` ships in the wheel but the running uvicorn process only picks up worker-side changes (executor split, `queue_position`) on a **fresh boot / service restart** — `ensure_latest_wheel` alone does not reload the app process.
Since **v0.194.2**, the CI deploy handles that restart automatically even during a c4d Spot stockout. The old blue-green only targeted the c4d primary/secondary; when both were down it rolled back and **never refreshed the serving n2 fallback** (recorded as `active_override_vm`), so worker-side changes didn't reach prod until a manual restart (`primary_version` in the config doc went stale). The deploy is now **capacity-aware** (`infrastructure/encoding-worker/deploy_promote.py`): it validates the new wheel on a *fresh* green worker selected from the **ranked 6-family pool** (`select_green_candidates` → the shared `encoding_worker_preference.ordered_candidates` — fastest-first with capacity cooldown; the c4d secondary if it can start, else the fastest available fallback family, never the current override so it keeps serving) — then **promotes** the green (primary/secondary swap for a c4d green, or sets `active_override` for a fallback green) and drains+stops the retired worker. A c4d green also **clears a stale override** so traffic returns to the fresh primary. Zero-downtime, and it works while c4d is exhausted. Last resort if no separate green can start: an in-place restart of the serving override (brief blip, covered by auto-resubmit).
---
## CDG/TXT packages missing from completed job
@@ -90,13 +94,18 @@ The script is idempotent — re-running it skips regeneration if the CDG ZIP alr
**Cause:** Worker picks up a new deploy but doesn't restart automatically.
Target the **currently-serving** VM — `active_override_vm` in `config/encoding-worker`
if set, else `primary_vm` (with its zone). There is no VM literally named
`encoding-worker`; the examples below use the primary `encoding-worker-a` — swap in
the active VM/zone if a fallback is serving.
```bash
# Check current wheel version
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
# Check current wheel version (example: the primary a in us-central1-c)
gcloud compute ssh encoding-worker-a --zone=us-central1-c --project=nomadkaraoke \
--command="curl -s http://localhost:8080/health | python3 -m json.tool"
# Restart to pick up latest wheel
gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
gcloud compute ssh encoding-worker-a --zone=us-central1-c --project=nomadkaraoke \
--command="sudo systemctl restart encoding-worker"
```
@@ -106,10 +115,14 @@ gcloud compute ssh encoding-worker --zone=us-central1-c --project=nomadkaraoke \
**Symptoms:** A render fails with `OutputGenerator not available: No module named 'tenacity'. The karaoke-gen wheel must be installed. Check that ensure_latest_wheel() succeeded.` (or another missing package). Retries hit the same VM and fail identically.
**Cause:** A freshly-provisioned encoding-worker VM comes up with only a handful of packages baked into the Packer image, and boot installs the wheel with `--no-deps`. The full karaoke-gen dependency tree (torch, langchain, tenacity, …) is installed lazily at the first job by `ensure_latest_wheel()`. If that install fails or partially completes, the venv is left importable-but-incomplete and the render dies on the first missing import. First seen 2026-08-13 (job 233b9536) on a fresh `n2-highcpu-32` fallback added in #903.
**Largely fixed in v0.195.0 (dep-bake):** the Packer image now bakes the **full** karaoke-gen dependency tree (with CPU-only torch) into the venv at build time, so a freshly-provisioned VM of any family boots self-sufficient — no first-job dependency install. This failure mode should now only appear on a VM whose boot disk predates the dep-bake image, or a venv left partial by an interrupted repair. The `ensure_latest_wheel()` runtime backstop below still exists for those cases.
**Original cause (pre-v0.195.0):** A freshly-provisioned VM came up with only a handful of packages baked in, and boot installed the wheel with `--no-deps`. The full dependency tree (torch, langchain, tenacity, …) was installed lazily at the first job by `ensure_latest_wheel()`; a failed/partial install left the venv importable-but-incomplete and the render died on the first missing import. First seen 2026-08-13 (job 233b9536) on a fresh `n2-highcpu-32` fallback added in #903.
**Fixed in v0.192.7:** `ensure_latest_wheel()` now downloads only the single latest wheel (was: copying the entire ~6 GiB `wheels/` dir every job with a 60 s timeout), retries the install (3× at 900 s), and **verifies the render/encode import chain** before returning — a clean `pip` exit is no longer trusted. Callers fail the job with a clear retryable error instead of proceeding. Fresh workers pick this up via the wheel-at-boot.
**Also fixed in v0.194.1 (concurrency race):** `ensure_latest_wheel()` runs on the *light* lane (>1 thread) at the start of every job, so on a fresh boot several jobs would call it at once and race on the shared `/tmp` wheel path (`gsutil cp` clobbered mid-copy) and the venv (two `pip install`s at once) — one job then failed with `wheel/dependencies not ready ... retry on a healthy worker` (2026-08-15, job 374dec26, 3 jobs on a fresh n2f boot). Now it's guarded by a process-wide lock **and** short-circuits when the installed version already matches the latest GCS wheel (the common case — startup.sh installs it at boot). So only the *first* job after a new wheel actually installs; the rest wait briefly then take the verified fast path. A single job failing this way can simply be retried once a worker is warm.
**Manual repair (if a running VM is stuck on an old wheel):** the venv is root-owned, so use `sudo`:
```bash
@@ -275,7 +288,7 @@ gcloud compute instances describe encoding-worker-a \
**Background — what this state means:** GCE returned `ZONE_RESOURCE_POOL_EXHAUSTED` or transient `503 SERVICE_UNAVAILABLE` from `compute.instances.start` on every encoding-worker VM. The render worker parks the job in `RENDER_PENDING_CAPACITY` instead of failing it; Cloud Scheduler retries it every 5 min via `/api/internal/retry-pending-render-jobs`. Hard timeout is 24 hours (then transitions to `failed` with a clear permanent-failure message).
The fallback fleet is diversified by **machine family** (since incident 2026-08-12): `c4d-highcpu-32` primaries in `us-central1-c` + `c4d` fallbacks in `-a`/`-b` + `n2-highcpu-32` fallbacks (`encoding-worker-fallback-n2c`/`-n2f`) in `-c`/`-f`. The n2 pool is much deeper, so a full `c4d` region-wide stockout (which took out a/b/c at once on 2026-08-12) should now still find n2 capacity. If you see EVERY candidate (c4d **and** n2) return stockout, that's a genuinely severe regional event — wait, or add a cross-region fallback.
The fallback fleet is diversified across **6 machine families** (broadened to the full pool in v0.195.0): `c4d-highcpu-32` primaries (`encoding-worker-a`/`-b`) in `us-central1-c`, plus 8 stopped fallbacks — `c4d` (`-fallback-a`/`-b`, zones a/b), `n2` (`-n2c`/`-n2f`, zones c/f), `c4` (`-c4a`, zone a), `n4d` (`-n4db`, zone b), `c2d` (`-c2df`, zone f), `n2d` (`-n2da`, zone a). Candidates are tried **fastest-first with a 15-min capacity cooldown** (a family that stocks out is demoted, then re-probed) — see `backend/services/encoding_worker_preference.py`. A single-family region-wide stockout (which took out c4d a/b/c at once on 2026-08-12) now still finds capacity in the 5 other families. If you see EVERY family return stockout, that's a genuinely severe regional event — wait, or add a cross-region fallback. NOTE: creating a *new* fallback VM (or re-creating a deleted one) still needs a one-time boot allocation, so a deep enough crunch can even block provisioning — a `pulumi up` may show the missing VM as "to create / errored" until capacity returns.
**Related symptom — preview 524 / "NetworkError":** the same capacity exhaustion also makes `POST /api/review/{id}/preview-video` fall back to slow local encoding (~130–160 s), which exceeds Cloudflare's ~100 s edge timeout → the browser shows a **524** or Firefox *"NetworkError when attempting to fetch resource"* even though the backend returns 200. If a user reports the review preview failing, check for a concurrent stockout; the already-rendered preview mp4 (if any) is fetchable via `GET /api/review/{id}/preview-video/{hash}` (302 → signed GCS URL) with a Bearer admin token. Completing the review does **not** require the preview.
@@ -303,14 +316,18 @@ gcloud logging read 'protoPayload.methodName:"instances.start" AND "ZONE_RESOURC
--project=nomadkaraoke --freshness=30m --limit=5 \
--format='value(timestamp, protoPayload.resourceName)'
# Try starting a fallback in each family; if BOTH c4d and n2 refuse, it's severe — wait.
# Try starting a fallback in each of the 6 families; if ALL refuse, it's severe — wait.
# Synchronous (no --async) so the start op surfaces stockout inline, and we capture
# gcloud's own exit status rather than piping (a pipe would return sed's status).
for VM_ZONE in \
"encoding-worker-fallback-a:us-central1-a" \
"encoding-worker-fallback-b:us-central1-b" \
"encoding-worker-fallback-n2c:us-central1-c" \
"encoding-worker-fallback-n2f:us-central1-f"; do
"encoding-worker-fallback-n2f:us-central1-f" \
"encoding-worker-fallback-c4a:us-central1-a" \
"encoding-worker-fallback-n4db:us-central1-b" \
"encoding-worker-fallback-c2df:us-central1-f" \
"encoding-worker-fallback-n2da:us-central1-a"; do
VM="${VM_ZONE%%:*}"; ZONE="${VM_ZONE##*:}"
if OUT=$(gcloud compute instances start "$VM" --zone="$ZONE" --project=nomadkaraoke 2>&1); then
echo "$VM: OK (started — remember to stop it)"
@@ -0,0 +1,150 @@
# Portrait (9:16) Karaoke Video Output — Design
**Date:** 2026-06-14
**Status:** Design (approved direction; pending spec review → implementation plan)
**Author:** Claude (with Andrew)
**Worktree:** `karaoke-gen-portrait-video` · branch `feat/sess-20260614-1550-portrait-video`
## 1. Problem & Goal
Customers have asked for **portrait-format** karaoke videos that are easier to view on
a phone and to share on social media (Reels / TikTok / Shorts). Today every job produces
only **landscape 16:9** finals.
**Goal:** add a portrait (9:16) karaoke video as an **additional output file** during
finalisation, stored in **GCS** and uploaded to the **final Dropbox brand-code folder
only** — *not* Google Drive or YouTube.
## 2. Decisions (confirmed with Andrew, 2026-06-14)
| Decision | Choice |
|---|---|
| **Approach** | Re-render at portrait resolution (NOT a transform of the finished landscape video) |
| **Layout** | Branded header (wordmark + song/artist) → lyrics in lower-center → `nomadkaraoke.com` footer, on a dark theme background |
| **Output scope** | **Instrumental karaoke only** — one portrait file per job (the version people sing to / share) |
| **Rollout** | **Default-on for every job** (no opt-in toggle) |
| **Destinations** | GCS output + Dropbox brand-code folder only |
| **Resolution** | 1080×1920 (H.264 / AAC, `+faststart`) |
## 3. Key Finding That Drives the Design
The karaoke video is `ffmpeg` compositing *background + instrumental + an ASS subtitle
filter*. **The ASS file bakes absolute pixel coordinates at 3840×2160** — lyrics centered
at x=1920, lines stacked at fixed Y positions (`\an8\pos(1920,477)` …). Because of this,
you **cannot** turn a finished landscape video into a good portrait one:
| Approach | Result | Evidence |
|---|---|---|
| Letterbox (pad 16:9 → 9:16) | ❌ Lyrics tiny, ~68% black bars | `comparison.png` (panel 1) |
| Center-crop (16:9 → 9:16) | ❌ Start/end of **every** line cut off | `comparison.png` (panel 2) |
| **Re-render at 1080×1920 with re-wrapped lyrics** | ✅ Large, readable, on-brand | `branded_still.png`, `comparison.png` (panel 3) |
The lyrics must be **re-laid-out** for the narrow frame. Validated empirically on a real
prod job (**piri – dog**, `052b94ab`) — see §8.
**Enabling fact:** the existing generator is already fully parameterized for this. The
portrait render reuses the *same engine* and the *same per-job corrected-lyrics data*;
it is an additive render path, not a new rendering system.
## 4. Architecture
Insert a **portrait render sub-step into `karaoke_finalise.process()`**, after the
landscape encodes and before/within the distribution (GCS + Dropbox) step. Finalisation
already operates on the job's local files (With Vocals video, instrumental, title/end
screens) and can receive a corrections-JSON path, so all inputs are in reach.
```
finalise.process()
├─ (existing) detect inputs, CDG/TXT, landscape encodes (lossless/lossy 4k, 720p)
├─ (NEW) render_portrait_video() ← this feature
│ ├─ build portrait lyrics ASS (1080×1920, re-wrapped)
│ ├─ build portrait background (branded, 1080×1920)
│ ├─ build portrait title/end screens (1080×1920)
│ └─ ffmpeg: title + [bg + ass + instrumental] + end → portrait MP4
└─ (existing) upload finals → GCS + Dropbox brand-code folder (portrait file joins the set)
```
### 4.1 Components
1. **Portrait lyrics ASS generator.** Reuse `SubtitlesGenerator` / `SegmentResizer` at a
portrait resolution tuple. Source of word-timed lyrics = the job's
`corrections_updated.json` (`corrected_segments`). *(Recommended over transforming the
existing landscape `karaoke.ass`, which would re-implement wrapping/positioning.)*
Add a **portrait resolution preset** (the current `resolution_map` is landscape-only).
- Recommended params from experiments (1080×1920): `font_size ≈ 88`, `line_height ≈ 118`,
`max_visible_lines = 4`, `max_line_length ≈ 19`, `top_padding ≈ 709` (centers the
lyric block in the open zone below the header).
2. **Portrait background.** A branded 1080×1920 background: dark theme gradient + neon
Nomad wordmark + song/artist + `nomadkaraoke.com` footer + subtle neon border. Generated
per-job (artist/title baked in), reusing theme brand assets. (Prototype: `build_bg.py`.)
3. **Portrait title/end screens.** The current `video_generator.py` renders 4K-landscape
title/end via PIL with region-based text placement. Add portrait variants (portrait
regions / canvas). Reuse the same theme params (`style_params.json`).
4. **Render + mux.** `ffmpeg` looping the portrait background + ASS subtitle filter +
instrumental, concatenated with portrait title/end. H.264 / AAC, `yuv420p`, `+faststart`.
5. **Upload.** The portrait MP4 joins the outputs dict and the existing GCS + Dropbox
upload (brand-code folder). Filename suffix e.g. `(Final Karaoke Portrait 1080x1920).mp4`.
### 4.2 Data flow
`corrections_updated.json` + `style_params.json` + instrumental (+ theme assets)
→ portrait ASS + portrait bg + portrait title/end
→ ffmpeg → portrait MP4 → GCS + Dropbox.
## 5. Error Handling & Rollout
- **Additive and non-fatal.** Portrait render failure must **not** fail the job or block
the landscape outputs/distribution. On error: log, capture to the error monitor, and
continue. The portrait file is a bonus, never a gate.
- **Default-on** for every finalised job. Adds ~15–30 s render + ~10 MB storage per job
(see §7). No user toggle in v1.
- Idempotency: re-running finalise regenerates and re-uploads the portrait file
deterministically (same naming), consistent with existing finals.
## 6. Testing Strategy
Per `docs/TESTING.md`:
- **Unit:** portrait param selection (resolution preset, font/line-height/top-padding);
line-balancing/wrapping helper (no orphaned single words); filename/suffix; outputs-dict
inclusion.
- **Integration:** render a **short** portrait clip from fixture corrected-lyrics + a few
seconds of audio; assert dimensions 1080×1920, non-trivial duration, subtitle burn-in
present (frame hash / pixel sample), `+faststart`.
- **Regression:** portrait output is added to the finalise outputs dict and is included in
the GCS + Dropbox upload set; a portrait-render exception does NOT fail the job.
- **Production E2E (run-once):** finalise a real job, confirm a portrait MP4 lands in GCS
and the Dropbox brand-code folder and is *absent* from Drive/YouTube.
## 7. Cost / Performance
Measured locally: a full **3:19** song rendered to 1080×1920 (libx264 `fast`, crf 20) in
**~19 s** (≈10× realtime), ~9.6 MB. Per-job overhead is modest and acceptable for
default-on. Negligible relative to the existing 4K landscape encodes.
## 8. Validation Evidence (real prod job)
Job **piri – dog** (`052b94ab`). Assets pulled from
`gs://karaoke-gen-storage-nomadkaraoke/jobs/052b94ab/` (corrected lyrics, theme params,
instrumental, title/end, landscape final). Artifacts in
`docs/archive/2026-06-14-portrait-video-experiments/`:
- `comparison.png` — the three approaches side-by-side (letterbox / crop / re-render)
- `branded_still.png` — the recommended portrait re-render (full frame)
- `render_portrait.py`, `build_bg.py`, `montage.py` — reproducible experiment scripts
## 9. Open Polish Items (for implementation)
- **Line-balancing** in the wrapper: the quick `max_line_length` pass occasionally orphans
a short word (e.g. "No,"). Add balanced wrapping (avoid trailing 1–2-char lines).
- **Vertical fill** at sparse moments (1–2 active lines) — acceptable, but consider a
subtle scroll/anchor so the block doesn't float.
- **Portrait title/end** region tuning (the landscape regions don't map 1:1).
- **Background**: ship the dark-gradient + wordmark direction; the neon-brick variant was
considered and not chosen for v1.
- Confirm the **encoding-worker / finalise runtime** has the `lyrics_transcriber` generator
+ `corrections_updated.json` available locally (it receives a corrections-JSON path
today); wire the fetch if needed.
## 10. Out of Scope (v1)
- With-vocals portrait, multiple portrait resolutions, per-job opt-in toggle, Drive/YouTube
upload of portrait, short-form "highlight clip" auto-cutting.
Binary file not shown.

After

Width:  |  Height:  |  Size: 196 KiB

@@ -0,0 +1,69 @@
#!/usr/bin/env python3
"""Build a branded 1080x1920 portrait karaoke background for the experiment."""
from PIL import Image, ImageDraw, ImageFont
W, H = 1080, 1920
OUT = "/Users/andrew/portrait-exp/out/bg_branded.png"
LOGO = "/Users/andrew/portrait-exp/out/logo_crop.png"
FONT = "/Users/andrew/portrait-exp/piri/font.ttf"
ARTIST = "PIRI"
TITLE = "DOG"
# Vertical gradient navy -> near black
img = Image.new("RGB", (W, H), (8, 10, 24))
top = (16, 18, 42)
bot = (4, 5, 12)
px = img.load()
for y in range(H):
t = y / (H - 1)
r = int(top[0] * (1 - t) + bot[0] * t)
g = int(top[1] * (1 - t) + bot[1] * t)
b = int(top[2] * (1 - t) + bot[2] * t)
for x in range(W):
px[x, y] = (r, g, b)
draw = ImageDraw.Draw(img, "RGBA")
# Subtle neon-pink rounded border
margin = 26
draw.rounded_rectangle([margin, margin, W - margin, H - margin],
radius=46, outline=(255, 60, 200, 90), width=4)
draw.rounded_rectangle([margin + 6, margin + 6, W - margin - 6, H - margin - 6],
radius=40, outline=(150, 80, 247, 50), width=2)
# Wordmark (NOMAD KARAOKE), neon pink on dark — paste with screen-ish blend by
# compositing over the gradient (dark areas blend, neon stays).
logo = Image.open(LOGO).convert("RGBA")
lw = 540
lh = int(logo.height * lw / logo.width)
logo = logo.resize((lw, lh), Image.LANCZOS)
# Knock out the dark brick background: make near-dark pixels transparent so only neon remains.
lpx = logo.load()
for y in range(logo.height):
for x in range(logo.width):
r, g, b, a = lpx[x, y]
lum = max(r, g, b)
if lum < 70:
lpx[x, y] = (r, g, b, 0)
elif lum < 130:
lpx[x, y] = (r, g, b, int(a * (lum - 70) / 60))
img.paste(logo, ((W - lw) // 2, 70), logo)
# Artist · Title under the wordmark
f_title = ImageFont.truetype(FONT, 60)
f_artist = ImageFont.truetype(FONT, 44)
y0 = 70 + lh + 26
tw = draw.textlength(TITLE, font=f_title)
draw.text(((W - tw) / 2, y0), TITLE, font=f_title, fill=(255, 255, 255))
aw = draw.textlength(ARTIST, font=f_artist)
draw.text(((W - aw) / 2, y0 + 70), ARTIST, font=f_artist, fill=(255, 223, 107))
# Footer handle
f_foot = ImageFont.truetype(FONT, 38)
foot = "nomadkaraoke.com"
fw = draw.textlength(foot, font=f_foot)
draw.text(((W - fw) / 2, H - 110), foot, font=f_foot, fill=(255, 122, 204))
img.save(OUT)
print(OUT, img.size)
Binary file not shown.

After

Width:  |  Height:  |  Size: 832 KiB

@@ -0,0 +1,35 @@
#!/usr/bin/env python3
from PIL import Image, ImageDraw, ImageFont
O = "/Users/andrew/portrait-exp/out/"
FONT = "/Users/andrew/portrait-exp/piri/font.ttf"
panels = [
("p_letterbox.png", "1. LETTERBOX", "(pad finished video)"),
("p_crop.png", "2. CENTER-CROP", "(crop finished video)"),
("branded_still.png", "3. RE-RENDER", "(reflow lyrics)"),
]
PH = 1100 # panel image height
lab_h = 90
gap = 30
imgs = []
for fn, _, _ in panels:
im = Image.open(O + fn).convert("RGB")
w = int(im.width * PH / im.height)
imgs.append(im.resize((w, PH), Image.LANCZOS))
W = sum(i.width for i in imgs) + gap * (len(imgs) + 1)
H = PH + lab_h + gap * 2
canvas = Image.new("RGB", (W, H), (20, 20, 28))
draw = ImageDraw.Draw(canvas)
f1 = ImageFont.truetype(FONT, 40)
f2 = ImageFont.truetype(FONT, 28)
x = gap
for (fn, t1, t2), im in zip(panels, imgs):
canvas.paste(im, (x, lab_h + gap))
cx = x + im.width / 2
w1 = draw.textlength(t1, font=f1)
good = t1.startswith("3")
draw.text((cx - w1 / 2, 14), t1, font=f1, fill=(120, 230, 140) if good else (240, 120, 120))
w2 = draw.textlength(t2, font=f2)
draw.text((cx - w2 / 2, 58), t2, font=f2, fill=(180, 180, 190))
x += im.width + gap
canvas.save(O + "comparison.png")
print(O + "comparison.png", canvas.size)
@@ -0,0 +1,94 @@
#!/usr/bin/env python3
"""Experimental portrait karaoke ASS generator driving the real karaoke-gen generator.
Loads a real job's corrected_segments + style params, then re-lays-out the lyrics
for a portrait (9:16) frame at a chosen resolution / font / wrapping, and writes a
portrait .ass file. Rendering to video/still is done separately with ffmpeg.
Usage:
python render_portrait.py --segments piri/corrections_updated.json \
--style piri/style_params.json --out out/portrait_tuned.ass \
--width 1080 --height 1920 --font 90 --lines 4 --maxlen 21 --top-padding 90
"""
import argparse
import json
import logging
import os
import sys
import tempfile
REPO = "/Users/andrew/Projects/nomadkaraoke/karaoke-gen-portrait-video"
sys.path.insert(0, REPO)
from karaoke_gen.lyrics_transcriber.types import LyricsSegment
from karaoke_gen.lyrics_transcriber.output.subtitles import SubtitlesGenerator
from karaoke_gen.lyrics_transcriber.output.segment_resizer import SegmentResizer
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--segments", required=True)
ap.add_argument("--style", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--width", type=int, default=1080)
ap.add_argument("--height", type=int, default=1920)
ap.add_argument("--font", type=int, default=90)
ap.add_argument("--line-height", type=int, default=None, help="defaults to font")
ap.add_argument("--lines", type=int, default=4, help="max visible lines")
ap.add_argument("--maxlen", type=int, default=21, help="max chars per line (wrapping)")
ap.add_argument("--top-padding", type=int, default=None, help="defaults to line height")
args = ap.parse_args()
logging.basicConfig(level=logging.WARNING)
logger = logging.getLogger("portrait")
with open(args.segments) as f:
data = json.load(f)
segments = [LyricsSegment.from_dict(s) for s in data["corrected_segments"]]
logger.warning(f"Loaded {len(segments)} corrected segments")
with open(args.style) as f:
style_params = json.load(f)
# Build styles dict from the real theme, with portrait overrides.
styles = {"karaoke": dict(style_params.get("karaoke", {}))}
k = styles["karaoke"]
k["font_size"] = args.font
k["max_visible_lines"] = args.lines
if args.top_padding is not None:
k["top_padding"] = args.top_padding
# Resolve font_path: theme paths are relative to the GCS themes/ mirror; if a local
# copy exists use it, otherwise drop it so libass falls back to the named font.
fp = k.get("font_path")
if fp and not os.path.isfile(fp):
local_fp = os.path.join(os.path.dirname(args.style), "font.ttf")
k["font_path"] = local_fp if os.path.isfile(local_fp) else None
line_height = args.line_height or args.font
# Re-wrap segments for the narrow portrait frame.
resizer = SegmentResizer(max_line_length=args.maxlen, logger=logger)
resized = resizer.resize_segments(segments)
logger.warning(f"Resized to {len(resized)} segments (maxlen={args.maxlen})")
out_dir = os.path.dirname(os.path.abspath(args.out))
os.makedirs(out_dir, exist_ok=True)
gen = SubtitlesGenerator(
output_dir=out_dir,
video_resolution=(args.width, args.height),
font_size=args.font,
line_height=line_height,
styles=styles,
logger=logger,
)
prefix = os.path.splitext(os.path.basename(args.out))[0]
ass_path = gen.generate_ass(resized, prefix, audio_filepath="dummy.flac")
# generate_ass writes "{prefix} (Karaoke).ass" — normalize to requested --out
if os.path.abspath(ass_path) != os.path.abspath(args.out):
os.replace(ass_path, args.out)
print(args.out)
if __name__ == "__main__":
main()
@@ -0,0 +1,122 @@
# Plan: Portrait (9:16) Karaoke Video Output
**Created:** 2026-07-13
**Branch:** `feat/sess-20260614-1550-portrait-video`
**Status:** Draft
**Design:** `docs/archive/2026-06-14-portrait-video-design.md` (approved)
## Overview
Add a **portrait 1080×1920 karaoke video** as an additional output of every finalised job,
stored in GCS and uploaded to the Dropbox brand-code folder only (not Drive/YouTube). It is
a **re-render** at portrait resolution with re-wrapped lyrics — not a transform of the
finished landscape video (proven necessary in the design experiments). It reuses the
existing `SubtitlesGenerator`/`VideoGenerator` engine and the job's already-present
corrected-lyrics + theme data.
## Requirements
- [ ] Produce `{base} (Final Karaoke Portrait 1080x1920).mp4` (H.264/AAC, yuv420p, +faststart) for the **instrumental karaoke** version.
- [ ] Portrait layout: branded header (wordmark + song/artist), lyrics in the lower-center, `nomadkaraoke.com` footer, dark theme background.
- [ ] Lyrics re-wrapped for the narrow frame with **balanced** wrapping (no orphaned 1–2-char lines).
- [ ] Uploaded to GCS (`jobs/{id}/finals/`) and the Dropbox brand-code folder; included in job result/state so the dashboard/email can surface it.
- [ ] **Default-on** for every job; **non-fatal** (portrait failure must never fail the job or block landscape outputs/distribution).
- [ ] Render cost stays modest (~15–30s/job, ~10 MB).
## Technical Approach
### Insertion point (confirmed)
The GCE encoder `backend/services/gce_encoding/main.py::run_render_video` **already** loads a
`CorrectionResult` (corrections JSON), the countdown-padded audio, and the theme styles, and
runs `OutputGenerator` to render the landscape with-vocals video + `karaoke.ass`. So every
input a portrait render needs is already resolved on the encoder — **no new data path**.
Add a **self-contained portrait render op**, `run_render_portrait`, on the GCE encoder,
orchestrated as an additional step after the existing render/encode. It:
- Reuses the same asset-loading as `run_render_video` (corrections → segments, style,
countdown processing) but targets the **instrumental** audio + the portrait screens.
- Is guarded try/except → on failure, log + report to error-monitor + continue (bonus output);
it never blocks the landscape outputs or distribution.
The orchestrator (`backend/workers/video_worker_orchestrator.py` — same place the
original-vocals guide is emitted) triggers the portrait op and records/uploads the result,
mirroring that existing pattern. The shared ffmpeg assembly lives in a reusable helper so the
local CLI path can call it too.
### New component: portrait render
A `PortraitRenderer` (new module, e.g. `karaoke_gen/portrait/portrait_renderer.py`) that:
1. **Portrait lyrics ASS** — load `corrected_segments` from `corrections_updated.json`
(fallback: the landscape `lyrics/karaoke.ass` is present if corrections JSON is absent —
see Open Questions), re-wrap via `SegmentResizer(max_line_length≈19)` with an added
balanced-wrap pass, then `SubtitlesGenerator(video_resolution=(1080,1920), font_size≈88,
line_height≈118, styles{max_visible_lines:4, top_padding≈709})`.
2. **Portrait background** — 1080×1920 branded PNG: dark gradient + neon Nomad wordmark +
song/artist + `nomadkaraoke.com` footer + subtle border. Port `build_bg.py` (experiment)
to a themed generator driven by `style_params.json` + brand assets.
3. **Portrait title/end screens** — add portrait variants to `video_generator.py`
(currently 4K-landscape, region-based). Reuse theme params; portrait regions.
4. **Assemble** — ffmpeg: title + [bg loop + `ass=` filter + instrumental] + end → portrait MP4.
5. Return the local path; orchestrator uploads to GCS + Dropbox and records it in the result.
### Add a portrait resolution path
`generator.py::_get_video_params` only knows landscape presets (4k/1080p/720p/360p). Rather
than overload that string map, the `PortraitRenderer` constructs `SubtitlesGenerator`/
`VideoGenerator` **directly** with the `(1080,1920)` tuple + explicit font/line-height (as the
experiment does), avoiding changes to the landscape presets.
## Implementation Steps
1. [ ] **Balanced wrapper** — add balanced line-wrapping (unit-tested) so no orphan lines.
3. [ ] **Portrait ASS generation** — `PortraitRenderer.build_ass()` from corrected segments;
unit test dimensions/positions/wrap.
4. [ ] **Portrait background generator** — themed 1080×1920 bg from style params + brand assets.
5. [ ] **Portrait title/end screens** — portrait variants in `video_generator.py`.
6. [ ] **Assemble portrait MP4** — ffmpeg concat/mux in `local_encoding_service` (or renderer);
integration test on a short fixture.
7. [ ] **Wire into orchestrator** — call renderer, upload to GCS `finals/` + Dropbox brand
folder, add to result/state; guard non-fatal.
8. [ ] **Tests** — unit + integration + regression (non-fatal; included in upload set); prod E2E.
9. [ ] **Version bump** + docs (`README.md` status, `ARCHITECTURE.md` data flow, LESSONS-LEARNED).
## Files to Create/Modify
| File | Action | Description |
|------|--------|-------------|
| `karaoke_gen/portrait/portrait_renderer.py` | Create | Portrait ASS + bg + title/end + assemble |
| `karaoke_gen/portrait/wrap.py` | Create | Balanced line-wrapping helper |
| `karaoke_gen/lyrics_transcriber/output/video_generator.py` | Modify | Portrait title/end screen variants |
| `backend/services/gce_encoding/main.py` | Modify | `run_render_portrait` op (reuses corrections/style loading) |
| `backend/workers/video_worker_orchestrator.py` | Modify | Trigger portrait op, upload GCS+Dropbox, record result, non-fatal guard |
| `tests/.../test_portrait_*.py` | Create | Unit + integration + regression |
| `frontend/e2e/production/portrait-output.spec.ts` | Create | Prod E2E: portrait in GCS+Dropbox, absent from Drive/YouTube |
| `pyproject.toml` | Modify | Version bump |
| `docs/README.md`, `docs/ARCHITECTURE.md`, `docs/LESSONS-LEARNED.md` | Modify | Status/data-flow/learnings |
## Testing Strategy
Per `docs/TESTING.md`:
- **Unit:** balanced wrapper (no orphans); portrait param selection; ASS output is 1080×1920,
centered, correct visible-line count; filename/suffix; result-dict inclusion.
- **Integration:** render a short portrait clip from fixture corrected-lyrics + a few seconds
of audio → assert 1080×1920, non-trivial duration, subtitle burn-in present, +faststart.
- **Regression:** portrait output added to result + upload set; a portrait-render exception
does NOT fail the job (mock renderer to raise, assert job still completes with landscape).
- **Production E2E (run-once):** finalise a real job; portrait MP4 present in GCS + Dropbox
brand folder, absent from Drive/YouTube.
## Open Questions
- [x] **#1 — Lyric data source at encode time.** RESOLVED: `gce_encoding/main.py::run_render_video`
already downloads the corrections JSON (`original_corrections_gcs_path` +
`updated_corrections_gcs_path`), applies user corrections → `CorrectionResult`, and runs
countdown processing. The portrait op reuses this exact loading. No new data path needed.
- [ ] **#2 — Background asset source.** Reuse the experiment's wordmark-crop approach vs a
clean brand PNG from the theme assets. Pick the cleaner brand-managed asset if one exists.
- [ ] **#3 — Filename/label** convention for the portrait file (proposed:
`… (Final Karaoke Portrait 1080x1920).mp4`).
## Rollback Plan
Feature is additive and non-fatal. Rollback = env flag `PORTRAIT_RENDER_ENABLED=false`
(gate the orchestrator call) or revert the PR; landscape pipeline is untouched. No schema or
infra changes required beyond the new output file.
@@ -0,0 +1,279 @@
# Encoding Worker — Mature Multi-Instance-Type Strategy (Plan)
**Date:** 2026-08-15
**Branch:** `feat/sess-20260815-1915-encoding-instance-type-diversity`
**Status:** SHIPPED (v0.195.0 #911 + v0.195.1 #912) — code + IaC + Packer merged & rolled out.
## Rollout outcome (2026-08-16)
- ✅ Backend 0.195.1 live on Cloud Run; encode path healthy (c4d primary `encoding-worker-a`
RUNNING 0.195.1 after c4d capacity returned to us-central1-c). `capacity_state` field live.
- ✅ Encoding-worker image rebuilt with the CPU-torch dep-bake; **validated end-to-end** — a fresh
`c4a` booted healthy in ~24s and encoded a preview in <6s (no first-job dep install).
- ✅ **All 8 fallback VMs provisioned** (stopped), so the full 6-family pool is live:
`-a`/`-b` (c4d), `-n2c`/`-n2f` (n2), `-c4a` (c4), `-n2da` (n2d), `-c2df` (c2d), `-n4db` (n4d).
Pulumi state consistent (`c4a`, orphaned by a killed apply, was `pulumi import`ed + reconciled).
Secret at **version 5** (8 entries, all with `machine_type`).
- ⏳→✅ **`c2df` + `n4db` were initially deferred** (created stopped VM still needs a one-time boot
allocation, so the 2026-08-15 stockout in zones f/b blocked provisioning). An autonomous
10-minute retry loop finished them on **2026-08-16 ~07:48** when zones f/b left stockout, and
added both to the secret (v5). **Historical note for a future crunch:** if a fallback VM is
missing/deleted, re-create it with the FULL Pulumi URNs (not an ellipsis) — e.g.
`cd infrastructure && pulumi up --yes --target 'urn:pulumi:prod::karaoke-gen-infrastructure::gcp:compute/instance:Instance::encoding-worker-fallback-c2df' --target 'urn:pulumi:prod::karaoke-gen-infrastructure::gcp:compute/instance:Instance::encoding-worker-fallback-n4db'`
(use the write-token env from the rollout notes) — then add it to the `encoding-worker-fallback-vms`
secret with its `machine_type`, but **never add a VM to the secret before it exists** (a
non-existent candidate → `get_vm_status` 404 → breaks warmup).
- Not done: measured `SPEED_RANK` benchmark run (arch-seeded; a 2026-08-16 benchmark was too noisy
to apply — see the CPU-platform-variance findings); MIG; reservations.
---
**Context:** memory `project_gen_encoding_instance_type_diversity` + `_worker_serialization` + `_machine_family_diversity` + `_wheel_deps_missing`
## Goal
Replace "c4d primary + single n2 fallback family" with a **ranked pool of ≥5 encode-capable
x86_64 instance types** and **availability-aware selection**, so a render never stalls even
when 2+ instance types are fully stocked out in us-central1 — while still **preferring the
fastest type (c4d) whenever it's available**. Resilience, not abandoning c4d.
---
## Current system (verified against code, 2026-08-15)
| Piece | File | Behaviour |
|---|---|---|
| Runtime candidate order | `backend/services/encoding_service.py::_build_worker_candidates` | `[primary] + ENCODING_WORKER_FALLBACK_VMS (secret order)` |
| Runtime fall-through | `backend/services/encoding_worker_manager.py::ensure_any_running` / `_ensure_any_running_once` | Iterates candidates; capacity/transient error → next; sets `active_override_*` on fallback success |
| Deploy green pick | `infrastructure/encoding-worker/deploy_promote.py::select_green_candidates` | secondary first, then fallbacks, **n2-before-c4d**, excluding current override |
| Idle shutdown | `infrastructure/functions/encoding_worker_idle/main.py::_parse_fallback_vms` | Stops idle primary/secondary/fallbacks (secret-driven) |
| IaC pool | `infrastructure/config.py::EncodingWorkerConfig.FALLBACKS` + `compute/encoding_worker_vm.py` | 2× c4d (a/b) + 2× n2 (n2c/n2f) fallbacks, each `{machine_type, disk_type}` |
| Secret | `encoding-worker-fallback-vms` | `[{vm,zone,ip}×4]` — **no machine_type today** |
| ffmpeg | `infrastructure/packer/scripts/provision.sh:59` | johnvansickle **amd64-static** → x86_64 only |
**Live state now:** primary `encoding-worker-a` (c4d, us-central1-c) @0.194.2 serving; no override
(c4d capacity currently back). Fallback fleet = c4d a/b (zones a,b) + n2 n2c/n2f (zones c,f).
2 machine families, 6 VMs total.
**Two order heuristics exist independently** (runtime = secret order; deploy = n2-first) — the
plan unifies them behind one pure, scored module.
---
## Ground-truth SKU menu (us-central1 a/b/c/f, all present)
x86_64, 32 vCPU, ≥32 GB, highcpu — verified via `gcloud compute machine-types list`:
| Type | vCPU | RAM | Silicon | Disk support | Pool notes |
|---|---|---|---|---|---|
| **c4d-highcpu-32** | 32 | 60 | AMD EPYC Turin (Zen5) | hyperdisk-balanced only | **current primary, fastest**; in the crunch |
| **c4-highcpu-32** | 32 | 64 | Intel Emerald Rapids | hyperdisk-balanced only | newest Intel perf tier, also in-demand |
| **n4-highcpu-32** | 32 | 64 | Intel Emerald Rapids (Titanium) | hyperdisk-balanced only | flexible/deep Intel |
| **n4d-highcpu-32** | 32 | 64 | AMD (Titanium) | hyperdisk-balanced only | flexible/deep AMD |
| **c2d-highcpu-32** | 32 | 64 | AMD Milan (Zen3) | pd-balanced | mature, **deep** |
| **n2d-highcpu-32** | 32 | 32 | AMD Rome/Milan | pd-balanced | **deep**, 32 GB floor |
| **n2-highcpu-32** | 32 | 32 | Intel Cascade/Ice Lake | pd-balanced | **current fallback**, floor |
Excluded:
- `n1-highcpu-32` = **28.8 GB** → below the 32 GB serialized-4K floor.
- `e2-highcpu-32` = 32 GB but E2 is cost/shared-tier, variable perf → not for fast finalization.
- `c4a-/n4a-highcpu-32` (Arm Axion, 64 GB) → **needs a separate Arm static ffmpeg** (provision.sh
bakes amd64 only). Documented as a future pool-doubler, NOT in this phase.
- `c3-highcpu-44` (44/88) / `c3d-highcpu-30` (30/59) — no exact 32-vCPU SKU; optional extra pools
if we want more breadth later (both support pd + hyperdisk).
### Chosen pool (≥5, spanning ≥3 independent silicon pools)
Two tiers by intent:
- **Tier A — fast, newest-gen (may stock out together in a crunch):** `c4d` (keep primary), `c4`, `n4d`
- **Tier B — deep, mature, independent pools (the insurance):** `c2d`, `n2d`, `n2` (already deployed)
= **6 types across 4 zones and 4 distinct silicon lineages** (AMD Turin, Intel Emerald, AMD
Milan, Intel Cascade, AMD Rome). Even if ALL of Tier A (all newest-gen, the crunch cohort) is
exhausted at once, three independent mature pools keep serving. Meets "no disruption if 2+ types
stocked out."
Zone spread (one type per zone where possible to avoid same-type-same-zone correlation):
c4d→c (primary, keep) · c4→a · n4d→b · c2d→f · n2d→a · n2→c/f (keep n2c/n2f).
---
## Design
### 1. Shared, scored preference module (single source of truth)
New pure module `backend/services/encoding_worker_preference.py` (importable by BOTH backend and
`infrastructure/encoding-worker/deploy_promote.py` — deploy already `sys.path`-inserts that dir;
we vendor/import the pure function so runtime + deploy can never drift).
```python
SPEED_RANK = { # lower = faster; seed from arch, refine with benchmark (§2)
"c4d-highcpu-32": 10,
"c4-highcpu-32": 20,
"n4d-highcpu-32": 30,
"c2d-highcpu-32": 50,
"n2d-highcpu-32": 60,
"n2-highcpu-32": 70,
}
COOLDOWN_SECONDS = 900 # a type that just stocked out is demoted for 15 min, then re-probed
def ordered_candidates(pool, capacity_state, now):
"""pool: [{vm,zone,ip,machine_type,kind}]. capacity_state: {type|type@zone: last_stockout_iso}.
Returns pool ranked fastest-first, but any candidate whose (type[,zone]) stocked out within
COOLDOWN is stable-partitioned to the back (keeping speed order within each group)."""
def speed(c): return SPEED_RANK.get(c["machine_type"], _infer_rank(c))
base = sorted(pool, key=speed) # fastest first — c4d stays top
cooled = lambda c: _recently_out(capacity_state, c, now, COOLDOWN_SECONDS)
return [c for c in base if not cooled(c)] + [c for c in base if cooled(c)]
```
Why this shape:
- **Fastest-first base order** → keeps preferring c4d/c4 whenever they're up (the whole reason c4d
was chosen). No behavioural change on a healthy day.
- **Cooldown demotion** → the "availability-aware" layer. When c4d throws
`ZONE_RESOURCE_POOL_EXHAUSTED`, we record it and stop paying the ~2 min-per-deploy /
per-render probe cost on a known-dead type — but we DON'T remove it, we re-probe after 15 min so
we snap back to c4d the moment capacity returns.
- **Deterministic + pure** → fully unit-testable; identical logic drives runtime and deploy.
Consumers:
- Runtime: `_build_worker_candidates` builds the pool (primary + all fallbacks, each carrying
`machine_type`) and calls `ordered_candidates`. `ensure_any_running` iterates unchanged.
- Deploy: `select_green_candidates` builds the pool minus the current `active_override_vm`
(guarantees a fresh green) and calls the SAME `ordered_candidates`. Drops the ad-hoc "n2-first"
rule — the cooldown state now handles "don't waste time on the stocked-out fast type."
### 2. Capacity-state feedback (availability awareness)
- New Firestore map on `config/encoding-worker`: `capacity_state = { "<type>@<zone>": "<iso>" }`.
- Write `<iso>=now` in `_ensure_any_running_once` when a candidate raises
`EncodingWorkerCapacityError`; clear a type's entry on a successful start of that type.
- Read in both consumers. Stale entries self-expire via COOLDOWN (no GC needed).
- Deploy's `Select & start green` step reads it too (already reads config), so CI stops probing a
dead fast type first during a sustained stockout.
- Backward-compatible: absent map ⇒ pure speed order (today's behaviour).
### 3. Benchmark to build the real ranking
Seed `SPEED_RANK` from architecture now; replace with measured wall-time. Harness:
- `infrastructure/encoding-worker/benchmark_types.py` (manual, not CI — it starts real VMs):
1. For each type: ensure its fallback VM is RUNNING + `/health` 200.
2. POST an identical **canonical 4K encode** (pin one real production render's inputs in GCS;
reuse the CI `test-assets` encode input but at full 4K/length for representativeness).
3. Poll `/status`; record ffmpeg wall-time (worker already times jobs). Median of 3.
4. Emit `ranking.json` → hand-copy medians into `SPEED_RANK` (as relative-to-c4d if preferred).
5. Stop all started VMs.
- Re-run occasionally / after a new type is added. Document expected order: Turin ≳ Emerald ≈
Genoa > Milan > Rome > Cascade (verify — don't assume).
### 4. IaC changes (Pulumi, purely additive)
- Extend `EncodingWorkerConfig.FALLBACKS` with the new entries, each `{suffix, zone_suffix,
machine_type, disk_type}`:
- `c4` → `{suffix:"c4a", zone:"a", machine:"c4-highcpu-32", disk:"hyperdisk-balanced"}`
- `n4d`→ `{suffix:"n4db", zone:"b", machine:"n4d-highcpu-32", disk:"hyperdisk-balanced"}`
- `c2d`→ `{suffix:"c2df", zone:"f", machine:"c2d-highcpu-32", disk:"pd-balanced"}`
- `n2d`→ `{suffix:"n2da", zone:"a", machine:"n2d-highcpu-32", disk:"pd-balanced"}`
(suffix names avoid collision; disk_type matches each family's capability — **c4/c4d/n4/n4d =
hyperdisk-balanced ONLY; c2d/n2/n2d = pd-balanced**. Getting this wrong = pulumi error.)
- **Do NOT touch** existing a/b/n2c/n2f entries or the c4d a/b Address `description` strings
(changing them forces an Address replace → cascades to replacing the c4d VM, which needs the
exact scarce capacity — see `_machine_family_diversity`). Verify `pulumi preview` shows only
`+N to create` (new IPs + new stopped VMs), zero replace.
- `create_encoding_worker_fallback_vms` already reads `machine_type`/`disk_type` per entry and
provisions `desired_status=TERMINATED` — no code change beyond the config list.
### 5. Secret schema: add `machine_type`
- `encoding-worker-fallback-vms` entries become `{vm,zone,ip,machine_type}` (append the 4 new
VMs' entries too). `machine_type` lets the preference module score without a name lookup.
- Backward-compatible reads: `_build_worker_candidates`, `_parse_fallback_vms`,
`select_green_candidates` treat `machine_type` as optional; when absent, `_infer_rank` derives
it from the vm-name/type substring (c4d/c4/n4d/c2d/n2d/n2). Primary/secondary machine_type
(c4d) is known from config.
- Carry `machine_type` through `EncodingWorkerCandidate` (add field, default None).
### 6. Wheel-deps + ffmpeg companion checks
- **ffmpeg:** all chosen types are x86_64 → baked amd64 static ffmpeg works unchanged. Arm
excluded precisely because it wouldn't. (No image change needed for this phase.)
- **Wheel deps** (`_wheel_deps_missing`): every fresh type VM hits first-render full-tree install;
already covered by `ensure_latest_wheel` (single-wheel + `verify_wheel_imports` + 900s×3). But
adding 4 fresh types multiplies first-render exposure → **strongly recommend the durable
follow-up: bake the full dep tree (CPU-only torch) into the Packer image** so every type boots
self-sufficient. One image-family rebuild covers all types (all share the `encoding-worker`
image). Track as a fast-follow; not strictly blocking because the runtime guard exists.
---
## Architecture assessment: per-VM start/stop vs MIG vs reservations
| Option | Verdict |
|---|---|
| **Per-VM start/stop (today) + broadened ranked pool** | **RECOMMENDED for this phase.** Low-risk incremental extension of the system just hardened in #908–#910. Reuses `ensure_any_running`, `deploy_promote`, idle-shutdown, the secret, static IPs, IP-addressed blue-green. Delivers the resilience goal. Cost when idle ≈ boot disk only (~$10/mo/VM × ~4 new = ~$40/mo). |
| **Regional MIG + instance flexibility** | **Right long-term shape per GCP guidance, but DEFER.** A MIG lists ranked machine types and lets GCP find capacity across type×zone natively (add-a-type = one policy line, no VM sprawl). BUT it invalidates the just-stabilized model: MIG instances have ephemeral names/IPs → the entire Firestore primary/secondary/override addressing (routes by IP) breaks → needs an internal LB / service discovery (extra hop, cost); blue-green deploy (IP swap) becomes rolling-update; on-demand scale-to-zero isn't native (keep a warm instance = cost, or bolt on a scaler); the 1-heavy-encode serialization + in-memory queue + client-resubmit assume a stable addressable worker. High blast radius days after stabilizing. **Trigger to revisit:** we need horizontal autoscaling (>1 concurrent worker per burst) OR per-VM sprawl becomes unmanageable (>~10 types). |
| **Reservation / CUD for a fast baseline** | **Optional lever — user's cost call.** A 1× `c4d-highcpu-32` reservation in us-central1-c *guarantees* the primary can always start, eliminating the exact stockout behind #908/#910. Purely additive (attach to the primary), no code change, instantly removable when demand subsides. Cost ≈ full on-demand of one c4d-highcpu-32 (~$650–800/mo) whether running or not; 1yr CUD lowers rate but commits spend. Given demand is "expected to subside," a *temporary* reservation during the crunch is the pragmatic middle. |
**Recommendation:** ship the broadened ranked pool + adaptive selection now (per-VM model);
offer a temporary c4d reservation as an independent toggle; keep MIG documented as the future
path with explicit triggers.
---
## Testing strategy (per `docs/TESTING.md`)
- **Unit (pure, highest value):** `encoding_worker_preference` — fastest-first ordering, cooldown
demotion + stable-partition, re-probe after COOLDOWN, missing-`machine_type` inference,
empty/degenerate pools. `test_deploy_promote.py` — updated to assert new ordering + fresh-green
exclusion + machine_type carry-through.
- **Unit:** `test_encoding_worker_manager.py` — multi-type fall-through, capacity_state
write-on-stockout / clear-on-success.
- **Infra:** `test_encoding_worker_config.py` — every FALLBACK entry has a disk_type valid for its
family (hyperdisk-only vs pd), unique VM/IP names, expected zone spread.
- **Emulator/integration:** capacity_state Firestore round-trip; idle-shutdown parses new entries.
- **Prod E2E (post-deploy, once):** start each new type, `/health` 200, run canonical encode,
confirm output — codifies that each type actually encodes. (Doubles as the benchmark seed run.)
## Rollout (operator, needs WRITE creds — my ADC is read-only)
1. Merge code (preference module + consumers + tests) — no infra yet, behaviour identical (pool
still 2 families until secret grows).
2. `cd infrastructure && pulumi up` (stack prod) → creates 4 new IPs + 4 stopped VMs. **Verify
`+8 to create`, zero replace** before applying.
3. Add a new `encoding-worker-fallback-vms` secret version = existing 4 + 4 new entries, each with
`machine_type`. Cloud Run svc + `video-encoding-job` + idle fn read `:latest` (cycle/redeploy to
pick up).
4. Run `benchmark_types.py` → fill real `SPEED_RANK` medians → small follow-up PR.
5. (Optional) `bake full deps into Packer` fast-follow. (Optional) create c4d reservation.
## Decisions (locked 2026-08-15)
1. **Pool size — 6 types** (c4d, c4, n4d, c2d, n2d, n2). 4 silicon lineages × 4 zones.
2. **Reservation — NO.** Rely on the broadened pool; no guaranteed c4d baseline (revisit only if
stockouts persist). No reservation/CUD in this effort.
3. **MIG — DEFER.** Ship per-VM start/stop; MIG documented as future path with triggers above.
4. **Packer dep-bake — INCLUDE IN THIS EFFORT.** Bake the full CPU-only-torch dep tree into the
`encoding-worker` image so all 4 new type VMs (and existing ones) boot self-sufficient, instead
of relying on first-render `ensure_latest_wheel`. See scope note below.
### Scope note: Packer dep-bake (now in-scope)
- `infrastructure/packer/scripts/provision.sh` currently bakes only
`fastapi uvicorn google-cloud-storage aiofiles aiohttp packaging` (per `_wheel_deps_missing`).
Extend it to `pip install` the full karaoke-gen dependency set with **CPU-only torch**
(`--index-url https://download.pytorch.org/whl/cpu` for torch) into `/opt/encoding-worker/venv`
at build time — the encode/render path needs the generator→correction/langchain chain
(tenacity etc.) but NOT CUDA, so CPU torch keeps the image far smaller than the ~6.4 GB GPU tree.
- Keep `ensure_latest_wheel` as the runtime code-update path (it still upgrades the karaoke-gen
wheel itself on each new version), but a fresh VM will now already have the whole dep tree →
first render no longer risks a partial/timed-out full-tree install.
- Requires: image rebuild (`build-runner-images.yml`/Packer) + a Pulumi apply that repoints the
`encoding-worker` image family. Re-apply the `gcloud compute disks update` IOPS tune after any
rebuild that recreates disks (per `encoding_worker_vm.py` comments).
- **Sequencing:** rebuild the image FIRST (all types boot self-sufficient), then `pulumi up` the
new VMs against the new image family, then grow the secret. This way the 4 new types never hit
the fragile first-render install path at all.
- Verify amd64 CPU-torch wheels resolve for Python 3.13 during the Packer build (fail the build if
`verify_wheel_imports`-equivalent import check fails, so a broken image never ships).
@@ -0,0 +1,136 @@
# Plan: Serialize encoding-worker jobs (OOM fix) + resubmit lost renders
## Context
**Incident (2026-08-15 ~17:57 UTC):** Three Arctic Monkeys renders (`a3f340a2`, `374dec26`,
`590630c0`) all failed within ~2 min with `lost contact with worker after 5 consecutive poll
failures: Encoding job … not found`.
**Root cause (confirmed from live forensics):**
- Both c4d primary encoding workers (`encoding-worker-a/b`) are TERMINATED (c4d Spot stockout in
us-central1 — a recurring known issue). All render traffic funnels onto the single running
fallback `encoding-worker-fallback-n2f` (n2-highcpu-32, **32 GB** — half the c4d's 60 GB).
- The worker runs `ThreadPoolExecutor(max_workers=4)` → up to 4 heavy ffmpeg encodes in parallel.
The Arctic Monkeys batch put **3 concurrent 4K encodes** on n2f (~17.9 + ~10.6 + ~2 GB ≈ 30 GB).
- **17:57:36 kernel OOM-killer fired** (`global_oom, task=ffmpeg`) → systemd restarted
`encoding-worker.service` (`NRestarts=1`) → the in-memory `jobs` dict was wiped → every poll
returned `404 not found` → all three renders failed. No resubmit happened.
**Why the existing safety nets didn't catch it:**
- `ThreadPoolExecutor(max_workers=4)` is the only concurrency gate; nothing bounds it by memory.
ffmpeg already saturates all cores for one job, so parallel encodes add **no throughput** — only
multiplied memory. (active_url points at a single worker at a time, so the fleet was already
1-worker-wide; serializing to 1-at-a-time costs no real throughput today.)
- The worker's restart-recovery (`persistence.mark_orphans_failed_on_startup`) is meant to convert a
post-restart poll into a clean `failed` with `restart_failure_code`, but it relies on Firestore
persistence that is likely disabled on the fallback VM (IAM) — so polls got a raw 404 instead.
- The client (`wait_for_completion`) treats a 404 the same whether the job never existed or vanished
mid-run; after 5 polls it gives up with "lost contact" and **never resubmits**.
**Desired outcome (per user):** the encoding worker processes **one heavy job at a time** (queue the
rest), and the orchestrator **retries on error** so a worker restart/OOM/deploy no longer loses a
render. Scope: worker serialization + client resubmit now; multi-worker load-balancing is a
follow-up.
## Key files & current behavior
- `backend/services/gce_encoding/main.py` — the GCE worker FastAPI app.
`executor = ThreadPoolExecutor(max_workers=4)` (line 32). `process_job` (encode, ~1075),
`process_render_video_job` (render, ~1184), `process_preview_job` (preview, ~1154) all call
`run_in_executor(executor, …)`. `/encode`, `/render-video`, `/encode-preview`, `/status`,
`/health`. Jobs tracked in in-memory `jobs` dict; `queue_length`/`active_jobs` already derived
from `pending`/`running` status.
- `backend/services/gce_encoding/persistence.py` — `JobStatePersister`;
`mark_orphans_failed_on_startup` sets `restart_failure_code = "encoding_worker_restart"`.
- `backend/services/encoding_service.py` — client. `wait_for_completion` (~595) with
`MAX_CONSECUTIVE_POLL_FAILURES` tolerance; `get_job_status` raises `RuntimeError("… not found")`
on 404 (589); `encode_videos` (~693) submit+wait.
- `backend/workers/video_worker_orchestrator.py` — `encoding_backend.encode()` call (~498) and the
existing **stale-cache resubmit** block (521-548) that generates `{job_id}_retry_{hex8}` — the
pattern to generalize.
## Approach
### 1. Worker: split into a serialized heavy lane + a light lane (the OOM fix)
In `main.py`, replace the single pool with two:
- `HEAVY_CONCURRENCY = int(os.getenv("ENCODING_HEAVY_CONCURRENCY", "1"))`;
`heavy_executor = ThreadPoolExecutor(max_workers=HEAVY_CONCURRENCY)` — used **only** for the
heavy ffmpeg work: `run_encoding` (in `process_job`) and `render_video` (in
`process_render_video_job`). Default 1 = one heavy job at a time on every machine type → OOM-proof.
- `light_executor = ThreadPoolExecutor(max_workers=2)` — used for `ensure_latest_wheel` (pip, light)
and `run_preview_encoding` (interactive previews). Keeps review snappy and never blocks wheel
installs behind a long encode. (1 heavy ~18 GB + a preview ~2 GB + base ≈ 22 GB < 32 GB.)
Submitted-but-not-yet-started heavy jobs remain `status="pending"` (existing behavior) → the
`heavy_executor` work queue **is** the encode queue; `/health` `queue_length` already surfaces it.
Add `queue_position` to the `/status` response (cheap: index among `pending`+`running` heavy jobs)
so clients can wait through the queue without tripping the encode timeout (see #3).
### 2. Worker: expose the restart code so the client can act on it
Add optional `restart_failure_code: Optional[str]` (and `queue_position: Optional[int]`) to the
`JobStatus` pydantic model (line 115) and include them in the `/status` payload. `persistence` already
writes `restart_failure_code` into the job dict on restart-recovery.
### 3. Client: detect a *lost* job vs a transient blip; wait through the queue
In `encoding_service.py` `wait_for_completion`:
- Track "have we seen this job run" (any successful poll, or `status in {running, complete}` /
`progress > 0`). If a `404 not found` arrives **after** the job was seen, raise a new
`EncodingJobLostError` **immediately** (the job was wiped — don't burn 5 polls, don't mislabel as
unrecoverable). A 404 *before* the job is ever seen keeps the current 5-poll tolerance (submit/poll
race).
- If a terminal `status=="failed"` carries `restart_failure_code=="encoding_worker_restart"`, raise
`EncodingJobLostError` too.
- While `status=="pending"` (queued, not yet started), keep polling without counting toward the
encode `timeout` — only start the encode clock once the job is `running`. This makes deep queues
safe under concurrency=1 without an enormous fixed timeout (cap total queue wait separately, e.g.
a generous `queue_timeout`).
### 4. Orchestrator: bounded resubmit on a lost job
In `video_worker_orchestrator.py`, wrap the `encoding_backend.encode()` call (~498) in a bounded loop
(`ENCODING_RESUBMIT_MAX`, default 2 extra attempts): on `EncodingJobLostError`, mint a fresh
`{job_id}_retry_{hex8}` (reuse the 525-527 pattern), log, and resubmit. Generalize the existing
stale-cache block (521-548) so the lost/restart and stale-cache cases share one resubmit path. This
is the "retry on error" safety net and works **even if worker persistence is disabled** (the client
detects the vanished job itself).
### 5. Infra (supporting, verify-then-fix): fallback-VM Firestore IAM
Confirm whether `encoding_worker_jobs` writes are actually failing on `encoding-worker-fallback-n2f`
(persister self-disables on IAM error). If so, grant the fallback VMs' service account Firestore
write via Pulumi so restart-recovery produces a clean `failed`+`restart_failure_code` there too.
Belt-and-suspenders behind #3/#4. Read-only verify first; only a Pulumi PR if broken.
### 6. Step 0 — immediate operational recovery (run on approval, before/independent of the ship)
Re-render the three stuck jobs via `POST /api/jobs/{id}/retry` (admin token; resumes from the render
stage since review is complete), **serialized** — one at a time, waiting for each to reach a terminal
state and checking worker load between — because the deployed worker still runs concurrency=4 until
the fix ships. Order: `a3f340a2`, `374dec26`, `590630c0`.
## Tests
- **Worker** (`backend/tests/test_gce_encoding_*` / new): with `run_encoding` stubbed to block,
submit 3 `/encode` jobs and assert only 1 is `running` while the rest are `pending` (serialized);
assert a `/encode-preview` runs concurrently with a heavy job (light lane); assert `/status`
returns `queue_position`.
- **Client** (`backend/tests/test_encoding_service.py`): `wait_for_completion` raises
`EncodingJobLostError` on 404-after-seen and on `restart_failure_code`; still tolerates 404s
before first success (keep existing poll-failure test green); pending status doesn't trip the
encode timeout.
- **Orchestrator** (`backend/tests/test_video_worker_orchestrator*`): a lost job triggers a resubmit
with a new `_retry_` id and then succeeds; resubmit attempts are bounded.
## Verification (end-to-end)
1. `make test 2>&1 | tail -n 500` — all green.
2. Deploy the worker wheel; `curl /health` shows the new version and `queue_length`.
3. **Real-world repro:** submit the 3 Arctic Monkeys renders **concurrently** (the exact OOM
trigger). Expect: one `running`, others `pending`; peak RSS bounded (~1 heavy ffmpeg);
`journalctl -k` shows **no OOM**; capture `systemctl show encoding-worker -p NRestarts`
*before* the run and assert it does **not increase** (the worker already carries a
nonzero `NRestarts` from the incident); all three complete. This doubles as Step 0
recovery once the fix is live.
4. Simulate a mid-render worker restart (`systemctl restart encoding-worker` during an encode) and
confirm the orchestrator resubmits (`_retry_` id in logs) and the job completes instead of failing.
## Out of scope (follow-ups)
- Fleet-level load-balancing / dispatching queued jobs across multiple running workers (the throughput
lever once c4d capacity or additional n2 workers are added).
- Restoring c4d primary capacity / machine-family strategy (tracked separately —
`project_gen_encoding_machine_family_diversity`).
@@ -0,0 +1,141 @@
# Handoff: Investigate prod finalization CPU efficiency / utilization — 2026-08-16
**Status:** OPEN investigation (not started). Written for a fresh Claude session —
self-contained; all facts you need are inlined below or in the linked repo docs.
**Origin:** surfaced by the encode-worker multi-instance-type benchmark
(`docs/archive/2026-08-15-encoding-instance-type-diversity-plan.md`; benchmark
baselines inlined under "Reproducing the benchmark" below).
## The question
Prod video **finalization** (the `/encode` path that produces
`mp4_4k_lossless + mp4_4k_lossy + mp4_720p`) — is it using the 32-vCPU
`*-highcpu-32` workers efficiently? The trigger was the stale
`"ffmpeg_threads": 8` (with a comment referencing the retired `c4-standard-8`)
in the job config, which looked like it might cap ffmpeg to 8 of 32 cores.
**Static analysis has already answered the first-order question (do NOT re-derive
it — verify then move on):** `ffmpeg_threads` is **dead config**. It is set at
`backend/workers/video_worker.py:131` but **no code reads it** (grep for consumers
returns nothing; `run_encoding()`'s `EncodingConfig(...)` at
`backend/services/gce_encoding/main.py:1111` never passes it), and the actual
finalization ffmpeg commands in `backend/services/local_encoding_service.py`
(`encode_all_formats` → `encode_lossless_mp4`/`encode_lossy_mp4`/`encode_720p`,
around lines 343 / 396 / 471) carry **no `-threads` flag at all** → ffmpeg falls
back to its default (`-threads 0`, i.e. auto ≈ all cores). So finalization is
**almost certainly NOT capped at 8 cores**; the "leaving 75% idle" fear is likely
unfounded. (Separate, unrelated paths that DO hardcode threads — don't confuse
them: `main.py:372` uses `-threads 8` in the **preview** `/encode-preview`
480×270 path; `local_preview_encoding_service.py:310` uses `-threads 0`.)
So this is now a **narrower efficiency + cleanup** task, not a "fix the cap" task.
## What to determine (in order)
1. **Confirm the static finding empirically** (x264's `-threads 0` "auto" is a
heuristic — it does NOT always scale to all cores; historically it caps frame
threads, with diminishing returns past ~16). Drive a real finalization and
capture **process-level** evidence, not just host-wide load:
- the **deployed ffmpeg argv** for each format (`ps -eo pid,args | grep ffmpeg`
on the worker mid-encode, or add a log line) — confirm no `-threads` and see
what x264 chose;
- **per-process / per-thread** CPU% and RSS (`top -H -p <ffmpeg-pid>`,
`pidstat -t -p <pid> 2`), NOT `mpstat -P ALL` alone — host-wide utilization
can't tell an 8-thread cap from serial `encode_all_formats` stages or
unrelated work;
- **per-format stage timings** (which of lossless/lossy/720p dominates).
Run all of this against the SAME worker you drive the encode to (see the
binding note in "Reproducing the benchmark").
2. **Check whether the 3 formats encode SERIALLY or in PARALLEL** in
`encode_all_formats` (`backend/services/local_encoding_service.py`). If serial,
wall-time ≈ sum of the three even if each saturates the cores — the real lever
may be **overlapping independent format encodes** rather than more threads. But
see the RAM constraint below before parallelizing.
3. **Decide the fix (likely small) and validate it:**
- **Cleanup regardless:** remove the dead `ffmpeg_threads` field + stale comment
at `backend/workers/video_worker.py:131` (it misleads; that is the "documentation-
only" close-out CodeRabbit flagged). If you'd rather *use* it, wire it through
`EncodingConfig` → the `local_encoding_service.py` ffmpeg commands as an explicit
`-threads`; otherwise delete it.
- If step 1 shows real idle cores (x264 auto under-scales), the win is an explicit
high `-threads` (or `-x264-params threads=N`) or overlapping formats — validate
with a before/after re-benchmark on the SAME input+VM.
- If step 1 shows cores already saturated, close this out as "already efficient;
removed dead config" and stop.
## Hard constraints — do NOT regress these
- **Heavy-lane serialization stays.** `ENCODING_HEAVY_CONCURRENCY=1` (one heavy
encode at a time per worker) exists because 3 **concurrent** 4K encodes OOM-killed
the 32 GB worker (incident 2026-08-15; full write-up in `docs/LESSONS-LEARNED.md`
→ "Concurrent encodes OOM-killed the worker → lost renders").
Raising *threads within a single encode* is **orthogonal** to that and does not
reintroduce concurrency — but it DOES raise a single encode's **peak RAM** (more
parallel ffmpeg slices / parallel format encodes). Watch RSS on a 32 GB floor VM
(n2/n2d fallbacks are 32 GB; c4d/c4/n4d are 60–64 GB). A single 4K lossless encode
was ~18 GB; leave headroom.
- **Lossless 4K is the heavy one** (`pcm_s16le`, huge intermediate) — profile that
format specifically.
## Reproducing the benchmark (for before/after numbers)
The benchmark used a real completed job's inputs as a canonical `/encode` input.
It was deleted after the run (`gs://…/bench/` cleaned up). To recreate:
```bash
J=gs://karaoke-gen-storage-nomadkaraoke/jobs/ffc17eb7 # "Glen Campbell - A Better Place"
I=gs://karaoke-gen-storage-nomadkaraoke/bench/encode-input
gsutil -q cp "$J/videos/with_vocals.mkv" "$I/videos/with_vocals.mkv" # 119 MB rendered 4K karaoke video
gsutil -q cp "$J/screens/title.png" "$I/screens/title.png"
gsutil -q cp "$J/screens/end.png" "$I/screens/end.png"
gsutil -q cp "$J/stems/instrumental_clean.flac" "$I/stems/instrumental_clean.flac"
gsutil -q cp "$J/style/style_params.json" "$I/style/style_params.json"
gsutil -q cp "$J/lyrics/karaoke.ass" "$I/lyrics/karaoke.ass"
```
**Bind the encode to the worker you observe.** Pick ONE stopped fallback (e.g.
`encoding-worker-fallback-c4a`, us-central1-a), start it, and send BOTH the
`/encode` POST and the `/status` polls **directly to that worker's external IP**
(`http://<IP>:8080/…`, not through the backend/`api.nomadkaraoke.com` — the
backend may route to a different active worker). SSH the SAME VM for the
process-level probes in step 1, so the CPU/RSS you measure is the encode you drove.
Get the IP: `gcloud compute instances describe <vm> --zone=<z>
--format='value(networkInterfaces[0].accessConfigs[0].natIP)'`.
`POST http://<IP>:8080/encode` body (`X-API-Key` from
`gcloud secrets versions access latest --secret=encoding-worker-api-key`):
```json
{"job_id":"cpu-probe-1","input_gcs_path":"gs://…/bench/encode-input/",
"output_gcs_path":"gs://…/bench/out/probe/",
"encoding_config":{"formats":["mp4_4k_lossless","mp4_4k_lossy","mp4_720p"],
"base_name":"Glen Campbell - A Better Place","artist":"Glen Campbell",
"title":"A Better Place","instrumental_selection":"clean",
"existing_instrumental":null}}
```
(`ffmpeg_threads` deliberately omitted from the body above — it is dead config;
see "The question".) Poll `GET http://<IP>:8080/status/{job_id}` to `complete`. Baseline medians from 2026-08-16 (full
3-format finalization of this ~4-min song; the runs sent `ffmpeg_threads:8` in the
body but the worker ignored it, so these reflect ffmpeg's default all-core threading):
c4-Emerald ≈ **139s**, n2d-Milan ≈ **139s**, n2-CascadeLake ≈ **247s**, n2-IceLake
≈ **92s** (c4d unmeasured — could not start a 2nd c4d in the stockout). The huge
n2 spread — **92s vs 247s for the identical `n2-highcpu-32` SKU** — is because n2
spans Intel Ice Lake (fast) and Cascade Lake (slow) and GCE assigns either; that
intra-family variance exceeds the between-family differences. Separate actionable
finding: pin `min_cpu_platform` (e.g. "Intel Ice Lake" / "AMD Milan") on n2/n2d
fallbacks for predictable speed, or rank them lower to reflect the gamble. Also
note the counterintuitive result that c4 (newest Intel Emerald) ≈ n2d (Milan) and
did NOT beat n2 Ice Lake for this lossless-4K-heavy workload — so "newest = fastest"
does not hold here; measure, don't assume.
**Operational hygiene:** benchmark VMs are stopped fallbacks — start, probe, then
STOP them (never the live-serving primary; the idle-shutdown fn also handles it).
Delete `gs://…/bench/**` when done. Auth for VM start/stop: `gcloud` as
`admin@nomadkaraoke.com`.
## Expected outcome
Either: (a) confirm CPU is already saturated (`ffmpeg_threads` is dead config) →
close this out and just fix the stale comment; or (b) confirm an ~2–4× idle-core
gap → raise threads / parallelize formats, validate the speedup and RAM headroom,
ship it. Bump `pyproject.toml` version; if the fix is in the wheel's
`LocalEncodingService`, it ships via the normal wheel → `ensure_latest_wheel` path.
+2 -1
View File
@@ -6,6 +6,7 @@ import { useSearchParams } from "next/navigation"
import { api, Job, getAccessToken } from "@/lib/api"
import { useAuth } from "@/lib/auth"
import { useAdminSettings } from "@/lib/admin-settings"
import { parseServerDate } from "@/lib/utils"
import { useJobNotifications, useVisibilityRefresh } from "@/hooks/use-notifications"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
@@ -293,7 +294,7 @@ function AppPageContent() {
</p>
<p className="text-xs" style={{ color: 'var(--text-muted)' }}>
{user.referred_by_code && <>Referred with code <strong>{user.referred_by_code}</strong> · </>}
Expires {new Date(user.referral_discount_expires_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}
Expires {parseServerDate(user.referral_discount_expires_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}
</p>
</div>
<button
@@ -2,7 +2,7 @@
import { useState, useEffect, useMemo } from "react"
import { useTranslations } from 'next-intl'
import { api } from "@/lib/api"
import { api, ApiError } from "@/lib/api"
import {
ExtendedAudioSearchResult,
groupResults,
@@ -14,8 +14,9 @@ import {
checkFilenameMismatch,
} from "@/lib/audio-search-utils"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog"
import { Loader2, Music2, ChevronDown, ChevronUp, Lightbulb } from "lucide-react"
import { Loader2, Music2, ChevronDown, ChevronUp, Lightbulb, Search, Youtube, Upload } from "lucide-react"
import { ResultCostChip } from "./ResultCostChip"
// Version from pyproject.toml (single source of truth)
@@ -26,10 +27,11 @@ interface AudioSearchDialogProps {
open: boolean
onClose: () => void
onSelect: () => void
searchArtist?: string
searchTitle?: string
}
export function AudioSearchDialog({ jobId, open, onClose, onSelect, searchTitle }: AudioSearchDialogProps) {
export function AudioSearchDialog({ jobId, open, onClose, onSelect, searchArtist, searchTitle }: AudioSearchDialogProps) {
const t = useTranslations('audioSearch')
const [results, setResults] = useState<ExtendedAudioSearchResult[]>([])
const [isLoading, setIsLoading] = useState(true)
@@ -38,33 +40,57 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect, searchTitle
const [expandedCategories, setExpandedCategories] = useState<Set<string>>(new Set())
const [showGuidance, setShowGuidance] = useState(false)
// Debug: Log component version on mount
useEffect(() => {
console.log(`[AudioSearchDialog] App version: ${APP_VERSION}`)
}, [])
// Editable search terms + recovery actions (edit → re-search, or provide own audio).
const [editArtist, setEditArtist] = useState(searchArtist || "")
const [editTitle, setEditTitle] = useState(searchTitle || "")
const [isResearching, setIsResearching] = useState(false)
const [actionError, setActionError] = useState("")
// Fallback (own audio) — auto-opens when a search returns nothing.
const [fallbackMode, setFallbackMode] = useState<"url" | "upload" | null>(null)
const [youtubeUrl, setYoutubeUrl] = useState("")
const [uploadFile, setUploadFile] = useState<File | null>(null)
const [isSubmittingSource, setIsSubmittingSource] = useState(false)
// The title used for filename-mismatch badges tracks the (possibly edited) terms.
const effectiveTitle = editTitle || searchTitle
// Load results when dialog opens
useEffect(() => {
if (open) {
console.log(`[AudioSearchDialog v${APP_VERSION}] Dialog opened for job: ${jobId}`)
loadResults()
setExpandedCategories(new Set()) // Reset expanded state
setShowGuidance(false)
setFallbackMode(null)
setActionError("")
setYoutubeUrl("")
setUploadFile(null)
// Seed editable terms from props; refined again from the API response below.
setEditArtist(searchArtist || "")
setEditTitle(searchTitle || "")
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [open, jobId])
async function loadResults() {
setIsLoading(true)
setError("")
try {
console.log(`[AudioSearchDialog v${APP_VERSION}] Loading results...`)
const data = await api.getAudioSearchResults(jobId)
console.log(`[AudioSearchDialog v${APP_VERSION}] Raw API response:`, data)
console.log(`[AudioSearchDialog v${APP_VERSION}] Results count: ${data.results?.length || 0}`)
setResults((data.results || []) as ExtendedAudioSearchResult[])
// Prefer the job's stored search terms so the edit fields reflect reality.
if (data.artist) setEditArtist(data.artist)
if (data.title) setEditTitle(data.title)
if ((data.results || []).length === 0) setFallbackMode(null)
} catch (err: any) {
console.error(`[AudioSearchDialog v${APP_VERSION}] Failed to load search results:`, err)
setError(err.message || "Failed to load search results")
// A parked job with no cached results returns 400 — that's the dead-end we
// are fixing, so render it as the empty state (with the refine bar), not a
// red banner. Any other failure (network / 5xx / session) is a real error.
if (err instanceof ApiError && err.status === 400) {
setResults([])
} else {
setResults([])
setError(err?.message || t('selectFailed'))
}
} finally {
setIsLoading(false)
}
@@ -72,8 +98,6 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect, searchTitle
// Group results by category
const groupedResults = useMemo(() => groupResults(results), [results])
// Count total categories
const totalCategories = groupedResults.length
async function handleSelect(index: number) {
@@ -84,25 +108,74 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect, searchTitle
onSelect()
onClose()
} catch (err: any) {
console.error("Failed to select audio:", err)
setError(err.message || "Failed to select audio")
setError(err.message || t('selectFailed'))
} finally {
setIsSelecting(null)
}
}
async function handleResearch() {
if (!editArtist.trim() || !editTitle.trim() || isResearching) return
setIsResearching(true)
setActionError("")
setError("")
try {
const data = await api.researchAudio(jobId, { artist: editArtist.trim(), title: editTitle.trim() })
const fresh = (data.results || []) as ExtendedAudioSearchResult[]
setResults(fresh)
setExpandedCategories(new Set())
// Nothing found again → auto-open the own-audio fallback; results → close it.
setFallbackMode(prev => (fresh.length === 0 ? (prev ?? "url") : null))
} catch (err: any) {
setActionError(err.message || t('researchFailed'))
} finally {
setIsResearching(false)
}
}
async function handleProvideUrl() {
const url = youtubeUrl.trim()
if (!url || isSubmittingSource) return
setIsSubmittingSource(true)
setActionError("")
try {
await api.provideUrlForJob(jobId, url)
onSelect()
onClose()
} catch (err: any) {
setActionError(err.message || t('urlFailed'))
} finally {
setIsSubmittingSource(false)
}
}
async function handleUpload() {
if (!uploadFile || isSubmittingSource) return
setIsSubmittingSource(true)
setActionError("")
try {
await api.attachUploadToJob(jobId, uploadFile)
onSelect()
onClose()
} catch (err: any) {
setActionError(err.message || t('uploadFailed'))
} finally {
setIsSubmittingSource(false)
}
}
function toggleCategory(category: string) {
setExpandedCategories(prev => {
const next = new Set(prev)
if (next.has(category)) {
next.delete(category)
} else {
next.add(category)
}
if (next.has(category)) next.delete(category)
else next.add(category)
return next
})
}
const hasResults = results.length > 0
const busy = isResearching || isSubmittingSource
return (
<Dialog open={open} onOpenChange={(open) => !open && onClose()}>
<DialogContent className="max-w-7xl w-[95vw] max-h-[90vh] flex flex-col bg-card border-border !p-0 gap-0 overflow-hidden">
@@ -116,8 +189,113 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect, searchTitle
</DialogTitle>
</div>
{/* Guidance header (collapsed by default) */}
{!isLoading && results.length > 0 && (
{/* Refine bar: edit the search terms and search again. Always available so a
wrong-track match or a no-results dead-end is never a trap. */}
<div className="px-4 py-2 border-b border-border bg-secondary/30 shrink-0 space-y-2">
<div className="flex flex-col sm:flex-row sm:items-end gap-2">
<div className="flex-1 min-w-0">
<label className="block text-[10px] text-muted-foreground mb-0.5">{t('artistLabel')}</label>
<Input
value={editArtist}
onChange={(e) => setEditArtist(e.target.value)}
onKeyDown={(e) => { if (e.key === 'Enter') handleResearch() }}
placeholder={t('artistLabel')}
disabled={busy}
className="h-8 text-xs bg-background"
/>
</div>
<div className="flex-1 min-w-0">
<label className="block text-[10px] text-muted-foreground mb-0.5">{t('titleLabel')}</label>
<Input
value={editTitle}
onChange={(e) => setEditTitle(e.target.value)}
onKeyDown={(e) => { if (e.key === 'Enter') handleResearch() }}
placeholder={t('titleLabel')}
disabled={busy}
className="h-8 text-xs bg-background"
/>
</div>
<Button
size="sm"
onClick={handleResearch}
disabled={busy || !editArtist.trim() || !editTitle.trim()}
className="h-8 text-xs bg-[var(--brand-pink)] hover:bg-[var(--brand-pink-hover)] text-white shrink-0"
>
{isResearching ? <Loader2 className="w-3.5 h-3.5 animate-spin mr-1" /> : <Search className="w-3.5 h-3.5 mr-1" />}
{t('searchAgain')}
</Button>
</div>
{/* Provide-your-own-audio fallback */}
<div className="flex items-center gap-3 text-[10px]">
<button
onClick={() => setFallbackMode(fallbackMode === "url" ? null : "url")}
className={`flex items-center gap-1 hover:text-foreground transition-colors ${fallbackMode === "url" ? 'text-[var(--brand-pink)]' : 'text-muted-foreground'}`}
>
<Youtube className="w-3 h-3" /> {t('pasteUrl')}
</button>
<button
onClick={() => setFallbackMode(fallbackMode === "upload" ? null : "upload")}
className={`flex items-center gap-1 hover:text-foreground transition-colors ${fallbackMode === "upload" ? 'text-[var(--brand-pink)]' : 'text-muted-foreground'}`}
>
<Upload className="w-3 h-3" /> {t('uploadFileAction')}
</button>
</div>
{fallbackMode === "url" && (
<div className="flex flex-col sm:flex-row gap-2">
<Input
type="url"
value={youtubeUrl}
onChange={(e) => setYoutubeUrl(e.target.value)}
onKeyDown={(e) => { if (e.key === 'Enter') handleProvideUrl() }}
placeholder={t('urlPlaceholder')}
disabled={busy}
className="h-8 text-xs bg-background flex-1"
/>
<Button
size="sm"
onClick={handleProvideUrl}
disabled={busy || !youtubeUrl.trim()}
className="h-8 text-xs bg-[var(--brand-pink)] hover:bg-[var(--brand-pink-hover)] text-white shrink-0"
>
{isSubmittingSource ? <Loader2 className="w-3.5 h-3.5 animate-spin mr-1" /> : null}
{t('useThisUrl')}
</Button>
</div>
)}
{fallbackMode === "upload" && (
<div className="flex flex-col sm:flex-row gap-2 items-stretch sm:items-center">
<label className="flex-1 border border-dashed border-border rounded px-2 py-1.5 text-[10px] text-muted-foreground cursor-pointer hover:border-[var(--brand-pink)] truncate">
<input
type="file"
accept=".mp3,.wav,.flac,.m4a,.ogg,audio/*"
onChange={(e) => setUploadFile(e.target.files?.[0] || null)}
className="sr-only"
disabled={busy}
/>
{uploadFile ? uploadFile.name : t('chooseFile')}
</label>
<Button
size="sm"
onClick={handleUpload}
disabled={busy || !uploadFile}
className="h-8 text-xs bg-[var(--brand-pink)] hover:bg-[var(--brand-pink-hover)] text-white shrink-0"
>
{isSubmittingSource ? <Loader2 className="w-3.5 h-3.5 animate-spin mr-1" /> : null}
{t('useThisFile')}
</Button>
</div>
)}
{actionError && (
<p className="text-[10px] text-red-400">{actionError}</p>
)}
</div>
{/* Guidance header (collapsed by default) — only meaningful when there are results */}
{!isLoading && hasResults && (
<div className="px-4 py-1.5 border-b border-border bg-secondary/30">
<button
onClick={() => setShowGuidance(!showGuidance)}
@@ -148,12 +326,13 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect, searchTitle
{isLoading ? (
<div className="flex-1 flex items-center justify-center py-12">
<Loader2 className="w-5 h-5 animate-spin text-muted-foreground" />
<span className="ml-2 text-sm text-muted-foreground">Loading...</span>
<span className="ml-2 text-sm text-muted-foreground">{t('loading')}</span>
</div>
) : results.length === 0 ? (
<div className="flex-1 flex flex-col items-center justify-center py-12 text-muted-foreground">
) : !hasResults ? (
<div className="flex-1 flex flex-col items-center justify-center py-12 text-muted-foreground px-6 text-center">
<Music2 className="w-8 h-8 mb-2 opacity-50" />
<p className="text-sm">{t('noAudioSources')}</p>
<p className="text-sm font-medium text-foreground">{t('noAudioSources')}</p>
<p className="text-xs mt-1.5 max-w-md">{t('noResultsHelp')}</p>
</div>
) : (
<div className="flex-1 overflow-y-auto min-h-0 p-4">
@@ -190,7 +369,7 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect, searchTitle
{/* Results in category */}
<div className="divide-y divide-slate-700/50">
{displayResults.map((result) => {
const mismatch = searchTitle ? checkFilenameMismatch(searchTitle, result) : null
const mismatch = effectiveTitle ? checkFilenameMismatch(effectiveTitle, result) : null
const hasMismatch = mismatch?.isMismatch ?? false
return (
@@ -226,7 +405,7 @@ export function AudioSearchDialog({ jobId, open, onClose, onSelect, searchTitle
)}
{hasMismatch && (
<span
title={`Expected "${searchTitle}" but filename is "${mismatch!.filename}"${mismatch!.suggestedTrack ? ` (looks like "${mismatch!.suggestedTrack}")` : ''}`}
title={`Expected "${effectiveTitle}" but filename is "${mismatch!.filename}"${mismatch!.suggestedTrack ? ` (looks like "${mismatch!.suggestedTrack}")` : ''}`}
className="text-[8px] px-1 py-0.5 rounded font-medium bg-yellow-600/20 text-yellow-400 cursor-help"
>
{t('wrongTrack')}
@@ -0,0 +1,141 @@
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { AudioSearchDialog } from '../AudioSearchDialog'
import { api, ApiError } from '@/lib/api'
jest.mock('@/lib/api', () => {
class ApiError extends Error {
status: number
constructor(message: string, status: number) {
super(message)
this.status = status
}
}
return {
ApiError,
api: {
getAudioSearchResults: jest.fn(),
selectAudioResult: jest.fn(),
researchAudio: jest.fn(),
provideUrlForJob: jest.fn(),
attachUploadToJob: jest.fn(),
},
}
})
const mockApi = api as jest.Mocked<typeof api>
const aResult = (index = 0) => ({
index,
title: 'The View From the Afternoon',
artist: 'Arctic Monkeys',
provider: 'RED',
is_lossless: true,
seeders: 30,
target_file: 'The View From the Afternoon.flac',
quality_data: {},
})
describe('AudioSearchDialog recovery UX', () => {
beforeEach(() => {
jest.clearAllMocks()
})
it('renders no-results help and the refine bar when the job has no sources', async () => {
mockApi.getAudioSearchResults.mockResolvedValue({
status: 'success', job_id: 'j1', results: [], total_results: 0,
artist: 'Arctic Monkeys', title: 'The View From the Afternoon',
} as any)
render(
<AudioSearchDialog jobId="j1" open onClose={jest.fn()} onSelect={jest.fn()}
searchArtist="Arctic Monkeys" searchTitle="The View From the Afternoon" />
)
await screen.findByText('No audio sources found')
expect(screen.getByText(/couldn't find any audio sources/i)).toBeInTheDocument()
// Editable terms seeded from the API response
expect(screen.getByDisplayValue('Arctic Monkeys')).toBeInTheDocument()
expect(screen.getByDisplayValue('The View From the Afternoon')).toBeInTheDocument()
expect(screen.getByRole('button', { name: /search again/i })).toBeInTheDocument()
})
it('re-searches with edited terms and shows the fresh results', async () => {
mockApi.getAudioSearchResults.mockResolvedValue({
status: 'success', job_id: 'j1', results: [], total_results: 0,
artist: 'Arctic Monkeys', title: 'The View From teh Afternoon',
} as any)
mockApi.researchAudio.mockResolvedValue({
status: 'awaiting_selection', job_id: 'j1', results: [aResult(0)], total_results: 1, results_count: 1,
} as any)
render(
<AudioSearchDialog jobId="j1" open onClose={jest.fn()} onSelect={jest.fn()}
searchArtist="Arctic Monkeys" searchTitle="The View From teh Afternoon" />
)
await screen.findByText('No audio sources found')
const titleInput = screen.getByDisplayValue('The View From teh Afternoon')
fireEvent.change(titleInput, { target: { value: 'The View From the Afternoon' } })
fireEvent.click(screen.getByRole('button', { name: /search again/i }))
await waitFor(() => {
expect(mockApi.researchAudio).toHaveBeenCalledWith('j1', {
artist: 'Arctic Monkeys', title: 'The View From the Afternoon',
})
})
// Results now render (RED category chip + a Select button)
await waitFor(() => expect(screen.getByRole('button', { name: /select/i })).toBeInTheDocument())
})
it('submits a provided URL and advances the job', async () => {
mockApi.getAudioSearchResults.mockResolvedValue({
status: 'success', job_id: 'j1', results: [], total_results: 0,
} as any)
mockApi.provideUrlForJob.mockResolvedValue({ status: 'success', job_id: 'j1', message: 'ok' } as any)
const onSelect = jest.fn()
const onClose = jest.fn()
render(
<AudioSearchDialog jobId="j1" open onClose={onClose} onSelect={onSelect}
searchArtist="Arctic Monkeys" searchTitle="Riot Van" />
)
await screen.findByText('No audio sources found')
fireEvent.click(screen.getByRole('button', { name: /paste url/i }))
const urlInput = await screen.findByPlaceholderText(/youtube\.com/i)
fireEvent.change(urlInput, { target: { value: 'https://youtube.com/watch?v=abc' } })
fireEvent.click(screen.getByRole('button', { name: /use this url/i }))
await waitFor(() =>
expect(mockApi.provideUrlForJob).toHaveBeenCalledWith('j1', 'https://youtube.com/watch?v=abc')
)
await waitFor(() => expect(onSelect).toHaveBeenCalled())
expect(onClose).toHaveBeenCalled()
})
it('treats a 400 (no cached results) as an empty state, not a red error', async () => {
mockApi.getAudioSearchResults.mockRejectedValue(new ApiError('No search results available', 400))
render(
<AudioSearchDialog jobId="j1" open onClose={jest.fn()} onSelect={jest.fn()}
searchArtist="Arctic Monkeys" searchTitle="The View From the Afternoon" />
)
await screen.findByText('No audio sources found')
expect(screen.queryByText('No search results available')).not.toBeInTheDocument()
})
it('surfaces a non-400 (network/500) failure as an error banner', async () => {
mockApi.getAudioSearchResults.mockRejectedValue(new ApiError('Server exploded', 500))
render(
<AudioSearchDialog jobId="j1" open onClose={jest.fn()} onSelect={jest.fn()}
searchArtist="Arctic Monkeys" searchTitle="The View From the Afternoon" />
)
// Empty state still renders (refine bar available), but the real error shows too.
await screen.findByText('No audio sources found')
expect(screen.getByText('Server exploded')).toBeInTheDocument()
})
})
@@ -7,6 +7,7 @@ import { Button } from '@/components/ui/button'
import { api, CreditPackage, getReferralInterstitial } from '@/lib/api'
import { useAuth } from '@/lib/auth'
import { useTranslations, useLocale } from 'next-intl'
import { parseServerDate } from '@/lib/utils'
interface BuyCreditsDialogProps {
open: boolean
@@ -101,7 +102,7 @@ export function BuyCreditsDialog({ open, onClose }: BuyCreditsDialogProps) {
)}
{user.referral_discount_expires_at && (
<p className="text-green-600/70 dark:text-green-400/70 text-xs mt-1">
{tRef('appliedAtCheckout')} · {tRef('expires', { date: new Date(user.referral_discount_expires_at).toLocaleDateString(locale, { year: 'numeric', month: 'short', day: 'numeric' }) })}
{tRef('appliedAtCheckout')} · {tRef('expires', { date: parseServerDate(user.referral_discount_expires_at).toLocaleDateString(locale, { year: 'numeric', month: 'short', day: 'numeric' }) })}
</p>
)}
</div>
+3 -1
View File
@@ -14,6 +14,7 @@ import { BuyCreditsDialog } from "@/components/credits/BuyCreditsDialog"
import { getJobStep, formatStepIndicator, getJobProgressPercent, isWaitingForEncodingCapacity, isVisibilityChangeInProgress } from "@/lib/job-status"
import { useAuth } from "@/lib/auth"
import { useDurationConfirm } from "@/hooks/use-duration-confirm"
import { parseServerDate } from "@/lib/utils"
/**
* StatusIndicator component - Shows step-based progress with visual indicator
@@ -113,7 +114,7 @@ export function JobCard({ job, onRefresh, showAdminControls }: JobCardProps) {
onNeedRefresh: onRefresh,
})
const createdAt = new Date(job.created_at).toLocaleString()
const createdAt = parseServerDate(job.created_at).toLocaleString()
const isInteractive = job.status === "awaiting_review" ||
job.status === "in_review" ||
job.status === "awaiting_instrumental_selection" ||
@@ -279,6 +280,7 @@ export function JobCard({ job, onRefresh, showAdminControls }: JobCardProps) {
open={showAudioSearch}
onClose={() => setShowAudioSearch(false)}
onSelect={onRefresh}
searchArtist={job.artist}
searchTitle={job.title}
/>
+2 -1
View File
@@ -3,6 +3,7 @@
import { useEffect, useState } from "react"
import { api, JobLog } from "@/lib/api"
import { Loader2, AlertCircle } from "lucide-react"
import { parseServerDate } from "@/lib/utils"
interface JobLogsProps {
jobId: string
@@ -73,7 +74,7 @@ export function JobLogs({ jobId, limit = 50 }: JobLogsProps) {
style={log.level !== "ERROR" && log.level !== "WARNING" && log.level !== "INFO" ? { color: 'var(--text-muted)' } : undefined}
>
<span className="shrink-0" style={{ color: 'var(--text-muted)', opacity: 0.7 }}>
{new Date(log.timestamp).toLocaleTimeString()}
{parseServerDate(log.timestamp).toLocaleTimeString()}
</span>
<span className="shrink-0 font-semibold w-12">
{log.level}
@@ -84,6 +84,7 @@ export function BulkBatchProgress({ batchId, onStartAnother, onJobsChanged }: Bu
<AudioSearchDialog
jobId={selectingJob.job_id}
open={true}
searchArtist={selectingJob.artist}
searchTitle={selectingJob.title}
onClose={() => setSelectingJob(null)}
onSelect={() => {
@@ -17,6 +17,7 @@ import {
Loader2, Banknote, Settings,
} from 'lucide-react';
import ReferralToolsDialog from './ReferralToolsDialog';
import { parseServerDate } from '@/lib/utils';
function formatCents(cents: number): string {
return `$${(cents / 100).toFixed(2)}`;
@@ -505,7 +506,7 @@ export default function ReferralDashboard() {
<div className="space-y-2">
{data.recent_payouts.map((p) => (
<div key={p.id} className="flex justify-between text-sm">
<span style={{ color: 'var(--text-muted)' }}>{new Date(p.created_at).toLocaleDateString()}</span>
<span style={{ color: 'var(--text-muted)' }}>{parseServerDate(p.created_at).toLocaleDateString()}</span>
<span className="font-mono">{formatCents(p.amount_cents)}</span>
</div>
))}
+48
View File
@@ -0,0 +1,48 @@
import { parseServerDate } from '../utils'
describe('parseServerDate', () => {
it('treats an offset-less ISO timestamp (naive UTC) as UTC', () => {
// Backend serializes datetime.utcnow() with no timezone designator.
// This should be interpreted as UTC, NOT local time.
const d = parseServerDate('2026-08-14T18:10:25')
expect(d.getTime()).toBe(Date.UTC(2026, 7, 14, 18, 10, 25))
})
it('treats an offset-less timestamp with fractional seconds as UTC', () => {
const d = parseServerDate('2026-08-14T18:10:25.123456')
expect(d.getTime()).toBe(Date.UTC(2026, 7, 14, 18, 10, 25, 123))
})
it('respects an explicit Z (UTC) designator', () => {
const d = parseServerDate('2026-08-14T18:10:25Z')
expect(d.getTime()).toBe(Date.UTC(2026, 7, 14, 18, 10, 25))
})
it('respects an explicit +00:00 offset', () => {
const d = parseServerDate('2026-08-14T18:10:25+00:00')
expect(d.getTime()).toBe(Date.UTC(2026, 7, 14, 18, 10, 25))
})
it('respects a non-UTC offset', () => {
// 18:10 at +02:00 == 16:10 UTC
const d = parseServerDate('2026-08-14T18:10:25+02:00')
expect(d.getTime()).toBe(Date.UTC(2026, 7, 14, 16, 10, 25))
})
it('passes through Date instances unchanged', () => {
const original = new Date(Date.UTC(2026, 7, 14, 18, 10, 25))
expect(parseServerDate(original)).toBe(original)
})
it('accepts epoch milliseconds', () => {
const ms = Date.UTC(2026, 7, 14, 18, 10, 25)
expect(parseServerDate(ms).getTime()).toBe(ms)
})
it('does not append Z to non-ISO-datetime strings (date-only)', () => {
// Date-only strings are already parsed as UTC by the Date constructor;
// appending Z would be invalid. Ensure we leave them alone.
const d = parseServerDate('2026-08-14')
expect(d.getTime()).toBe(Date.UTC(2026, 7, 14))
})
})
+57
View File
@@ -326,6 +326,10 @@ export interface AudioSearchResponse {
job_id: string;
results: AudioSearchResult[];
total_results: number;
results_count?: number;
// Present on GET /results and POST /research — the job's current search terms.
artist?: string;
title?: string;
message?: string;
}
@@ -1440,6 +1444,59 @@ export const api = {
return handleResponse(response);
},
/**
* Re-run the audio search for a parked job, optionally with edited
* artist/title. Empty results are a normal 200 (no sources found), not an error.
*/
async researchAudio(
jobId: string,
edits?: { artist?: string; title?: string }
): Promise<AudioSearchResponse> {
const response = await fetch(`${API_BASE_URL}/api/audio-search/${jobId}/research`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ artist: edits?.artist, title: edits?.title }),
});
return handleResponse(response);
},
/**
* Attach a YouTube/yt-dlp URL to a parked job and start processing.
* Manual fallback when audio search finds nothing usable.
*/
async provideUrlForJob(
jobId: string,
url: string
): Promise<{ status: string; job_id: string; message: string }> {
const response = await fetch(`${API_BASE_URL}/api/audio-search/${jobId}/provide-url`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ url }),
});
return handleResponse(response);
},
/**
* Attach an uploaded audio file to a parked job:
* 1) request a signed upload URL, 2) PUT the file, 3) mark complete.
*/
async attachUploadToJob(jobId: string, file: File): Promise<{ status: string; message: string }> {
const contentType = file.type || 'application/octet-stream';
const signed = await fetch(`${API_BASE_URL}/api/audio-search/${jobId}/attach-upload-url`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ filename: file.name, content_type: contentType }),
});
const { upload_url, gcs_path } = await handleResponse<{ upload_url: string; gcs_path: string }>(signed);
await this.uploadFileToSignedUrl(upload_url, file, contentType);
const done = await fetch(`${API_BASE_URL}/api/audio-search/${jobId}/attach-upload-complete`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ gcs_path }),
});
return handleResponse(done);
},
/**
* Get job logs
*/
+25
View File
@@ -4,3 +4,28 @@ import { twMerge } from 'tailwind-merge'
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
/**
* Parse a timestamp returned by the backend into a Date.
*
* Backend timestamps (job.created_at, log timestamps, etc.) are UTC but are
* frequently serialized from naive `datetime.utcnow()` values, producing ISO
* strings with NO timezone offset (e.g. "2026-08-14T18:10:25.123456"). The
* JS `Date` constructor parses such offset-less date-time strings as *local*
* time, which displays the raw UTC wall-clock unconverted (off by the viewer's
* UTC offset). To fix this we treat offset-less timestamps as UTC by appending
* "Z". Strings that already carry an offset ("Z" or "+HH:MM"/"-HH:MM") — or that
* aren't the expected ISO date-time shape — are passed through unchanged.
*/
export function parseServerDate(value: string | number | Date): Date {
if (value instanceof Date) return value
if (typeof value === 'number') return new Date(value)
// ISO date-time with no timezone designator → assume UTC.
// Matches "YYYY-MM-DDTHH:MM:SS" with optional fractional seconds and no
// trailing Z / ±HH:MM offset.
if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?$/.test(value)) {
return new Date(`${value}Z`)
}
return new Date(value)
}
+16 -1
View File
@@ -760,7 +760,22 @@
"views": "{count} مشاهدات",
"moreVersions": "+{count} المزيد",
"select": "تحديد",
"creditCost": "{credits} رصيد"
"creditCost": "{credits} رصيد",
"chooseFile": "اختر ملفاً صوتياً (MP3، WAV، FLAC، M4A، OGG)",
"noResultsHelp": "لم نتمكن من العثور على أي مصادر صوتية. حاول تعديل اسم الفنان أو العنوان أعلاه وابحث مرة أخرى، أو أضف ملفك الصوتي باستخدام رابط أو برفع ملف.",
"pasteUrl": "لصق الرابط",
"researchFailed": "فشل البحث. يرجى المحاولة مرة أخرى.",
"searchAgain": "البحث مرة أخرى",
"selectFailed": "فشل تحديد الصوت",
"uploadFailed": "فشل الرفع. يرجى المحاولة مرة أخرى.",
"urlFailed": "تعذر استخدام هذا الرابط. جرب مصدراً آخر.",
"urlPlaceholder": "https://youtube.com/watch?v=...",
"useThisFile": "استخدم هذا الملف",
"useThisUrl": "استخدم هذا الرابط",
"artistLabel": "فنان",
"loading": "جاري التحميل...",
"titleLabel": "العنوان",
"uploadFileAction": "رفع ملف"
},
"audioEditor": {
"loading": "جاري تحميل محرر الصوت...",
+16 -1
View File
@@ -760,7 +760,22 @@
"views": "{count} visualitzacions",
"moreVersions": "+{count} més",
"select": "Selecciona",
"creditCost": "{credits} crèdits"
"creditCost": "{credits} crèdits",
"chooseFile": "Tria un fitxer d'àudio (MP3, WAV, FLAC, M4A, OGG)",
"noResultsHelp": "No hem pogut trobar cap font d'àudio. Prova d'editar l'artista o el títol de dalt i torna a cercar, o afegeix el teu propi àudio amb un URL o pujant un fitxer.",
"pasteUrl": "Enganxa l'URL",
"researchFailed": "La cerca ha fallat. Si us plau, torna-ho a provar.",
"searchAgain": "Torna a cercar",
"selectFailed": "No s'ha pogut seleccionar l'àudio",
"uploadFailed": "La pujada ha fallat. Si us plau, torna-ho a provar.",
"urlFailed": "No s'ha pogut utilitzar aquest URL. Prova una altra font.",
"urlPlaceholder": "https://youtube.com/watch?v=...",
"useThisFile": "Utilitza aquest fitxer",
"useThisUrl": "Utilitza aquest URL",
"artistLabel": "Artista",
"loading": "Carregant...",
"titleLabel": "Títol",
"uploadFileAction": "Puja un fitxer"
},
"audioEditor": {
"loading": "Carregant l'editor d'àudio...",
+16 -1
View File
@@ -760,7 +760,22 @@
"views": "{count} zhlédnutí",
"moreVersions": "+{count} dalších",
"select": "Vybrat",
"creditCost": "{credits} kreditů"
"creditCost": "{credits} kreditů",
"chooseFile": "Vyber zvukový soubor (MP3, WAV, FLAC, M4A, OGG)",
"noResultsHelp": "Nepodařilo se nám najít žádné zdroje zvuku. Zkus upravit interpreta nebo název výše a hledat znovu, případně přidej vlastní zvuk pomocí URL adresy nebo nahráním souboru.",
"pasteUrl": "Vlož URL",
"researchFailed": "Hledání selhalo. Zkus to prosím znovu.",
"searchAgain": "Hledat znovu",
"selectFailed": "Nepodařilo se vybrat zvuk",
"uploadFailed": "Nahrávání selhalo. Zkus to prosím znovu.",
"urlFailed": "Tuto URL adresu nelze použít. Zkus jiný zdroj.",
"urlPlaceholder": "https://youtube.com/watch?v=...",
"useThisFile": "Použít tento soubor",
"useThisUrl": "Použít tuto URL",
"artistLabel": "Umělec",
"loading": "Načítám...",
"titleLabel": "Název",
"uploadFileAction": "Nahrát soubor"
},
"audioEditor": {
"loading": "Načítání editoru zvuku...",
+16 -1
View File
@@ -760,7 +760,22 @@
"views": "{count} visninger",
"moreVersions": "+{count} mere",
"select": "Vælg",
"creditCost": "{credits} kreditter"
"creditCost": "{credits} kreditter",
"chooseFile": "Vælg en lydfil (MP3, WAV, FLAC, M4A, OGG)",
"noResultsHelp": "Vi kunne ikke finde nogen lydkilder. Prøv at ændre kunstneren eller titlen ovenfor og søg igen, eller tilføj din egen lyd via en URL eller filupload.",
"pasteUrl": "Indsæt URL",
"researchFailed": "Søgning mislykkedes. Prøv igen.",
"searchAgain": "Søg igen",
"selectFailed": "Kunne ikke vælge lyd",
"uploadFailed": "Upload mislykkedes. Prøv igen.",
"urlFailed": "Kunne ikke bruge den URL. Prøv en anden kilde.",
"urlPlaceholder": "https://youtube.com/watch?v=...",
"useThisFile": "Brug denne fil",
"useThisUrl": "Brug denne URL",
"artistLabel": "Kunstner",
"loading": "Indlæser...",
"titleLabel": "Titel",
"uploadFileAction": "Upload fil"
},
"audioEditor": {
"loading": "Indlæser lydredigeringsprogram...",
+16 -1
View File
@@ -760,7 +760,22 @@
"views": "{count} Aufrufe",
"moreVersions": "+{count} weitere",
"select": "Auswählen",
"creditCost": "{credits} Guthaben"
"creditCost": "{credits} Guthaben",
"chooseFile": "Wähle eine Audiodatei (MP3, WAV, FLAC, M4A, OGG)",
"noResultsHelp": "Wir konnten keine Audioquellen finden. Versuche, den Künstler oder Titel oben zu bearbeiten und erneut zu suchen, oder verwende dein eigenes Audio per URL oder Datei-Upload.",
"pasteUrl": "URL einfügen",
"researchFailed": "Suche fehlgeschlagen. Bitte versuche es erneut.",
"searchAgain": "Erneut suchen",
"selectFailed": "Audio konnte nicht ausgewählt werden",
"uploadFailed": "Upload fehlgeschlagen. Bitte versuche es erneut.",
"urlFailed": "Diese URL konnte nicht verwendet werden. Versuche eine andere Quelle.",
"urlPlaceholder": "https://youtube.com/watch?v=...",
"useThisFile": "Diese Datei verwenden",
"useThisUrl": "Diese URL verwenden",
"artistLabel": "Künstler",
"loading": "Laden...",
"titleLabel": "Titel",
"uploadFileAction": "Datei hochladen"
},
"audioEditor": {
"loading": "Lade Audio-Editor...",
+16 -1
View File
@@ -760,7 +760,22 @@
"views": "{count} προβολές",
"moreVersions": "+{count} ακόμα",
"select": "Επιλογή",
"creditCost": "{credits} μονάδες"
"creditCost": "{credits} μονάδες",
"chooseFile": "Επίλεξε ένα αρχείο ήχου (MP3, WAV, FLAC, M4A, OGG)",
"noResultsHelp": "Δεν μπορέσαμε να βρούμε πηγές ήχου. Δοκίμασε να επεξεργαστείς τον καλλιτέχνη ή τον τίτλο παραπάνω και να αναζητήσεις ξανά, ή πρόσθεσε τον δικό σου ήχο με ένα URL ή ανεβάζοντας ένα αρχείο.",
"pasteUrl": "Επικόλληση URL",
"researchFailed": "Η αναζήτηση απέτυχε. Παρακαλώ δοκίμασε ξανά.",
"searchAgain": "Αναζήτησε ξανά",
"selectFailed": "Αποτυχία επιλογής ήχου",
"uploadFailed": "Το ανέβασμα απέτυχε. Παρακαλώ δοκίμασε ξανά.",
"urlFailed": "Δεν ήταν δυνατή η χρήση αυτού του URL. Δοκίμασε μια άλλη πηγή.",
"urlPlaceholder": "https://youtube.com/watch?v=...",
"useThisFile": "Χρησιμοποίησε αυτό το αρχείο",
"useThisUrl": "Χρησιμοποίησε αυτό το URL",
"artistLabel": "Καλλιτέχνης",
"loading": "Φόρτωση...",
"titleLabel": "Τίτλος",
"uploadFileAction": "Ανέβασμα αρχείου"
},
"audioEditor": {
"loading": "Φόρτωση επεξεργαστή ήχου...",
+16 -1
View File
@@ -763,7 +763,22 @@
"views": "{count} views",
"moreVersions": "+{count} more",
"select": "Select",
"creditCost": "{credits} credits"
"creditCost": "{credits} credits",
"loading": "Loading...",
"artistLabel": "Artist",
"titleLabel": "Title",
"searchAgain": "Search again",
"pasteUrl": "Paste URL",
"uploadFileAction": "Upload file",
"urlPlaceholder": "https://youtube.com/watch?v=...",
"useThisUrl": "Use this URL",
"useThisFile": "Use this file",
"chooseFile": "Choose an audio file (MP3, WAV, FLAC, M4A, OGG)",
"noResultsHelp": "We couldn't find any audio sources. Try editing the artist or title above and searching again, or provide your own audio with a URL or file upload.",
"selectFailed": "Failed to select audio",
"researchFailed": "Search failed. Please try again.",
"urlFailed": "Couldn't use that URL. Try another source.",
"uploadFailed": "Upload failed. Please try again."
},
"audioEditor": {
"loading": "Loading audio editor...",
+16 -1
View File
@@ -760,7 +760,22 @@
"views": "{count} vistas",
"moreVersions": "+{count} más",
"select": "Seleccionar",
"creditCost": "{credits} créditos"
"creditCost": "{credits} créditos",
"chooseFile": "Elige un archivo de audio (MP3, WAV, FLAC, M4A, OGG)",
"noResultsHelp": "No pudimos encontrar ninguna fuente de audio. Intenta editar el artista o el título arriba y buscar de nuevo, o proporciona tu propio audio con una URL o subiendo un archivo.",
"pasteUrl": "Pegar URL",
"researchFailed": "Error en la búsqueda. Por favor, inténtalo de nuevo.",
"searchAgain": "Buscar de nuevo",
"selectFailed": "Error al seleccionar el audio",
"uploadFailed": "Error en la subida. Por favor, inténtalo de nuevo.",
"urlFailed": "No se pudo usar esa URL. Intenta con otra fuente.",
"urlPlaceholder": "https://youtube.com/watch?v=...",
"useThisFile": "Usar este archivo",
"useThisUrl": "Usar esta URL",
"artistLabel": "Artista",
"loading": "Cargando...",
"titleLabel": "Título",
"uploadFileAction": "Subir archivo"
},
"audioEditor": {
"loading": "Cargando editor de audio...",
+16 -1
View File
@@ -760,7 +760,22 @@
"views": "{count} katselukertaa",
"moreVersions": "+{count} muuta",
"select": "Valitse",
"creditCost": "{credits} krediittiä"
"creditCost": "{credits} krediittiä",
"chooseFile": "Valitse äänitiedosto (MP3, WAV, FLAC, M4A, OGG)",
"noResultsHelp": "Emme löytäneet äänilähteitä. Kokeile muokata esittäjää tai kappaleen nimeä yllä ja hae uudelleen, tai lisää oma äänitiedostosi URL-osoitteella tai lataamalla tiedosto.",
"pasteUrl": "Liitä URL-osoite",
"researchFailed": "Haku epäonnistui. Yritä uudelleen.",
"searchAgain": "Hae uudelleen",
"selectFailed": "Äänitiedoston valinta epäonnistui",
"uploadFailed": "Lataus epäonnistui. Yritä uudelleen.",
"urlFailed": "Tuota URL-osoitetta ei voitu käyttää. Kokeile toista lähdettä.",
"urlPlaceholder": "https://youtube.com/watch?v=...",
"useThisFile": "Käytä tätä tiedostoa",
"useThisUrl": "Käytä tätä URL-osoitetta",
"artistLabel": "Artisti",
"loading": "Ladataan...",
"titleLabel": "Nimi",
"uploadFileAction": "Lataa tiedosto"
},
"audioEditor": {
"loading": "Ladataan äänieditoria...",
+16 -1
View File
@@ -760,7 +760,22 @@
"views": "{count} vues",
"moreVersions": "+{count} de plus",
"select": "Sélectionner",
"creditCost": "{credits} crédits"
"creditCost": "{credits} crédits",
"chooseFile": "Choisis un fichier audio (MP3, WAV, FLAC, M4A, OGG)",
"noResultsHelp": "Nous n'avons trouvé aucune source audio. Essaie de modifier l'artiste ou le titre ci-dessus et de chercher à nouveau, ou ajoute ton propre audio via une URL ou en important un fichier.",
"pasteUrl": "Coller l'URL",
"researchFailed": "La recherche a échoué. Réessaie.",
"searchAgain": "Chercher à nouveau",
"selectFailed": "Impossible de sélectionner l'audio",
"uploadFailed": "L'importation a échoué. Réessaie.",
"urlFailed": "Impossible d'utiliser cette URL. Essaie une autre source.",
"urlPlaceholder": "https://youtube.com/watch?v=...",
"useThisFile": "Utiliser ce fichier",
"useThisUrl": "Utiliser cette URL",
"artistLabel": "Artiste",
"loading": "Chargement...",
"titleLabel": "Titre",
"uploadFileAction": "Importer un fichier"
},
"audioEditor": {
"loading": "Chargement de l'éditeur audio...",
+16 -1
View File
@@ -760,7 +760,22 @@
"views": "{count} צפיות",
"moreVersions": "+{count} נוספים",
"select": "בחר",
"creditCost": "{credits} קרדיטים"
"creditCost": "{credits} קרדיטים",
"chooseFile": "בחירת קובץ שמע (MP3, WAV, FLAC, M4A, OGG)",
"noResultsHelp": "לא הצלחנו למצוא מקורות שמע. נסו לערוך את שם האמן או השיר למעלה ולחפש שוב, או הוסיפו שמע משלכם באמצעות קישור או העלאת קובץ.",
"pasteUrl": "הדבקת קישור",
"researchFailed": "החיפוש נכשל. אנא נסו שוב.",
"searchAgain": "חיפוש מחדש",
"selectFailed": "בחירת השמע נכשלה",
"uploadFailed": "ההעלאה נכשלה. אנא נסו שוב.",
"urlFailed": "לא הצלחנו להשתמש בקישור הזה. נסו מקור אחר.",
"urlPlaceholder": "https://youtube.com/watch?v=...",
"useThisFile": "שימוש בקובץ זה",
"useThisUrl": "שימוש בקישור זה",
"artistLabel": "אומן",
"loading": "טוען...",
"titleLabel": "כותרת",
"uploadFileAction": "העלאת קובץ"
},
"audioEditor": {
"loading": "טוען עורך אודיו...",
+16 -1
View File
@@ -760,7 +760,22 @@
"views": "{count} व्यूज़",
"moreVersions": "+{count} और",
"select": "चुनो",
"creditCost": "{credits} क्रेडिट"
"creditCost": "{credits} क्रेडिट",
"chooseFile": "एक ऑडियो फ़ाइल चुनो (MP3, WAV, FLAC, M4A, OGG)",
"noResultsHelp": "हमें कोई ऑडियो स्रोत नहीं मिला। ऊपर दिए गए कलाकार या शीर्षक को बदलकर फिर से खोजने की कोशिश करो, या URL या फ़ाइल अपलोड करके अपना खुद का ऑडियो जोड़ो।",
"pasteUrl": "URL पेस्ट करो",
"researchFailed": "खोज विफल रही। कृपया फिर से कोशिश करो।",
"searchAgain": "फिर से खोजो",
"selectFailed": "ऑडियो चुनने में विफल",
"uploadFailed": "अपलोड विफल रहा। कृपया फिर से कोशिश करो।",
"urlFailed": "उस URL का उपयोग नहीं हो सका। किसी दूसरे स्रोत की कोशिश करो।",
"urlPlaceholder": "https://youtube.com/watch?v=...",
"useThisFile": "इस फ़ाइल का उपयोग करो",
"useThisUrl": "इस URL का उपयोग करो",
"artistLabel": "कलाकार",
"loading": "लोड हो रहा है...",
"titleLabel": "टाइटल",
"uploadFileAction": "फ़ाइल अपलोड करो"
},
"audioEditor": {
"loading": "ऑडियो एडिटर लोड हो रहा है...",
+16 -1
View File
@@ -760,7 +760,22 @@
"views": "{count} pregleda",
"moreVersions": "+{count} više",
"select": "Odaberi",
"creditCost": "{credits} kredita"
"creditCost": "{credits} kredita",
"chooseFile": "Odaberi audio datoteku (MP3, WAV, FLAC, M4A, OGG)",
"noResultsHelp": "Nismo uspjeli pronaći nijedan audio izvor. Pokušaj izmijeniti izvođača ili naslov iznad i pretražiti ponovno, ili dodaj vlastiti audio putem URL-a ili učitavanjem datoteke.",
"pasteUrl": "Zalijepi URL",
"researchFailed": "Pretraživanje nije uspjelo. Pokušaj ponovno.",
"searchAgain": "Pretraži ponovno",
"selectFailed": "Odabir audija nije uspio",
"uploadFailed": "Učitavanje nije uspjelo. Pokušaj ponovno.",
"urlFailed": "Nismo mogli upotrijebiti taj URL. Pokušaj s drugim izvorom.",
"urlPlaceholder": "https://youtube.com/watch?v=...",
"useThisFile": "Koristi ovu datoteku",
"useThisUrl": "Koristi ovaj URL",
"artistLabel": "Izvođač",
"loading": "Učitavanje...",
"titleLabel": "Naslov",
"uploadFileAction": "Prenesi datoteku"
},
"audioEditor": {
"loading": "Učitavanje audio uređivača...",
+16 -1
View File
@@ -760,7 +760,22 @@
"views": "{count} megtekintés",
"moreVersions": "+{count} további",
"select": "Kiválasztás",
"creditCost": "{credits} kredit"
"creditCost": "{credits} kredit",
"chooseFile": "Válassz egy hangfájlt (MP3, WAV, FLAC, M4A, OGG)",
"noResultsHelp": "Nem találtunk hangforrást. Próbáld meg módosítani a fenti előadót vagy címet, és keress újra, vagy adj meg egy saját hangfájlt URL-en keresztül vagy feltöltéssel.",
"pasteUrl": "URL beillesztése",
"researchFailed": "A keresés nem sikerült. Kérlek, próbáld újra.",
"searchAgain": "Új keresés",
"selectFailed": "Nem sikerült kiválasztani a hanganyagot",
"uploadFailed": "A feltöltés nem sikerült. Kérlek, próbáld újra.",
"urlFailed": "Ezt az URL-t nem tudtuk használni. Próbálj meg egy másik forrást.",
"urlPlaceholder": "https://youtube.com/watch?v=...",
"useThisFile": "Használd ezt a fájlt",
"useThisUrl": "Használd ezt az URL-t",
"artistLabel": "Előadó",
"loading": "Betöltés...",
"titleLabel": "Cím",
"uploadFileAction": "Fájl feltöltése"
},
"audioEditor": {
"loading": "Hangszerkesztő betöltése...",
+16 -1
View File
@@ -760,7 +760,22 @@
"views": "{count} tayangan",
"moreVersions": "+{count} lainnya",
"select": "Pilih",
"creditCost": "{credits} kredit"
"creditCost": "{credits} kredit",
"chooseFile": "Pilih file audio (MP3, WAV, FLAC, M4A, OGG)",
"noResultsHelp": "Kami tidak dapat menemukan sumber audio. Coba edit nama artis atau judul di atas dan cari lagi, atau gunakan audio Anda sendiri melalui URL atau unggah file.",
"pasteUrl": "Tempel URL",
"researchFailed": "Pencarian gagal. Silakan coba lagi.",
"searchAgain": "Cari lagi",
"selectFailed": "Gagal memilih audio",
"uploadFailed": "Gagal mengunggah. Silakan coba lagi.",
"urlFailed": "Tidak dapat menggunakan URL tersebut. Coba sumber lain.",
"urlPlaceholder": "https://youtube.com/watch?v=...",
"useThisFile": "Gunakan file ini",
"useThisUrl": "Gunakan URL ini",
"artistLabel": "Artis",
"loading": "Memuat...",
"titleLabel": "Judul",
"uploadFileAction": "Unggah file"
},
"audioEditor": {
"loading": "Memuat editor audio...",
+16 -1
View File
@@ -760,7 +760,22 @@
"views": "{count} visualizzazioni",
"moreVersions": "+{count} altre",
"select": "Seleziona",
"creditCost": "{credits} crediti"
"creditCost": "{credits} crediti",
"chooseFile": "Scegli un file audio (MP3, WAV, FLAC, M4A, OGG)",
"noResultsHelp": "Non abbiamo trovato nessuna fonte audio. Prova a modificare l'artista o il titolo qui sopra e cerca di nuovo, oppure fornisci il tuo audio tramite URL o caricando un file.",
"pasteUrl": "Incolla URL",
"researchFailed": "Ricerca non riuscita. Riprova.",
"searchAgain": "Cerca di nuovo",
"selectFailed": "Impossibile selezionare l'audio",
"uploadFailed": "Caricamento non riuscito. Riprova.",
"urlFailed": "Impossibile usare quell'URL. Prova un'altra fonte.",
"urlPlaceholder": "https://youtube.com/watch?v=...",
"useThisFile": "Usa questo file",
"useThisUrl": "Usa questo URL",
"artistLabel": "Artista",
"loading": "Caricamento in corso...",
"titleLabel": "Titolo",
"uploadFileAction": "Carica file"
},
"audioEditor": {
"loading": "Caricamento editor audio...",
+16 -1
View File
@@ -760,7 +760,22 @@
"views": "{count} 回視聴",
"moreVersions": "他 {count} 件",
"select": "選択",
"creditCost": "{credits} クレジット"
"creditCost": "{credits} クレジット",
"chooseFile": "音声ファイルを選択 (MP3, WAV, FLAC, M4A, OGG)",
"noResultsHelp": "音源が見つかりませんでした。上のアーティスト名やタイトルを編集して再検索するか、URLまたはファイルのアップロードでご自身の音源を追加してみてください。",
"pasteUrl": "URLを貼り付け",
"researchFailed": "検索に失敗しました。もう一度お試しください。",
"searchAgain": "もう一度検索",
"selectFailed": "音源の選択に失敗しました",
"uploadFailed": "アップロードに失敗しました。もう一度お試しください。",
"urlFailed": "そのURLは使用できませんでした。別の音源をお試しください。",
"urlPlaceholder": "https://youtube.com/watch?v=...",
"useThisFile": "このファイルを使用",
"useThisUrl": "このURLを使用",
"artistLabel": "アーティスト",
"loading": "読み込み中...",
"titleLabel": "タイトル",
"uploadFileAction": "ファイルをアップロード"
},
"audioEditor": {
"loading": "オーディオエディタを読み込み中...",
+16 -1
View File
@@ -760,7 +760,22 @@
"views": "조회수 {count}회",
"moreVersions": "+{count}개 더 보기",
"select": "선택",
"creditCost": "{credits} 크레딧"
"creditCost": "{credits} 크레딧",
"chooseFile": "오디오 파일을 선택해 주세요 (MP3, WAV, FLAC, M4A, OGG)",
"noResultsHelp": "오디오 소스를 찾을 수 없습니다. 위에서 아티스트나 제목을 수정하여 다시 검색하거나, URL 또는 파일 업로드로 직접 오디오를 추가해 주세요.",
"pasteUrl": "URL 붙여넣기",
"researchFailed": "검색에 실패했습니다. 다시 시도해 주세요.",
"searchAgain": "다시 검색하기",
"selectFailed": "오디오 선택에 실패했습니다",
"uploadFailed": "업로드에 실패했습니다. 다시 시도해 주세요.",
"urlFailed": "해당 URL은 사용할 수 없습니다. 다른 소스로 시도해 주세요.",
"urlPlaceholder": "https://youtube.com/watch?v=...",
"useThisFile": "이 파일 사용하기",
"useThisUrl": "이 URL 사용하기",
"artistLabel": "아티스트",
"loading": "로딩 중...",
"titleLabel": "제목",
"uploadFileAction": "파일 업로드"
},
"audioEditor": {
"loading": "오디오 편집기 불러오는 중...",
+16 -1
View File
@@ -760,7 +760,22 @@
"views": "{count} tontonan",
"moreVersions": "+{count} lagi",
"select": "Pilih",
"creditCost": "{credits} kredit"
"creditCost": "{credits} kredit",
"chooseFile": "Pilih fail audio (MP3, WAV, FLAC, M4A, OGG)",
"noResultsHelp": "Kami tidak menemui sebarang sumber audio. Cuba sunting artis atau tajuk di atas dan cari semula, atau gunakan audio anda sendiri melalui URL atau muat naik fail.",
"pasteUrl": "Tampal URL",
"researchFailed": "Carian gagal. Sila cuba lagi.",
"searchAgain": "Cari semula",
"selectFailed": "Gagal memilih audio",
"uploadFailed": "Muat naik gagal. Sila cuba lagi.",
"urlFailed": "Tidak dapat menggunakan URL tersebut. Cuba sumber lain.",
"urlPlaceholder": "https://youtube.com/watch?v=...",
"useThisFile": "Gunakan fail ini",
"useThisUrl": "Gunakan URL ini",
"artistLabel": "Artis",
"loading": "Memuatkan...",
"titleLabel": "Tajuk",
"uploadFileAction": "Muat naik fail"
},
"audioEditor": {
"loading": "Memuatkan editor audio...",
+16 -1
View File
@@ -760,7 +760,22 @@
"views": "{count} visninger",
"moreVersions": "+{count} flere",
"select": "Velg",
"creditCost": "{credits} kreditter"
"creditCost": "{credits} kreditter",
"chooseFile": "Velg en lydfil (MP3, WAV, FLAC, M4A, OGG)",
"noResultsHelp": "Vi fant ingen lydkilder. Prøv å endre artist eller tittel ovenfor og søk på nytt, eller legg til din egen lyd via en URL eller filopplasting.",
"pasteUrl": "Lim inn URL",
"researchFailed": "Søket mislyktes. Prøv igjen.",
"searchAgain": "Søk på nytt",
"selectFailed": "Kunne ikke velge lyd",
"uploadFailed": "Opplastingen mislyktes. Prøv igjen.",
"urlFailed": "Kunne ikke bruke den URL-en. Prøv en annen kilde.",
"urlPlaceholder": "https://youtube.com/watch?v=...",
"useThisFile": "Bruk denne filen",
"useThisUrl": "Bruk denne URL-en",
"artistLabel": "Artist",
"loading": "Laster...",
"titleLabel": "Tittel",
"uploadFileAction": "Last opp fil"
},
"audioEditor": {
"loading": "Laster inn lydredigering...",
+16 -1
View File
@@ -760,7 +760,22 @@
"views": "{count} weergaven",
"moreVersions": "+{count} meer",
"select": "Selecteren",
"creditCost": "{credits} credits"
"creditCost": "{credits} credits",
"chooseFile": "Kies een audiobestand (MP3, WAV, FLAC, M4A, OGG)",
"noResultsHelp": "We konden geen audiobronnen vinden. Probeer de artiest of titel hierboven aan te passen en opnieuw te zoeken, of voeg je eigen audio toe via een URL of bestandsupload.",
"pasteUrl": "Plak URL",
"researchFailed": "Zoeken mislukt. Probeer het opnieuw.",
"searchAgain": "Opnieuw zoeken",
"selectFailed": "Audio selecteren mislukt",
"uploadFailed": "Uploaden mislukt. Probeer het opnieuw.",
"urlFailed": "We konden die URL niet gebruiken. Probeer een andere bron.",
"urlPlaceholder": "https://youtube.com/watch?v=...",
"useThisFile": "Gebruik dit bestand",
"useThisUrl": "Gebruik deze URL",
"artistLabel": "Artiest",
"loading": "Laden...",
"titleLabel": "Titel",
"uploadFileAction": "Bestand uploaden"
},
"audioEditor": {
"loading": "Audio-editor laden...",
+16 -1
View File
@@ -760,7 +760,22 @@
"views": "{count} wyświetleń",
"moreVersions": "+{count} więcej",
"select": "Wybierz",
"creditCost": "{credits} kredytów"
"creditCost": "{credits} kredytów",
"chooseFile": "Wybierz plik audio (MP3, WAV, FLAC, M4A, OGG)",
"noResultsHelp": "Nie znaleźliśmy żadnych źródeł audio. Spróbuj edytować wykonawcę lub tytuł powyżej i wyszukać ponownie, albo dodaj własne audio za pomocą adresu URL lub przesyłając plik.",
"pasteUrl": "Wklej adres URL",
"researchFailed": "Wyszukiwanie nie powiodło się. Spróbuj ponownie.",
"searchAgain": "Wyszukaj ponownie",
"selectFailed": "Nie udało się wybrać audio",
"uploadFailed": "Przesyłanie nie powiodło się. Spróbuj ponownie.",
"urlFailed": "Nie można użyć tego adresu URL. Spróbuj innego źródła.",
"urlPlaceholder": "https://youtube.com/watch?v=...",
"useThisFile": "Użyj tego pliku",
"useThisUrl": "Użyj tego adresu URL",
"artistLabel": "Wykonawca",
"loading": "Wczytywanie...",
"titleLabel": "Tytuł",
"uploadFileAction": "Wgraj plik"
},
"audioEditor": {
"loading": "Wczytywanie edytora audio...",
+16 -1
View File
@@ -760,7 +760,22 @@
"views": "{count} visualizações",
"moreVersions": "+{count} mais",
"select": "Selecionar",
"creditCost": "{credits} créditos"
"creditCost": "{credits} créditos",
"chooseFile": "Escolha um arquivo de áudio (MP3, WAV, FLAC, M4A, OGG)",
"noResultsHelp": "Não conseguimos encontrar nenhuma fonte de áudio. Tente editar o artista ou título acima e pesquisar novamente, ou envie seu próprio áudio via URL ou upload de arquivo.",
"pasteUrl": "Colar URL",
"researchFailed": "Falha na pesquisa. Por favor, tente novamente.",
"searchAgain": "Pesquisar novamente",
"selectFailed": "Falha ao selecionar o áudio",
"uploadFailed": "Falha no upload. Por favor, tente novamente.",
"urlFailed": "Não foi possível usar esse URL. Tente outra fonte.",
"urlPlaceholder": "https://youtube.com/watch?v=...",
"useThisFile": "Usar este arquivo",
"useThisUrl": "Usar este URL",
"artistLabel": "Artista",
"loading": "Carregando...",
"titleLabel": "Título",
"uploadFileAction": "Enviar arquivo"
},
"audioEditor": {
"loading": "Carregando editor de áudio...",
+16 -1
View File
@@ -760,7 +760,22 @@
"views": "{count} vizualizări",
"moreVersions": "+{count} mai multe",
"select": "Selectează",
"creditCost": "{credits} credite"
"creditCost": "{credits} credite",
"chooseFile": "Alege un fișier audio (MP3, WAV, FLAC, M4A, OGG)",
"noResultsHelp": "Nu am putut găsi nicio sursă audio. Încearcă să editezi artistul sau titlul de mai sus și să cauți din nou, sau adaugă propriul fișier audio printr-un URL sau prin încărcare.",
"pasteUrl": "Lipește URL-ul",
"researchFailed": "Căutarea a eșuat. Încearcă din nou.",
"searchAgain": "Caută din nou",
"selectFailed": "Nu s-a putut selecta fișierul audio",
"uploadFailed": "Încărcarea a eșuat. Încearcă din nou.",
"urlFailed": "Nu am putut folosi acel URL. Încearcă o altă sursă.",
"urlPlaceholder": "https://youtube.com/watch?v=...",
"useThisFile": "Folosește acest fișier",
"useThisUrl": "Folosește acest URL",
"artistLabel": "Artist",
"loading": "Se încarcă...",
"titleLabel": "Titlu",
"uploadFileAction": "Încarcă fișier"
},
"audioEditor": {
"loading": "Se încarcă editorul audio...",
+16 -1
View File
@@ -760,7 +760,22 @@
"views": "{count} просмотров",
"moreVersions": "Еще +{count}",
"select": "Выбрать",
"creditCost": "{credits} кредитов"
"creditCost": "{credits} кредитов",
"chooseFile": "Выбери аудиофайл (MP3, WAV, FLAC, M4A, OGG)",
"noResultsHelp": "Мы не смогли найти аудио. Попробуй изменить исполнителя или название выше и поискать снова, либо добавь свое аудио по URL или загрузи файл.",
"pasteUrl": "Вставь URL",
"researchFailed": "Ошибка поиска. Попробуй еще раз.",
"searchAgain": "Искать снова",
"selectFailed": "Не удалось выбрать аудио",
"uploadFailed": "Ошибка загрузки. Попробуй еще раз.",
"urlFailed": "Не удалось использовать этот URL. Попробуй другой источник.",
"urlPlaceholder": "https://youtube.com/watch?v=...",
"useThisFile": "Использовать этот файл",
"useThisUrl": "Использовать этот URL",
"artistLabel": "Исполнитель",
"loading": "Загрузка...",
"titleLabel": "Название",
"uploadFileAction": "Загрузить файл"
},
"audioEditor": {
"loading": "Загрузка аудиоредактора...",
+16 -1
View File
@@ -760,7 +760,22 @@
"views": "{count} zhliadnutí",
"moreVersions": "+{count} ďalších",
"select": "Vybrať",
"creditCost": "{credits} kreditov"
"creditCost": "{credits} kreditov",
"chooseFile": "Vyber zvukový súbor (MP3, WAV, FLAC, M4A, OGG)",
"noResultsHelp": "Nenašli sme žiadne zdroje zvuku. Skús upraviť interpreta alebo názov vyššie a vyhľadať znova, alebo pridaj vlastný zvuk pomocou URL adresy či nahratím súboru.",
"pasteUrl": "Vlož URL",
"researchFailed": "Vyhľadávanie zlyhalo. Skús to znova.",
"searchAgain": "Hľadať znova",
"selectFailed": "Nepodarilo sa vybrať zvuk",
"uploadFailed": "Nahrávanie zlyhalo. Skús to znova.",
"urlFailed": "Túto URL adresu nebolo možné použiť. Skús iný zdroj.",
"urlPlaceholder": "https://youtube.com/watch?v=...",
"useThisFile": "Použiť tento súbor",
"useThisUrl": "Použiť túto URL",
"artistLabel": "Interpret",
"loading": "Načítava sa...",
"titleLabel": "Názov",
"uploadFileAction": "Nahrať súbor"
},
"audioEditor": {
"loading": "Načítava sa editor zvuku...",
+16 -1
View File
@@ -760,7 +760,22 @@
"views": "{count} visningar",
"moreVersions": "+{count} fler",
"select": "Välj",
"creditCost": "{credits} krediter"
"creditCost": "{credits} krediter",
"chooseFile": "Välj en ljudfil (MP3, WAV, FLAC, M4A, OGG)",
"noResultsHelp": "Vi kunde inte hitta några ljudkällor. Prova att ändra artist eller titel ovan och sök igen, eller lägg till ditt eget ljud via en URL eller filuppladdning.",
"pasteUrl": "Klistra in URL",
"researchFailed": "Sökningen misslyckades. Försök igen.",
"searchAgain": "Sök igen",
"selectFailed": "Det gick inte att välja ljud",
"uploadFailed": "Uppladdningen misslyckades. Försök igen.",
"urlFailed": "Det gick inte att använda den URL:en. Prova en annan källa.",
"urlPlaceholder": "https://youtube.com/watch?v=...",
"useThisFile": "Använd den här filen",
"useThisUrl": "Använd den här URL:en",
"artistLabel": "Artist",
"loading": "Laddar...",
"titleLabel": "Titel",
"uploadFileAction": "Ladda upp fil"
},
"audioEditor": {
"loading": "Laddar ljudredigerare...",
+16 -1
View File
@@ -760,7 +760,22 @@
"views": "{count} ยอดดู",
"moreVersions": "อีก +{count}",
"select": "เลือก",
"creditCost": "{credits} เครดิต"
"creditCost": "{credits} เครดิต",
"chooseFile": "เลือกไฟล์เสียง (MP3, WAV, FLAC, M4A, OGG)",
"noResultsHelp": "เราไม่พบแหล่งที่มาของเสียงเลย ลองแก้ไขชื่อศิลปินหรือชื่อเพลงด้านบนแล้วค้นหาอีกครั้ง หรือใช้ไฟล์เสียงของคุณเองโดยการระบุ URL หรืออัปโหลดไฟล์",
"pasteUrl": "วาง URL",
"researchFailed": "ค้นหาไม่สำเร็จ กรุณาลองใหม่อีกครั้ง",
"searchAgain": "ค้นหาอีกครั้ง",
"selectFailed": "เลือกไฟล์เสียงไม่สำเร็จ",
"uploadFailed": "อัปโหลดไม่สำเร็จ กรุณาลองใหม่อีกครั้ง",
"urlFailed": "ไม่สามารถใช้ URL นั้นได้ ลองใช้แหล่งที่มาอื่น",
"urlPlaceholder": "https://youtube.com/watch?v=...",
"useThisFile": "ใช้ไฟล์นี้",
"useThisUrl": "ใช้ URL นี้",
"artistLabel": "ศิลปิน",
"loading": "กำลังโหลด...",
"titleLabel": "ชื่อเพลง",
"uploadFileAction": "อัปโหลดไฟล์"
},
"audioEditor": {
"loading": "กำลังโหลดโปรแกรมแก้ไขเสียง...",
+16 -1
View File
@@ -760,7 +760,22 @@
"views": "{count} views",
"moreVersions": "+{count} pa",
"select": "Piliin",
"creditCost": "{credits} credits"
"creditCost": "{credits} credits",
"chooseFile": "Pumili ng audio file (MP3, WAV, FLAC, M4A, OGG)",
"noResultsHelp": "Wala kaming nahanap na audio sources. Subukang i-edit ang artist o pamagat sa itaas at maghanap ulit, o magbigay ng sarili mong audio gamit ang URL o file upload.",
"pasteUrl": "I-paste ang URL",
"researchFailed": "Nabigo ang paghahanap. Pakisubukan ulit.",
"searchAgain": "Maghanap ulit",
"selectFailed": "Hindi napili ang audio",
"uploadFailed": "Nabigo ang pag-upload. Pakisubukan ulit.",
"urlFailed": "Hindi magamit ang URL na iyon. Subukan ang ibang source.",
"urlPlaceholder": "https://youtube.com/watch?v=...",
"useThisFile": "Gamitin ang file na ito",
"useThisUrl": "Gamitin ang URL na ito",
"artistLabel": "Artist",
"loading": "Nagloload...",
"titleLabel": "Pamagat",
"uploadFileAction": "Mag-upload ng file"
},
"audioEditor": {
"loading": "Nilo-load ang audio editor...",
+16 -1
View File
@@ -760,7 +760,22 @@
"views": "{count} görüntülenme",
"moreVersions": "+{count} daha",
"select": "Seç",
"creditCost": "{credits} kredi"
"creditCost": "{credits} kredi",
"chooseFile": "Bir ses dosyası seç (MP3, WAV, FLAC, M4A, OGG)",
"noResultsHelp": "Hiçbir ses kaynağı bulamadık. Yukarıdaki sanatçı veya başlık bilgisini düzenleyip tekrar aramayı dene ya da bir URL veya dosya yükleyerek kendi ses dosyanı ekle.",
"pasteUrl": "URL'yi yapıştır",
"researchFailed": "Arama başarısız oldu. Lütfen tekrar dene.",
"searchAgain": "Tekrar ara",
"selectFailed": "Ses seçilemedi",
"uploadFailed": "Yükleme başarısız oldu. Lütfen tekrar dene.",
"urlFailed": "Bu URL kullanılamadı. Başka bir kaynak dene.",
"urlPlaceholder": "https://youtube.com/watch?v=...",
"useThisFile": "Bu dosyayı kullan",
"useThisUrl": "Bu URL'yi kullan",
"artistLabel": "Sanatçı",
"loading": "Yükleniyor...",
"titleLabel": "Başlık",
"uploadFileAction": "Dosya yükle"
},
"audioEditor": {
"loading": "Ses düzenleyici yükleniyor...",
+16 -1
View File
@@ -760,7 +760,22 @@
"views": "{count} переглядів",
"moreVersions": "+ще {count}",
"select": "Вибрати",
"creditCost": "{credits} кредитів"
"creditCost": "{credits} кредитів",
"chooseFile": "Вибери аудіофайл (MP3, WAV, FLAC, M4A, OGG)",
"noResultsHelp": "Ми не змогли знайти жодних аудіоджерел. Спробуй змінити виконавця або назву вище та повторити пошук, або додай власне аудіо за допомогою URL чи завантаж файл.",
"pasteUrl": "Встав URL",
"researchFailed": "Помилка пошуку. Будь ласка, спробуй ще раз.",
"searchAgain": "Шукати знову",
"selectFailed": "Не вдалося вибрати аудіо",
"uploadFailed": "Помилка завантаження. Будь ласка, спробуй ще раз.",
"urlFailed": "Не вдалося використати цей URL. Спробуй інше джерело.",
"urlPlaceholder": "https://youtube.com/watch?v=...",
"useThisFile": "Використати цей файл",
"useThisUrl": "Використати цей URL",
"artistLabel": "Виконавець",
"loading": "Завантаження...",
"titleLabel": "Назва",
"uploadFileAction": "Завантажити файл"
},
"audioEditor": {
"loading": "Завантаження аудіоредактора...",
+16 -1
View File
@@ -760,7 +760,22 @@
"views": "{count} lượt xem",
"moreVersions": "+{count} phiên bản khác",
"select": "Chọn",
"creditCost": "{credits} credit"
"creditCost": "{credits} credit",
"chooseFile": "Chọn tệp âm thanh (MP3, WAV, FLAC, M4A, OGG)",
"noResultsHelp": "Chúng tôi không tìm thấy nguồn âm thanh nào. Bạn hãy thử chỉnh sửa tên nghệ sĩ hoặc tiêu đề ở trên và tìm kiếm lại, hoặc tự cung cấp âm thanh bằng URL hoặc tải tệp lên.",
"pasteUrl": "Dán URL",
"researchFailed": "Tìm kiếm thất bại. Vui lòng thử lại.",
"searchAgain": "Tìm kiếm lại",
"selectFailed": "Không thể chọn âm thanh",
"uploadFailed": "Tải lên thất bại. Vui lòng thử lại.",
"urlFailed": "Không thể sử dụng URL đó. Bạn hãy thử một nguồn khác.",
"urlPlaceholder": "https://youtube.com/watch?v=...",
"useThisFile": "Sử dụng tệp này",
"useThisUrl": "Sử dụng URL này",
"artistLabel": "Nghệ sĩ",
"loading": "Đang tải...",
"titleLabel": "Tiêu đề",
"uploadFileAction": "Tải tệp lên"
},
"audioEditor": {
"loading": "Đang tải trình chỉnh sửa âm thanh...",
+16 -1
View File
@@ -760,7 +760,22 @@
"views": "{count} 次观看",
"moreVersions": "还有 {count} 个",
"select": "选择",
"creditCost": "{credits} 积分"
"creditCost": "{credits} 积分",
"chooseFile": "选择音频文件(MP3、WAV、FLAC、M4A、OGG)",
"noResultsHelp": "未能找到任何音频源。请尝试修改上方的歌手或歌曲名并重新搜索,或者通过提供网址或上传文件来使用您自己的音频。",
"pasteUrl": "粘贴网址",
"researchFailed": "搜索失败。请重试。",
"searchAgain": "重新搜索",
"selectFailed": "选择音频失败",
"uploadFailed": "上传失败。请重试。",
"urlFailed": "无法使用该网址。请尝试其他来源。",
"urlPlaceholder": "https://youtube.com/watch?v=...",
"useThisFile": "使用此文件",
"useThisUrl": "使用此网址",
"artistLabel": "歌手",
"loading": "加载中...",
"titleLabel": "标题",
"uploadFileAction": "上传文件"
},
"audioEditor": {
"loading": "正在加载音频编辑器...",
+31 -3
View File
@@ -53,7 +53,17 @@ class MachineTypes:
# us-central1-a/-b/-c simultaneously (2026-08-12) which took out every same-family lane.
# n2-highcpu-32 (Intel Cascade/Ice Lake) draws from a much deeper, independent pool, so a
# c4d shortage cannot exhaust it. n2 does NOT support hyperdisk-balanced → uses pd-balanced.
ENCODING_WORKER_ALT = "n2-highcpu-32" # 32 vCPU, Intel - deep-capacity fallback pool
ENCODING_WORKER_ALT = "n2-highcpu-32" # 32 vCPU, Intel Cascade/Ice Lake - deep-capacity fallback pool
# Broadened ranked pool (2026-08-15) — ≥5 x86_64, 32-vCPU, ≥32 GB highcpu types
# across 4 distinct silicon lineages, so a stockout of the newest-gen cohort
# (c4d/c4, the crunch) cannot exhaust every lane. Encode-speed ranking lives in
# backend/services/encoding_worker_preference.py::SPEED_RANK. Disk-type rule:
# next-gen Titanium families (c4/c4d/n4/n4d) support hyperdisk-balanced ONLY;
# older families (c2d/n2/n2d) use pd-balanced. Getting this wrong = pulumi error.
ENCODING_WORKER_C4 = "c4-highcpu-32" # 32 vCPU / 64 GB, Intel Emerald Rapids (hyperdisk-only)
ENCODING_WORKER_N4D = "n4d-highcpu-32" # 32 vCPU / 64 GB, AMD Titanium (hyperdisk-only)
ENCODING_WORKER_C2D = "c2d-highcpu-32" # 32 vCPU / 64 GB, AMD Milan (Zen3), deep pool (pd-balanced)
ENCODING_WORKER_N2D = "n2d-highcpu-32" # 32 vCPU / 32 GB, AMD Rome/Milan, deep pool (pd-balanced)
FLACFETCH = "e2-small" # 0.5 vCPU, 2GB RAM
@@ -300,8 +310,17 @@ class EncodingWorkerConfig:
#
# Each entry: name/IP suffix, zone suffix ({REGION}-{zone_suffix}),
# machine_type, boot disk_type. ORDER MATTERS — IPs and VMs are zipped by
# position, and it defines candidate priority. Keep the c4d a/b entries
# first and byte-identical so Pulumi does not recreate the existing VMs.
# position. (Candidate PRIORITY is no longer positional: it is decided at
# runtime/deploy by the shared speed-rank + cooldown in
# backend/services/encoding_worker_preference.py.) Keep the existing a/b/n2c/n2f
# entries first and byte-identical so Pulumi does not recreate those VMs; the
# broadened-pool entries are APPENDED so the change is purely additive
# (verify `pulumi preview` shows only new IPs+VMs, zero replace).
#
# Zone spread: one machine type per zone where possible so a single
# (type × zone) stockout can't correlate across the pool. c4d primary lives in
# zone c (the primary pair), so the c4 fallback goes to a, n4d to b, c2d to f,
# n2d to a — 4 lineages across 4 zones.
FALLBACKS = [
{"suffix": "a", "zone_suffix": "a",
"machine_type": MachineTypes.ENCODING_WORKER, "disk_type": "hyperdisk-balanced"},
@@ -311,6 +330,15 @@ class EncodingWorkerConfig:
"machine_type": MachineTypes.ENCODING_WORKER_ALT, "disk_type": "pd-balanced"},
{"suffix": "n2f", "zone_suffix": "f",
"machine_type": MachineTypes.ENCODING_WORKER_ALT, "disk_type": "pd-balanced"},
# --- Broadened pool (2026-08-15), appended (additive-only) ---
{"suffix": "c4a", "zone_suffix": "a",
"machine_type": MachineTypes.ENCODING_WORKER_C4, "disk_type": "hyperdisk-balanced"},
{"suffix": "n4db", "zone_suffix": "b",
"machine_type": MachineTypes.ENCODING_WORKER_N4D, "disk_type": "hyperdisk-balanced"},
{"suffix": "c2df", "zone_suffix": "f",
"machine_type": MachineTypes.ENCODING_WORKER_C2D, "disk_type": "pd-balanced"},
{"suffix": "n2da", "zone_suffix": "a",
"machine_type": MachineTypes.ENCODING_WORKER_N2D, "disk_type": "pd-balanced"},
]
# Derived name lists (kept for readability / any external reference).
@@ -0,0 +1,297 @@
#!/usr/bin/env python3
"""Benchmark encode wall-time per instance type to build the speed ranking.
The runtime + deploy candidate ordering is driven by
``backend/services/encoding_worker_preference.SPEED_RANK`` — a fastest-first
preference. That table is SEEDED from CPU architecture; this script replaces the
seed with MEASURED medians so the ranking reflects reality on our actual encode
workload (fast finalization is the whole reason c4d was chosen).
This is an OPERATOR tool, not part of CI: it starts real (billed) VMs, runs a
canonical encode on each, and stops them again. Run it occasionally and after
adding a new type.
Usage:
python infrastructure/encoding-worker/benchmark_types.py \\
--input-gcs gs://karaoke-gen-storage-nomadkaraoke/bench/inputs/ \\
--encoding-config @bench/encoding_config.json \\
--out-prefix gs://karaoke-gen-storage-nomadkaraoke/bench/out \\
[--repeats 3] [--types c4-highcpu-32,n2-highcpu-32] [--json ranking.json] \\
[--include-running] [--no-stop]
The payload matches the real /encode contract (input_gcs_path + output_gcs_path +
encoding_config), i.e. the production FULL finalization path — not the lighter
/encode-preview. Pin one real job's inputs dir + its encoding_config in a stable
GCS location once and reuse it so the medians reflect production 4K finalization
time. `--encoding-config` takes inline JSON or `@path/to/file.json`.
SAFETY: VMs already RUNNING (likely serving production) are skipped by default and
never stopped; only VMs this run starts are benchmarked and stopped afterwards.
Requires: gcloud/gsutil authenticated with compute + secret access. The fallback
VM inventory (vm/zone/ip/machine_type) is read from the
``encoding-worker-fallback-vms`` secret; the c4d primary is added from Firestore.
"""
from __future__ import annotations
import argparse
import json
import statistics
import subprocess
import sys
import time
import urllib.error
import urllib.request
from typing import Any, Dict, List, Optional
PROJECT = "nomadkaraoke"
PORT = 8080
DEFAULT_C4D_ZONE = "us-central1-c"
def _gcloud(*args: str, check: bool = True) -> str:
r = subprocess.run(
["gcloud", *args, f"--project={PROJECT}"],
capture_output=True, text=True,
)
if check and r.returncode != 0:
raise RuntimeError(f"gcloud {' '.join(args)} failed: {r.stderr.strip()}")
return r.stdout.strip()
def _api_key() -> str:
return _gcloud("secrets", "versions", "access", "latest",
"--secret=encoding-worker-api-key")
def _inventory(only_types: Optional[set]) -> List[Dict[str, Any]]:
"""Assemble the {vm,zone,ip,machine_type} list to benchmark.
Primary c4d (from Firestore) + every fallback (from the secret). machine_type
is required here — legacy entries without it are skipped with a warning.
"""
workers: List[Dict[str, Any]] = []
# Primary c4d from Firestore config.
cfg_raw = _gcloud("firestore", "documents", "get",
"projects/nomadkaraoke/databases/(default)/documents/config/encoding-worker",
"--format=json", check=False)
try:
# Fall back to the python client if the CLI shape isn't available.
from google.cloud import firestore # type: ignore
doc = firestore.Client(project=PROJECT).collection("config").document("encoding-worker").get()
data = doc.to_dict() or {}
if data.get("primary_vm"):
workers.append({
"vm": data["primary_vm"], "zone": DEFAULT_C4D_ZONE,
"ip": data.get("primary_ip"), "machine_type": "c4d-highcpu-32",
})
except Exception as e: # noqa: BLE001
print(f"WARN: could not read primary from Firestore ({e}); benchmarking fallbacks only")
secret = _gcloud("secrets", "versions", "access", "latest",
"--secret=encoding-worker-fallback-vms", check=False)
try:
for f in json.loads(secret or "[]"):
mt = f.get("machine_type")
if not mt:
print(f"WARN: fallback {f.get('vm')} has no machine_type; skipping")
continue
workers.append({"vm": f["vm"], "zone": f["zone"], "ip": f.get("ip"), "machine_type": mt})
except Exception as e: # noqa: BLE001
print(f"WARN: could not parse fallback secret ({e})")
# De-dup by machine_type (one representative VM per type) and optional filter.
seen, result = set(), []
for w in workers:
if only_types and w["machine_type"] not in only_types:
continue
if w["machine_type"] in seen:
continue
seen.add(w["machine_type"])
result.append(w)
return result
def _vm_status(vm: str, zone: str) -> str:
return _gcloud("compute", "instances", "describe", vm, f"--zone={zone}",
"--format=value(status)", check=False)
def _start(vm: str, zone: str) -> None:
_gcloud("compute", "instances", "start", vm, f"--zone={zone}", check=False)
def _stop(vm: str, zone: str) -> None:
_gcloud("compute", "instances", "stop", vm, f"--zone={zone}", check=False)
def _http(method: str, url: str, api_key: str, body: Optional[dict] = None,
timeout: float = 30.0) -> Dict[str, Any]:
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(url, data=data, method=method)
req.add_header("X-API-Key", api_key)
if data is not None:
req.add_header("Content-Type", "application/json")
with urllib.request.urlopen(req, timeout=timeout) as resp:
return json.loads(resp.read().decode() or "{}")
def _wait_health(ip: str, api_key: str, timeout: float = 240.0) -> bool:
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
_http("GET", f"http://{ip}:{PORT}/health", api_key, timeout=5.0)
return True
except (urllib.error.URLError, OSError, ValueError):
time.sleep(5)
return False
def _one_encode(ip: str, api_key: str, job_id: str, input_gcs: str,
encoding_config: dict, out: str, poll_timeout: float = 1800.0) -> float:
"""Submit one full /encode and return client-side wall-time (seconds).
Payload matches the real /encode contract (EncodeRequest:
input_gcs_path + output_gcs_path + encoding_config) — the production
finalization path we want to benchmark, NOT the lighter /encode-preview.
"""
start = time.monotonic()
_http("POST", f"http://{ip}:{PORT}/encode", api_key, body={
"job_id": job_id,
"input_gcs_path": input_gcs,
"output_gcs_path": out,
"encoding_config": encoding_config,
})
deadline = time.monotonic() + poll_timeout
while time.monotonic() < deadline:
time.sleep(5)
try:
st = _http("GET", f"http://{ip}:{PORT}/status/{job_id}", api_key, timeout=10.0)
except (urllib.error.URLError, OSError, ValueError):
continue
status = st.get("status")
if status == "complete":
return time.monotonic() - start
if status == "failed":
raise RuntimeError(f"encode {job_id} failed: {st.get('error')}")
raise TimeoutError(f"encode {job_id} did not complete within {poll_timeout}s")
def benchmark(args) -> Dict[str, float]:
api_key = _api_key()
only = set(args.types.split(",")) if args.types else None
workers = _inventory(only)
if not workers:
print("No workers to benchmark (check --types / secret).")
return {}
print(f"Benchmarking {len(workers)} types × {args.repeats} repeats each:")
for w in workers:
print(f" - {w['machine_type']:>16} {w['vm']} ({w['zone']})")
medians: Dict[str, float] = {}
for w in workers:
vm, zone, ip, mt = w["vm"], w["zone"], w.get("ip"), w["machine_type"]
print(f"\n=== {mt} — {vm} ({zone}) ===")
initial_status = _vm_status(vm, zone)
# SAFETY: never touch a VM that is already RUNNING — it may be the serving
# primary/override, and injecting bench jobs (or stopping it) would disrupt
# production and wipe its in-memory job registry. Only benchmark VMs we
# start ourselves, and only stop those. `--include-running` overrides the
# skip but STILL never stops a VM this run didn't start.
started_by_us = False
if initial_status == "RUNNING" and not args.include_running:
print(f" SKIP: {vm} is already RUNNING (likely serving); pass --include-running to bench it")
continue
try:
if initial_status != "RUNNING":
print(" starting VM...")
_start(vm, zone)
started_by_us = True
if not ip:
ip = _gcloud("compute", "instances", "describe", vm, f"--zone={zone}",
"--format=value(networkInterfaces[0].accessConfigs[0].natIP)")
if not _wait_health(ip, api_key):
print(f" SKIP: {vm} never became healthy")
continue
samples: List[float] = []
for i in range(args.repeats):
job_id = f"bench-{mt}-{i}"
out = f"{args.out_prefix}/{mt}-{i}/"
secs = _one_encode(ip, api_key, job_id, args.input_gcs,
args.encoding_config, out)
print(f" run {i + 1}/{args.repeats}: {secs:.1f}s")
samples.append(secs)
medians[mt] = round(statistics.median(samples), 1)
except Exception as e: # noqa: BLE001 — keep benchmarking the rest
print(f" ERROR benchmarking {mt}: {e}")
finally:
# Only stop a VM this invocation actually started (never a serving one).
if started_by_us and not args.no_stop:
print(" stopping VM...")
_stop(vm, zone)
elif not started_by_us:
print(" leaving VM as found (was already running before this benchmark)")
return medians
def _suggest_ranks(medians: Dict[str, float]) -> Dict[str, int]:
"""Map medians → SPEED_RANK ints (fastest = smallest), spaced by 10."""
ordered = sorted(medians.items(), key=lambda kv: kv[1])
return {mt: (idx + 1) * 10 for idx, (mt, _) in enumerate(ordered)}
def main() -> int:
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--input-gcs", dest="input_gcs", required=True,
help="gs:// path to the canonical /encode inputs dir")
p.add_argument("--encoding-config", dest="encoding_config_raw", required=True,
help="encoding_config as inline JSON or @path/to/file.json")
p.add_argument("--out-prefix", dest="out_prefix", required=True)
p.add_argument("--repeats", type=int, default=3)
p.add_argument("--types", default=None, help="comma-separated machine types to limit to")
p.add_argument("--json", dest="json_out", default=None, help="write ranking JSON here")
p.add_argument("--no-stop", action="store_true", help="leave VMs running after benchmarking")
p.add_argument("--include-running", action="store_true",
help="also benchmark VMs already RUNNING (never stops them)")
args = p.parse_args()
# Resolve --encoding-config (inline JSON or @file) into a dict once.
raw = args.encoding_config_raw
try:
if raw.startswith("@"):
with open(raw[1:]) as f:
args.encoding_config = json.load(f)
else:
args.encoding_config = json.loads(raw)
except (OSError, ValueError) as e:
print(f"ERROR: --encoding-config is not valid JSON / readable file: {e}")
return 2
if not isinstance(args.encoding_config, dict):
print("ERROR: --encoding-config must be a JSON object")
return 2
medians = benchmark(args)
if not medians:
return 1
ranks = _suggest_ranks(medians)
print("\n=== RESULTS (median encode seconds, fastest first) ===")
for mt, secs in sorted(medians.items(), key=lambda kv: kv[1]):
print(f" {mt:>16}: {secs:>7.1f}s → suggested SPEED_RANK {ranks[mt]}")
payload = {"medians_seconds": medians, "suggested_speed_rank": ranks}
if args.json_out:
with open(args.json_out, "w") as f:
json.dump(payload, f, indent=2)
print(f"\nWrote {args.json_out}")
print("\nCopy suggested_speed_rank into "
"backend/services/encoding_worker_preference.py::SPEED_RANK "
"(keep c4d lowest/first unless measurements say otherwise).")
return 0
if __name__ == "__main__":
sys.exit(main())
@@ -0,0 +1,187 @@
"""Pure decision logic for the encoding-worker blue-green deploy (used by CI).
The GitHub Actions workflow (`.github/workflows/ci.yml`) does all the GCP I/O
(`gcloud compute instances start/stop`, health `curl`s, Firestore writes). It
delegates the *decisions* to the pure functions here so the branching — the part
that's easy to get wrong and impossible to run locally in CI — has real unit
tests (`backend/tests/test_deploy_promote.py`).
Background: us-central1 is in a persistent c4d Spot stockout, so the c4d
primary/secondary are usually down and all traffic runs on an n2 fallback
recorded as `active_override_vm`. A naive "start the c4d secondary and swap"
deploy can't start the secondary and never refreshes the serving fallback, so
worker-side changes never reach production. These helpers make the deploy pick a
*fresh* green target (c4d secondary if it starts, else a different n2 fallback)
and then promote that validated green to serving with zero downtime.
"""
from __future__ import annotations
from typing import Any, Dict, List, Optional
# c4d/n2 primary+secondary live here; the worker manager uses the same zone.
DEFAULT_C4D_ZONE = "us-central1-c"
# Shared, pure candidate-ranking logic — the SINGLE SOURCE OF TRUTH also used by
# the runtime worker manager, so deploy green selection and runtime selection can
# never drift. Preferred import is the normal package path; when that isn't
# importable (this file is loaded by path in CI/tests, and an installed `backend`
# package can even shadow the repo working tree), fall back to loading the module
# straight from its file. It is stdlib-only, so by-path exec has no side effects.
try:
from backend.services.encoding_worker_preference import (
PRIMARY_MACHINE_TYPE,
ordered_candidates,
)
except ImportError: # pragma: no cover - exercised in the bare CI heredoc / shadowed env
import importlib.util
import pathlib
_pref_path = (
pathlib.Path(__file__).resolve().parents[2]
/ "backend" / "services" / "encoding_worker_preference.py"
)
_spec = importlib.util.spec_from_file_location("encoding_worker_preference", _pref_path)
_pref = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_pref)
PRIMARY_MACHINE_TYPE = _pref.PRIMARY_MACHINE_TYPE
ordered_candidates = _pref.ordered_candidates
def select_green_candidates(
config: Dict[str, Any],
fallback_vms: List[Dict[str, Any]],
) -> List[Dict[str, Optional[str]]]:
"""Ranked list of candidate green (staging) targets for the workflow to try.
Pool = the c4d ``secondary_vm`` (kind="secondary") + all fallback VMs
(kind="fallback"), EXCLUDING the current ``active_override_vm``. The pool is
ranked by the shared preference logic — fastest-first, demoting any type that
recently stocked out (per ``config["capacity_state"]``). So:
* when c4d has capacity, the c4d secondary sorts first → normal blue-green;
* during a c4d stockout, the secondary is demoted and a deep-pool fallback
(n2d/n2/c2d) leads, instead of wasting ~2 min probing a c4d that won't boot.
Excluding the current override is what makes the deploy zero-downtime: the
green is always a *different*, freshly-booted worker, so the override keeps
serving until the workflow atomically switches to the validated green.
Each candidate: {"vm", "ip", "zone", "machine_type", "kind"}.
"""
pool: List[Dict[str, Optional[str]]] = []
secondary_vm = config.get("secondary_vm")
if secondary_vm:
pool.append({
"vm": secondary_vm,
"ip": config.get("secondary_ip"),
"zone": config.get("secondary_zone") or DEFAULT_C4D_ZONE,
# secondary is always the c4d pair unless the config says otherwise.
"machine_type": config.get("secondary_machine_type") or PRIMARY_MACHINE_TYPE,
"kind": "secondary",
})
override_vm = config.get("active_override_vm")
# Only complete entries are usable — a fallback missing vm/zone/ip would
# produce an unstartable candidate (e.g. `gcloud ... --zone=None`) and
# silently drop capacity from the selection path.
usable = [
f for f in (fallback_vms or [])
if f.get("vm") and f.get("zone") and f.get("ip") and f.get("vm") != override_vm
]
for f in usable:
pool.append({
"vm": f["vm"],
"ip": f.get("ip"),
"zone": f.get("zone"),
"machine_type": f.get("machine_type"), # inferred from vm name if absent
"kind": "fallback",
})
return ordered_candidates(pool, capacity_state=config.get("capacity_state"))
def promote_plan(
green: Dict[str, Any],
config: Dict[str, Any],
*,
now: str,
version: str,
) -> Dict[str, Any]:
"""Given a *validated* green worker, decide how to make it the serving worker.
Returns {"firestore_updates": {...}, "drain_and_stop": [{"vm","ip","zone"}, ...]}.
The workflow applies the Firestore updates in one transaction, then drains
(waits for active_jobs==0, bounded) and stops each VM in `drain_and_stop`.
Two cases:
* green.kind == "secondary": standard blue-green swap (green→primary, old
primary→secondary); ALSO clear any `active_override_*` so traffic returns
to the fresh c4d primary. Drain+stop the old primary and the old override.
* green.kind == "fallback": the green becomes the `active_override` (the
serving worker). Leave primary/secondary untouched so c4d resumes as
primary when capacity returns. Drain+stop the previous override (if any,
and different from the green).
"""
drain: List[Dict[str, Optional[str]]] = []
def _finalize(updates: Dict[str, Any]) -> Dict[str, Any]:
# Never drain/stop the worker we just promoted, whatever the config held
# (e.g. a stale override that pointed at the green, or primary==secondary).
safe = [t for t in drain if t.get("vm") and t["vm"] != green["vm"]]
return {"firestore_updates": updates, "drain_and_stop": safe}
if green["kind"] == "secondary":
updates: Dict[str, Any] = {
"primary_vm": green["vm"],
"primary_ip": green["ip"],
"primary_version": version,
"primary_deployed_at": now,
"secondary_vm": config.get("primary_vm"),
"secondary_ip": config.get("primary_ip"),
"secondary_version": config.get("primary_version"),
"secondary_deployed_at": now,
"last_swap_at": now,
"deploy_in_progress": False,
"deploy_in_progress_since": None,
}
old_primary = config.get("primary_vm")
if old_primary:
drain.append({
"vm": old_primary,
"ip": config.get("primary_ip"),
"zone": config.get("primary_zone") or DEFAULT_C4D_ZONE,
})
# A stale override must be cleared so active_url follows the fresh primary.
if config.get("active_override_vm"):
updates.update({
"active_override_vm": None,
"active_override_ip": None,
"active_override_zone": None,
"active_override_set_at": None,
"active_override_version": None,
})
drain.append({
"vm": config["active_override_vm"],
"ip": config.get("active_override_ip"),
"zone": config.get("active_override_zone"),
})
return _finalize(updates)
# kind == "fallback": the green becomes the serving override.
updates = {
"active_override_vm": green["vm"],
"active_override_ip": green["ip"],
"active_override_zone": green["zone"],
"active_override_set_at": now,
"active_override_version": version,
"deploy_in_progress": False,
"deploy_in_progress_since": None,
}
old_override = config.get("active_override_vm")
if old_override and old_override != green["vm"]:
drain.append({
"vm": old_override,
"ip": config.get("active_override_ip"),
"zone": config.get("active_override_zone"),
})
return _finalize(updates)
+6 -5
View File
@@ -114,11 +114,12 @@ echo "Downloaded wheel as: ${WHEEL_NAME}"
# graph (langchain, CUDA, etc.) can hit pip's "resolution-too-deep" error and
# crash-loop the service before it can serve health checks (see #587).
#
# The karaoke-gen dependency tree (torch, langchain, tenacity, ...) is therefore
# NOT installed here. It is installed lazily at the first job by
# ensure_latest_wheel() in backend/services/gce_encoding/main.py (which installs
# WITH deps, retries, and verifies the import chain). Do not assume deps are
# present just because this step succeeded.
# The full karaoke-gen dependency tree (torch [CPU-only], langchain, tenacity,
# ...) is now BAKED INTO THE IMAGE at build time (provision.sh), so this --no-deps
# code upgrade just fast-forwards the app to the newest wheel on an already-
# complete venv. ensure_latest_wheel() in backend/services/gce_encoding/main.py
# remains as a runtime backstop (installs WITH deps + verifies imports) for the
# rare case of an image predating the dep-bake or a partial venv.
echo "[4/5] Installing wheel..."
"${VENV}/bin/pip" install --upgrade --quiet --force-reinstall --no-deps "${WHEEL_PATH}"
+6 -4
View File
@@ -40,10 +40,12 @@ def create_secrets() -> dict[str, secretmanager.Secret]:
"flacfetch-api-key",
"flacfetch-api-url",
"encoding-worker-api-key",
# Capacity-fallback VMs config (JSON list of {vm,zone,ip}). Stored as
# a secret because --set-env-vars on Cloud Run is comma-delimited and
# the JSON value contains commas; the value itself is non-secret
# (just public IPs of fallback VMs).
# Capacity-fallback VMs config (JSON list of {vm,zone,ip,machine_type?}).
# machine_type (e.g. "c4-highcpu-32") drives the shared speed-rank
# ordering; optional for legacy entries (inferred from the vm name).
# Stored as a secret because --set-env-vars on Cloud Run is
# comma-delimited and the JSON value contains commas; the value itself is
# non-secret (just public IPs of fallback VMs).
"encoding-worker-fallback-vms",
# Notifications
+113 -8
View File
@@ -93,19 +93,123 @@ cd /opt/encoding-worker
echo "Creating Python virtual environment..."
/opt/python313/bin/python3.13 -m venv venv
# Install ONLY the packages the worker needs to boot and serve HTTP. The full
# karaoke-gen dependency tree (torch, langchain, tenacity, ...) is NOT baked
# here — it is installed at the first job by ensure_latest_wheel() in
# backend/services/gce_encoding/main.py, because startup.sh installs the wheel
# with --no-deps (see #587: full resolution at boot crash-loops the service).
# Bake the FULL karaoke-gen dependency tree into the image (2026-08-15) so every
# fresh worker VM — including the broadened multi-instance-type fallback pool — is
# self-sufficient at boot instead of relying on a first-job ensure_latest_wheel()
# install of the whole tree (torch + CUDA, langchain, tenacity, ...). That lazy
# path repeatedly bit fresh fallback VMs (see #903 / "No module named 'tenacity'"):
# a partial/timed-out install left a broken venv and every retry hit the same VM.
#
# Consequence: a freshly-provisioned worker's first job pays a one-time cost to
# install the whole tree, and depends on that install succeeding. ensure_latest_wheel()
# retries and verifies the import chain to keep that reliable.
# HOW: install the current published wheel WITH deps, but resolve torch from the
# PyTorch CPU index (primary) with PyPI as the fallback index (everything else).
# CPU-only torch avoids the multi-GB CUDA/nvidia wheels the encode/finalize path
# never needs, keeping the image small. The wheel's CODE is intentionally kept
# installed too — startup.sh still runs `pip install --no-deps <latest wheel>` at
# boot to fast-forward the code to the newest version (deps already satisfied), so
# there's no crash-loop from full resolution at boot (the #587 reason for --no-deps)
# AND no missing-dep failure on the first job.
source venv/bin/activate
pip install --upgrade pip
# Boot/serve packages first (guarantees the service can start even if the heavy
# install below is ever trimmed).
pip install fastapi uvicorn google-cloud-storage aiofiles aiohttp packaging
# Pull the current wheel from the fixed GCS path (same artifact the runtime
# fallback uses). gsutil ships in the debian-cloud base image and the Packer
# builder SA has GCS read on this bucket.
BUCKET="gs://karaoke-gen-storage-nomadkaraoke"
# pip requires a PEP 427-valid wheel filename; the GCS alias
# `karaoke_gen-current.whl` is NOT valid, so copy it to a properly-versioned
# name (mirrors startup.sh). Prefer version.txt for the version tag.
BAKE_VERSION=$(gsutil cat "${BUCKET}/encoding-worker/version.txt" 2>/dev/null | tr -d '[:space:]')
if [ -n "${BAKE_VERSION}" ]; then
WHEEL_NAME="karaoke_gen-${BAKE_VERSION}-py3-none-any.whl"
else
WHEEL_NAME="karaoke_gen-0.0.0-py3-none-any.whl"
fi
WHEEL_PATH="/tmp/${WHEEL_NAME}"
echo "Baking full dependency tree (CPU-only torch) from ${BUCKET}/wheels/karaoke_gen-current.whl → ${WHEEL_NAME} ..."
if ! gsutil cp "${BUCKET}/wheels/karaoke_gen-current.whl" "${WHEEL_PATH}"; then
# Fall back to the latest properly-named versioned wheel.
LATEST_WHEEL=$(gsutil ls "${BUCKET}/wheels/karaoke_gen-*.whl" 2>/dev/null | grep -v 'current' | sort -V | tail -1 || echo "")
if [ -n "${LATEST_WHEEL}" ]; then
WHEEL_NAME=$(basename "${LATEST_WHEEL}")
WHEEL_PATH="/tmp/${WHEEL_NAME}"
gsutil cp "${LATEST_WHEEL}" "${WHEEL_PATH}"
else
echo "FATAL: could not download a wheel to bake deps into the image"
exit 1
fi
fi
# --index-url = PyTorch CPU index (primary, so torch resolves to the CPU build),
# --extra-index-url = PyPI (everything else). Retry a couple of times to ride out
# transient index blips during the build.
for attempt in 1 2 3; do
if pip install \
--index-url https://download.pytorch.org/whl/cpu \
--extra-index-url https://pypi.org/simple \
"${WHEEL_PATH}"; then
break
fi
echo "pip install of full dep tree failed (attempt ${attempt}/3); retrying..."
sleep 15
if [ "${attempt}" = "3" ]; then
echo "FATAL: could not install the full karaoke-gen dependency tree"
exit 1
fi
done
rm -f "${WHEEL_PATH}"
# Verify the dependency TREE is complete. We import the heavy transitive
# libraries that constitute the encode/finalization chain — crucially tenacity,
# the dep that was silently missing on fresh fallback VMs (pulled via the
# generator→correction/langchain chain). We deliberately do NOT import the worker
# app module (backend.services.gce_encoding.main): it constructs GCP clients at
# import and needs GOOGLE_CLOUD_PROJECT + auth that only exist at runtime (systemd
# env), so importing it at BUILD time fails for environment reasons, not missing
# deps. The canary libs below prove the install is complete without that
# fragility. Fail the BUILD on any missing import so a half-baked image that
# claims to be self-sufficient can never ship.
echo "Verifying baked dependency imports..."
python - << 'PYVERIFY'
import importlib
import sys
# torch must be the CPU build. NOTE: torch.cuda.is_available() is False even for a
# CUDA build on this GPU-less builder, so it can't tell CPU from CUDA — check the
# build's compiled CUDA version instead (None only for a true CPU-only wheel).
import torch
assert torch.version.cuda is None, (
f"baked torch is a CUDA build (torch.version.cuda={torch.version.cuda!r}) — "
"expected CPU-only; check the --index-url resolves torch from the CPU index"
)
# Canary imports across the encode/generation dep tree. tenacity + the langchain
# chain are the exact modules whose absence broke fresh fallback VMs before.
modules = [
"tenacity",
"langchain",
"langchain_core",
"transformers",
"librosa",
"onnxruntime",
]
failed = []
for name in modules:
try:
importlib.import_module(name)
except Exception as exc: # noqa: BLE001
failed.append(f"{name}: {exc}")
if failed:
print("FATAL: baked dependency import check failed:")
for f in failed:
print(f" - {f}")
sys.exit(1)
print("Baked dependency imports OK (CPU-only torch).")
PYVERIFY
# Create bootstrap script (runs via ExecStartPre before service starts)
# This minimal script downloads the REAL startup script from GCS.
# All actual logic lives in the GCS-hosted startup.sh, managed by CI.
@@ -226,6 +330,7 @@ echo " - Python ${PYTHON_VERSION} at /opt/python313"
echo " - FFmpeg at /usr/local/bin/ffmpeg"
echo " - Noto fonts (including CJK)"
echo " - Virtual environment at /opt/encoding-worker/venv"
echo " - Full karaoke-gen dependency tree baked (CPU-only torch)"
echo " - Systemd service: encoding-worker.service"
echo ""
echo "Immutable deployment pattern:"
@@ -33,6 +33,59 @@ def test_n2_fallbacks_use_pd_balanced_disk():
assert fb["disk_type"] == "pd-balanced", fb
# Machine families and the ONLY boot-disk type each supports for these VMs.
# Next-gen Titanium families (c4/c4d/n4/n4d) support hyperdisk-balanced only;
# older families (c2d/n2/n2d) use pd-balanced. Mismatched disk_type = GCE rejects
# the instance at create time (the exact failure the fallback fleet must avoid).
_FAMILY_DISK_TYPE = {
"c4d": "hyperdisk-balanced",
"c4": "hyperdisk-balanced",
"n4d": "hyperdisk-balanced",
"n4": "hyperdisk-balanced",
"c2d": "pd-balanced",
"n2d": "pd-balanced",
"n2": "pd-balanced",
}
def _family(machine_type: str) -> str:
# Longest prefix wins so "n2d"/"c4d" aren't shadowed by "n2"/"c4".
return max(
(fam for fam in _FAMILY_DISK_TYPE if machine_type.startswith(fam)),
key=len,
default="",
)
def test_every_fallback_disk_type_matches_its_family_capability():
"""Each fallback's disk_type must be the one its machine family supports."""
for fb in EncodingWorkerConfig.FALLBACKS:
fam = _family(fb["machine_type"])
assert fam, f"unknown family for {fb['machine_type']}"
assert fb["disk_type"] == _FAMILY_DISK_TYPE[fam], fb
def test_pool_has_at_least_five_types_across_multiple_lineages():
"""The broadened pool must be ≥5 distinct machine types spanning ≥3 lineages
(AMD Turin / Intel Emerald / AMD Milan / Intel Cascade / AMD Rome) so a
newest-gen stockout can't exhaust every lane."""
types = {fb["machine_type"] for fb in EncodingWorkerConfig.FALLBACKS}
# primary (c4d) + the fallback types.
types.add(MachineTypes.ENCODING_WORKER)
assert len(types) >= 5, f"pool has only {len(types)} types: {types}"
families = {_family(mt) for mt in types}
assert len(families) >= 3, f"pool spans only {families}"
def test_zone_spread_avoids_same_type_same_zone():
"""No machine type should sit twice in the same zone (correlated stockout)."""
seen = set()
for fb in EncodingWorkerConfig.FALLBACKS:
key = (fb["machine_type"], fb["zone_suffix"])
assert key not in seen, f"duplicate (type,zone): {key}"
seen.add(key)
def test_fallback_names_and_ips_are_unique_and_aligned():
"""Names/IPs are zipped by position with FALLBACKS — they must stay aligned
and unique so no two VMs collide on a resource name or static IP."""
+28
View File
@@ -0,0 +1,28 @@
"""Portrait (9:16) karaoke video rendering.
Re-renders karaoke lyrics for a 1080x1920 phone/social frame from the same
corrected-lyrics data used by the landscape pipeline. See ``renderer`` for the entry
point and ``docs/archive/2026-06-14-portrait-video-design.md`` for the rationale.
"""
from karaoke_gen.portrait.background import PortraitBrandConfig, build_background
from karaoke_gen.portrait.renderer import (
PORTRAIT_HEIGHT,
PORTRAIT_WIDTH,
PortraitLayout,
build_portrait_ass,
prepare_portrait_segments,
render_portrait_video,
)
from karaoke_gen.portrait.wrap import balance_segments
__all__ = [
"PortraitBrandConfig",
"build_background",
"PortraitLayout",
"PORTRAIT_WIDTH",
"PORTRAIT_HEIGHT",
"build_portrait_ass",
"prepare_portrait_segments",
"render_portrait_video",
"balance_segments",
]
+163
View File
@@ -0,0 +1,163 @@
"""Branded portrait (9:16) background generation for karaoke lyric videos.
Produces a 1080x1920 background with a branded header (a neon wordmark image when
one is supplied, otherwise the brand name rendered in the theme font), the song
title + artist, a subtle neon border, and a footer handle. The same background is
used behind the scrolling lyrics and as the held title card; an ``end`` variant adds
a centred "thank you" message.
The module is brand-agnostic: all brand specifics (wordmark, colours, footer text)
come in via :class:`PortraitBrandConfig`, so tenants can theme it without code
changes. Callers supply the config; the karaoke-gen defaults live at the call site.
"""
from __future__ import annotations
import os
from dataclasses import dataclass, field
from typing import Optional, Tuple
from PIL import Image, ImageDraw, ImageFont
RGB = Tuple[int, int, int]
RGBA = Tuple[int, int, int, int]
@dataclass
class PortraitBrandConfig:
"""Visual configuration for the portrait background."""
width: int = 1080
height: int = 1920
bg_top: RGB = (16, 18, 42)
bg_bottom: RGB = (4, 5, 12)
border_color: RGBA = (255, 60, 200, 90)
inner_border_color: RGBA = (150, 80, 247, 50)
# Header: prefer a wordmark image (neon logo); fall back to brand_text.
wordmark_image: Optional[str] = None
brand_text: Optional[str] = None
brand_color: RGB = (255, 122, 204)
title_color: RGB = (255, 255, 255)
artist_color: RGB = (255, 223, 107)
footer_text: Optional[str] = None
footer_color: RGB = (255, 122, 204)
end_text: str = "THANK YOU FOR SINGING!"
end_text_color: RGB = (255, 122, 204)
font_path: Optional[str] = None
# Match the landscape title/end screens, which upper-case the song/artist.
uppercase_meta: bool = True
def _gradient(cfg: PortraitBrandConfig) -> Image.Image:
"""Vertical gradient from ``bg_top`` to ``bg_bottom`` (numpy-free, one row/px)."""
img = Image.new("RGB", (cfg.width, cfg.height), cfg.bg_bottom)
draw = ImageDraw.Draw(img)
h = cfg.height
for y in range(h):
t = y / (h - 1) if h > 1 else 0
r = int(cfg.bg_top[0] * (1 - t) + cfg.bg_bottom[0] * t)
g = int(cfg.bg_top[1] * (1 - t) + cfg.bg_bottom[1] * t)
b = int(cfg.bg_top[2] * (1 - t) + cfg.bg_bottom[2] * t)
draw.line([(0, y), (cfg.width, y)], fill=(r, g, b))
return img
def _load_font(cfg: PortraitBrandConfig, size: int):
if cfg.font_path and os.path.isfile(cfg.font_path):
return ImageFont.truetype(cfg.font_path, size)
# Pillow >= 10.1 supports a sized default font, so the no-custom-font fallback
# still respects the layout's intended scaling instead of the tiny legacy bitmap.
try:
return ImageFont.load_default(size=size)
except TypeError:
return ImageFont.load_default()
def _paste_wordmark(img: Image.Image, cfg: PortraitBrandConfig, top: int) -> int:
"""Paste the neon wordmark, knocking out its dark backing. Returns bottom y."""
logo = Image.open(cfg.wordmark_image).convert("RGBA")
target_w = int(cfg.width * 0.50)
target_h = max(1, int(logo.height * target_w / logo.width))
logo = logo.resize((target_w, target_h), Image.LANCZOS)
px = logo.load()
for y in range(logo.height):
for x in range(logo.width):
r, g, b, a = px[x, y]
lum = max(r, g, b)
if lum < 70:
px[x, y] = (r, g, b, 0)
elif lum < 130:
px[x, y] = (r, g, b, int(a * (lum - 70) / 60))
img.paste(logo, ((cfg.width - target_w) // 2, top), logo)
return top + target_h
def build_background(
cfg: PortraitBrandConfig,
artist: str,
title: str,
variant: str = "lyrics",
) -> Image.Image:
"""Build a portrait background image.
variant:
* ``"lyrics"`` / ``"title"`` — header (brand + song/artist) and footer, empty
centre (lyrics are overlaid at render time; the title card just holds this).
* ``"end"`` — header brand, a centred end message, and footer.
"""
if cfg.uppercase_meta:
title = (title or "").upper()
artist = (artist or "").upper()
img = _gradient(cfg)
draw = ImageDraw.Draw(img, "RGBA")
# Neon border
margin = int(cfg.width * 0.024)
draw.rounded_rectangle(
[margin, margin, cfg.width - margin, cfg.height - margin],
radius=46, outline=cfg.border_color, width=4,
)
draw.rounded_rectangle(
[margin + 6, margin + 6, cfg.width - margin - 6, cfg.height - margin - 6],
radius=40, outline=cfg.inner_border_color, width=2,
)
# Header: wordmark image or brand text
header_top = int(cfg.height * 0.036)
header_bottom = header_top
if cfg.wordmark_image and os.path.isfile(cfg.wordmark_image):
header_bottom = _paste_wordmark(img, cfg, header_top)
elif cfg.brand_text:
f_brand = _load_font(cfg, int(cfg.width * 0.075))
bw = draw.textlength(cfg.brand_text, font=f_brand)
draw.text(((cfg.width - bw) / 2, header_top), cfg.brand_text,
font=f_brand, fill=cfg.brand_color)
header_bottom = header_top + int(cfg.width * 0.075 * 1.2)
# Song title + artist under the header
y0 = header_bottom + int(cfg.height * 0.014)
if title:
f_title = _load_font(cfg, int(cfg.width * 0.056))
tw = draw.textlength(title, font=f_title)
draw.text(((cfg.width - tw) / 2, y0), title, font=f_title, fill=cfg.title_color)
y0 += int(cfg.width * 0.056 * 1.15)
if artist:
f_artist = _load_font(cfg, int(cfg.width * 0.041))
aw = draw.textlength(artist, font=f_artist)
draw.text(((cfg.width - aw) / 2, y0), artist, font=f_artist, fill=cfg.artist_color)
# End message (centred)
if variant == "end" and cfg.end_text:
f_end = _load_font(cfg, int(cfg.width * 0.06))
ew = draw.textlength(cfg.end_text, font=f_end)
draw.text(((cfg.width - ew) / 2, cfg.height * 0.46), cfg.end_text,
font=f_end, fill=cfg.end_text_color)
# Footer handle
if cfg.footer_text:
f_foot = _load_font(cfg, int(cfg.width * 0.035))
fw = draw.textlength(cfg.footer_text, font=f_foot)
draw.text(((cfg.width - fw) / 2, cfg.height - int(cfg.height * 0.057)),
cfg.footer_text, font=f_foot, fill=cfg.footer_color)
return img
+235
View File
@@ -0,0 +1,235 @@
"""Render a portrait (9:16) karaoke video from corrected lyrics + an instrumental.
This is the self-contained core of the portrait-video feature. It re-renders the
lyrics for a 1080x1920 frame (re-wrapping long lines, larger relative font, centred
block) rather than transforming a finished landscape video — the design experiments
showed transforms (letterbox/crop) are unusable. It reuses the same
``SubtitlesGenerator`` engine as the landscape pipeline, so word-by-word karaoke
timing and styling are identical; only the layout changes.
Public entry point: :func:`render_portrait_video`.
"""
from __future__ import annotations
import logging
import os
import subprocess
import tempfile
from dataclasses import dataclass
from typing import List, Optional
from karaoke_gen.lyrics_transcriber.types import LyricsSegment
from karaoke_gen.lyrics_transcriber.output.segment_resizer import SegmentResizer
from karaoke_gen.lyrics_transcriber.output.subtitles import SubtitlesGenerator
from karaoke_gen.portrait.background import PortraitBrandConfig, build_background
from karaoke_gen.portrait.wrap import balance_segments
PORTRAIT_WIDTH = 1080
PORTRAIT_HEIGHT = 1920
@dataclass
class PortraitLayout:
"""Tunable layout parameters for the portrait lyric render.
Defaults were chosen from renders of real jobs: font 88 / line-height 118 keeps
four wrapped lines large and readable in the lower-centre zone below the header.
"""
width: int = PORTRAIT_WIDTH
height: int = PORTRAIT_HEIGHT
font_size: int = 88
line_height: int = 118
max_visible_lines: int = 4
max_line_length: int = 19
intro_seconds: float = 5.0
outro_seconds: float = 5.0
# Vertical centre of the lyric block as a fraction of frame height (below the
# branded header, above the footer).
block_center_frac: float = 0.60
def _ffprobe_duration(path: str) -> float:
out = subprocess.run(
["ffprobe", "-v", "error", "-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1", path],
capture_output=True, text=True, check=True, timeout=60,
).stdout.strip()
return float(out)
def _computed_top_padding(layout: PortraitLayout) -> int:
"""Top padding that centres the visible lyric block at ``block_center_frac``.
``SubtitlesGenerator`` positions the first line at
``top_padding + (H - total - top_padding) // 4`` (see
``ass.lyrics_screen.PositionCalculator``). Invert that so the block's centre
lands where we want it.
"""
total = layout.max_visible_lines * layout.line_height
desired_first_top = layout.height * layout.block_center_frac - total / 2
tp = (4.0 / 3.0) * (desired_first_top - (layout.height - total) / 4.0)
return max(0, int(round(tp)))
def _escape_ass_path(path: str) -> str:
"""Escape a filesystem path for use inside an ffmpeg -vf ass= filter value."""
return path.replace("\\", "\\\\").replace(":", "\\:").replace("'", "\\'")
def prepare_portrait_segments(
correction_result,
layout: PortraitLayout,
logger: Optional[logging.Logger] = None,
) -> List[LyricsSegment]:
"""Resize + orphan-balance the corrected segments for the portrait frame."""
resizer = SegmentResizer(max_line_length=layout.max_line_length, logger=logger)
resized = resizer.resize_segments(correction_result.corrected_segments)
return balance_segments(resized, layout.max_line_length, logger=logger)
def build_portrait_ass(
correction_result,
styles: dict,
audio_filepath: str,
output_dir: str,
output_prefix: str,
layout: PortraitLayout,
font_path: Optional[str] = None,
logger: Optional[logging.Logger] = None,
) -> str:
"""Generate the portrait lyrics ASS file and return its path."""
# Merge the caller's karaoke block over the theme defaults so required ASS style
# keys (primary_color, secondary_color, ...) always exist even for partial styles.
from karaoke_gen.style_loader import DEFAULT_KARAOKE_STYLE
merged = dict(DEFAULT_KARAOKE_STYLE)
merged.update(styles.get("karaoke", {}))
styles = {"karaoke": merged}
k = styles["karaoke"]
k["font_size"] = layout.font_size
k["max_visible_lines"] = layout.max_visible_lines
k["top_padding"] = _computed_top_padding(layout)
if font_path:
k["font_path"] = font_path
elif k.get("font_path") and not os.path.isfile(k["font_path"]):
# Drop an unresolved theme font path so libass falls back to the named font.
k.pop("font_path", None)
segments = prepare_portrait_segments(correction_result, layout, logger)
gen = SubtitlesGenerator(
output_dir=output_dir,
video_resolution=(layout.width, layout.height),
font_size=layout.font_size,
line_height=layout.line_height,
styles=styles,
logger=logger or logging.getLogger(__name__),
)
ass_path = gen.generate_ass(segments, output_prefix, audio_filepath=audio_filepath)
return ass_path
def render_portrait_video(
correction_result,
instrumental_path: str,
styles: dict,
artist: str,
title: str,
output_path: str,
*,
brand: Optional[PortraitBrandConfig] = None,
layout: Optional[PortraitLayout] = None,
font_path: Optional[str] = None,
work_dir: Optional[str] = None,
logger: Optional[logging.Logger] = None,
) -> str:
"""Render a portrait karaoke MP4 (title + lyrics body + end) and return its path.
Args:
correction_result: A ``CorrectionResult`` (already countdown-processed by the
caller, so its segment timings match ``instrumental_path``).
instrumental_path: The selected instrumental audio, padded to match the
countdown offset applied to ``correction_result``.
styles: Loaded theme style params (the ``karaoke`` block drives ASS colours).
artist, title: Displayed in the branded header.
output_path: Destination MP4 path.
brand: Branding/background config; defaults to a plain themed background.
layout: Portrait layout overrides.
font_path: Resolved local font file for the lyrics + header.
work_dir: Scratch dir for intermediates (a temp dir is used if omitted).
"""
logger = logger or logging.getLogger(__name__)
layout = layout or PortraitLayout()
brand = brand or PortraitBrandConfig(font_path=font_path)
if font_path and not brand.font_path:
brand.font_path = font_path
intro = float(styles.get("intro", {}).get("video_duration", layout.intro_seconds))
outro = float(styles.get("end", {}).get("video_duration", layout.outro_seconds))
_own_tmp = None
if work_dir is None:
_own_tmp = tempfile.TemporaryDirectory(prefix="portrait_")
work_dir = _own_tmp.name
os.makedirs(work_dir, exist_ok=True)
try:
# 1. Backgrounds
bg_body = os.path.join(work_dir, "bg_body.png")
bg_end = os.path.join(work_dir, "bg_end.png")
build_background(brand, artist, title, variant="lyrics").save(bg_body)
build_background(brand, artist, title, variant="end").save(bg_end)
# 2. Portrait lyrics ASS
ass_path = build_portrait_ass(
correction_result, styles, instrumental_path, work_dir,
"portrait", layout, font_path=font_path, logger=logger,
)
# 3. Assemble: title card + lyrics body + end card, single ffmpeg pass.
body_dur = _ffprobe_duration(instrumental_path)
ass_filter = f"ass='{_escape_ass_path(os.path.abspath(ass_path))}'"
if font_path and os.path.isfile(font_path):
ass_filter += f":fontsdir='{_escape_ass_path(os.path.dirname(os.path.abspath(font_path)))}'"
w, h = layout.width, layout.height
filtergraph = (
f"[1:v]{ass_filter},trim=duration={body_dur:.3f},setpts=PTS-STARTPTS,"
f"scale={w}:{h},setsar=1,fps=30[body];"
f"[0:v]scale={w}:{h},setsar=1,fps=30[intro];"
f"[2:v]scale={w}:{h},setsar=1,fps=30[outro];"
# Pair each card with its own silence and the body with the instrumental:
# intro(v)+intro_silence(4:a), body(v)+instrumental(3:a), outro(v)+outro_silence(5:a).
f"[intro][4:a][body][3:a][outro][5:a]concat=n=3:v=1:a=1[v][a]"
)
cmd = [
"ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
"-loop", "1", "-framerate", "30", "-t", f"{intro:.3f}", "-i", bg_body,
"-loop", "1", "-framerate", "30", "-i", bg_body,
"-loop", "1", "-framerate", "30", "-t", f"{outro:.3f}", "-i", bg_end,
"-i", os.path.abspath(instrumental_path),
"-f", "lavfi", "-t", f"{intro:.3f}", "-i", "anullsrc=r=48000:cl=stereo",
"-f", "lavfi", "-t", f"{outro:.3f}", "-i", "anullsrc=r=48000:cl=stereo",
"-filter_complex", filtergraph,
"-map", "[v]", "-map", "[a]",
"-c:v", "libx264", "-preset", "fast", "-crf", "20", "-pix_fmt", "yuv420p",
"-c:a", "aac", "-b:a", "192k", "-movflags", "+faststart",
os.path.abspath(output_path),
]
logger.info(f"Rendering portrait video ({w}x{h}, body {body_dur:.1f}s) -> {output_path}")
try:
# A full song encodes in well under a minute; 30 min is a generous ceiling
# so a stalled ffmpeg can never hang the encoding worker indefinitely.
result = subprocess.run(cmd, capture_output=True, text=True, timeout=1800)
except subprocess.TimeoutExpired as exc:
raise RuntimeError(f"Portrait ffmpeg timed out after {exc.timeout}s") from exc
if result.returncode != 0:
raise RuntimeError(f"Portrait ffmpeg failed: {result.stderr[-2000:]}")
if not os.path.isfile(output_path):
raise RuntimeError(f"Portrait render produced no output: {output_path}")
return output_path
finally:
if _own_tmp is not None:
_own_tmp.cleanup()
+105
View File
@@ -0,0 +1,105 @@
"""Balanced line-wrapping for portrait karaoke lyrics.
The landscape pipeline wraps lyric lines with ``SegmentResizer``, which splits at
natural break points (sentence ends, commas, conjunctions) calibrated for the wide
16:9 frame. In a narrow 9:16 frame the same splits — combined with a much smaller
``max_line_length`` — can leave orphan lines: a stray one- or two-word segment such
as ``"No,"`` sitting alone on a row. This module merges those orphans back into an
adjacent segment when the merged line still fits the portrait width and the two
segments are close together in time (i.e. part of the same sung phrase).
It operates on already-resized segments and only ever *merges* — it never re-splits —
so per-word karaoke timing is preserved exactly.
"""
from __future__ import annotations
import logging
from typing import List, Optional
from karaoke_gen.lyrics_transcriber.types import LyricsSegment
from karaoke_gen.lyrics_transcriber.output.segment_resizer import display_width
# A segment whose rendered width is below this (in half-width char units) is an
# "orphan" candidate — short enough to look stranded on its own row.
DEFAULT_ORPHAN_WIDTH = 8.0
# Only merge segments separated by at most this gap (seconds); larger gaps mean the
# lines belong to different phrases and should stay on separate rows.
DEFAULT_MAX_GAP_SECONDS = 1.5
def _merge(a: LyricsSegment, b: LyricsSegment) -> LyricsSegment:
"""Merge two temporally-adjacent segments (``a`` before ``b``) into one."""
words = a.words + b.words
text = f"{a.text} {b.text}".strip()
return LyricsSegment(
id=a.id,
text=text,
words=words,
start_time=min(a.start_time, b.start_time),
end_time=max(a.end_time, b.end_time),
singer=a.singer if a.singer == b.singer else None,
)
def _gap(a: LyricsSegment, b: LyricsSegment) -> float:
"""Non-negative time gap between the end of ``a`` and the start of ``b``."""
return max(0.0, b.start_time - a.end_time)
def balance_segments(
segments: List[LyricsSegment],
max_line_length: int,
*,
orphan_width: float = DEFAULT_ORPHAN_WIDTH,
max_gap_seconds: float = DEFAULT_MAX_GAP_SECONDS,
logger: Optional[logging.Logger] = None,
) -> List[LyricsSegment]:
"""Merge orphan (very short) segments into a neighbour when it fits the frame.
A segment is merged when:
* its rendered ``display_width`` is below ``orphan_width``, and
* a neighbour exists within ``max_gap_seconds``, and
* the merged line's ``display_width`` is ``<= max_line_length``.
When both neighbours qualify, the one with the smaller time gap wins. The pass
repeats until no further merge is possible, so a run of short fragments collapses
into as few well-filled lines as the width budget allows. Timing is preserved
because segments are only concatenated, never re-split.
"""
if not segments:
return []
result = list(segments)
changed = True
while changed:
changed = False
for i, seg in enumerate(result):
if display_width(seg.text) >= orphan_width:
continue
# Candidate merges: (merged_segment, replace_slice, gap)
candidates = []
if i + 1 < len(result):
nxt = result[i + 1]
if _gap(seg, nxt) <= max_gap_seconds and display_width(
f"{seg.text} {nxt.text}"
) <= max_line_length:
candidates.append((_merge(seg, nxt), (i, i + 2), _gap(seg, nxt)))
if i - 1 >= 0:
prev = result[i - 1]
if _gap(prev, seg) <= max_gap_seconds and display_width(
f"{prev.text} {seg.text}"
) <= max_line_length:
candidates.append((_merge(prev, seg), (i - 1, i + 1), _gap(prev, seg)))
if not candidates:
continue
merged, (lo, hi), _ = min(candidates, key=lambda c: c[2])
result[lo:hi] = [merged]
if logger:
logger.debug(f"Portrait balance: merged orphan into '{merged.text}'")
changed = True
break # indices shifted; restart the scan
return result
+1 -1
View File
@@ -1,6 +1,6 @@
[tool.poetry]
name = "karaoke-gen"
version = "0.192.7"
version = "0.195.1"
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"
View File
Whitespace-only changes.
+38
View File
@@ -0,0 +1,38 @@
"""Tests for portrait background generation and layout math."""
from karaoke_gen.portrait.background import PortraitBrandConfig, build_background
from karaoke_gen.portrait.renderer import PortraitLayout, _computed_top_padding
def test_background_dimensions_and_variants():
cfg = PortraitBrandConfig(width=1080, height=1920, brand_text="NOMAD KARAOKE",
footer_text="nomadkaraoke.com")
for variant in ("lyrics", "title", "end"):
img = build_background(cfg, "Piri", "Dog", variant=variant)
assert img.size == (1080, 1920)
assert img.mode == "RGB"
def test_background_custom_size():
cfg = PortraitBrandConfig(width=720, height=1280)
img = build_background(cfg, "A", "B", variant="lyrics")
assert img.size == (720, 1280)
def test_uppercase_meta_default_on():
# Smoke: uppercase path shouldn't error and still yields a valid frame.
cfg = PortraitBrandConfig(uppercase_meta=True, brand_text="NOMAD")
img = build_background(cfg, "piri", "dog", variant="lyrics")
assert img.size == (1080, 1920)
def test_computed_top_padding_centers_block():
"""top_padding should place the block centre near block_center_frac * height."""
layout = PortraitLayout(height=1920, line_height=118, max_visible_lines=4,
block_center_frac=0.60)
tp = _computed_top_padding(layout)
total = layout.max_visible_lines * layout.line_height
# Reproduce the generator's first-line formula and check the block centre.
first = tp + (layout.height - total - tp) // 4
block_center = first + total / 2
assert abs(block_center - layout.height * 0.60) < 20
assert tp >= 0
+76
View File
@@ -0,0 +1,76 @@
"""Tests for the backend wiring that emits/distributes the portrait video.
These cover the additive, non-fatal contract and the plumbing that carries the
portrait file to GCS + Dropbox (and keeps it out of YouTube/Drive) — without
needing the GCE VM or a real render.
"""
from pathlib import Path
from unittest.mock import MagicMock, patch
# Mock google.cloud.storage.Client only while importing main.py so this test collects
# in the wheel-only CI job (which has no GCP project/ADC). Scoped so we don't leave a
# session-wide global patch that could affect other tests.
with patch("google.cloud.storage.Client", MagicMock()):
import backend.services.gce_encoding.main as gce # noqa: E402
from backend.services.encoding_interface import EncodingOutput # noqa: E402
def test_encoding_output_has_portrait_field():
out = EncodingOutput(success=True, portrait_mp4_path="finals/x (Final Karaoke Portrait 1080x1920).mp4")
assert out.portrait_mp4_path.endswith("Portrait 1080x1920).mp4")
def test_portrait_render_disabled_returns_none(monkeypatch, tmp_path):
monkeypatch.setattr(gce, "PORTRAIT_RENDER_ENABLED", False)
result = gce.render_portrait_into_outputs(
"job1", tmp_path, tmp_path, "Artist - Title", "Artist", "Title",
tmp_path / "instr.flac", {},
)
assert result is None
def test_portrait_render_missing_corrections_is_non_fatal(monkeypatch, tmp_path):
# Enabled, but no corrections JSON present anywhere -> returns None, no raise.
monkeypatch.setattr(gce, "PORTRAIT_RENDER_ENABLED", True)
out_dir = tmp_path / "outputs"
out_dir.mkdir()
result = gce.render_portrait_into_outputs(
"job1", tmp_path, out_dir, "Artist - Title", "Artist", "Title",
tmp_path / "instr.flac", {},
)
assert result is None
def test_portrait_render_swallows_renderer_errors(monkeypatch, tmp_path):
"""A failure inside the renderer must not propagate (job must still finish)."""
monkeypatch.setattr(gce, "PORTRAIT_RENDER_ENABLED", True)
(tmp_path / "lyrics").mkdir()
(tmp_path / "lyrics" / "corrections_updated.json").write_text('{"corrected_segments": []}')
def _boom(*a, **k):
raise RuntimeError("render exploded")
import karaoke_gen.portrait as portrait_pkg
monkeypatch.setattr(portrait_pkg, "render_portrait_video", _boom)
# CorrectionResult.from_dict on a minimal dict may also raise; either way -> None.
result = gce.render_portrait_into_outputs(
"job1", tmp_path, tmp_path, "Artist - Title", "Artist", "Title",
tmp_path / "instr.flac", {},
)
assert result is None
def test_portrait_filename_classified_for_dropbox_not_drive():
"""The portrait file name must be routed to the portrait output slot."""
name = "Artist - Title (Final Karaoke Portrait 1080x1920).mp4".lower()
# Mirror the classification chain in GCEEncodingBackend.encode().
assert "portrait" in name
assert "lossless 4k" not in name and "lossy 4k" not in name and "720p" not in name
def test_orchestrator_downloads_portrait_into_output_dir():
"""The download allowlist must include the portrait mapping so it reaches Dropbox."""
import inspect
from backend.workers import video_worker_orchestrator as vwo
src = inspect.getsource(vwo.VideoWorkerOrchestrator._download_gce_encoded_files)
assert "('portrait_mp4_path', 'portrait_video')" in src
@@ -0,0 +1,96 @@
"""End-to-end portrait render on a tiny synthetic fixture.
Renders a real (short) portrait MP4 with ffmpeg and asserts the output dimensions,
total duration (title + body + end), and that lyrics are actually burned into the
body. Skipped when ffmpeg/ffprobe are unavailable.
"""
import os
import shutil
import subprocess
from types import SimpleNamespace
import pytest
from karaoke_gen.lyrics_transcriber.types import LyricsSegment, Word
from karaoke_gen.portrait import PortraitBrandConfig, PortraitLayout, render_portrait_video
pytestmark = pytest.mark.skipif(
not (shutil.which("ffmpeg") and shutil.which("ffprobe")),
reason="ffmpeg/ffprobe not available",
)
def _word(wid, text, start, end):
return Word(id=wid, text=text, start_time=start, end_time=end)
def _fixture_result():
seg1 = LyricsSegment(
id="s1", text="Hello portrait world", start_time=0.2, end_time=1.8,
words=[_word("w1", "Hello", 0.2, 0.7), _word("w2", "portrait", 0.8, 1.3),
_word("w3", "world", 1.4, 1.8)],
)
seg2 = LyricsSegment(
id="s2", text="Singing along tonight", start_time=2.0, end_time=3.6,
words=[_word("w4", "Singing", 2.0, 2.5), _word("w5", "along", 2.6, 3.0),
_word("w6", "tonight", 3.1, 3.6)],
)
return SimpleNamespace(corrected_segments=[seg1, seg2])
def _probe(path, entries):
out = subprocess.run(
["ffprobe", "-v", "error", "-select_streams", "v:0",
"-show_entries", entries, "-of", "default=noprint_wrappers=1:nokey=1", path],
capture_output=True, text=True, check=True,
).stdout.split()
return out
def test_render_portrait_end_to_end(tmp_path):
audio = tmp_path / "instr.flac"
subprocess.run(
["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", "-f", "lavfi",
"-i", "anullsrc=r=44100:cl=stereo", "-t", "4", str(audio)],
check=True,
)
out = tmp_path / "portrait.mp4"
# Short intro/outro to keep the encode quick.
styles = {"karaoke": {}, "intro": {"video_duration": 1}, "end": {"video_duration": 1}}
render_portrait_video(
correction_result=_fixture_result(),
instrumental_path=str(audio),
styles=styles,
artist="Test Artist",
title="Test Title",
output_path=str(out),
brand=PortraitBrandConfig(brand_text="NOMAD KARAOKE", footer_text="nomadkaraoke.com"),
layout=PortraitLayout(),
)
assert out.exists()
w, h = _probe(str(out), "stream=width,height")
assert (int(w), int(h)) == (1080, 1920)
dur = float(subprocess.run(
["ffprobe", "-v", "error", "-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1", str(out)],
capture_output=True, text=True, check=True,
).stdout.strip())
# 1s intro + 4s body + 1s outro.
assert abs(dur - 6.0) < 0.5
# Assert lyrics are burned in: a frame ~1s into the body must have bright text
# pixels the empty title card does not.
frame = tmp_path / "f.png"
subprocess.run(
["ffmpeg", "-hide_banner", "-loglevel", "error", "-y", "-ss", "2.0",
"-i", str(out), "-frames:v", "1", str(frame)],
check=True,
)
from PIL import Image
img = Image.open(frame).convert("L")
# Central lyric band should contain near-white text pixels.
band = img.crop((0, 900, 1080, 1500))
assert band.getextrema()[1] > 180, "expected bright lyric text in the body frame"
+77
View File
@@ -0,0 +1,77 @@
"""Tests for portrait balanced line-wrapping."""
from karaoke_gen.lyrics_transcriber.types import LyricsSegment, Word
from karaoke_gen.portrait.wrap import balance_segments
def _seg(seg_id, text, start, end):
# One synthetic word spanning the segment is enough for these tests; balance_segments
# only concatenates word lists, it does not inspect per-word timing.
return LyricsSegment(
id=seg_id,
text=text,
words=[Word(id=f"w{seg_id}", text=text, start_time=start, end_time=end)],
start_time=start,
end_time=end,
)
def test_orphan_merges_forward_when_it_fits():
segs = [
_seg("1", "No,", 10.0, 10.3),
_seg("2", "he only wants", 10.4, 12.0),
]
out = balance_segments(segs, max_line_length=19)
assert len(out) == 1
assert out[0].text == "No, he only wants"
# Words preserved and combined in order.
assert [w.text for w in out[0].words] == ["No,", "he only wants"]
assert out[0].start_time == 10.0
assert out[0].end_time == 12.0
def test_no_merge_when_result_would_overflow():
segs = [
_seg("1", "No,", 10.0, 10.3),
_seg("2", "he only wants the naughty shit", 10.4, 12.0),
]
out = balance_segments(segs, max_line_length=19)
# Merged line (34 chars) exceeds the width budget → leave both as-is.
assert [s.text for s in out] == ["No,", "he only wants the naughty shit"]
def test_no_merge_across_large_time_gap():
segs = [
_seg("1", "Oh,", 10.0, 10.3),
_seg("2", "later line", 30.0, 31.0), # 20s gap → different phrase
]
out = balance_segments(segs, max_line_length=19, max_gap_seconds=1.5)
assert [s.text for s in out] == ["Oh,", "later line"]
def test_prefers_smaller_gap_neighbour():
segs = [
_seg("1", "keep me here", 9.0, 9.9), # gap to orphan = 0.05
_seg("2", "hi", 9.95, 10.1), # orphan
_seg("3", "and далеко", 11.5, 12.0), # gap from orphan = 1.4
]
out = balance_segments(segs, max_line_length=20)
# Orphan "hi" should merge backward (smaller gap) into "keep me here".
assert out[0].text == "keep me here hi"
assert len(out) == 2
def test_long_run_of_fragments_collapses():
segs = [
_seg("1", "a", 1.0, 1.1),
_seg("2", "b", 1.2, 1.3),
_seg("3", "c", 1.4, 1.5),
_seg("4", "d", 1.6, 1.7),
]
out = balance_segments(segs, max_line_length=12)
# All fit within 12 chars → collapse to a single filled line.
assert len(out) == 1
assert out[0].text == "a b c d"
def test_empty_input():
assert balance_segments([], max_line_length=19) == []
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff. Show more