Compare commits

...
36 Commits
Author SHA1 Message Date
Andrew Beveridge ☄️andClaude Opus 4.8 6fa4400d3d feat(dr): back up all GitHub repos to S3 (survive a GitHub ban) (#929)
## Summary

Extends the nightly DR backup Cloud Function (`backup-to-aws`) to bundle
**every git repo under `github.com/nomadkaraoke` and
`github.com/beveradb`** into a per-repo `git bundle` on S3, so code +
full history survive a complete loss of GitHub access (e.g. an automated
copyright-strike account ban). Each bundle is directly cloneable —
restore is `git clone --mirror <bundle>` → `git push --mirror
<new-remote>`.

## Changes

- **`git_repos_export.py`** (new): enumerate repos via GitHub
`/user/repos` (includes private), mirror-clone + `git bundle create
--all`, upload to `git-repos/{owner}/{repo}.bundle` in staging, plus a
`manifest.json` inventory. Forks excluded, oversized/empty repos
skipped, per-repo errors non-fatal, org backed up **before** the
personal account for deadline resilience. PAT is read from Secret
Manager at **runtime** (not a deploy-time secret env var) so the
function deploys before the secret has a value and skips gracefully if
absent.
- **`main.py`**: new nightly Step 4b (between secrets export and S3
upload).
- **`infrastructure/modules/backup.py`**: bump function to 4Gi/2CPU
(mirror-clone uses in-memory `/tmp`); add `GIT_BACKUP_OWNERS` env.
- **`infrastructure/modules/secrets.py`**: new `github-backup-token`
secret (value added manually).
- **`.github/workflows/dr-backup-freshness.yml`**: monitor `git-repos/`
at 36h, counting only `.bundle` objects.
- **`docs/DISASTER-RECOVERY.md`**: new "Scenario 3: Loss of GitHub
access" + restore steps + token setup.

## Security

- The GitHub PAT is injected via a `GIT_CONFIG_*` `Authorization` header
(like `actions/checkout`), never in the clone URL/argv — so it can't
leak via `ps`, `TimeoutExpired`, or captured stderr. Token is also
redacted from any error text persisted into `manifest.json`.

## Testing

- 14 new unit tests for the module
(enumerate/filter/bundle/skip/error/security paths); full
`backup_to_aws` suite: **27 passing**.
- CodeRabbit local review (cycle 1) completed; all 4 findings (1
critical PAT leak, 2 major, 1 minor) addressed. Cycle-2 verification was
rate-limited (free-tier), so **left for the GitHub bot to review the
final diff**.

## Deploy notes

- **Pulumi already applied locally** (`github-backup-token` secret
created + function on 4Gi/2CPU) — CI re-run is a no-op.
- After merge, run `infrastructure/functions/backup_to_aws/deploy.sh` to
ship the new function source, then set the PAT:
`printf %s '<PAT>' | gcloud secrets versions add github-backup-token
--data-file=- --project=nomadkaraoke`
- Requires a classic GitHub PAT (owner: beveradb, member of nomadkaraoke
org) with `repo` + `read:org`.

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

---
@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-23 00:44:52 -04:00
Andrew Beveridge ☄️ d7482ee85a feat(review): vocals waveform in timeline editor — finished + fixed (takes over #895) (#927)
Vocals waveform in the timeline editor (finishes @netux's #895): backend stem-selection fix (vocals_clean), downsampled peak-envelope perf, edit-modal space reclaim, full i18n (33 locales), CodeRabbit fixes, and ReviewServer.vocals_filepath made optional. Reviewed + visually QA'd on a real job.
2026-08-23 00:23:18 -04:00
Andrew Beveridge ☄️andClaude Fable 5 0497168dda feat(admin): UX/UI overhaul — overflow fixes, mobile responsiveness, clickable dashboard (v0.197.0) (#928)
## Summary

UX/UI overhaul of the admin pages, focused on the most-used surfaces
(dashboard, jobs list/detail, users list/detail), fixing reported
overflow bugs and making everything usable on mobile.

### Job detail page (`/admin/jobs?id=...`)
- **Status timeline**: long timelines (retries/edits) collapse to the
last 6 stages behind a `+N earlier (M failed)` expander chip, with a
Collapse chip when expanded; resets when switching jobs
- **Source field overflow fixed**: info-grid cells get `min-w-0` so long
source strings truncate instead of bleeding across
Created/Progress/Total Time
- **Audio Source Details modal**: rebuilt with stacked wrap-safe rows
(no clipped values), scrollable, plus a prominent "Open in
YouTube/Spotify" link built from provider + source ID
- **Configuration fields**: click-to-edit values with always-visible
pencil (was hover-only); empty values show "— click to set"
- **Bug fix**: "Trigger Now" in the reset-result dialog called a deleted
`handleTriggerWorker` (runtime crash); reimplemented via
`adminApi.triggerWorker`
- 404 job load no longer shows a redundant error toast (also fixes a
pre-existing flaky e2e)
- Skips loading the 100-job list while viewing a single job
- `generating_screens` status gets a label + filter option

### Jobs list
- Search box jumps straight to the detail page when given a job ID
- Status filter synced to URL (`?status=failed` is shareable/linkable)
- Compact created dates; User/Progress/Created columns hidden on small
screens

### Dashboard
- Stat cards link to their pages; Job Status Breakdown rows link to the
pre-filtered jobs list

### Users list/detail + layout
- Responsive columns, truncation-safe email cells, mobile-stacking
detail header, break-all for long emails/fingerprints
- Breadcrumb shows "User Detail" instead of raw "detail" segment; header
no longer overflows on phones

## Testing
- 4 new e2e tests (timeline collapse/expand, short-timeline no-collapse,
provider link from source ID, job-ID search jump); full admin-job-detail
spec 28/28 passing
- Full regression e2e suite: 171 passed; frontend unit tests: 1132
passed
- Visually verified at 1280px and 390px widths with mocked-API renders
(worst-case long timeline + long source strings)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-22 23:54:59 -04:00
Martín Rodríguez 21c58289b6 fix(frontend): correct timeline editor collision checks (#893)
Reviewed, verified locally against fixture review data, and merged by maintainer. Thanks @netux!
2026-08-22 22:25:59 -04:00
Martín Rodríguez a3ab2a4048 fix(frontend): make only the word list scrollable in the lyrics review edit modal (#896)
Reviewed, verified locally against fixture review data, and merged by maintainer. Thanks @netux!
2026-08-22 22:25:56 -04:00
Martín Rodríguez 9ac53e32b6 feat(frontend): read API base url from query parameters in localhost frontend (#894)
Reviewed, verified locally against fixture review data, and merged by maintainer. Thanks @netux!
2026-08-22 22:25:53 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 d98e90c1d7 fix(audio-download): wire POSTMARK_SERVER_TOKEN into audio-download-job + resilient email construct (#925)
## Summary

Fixes production job `a453d1d5` (Regina Spektor – Laughing With), which
failed with:

> Audio download failed: POSTMARK_SERVER_TOKEN is not set in production.
Refusing to silently drop emails via the console provider — set the
Postmark token secret.

### Root cause
The audio download worker runs as its **own Cloud Run Job**
(`audio-download-job`) — a thin orchestrator that calls the flacfetch VM
over the VPC and waits, then triggers separation + lyrics. Each Cloud
Run Job has an **independent env block**, and `audio-download-job`'s
block omitted `POSTMARK_SERVER_TOKEN` (it was wired only into
`karaoke-backend` and `video-encoding-job`).

`audio_download_worker` → `reconcile_and_maybe_pause()` **eagerly**
builds `get_email_service()` on every no-edit download, even though
email is only sent in the rare over‑60‑min cancel branch.
`EmailService()` deliberately raises in production when the token is
absent (2026‑06‑09 fallback‑audit "fail loudly" guard), so the whole
download failed.

Blast radius was small (1 job in Firestore) because jobs that stop at
`AWAITING_AUDIO_EDIT` never reach reconcile — but it recurs for every
automated/no‑edit download.

## Changes
- **infra** (`infrastructure/modules/cloud_run.py`): add
`POSTMARK_SERVER_TOKEN` secret env to `audio-download-job` so the
over‑limit cancellation email works. *(Needs `pulumi up` — applied
locally before merge.)*
- **`backend/services/duration_reconciliation.py`**: wrap
`get_email_service()` in try/except → log and proceed with
`email_service=None`. A construct‑time email failure can no longer crash
an otherwise‑successful paid download (`reconcile_duration` already
tolerates `None`; over‑limit still cancels + refunds).
- **tests**: `survives-email-service-failure` (proceeds) and
`over-limit-still-cancels-without-email`.
- **`backend/config.py`**: corrected a stale comment claiming
`lyrics-transcription-job` needs `ANTHROPIC_API_KEY` — the LLM work
actually runs on the API service (`auto_correct_worker`), not the lyrics
job.
- version bump 0.196.9 → 0.196.10.

## Env audit
Audited **all** Cloud Run Jobs' env vs. their worker code paths. The
only production hard‑fail pattern is the `EmailService` guard; the
POSTMARK gap was **unique to `audio-download-job`**. `bulk-search-job`
and `lyrics-transcription-job` never construct `EmailService` on their
path; `video-encoding-job` already has the token and is doubly defended.
No other env vars need adding.

## Testing
- `test_duration_reconciliation.py` 14/14,
`test_audio_download_worker.py` 37/37, `test_email_service.py` included
— 94 passed.
- CodeRabbit local review: no findings.

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-22 21:55:50 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 0bba4ff041 fix(made-for-you): isolate order emails from audio-acquisition failures (#924)
## Problem

Job `17dc6f48` (a Made-For-You order) failed on a YouTube "confirm
you're not a bot" download error, and the admin **never received the
"New Made-For-You Order Received!" email** — leaving no signal that a
paid order needed attention, and no certainty the customer got their
confirmation. The Discord error monitor also fired `'EmailService'
object has no attribute 'send_email'`.

Two root causes in `_handle_made_for_you_order`
(`backend/api/routes/users.py`):

1. **Emails were sent *after* audio acquisition.** Both the customer
confirmation and the admin notification ran only after the fallible
YouTube download / audio search. When acquisition raised, execution
jumped to the error handler, **skipping both emails.**
2. **The error fallback itself crashed.** It called
`email_service.send_email(...)`, but that method existed only on the
*provider* (`self.provider.send_email`), never on `EmailService` — so
even the failure alert was lost.

## Changes

- **Send the customer order-confirmation email up-front**, right after
job creation and *before* audio acquisition. The order is paid/confirmed
regardless of the download/search outcome. Resilient: a delivery failure
is logged, not fatal.
- **Wrap the admin notification** so an email hiccup on a successful
order can't fake a `[FAILED]` alert.
- **Route the outer failure handler through
`_send_mfy_failure_alert()`** — never raises, HTML-escapes user input,
tolerates `job_id=None`. Success → normal admin notification;
audio-acquisition failure → `[FAILED]` admin alert while the customer
stays confirmed.
- **Add a thin `EmailService.send_email()` passthrough** to the provider
(fixes the `AttributeError`).
- **Handle `False` provider results** (providers signal rejection by
returning `False`, not raising): log accurately instead of always
"Sent"; a rejected *customer* confirmation is escalated to the admin so
it can be resent manually.
- **Retry dropped paid orders:** if job creation fails (no `job_id`,
session never marked processed), re-raise after alerting so the Stripe
webhook returns non-2xx and Stripe retries. Post-creation failures keep
`job_id` set and return 200 to avoid duplicate jobs on retry.
- Idempotency preserved: the Stripe session is marked processed before
the confirmation send, so a webhook retry can't double-send.

## Out of scope

The YouTube "confirm you're not a bot" download error itself is a
separate flacfetch/yt-dlp cookies issue (credential keeper) — this PR
only makes the order emails resilient to it.

## Testing

- `make`-level backend suites for made-for-you, tenant/email,
admin-feedback, internal-webhook all green (138 passed locally).
- New/updated regression tests:
  - customer confirmation survives a YouTube download failure
- confirmation-email failure doesn't abort order processing (and is
escalated)
  - provider-returns-`False` confirmation is escalated
  - job-creation failure re-raises (Stripe retry) after alerting
  - `EmailService.send_email` passthrough delegates to the provider
- Local CodeRabbit review: 2 findings addressed, re-run clean (no new
findings).

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-22 19:23:48 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 c76d58394d fix(fallbacks): T7 — prod fail-fast on missing config + tenant gate safe-by-default (#808)
## Summary
Theme 7 of the silent-fallback audit
(`docs/archive/2026-06-09-fallback-audit-plan.md`, in #805). A single
unset/rotated env var used to silently produce wrong behaviour in prod
with only a warning. Now production fails fast / is safe-by-default.
Verified against Pulumi infra: prod sets `ENVIRONMENT=production`,
`CLOUD_RUN_SERVICE_URL`, `GCS_BUCKET_NAME`, `GOOGLE_CLOUD_PROJECT`, and
Postmark (secret); Cloud Run also auto-sets `K_SERVICE`.

## Changes
- **`config.is_production()` + `validate_production_config()`** (called
from `main.py` lifespan): production refuses to boot if
`GOOGLE_CLOUD_PROJECT`, `GCS_BUCKET_NAME`, or `CLOUD_RUN_SERVICE_URL`
are unset — instead of silently using a dev default (wrong project for
secret lookups / wrong bucket / localhost worker URL). This **subsumes
7.3** (worker_service localhost fallback). `is_production()` treats
Cloud Run's auto-set `K_SERVICE` as production, so it's robust even if
`ENVIRONMENT` were unset.
- **Tenant middleware (7.4, security)**: the `?tenant=` override (a
spoofing vector) is now disabled whenever `K_SERVICE` is present, not
only when `ENVIRONMENT=production` — production-safe by default.
- **dropbox_service (7.1)**: `GOOGLE_CLOUD_PROJECT` default was the
**wrong literal** `"karaoke-gen"` (real project is `nomadkaraoke`);
replaced with an empty default (prod requires it via the startup gate).
- **email_service (7.5)**: a missing `POSTMARK_SERVER_TOKEN` in
production used to silently use the console provider (sends "succeed"
while emails vanish). Now raises in production; console fallback remains
for dev/test.

## Deferred (flagged)
**7.2** `GCS_TEMP_BUCKET` / `GCS_OUTPUT_BUCKET` — these are **not** set
via env in infra, so their config defaults are load-bearing. Requiring
or changing them risks prod, so deferred pending confirmation of whether
those buckets are actually used.

## Testing
- [x] New `backend/tests/test_fallback_prod_config.py` (is_production,
validate gate raise/pass/no-op, email prod-raise vs dev-console, tenant
K_SERVICE)
- [x] 111 related tests pass (email, tenant, config) — no regressions,
no cross-test pollution from the tenant module reload

## Review
- [x] CodeRabbit CLI review completed locally (0 findings)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-22 19:01:23 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 51d9233cb8 fix(fallbacks): T4 — fail loud on missing configured render asset (font dir, background) (#807)
## Summary
Theme 4 of the silent-fallback audit
(`docs/archive/2026-06-09-fallback-audit-plan.md`, in #805). A
*configured* branded render asset that is missing must not silently
substitute a different font/background on a paid deliverable. Mirrors
the existing background-image check in
`output/video.VideoGenerator.__init__` (which already raises).

## Changes
- **`output/video._build_ass_filter`** (4.1): when the theme's karaoke
`font_path` is set but the file is missing, the final MP4 used to
silently drop `:fontsdir` → libass resolves a system fallback font for
the whole song. Now raises `FileNotFoundError`. *(Unset `font_path` is
still fine — no fontsdir, no raise.)*
- **`video_generator._create_background`** (4.3): a set-but-missing
title/end-screen `background_image` used to silently fall back to a flat
color. Now raises `FileNotFoundError`. *(No background configured is
still fine — flat color.)*

## Scope (per your decision)
Only these two clean "configured-but-missing → raise" cases are changed.
The font **substitution** items (4.2 title/end font, 4.4 CDG→arial, 4.8
measurement font) and duet/colour items (4.5–4.7) are **left as-is** —
font substitution overlaps with legitimate CJK font fallback
(`test_video_generator_cjk_font.py`) and warrants per-item treatment.

## Testing
- [x] New `tests/unit/test_fallback_render_assets.py` (raise +
legitimate-unset cases)
- [x] 105 render/video tests pass

## Review
- [x] CodeRabbit CLI review completed locally (0 findings)

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-22 18:50:16 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 6c374842f9 infra: Firestore composite index for jobs by request_metadata.client_id (#923)
## Problem

`karaoke-backend` started logging `400 The query requires an index` for
`GET /api/jobs?client_id=` (both "Error listing jobs" and "Error listing
jobs summary" patterns — one prod error alert). The query filters
`request_metadata.client_id` + `tenant_id` and orders by `created_at`,
with no composite index.

This surfaced because the **fiverr-agent** now tags the jobs it creates
with `client_id="fiverr:{order_id}"` and calls that endpoint for
idempotency (finding an existing job before creating one).

## Fix

Adds `firestore-index-jobs-client-id` to the IaC:
- `request_metadata.client_id` ASC
- `tenant_id` ASC
- `created_at` DESC

(matches the index Firestore's error link requested).

## Applied

Already applied to prod via `pulumi up` (`+1 created, 294 unchanged` —
clean preview, no other drift). Verified: `GET
/api/jobs?client_id=fiverr:…` now returns **200** (was 500/400). This PR
codifies the change to prevent IaC drift.

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

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

## Summary by CodeRabbit

* **Bug Fixes**
* Improved database query support for filtering jobs by client and
tenant while sorting by newest first.
  * Helps ensure relevant job results load reliably and efficiently.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-22 18:49:13 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 5fff6d67b0 fix(fallbacks): T1 — flacfetch sole downloader, no silent YouTube downgrade (#806)
## Summary
Theme 1 of the silent-fallback audit
(`docs/archive/2026-06-09-fallback-audit-plan.md`, added in #805).
flacfetch is the sole/lossless downloader — a configured-remote failure
must not silently downgrade to a local YouTube-only rip. This is the
exact class as the 2026-06-08 Facebook-URL incident.

## Changes
- **`audio_search_service._search_remote`**: a `FlacfetchServiceError`
from the remote service was swallowed and silently re-run against the
local YouTube-only fetcher. Now fails loudly (`AudioSearchError`) and
clears cached state. **No silent downgrade.**
- **`create_audio_fetcher`** (local CLI factory): a half-configured
remote (exactly one of `FLACFETCH_API_URL`/`FLACFETCH_API_KEY`) used to
warn and silently use local mode, masking a deploy/secret typo. Now
raises `AudioFetcherError`.

## Scope / deferred (needs your call)
Findings **1.2** (tracker configured-but-unusable → silently
YouTube-only) and **1.4** (`select_best` → first result on ranking
failure) live in the **shared local `FlacFetcher`** and have dedicated
tests asserting graceful local-CLI behaviour
(`test_select_best_handles_exception`). Your "fail loud" directive was
framed around the *cloud* silent-downgrade; hard-failing the local CLI
when a user simply has no usable tracker would change intentional local
behaviour. **Deferred for a per-item decision** rather than steamrolled
— see the audit plan doc.

## Testing
- [x] `backend/tests/test_audio_search.py` +
`tests/unit/test_audio_fetcher.py` pass (209)
- Added: remote-error-does-not-fall-back-to-local; updated the two
half-config factory tests to expect a raise.

## Review
- [x] CodeRabbit CLI review completed locally (1 major finding: clear
cached results on failure — fixed)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-22 18:35:12 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 27a5d8fdff fix(fallbacks): T8 — fail loud cleanups (docstrings, download errors, admin-token signal) (#805)
## Summary
First (low-risk) batch of the silent-fallback audit — see
`docs/archive/2026-06-09-fallback-audit-plan.md` for the full catalogue
and Andrew's per-theme decisions. This PR is **Theme 8**: fix
lying/stale docstrings, surface specific download-failure reasons, and
make an empty admin-token config a loud signal.

## Changes
- **Fail-open docstring lie → fail-closed**
(`credit_evaluation_service.py`, `config.py`): the AI credit evaluator
is fail-CLOSED (`pending_review`, no auto-grant) but its docstrings
claimed fail-open. Corrected so a future maintainer can't "fix" the code
into a free-credit-abuse hole.
- **Stale yt-dlp docstrings** (`youtube_download_service.py`,
`lyrics_worker.py`): removed text still describing the deleted
local-yt-dlp fallback. flacfetch is the sole downloader; the service
raises when unconfigured.
- **Specific download errors** (`audio_worker.py`, `lyrics_worker.py`):
`download_audio()` now raises a specific `DownloadError` per failure
mode instead of returning `None` → generic "Failed to download audio
file". Workers map it to a clear `Audio download failed: <reason>`
job-failure message.
- **Loud admin-token signal** (`auth_service.py`): empty `ADMIN_TOKENS`
now logs at ERROR (error-monitor → Discord) instead of a quiet warning.
It fails closed (403 everywhere) and looked like an auth bug rather than
a config error.
- Adds the audit plan doc + a `LESSONS-LEARNED` principle ("don't invent
silent fallbacks — ask or fail loud").

## Testing
- [x] Affected backend tests pass locally (85 passed): `test_workers`,
`test_workers_extended`, `test_audio_worker_download`,
`test_auth_admin_tokens`
- [x] Import sanity check (no circular import from new `DownloadError`
imports)
- Updated `test_download_audio_url_without_gcs_path_refuses` to expect
`DownloadError`; added no-source raise tests for both workers +
admin-token tests.

## Review
- [x] CodeRabbit CLI review completed locally (1 minor doc finding,
fixed)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-22 18:19:30 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 3d56dd4108 fix: connectivity banner only on real read stall (not slowness) (#922)
## Why

Follow-up to #921. In prod the connectivity banner was **too
sensitive**:
1. It fired during a normal lyrics-review load — the 2.5s "slow request"
hint tripped on any request taking >2.5s, even successful ones.
2. The "Preview Video" modal showed **"The server is temporarily
unavailable"** — the long-running preview-generation POST (video encode,
often >45s) hit apiFetch's blanket 45s hard-timeout and failed, even
though the backend was fine.

## What

- **`backend-status.ts` — status now derives purely from a real STALL.**
It tracks how long the *oldest in-flight tracked read* has been
outstanding: `reconnecting` at 10s, `unavailable` at 20s, back to
`online` the instant it settles. A read that completes — even a
normal-slow 3–5s one — surfaces **nothing**.
- **`apiFetch` — GET-only tracking + GET-only hard-timeout.**
- Only GETs feed the banner (a page waits on reads during a recycle;
long POSTs are legitimately slow).
- The 45s hard-timeout backstop applies to **GETs only** —
preview/generate/search POSTs run **untimed** to completion, fixing the
false "unavailable" error.
- New `opts.trackConnectivity: false` lets a known-slow read opt out;
`opts.timeoutMs` still time-boxes any call.

Retry semantics unchanged (GET-only, never replays a mutation).

## Testing
- Rewrote store + apiFetch unit tests for the stall model: POST
untracked, POST not hard-timed-out (signal not aborted after 60s), a
stalled GET → reconnecting→unavailable→clear, fast failures stay
`online`.
- Full suite green: **1132 passing**.
- Banner rendering re-verified locally.
- Local CodeRabbit review: **no findings**.

No infra changes in this PR.

@coderabbitai ignore

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-22 17:57:14 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 c65a920a59 feat: graceful backend-outage handling + soften uptime alert noise (#921)
## Why

A "Karaoke Backend - Service Unavailable" uptime alert fired at 06:06
UTC on 2026-08-22 and auto-recovered ~1m41s later. Investigation showed
it was a **routine Cloud Run instance recycle** on `--min-instances 1`:
the single warm instance (up ~9.6h) was reaped at 06:01:53, leaving a
~80s gap with no origin, so Cloudflare failed the health check from all
6 checker regions at once. No crash/OOM — a self-healing platform
recycle. (Full write-up:
`docs/archive/2026-08-22-health-check-alert-noise-and-graceful-degradation.md`.)

We're deliberately keeping `--min-instances 1` for cost, so this
addresses the two things we *can* control: alert noise, and how the UI
behaves during such a blip.

## What

**1. Soften the uptime alert** (`infrastructure/modules/monitoring.py`)
- Condition `duration` 60s → **300s**: a sub-5-min self-healing recycle
no longer pages; a sustained hard-down still fires (~5–6 min). Incident
documented in-code.

**2. Graceful frontend degradation**
- `lib/api.ts` — new **`apiFetch`** wrapping every backend call:
non-aborting 2.5s "reconnecting" hint, hard-timeout backstop, **safe
retries (GET only — never replays a mutation)**, transient-status
detection (502/503/504 + Cloudflare 52x), GCS/third-party passthrough.
Throws a typed `BackendUnavailableError`.
- `lib/backend-status.ts` — framework-agnostic connectivity store
(`online | reconnecting | unavailable`); escalates to `unavailable` on a
10s clock, clears to `online` on any success.
- `components/backend-status-banner.tsx` — one reassuring app-wide
banner (mounted under `[locale]`, covers landing + logged-in dashboard +
review screens), **i18n across all 33 locales**. `/admin/*`
intentionally excluded. Copy reassures that in-flight renders are
unaffected.

During a real recycle the dashboard's own polling drives the banner and
it self-heals when the backend returns — no refresh needed.

## Testing
- New unit tests: `__tests__/backend-status.test.ts`,
`__tests__/api-fetch.test.ts` (GET retry→10s escalation, transient 503,
transparent recovery, non-GET never retried, `Request`-input
method/signal, GCS passthrough, caller-abort passthrough). Updated
`completeJobUpload` assertion.
- Full suite green: **1130 passing**.
- Banner verified visually locally (reconnecting + unavailable, en +
es).
- Local CodeRabbit review: 5 findings (1 major, 4 minor) all addressed;
cycle 2 clean.

## Deploy notes
- Infra change: `pulumi up` run locally before merge to avoid IaC drift
(Pulumi CI re-runs as no-op).

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-22 17:11:58 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 df93eb9f82 feat(status): opaque System Status modal + live encoding-worker instance type (#920)
## Summary

Two fixes to the **System Status** modal (opened from the version
footer):

### 1. Modal was transparent
The modal set `backgroundColor: var(--card-bg)` — but `--card-bg` is
**defined nowhere** in the codebase (the real vars are `--card` /
`--card-border`). An undefined CSS variable makes the property invalid,
so the modal fell back to `transparent` and the job list showed through
it (see the reported screenshot).

Fixed by using defined opaque surfaces:
- Dialog shell → `var(--bg)` (`#0f0f0f` dark / `#f8fafc` light)
- Service cards → `var(--card)` (`#1a1a1a` dark / `#ffffff` light)

This was the only usage of the phantom `var(--card-bg)` anywhere in the
frontend.

### 2. Show the currently-live encoding worker
Given the recent c4d stockout / multi-instance-family fallback work,
admins couldn't see **which** worker was actually serving or its
instance type. The live worker is the `active_override` VM when a
capacity fallback has routed off the primary, else the c4d blue-green
primary.

- **Backend** (`/health/system-status`): the admin-only encoder
`admin_details` now carries `active_vm`, `active_zone`,
`active_machine_type`, and `on_fallback`. The instance type is derived
via the existing `infer_machine_type` helper (primary →
`c4d-highcpu-32`; fallbacks decoded from the VM-name family token, e.g.
`…-fallback-n2c` → `n2-highcpu-32`).
- **Frontend**: a new `LiveWorkerSection` on the Encoder card shows the
instance type prominently, the serving `VM · zone`, and an amber
**"Fallback"** badge + notice when running off the primary due to a
stockout. The existing Blue-Green expander is unchanged.

## Changes
- `backend/api/routes/health.py` — compute live-worker fields (admin
only)
- `frontend/components/system-status-modal.tsx` — opaque vars +
`LiveWorkerSection`
- `frontend/lib/api.ts` — `ServiceStatus.admin_details` new fields
- `frontend/messages/*` — 3 new `status` keys translated to all 32
locales

## Testing
- `make test` — full suite green (backend 1741+3878+103, frontend 1115
tests / 86 suites)
- Added a capacity-fallback path test to
`test_system_status_endpoint.py`
- Added `frontend/__tests__/system-status-modal.test.tsx` (primary,
fallback badge/notice, non-admin omission)
- CodeRabbit reviewed locally; addressed 3 minor translation-grammar
findings (ja/sk/ro)

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-20 22:47:16 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 3e666c28bb fix(e2e,submit): tolerate Stripe layout A/B + retry tenant upload-complete (#919)
## Problem

Two independent daily-E2E failures fired alerts:

- **E2E Daily #138/#139 (Credit Purchase)** — timed out 30s at
`stripe-checkout.ts` waiting for a top-frame `Pay` button.
- **Tenant E2E #80 (`vocalstar`; `singa` passed)** — timed out 120s
waiting for "Track Submitted".

## Root causes (both investigated to ground truth)

**1. Stripe Checkout layout flipped again (test-only).**
Stripe has now oscillated its hosted Checkout layout **three times**,
strongly implying A/B testing / staged rollout:
- Apr (#715): multi-method accordion of **radios**, card fields in
iframes, Pay in top frame
- Aug 17 (#916): **single-method**, direct textbox inputs, no chooser
- Now: multi-method **Payment Element** where the chooser is **buttons**
and the whole element — chooser, card fields **and the Pay button** — is
inside a **nested iframe**

`page.getByRole(...)` only searches the top frame, so the Pay button
(now nested) was invisible → 30s timeout. The real checkout rendered
correctly throughout (right product, referral 70% off, $3.00 total).

**2. Tenant submit: network blip on the final completion call (real,
transient).**
For `vocalstar` the submit **created the job + deducted a credit**, both
files reached GCS (verified in the bucket), but the final
`completeJobUpload()` `fetch` failed at the network layer — it never
reached the server (zero backend logs) — and threw a non-`ApiError`,
surfacing the generic "Something went wrong" while stranding the
paid-for job at "Setting up". `singa` passed the identical flow seconds
earlier.

## Changes (v0.196.2)

- **`frontend/e2e/helpers/stripe-checkout.ts`** — rewritten to be
**layout-agnostic**: searches **every frame** (top + nested iframes) for
the Pay button, the Card chooser (radio **or** button), card fields
(direct **or** iframe), ZIP and save-info toggle. Prominent doc-comment
cataloguing the three observed variants with a "do not narrow to one
layout" warning.
- **`frontend/lib/api.ts`** — `completeJobUpload` now retries
**network-level** failures (3 attempts, backoff). HTTP errors are never
retried (deterministic). Self-heals the exact failure observed.
- **`frontend/components/job/TenantJobFlow.tsx`** — logs the real error;
shows a network-specific message (`submitNetworkError`, translated to
all 33 locales).
- Tests: 3 new `completeJobUpload` retry tests; tenant error-mapping
tests updated. All pass; tsc/eslint clean on changed files.

## Verification

- Dispatched `e2e-daily.yml` on this branch (test code from branch,
driving **production**):
- **Stage 1: Credit Purchase — ✅ success** (real ~$3 charge through the
new nested-iframe Stripe layout — directly exercises the helper fix)
  - Stage 2: Happy Path — validating (orthogonal to these changes)
- Run:
https://github.com/nomadkaraoke/karaoke-gen/actions/runs/32394417473
- Local CodeRabbit review completed; one legit finding fixed (Hebrew
register), one false positive skipped (`ApiError` is exported at
`api.ts:3982`; the new `toBeInstanceOf(ApiError)` test passes).

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-20 13:18:04 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 03464145b5 fix(monitoring): replace flaky instance-count-absence alert with /api/health uptime check (#918)
## Summary
- The **"Karaoke Backend - Service Unavailable"** alert fired a false
page at 2026-08-19 03:15 UTC. Root cause: it alerted on *absence* of the
`run.googleapis.com/container/instance_count` metric, which is a sampled
series that legitimately blinks out for a `min-instances=1`, low-traffic
service. Logs confirmed the same instance was serving the scheduled
recover-stuck-jobs / retry-render crons with HTTP 200 the whole time —
zero errors, no instance replacement.
- Replaces the metric-absence condition with a real **Cloud Monitoring
uptime check** against `https://api.nomadkaraoke.com/api/health`
(through the Cloudflare edge, the same path real users take; body must
contain `"healthy"`).
- Pages only when the check **fails from more than one checker
location**, so a single flaky checker can't page us but a genuine
hard-down fires in ~1–2 min.

## Changes
- `infrastructure/modules/monitoring.py`:
- New `UptimeCheckConfig` `backend-health-uptime-check` (HTTPS GET
`/api/health`, 60s period, content matcher `"healthy"`).
- `service-unavailable-alert` condition changed from
`condition_absent(instance_count)` → `condition_threshold` on
`monitoring.googleapis.com/uptime_check/check_passed`
(`REDUCE_COUNT_FALSE` grouped by host, fire when `>1` failing checker
location).
  - Updated the alert documentation accordingly.

## Deployment status
- **Already applied to the `prod` stack** via targeted `pulumi up` (`+1
created` uptime check, `~1 updated` policy). Verified live: uptime check
passing 100% from all checker locations (`fraction_true=1.0`,
`COUNT_FALSE=0`) — confirms Cloudflare does not block Google's checkers.
This PR reconciles `main` with the deployed state; CI's pulumi apply is
a no-op.

## Testing
- [x] `pulumi preview` / `pulumi up` on prod stack (targeted; unrelated
runner-manager drift left untouched)
- [x] Uptime check verified passing from all checker locations
post-deploy
- [x] Alert policy condition + docs verified on the deployed policy
- N/A `make test` — infra-only Pulumi change, not covered by app test
suites

## Review
- [x] Local CodeRabbit review completed (1 major finding: "count checker
locations, not regions" — addressed by making the condition name + docs
accurately say "checker location")
- [x] Final CodeRabbit pass: no new findings

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-19 10:45:16 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 cd4c88ca3e fix(visibility): make public→private atomic; fix redistribute crash (NOMAD-1537 gap) (#917)
## Summary

Investigated a `⚠️ GDrive Validation: missing NOMAD-1537` alert. Root
cause was **not** a brand-code allocation race — it was a
**public→private visibility change** on job `25d076e5` (`Alma Nocturna –
Mejor Cállate`) that:

1. deleted the public YouTube/Dropbox/GDrive outputs and recycled
`NOMAD-1537`, **then**
2. crashed the private redistribution on an illegal `complete →
packaging` state transition (`redistribute_video` drove the normal
orchestrator progress path on an already-`complete` job).

So the flow was **delete-first with no rollback**: public files gone,
private archive never created. The gap self-closed when an unrelated
public job (`Luvcat – Spider`) reused the recycled number. The customer
track was fine (GCS-backed downloads intact + correctly private), but
every public→private conversion was silently failing its private-side
archive, and each leaked a `NOMADNP` code.

## Changes

- **A — fix the crash:** `OrchestratorConfig.redistribute_mode`;
`_update_progress` updates progress only and skips status transitions
when redistributing a `complete` job. `redistribute_video` sets it.
- **B — distribute-then-delete:** `change_to_private` captures the
public refs, redistributes to the private destination first, and only on
success deletes the public outputs + recycles the public number. On
redistribution failure it reverts to public — nothing deleted (YouTube
deletion is irreversible, so it must be last).
- **C — no leaked codes:** a redistribution that fails after allocating
a `NOMADNP` code recycles it.
- **Hardening (from local CodeRabbit review):** `redistribute_video`
verifies the archive actually materialized (brand code + Dropbox upload)
before reporting success — the orchestrator swallows those failures as
warnings; the public number is recycled only when every public deletion
succeeded; revert-to-public happens only pre-deletion.

**Validator intentionally unchanged.** Going-private is a rare,
legitimate cause of a transient gap that the next public track refills;
the owner wants to keep receiving that warning.

## Testing

- New/updated unit tests: distribute-then-delete ordering, real rollback
(no public deletion + revert on failure), `redistribute_mode` skips
status transition, public/private brand-code recycle, recycle-gating on
incomplete cleanup.
- Green: `test_change_visibility.py`,
`test_video_worker_orchestrator.py`, `test_brand_code_service.py`,
`test_private_tracks.py`, `test_cleanup_distribution.py`,
`test_admin_delete_outputs.py` (326 tests).

## Follow-up (post-merge, operational)

- Recover job `25d076e5`: re-run `redistribute_video('25d076e5')` (GCS
finals intact) to create its NonPublished archive + `NOMADNP` code.
- Recycle the leaked `NOMADNP-0214`.

Full analysis + plan:
`docs/archive/2026-08-18-visibility-change-recycle-dataloss-plan.md`.

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-18 12:15:01 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 e78ba02e62 fix(e2e): handle Stripe Checkout single-payment-method layout (#916)
## Problem

The daily E2E test (`e2e-daily.yml` → **Stage 1: Credit Purchase**)
started failing, firing the "🚨 Payment flow is broken" alert (run #135).
All 3 attempts timed out at the same line:

```
TimeoutError: locator.check: Timeout 10000ms exceeded.
> 67 |   await cardRadio.check({ force: true, timeout: 10_000 });
```

## Root cause — test-only, prod is healthy

Stripe changed its **hosted Checkout** layout. It now serves a
**single-payment-method (Card-only)** page where the card fields render
directly — there is **no `radio` named "Card"** to select. The helper
unconditionally waited on that radio, which no longer exists, so it hung
for 10s × 3.

The failure snapshot shows the real customer checkout rendering
**correctly**: right product ("1 Karaoke Credit"), referral discount
applied ("Referral 70% off"), correct total ($3.00), and working card
inputs. The alert message is the workflow's generic worst-case text, not
an observed payment break. **No product/app code changed or needed to
change** — this is purely test-automation drift.

(On the hosted `checkout.stripe.com` page the card inputs are
same-origin **direct textboxes**, not cross-origin iframes.)

## Fix

`frontend/e2e/helpers/stripe-checkout.ts` — make
`completeStripeCheckout` resilient to **both** layouts:

- Only click the "Card" radio when one is actually present.
- If card fields are already visible (single-method layout), skip radio
selection entirely.
- Fill fields via direct locators (stable-field-name / id / placeholder
/ accessible name), keeping the existing iframe fallback for the legacy
accordion layout.
- Broaden cardholder-name and ZIP locators to match the new accessible
names.

## Verification

Dispatched `e2e-daily.yml` on this branch (test code from branch,
driving **production**). The changed helper is exercised on the real
Stripe page:

- **Stage 1: Credit Purchase — ✅ success** (real ~$3 charge; full flow:
checkout → submit → success page → credits allocated)
- **Stage 2: Happy Path — ✅ success**
- Run:
https://github.com/nomadkaraoke/karaoke-gen/actions/runs/32037148447

Test-helper-only change; no shipped code affected, so no
`pyproject.toml` version bump.

@coderabbitai ignore

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

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-17 12:23:22 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 c9c019aaf7 perf(encoding): faster, smaller, portable "With Vocals" mp4 (yuv420p + veryfast + AAC) (#915)
## Summary
- The **"(With Vocals).mp4"** sing-along deliverable was the *single
longest finalization stage* (~59s on a 32-vCPU worker).
`convert_mov_to_mp4` encoded it accidentally-badly: no `-pix_fmt`
(inherited the renderer's `High 4:4:4`/`yuv444p` — the only 4:4:4 file
in the set, poorly supported by browsers/TVs/phones), default `medium`
preset (slow), and `-c:a copy` → **FLAC-in-mp4** (non-standard) despite
the documented spec ("4k H264/**AAC**").
- Verified the file is a **pure leaf** — nothing downstream reads its
video or audio. Every later output (Karaoke.mp4, Lossless/Lossy/720p,
MKV) derives from the *source* `with_vocals` file + the *instrumental*
audio; YouTube uploads the lossless MKV. So the encode is chosen purely
for the deliverable.

## Change
`convert_mov_to_mp4` (software/CPU path — what runs on prod workers):
```
-c:v libx264 -pix_fmt yuv420p -preset veryfast -c:a aac -ar 48000 -b:a 320k -movflags +faststart
```
Applied to both implementations, kept in sync:
- `LocalEncodingService.convert_mov_to_mp4` (cloud worker — prod). Its
`MP4_FLAGS` has no pix_fmt, so `-pix_fmt yuv420p` is explicit on both
GPU and CPU commands.
- `KaraokeFinalise.convert_mov_to_mp4` (local CLI). Already emitted AAC
and already forces yuv420p via its `mp4_flags`; adds the `-preset
veryfast` speed win + `-b:a 320k`.

## Measured result (real 138s 4K source: Arctic Monkeys – Riot Van)
| Metric | Before (prod) | After |
|---|---|---|
| Encode time | 56 s | **29 s** (~2×) |
| File size | 22 MB | **14 MB** (~36% smaller) |
| Video | h264 High 4:4:4 / yuv444p | **h264 High / yuv420p** |
| Audio | FLAC-in-mp4 (~639 kbps) | **AAC-LC 48 kHz / 320 kbps** |

This is the longest finalization stage, so ~halving it cuts **~20-25%
off total finalization wall-time**. The file also gets **smaller** (AAC
320k ≪ FLAC ~639k, 4:2:0 < 4:4:4) — no size/CPU tradeoff; every axis
improves, plus universal playback + spec alignment. Verified end-to-end
by running the exact shipped command on the source and re-probing the
output.

## Testing
- [x] `backend/tests/test_local_encoding_service.py` +
`tests/unit/test_karaoke_finalise/test_ffmpeg_commands.py` updated to
assert the new flags (pix_fmt/preset/AAC/320k + regression guard: no
`-c:a copy`)
- [x] 236 passed / 8 skipped across encoding + karaoke_finalise suites
- [x] End-to-end: exact command on real source → 29s, 14MB, yuv420p, AAC
320k

## Review
- [x] Local CodeRabbit review completed (2 cycles); findings addressed
(forced yuv420p on NVENC path; removed duplicate pix_fmt on CLI path).
Pre-existing skipped-NVENC-test fixture gap noted, out of scope.

## Non-goals
User-uploaded (finalise-only) non-H.264 videos still re-encode correctly
(codec-agnostic). Whether a "reference" file needs to be 4K at all is a
separate product decision.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-16 16:49:21 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 bcbe87a68d perf(encoding): remove dead ffmpeg_threads config; confirm finalization not CPU-capped (#914)
## Summary
- Investigated whether prod video **finalization** (`/encode` → 4K
lossless/lossy + 720p) uses the 32-vCPU `*-highcpu-32` workers
efficiently. **It does** — ~21–25 of 32 cores busy during every heavy
libx264 stage. Not capped at 8.
- `"ffmpeg_threads": 8` in `video_worker.py` was **dead config** (zero
consumers; no finalization ffmpeg command carries `-threads`). Removed
it + the stale `c4-standard-8` comment.
- No behaviour change — cleanup + documentation of the empirical
finding.

## Evidence (process-level measurement)
Drove a real finalization on a live `c4-highcpu-32` worker and sampled
`top -bH` on that same VM. System-wide `%Cpu(s)` during the heavy
stages:

| Stage | ffmpeg | `%Cpu us` (of 32) | ≈cores | peak RSS |
|---|---|---|---|---|
| "With Vocals" convert | `libx264 -c:a copy` | 64–70% | ~21 | ~11 GB |
| Lossless 4K concat | `libx264 -c:a pcm_s16le` | 72–75% | ~23 | ~9 GB |
| 720p | `libx264 scale=1280:720` | 76–78% | ~25 | ~1.2 GB |
| Lossy 4K / MKV | stream copies | low (I/O) | — | <0.1 GB |

An 8-core cap would show `us≈25%, idle≈75%`; observed the opposite. The
residual ~25–30% idle is x264's structural frame-threading ceiling, not
a recoverable cap. Full write-up in
`docs/archive/2026-08-16-finalization-cpu-efficiency-handoff.md`
(RESOLUTION section).

## Changes
- `backend/workers/video_worker.py` — remove dead `"ffmpeg_threads": 8`
field + stale comment; replace with explanatory NOTE.
- `docs/archive/2026-08-16-finalization-cpu-efficiency-handoff.md` —
append RESOLUTION with measurement, argv, stage timings, and a follow-up
note.
- `pyproject.toml` — bump `0.195.1` → `0.195.2`.
- `CLAUDE.md` — note to avoid `gsutil -m` on macOS (fork segfaults →
crash popups/hangs); use `gcloud storage`.

## Testing
- [x] Targeted encoding/worker tests pass (110:
`test_video_worker_orchestrator`, `test_workers_extended`,
`test_encoding_interface_contract`)
- [x] `grep` confirms no remaining `ffmpeg_threads` code/test references
- [x] Change is a no-op removal of an already-ignored dict field

## Review
- [x] Local CodeRabbit review completed
- [x] Review feedback addressed (1 minor doc-accuracy fix)

## Follow-up (separate task)
The "With Vocals" preview is a full 4K libx264 re-encode (~59s) of an
**already-H.264** source (`yuv444p`). If nothing downstream needs a
re-encode / different pix_fmt, a `-c:v copy` remux could save
~40–50s/job — bigger than any threading tweak. Needs its own
investigation.

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-16 15:14:04 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 a1a92d197c docs: reflect multi-instance-type encode pool + finalization-CPU handoff (#913)
## Summary
Brings all **live** repo docs in line with the v0.195.0 encode-worker
mechanism (shipped in #911/#912) and adds a handoff for the next
investigation. Docs-only, no version bump.

## What changed
- **ARCHITECTURE.md** — rewrote the "Encoding Worker" section: c4d
blue-green primary pair **+ ranked 6-family fallback pool**
(c4d/c4/n4d/c2d/n2d/n2, 10 VMs), the shared
`encoding_worker_preference.ordered_candidates` driving **both** runtime
and deploy selection, fastest-first + 15-min `capacity_state` cooldown,
`is_primary` override routing, and the self-sufficient CPU-torch
dep-baked image. Updated the topology diagram + intro.
- **TROUBLESHOOTING.md** — capacity runbook now lists all 6 families / 8
fallbacks + cooldown; the capacity-probe loop covers the 4 new VMs;
deploy green-selection points at the ranked pool; the "No module named"
section notes the dep-bake largely eliminated it (plus the
create-time-stockout caveat).
- **DEVELOPMENT.md** + **CLAUDE.md** — fixed "two VMs" framing;
CLAUDE.md ssh example uses a real VM name (there is no VM literally
named `encoding-worker`).
- **GCP-COST-OPTIMIZATION.md** — corrected the stale "c4d running 24/7,
~\$700/mo" current-state (now an on-demand pool with idle-shutdown — the
listed opportunities are largely shipped).
- **LESSONS-LEARNED.md** — marked the Aug-2026 2-family diversification
lesson as **superseded** by the v0.195.0 pool (history preserved,
redirects 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
steps, constraints (heavy-lane serialization / RAM), and the benchmark
baselines.

Left untouched: `docs/archive/**` and `docs/superpowers/**` (historical
snapshots), and dated changelog entries in `docs/README.md`.

## Testing
Docs-only — verified internal anchor link (DEVELOPMENT → ARCHITECTURE
section) resolves. No code/tests affected.

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

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

* **Documentation**
* Updated architecture and development guidance for blue-green encoding
workers, fallback capacity, active VM selection, and on-demand startup.
* Refined troubleshooting instructions for capacity-aware deployment, VM
promotion, health checks, restarts, and dependency recovery.
* Updated cost-optimization guidance to document auto-shutdown,
scale-to-zero behavior, and on-demand capacity.
* Marked instance-type diversification as shipped and documented rollout
outcomes.
* Added a handoff for investigating CPU utilization during video
finalization.
  * Clarified outdated guidance in the lessons learned documentation.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-16 14:14:46 -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
Andrew Beveridge ☄️andClaude Opus 4.8 c5bca2240a fix(encoding): self-heal missing wheel deps on fresh workers (No module named 'tenacity') (#905)
## Problem

Renders failed with `OutputGenerator not available: No module named
'tenacity'. The karaoke-gen wheel must be installed. Check that
ensure_latest_wheel() succeeded.` (job `233b9536`, Luke Bell –
Sometimes; all 4 retries failed identically).

**Root cause (confirmed live in prod):** A freshly-provisioned
encoding-worker VM — specifically the `n2-highcpu-32` fallback added in
#903 — boots with only a handful of packages baked into the Packer image
and 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()`. Two bugs made that fragile:

1. `ensure_latest_wheel()` ran `gsutil cp
gs://…/wheels/karaoke_gen-*.whl /tmp/` — copying the **entire `wheels/`
dir (338 wheels ≈ 6.4 GiB)** every job with a 60 s timeout. On a fresh
VM that times out → "no wheel found" → no deps installed.
2. The actual dep install (torch + CUDA, multi-GB) can't finish in the
old 300 s timeout. A partial/failed install left the venv
importable-but-incomplete, and **`ensure_latest_wheel()`'s return value
was ignored**, so the render proceeded and died on the first missing
import.

The SSH repair on the stuck VM showed the venv was nearly bare (install
pulled the whole tree, ~3.5 min).

## Fix

`backend/services/gce_encoding/main.py`:
- **Download only the single latest wheel** (`gsutil ls` → version-sort
→ `gsutil cp` one file, ~2 s) instead of copying the whole 6.4 GiB
directory.
- **Retry the install** (3× at 900 s) and **verify the render/encode
import chain** in a subprocess (`verify_wheel_imports()`) before
returning `True` — a clean `pip` exit is no longer trusted, since pip
can exit 0 while a dependency is still missing.
- **Callers fail fast** with a clear, retryable error when the
environment isn't ready, instead of proceeding into a confusing
`ImportError`.
- Run `ensure_latest_wheel()` in the **thread-pool executor** so its
blocking, multi-minute installs don't stall the async event loop
(health/status endpoints stay responsive).
- Fix misleading "deps pre-installed" comments in `startup.sh` /
`provision.sh`; add a `TROUBLESHOOTING.md` runbook (manual VM repair +
safe re-render path).

The fix propagates to fresh workers automatically via the wheel
installed at boot.

## Testing

- New `TestEnsureLatestWheelVerification` + `TestVerifyWheelImports` (13
tests) cover: single-wheel download, **pip-ok-but-imports-broken** (the
core regression), retry-after-partial-install, install timeout recovery,
and no-wheel / download-fail. `test_gce_encoding_worker.py`: 40 passed;
encoding-related suite: 111 passed.
- **Verified in prod:** repaired the stuck
`encoding-worker-fallback-n2c` venv (`sudo pip install` latest wheel →
imports OK, health OK), then re-rendered job `233b9536` via
`awaiting_review` → review `/complete`. Render ran on the repaired
worker past the old ~72 s failure point and the job reached **`complete`
(100%)**.
- CodeRabbit reviewed locally (2 cycles): event-loop-blocking + docs
findings fixed; no new findings.

## Known limitation (not addressed here)

CodeRabbit flagged that per-job `pip install --upgrade` mutates a
**shared venv**, which could disrupt a concurrent job. This is
pre-existing behavior (the GCE worker is single-tenant per render by
design) and would require job isolation / install serialization — out of
scope for this hotfix.

## Durable follow-up

Bake the full dependency tree into the Packer image (and/or pin CPU-only
torch) so fresh workers are self-sufficient and don't pay a multi-GB
first-job install. Larger infra change (image rebuild + Pulumi).

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-13 16:26:46 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 807145a6f9 fix(ci): bump Windows GHA runner 2.334.0 → 2.336.0 (missed in #902) (#904)
## Follow-up to #902
#902 bumped the runner pin to `2.336.0` in the Linux provision + startup
scripts but **missed the Windows image bake** —
`infrastructure/scripts/runner-image-provision.ps1` still pinned
deprecated `v2.334.0` (my grep only covered `.sh/.py/.yml`).

Symptom: the `gpu-windows` image rebuild failed downloading
`actions-runner-win-x64-2.334.0.zip`, and even on success would bake a
deprecated runner (→ Windows GPU runners self-terminate, same failure
mode as #902).

## Fix
One-line bump in `runner-image-provision.ps1` to match (`2.336.0`). Then
rebuild the `gha-runner-gpu-windows` image (dispatched from this
branch).

Infra-only, image-build-consumed script (no Pulumi graph impact — same
as #902). The Linux `gpu` image already rebuilt successfully on 2.336.0.

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

## Summary by CodeRabbit

* **Chores**
* Updated the Windows build runner environment to use a newer runner
version.
  * No other provisioning behavior changed.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-12 17:31:33 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 f5d3bdf426 fix(ci): bump GHA runner 2.334.0 → 2.336.0 (deprecated, wedging all self-hosted CI) (#902)
## Incident
All self-hosted CI jobs (`Backend - Unit Tests`, `Backend - Emulator
Integration Tests`, and any `build`/`gpu` jobs) have been **wedged in
`queued`** — ephemeral runner VMs boot, then self-terminate within ~1-2
min without ever picking up a job.

## Root cause (confirmed via live serial console)
GitHub **deprecated `actions/runner` v2.334.0**. Our ephemeral runners
register with JIT config (`run.sh --jitconfig`), which runs with
`disableUpdate` — so they **cannot self-update**. Serial console of a
dispatched runner VM:

```
√ Connected to GitHub
Current runner version: '2.334.0'
2026-08-12 ...Z: Listening for Jobs
An error occurred: Runner version v2.334.0 is deprecated and cannot receive messages.
Runner listener exit with terminated error, stop the service, no retry needed.
Exiting runner...
Shutdown scheduled for ...
```

The VM's `trap 'shutdown -h +1' EXIT` then terminates it, the
orphan-reaper deletes it, and the queued job is stranded. (The
immediate-TERMINATED reaping made this masquerade as Spot
preemption/capacity — it is not.)

This is a recurrence of the known runner-deprecation failure mode; the
provision script even documents it.

## Fix
Bump the pin `2.334.0 → 2.336.0` (current latest) in:
- `infrastructure/scripts/runner-image-provision.sh` (image bake — the
one the ephemeral `run.sh` actually uses)
- `infrastructure/compute/startup_scripts/github_runner.sh`,
`github_runner_gpu.sh` (baked startup scripts, kept consistent)

## Rollout
The **`Build GHA Runner Images`** workflow must rebuild the
`gha-runner-*` images so the ephemeral dispatcher (which selects the
newest non-deprecated image in each family) picks up the new binary.
I've dispatched a build for `general,build` from this branch. **`gpu` +
`gpu-windows` still need rebuilding too** (follow-up) to unblock GPU CI.

## Testing
Infra-only change; validated by the image build + a green self-hosted CI
run once new images are live.

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

## Summary by CodeRabbit

* **Chores**
  * Updated the GitHub Actions runner to version 2.336.0.
* Applied the update across standard, GPU, and provisioned runner
environments.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-12 15:00:21 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 5291d6ca78 fix: quiet visibility-change 404 noise + clarify re-render UX (#901)
## Summary

A **private→public visibility change** on a completed job re-runs the
render pipeline. This tripped three error-monitor alerts and confused
users. All fixed here (backend noise + frontend UX), plus the
encoding-capacity transparency the delay exposed.

Traced from prod alerts on job `25d076e5` (user clicked "Make Public";
the finals were deleted for re-render, and the encoding-worker capacity
was exhausted → 503s for ~26 min → looked "stuck").

## Backend — kill the false-alarm noise
- `visibility_change_service`: best-effort intermediate-artifact deletes
now pass `ignore_missing=True` (no more spurious `Error deleting file
…404` ERRORs).
- `storage_service.download_file`: re-raises `NotFound` at `warning`,
not `error`.
- `jobs` download route: missing object → **HTTP 404** (localized
detail), not 500. Temp file is now cleaned up when download fails before
streaming starts (no leak).

## Frontend — fix the UX confusion
- **JobCard banner** while `visibility_change_in_progress` (and not
complete): explains the re-render + republish takes ~15–30 min, so a
completed track no longer silently reverts to a generic processing
state.
- **OutputLinks** hides stale links during a change: GCS finals only
during the private→public re-render (status leaves `complete`);
YouTube/Dropbox in both directions. The fast public→private path keeps
its finals.
- **Encoding-capacity transparency**: the `render_pending_capacity`
status + its persistent `state_data` breadcrumb drive a `(waiting for
encoding server availability)` note next to progress; reworded
`jobStatus.waitingForCapacity`.
- New i18n strings translated to all 33 locales (frontend + backend).

## Testing
- Backend: `test_change_visibility`, `test_storage_service`,
`test_routes_jobs` (added: intermediate deletes use `ignore_missing`;
`download_file` re-raises `NotFound`).
- Frontend: `job-status` helper tests (capacity/visibility, incl.
lingering-breadcrumb guard) + `OutputLinks` (both transition
directions).
- Full frontend jest suite green (1094 tests).

## Reviewed locally with CodeRabbit
2 major + 1 minor findings addressed (temp-file leak, direction-aware
download gating, localized 404).

@coderabbitai ignore

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-12 12:32:31 -04:00
Andrew Beveridge ☄️andClaude Opus 4.8 ec99164a05 feat(infra): diversify encoding-worker fallbacks with n2-highcpu-32 (capacity resilience) (#903)
## Problem

A **region-wide `c4d-highcpu-32` capacity stockout**
(`ZONE_RESOURCE_POOL_EXHAUSTED` across `us-central1-a`, `-b`, and `-c`
simultaneously, 2026-08-12) took out **every** encoding-worker lane at
once, because the primary blue-green pair *and* both capacity fallbacks
are all the same machine family.

Consequences observed in prod:
- **Lyrics-review preview** (`POST /api/review/{id}/preview-video`) fell
back to slow local Cloud-Run encoding (~130–160 s), which **exceeds
Cloudflare's ~100 s edge timeout** → users got a **524 / "NetworkError
when attempting to fetch resource"** even though the backend actually
returned 200.
- **Final renders** parked in `RENDER_PENDING_CAPACITY` and could only
complete once c4d capacity returned (24 h auto-retry window).

Prior work (May 2026) diversified fallbacks across **zones** but not
**machine family** — and a stockout is per *(machine family × region)*,
so every zone of a family can go at once.

## Fix (Option B)

Add **`n2-highcpu-32`** capacity fallbacks
(`encoding-worker-fallback-n2c` in `us-central1-c`, `-n2f` in
`us-central1-f`) — an independent, much deeper capacity pool a c4d
stockout cannot exhaust.

**Runtime is unchanged** — `ensure_any_running` already iterates
arbitrary `{vm,zone,ip}` candidates, `start_vm(zone=)` is zone-generic,
and the idle-shutdown function is secret-driven. This is purely IaC + a
secret version:

- `infrastructure/config.py` — `EncodingWorkerConfig.FALLBACKS` now
carries per-VM `machine_type` + `disk_type` (n2 uses `pd-balanced`; it
doesn't support hyperdisk-balanced). Existing `a`/`b` entries kept
**byte-identical** so `pulumi up` does not replace the live c4d VMs.
- `infrastructure/compute/encoding_worker_vm.py` — build fallback
IPs/VMs from `FALLBACKS`.
- Tests: config invariants + n2 idle-shutdown regression (**29 pass**).
- Docs: `LESSONS-LEARNED`, `TROUBLESHOOTING`, plan doc.

## Rollout status (already applied locally)

- ✅ `pulumi up` (targeted) applied to `prod`: created 2 n2 IPs + 2 n2
VMs (stopped). Verified additive — the existing c4d VMs were **not**
touched. (A pre-existing unrelated `runner-manager` drift from another
worktree was deliberately **not** applied.)
- ✅ `encoding-worker-fallback-vms` secret updated to v2 with the two n2
entries (picked up by Cloud Run / `video-encoding-job` / idle function
at next instance start).
- ✅ Smoke-tested: n2 VM boots the encoding-worker image and serves
`/health`.

## Testing

- `pytest infrastructure/test_encoding_worker_config.py
infrastructure/functions/encoding_worker_idle/test_idle_shutdown.py` →
29 passed.
- `pulumi preview` → `+4 to create`, no replacement of existing
encoding-worker resources.

## Follow-up (separate)

Preview is synchronous and can outlive the ~100 s edge timeout → opaque
524. Durable fix is making preview async/polling (like render), or
fail-fast to local when all VM starts stock out. Tracked in the plan
doc.

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

@coderabbitai ignore

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-12 12:07:53 -04:00
231 changed files with 14806 additions and 1833 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: |
+13 -6
View File
@@ -53,7 +53,11 @@ jobs:
import os, sys, datetime, boto3
BUCKET = os.environ["BUCKET"]
# (label, prefix, max_age_hours)
# (label, prefix, max_age_hours, require_suffix)
# require_suffix: only objects with this key suffix count toward
# freshness (None = any object). git-repos/ requires ".bundle" so the
# always-written manifest.json can't mark the prefix fresh when every
# bundle failed / nothing was bundled — 0 bundles then reads as stale.
# NOTE: Firestore and BigQuery export to GCS staging nightly but are
# only uploaded to S3 *weekly* (Sundays) to cut cross-cloud egress —
# see backup_to_aws/main.py (firestore_to_s3_today). This monitor only
@@ -61,10 +65,11 @@ jobs:
# plus slack (192h ≈ 8 days), NOT the 36h nightly cadence. GCS job
# files and secrets DO upload to S3 nightly, so they stay at 36h.
TARGETS = [
("Firestore", "firestore/", 192),
("GCS job files", "gcs/job-files/", 36),
("Encrypted secrets", "secrets/", 36),
("BigQuery weekly", "bigquery/daily-refresh/", 192),
("Firestore", "firestore/", 192, None),
("GCS job files", "gcs/job-files/", 36, None),
("Encrypted secrets", "secrets/", 36, None),
("BigQuery weekly", "bigquery/daily-refresh/", 192, None),
("Git repos", "git-repos/", 36, ".bundle"),
]
s3 = boto3.client("s3")
@@ -75,10 +80,12 @@ jobs:
# operates per-page, which silently breaks "newest across all pages"
# queries on prefixes with >1000 objects (e.g. firestore/ has ~22k).
paginator = s3.get_paginator("list_objects_v2")
for label, prefix, max_hours in TARGETS:
for label, prefix, max_hours, require_suffix in TARGETS:
latest = None
for page in paginator.paginate(Bucket=BUCKET, Prefix=prefix):
for obj in page.get("Contents", []):
if require_suffix and not obj["Key"].endswith(require_suffix):
continue
if latest is None or obj["LastModified"] > latest:
latest = obj["LastModified"]
+13 -4
View File
@@ -96,6 +96,10 @@ See `docs/TESTING.md` § "Ad-Hoc Production Debugging" for full details.
- Never modify GCP resources directly via console or `gcloud` CLI
- `gcloud` CLI for reading/debugging only (e.g., checking logs, SSH to VMs)
- Stop and notify user on auth issues
- **GCS ops on macOS: never use `gsutil -m`** — its fork-based multiprocessing segfaults
on macOS (crash-report popups + the parent process hangs forever). Use `gcloud storage`
instead (`gcloud storage cp/rm/rsync …`) — no fork, and faster. Plain `gsutil` (no `-m`)
is safe but slower. `~/.boto` pins `parallel_process_count=1` as a safety net; don't remove it.
### Internationalization (i18n)
@@ -145,13 +149,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,
+26
View File
@@ -15,6 +15,7 @@ from backend.services.flacfetch_client import get_flacfetch_client
from backend.services.email_service import get_email_service
from backend.services.stripe_service import get_stripe_service
from backend.services.encoding_service import get_encoding_service
from backend.services.encoding_worker_preference import infer_machine_type, PRIMARY_MACHINE_TYPE
from backend.services.spacy_preloader import get_preloaded_model, is_model_preloaded
from backend.services.nltk_preloader import get_preloaded_cmudict, is_cmudict_preloaded
from backend.services.langfuse_preloader import get_preloaded_langfuse_handler, is_langfuse_preloaded, is_langfuse_configured
@@ -443,6 +444,26 @@ async def system_status(
if manager:
try:
config = manager.get_config()
# Which VM is actually serving right now? When a capacity
# fallback is active (e.g. a c4d stockout routed us to an
# alternate family) the override points at the live VM;
# otherwise it's the blue-green primary. The primary pair is
# always c4d — fallbacks carry their family in the VM name
# (…-fallback-n2c, …-fallback-c4a), which infer_machine_type
# decodes when no explicit machine_type is stored on the config.
on_fallback = bool(config.active_override_vm)
active_vm = config.active_override_vm or config.primary_vm
default_zone = getattr(manager, "_zone", "us-central1-c")
active_zone = config.active_override_zone or default_zone
if on_fallback:
active_machine_type = infer_machine_type({"vm": active_vm})
else:
active_machine_type = (
getattr(config, "primary_machine_type", None)
or PRIMARY_MACHINE_TYPE
)
encoder_svc["admin_details"] = {
"primary_vm": config.primary_vm,
"primary_ip": config.primary_ip,
@@ -456,6 +477,11 @@ async def system_status(
"deploy_in_progress": config.deploy_in_progress,
"active_jobs": encoding_status.get("active_jobs", 0),
"queue_length": encoding_status.get("queue_length", 0),
# Currently-serving worker (fallback-aware)
"active_vm": active_vm,
"active_zone": active_zone,
"active_machine_type": active_machine_type,
"on_fallback": on_fallback,
}
except Exception as e:
logger.warning(f"Failed to get blue-green config: {e}")
+26
View File
@@ -18,6 +18,7 @@ from typing import List, Optional, Dict, Any
from fastapi import APIRouter, HTTPException, BackgroundTasks, Depends, Request, UploadFile, File
from datetime import datetime, timezone
from google.cloud.exceptions import NotFound
from backend.utils.request_helpers import get_client_ip
from backend.models.job import Job, JobCreate, JobResponse, JobStatus
from backend.models.requests import (
@@ -1646,6 +1647,17 @@ DOWNLOAD_FILENAME_SUFFIXES = {
}
def _cleanup_temp_file(path: Optional[str]) -> None:
"""Best-effort removal of a temp file created for a download that failed
before streaming started (so it never reaches the iterator's cleanup)."""
if not path:
return
try:
os.unlink(path)
except OSError:
pass
@router.get("/{job_id}/download/{category}/{file_key}")
async def download_file(
job_id: str,
@@ -1719,6 +1731,11 @@ async def download_file(
else:
filename = gcs_path.split('/')[-1] # Fallback to original
# Created below with delete=False; the streaming iterator's finally removes it
# on the happy path. If download/setup raises before streaming starts, the
# except handlers below unlink it so failed (e.g. 404) requests don't leak
# temp files and fill local disk.
tmp_path = None
try:
# Download to temp file and stream
storage = StorageService()
@@ -1754,7 +1771,16 @@ async def download_file(
'Content-Disposition': content_disposition
}
)
except NotFound:
# The recorded output is gone from GCS (e.g. a stale download link hit
# mid-reprocess after a visibility change / edit deleted the finals). This
# is "not found", not a server error — return 404 and log at warning so it
# doesn't trip the error-monitor.
_cleanup_temp_file(tmp_path)
logger.warning(f"Download requested for missing object {gcs_path}")
raise HTTPException(status_code=404, detail=t(locale, "jobs.fileNoLongerAvailable"))
except Exception as e:
_cleanup_temp_file(tmp_path)
logger.error(f"Error downloading {gcs_path}: {e}")
raise HTTPException(status_code=500, detail=f"Error downloading file: {e}")
+27 -3
View File
@@ -19,7 +19,7 @@ import json
import os
import tempfile
from pathlib import Path
from typing import Dict, Any, List, Optional, Set, Tuple
from typing import Dict, Any, List, Literal, Optional, Set, Tuple
from fastapi import APIRouter, HTTPException, Request, Depends, Form, File, UploadFile
from fastapi.responses import RedirectResponse
@@ -372,6 +372,15 @@ async def get_correction_data(
raise HTTPException(status_code=500, detail=t("en", "review.correctionsLoadFailed", error=str(e)))
@router.get("/{job_id}/audio/vocals")
async def get_vocals_audio(
job_id: str,
auth_info: Tuple[str, str] = Depends(require_review_auth)
):
"""Stream the vocals audio file for playback."""
return await _stream_audio(job_id, stem="vocals")
@router.get("/{job_id}/audio/{audio_hash}")
async def get_audio_with_hash(
job_id: str,
@@ -392,7 +401,7 @@ async def get_audio_no_hash(
return await _stream_audio(job_id)
async def _stream_audio(job_id: str):
async def _stream_audio(job_id: str, stem: Literal["input"] | Literal["vocals"] = "input"):
"""
Redirect to a signed GCS URL for audio playback in the review interface.
@@ -407,7 +416,22 @@ async def _stream_audio(job_id: str):
if not job:
raise HTTPException(status_code=404, detail=t("en", "review.jobNotFound"))
audio_gcs_path = job.input_media_gcs_path
audio_gcs_path = None
if stem == "input":
audio_gcs_path = job.input_media_gcs_path
elif stem == "vocals":
stems = job.file_urls.get("stems", {}) if job.file_urls else {}
# Stem keys vary by separation model. We want the full vocal mix
# (lead + backing) so every word can be lined up against the waveform:
# - "vocals" : full vocal from a 2-stem split (rare)
# - "vocals_clean" : full vocal from the primary vocal/instrumental
# split (present on essentially all cloud jobs)
# - "lead_vocals" : last-resort fallback (misses backing lines)
# Use .get() so a missing key yields a clean 404 below, not a KeyError/500.
for key in ("vocals", "vocals_clean", "lead_vocals"):
if stems.get(key):
audio_gcs_path = stems[key]
break
if not audio_gcs_path:
raise HTTPException(status_code=404, detail=t("en", "review.audioNotFound"))
+160 -54
View File
@@ -9,6 +9,7 @@ Handles:
- Admin user management
"""
import hashlib
import html
import logging
import threading
from datetime import datetime
@@ -844,6 +845,72 @@ async def create_made_for_you_checkout(
ADMIN_EMAIL = "madeforyou@nomadkaraoke.com"
def _send_mfy_failure_alert(
email_service: EmailService,
*,
customer_email: str,
artist: str,
title: str,
job_id: Optional[str],
error: Exception,
) -> None:
"""Best-effort admin alert when a made-for-you order can't be fully processed.
This never raises: a failure to send the alert must not mask the original
error, nor interfere with the customer-facing order-confirmation email
(which is sent independently, before audio acquisition is attempted).
"""
safe_customer = html.escape(customer_email or "")
safe_artist = html.escape(artist or "")
safe_title = html.escape(title or "")
safe_error = html.escape(str(error))
job_line_html = f"<li><strong>Job ID:</strong> {html.escape(job_id)}</li>" if job_id else ""
job_line_text = f"Job ID: {job_id}\n" if job_id else ""
remediation = (
"The customer's order-confirmation email is sent separately and up-front, so it "
"is unaffected by failures during processing. Please review this order and take "
"any needed manual action — e.g. provide/repair the audio source, or resend the "
"customer confirmation."
)
try:
sent = email_service.send_email(
to_email=ADMIN_EMAIL,
subject=f"[FAILED] Made For You Order: {artist} - {title}",
html_content=f"""
<h2>Made-For-You Order — Action Needed</h2>
<p>A problem occurred while processing this order:</p>
<ul>
<li><strong>Customer:</strong> {safe_customer}</li>
<li><strong>Artist:</strong> {safe_artist}</li>
<li><strong>Title:</strong> {safe_title}</li>
{job_line_html}
<li><strong>Error:</strong> {safe_error}</li>
</ul>
<p>{remediation}</p>
""",
text_content=(
"Made-For-You Order — Action Needed\n\n"
f"Customer: {customer_email}\n"
f"Artist: {artist}\n"
f"Title: {title}\n"
f"{job_line_text}"
f"Error: {error}\n\n"
f"{remediation}"
),
)
if sent:
logger.info(f"Sent made-for-you failure alert to admin for job {job_id}")
else:
logger.error(
f"Made-for-you failure alert to admin was rejected by the email provider (job {job_id})"
)
except Exception as email_error:
logger.error(
f"Failed to send made-for-you failure alert (job {job_id}): {email_error}",
exc_info=True,
)
async def _handle_made_for_you_order(
session_id: str,
metadata: dict,
@@ -892,6 +959,10 @@ async def _handle_made_for_you_order(
f"(session: {session_id}, source_type: {source_type})"
)
# Defined up-front so the outer failure handler can reference it even if job
# creation is what failed (job_id stays None until the job actually exists).
job_id = None
try:
job_manager = JobManager()
storage_service = StorageService()
@@ -977,6 +1048,48 @@ async def _handle_made_for_you_order(
# Initialize search_results for later use in email notification
search_results = None
# Send the customer's order-confirmation email NOW, before attempting audio
# acquisition. The order is paid and confirmed regardless of whether the
# (fallible) YouTube download / audio search succeeds, so a failure there must
# never rob the customer of their confirmation email. Resilient: a delivery
# failure is logged but does not abort order processing.
confirmation_ok = False
try:
# Providers return False (not an exception) when the send is rejected, so
# check the result rather than assuming success.
confirmation_ok = bool(email_service.send_made_for_you_order_confirmation(
to_email=customer_email,
artist=artist,
title=title,
job_id=job_id,
notes=notes,
))
if confirmation_ok:
logger.info(f"Sent made-for-you customer confirmation for job {job_id}")
else:
logger.error(
f"Job {job_id}: customer order-confirmation email was rejected by the email provider"
)
except Exception as confirm_error:
logger.error(
f"Job {job_id}: Failed to send customer order-confirmation email: {confirm_error}",
exc_info=True,
)
if not confirmation_ok:
# A paid customer must never silently miss their confirmation. Escalate to
# the admin so it can be resent manually. Order processing still continues.
_send_mfy_failure_alert(
email_service,
customer_email=customer_email,
artist=artist,
title=title,
job_id=job_id,
error=RuntimeError(
"Customer order-confirmation email failed to send — please resend it manually"
),
)
# Handle based on whether we have a YouTube URL or need to search
if youtube_url:
# URL provided - download audio first, then trigger workers
@@ -1099,66 +1212,59 @@ async def _handle_made_for_you_order(
# (search_results may be set from the search flow above, or None for YouTube URL orders)
audio_source_count = len(search_results) if search_results else 0
# Generate admin login token for one-click email access (24hr expiry)
admin_login = user_service.create_admin_login_token(
email=ADMIN_EMAIL,
expiry_hours=24,
)
# Send notification email to admin using professional template.
# Resilient: an email delivery error here must not turn a successfully-created
# order into a "[FAILED]" alert — it's logged and swallowed instead.
try:
# Generate admin login token for one-click email access (24hr expiry)
admin_login = user_service.create_admin_login_token(
email=ADMIN_EMAIL,
expiry_hours=24,
)
admin_notified = bool(email_service.send_made_for_you_admin_notification(
to_email=ADMIN_EMAIL,
customer_email=customer_email,
artist=artist,
title=title,
job_id=job_id,
admin_login_token=admin_login.token,
notes=notes,
audio_source_count=audio_source_count,
))
if admin_notified:
logger.info(f"Sent made-for-you admin notification for job {job_id}")
else:
logger.error(
f"Job {job_id}: admin order notification was rejected by the email provider"
)
except Exception as admin_email_error:
logger.error(
f"Job {job_id}: Failed to send admin order notification: {admin_email_error}",
exc_info=True,
)
# Send confirmation email to customer using professional template
email_service.send_made_for_you_order_confirmation(
to_email=customer_email,
artist=artist,
title=title,
job_id=job_id,
notes=notes,
)
# Send notification email to admin using professional template
email_service.send_made_for_you_admin_notification(
to_email=ADMIN_EMAIL,
except Exception as e:
# A hard failure in order processing (e.g. job creation, or audio acquisition
# raising after transitioning the job to FAILED). The customer confirmation is
# sent earlier and independently, so it is unaffected by failures here. Alert
# the admin so they can intervene manually.
logger.error(f"Error processing made-for-you order: {e}", exc_info=True)
_send_mfy_failure_alert(
email_service,
customer_email=customer_email,
artist=artist,
title=title,
job_id=job_id,
admin_login_token=admin_login.token,
notes=notes,
audio_source_count=audio_source_count,
error=e,
)
logger.info(f"Sent made-for-you order notifications for job {job_id}")
except Exception as e:
logger.error(f"Error processing made-for-you order: {e}", exc_info=True)
# Still try to notify Andrew of the failure
try:
email_service.send_email(
to_email=ADMIN_EMAIL,
subject=f"[FAILED] Made For You Order: {artist} - {title}",
html_content=f"""
<h2>Made-For-You Order Failed</h2>
<p>An error occurred processing this order:</p>
<ul>
<li><strong>Customer:</strong> {customer_email}</li>
<li><strong>Artist:</strong> {artist}</li>
<li><strong>Title:</strong> {title}</li>
<li><strong>Error:</strong> {str(e)}</li>
</ul>
<p>Please manually create this job and notify the customer.</p>
""",
text_content=f"""
Made-For-You Order Failed
Customer: {customer_email}
Artist: {artist}
Title: {title}
Error: {str(e)}
Please manually create this job and notify the customer.
""".strip(),
)
except Exception as email_error:
logger.error(f"Failed to send error notification: {email_error}")
# If we failed before the job was even created, no job exists and the Stripe
# session was never marked processed — re-raise so the webhook returns non-2xx
# and Stripe retries the (likely transient) failure rather than silently
# dropping a paid order. Post-creation failures keep job_id set: those return
# normally (job exists, session marked processed, admin already alerted), so a
# retry would be a no-op / risk a duplicate job.
if job_id is None:
raise
@router.post("/webhooks/stripe")
+57 -6
View File
@@ -85,7 +85,8 @@ class Settings(BaseSettings):
# AI Credit Evaluation (anti-abuse gating for free credits)
# When enabled, welcome and feedback credit grants are evaluated by Gemini
# before granting. Fail-open: if evaluation fails, credits are granted anyway.
# before granting. Fail-CLOSED: if evaluation fails, the decision becomes
# "pending_review" (no auto-grant; an admin is notified to decide).
credit_eval_enabled: bool = os.getenv("CREDIT_EVAL_ENABLED", "true").lower() in ("true", "1", "yes")
credit_eval_model: str = os.getenv("CREDIT_EVAL_MODEL", "gemini-3.1-pro-preview")
@@ -106,11 +107,13 @@ class Settings(BaseSettings):
# Models used by the multi-model "compare" mode (semicolon-separated —
# Cloud Run --set-env-vars is comma-delimited). Empty = single-model only.
auto_correct_compare_models: str = os.getenv("AUTO_CORRECT_COMPARE_MODELS", "")
# Proactively generate (and cache) auto-correct suggestions in the lyrics
# worker once transcription + references are ready, so the review UI has
# them instantly. Best-effort: failures never block or fail the job. Only
# meaningful where ANTHROPIC_API_KEY + AUTO_CORRECT_COMPARE_MODELS are set
# (the lyrics-transcription-job, via ci.yml). Default off.
# Proactively generate (and cache) auto-correct suggestions once
# transcription + references are ready, so the review UI has them instantly.
# This flag gates whether the lyrics worker fires the trigger; the actual
# multi-model LLM call + caching runs on the API service (auto_correct_worker),
# which holds the model credentials — the lyrics-transcription-job itself does
# NOT need ANTHROPIC_API_KEY / AUTO_CORRECT_COMPARE_MODELS. Best-effort:
# failures never block or fail the job. Default off.
auto_correct_proactive_enabled: bool = os.getenv(
"AUTO_CORRECT_PROACTIVE_ENABLED", "false"
).lower() in ("true", "1", "yes")
@@ -306,3 +309,51 @@ def get_settings() -> Settings:
"""Get the global settings instance."""
return settings
def is_production() -> bool:
"""True when running in a deployed/production environment.
Cloud Run automatically sets ``K_SERVICE``, so we treat its presence as
production even if ``ENVIRONMENT`` were somehow unset — a production-safe
default. Local dev/test have no ``K_SERVICE`` and a non-"production"
``ENVIRONMENT``. (Fallback audit 2026-06-09, Theme 7.)
"""
env = (os.environ.get("ENVIRONMENT") or os.environ.get("ENV") or "").lower()
if env == "production":
return True
return bool(os.environ.get("K_SERVICE"))
# Env vars that MUST be explicitly set in production. A missing one used to
# silently fall back to a dev default and produce wrong behaviour with only a
# warning (wrong GCP project for secret lookups, wrong GCS bucket, localhost
# worker URL). We only require vars that infra confirms are set on every service
# (GCS temp/output buckets are intentionally excluded — their defaults are
# load-bearing and not set via env). (Fallback audit 2026-06-09, Theme 7.)
_REQUIRED_PRODUCTION_ENV_VARS = (
"GOOGLE_CLOUD_PROJECT",
"GCS_BUCKET_NAME",
"CLOUD_RUN_SERVICE_URL",
)
def validate_production_config() -> None:
"""Fail fast at startup if required production env vars are missing.
In production each var in ``_REQUIRED_PRODUCTION_ENV_VARS`` must be explicitly
set; otherwise the service would silently run with a dev default (wrong GCP
project / wrong GCS bucket / localhost worker URL) and appear to work while
doing the wrong thing. Raises RuntimeError listing every missing var. No-op
outside production. (Fallback audit 2026-06-09, Theme 7.)
"""
if not is_production():
return
missing = [v for v in _REQUIRED_PRODUCTION_ENV_VARS if not (os.environ.get(v) or "").strip()]
if missing:
raise RuntimeError(
"Production misconfiguration: required environment variable(s) not set: "
+ ", ".join(missing)
+ ". Refusing to start with silent dev defaults (wrong GCP project / "
"GCS bucket / localhost worker URL)."
)
+6 -1
View File
@@ -9,7 +9,7 @@ from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from backend.config import settings
from backend.config import settings, validate_production_config
from backend.api.routes import health, jobs, internal, file_upload, review, auth, audio_search, themes, users, admin, tenant, rate_limits, push, catalog, encoding_worker, client_errors, bulk, parse_titles
from backend.services.tracing import setup_tracing, instrument_app, get_current_trace_id
from backend.services.structured_logging import setup_structured_logging
@@ -77,6 +77,11 @@ async def lifespan(app: FastAPI):
logger.info(f"GCS Bucket: {settings.gcs_bucket_name}")
logger.info(f"Tracing enabled: {tracing_enabled}")
# Fail fast if required production config is missing, rather than silently
# running on dev defaults (wrong GCP project / GCS bucket / localhost worker
# URL). No-op outside production. (Fallback audit 2026-06-09, Theme 7.)
validate_production_config()
# Preload NLP models and resources to avoid cold start delays
# See docs/archive/2026-01-08-performance-investigation.md for background
+7 -2
View File
@@ -26,9 +26,14 @@ from backend.models.tenant import TenantConfig
logger = logging.getLogger(__name__)
# Only allow query param tenant override in non-production environments
# Only allow the `?tenant=` query-param override in non-production environments —
# in production it is a tenant-spoofing vector. Production-safe by default: Cloud
# Run always sets K_SERVICE, so we treat its presence as production even if
# ENVIRONMENT were somehow unset (which would otherwise re-enable the override).
# (Fallback audit 2026-06-09, Theme 7.)
IS_PRODUCTION = os.environ.get("ENV", "").lower() == "production" or \
os.environ.get("ENVIRONMENT", "").lower() == "production"
os.environ.get("ENVIRONMENT", "").lower() == "production" or \
bool(os.environ.get("K_SERVICE"))
# Known non-tenant subdomains that should be treated as default Nomad Karaoke
+10 -5
View File
@@ -368,12 +368,17 @@ class AudioSearchService:
return results
except FlacfetchServiceError as e:
logger.warning(f"Remote flacfetch search failed, falling back to local: {e}")
# Fallback to local search
# flacfetch is the sole downloader. The remote service was explicitly
# configured, so a failure here must NOT silently downgrade to the
# local YouTube-only fetcher — that hides the outage and ships a worse
# source than the user expected (the 2026-06-08 incident class).
# Fail loudly. (Fallback audit 2026-06-09, Theme 1.)
logger.error(f"Remote flacfetch search failed (not falling back to local): {e}")
# Clear cached state so a later download() can't consume stale results
# from a previous successful search on this (singleton) instance.
self._remote_search_id = None
results = self._fetcher.search(artist, title)
self._cached_results = results
return results
self._cached_results = []
raise AudioSearchError(f"Remote flacfetch search failed: {e}") from e
def select_best(self, results: List[AudioSearchResult]) -> int:
"""
+9 -1
View File
@@ -87,7 +87,15 @@ class AuthService:
if self.admin_tokens:
logger.info(f"Loaded {len(self.admin_tokens)} admin token(s)")
else:
logger.warning("No admin tokens configured! Set ADMIN_TOKENS environment variable.")
# Loud signal: with no admin tokens, every admin/internal-worker
# endpoint fails closed (403). That's safe but looks like an auth bug
# rather than a config error, so log at ERROR (picked up by the error
# monitor → Discord alert) instead of a quiet warning.
logger.error(
"No admin tokens configured! All admin and internal-worker "
"endpoints will reject every request (403). Set the ADMIN_TOKENS "
"secret/env var. This is almost certainly a misconfiguration."
)
def _validate_oidc_token(self, token: str) -> Optional[AuthResult]:
"""
@@ -2,8 +2,9 @@
AI-powered credit evaluation service.
Evaluates whether to grant free credits (welcome or feedback) by collecting
abuse signals and asking Gemini for a grant/deny decision. Fail-open: if
the AI call fails for any reason, credits are granted.
abuse signals and asking Gemini for a grant/deny decision. Fail-CLOSED: if
the AI call fails for any reason, the decision becomes "pending_review" (no
credits auto-granted; an admin is notified to decide manually).
"""
import json
import logging
@@ -25,7 +26,7 @@ class CreditEvaluation:
decision: str # "grant" or "deny"
reasoning: str
confidence: float
error: Optional[str] = None # Set if evaluation failed (decision defaults to "grant")
error: Optional[str] = None # Set if evaluation failed (decision defaults to "pending_review")
signals: Optional[dict] = None # Collected abuse signals (for admin review emails)
+7 -2
View File
@@ -30,8 +30,13 @@ class DropboxService:
"""Load OAuth credentials from Secret Manager."""
try:
client = secretmanager.SecretManagerServiceClient()
# Try to get the project ID from environment or use default
project_id = os.environ.get("GOOGLE_CLOUD_PROJECT", "karaoke-gen")
# Use the configured GCP project. The old default "karaoke-gen" was a
# WRONG literal (the real project is "nomadkaraoke"); an unset var
# would silently target a non-existent project and disable Dropbox.
# Prod always sets GOOGLE_CLOUD_PROJECT (startup validation requires
# it), so use an empty default rather than a misleading wrong one.
# (Fallback audit 2026-06-09, Theme 7.)
project_id = os.environ.get("GOOGLE_CLOUD_PROJECT", "")
name = f"projects/{project_id}/secrets/dropbox-oauth-credentials/versions/latest"
response = client.access_secret_version(request={"name": name})
return json.loads(response.payload.data.decode("UTF-8"))
+18 -1
View File
@@ -138,7 +138,24 @@ async def reconcile_and_maybe_pause(job_id: str) -> bool:
user_service = get_user_service()
storage = StorageService()
# JobManager/StorageService have no singleton accessor; instantiate directly (matches audio_download_worker).
email_service = get_email_service()
#
# Email is only actually sent on the rare over-limit *cancel* branch. Building
# the service must never crash an otherwise-successful download: EmailService()
# raises in production when POSTMARK_SERVER_TOKEN is unset (the "fail loudly"
# guard from the 2026-06-09 fallback audit), and this worker runs as the
# audio-download-job Cloud Run Job. If the provider can't be built, reconcile
# still proceeds (reconcile_duration tolerates email_service=None); we log
# loudly so a config regression is visible rather than silently dropping a
# customer notification. (Job a453d1d5: token missing on the job crashed the
# download entirely.)
try:
email_service = get_email_service()
except Exception as e:
logger.error(
"Job %s: could not construct email service for duration reconcile "
"(%s); proceeding without customer email notifications", job_id, e,
)
email_service = None
result = await asyncio.get_running_loop().run_in_executor(
None,
+40 -3
View File
@@ -17,7 +17,7 @@ from zoneinfo import ZoneInfo
import requests
from backend.config import get_settings
from backend.config import get_settings, is_production
from backend.i18n import t, get_locale_prefix
from karaoke_gen.utils import sanitize_filename
@@ -231,7 +231,7 @@ class EmailService:
"""Get the configured email provider.
Postmark is used when POSTMARK_SERVER_TOKEN is set; otherwise falls
back to console logging (dev/test).
back to console logging (dev/test only).
"""
postmark_token = os.getenv("POSTMARK_SERVER_TOKEN")
from_email = os.getenv("EMAIL_FROM", "gen@nomadkaraoke.com")
@@ -241,13 +241,50 @@ class EmailService:
logger.info("Using Postmark email provider")
return PostmarkEmailProvider(postmark_token, from_email, from_name)
logger.warning("No email provider configured, using console logging")
# In production a missing Postmark token used to silently fall back to
# console logging — every send "succeeded" while magic-link/completion/
# receipt emails vanished (users can't log in or get downloads). Fail
# loudly instead. (Fallback audit 2026-06-09, Theme 7.)
if is_production():
raise RuntimeError(
"POSTMARK_SERVER_TOKEN is not set in production. Refusing to "
"silently drop emails via the console provider — set the Postmark "
"token secret."
)
logger.warning("No email provider configured, using console logging (dev/test)")
return ConsoleEmailProvider()
def is_configured(self) -> bool:
"""Check if a real email provider is configured (not just console logging)."""
return isinstance(self.provider, PostmarkEmailProvider)
def send_email(
self,
to_email: str,
subject: str,
html_content: str,
text_content: Optional[str] = None,
cc_emails: Optional[List[str]] = None,
bcc_emails: Optional[List[str]] = None,
from_email_override: Optional[str] = None,
) -> bool:
"""Send a raw email via the configured provider.
Thin passthrough for callers that need to send an ad-hoc/plain email
(e.g. internal failure alerts) without a dedicated template method.
Prefer a dedicated ``send_*`` template method for customer-facing mail.
"""
return self.provider.send_email(
to_email=to_email,
subject=subject,
html_content=html_content,
text_content=text_content,
cc_emails=cc_emails,
bcc_emails=bcc_emails,
from_email_override=from_email_override,
)
def send_magic_link(
self,
email: 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,
+412 -48
View File
@@ -1,5 +1,4 @@
import asyncio
import glob as glob_module
import hashlib
import json
import logging
@@ -9,6 +8,7 @@ import shutil
import subprocess
import sys
import tempfile
import threading
import uuid
from concurrent.futures import ThreadPoolExecutor
from contextlib import asynccontextmanager
@@ -30,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.
@@ -120,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):
@@ -539,59 +591,211 @@ def run_render_video(job_id: str, work_dir: Path, request: "RenderVideoRequest")
raise
# Wheel install/verification tuning.
#
# On a freshly-provisioned worker the Packer image only pre-installs a handful
# of packages (fastapi/uvicorn/gcs/...) and boot installs the wheel with
# --no-deps, so the FIRST job's install here has to resolve the entire
# karaoke-gen dependency tree (torch, langchain, tenacity, ...). That can take
# well over 5 minutes and, if it times out or partially completes, leaves the
# environment importable-but-broken (e.g. "No module named 'tenacity'"). We
# therefore retry, and — critically — verify the import chain actually works
# before declaring success, since pip can return 0 while a dependency is still
# missing.
WHEEL_INSTALL_TIMEOUT = int(os.environ.get("WHEEL_INSTALL_TIMEOUT", "900"))
WHEEL_INSTALL_ATTEMPTS = int(os.environ.get("WHEEL_INSTALL_ATTEMPTS", "3"))
# 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
# actually present, not just that `pip install` exited 0.
_WHEEL_IMPORT_CHECK = (
"import tenacity; "
"from karaoke_gen.lyrics_transcriber.output.generator import OutputGenerator; "
"from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations; "
"from backend.services.local_encoding_service import LocalEncodingService"
)
def verify_wheel_imports():
'''Verify the karaoke-gen render/encode import chain is fully importable.
Runs in a subprocess so a broken/partial install surfaces as a clean
boolean instead of crashing (or half-importing into) the worker process.
Returns True if every module imports, False otherwise.
'''
try:
check = subprocess.run(
[sys.executable, "-c", _WHEEL_IMPORT_CHECK],
capture_output=True, text=True, timeout=180,
)
except subprocess.TimeoutExpired:
logger.warning("Wheel import verification timed out")
return False
if check.returncode != 0:
# Tail of stderr carries the actionable ModuleNotFoundError.
logger.warning(f"Wheel import verification failed: {check.stderr.strip()[-500:]}")
return False
return True
def ensure_latest_wheel():
'''Download and install latest karaoke-gen wheel from GCS.
'''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...")
# Download latest wheel
result = subprocess.run(
["gsutil", "cp", "gs://karaoke-gen-storage-nomadkaraoke/wheels/karaoke_gen-*.whl", "/tmp/"],
capture_output=True, text=True, timeout=60
)
# Find the downloaded wheel (get the latest by version sorting)
wheels = glob_module.glob("/tmp/karaoke_gen-*.whl")
# Filter out karaoke_gen-current.whl (not a valid PEP 427 wheel name)
wheels = [w for w in wheels if '-current' not in w]
if not wheels:
logger.warning("No wheel found in GCS, using fallback encoding logic")
return False
# Sort to get latest version (by semantic version, not alphabetically)
# Sort helper: extract version from a wheel name/URI like
# karaoke_gen-0.116.1-py3-none-any.whl
def extract_version(wheel_path):
"""Extract version from wheel filename like karaoke_gen-0.116.1-py3-none-any.whl"""
match = re.search(r'karaoke_gen-([0-9.]+)-', wheel_path)
if match:
return Version(match.group(1))
return Version("0.0.0") # Fallback for unparseable filenames
wheels.sort(key=extract_version, reverse=True)
wheel_path = wheels[0]
logger.info(f"Installing wheel: {wheel_path}")
# Install (or upgrade) the wheel
# Use 5-minute timeout - first install at job start may need to resolve dependencies
# Subsequent installs are faster since dependencies are cached
install_result = subprocess.run(
[sys.executable, "-m", "pip", "install", "--upgrade", "--quiet", wheel_path],
capture_output=True, text=True, timeout=300
# List wheel names only (fast), then copy just the single latest one.
# NOTE: `gsutil cp gs://.../karaoke_gen-*.whl /tmp/` would download the
# ENTIRE wheels/ directory (hundreds of wheels, multiple GiB) on every
# job and blow the timeout on fresh workers — the historical cause of
# "no wheel found" / partial installs. Listing + single copy is ~2s.
ls_result = subprocess.run(
["gsutil", "ls", "gs://karaoke-gen-storage-nomadkaraoke/wheels/karaoke_gen-*.whl"],
capture_output=True, text=True, timeout=60
)
# Filter out karaoke_gen-current.whl (not a valid PEP 427 wheel name)
wheel_uris = [
line.strip() for line in ls_result.stdout.splitlines()
if line.strip() and '-current' not in line
]
if install_result.returncode != 0:
logger.warning(f"Wheel installation failed: {install_result.stderr}")
if not wheel_uris:
logger.warning("No versioned wheel found in GCS, using fallback encoding logic")
return False
logger.info(f"Successfully installed wheel: {wheel_path}")
return True
wheel_uris.sort(key=extract_version)
latest_uri = wheel_uris[-1]
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
)
if cp_result.returncode != 0:
logger.warning(f"Failed to download wheel {latest_uri}: {cp_result.stderr.strip()[-500:]}")
return False
# Install (with deps), then verify the import chain is complete. Retry a
# failed or partial install: pip is resumable, so a second pass fills in
# dependencies a timed-out first pass left missing (e.g. tenacity).
for attempt in range(1, WHEEL_INSTALL_ATTEMPTS + 1):
logger.info(f"Installing wheel (attempt {attempt}/{WHEEL_INSTALL_ATTEMPTS}): {wheel_path}")
try:
install_result = subprocess.run(
[sys.executable, "-m", "pip", "install", "--upgrade", "--quiet", wheel_path],
capture_output=True, text=True, timeout=WHEEL_INSTALL_TIMEOUT
)
except subprocess.TimeoutExpired:
logger.warning(
f"Wheel install timed out after {WHEEL_INSTALL_TIMEOUT}s "
f"(attempt {attempt}/{WHEEL_INSTALL_ATTEMPTS})"
)
install_result = None
if install_result is not None and install_result.returncode != 0:
logger.warning(
f"Wheel installation failed (attempt {attempt}/{WHEEL_INSTALL_ATTEMPTS}): "
f"{install_result.stderr.strip()[-500:]}"
)
elif install_result is not None:
logger.info(f"pip install completed for wheel: {wheel_path}")
# A clean `pip install` exit is not sufficient — confirm the deps
# the render/encode paths need are actually importable before we let
# a job run against this environment.
if verify_wheel_imports():
_verified_wheel_version = latest_version
logger.info(f"Successfully installed and verified wheel: {wheel_path}")
return True
logger.warning(
f"Wheel environment incomplete after attempt {attempt}/{WHEEL_INSTALL_ATTEMPTS}; "
"dependencies are missing or failed to import"
)
logger.error(
f"Wheel not ready after {WHEEL_INSTALL_ATTEMPTS} attempts: import verification "
"still failing (environment is missing dependencies)"
)
return False
except subprocess.TimeoutExpired:
logger.warning("Wheel download/install timed out, using fallback")
logger.warning("Wheel download timed out, using fallback")
return False
except Exception as e:
logger.warning(f"Failed to ensure latest wheel: {e}")
@@ -644,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).
@@ -841,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
@@ -873,8 +1188,18 @@ async def process_job(job_id: str, request: EncodeRequest):
# Process an encoding job asynchronously
try:
# Download and install latest wheel at job start (allows hot updates without restart)
# This means in-progress jobs continue with their version, new jobs get latest code
ensure_latest_wheel()
# This means in-progress jobs continue with their version, new jobs get latest code.
# Fail fast (retryable) if the environment isn't ready rather than proceeding into a
# confusing "No module named ..." ImportError deep in encoding.
# ensure_latest_wheel() makes blocking subprocess calls (install can retry for many
# minutes) — run it in the thread pool so the async event loop keeps serving health
# checks and status polls.
loop = asyncio.get_event_loop()
if not await loop.run_in_executor(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"
)
with tempfile.TemporaryDirectory() as temp_dir:
work_dir = Path(temp_dir) / "work"
@@ -896,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,
@@ -945,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,
@@ -971,17 +1297,27 @@ async def process_preview_job(job_id: str, request: EncodePreviewRequest):
async def process_render_video_job(job_id: str, request: RenderVideoRequest):
# Process a render-video job asynchronously
try:
# Download and install latest wheel at job start (allows hot updates without restart)
ensure_latest_wheel()
# Download and install latest wheel at job start (allows hot updates without restart).
# Fail fast (retryable) if the environment isn't ready rather than proceeding into a
# confusing "No module named 'tenacity'" ImportError inside render_video.
# Run in the thread pool: ensure_latest_wheel() blocks on subprocess installs (which
# can retry for many minutes) and must not stall the async event loop.
loop = asyncio.get_event_loop()
if not await loop.run_in_executor(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"
)
with tempfile.TemporaryDirectory() as temp_dir:
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,
@@ -1024,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)
@@ -1056,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)
@@ -1088,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)
@@ -1096,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
+25 -4
View File
@@ -325,10 +325,29 @@ class LocalEncodingService:
output_file: str,
) -> bool:
"""
Convert MOV to MP4 format.
Convert the source "With Vocals" video (MOV/MKV) to a standard, portable MP4.
This produces the "(With Vocals).mp4" sing-along deliverable. It is a leaf
output — no later encode reads it — so the encode is chosen purely for the
deliverable itself:
- ``-pix_fmt yuv420p``: the renderer emits High 4:4:4 (yuv444p), which many
browsers/TVs/phones cannot decode. Normalize to 4:2:0 so it plays
everywhere and matches every other output. (Also ~halves this stage's CPU
time vs. re-encoding 4:4:4, and yields a slightly smaller file.)
- ``-preset veryfast``: this is the single longest finalization stage; a fast
preset roughly halves it (~56s → ~28s on a 32-vCPU worker) with negligible
quality difference for karaoke content (static background + text).
- ``-c:a aac``: the source audio is FLAC; FLAC-in-MP4 is non-standard. Encode
AAC 320k so the file is fully portable. Matches the documented spec
("4k H264/AAC with original vocals", see template_service.py).
Both commands force ``-pix_fmt yuv420p`` (h264_nvenc can otherwise *preserve* a
yuv444p input). Prod encoding workers are CPU-only, so ``cpu_command`` is the
real path; if the NVENC command ever errors, ``_execute_command_with_fallback``
drops to the (correct) CPU command.
Args:
input_file: Path to input MOV file
input_file: Path to input MOV/MKV file (source "With Vocals" video)
output_file: Path for output MP4 file
Returns:
@@ -336,11 +355,13 @@ class LocalEncodingService:
"""
gpu_command = (
f'{self._ffmpeg_base_command} {self.hwaccel_decode_flags} -i "{input_file}" '
f'-c:v {self.video_encoder} -c:a copy {self.MP4_FLAGS} "{output_file}"'
f'-c:v {self.video_encoder} -pix_fmt yuv420p -c:a {self.aac_codec} -ar 48000 -b:a 320k '
f'{self.MP4_FLAGS} "{output_file}"'
)
cpu_command = (
f'{self._ffmpeg_base_command} -i "{input_file}" '
f'-c:v libx264 -c:a copy {self.MP4_FLAGS} "{output_file}"'
f'-c:v libx264 -pix_fmt yuv420p -preset veryfast '
f'-c:a {self.aac_codec} -ar 48000 -b:a 320k {self.MP4_FLAGS} "{output_file}"'
)
return self._execute_command_with_fallback(
gpu_command, cpu_command, "Converting MOV to MP4"
+6
View File
@@ -55,6 +55,12 @@ class StorageService:
blob.download_to_filename(destination_path)
logger.info(f"Downloaded gs://{settings.gcs_bucket_name}/{source_path} to {destination_path}")
return destination_path
except NotFound:
# A missing object is a routine "not found", not a server-side failure.
# Log at warning so it doesn't trip the error-monitor, and let the caller
# decide how to surface it (e.g. the download route returns HTTP 404).
logger.warning(f"Object not found downloading {source_path}")
raise
except Exception as e:
logger.error(f"Error downloading file {source_path}: {e}")
raise
+171 -38
View File
@@ -57,61 +57,93 @@ class VisibilityChangeService:
"""
Change a public job to private (fast path).
Deletes distributed outputs (YouTube/Dropbox/GDrive) but keeps GCS finals,
then redistributes to private destination.
Distribute-then-delete: the track is first redistributed to the private
destination (private Dropbox archive + NOMADNP code, no YouTube/GDrive),
and only *after* that succeeds are the public outputs (YouTube, public
Dropbox folder, public GDrive files) deleted and the public NOMAD number
recycled. GCS finals are always kept.
This ordering is deliberate: YouTube deletion is irreversible, so nothing
public may be destroyed until the private archive exists. If redistribution
fails, the job is reverted to public and left fully intact (no partial
deletion, no leaked NOMADNP code — see redistribute_video's failure path).
"""
logger.info(f"[job:{job_id}] Starting visibility change: public -> private (by {user_email})")
db = self.job_manager.firestore.db
job_ref = db.collection("jobs").document(job_id)
# Set guard flag
# Capture the public output references BEFORE redistribution overwrites
# state_data with the new private values — we need them to delete the
# public outputs afterwards.
state_data = job.state_data or {}
public_outputs = {
"youtube_url": state_data.get("youtube_url"),
"brand_code": state_data.get("brand_code"),
"gdrive_files": state_data.get("gdrive_files"),
"dropbox_path": getattr(job, "dropbox_path", None),
"artist": job.artist,
"title": job.title,
}
# Set guard flag + flip to private so redistribution targets the private
# destination. Public outputs remain live until the private archive exists.
# No "changed to private" timeline event yet — it is only recorded once the
# move actually succeeds (this is reverted if redistribution fails).
job_ref.update({
"state_data.visibility_change_in_progress": True,
"is_private": True,
"updated_at": datetime.now(timezone.utc),
})
# Step 1: Redistribute to the private destination FIRST (public outputs
# still live). This is the only phase whose failure is safe to fully roll
# back — nothing public has been touched yet. redistribute_video verifies
# the archive actually materialized and recycles any NOMADNP code it
# allocated on failure, so a False return means "no-op, still public".
try:
# Step 1: Delete distributed outputs (keep GCS finals)
await self._delete_distributed_outputs(job_id, job, keep_gcs_finals=True)
# Step 2: Update job to private
job_ref.update({
"is_private": True,
"updated_at": datetime.now(timezone.utc),
"timeline": ArrayUnion([{
"status": "complete",
"timestamp": datetime.now(timezone.utc).isoformat(),
"message": f"Visibility changed to private by {user_email}",
}]),
})
# Step 3: Trigger redistribution via video worker
from backend.workers.video_worker import redistribute_video
success = await redistribute_video(job_id)
if not success:
raise RuntimeError("Redistribution failed - check worker logs")
# Clear guard flag (redistribution updates state_data with new brand_code etc.)
job_ref.update({
"state_data.visibility_change_in_progress": DELETE_FIELD,
})
logger.info(f"[job:{job_id}] Visibility change to private complete")
return {
"status": "success",
"message": "Job changed to private. Outputs redistributed to private destination.",
"reprocessing_required": False,
}
except Exception as e:
logger.error(f"[job:{job_id}] Visibility change to private failed: {e}", exc_info=True)
# Clear guard flag on failure
logger.error(f"[job:{job_id}] Redistribution raised during visibility change: {e}", exc_info=True)
success = False
if not success:
# Roll back to public: no public outputs were deleted, so restoring
# is_private=False leaves the job fully intact and public.
logger.error(f"[job:{job_id}] Visibility change to private failed: redistribution did not succeed")
job_ref.update({
"is_private": False,
"state_data.visibility_change_in_progress": DELETE_FIELD,
"updated_at": datetime.now(timezone.utc),
})
raise
raise RuntimeError("Redistribution failed - check worker logs")
# Step 2: Private archive now exists. From here we do NOT revert to public,
# even if public cleanup hiccups — the private move has committed. Deleting
# the public outputs + recycling the public NOMAD number is best-effort
# (each failure is logged inside the helper, never raised), so a stray
# orphaned public artifact cannot undo the successful private move.
await self._delete_public_outputs(job_id, public_outputs)
# Record the completed move and clear the guard flag. redistribute_video
# already updated state_data with the new private brand_code etc.
job_ref.update({
"state_data.visibility_change_in_progress": DELETE_FIELD,
"updated_at": datetime.now(timezone.utc),
"timeline": ArrayUnion([{
"status": "complete",
"timestamp": datetime.now(timezone.utc).isoformat(),
"message": f"Visibility changed to private by {user_email}",
}]),
})
logger.info(f"[job:{job_id}] Visibility change to private complete")
return {
"status": "success",
"message": "Job changed to private. Outputs redistributed to private destination.",
"reprocessing_required": False,
}
async def change_to_public(self, job_id: str, job, user_email: str) -> dict:
"""
@@ -141,7 +173,11 @@ class VisibilityChangeService:
f"jobs/{job_id}/videos/with_vocals.mov",
]:
try:
storage.delete_file(path)
# Best-effort delete over a template of possible artifacts; many of
# these intermediates legitimately never existed for a given render
# path. ignore_missing keeps a 404 a quiet no-op instead of a noisy
# ERROR log (which would otherwise trip the error-monitor).
storage.delete_file(path, ignore_missing=True)
except Exception:
pass
@@ -212,6 +248,103 @@ class VisibilityChangeService:
"reprocessing_required": True,
}
async def _delete_public_outputs(self, job_id: str, public_outputs: dict):
"""Delete the captured PUBLIC outputs and recycle the public NOMAD number.
Used by change_to_private AFTER a successful private redistribution. Operates
on references captured before redistribution (which overwrites state_data with
private values). Does not touch GCS finals and does not clear state_data keys
(redistribution already set the new private values). Best-effort: individual
failures are logged, not raised, so one orphaned artifact can't undo the move.
"""
import re
# Track whether each public destination was fully cleaned. The NOMAD number
# is only recycled when every deletion succeeded — otherwise a future public
# track could reuse the number while the old public files still linger,
# producing a duplicate. (Mirrors the admin delete-outputs recycle gate.)
youtube_ok = True
dropbox_ok = True
gdrive_ok = True
youtube_url = public_outputs.get("youtube_url")
if youtube_url:
try:
video_id_match = re.search(r'(?:youtu\.be/|youtube\.com/watch\?v=)([^&\s]+)', youtube_url)
if video_id_match:
video_id = video_id_match.group(1)
from karaoke_gen.karaoke_finalise.karaoke_finalise import KaraokeFinalise
from backend.services.youtube_service import get_youtube_service
youtube_service = get_youtube_service()
if youtube_service.is_configured:
finalise = KaraokeFinalise(
dry_run=False, non_interactive=True,
user_youtube_credentials=youtube_service.get_credentials_dict()
)
finalise.delete_youtube_video(video_id)
logger.info(f"[job:{job_id}] Deleted public YouTube video {video_id}")
except Exception as e:
youtube_ok = False
logger.warning(f"[job:{job_id}] Failed to delete public YouTube video: {e}")
brand_code = public_outputs.get("brand_code")
dropbox_path = public_outputs.get("dropbox_path")
if brand_code and dropbox_path:
try:
from backend.services.dropbox_service import get_dropbox_service
dropbox = get_dropbox_service()
if dropbox.is_configured:
from karaoke_gen.utils import sanitize_filename
safe_artist = sanitize_filename(public_outputs.get("artist")) if public_outputs.get("artist") else "Unknown"
safe_title = sanitize_filename(public_outputs.get("title")) if public_outputs.get("title") else "Unknown"
folder_name = f"{brand_code} - {safe_artist} - {safe_title}"
full_path = f"{dropbox_path}/{folder_name}"
dropbox.delete_folder(full_path)
logger.info(f"[job:{job_id}] Deleted public Dropbox folder {full_path}")
except Exception as e:
dropbox_ok = False
logger.warning(f"[job:{job_id}] Failed to delete public Dropbox folder: {e}")
gdrive_files = public_outputs.get("gdrive_files")
if gdrive_files:
try:
from backend.services.gdrive_service import get_gdrive_service
gdrive = get_gdrive_service()
if gdrive.is_configured:
file_ids = list(gdrive_files.values()) if isinstance(gdrive_files, dict) else []
gdrive.delete_files(file_ids)
logger.info(f"[job:{job_id}] Deleted public Google Drive files")
except Exception as e:
gdrive_ok = False
logger.warning(f"[job:{job_id}] Failed to delete public Google Drive files: {e}")
# A track going private should also leave the public Nomad GCS fast-sync
# mirror (and thus kjbox). Prefix-keyed by the public brand_code, non-fatal.
if brand_code:
try:
from backend.services.nomad_master_mirror import cleanup_nomad_masters
cleanup_nomad_masters(brand_code)
except Exception as e:
logger.warning(f"[job:{job_id}] Failed to clean up Nomad mirror for {brand_code}: {e}")
# Recycle the public NOMAD number so the next public track fills the gap —
# but only if every public deletion succeeded. If any lingered, keep the
# number reserved (a permanent gap the validator will flag) rather than
# risk a future duplicate; the leftover artifacts can then be cleaned up.
if brand_code and youtube_ok and dropbox_ok and gdrive_ok:
try:
from backend.services.brand_code_service import BrandCodeService, get_brand_code_service
prefix, number = BrandCodeService.parse_brand_code(brand_code)
get_brand_code_service().recycle_brand_code(prefix, number)
logger.info(f"[job:{job_id}] Recycled public brand code {brand_code}")
except Exception as e:
logger.warning(f"[job:{job_id}] Failed to recycle public brand code {brand_code}: {e}")
elif brand_code:
logger.warning(
f"[job:{job_id}] NOT recycling public brand code {brand_code}: "
f"public cleanup incomplete (youtube={youtube_ok}, dropbox={dropbox_ok}, gdrive={gdrive_ok})"
)
async def _delete_distributed_outputs(self, job_id: str, job, keep_gcs_finals: bool = False):
"""Delete distributed outputs (YouTube, Dropbox, GDrive) and recycle brand code."""
import re
+7 -5
View File
@@ -2,13 +2,15 @@
YouTube download service for cloud backend.
This service provides a single entry point for all YouTube downloads in the cloud.
It automatically routes downloads through the remote flacfetch service when configured,
avoiding YouTube bot detection issues on Cloud Run IPs.
flacfetch is the SOLE downloader: downloads are always routed through the remote
flacfetch service, which has YouTube cookies and avoids bot detection on Cloud Run IPs.
The flow is:
1. Check if remote flacfetch is configured (FLACFETCH_API_URL)
2. If yes: Use FlacfetchClient.download_by_id() - downloads on VM, uploads to GCS
3. If no: Use local yt_dlp (with warning about bot detection risk)
3. If no: raise YouTubeDownloadError — there is NO local yt-dlp fallback. We never
run yt-dlp inside the Cloud Run container (it's blocked by bot detection and a
silent fallback previously masked a real download bug — 2026-06-08 incident).
All entry points (audio search selection, direct URL submission) should use this
service for YouTube downloads to ensure consistent behavior.
@@ -34,8 +36,8 @@ class YouTubeDownloadService:
When remote flacfetch is configured (FLACFETCH_API_URL), downloads happen
on the flacfetch VM which has YouTube cookies and avoids bot detection.
When remote is not configured, falls back to local yt_dlp with a warning
that downloads may be blocked on Cloud Run IPs.
When remote is not configured, this raises YouTubeDownloadError. There is no
local yt-dlp fallback — flacfetch is the sole downloader.
Usage:
service = get_youtube_download_service()
@@ -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()
@@ -502,8 +502,12 @@ class TestMadeForYouYouTubeErrorHandling:
youtube_order_metadata
):
"""
Test that exceptions during processing send failure notification to admin.
Test that a job-creation failure sends a failure notification to admin AND
re-raises so the Stripe webhook returns non-2xx and Stripe retries the (likely
transient) failure — a paid order must not be silently dropped when no job was
ever created.
"""
import pytest
from backend.api.routes.users import _handle_made_for_you_order, ADMIN_EMAIL
# Make job creation fail
@@ -516,15 +520,16 @@ class TestMadeForYouYouTubeErrorHandling:
patch('backend.api.routes.users.get_effective_distribution_settings', return_value=mock_distribution_settings), \
patch('backend.api.routes.users.resolve_cdg_txt_defaults', return_value=(False, False)):
# Should not raise - error is handled internally
await _handle_made_for_you_order(
session_id="sess_test_error",
metadata=youtube_order_metadata,
user_service=mock_user_service_for_webhook,
email_service=mock_email_service,
)
# Re-raises (job never created) so the webhook returns non-2xx -> Stripe retries
with pytest.raises(Exception, match="Database error"):
await _handle_made_for_you_order(
session_id="sess_test_error",
metadata=youtube_order_metadata,
user_service=mock_user_service_for_webhook,
email_service=mock_email_service,
)
# Verify failure email was sent to admin
# Verify failure email was sent to admin before re-raising
mock_email_service.send_email.assert_called()
call_args = mock_email_service.send_email.call_args
assert call_args.kwargs['to_email'] == ADMIN_EMAIL
@@ -258,3 +258,58 @@ def test_stale_48h_expiry_sends_email_with_timeout_reason():
assert "48" not in sent['subject'] and "not confirmed" not in sent['subject'], (
f"over_limit email should not say '48 hours'. subject={sent.get('subject')!r}"
)
# ---------------------------------------------------------------------------
# Regression (job a453d1d5): a failing email-service construction must NOT
# crash an otherwise-successful audio download. reconcile_and_maybe_pause runs
# in the audio-download-job Cloud Run Job; EmailService() raises in production
# when POSTMARK_SERVER_TOKEN is unset. Reconcile must degrade to no-email.
# ---------------------------------------------------------------------------
def _patch_reconcile_singletons(monkeypatch, jm, us, actual_seconds):
"""Patch the function-scoped imports reconcile_and_maybe_pause pulls in.
These are imported inside the function (to avoid circular imports), so they
must be patched at their source modules, not on duration_reconciliation.
"""
from backend.services import duration_reconciliation as dr
monkeypatch.setattr("backend.services.job_manager.JobManager", lambda: jm)
monkeypatch.setattr("backend.services.user_service.get_user_service", lambda: us)
monkeypatch.setattr("backend.services.storage_service.StorageService", lambda: MagicMock())
monkeypatch.setattr(
"backend.services.email_service.get_email_service",
MagicMock(side_effect=RuntimeError("POSTMARK_SERVER_TOKEN is not set in production")),
)
monkeypatch.setattr(dr, "_ffprobe_seconds", lambda job, storage: actual_seconds)
@pytest.mark.asyncio
async def test_reconcile_and_maybe_pause_survives_email_service_failure(monkeypatch):
from backend.services import duration_reconciliation as dr
jm = MagicMock()
jm.get_job.return_value = _job(credits_charged=2)
# Duration matches estimate → proceed, no email needed anyway.
_patch_reconcile_singletons(monkeypatch, jm, MagicMock(), actual_seconds=900.0) # 15min -> 2 credits
# Must not raise despite email service construction failing.
blocked = await dr.reconcile_and_maybe_pause("job1")
assert blocked is False # proceeds normally
@pytest.mark.asyncio
async def test_reconcile_and_maybe_pause_over_limit_still_cancels_without_email(monkeypatch):
"""Over-limit cancel must still refund+cancel even if email can't be built."""
from backend.services import duration_reconciliation as dr
jm = MagicMock()
jm.get_job.return_value = _job(credits_charged=2)
us = MagicMock()
us.add_credits.return_value = (True, 99, "ok")
_patch_reconcile_singletons(monkeypatch, jm, us, actual_seconds=4000.0) # >60min
blocked = await dr.reconcile_and_maybe_pause("job1")
assert blocked is True # cancelled
jm.cancel_job.assert_called_once()
us.add_credits.assert_called_once() # full refund still happens
+16
View File
@@ -321,6 +321,22 @@ class TestAudioSearchServiceSearch:
assert "No results found" in str(exc_info.value)
def test_remote_search_failure_does_not_fall_back_to_local(self):
"""A remote flacfetch error must fail loudly, not silently downgrade to local YouTube."""
from backend.services.flacfetch_client import FlacfetchServiceError
service = AudioSearchService(red_api_key=None, red_api_url=None, ops_api_key=None, ops_api_url=None)
mock_remote = Mock()
mock_remote.search = AsyncMock(side_effect=FlacfetchServiceError("remote service down"))
service._remote_client = mock_remote
service._fetcher = Mock() # local fetcher — must NOT be used as a silent fallback
with pytest.raises(AudioSearchError, match="Remote flacfetch search failed"):
service.search("ABBA", "Waterloo")
# Critical: we did NOT silently fall back to the local YouTube-only fetcher.
service._fetcher.search.assert_not_called()
def test_search_multiple_results(self):
"""Test search returns multiple results with correct indices."""
mock_results = []
+42
View File
@@ -0,0 +1,42 @@
"""
Tests for admin-token initialization in AuthService.
An empty ADMIN_TOKENS configuration silently breaks every admin/internal-worker
endpoint (they fail closed with 403). That's safe but looks like an auth bug
rather than a config error, so it must be a LOUD signal: an ERROR log (picked up
by the error monitor → Discord alert), not a quiet warning.
"""
from unittest.mock import patch, MagicMock
from backend.services.auth_service import AuthService
def _make_service(admin_tokens_value):
"""Construct AuthService with a controlled settings.admin_tokens value."""
with patch("backend.services.auth_service.FirestoreService"), \
patch("backend.services.auth_service.get_settings") as mock_get_settings, \
patch("backend.services.auth_service.logger") as mock_logger:
mock_settings = MagicMock()
mock_settings.admin_tokens = admin_tokens_value
mock_settings.scheduler_service_account = "karaoke-backend@nomadkaraoke.iam.gserviceaccount.com"
mock_get_settings.return_value = mock_settings
service = AuthService()
return service, mock_logger
def test_no_admin_tokens_logs_error_not_warning():
"""Empty ADMIN_TOKENS → ERROR-level loud signal, not a quiet warning."""
service, mock_logger = _make_service("")
assert service.admin_tokens == []
mock_logger.error.assert_called_once()
# It used to be a quiet warning — make sure it isn't anymore.
mock_logger.warning.assert_not_called()
def test_admin_tokens_present_no_error():
"""Configured admin tokens → no error, tokens parsed."""
service, mock_logger = _make_service("tok1, tok2 ,tok3")
assert service.admin_tokens == ["tok1", "tok2", "tok3"]
mock_logger.error.assert_not_called()
+124 -10
View File
@@ -101,7 +101,9 @@ class TestChangeToPrivate:
"""Test public -> private visibility change."""
@pytest.mark.asyncio
async def test_calls_redistribute(self):
async def test_redistributes_then_deletes_public(self):
"""Distribute-then-delete: redistribute runs, then public outputs are deleted
with the references captured before redistribution overwrote state."""
mock_job_manager = MagicMock()
mock_job_ref = MagicMock()
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
@@ -110,18 +112,29 @@ class TestChangeToPrivate:
job = _make_job(is_private=False, state_data={
"youtube_url": "https://youtube.com/watch?v=abc",
"brand_code": "NOMAD-0001",
"gdrive_files": {"mp4": "id1"},
"dropbox_link": "https://dropbox.com/test",
})
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock) as mock_delete, \
patch("backend.workers.video_worker.redistribute_video", new_callable=AsyncMock, return_value=True) as mock_redist:
call_order = []
mock_redist = AsyncMock(return_value=True, side_effect=lambda *a, **k: call_order.append("redist") or True)
mock_delete = AsyncMock(side_effect=lambda *a, **k: call_order.append("delete"))
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_public_outputs", mock_delete), \
patch("backend.workers.video_worker.redistribute_video", mock_redist):
result = await service.change_to_private("test-123", job, "user@example.com")
assert result["status"] == "success"
assert result["reprocessing_required"] is False
mock_delete.assert_called_once_with("test-123", job, keep_gcs_finals=True)
mock_redist.assert_called_once_with("test-123")
# Redistribution must happen BEFORE any public deletion.
assert call_order == ["redist", "delete"]
# Public deletion receives the references captured before redistribution.
captured = mock_delete.call_args.args[1]
assert captured["youtube_url"] == "https://youtube.com/watch?v=abc"
assert captured["brand_code"] == "NOMAD-0001"
assert captured["gdrive_files"] == {"mp4": "id1"}
@pytest.mark.asyncio
async def test_sets_is_private_true(self):
@@ -132,7 +145,7 @@ class TestChangeToPrivate:
service = VisibilityChangeService(job_manager=mock_job_manager)
job = _make_job(is_private=False, state_data={})
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock), \
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_public_outputs", new_callable=AsyncMock), \
patch("backend.workers.video_worker.redistribute_video", new_callable=AsyncMock, return_value=True):
await service.change_to_private("test-123", job, "user@example.com")
@@ -179,6 +192,37 @@ class TestChangeToPublic:
mock_worker.trigger_screens_worker.assert_called_once_with("test-123")
mock_theme.assert_called_once_with(job_id="test-123", theme_id="nomad")
@pytest.mark.asyncio
async def test_intermediate_deletes_ignore_missing(self):
"""Best-effort deletes of intermediate render artifacts must pass
ignore_missing=True so absent .mov/.mkv files are a quiet no-op instead
of a noisy ERROR log that trips the error-monitor (regression)."""
mock_job_manager = MagicMock()
mock_job_ref = MagicMock()
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
service = VisibilityChangeService(job_manager=mock_job_manager)
job = _make_job(is_private=True, state_data={})
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock), \
patch("backend.services.visibility_change_service.StorageService") as mock_storage_cls, \
patch("backend.api.routes.file_upload._prepare_theme_for_job", return_value=("jobs/test-123/style/style_params.json", {"bg": "bg.png"}, None)), \
patch("backend.services.worker_service.get_worker_service") as mock_worker_svc:
mock_storage = MagicMock()
mock_storage_cls.return_value = mock_storage
mock_worker = MagicMock()
mock_worker.trigger_screens_worker = AsyncMock(return_value=True)
mock_worker_svc.return_value = mock_worker
await service.change_to_public("test-123", job, "user@example.com")
assert mock_storage.delete_file.call_count > 0
for call in mock_storage.delete_file.call_args_list:
assert call.kwargs.get("ignore_missing") is True, (
f"delete_file called without ignore_missing=True: {call}"
)
@pytest.mark.asyncio
async def test_resets_styles_to_nomad_theme(self):
mock_job_manager = MagicMock()
@@ -252,22 +296,33 @@ class TestChangeToPrivateErrors:
@pytest.mark.asyncio
async def test_rollback_on_redistribute_failure(self):
"""On redistribution failure NOTHING public is deleted and the job is
reverted to public — a failed going-private is a no-op, not a partial."""
mock_job_manager = MagicMock()
mock_job_ref = MagicMock()
mock_job_manager.firestore.db.collection.return_value.document.return_value = mock_job_ref
service = VisibilityChangeService(job_manager=mock_job_manager)
job = _make_job(is_private=False, state_data={})
job = _make_job(is_private=False, state_data={
"youtube_url": "https://youtube.com/watch?v=abc",
"brand_code": "NOMAD-0001",
"gdrive_files": {"mp4": "id1"},
})
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_distributed_outputs", new_callable=AsyncMock), \
mock_delete = AsyncMock()
with patch("backend.services.visibility_change_service.VisibilityChangeService._delete_public_outputs", mock_delete), \
patch("backend.workers.video_worker.redistribute_video", new_callable=AsyncMock, return_value=False):
with pytest.raises(RuntimeError, match="Redistribution failed"):
await service.change_to_private("test-123", job, "user@example.com")
# Guard flag should be cleared on failure (DELETE_FIELD sentinel)
last_update = mock_job_ref.update.call_args_list[-1]
val = last_update.args[0].get("state_data.visibility_change_in_progress")
# Public outputs must NOT be deleted when redistribution fails.
mock_delete.assert_not_called()
# Job reverted to public + guard flag cleared (DELETE_FIELD sentinel).
last_update = mock_job_ref.update.call_args_list[-1].args[0]
assert last_update.get("is_private") is False
val = last_update.get("state_data.visibility_change_in_progress")
assert "delete" in str(type(val)).lower() or "sentinel" in str(val).lower()
@@ -292,6 +347,65 @@ class TestDeleteDistributedOutputs:
mock_brand_svc.recycle_brand_code.assert_called_once_with("NOMAD", 42)
@pytest.mark.asyncio
async def test_delete_public_outputs_recycles_public_code(self):
"""_delete_public_outputs recycles the captured public NOMAD number."""
mock_job_manager = MagicMock()
service = VisibilityChangeService(job_manager=mock_job_manager)
public_outputs = {
"youtube_url": None,
"brand_code": "NOMAD-0042",
"gdrive_files": None,
"dropbox_path": None,
"artist": "A",
"title": "T",
}
with patch("backend.services.brand_code_service.get_brand_code_service") as mock_bcs, \
patch("backend.services.brand_code_service.BrandCodeService.parse_brand_code", return_value=("NOMAD", 42)), \
patch("backend.services.nomad_master_mirror.cleanup_nomad_masters") as mock_mirror:
mock_brand_svc = MagicMock()
mock_bcs.return_value = mock_brand_svc
await service._delete_public_outputs("test-123", public_outputs)
# No public YouTube/Dropbox/GDrive present → all deletions "succeed" →
# the public number is recycled and the mirror is cleaned.
mock_mirror.assert_called_once_with("NOMAD-0042")
mock_brand_svc.recycle_brand_code.assert_called_once_with("NOMAD", 42)
@pytest.mark.asyncio
async def test_delete_public_outputs_skips_recycle_on_incomplete_cleanup(self):
"""If a public deletion fails, the number is NOT recycled (avoids a future
duplicate against lingering public files)."""
mock_job_manager = MagicMock()
service = VisibilityChangeService(job_manager=mock_job_manager)
public_outputs = {
"youtube_url": None,
"brand_code": "NOMAD-0042",
"gdrive_files": {"mp4": "id1"},
"dropbox_path": None,
"artist": "A",
"title": "T",
}
with patch("backend.services.gdrive_service.get_gdrive_service") as mock_gd, \
patch("backend.services.nomad_master_mirror.cleanup_nomad_masters"), \
patch("backend.services.brand_code_service.get_brand_code_service") as mock_bcs, \
patch("backend.services.brand_code_service.BrandCodeService.parse_brand_code", return_value=("NOMAD", 42)):
gd = MagicMock()
gd.is_configured = True
gd.delete_files.side_effect = RuntimeError("gdrive boom")
mock_gd.return_value = gd
mock_brand_svc = MagicMock()
mock_bcs.return_value = mock_brand_svc
await service._delete_public_outputs("test-123", public_outputs)
mock_brand_svc.recycle_brand_code.assert_not_called()
@pytest.mark.asyncio
async def test_clears_distribution_state_keys(self):
mock_job_manager = MagicMock()
+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
+102
View File
@@ -0,0 +1,102 @@
"""
Fallback audit (Theme 7): production must fail loudly on missing required config
rather than silently running on dev defaults (wrong GCP project / GCS bucket /
localhost worker URL / console-only email), and the tenant query-param override
must be production-safe by default.
"""
import importlib
import pytest
from backend.config import is_production, validate_production_config
from backend.services.email_service import EmailService
# ---- is_production() ----
def test_is_production_via_environment(monkeypatch):
monkeypatch.setenv("ENVIRONMENT", "production")
monkeypatch.delenv("K_SERVICE", raising=False)
assert is_production() is True
def test_is_production_via_k_service(monkeypatch):
"""Cloud Run sets K_SERVICE automatically — production-safe even if ENVIRONMENT is unset."""
monkeypatch.delenv("ENVIRONMENT", raising=False)
monkeypatch.delenv("ENV", raising=False)
monkeypatch.setenv("K_SERVICE", "karaoke-api")
assert is_production() is True
def test_is_production_false_in_dev(monkeypatch):
monkeypatch.delenv("ENVIRONMENT", raising=False)
monkeypatch.delenv("ENV", raising=False)
monkeypatch.delenv("K_SERVICE", raising=False)
assert is_production() is False
# ---- validate_production_config() ----
def test_validate_raises_when_required_var_missing_in_prod(monkeypatch):
monkeypatch.setenv("ENVIRONMENT", "production")
monkeypatch.delenv("K_SERVICE", raising=False)
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "nomadkaraoke")
monkeypatch.setenv("GCS_BUCKET_NAME", "karaoke-gen-storage-nomadkaraoke")
monkeypatch.delenv("CLOUD_RUN_SERVICE_URL", raising=False) # missing!
with pytest.raises(RuntimeError, match="CLOUD_RUN_SERVICE_URL"):
validate_production_config()
def test_validate_passes_when_all_required_set_in_prod(monkeypatch):
monkeypatch.setenv("ENVIRONMENT", "production")
monkeypatch.delenv("K_SERVICE", raising=False)
monkeypatch.setenv("GOOGLE_CLOUD_PROJECT", "nomadkaraoke")
monkeypatch.setenv("GCS_BUCKET_NAME", "karaoke-gen-storage-nomadkaraoke")
monkeypatch.setenv("CLOUD_RUN_SERVICE_URL", "https://api.nomadkaraoke.com")
validate_production_config() # must not raise
def test_validate_noop_in_dev(monkeypatch):
monkeypatch.delenv("ENVIRONMENT", raising=False)
monkeypatch.delenv("ENV", raising=False)
monkeypatch.delenv("K_SERVICE", raising=False)
monkeypatch.delenv("CLOUD_RUN_SERVICE_URL", raising=False)
validate_production_config() # no-op, must not raise
# ---- email provider (7.5) ----
def test_email_provider_raises_in_prod_without_postmark(monkeypatch):
monkeypatch.setenv("ENVIRONMENT", "production")
monkeypatch.delenv("K_SERVICE", raising=False)
monkeypatch.delenv("POSTMARK_SERVER_TOKEN", raising=False)
with pytest.raises(RuntimeError, match="POSTMARK_SERVER_TOKEN"):
EmailService()
def test_email_provider_console_in_dev_without_postmark(monkeypatch):
monkeypatch.delenv("ENVIRONMENT", raising=False)
monkeypatch.delenv("ENV", raising=False)
monkeypatch.delenv("K_SERVICE", raising=False)
monkeypatch.delenv("POSTMARK_SERVER_TOKEN", raising=False)
svc = EmailService() # must not raise — console fallback is fine in dev
assert svc.is_configured() is False
# ---- tenant gate (7.4) ----
def test_tenant_gate_production_safe_with_k_service(monkeypatch):
"""K_SERVICE present (Cloud Run) → IS_PRODUCTION True → query-param override disabled."""
monkeypatch.delenv("ENVIRONMENT", raising=False)
monkeypatch.delenv("ENV", raising=False)
monkeypatch.setenv("K_SERVICE", "karaoke-api")
import backend.middleware.tenant as tenant_mod
try:
importlib.reload(tenant_mod)
assert tenant_mod.IS_PRODUCTION is True
finally:
# Restore module to a clean (dev) state so other tests aren't affected.
monkeypatch.delenv("K_SERVICE", raising=False)
importlib.reload(tenant_mod)
@@ -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)
+178
View File
@@ -555,3 +555,181 @@ class TestScreenVideoStaging:
assert (outputs / "Artist - Title (Title).mov").is_file()
assert not (outputs / "Artist - Title (End).mov").exists()
class TestEnsureLatestWheelVerification:
"""Test ensure_latest_wheel() install-retry + import-verification behavior.
Regression: a freshly-provisioned worker installs the wheel with --no-deps
at boot and relies on ensure_latest_wheel() to install the full dependency
tree at the first job. A transient/partial install could leave the env
importable-but-broken (`pip` exits 0 while `tenacity` is still missing),
and the return value was ignored, so the job proceeded and died with
"No module named 'tenacity'" deep inside render_video.
Fix: verify the render/encode import chain (via subprocess) and only return
True when it imports; retry a failed/partial install; callers fail fast.
"""
@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 = (
"gs://karaoke-gen-storage-nomadkaraoke/wheels/karaoke_gen-0.192.5-py3-none-any.whl\n"
"gs://karaoke-gen-storage-nomadkaraoke/wheels/karaoke_gen-0.192.6-py3-none-any.whl\n"
"gs://karaoke-gen-storage-nomadkaraoke/wheels/karaoke_gen-current.whl\n"
)
def _completed(self, returncode=0, stdout="", stderr=""):
import subprocess
return subprocess.CompletedProcess(args=[], returncode=returncode, stdout=stdout, stderr=stderr)
def _side_effect(self, ls_stdout=None, ls_rc=0, cp_rc=0, install_rc=0, verify_results=None):
"""Build a subprocess.run side_effect keyed on the command.
Models the download flow (gsutil ls -> gsutil cp of a single wheel),
the pip install, and the import-verification subprocess.
verify_results: list of booleans consumed in order, one per verify call
(True -> returncode 0). Lets a test model "install succeeded but imports
fail, then a retry fixes them".
"""
import sys
ls = self.DEFAULT_LS if ls_stdout is None else ls_stdout
verify_iter = iter(verify_results or [])
def side_effect(cmd, *args, **kwargs):
if cmd and cmd[0] == "gsutil" and cmd[1] == "ls":
return self._completed(returncode=ls_rc, stdout=ls)
if cmd and cmd[0] == "gsutil" and cmd[1] == "cp":
return self._completed(returncode=cp_rc)
if len(cmd) >= 2 and cmd[0] == sys.executable and cmd[1] == "-m":
# pip install ...
return self._completed(returncode=install_rc)
if len(cmd) >= 2 and cmd[0] == sys.executable and cmd[1] == "-c":
# import verification subprocess
ok = next(verify_iter, False)
return self._completed(
returncode=0 if ok else 1,
stderr="" if ok else "ModuleNotFoundError: No module named 'tenacity'",
)
return self._completed(returncode=0)
return side_effect
def test_downloads_only_latest_single_wheel(self, monkeypatch):
"""Must `gsutil cp` exactly one wheel (the latest version), not the whole dir."""
from backend.services.gce_encoding import main
cp_targets = []
base = self._side_effect(verify_results=[True])
def spy(cmd, *args, **kwargs):
if cmd and cmd[0] == "gsutil" and cmd[1] == "cp":
cp_targets.append(cmd[2])
return base(cmd, *args, **kwargs)
monkeypatch.setattr(main.subprocess, "run", spy)
assert main.ensure_latest_wheel() is True
assert cp_targets == [
"gs://karaoke-gen-storage-nomadkaraoke/wheels/karaoke_gen-0.192.6-py3-none-any.whl"
]
def test_returns_true_when_install_and_imports_succeed(self, monkeypatch):
from backend.services.gce_encoding import main
monkeypatch.setattr(main.subprocess, "run", self._side_effect(verify_results=[True]))
assert main.ensure_latest_wheel() is True
def test_returns_false_when_pip_ok_but_imports_broken(self, monkeypatch):
"""The core regression: pip exits 0 but a dependency is missing."""
from backend.services.gce_encoding import main
# install always "succeeds", verification always fails -> not ready.
monkeypatch.setattr(main.subprocess, "run",
self._side_effect(install_rc=0, verify_results=[False, False, False]))
assert main.ensure_latest_wheel() is False
def test_retries_and_succeeds_after_partial_install(self, monkeypatch):
"""First attempt leaves deps missing; a retry completes them."""
from backend.services.gce_encoding import main
monkeypatch.setattr(main.subprocess, "run", self._side_effect(verify_results=[False, True]))
assert main.ensure_latest_wheel() is True
def test_returns_false_when_no_wheel_found(self, monkeypatch):
"""Only the current wheel exists (filtered out) -> no versioned wheel."""
from backend.services.gce_encoding import main
only_current = "gs://karaoke-gen-storage-nomadkaraoke/wheels/karaoke_gen-current.whl\n"
monkeypatch.setattr(main.subprocess, "run", self._side_effect(ls_stdout=only_current))
assert main.ensure_latest_wheel() is False
def test_returns_false_when_download_fails(self, monkeypatch):
"""A failed single-wheel copy is reported, not silently installed."""
from backend.services.gce_encoding import main
monkeypatch.setattr(main.subprocess, "run", self._side_effect(cp_rc=1))
assert main.ensure_latest_wheel() is False
def test_install_timeout_then_success(self, monkeypatch):
"""A timed-out first install must not abort the whole routine."""
import sys
import subprocess
from backend.services.gce_encoding import main
state = {"install_calls": 0}
base = self._side_effect()
def side_effect(cmd, *args, **kwargs):
if len(cmd) >= 2 and cmd[0] == sys.executable and cmd[1] == "-m":
state["install_calls"] += 1
if state["install_calls"] == 1:
raise subprocess.TimeoutExpired(cmd, main.WHEEL_INSTALL_TIMEOUT)
return self._completed(returncode=0)
if len(cmd) >= 2 and cmd[0] == sys.executable and cmd[1] == "-c":
# Imports fail after the timed-out first install, succeed after retry.
return self._completed(returncode=0 if state["install_calls"] >= 2 else 1,
stderr="ModuleNotFoundError")
return base(cmd, *args, **kwargs)
monkeypatch.setattr(main.subprocess, "run", side_effect)
assert main.ensure_latest_wheel() is True
class TestVerifyWheelImports:
"""Test the verify_wheel_imports() helper in isolation."""
def test_true_on_clean_import(self, monkeypatch):
import subprocess
from backend.services.gce_encoding import main
monkeypatch.setattr(main.subprocess, "run",
lambda *a, **k: subprocess.CompletedProcess([], 0, "", ""))
assert main.verify_wheel_imports() is True
def test_false_on_import_error(self, monkeypatch):
import subprocess
from backend.services.gce_encoding import main
monkeypatch.setattr(
main.subprocess, "run",
lambda *a, **k: subprocess.CompletedProcess(
[], 1, "", "ModuleNotFoundError: No module named 'tenacity'"))
assert main.verify_wheel_imports() is False
def test_false_on_timeout(self, monkeypatch):
import subprocess
from backend.services.gce_encoding import main
def _timeout(*a, **k):
raise subprocess.TimeoutExpired(["python", "-c"], 180)
monkeypatch.setattr(main.subprocess, "run", _timeout)
assert main.verify_wheel_imports() is False
+14 -1
View File
@@ -171,7 +171,7 @@ class TestLocalEncodingServiceEncodingMethods:
@patch.object(LocalEncodingService, "_execute_command_with_fallback")
def test_convert_mov_to_mp4(self, mock_execute):
"""Test MOV to MP4 conversion."""
"""Test MOV to MP4 conversion produces a standard, portable "With Vocals" mp4."""
mock_execute.return_value = True
service = LocalEncodingService()
@@ -182,6 +182,19 @@ class TestLocalEncodingServiceEncodingMethods:
assert result is True
mock_execute.assert_called_once()
gpu_command, cpu_command = mock_execute.call_args[0][0], mock_execute.call_args[0][1]
# The CPU (software) command is what runs on prod encoding workers (no NVENC).
# It must normalize 4:4:4 -> 4:2:0 for playback compatibility, use a fast preset
# (this is the longest finalization stage), and emit portable AAC (not FLAC-in-mp4).
assert "-pix_fmt yuv420p" in cpu_command
assert "-preset veryfast" in cpu_command
assert "-c:a aac" in cpu_command
assert "-b:a 320k" in cpu_command
assert "-c:a copy" not in cpu_command # regression guard: no FLAC-in-mp4
# GPU path also forces 4:2:0 (h264_nvenc can preserve yuv444p) and emits AAC.
assert "-pix_fmt yuv420p" in gpu_command
assert "-c:a aac" in gpu_command
assert "-b:a 320k" in gpu_command
@patch.object(LocalEncodingService, "_execute_command_with_fallback")
def test_encode_lossless_mp4_without_end(self, mock_execute):
+204
View File
@@ -266,6 +266,37 @@ class TestMadeForYouOrderConfirmationEmail:
assert call_kwargs.get('cc_emails') is None
class TestEmailServiceSendEmailPassthrough:
"""Tests for the generic EmailService.send_email passthrough.
Regression (2026-08-22): the made-for-you failure handler called
``email_service.send_email(...)`` but EmailService had no such method (only the
provider did), so the failure alert itself crashed with
``'EmailService' object has no attribute 'send_email'`` — masking the original
error and losing the admin alert entirely.
"""
def test_send_email_delegates_to_provider(self):
service = EmailService()
service.provider = Mock()
service.provider.send_email.return_value = True
result = service.send_email(
to_email="admin@example.com",
subject="[FAILED] Test",
html_content="<p>oops</p>",
text_content="oops",
)
assert result is True
service.provider.send_email.assert_called_once()
call_kwargs = service.provider.send_email.call_args.kwargs
assert call_kwargs["to_email"] == "admin@example.com"
assert call_kwargs["subject"] == "[FAILED] Test"
assert call_kwargs["html_content"] == "<p>oops</p>"
assert call_kwargs["text_content"] == "oops"
class TestMadeForYouAdminNotificationEmail:
"""Tests for send_made_for_you_admin_notification method."""
@@ -1757,6 +1788,179 @@ class TestMadeForYouYouTubeDownloadContract:
assert "[FAILED]" in email_call.kwargs.get('subject', ''), \
"Error notification email should have [FAILED] in subject"
@pytest.mark.asyncio
async def test_youtube_download_failure_still_sends_customer_confirmation(
self, mock_job_manager, mock_email_service, mock_user_service,
mock_theme_service, youtube_order_metadata
):
"""
Regression: a YouTube download failure must NOT prevent the paid customer
from receiving their order-confirmation email, nor prevent the admin from
being alerted.
Bug context (2026-08-22): Job 17dc6f48 failed on a YouTube bot-check
download error. Because the confirmation + admin emails were only sent
*after* audio acquisition, the download failure skipped both — Andrew never
received the "New Made-For-You Order Received!" notification and there was no
guarantee the customer got their confirmation. The confirmation email is now
sent up-front, independently of the (fallible) audio acquisition step.
"""
from backend.api.routes.users import _handle_made_for_you_order, ADMIN_EMAIL
from backend.services.youtube_download_service import YouTubeDownloadError
mock_youtube_service = MagicMock()
mock_youtube_service.download = AsyncMock(
side_effect=YouTubeDownloadError(
"Sign in to confirm you're not a bot"
)
)
with patch('backend.services.job_manager.JobManager', return_value=mock_job_manager), \
patch('backend.services.worker_service.get_worker_service', return_value=MagicMock()), \
patch('backend.services.storage_service.StorageService'), \
patch('backend.api.routes.users.get_theme_service', return_value=mock_theme_service), \
patch('backend.api.routes.users.get_youtube_download_service', return_value=mock_youtube_service):
# Must not raise - order intake is resilient to audio-acquisition failures
await _handle_made_for_you_order(
session_id="sess_123",
metadata=youtube_order_metadata,
user_service=mock_user_service,
email_service=mock_email_service,
)
# CRITICAL: customer still receives their order confirmation despite the failure
mock_email_service.send_made_for_you_order_confirmation.assert_called_once()
confirm_kwargs = mock_email_service.send_made_for_you_order_confirmation.call_args.kwargs
assert confirm_kwargs['to_email'] == youtube_order_metadata['customer_email']
assert confirm_kwargs['job_id'] == "test-job-123"
# CRITICAL: admin is alerted to the failure so they can intervene manually
mock_email_service.send_email.assert_called_once()
failure_kwargs = mock_email_service.send_email.call_args.kwargs
assert failure_kwargs['to_email'] == ADMIN_EMAIL
assert "[FAILED]" in failure_kwargs['subject']
@pytest.mark.asyncio
async def test_customer_confirmation_email_failure_does_not_abort_order(
self, mock_job_manager, mock_email_service, mock_user_service,
mock_theme_service, youtube_order_metadata
):
"""
Resilience: if the customer confirmation email itself fails to send, order
processing (audio acquisition + admin notification) must still proceed, and the
failed confirmation must be escalated to the admin (never silently lost). An
email-provider hiccup should never block the actual work.
"""
from backend.api.routes.users import _handle_made_for_you_order, ADMIN_EMAIL
# Confirmation email raises, but the order must still be processed
mock_email_service.send_made_for_you_order_confirmation.side_effect = \
RuntimeError("Postmark timeout")
# start_job_processing is async - mock it so the success path completes
mock_job_manager.start_job_processing = AsyncMock()
mock_youtube_service = MagicMock()
mock_youtube_service.download = AsyncMock(
return_value="uploads/test-job-123/audio/test.webm"
)
with patch('backend.services.job_manager.JobManager', return_value=mock_job_manager), \
patch('backend.services.worker_service.get_worker_service', return_value=MagicMock()), \
patch('backend.services.storage_service.StorageService'), \
patch('backend.api.routes.users.get_theme_service', return_value=mock_theme_service), \
patch('backend.api.routes.users.get_youtube_download_service', return_value=mock_youtube_service):
# Must not raise despite the confirmation email failure
await _handle_made_for_you_order(
session_id="sess_123",
metadata=youtube_order_metadata,
user_service=mock_user_service,
email_service=mock_email_service,
)
# Download still happened and admin notification still sent
mock_youtube_service.download.assert_called_once()
mock_email_service.send_made_for_you_admin_notification.assert_called_once()
# The failed customer confirmation is escalated to the admin so it can be
# resent manually — a paid confirmation must never be silently lost.
mock_email_service.send_email.assert_called_once()
alert_kwargs = mock_email_service.send_email.call_args.kwargs
assert alert_kwargs['to_email'] == ADMIN_EMAIL
assert "[FAILED]" in alert_kwargs['subject']
@pytest.mark.asyncio
async def test_confirmation_provider_rejection_is_escalated(
self, mock_job_manager, mock_email_service, mock_user_service,
mock_theme_service, youtube_order_metadata
):
"""
Providers return False (not an exception) when a send is rejected. A rejected
customer confirmation must be escalated to the admin, not silently logged as
sent. Regression guard for the "log success even on False" bug.
"""
from backend.api.routes.users import _handle_made_for_you_order, ADMIN_EMAIL
# Provider rejects the confirmation (returns False, does not raise)
mock_email_service.send_made_for_you_order_confirmation.return_value = False
mock_job_manager.start_job_processing = AsyncMock()
mock_youtube_service = MagicMock()
mock_youtube_service.download = AsyncMock(
return_value="uploads/test-job-123/audio/test.webm"
)
with patch('backend.services.job_manager.JobManager', return_value=mock_job_manager), \
patch('backend.services.worker_service.get_worker_service', return_value=MagicMock()), \
patch('backend.services.storage_service.StorageService'), \
patch('backend.api.routes.users.get_theme_service', return_value=mock_theme_service), \
patch('backend.api.routes.users.get_youtube_download_service', return_value=mock_youtube_service):
await _handle_made_for_you_order(
session_id="sess_123",
metadata=youtube_order_metadata,
user_service=mock_user_service,
email_service=mock_email_service,
)
# Rejected confirmation escalated to admin; order still processed
mock_email_service.send_email.assert_called_once()
assert mock_email_service.send_email.call_args.kwargs['to_email'] == ADMIN_EMAIL
mock_email_service.send_made_for_you_admin_notification.assert_called_once()
@pytest.mark.asyncio
async def test_job_creation_failure_reraises_for_stripe_retry(
self, mock_email_service, mock_user_service, mock_theme_service,
youtube_order_metadata
):
"""
If job creation fails (no job_id, session never marked processed), the handler
must re-raise so the Stripe webhook returns non-2xx and Stripe retries — a paid
order must not be silently dropped. The admin is still alerted first.
"""
from backend.api.routes.users import _handle_made_for_you_order, ADMIN_EMAIL
mock_job_manager = MagicMock()
mock_job_manager.create_job.side_effect = RuntimeError("Firestore unavailable")
with patch('backend.services.job_manager.JobManager', return_value=mock_job_manager), \
patch('backend.services.storage_service.StorageService'), \
patch('backend.api.routes.users.get_theme_service', return_value=mock_theme_service):
with pytest.raises(RuntimeError, match="Firestore unavailable"):
await _handle_made_for_you_order(
session_id="sess_123",
metadata=youtube_order_metadata,
user_service=mock_user_service,
email_service=mock_email_service,
)
# Admin alerted before the re-raise; no confirmation (job never created)
mock_email_service.send_email.assert_called_once()
assert mock_email_service.send_email.call_args.kwargs['to_email'] == ADMIN_EMAIL
mock_email_service.send_made_for_you_order_confirmation.assert_not_called()
class TestMadeForYouYouTubeImports:
"""
+68
View File
@@ -1132,3 +1132,71 @@ class TestGetPreviewVideoRedirect:
self._call(mock_storage)
assert exc_info.value.status_code == 404
mock_storage.generate_signed_url.assert_not_called()
class TestGetVocalsAudio:
"""The vocals waveform endpoint streams the full vocal stem for the timeline.
Real jobs never store a plain 'vocals' key — separation writes
'vocals_clean' / 'lead_vocals' / 'backing_vocals'. The endpoint must select
the fullest vocal mix (vocals_clean) rather than KeyError on 'vocals'.
"""
def _call(self, stems):
import asyncio
from backend.api.routes.review import _stream_audio
job = MagicMock()
job.input_media_gcs_path = "jobs/j/input.flac"
job.file_urls = {"stems": stems}
job_manager = MagicMock()
job_manager.get_job.return_value = job
transcoding = MagicMock()
transcoding.get_review_audio_url_async = AsyncMock(
return_value="https://signed.example/vocals.ogg?sig=xyz"
)
with patch("backend.api.routes.review.JobManager", return_value=job_manager), patch(
"backend.services.audio_transcoding_service.AudioTranscodingService",
return_value=transcoding,
):
resp = asyncio.run(
_stream_audio(job_id="j", stem="vocals")
)
return resp, transcoding
def test_selects_vocals_clean_when_no_plain_vocals_key(self):
from starlette.responses import RedirectResponse
# The shape produced by real cloud jobs (no plain "vocals").
resp, transcoding = self._call(
{
"instrumental_clean": "jobs/j/stems/instrumental_clean.flac",
"vocals_clean": "jobs/j/stems/vocals_clean.flac",
"lead_vocals": "jobs/j/stems/lead_vocals.flac",
"backing_vocals": "jobs/j/stems/backing_vocals.flac",
}
)
assert isinstance(resp, RedirectResponse)
assert resp.status_code == 302
# Must pick the full vocal mix (vocals_clean), not lead_vocals or KeyError.
assert transcoding.get_review_audio_url_async.call_args[0][0] == "jobs/j/stems/vocals_clean.flac"
def test_prefers_plain_vocals_then_falls_back_to_lead(self):
# 2-stem split exposes a plain "vocals" — preferred.
_, transcoding = self._call({"vocals": "jobs/j/stems/vocals.flac"})
assert transcoding.get_review_audio_url_async.call_args[0][0] == "jobs/j/stems/vocals.flac"
# Only lead_vocals available — last-resort fallback.
_, transcoding = self._call({"lead_vocals": "jobs/j/stems/lead_vocals.flac"})
assert transcoding.get_review_audio_url_async.call_args[0][0] == "jobs/j/stems/lead_vocals.flac"
def test_404_when_no_vocal_stem_present(self):
from fastapi import HTTPException
with pytest.raises(HTTPException) as exc_info:
self._call({"instrumental_clean": "jobs/j/stems/instrumental_clean.flac"})
assert exc_info.value.status_code == 404
+27 -2
View File
@@ -206,9 +206,34 @@ class TestStorageServiceDownload:
with pytest.raises(Exception) as exc_info:
service.download_file("missing/file.flac", "/local/path")
assert "File not found" in str(exc_info.value)
@patch("backend.services.storage_service.storage.Client")
@patch("backend.services.storage_service.settings")
def test_download_file_missing_reraises_notfound(self, mock_settings, mock_client_class):
"""A 404 from GCS re-raises NotFound (so callers can map it to HTTP 404)
and is logged at warning, not error, to avoid tripping the error-monitor."""
from google.cloud.exceptions import NotFound
mock_settings.google_cloud_project = "test-project"
mock_settings.gcs_bucket_name = "test-bucket"
mock_blob = Mock()
mock_blob.download_to_filename.side_effect = NotFound("No such object")
mock_bucket = Mock()
mock_bucket.blob.return_value = mock_blob
mock_client = Mock()
mock_client.bucket.return_value = mock_bucket
mock_client_class.return_value = mock_client
service = StorageService()
with patch("backend.services.storage_service.logger") as mock_logger:
with pytest.raises(NotFound):
service.download_file("jobs/abc/finals/lossy_4k_mp4.mp4", "/local/path")
mock_logger.error.assert_not_called()
mock_logger.warning.assert_called_once()
@patch("backend.services.storage_service.storage.Client")
@patch("backend.services.storage_service.settings")
def test_download_json(self, mock_settings, mock_client_class):
@@ -51,6 +51,12 @@ def mock_encoding_worker_config():
config.deploy_in_progress = False
config.deploy_in_progress_since = None
config.last_activity_at = None
# No capacity fallback active by default → serving the c4d primary.
config.active_override_vm = None
config.active_override_ip = None
config.active_override_zone = None
config.active_override_set_at = None
config.primary_machine_type = None
return config
@@ -134,6 +140,7 @@ class TestSystemStatusAdmin:
mock_auth = ("token123", UserType.ADMIN, -1)
mock_manager = MagicMock()
mock_manager._zone = "us-central1-c"
mock_manager.get_config.return_value = mock_encoding_worker_config
with patch("backend.api.routes.health.check_encoding_worker_status", new_callable=AsyncMock, return_value=mock_encoding_status), \
@@ -155,3 +162,46 @@ class TestSystemStatusAdmin:
assert admin["secondary_vm"] == "encoding-worker-a"
assert admin["last_swap_at"] == "2026-03-31T18:10:00Z"
assert admin["deploy_in_progress"] is False
# No fallback active → serving the c4d primary VM.
assert admin["on_fallback"] is False
assert admin["active_vm"] == "encoding-worker-b"
assert admin["active_zone"] == "us-central1-c"
assert admin["active_machine_type"] == "c4d-highcpu-32"
@pytest.mark.asyncio
async def test_admin_sees_capacity_fallback_worker(
self, mock_encoding_status, mock_flacfetch_status, mock_separator_status, mock_encoding_worker_config
):
"""When a stockout routes off the primary, the live worker reflects the fallback."""
from backend.api.routes.health import system_status
from backend.services.auth_service import UserType
# Capacity fallback active: serving an n2-family VM in an alternate zone.
mock_encoding_worker_config.active_override_vm = "encoding-worker-fallback-n2c"
mock_encoding_worker_config.active_override_ip = "34.9.9.9"
mock_encoding_worker_config.active_override_zone = "us-central1-a"
mock_auth = ("token123", UserType.ADMIN, -1)
mock_manager = MagicMock()
mock_manager._zone = "us-central1-c"
mock_manager.get_config.return_value = mock_encoding_worker_config
with patch("backend.api.routes.health.check_encoding_worker_status", new_callable=AsyncMock, return_value=mock_encoding_status), \
patch("backend.api.routes.health.check_flacfetch_service_status", new_callable=AsyncMock, return_value=mock_flacfetch_status), \
patch("backend.api.routes.health.check_audio_separator_status", return_value=mock_separator_status), \
patch("backend.api.routes.health.VERSION", "0.155.3"), \
patch("backend.api.routes.health.COMMIT_SHA", ""), \
patch("backend.api.routes.health.PR_NUMBER", ""), \
patch("backend.api.routes.health.PR_TITLE", ""), \
patch("backend.api.routes.health.STARTUP_TIME", "2026-03-31T18:10:00Z"), \
patch("backend.api.routes.health._get_encoding_worker_manager", return_value=mock_manager):
result = await system_status(auth=mock_auth)
admin = result["services"]["encoder"]["admin_details"]
assert admin["on_fallback"] is True
assert admin["active_vm"] == "encoding-worker-fallback-n2c"
assert admin["active_zone"] == "us-central1-a"
# "n2c" family token → n2-highcpu-32 (inferred from the VM name).
assert admin["active_machine_type"] == "n2-highcpu-32"
@@ -21,6 +21,7 @@ from backend.workers.video_worker_orchestrator import (
VideoWorkerOrchestrator,
create_orchestrator_config_from_job,
)
from backend.models.job import JobStatus
class TestOrchestratorConfig:
@@ -2132,3 +2133,52 @@ class TestOriginalVocalsGuideEmit:
with patch("backend.workers.style_helper.load_style_config", side_effect=fake_load):
assert await orch._resolve_intro_seconds() == 8.0
class TestRedistributeModeProgress:
"""redistribute_mode must not attempt job status transitions.
Regression for the public->private data-loss bug: redistributing an already
`complete` job drove `_update_progress(PACKAGING)`, which raised
InvalidStateTransitionError (`complete -> packaging`) and aborted the
redistribution after the public outputs had already been deleted.
"""
def _config(self, redistribute_mode):
return OrchestratorConfig(
job_id="job-1",
artist="A",
title="T",
title_video_path="",
karaoke_video_path="",
instrumental_audio_path="",
redistribute_mode=redistribute_mode,
)
def test_redistribute_mode_skips_status_transition(self):
jm = MagicMock()
orch = VideoWorkerOrchestrator(
config=self._config(redistribute_mode=True),
job_manager=jm,
storage=MagicMock(),
job_logger=MagicMock(),
)
orch._update_progress(JobStatus.PACKAGING, 90, "Uploading files")
jm.transition_to_state.assert_not_called()
jm.update_job.assert_called_once_with("job-1", {"progress": 90})
def test_normal_mode_drives_status_transition(self):
jm = MagicMock()
orch = VideoWorkerOrchestrator(
config=self._config(redistribute_mode=False),
job_manager=jm,
storage=MagicMock(),
job_logger=MagicMock(),
)
orch._update_progress(JobStatus.PACKAGING, 90, "Uploading files")
jm.transition_to_state.assert_called_once()
jm.update_job.assert_not_called()
+36 -10
View File
@@ -816,20 +816,46 @@ class TestDownloadAudioWithUrl:
@pytest.mark.asyncio
async def test_download_audio_url_without_gcs_path_refuses(self, mock_job_with_url, mock_job_manager, mock_storage):
"""A URL job with no GCS file must fail (no local yt-dlp fallback)."""
"""A URL job with no GCS file must fail loudly (no local yt-dlp fallback)."""
from backend.workers.audio_worker import download_audio
from backend.services.audio_search_service import DownloadError
with tempfile.TemporaryDirectory() as temp_dir:
result = await download_audio(
"test123",
temp_dir,
mock_storage,
mock_job_with_url,
job_manager_instance=mock_job_manager
)
# Fails loudly with a specific DownloadError rather than returning
# None (which used to surface a generic "Failed to download audio file").
with pytest.raises(DownloadError, match="flacfetch service"):
await download_audio(
"test123",
temp_dir,
mock_storage,
mock_job_with_url,
job_manager_instance=mock_job_manager
)
# Refuses to download locally → returns None, never touches storage
assert result is None
# Refuses to download locally → never touches storage
mock_storage.download_file.assert_not_called()
@pytest.mark.asyncio
async def test_download_audio_no_source_raises(self, mock_job_manager, mock_storage):
"""A job with no GCS path, no file_urls and no URL must fail loudly."""
from backend.workers.audio_worker import download_audio
from backend.services.audio_search_service import DownloadError
no_source_job = Job(
job_id="test123",
status=JobStatus.PROCESSING,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
artist="Test Artist",
title="Test Song",
)
with tempfile.TemporaryDirectory() as temp_dir:
with pytest.raises(DownloadError, match="No input audio source"):
await download_audio(
"test123", temp_dir, mock_storage, no_source_job,
job_manager_instance=mock_job_manager,
)
mock_storage.download_file.assert_not_called()
@pytest.mark.asyncio
+22
View File
@@ -176,3 +176,25 @@ class TestWorkerFileOperations:
result = await download_audio("test123", temp_dir, mock_storage, mock_job, mock_job_manager)
mock_storage.download_file.assert_called()
@pytest.mark.asyncio
async def test_lyrics_download_audio_no_source_raises(self):
"""Lyrics worker download_audio must fail loudly when there's no source."""
from backend.workers.lyrics_worker import download_audio
from backend.services.audio_search_service import DownloadError
mock_storage = MagicMock()
mock_job_manager = MagicMock()
mock_job = Job(
job_id="test123",
status=JobStatus.TRANSCRIBING,
created_at=datetime.now(UTC),
updated_at=datetime.now(UTC),
# No input_media_gcs_path and no url → nothing to download
)
mock_job_manager.get_job.return_value = mock_job
with tempfile.TemporaryDirectory() as temp_dir:
with pytest.raises(DownloadError, match="No input audio available"):
await download_audio("test123", temp_dir, mock_storage, mock_job, mock_job_manager)
mock_storage.download_file.assert_not_called()
+1
View File
@@ -14,6 +14,7 @@
"authError": "Authentication error: no user identity available",
"noDefaultTheme": "No default theme configured. Please contact support or specify a theme_id.",
"notFound": "Job not found",
"fileNoLongerAvailable": "File no longer available",
"noPermissionAccess": "You don't have permission to access this job",
"noPermissionEdit": "You don't have permission to edit this job",
"noPermissionDelete": "You don't have permission to delete this job",
+2 -1
View File
@@ -47,7 +47,8 @@
"invalidInstrumentalSelection": "instrumental_selection غير صالح. يجب أن يكون واحدًا من: {valid_selections}",
"instrumentalSelected": "تم تحديد المسار الموسيقي. بدأ إنشاء الفيديو.",
"instrumentalSelectionError": "خطأ في تحديد المسار الموسيقي للمهمة {job_id}: {error}",
"downloadUrlsError": "خطأ في الحصول على روابط التنزيل: {error}"
"downloadUrlsError": "خطأ في الحصول على روابط التنزيل: {error}",
"fileNoLongerAvailable": "الملف لم يعد متاحاً"
},
"review": {
"jobNotFound": "المهمة غير موجودة",
+2 -1
View File
@@ -47,7 +47,8 @@
"invalidInstrumentalSelection": "instrumental_selection no vàlid. Ha de ser un de: {valid_selections}",
"instrumentalSelected": "Pista instrumental seleccionada. S'ha iniciat la generació del vídeo.",
"instrumentalSelectionError": "Error en seleccionar la pista instrumental per a la tasca {job_id}: {error}",
"downloadUrlsError": "Error en obtenir els URL de descàrrega: {error}"
"downloadUrlsError": "Error en obtenir els URL de descàrrega: {error}",
"fileNoLongerAvailable": "El fitxer ja no està disponible"
},
"review": {
"jobNotFound": "Tasca no trobada",
+2 -1
View File
@@ -47,7 +47,8 @@
"invalidInstrumentalSelection": "Neplatné instrumental_selection. Musí být jedno z: {valid_selections}",
"instrumentalSelected": "Instrumentál vybrán. Začalo generování videa.",
"instrumentalSelectionError": "Chyba při výběru instrumentálu pro úlohu {job_id}: {error}",
"downloadUrlsError": "Chyba při získávání adres URL ke stažení: {error}"
"downloadUrlsError": "Chyba při získávání adres URL ke stažení: {error}",
"fileNoLongerAvailable": "Soubor již není dostupný"
},
"review": {
"jobNotFound": "Úloha nebyla nalezena",
+2 -1
View File
@@ -47,7 +47,8 @@
"invalidInstrumentalSelection": "Ugyldig instrumental_selection. Skal være en af: {valid_selections}",
"instrumentalSelected": "Instrumental valgt. Videogenerering er startet.",
"instrumentalSelectionError": "Fejl ved valg af instrumental for job {job_id}: {error}",
"downloadUrlsError": "Fejl ved hentning af download-URL'er: {error}"
"downloadUrlsError": "Fejl ved hentning af download-URL'er: {error}",
"fileNoLongerAvailable": "Filen er ikke længere tilgængelig"
},
"review": {
"jobNotFound": "Jobbet blev ikke fundet",
+2 -1
View File
@@ -47,7 +47,8 @@
"invalidInstrumentalSelection": "Ungültige instrumental_selection. Muss eines der folgenden sein: {valid_selections}",
"instrumentalSelected": "Instrumental ausgewählt. Video-Generierung gestartet.",
"instrumentalSelectionError": "Fehler bei der Auswahl des Instrumentals für Auftrag {job_id}: {error}",
"downloadUrlsError": "Fehler beim Abrufen der Download-URLs: {error}"
"downloadUrlsError": "Fehler beim Abrufen der Download-URLs: {error}",
"fileNoLongerAvailable": "Datei nicht mehr verfügbar"
},
"review": {
"jobNotFound": "Auftrag nicht gefunden",
+2 -1
View File
@@ -47,7 +47,8 @@
"invalidInstrumentalSelection": "Μη έγκυρο instrumental_selection. Πρέπει να είναι ένα από τα: {valid_selections}",
"instrumentalSelected": "Το instrumental επιλέχθηκε. Ξεκίνησε η δημιουργία βίντεο.",
"instrumentalSelectionError": "Σφάλμα κατά την επιλογή instrumental για την εργασία {job_id}: {error}",
"downloadUrlsError": "Σφάλμα κατά τη λήψη των URL λήψης: {error}"
"downloadUrlsError": "Σφάλμα κατά τη λήψη των URL λήψης: {error}",
"fileNoLongerAvailable": "Το αρχείο δεν είναι πλέον διαθέσιμο"
},
"review": {
"jobNotFound": "Η εργασία δεν βρέθηκε",
+1
View File
@@ -14,6 +14,7 @@
"authError": "Authentication error: no user identity available",
"noDefaultTheme": "No default theme configured. Please contact support or specify a theme_id.",
"notFound": "Job not found",
"fileNoLongerAvailable": "File no longer available",
"noPermissionAccess": "You don't have permission to access this job",
"noPermissionEdit": "You don't have permission to edit this job",
"noPermissionDelete": "You don't have permission to delete this job",
+2 -1
View File
@@ -47,7 +47,8 @@
"invalidInstrumentalSelection": "instrumental_selection inválido. Debe ser uno de: {valid_selections}",
"instrumentalSelected": "Instrumental seleccionado. Generación de video iniciada.",
"instrumentalSelectionError": "Error al seleccionar el instrumental para el trabajo {job_id}: {error}",
"downloadUrlsError": "Error al obtener las URLs de descarga: {error}"
"downloadUrlsError": "Error al obtener las URLs de descarga: {error}",
"fileNoLongerAvailable": "El archivo ya no está disponible"
},
"review": {
"jobNotFound": "Trabajo no encontrado",
+2 -1
View File
@@ -47,7 +47,8 @@
"invalidInstrumentalSelection": "Virheellinen instrumental_selection. Täytyy olla jokin näistä: {valid_selections}",
"instrumentalSelected": "Instrumentaali valittu. Videon luonti aloitettu.",
"instrumentalSelectionError": "Virhe valittaessa instrumentaalia työlle {job_id}: {error}",
"downloadUrlsError": "Virhe haettaessa latausosoitteita: {error}"
"downloadUrlsError": "Virhe haettaessa latausosoitteita: {error}",
"fileNoLongerAvailable": "Tiedosto ei ole enää saatavilla"
},
"review": {
"jobNotFound": "Työtä ei löytynyt",
+2 -1
View File
@@ -47,7 +47,8 @@
"invalidInstrumentalSelection": "instrumental_selection invalide. Doit être l'un de : {valid_selections}",
"instrumentalSelected": "Instrumental sélectionné. La génération de la vidéo a commencé.",
"instrumentalSelectionError": "Erreur lors de la sélection de l'instrumental pour la tâche {job_id} : {error}",
"downloadUrlsError": "Erreur lors de l'obtention des URL de téléchargement : {error}"
"downloadUrlsError": "Erreur lors de l'obtention des URL de téléchargement : {error}",
"fileNoLongerAvailable": "Le fichier n'est plus disponible"
},
"review": {
"jobNotFound": "Tâche introuvable",
+2 -1
View File
@@ -47,7 +47,8 @@
"invalidInstrumentalSelection": "בחירת instrumental_selection לא חוקית. חייב להיות אחד מ: {valid_selections}",
"instrumentalSelected": "הפלייבק נבחר. יצירת הווידאו התחילה.",
"instrumentalSelectionError": "שגיאה בבחירת פלייבק עבור המשימה {job_id}: {error}",
"downloadUrlsError": "שגיאה בקבלת כתובות ההורדה: {error}"
"downloadUrlsError": "שגיאה בקבלת כתובות ההורדה: {error}",
"fileNoLongerAvailable": "הקובץ אינו זמין יותר"
},
"review": {
"jobNotFound": "המשימה לא נמצאה",
+2 -1
View File
@@ -47,7 +47,8 @@
"invalidInstrumentalSelection": "अमान्य instrumental_selection। इनमें से एक होना चाहिए: {valid_selections}",
"instrumentalSelected": "इंस्ट्रुमेंटल चुना गया। वीडियो जनरेशन शुरू हो गया है।",
"instrumentalSelectionError": "जॉब {job_id} के लिए इंस्ट्रुमेंटल चुनने में त्रुटि: {error}",
"downloadUrlsError": "डाउनलोड URLs प्राप्त करने में त्रुटि: {error}"
"downloadUrlsError": "डाउनलोड URLs प्राप्त करने में त्रुटि: {error}",
"fileNoLongerAvailable": "फ़ाइल अब उपलब्ध नहीं है"
},
"review": {
"jobNotFound": "जॉब नहीं मिली",
+2 -1
View File
@@ -47,7 +47,8 @@
"invalidInstrumentalSelection": "Nevažeći instrumental_selection. Mora biti jedno od: {valid_selections}",
"instrumentalSelected": "Instrumental je odabran. Generiranje videa je započelo.",
"instrumentalSelectionError": "Pogreška pri odabiru instrumentala za zadatak {job_id}: {error}",
"downloadUrlsError": "Pogreška pri dohvaćanju URL-ova za preuzimanje: {error}"
"downloadUrlsError": "Pogreška pri dohvaćanju URL-ova za preuzimanje: {error}",
"fileNoLongerAvailable": "Datoteka više nije dostupna"
},
"review": {
"jobNotFound": "Zadatak nije pronađen",
+2 -1
View File
@@ -47,7 +47,8 @@
"invalidInstrumentalSelection": "Érvénytelen instrumental_selection. A következők egyike kell legyen: {valid_selections}",
"instrumentalSelected": "Instrumentális sáv kiválasztva. A videó generálása megkezdődött.",
"instrumentalSelectionError": "Hiba a(z) {job_id} feladat instrumentális sávjának kiválasztásakor: {error}",
"downloadUrlsError": "Hiba a letöltési URL-ek lekérésekor: {error}"
"downloadUrlsError": "Hiba a letöltési URL-ek lekérésekor: {error}",
"fileNoLongerAvailable": "A fájl már nem elérhető"
},
"review": {
"jobNotFound": "A feladat nem található",
+2 -1
View File
@@ -47,7 +47,8 @@
"invalidInstrumentalSelection": "instrumental_selection tidak valid. Harus salah satu dari: {valid_selections}",
"instrumentalSelected": "Instrumental dipilih. Pembuatan video dimulai.",
"instrumentalSelectionError": "Kesalahan saat memilih instrumental untuk tugas {job_id}: {error}",
"downloadUrlsError": "Kesalahan saat mendapatkan URL unduhan: {error}"
"downloadUrlsError": "Kesalahan saat mendapatkan URL unduhan: {error}",
"fileNoLongerAvailable": "File sudah tidak tersedia"
},
"review": {
"jobNotFound": "Tugas tidak ditemukan",
+2 -1
View File
@@ -47,7 +47,8 @@
"invalidInstrumentalSelection": "instrumental_selection non valido. Deve essere uno tra: {valid_selections}",
"instrumentalSelected": "Strumentale selezionata. Generazione del video avviata.",
"instrumentalSelectionError": "Errore durante la selezione della strumentale per il lavoro {job_id}: {error}",
"downloadUrlsError": "Errore durante il recupero degli URL di download: {error}"
"downloadUrlsError": "Errore durante il recupero degli URL di download: {error}",
"fileNoLongerAvailable": "File non più disponibile"
},
"review": {
"jobNotFound": "Lavoro non trovato",
+2 -1
View File
@@ -47,7 +47,8 @@
"invalidInstrumentalSelection": "無効な instrumental_selection です。次のいずれかである必要があります: {valid_selections}",
"instrumentalSelected": "インストゥルメンタルが選択されました。動画の生成を開始しました。",
"instrumentalSelectionError": "ジョブ {job_id} のインストゥルメンタル選択中にエラーが発生しました: {error}",
"downloadUrlsError": "ダウンロードURLの取得中にエラーが発生しました: {error}"
"downloadUrlsError": "ダウンロードURLの取得中にエラーが発生しました: {error}",
"fileNoLongerAvailable": "ファイルはご利用いただけなくなりました"
},
"review": {
"jobNotFound": "ジョブが見つかりません",
+2 -1
View File
@@ -47,7 +47,8 @@
"invalidInstrumentalSelection": "잘못된 instrumental_selection입니다. 다음 중 하나여야 합니다: {valid_selections}",
"instrumentalSelected": "반주가 선택되었습니다. 비디오 생성이 시작되었습니다.",
"instrumentalSelectionError": "작업 {job_id}의 반주 선택 중 오류 발생: {error}",
"downloadUrlsError": "다운로드 URL을 가져오는 중 오류 발생: {error}"
"downloadUrlsError": "다운로드 URL을 가져오는 중 오류 발생: {error}",
"fileNoLongerAvailable": "파일을 더 이상 사용할 수 없습니다"
},
"review": {
"jobNotFound": "작업을 찾을 수 없습니다",
+2 -1
View File
@@ -47,7 +47,8 @@
"invalidInstrumentalSelection": "instrumental_selection tidak sah. Mesti salah satu daripada: {valid_selections}",
"instrumentalSelected": "Instrumental dipilih. Penjanaan video bermula.",
"instrumentalSelectionError": "Ralat memilih instrumental untuk tugasan {job_id}: {error}",
"downloadUrlsError": "Ralat mendapatkan URL muat turun: {error}"
"downloadUrlsError": "Ralat mendapatkan URL muat turun: {error}",
"fileNoLongerAvailable": "Fail tidak lagi tersedia"
},
"review": {
"jobNotFound": "Tugasan tidak dijumpai",
+2 -1
View File
@@ -47,7 +47,8 @@
"invalidInstrumentalSelection": "Ugyldig instrumental_selection. Må være en av: {valid_selections}",
"instrumentalSelected": "Instrumental valgt. Videogenerering startet.",
"instrumentalSelectionError": "Feil ved valg av instrumental for jobb {job_id}: {error}",
"downloadUrlsError": "Feil ved henting av nedlastings-URL-er: {error}"
"downloadUrlsError": "Feil ved henting av nedlastings-URL-er: {error}",
"fileNoLongerAvailable": "Filen er ikke lenger tilgjengelig"
},
"review": {
"jobNotFound": "Jobben ble ikke funnet",
+2 -1
View File
@@ -47,7 +47,8 @@
"invalidInstrumentalSelection": "Ongeldige instrumental_selection. Moet een van de volgende zijn: {valid_selections}",
"instrumentalSelected": "Instrumental geselecteerd. Videogeneratie is gestart.",
"instrumentalSelectionError": "Fout bij het selecteren van instrumental voor taak {job_id}: {error}",
"downloadUrlsError": "Fout bij het ophalen van download-URL's: {error}"
"downloadUrlsError": "Fout bij het ophalen van download-URL's: {error}",
"fileNoLongerAvailable": "Bestand niet meer beschikbaar"
},
"review": {
"jobNotFound": "Taak niet gevonden",
+2 -1
View File
@@ -47,7 +47,8 @@
"invalidInstrumentalSelection": "Nieprawidłowe instrumental_selection. Musi to być jedno z: {valid_selections}",
"instrumentalSelected": "Wybrano podkład. Rozpoczęto generowanie wideo.",
"instrumentalSelectionError": "Błąd podczas wybierania podkładu dla zadania {job_id}: {error}",
"downloadUrlsError": "Błąd podczas pobierania linków: {error}"
"downloadUrlsError": "Błąd podczas pobierania linków: {error}",
"fileNoLongerAvailable": "Plik nie jest już dostępny"
},
"review": {
"jobNotFound": "Nie znaleziono zadania",
+2 -1
View File
@@ -47,7 +47,8 @@
"invalidInstrumentalSelection": "instrumental_selection inválido. Deve ser um de: {valid_selections}",
"instrumentalSelected": "Instrumental selecionado. Geração de vídeo iniciada.",
"instrumentalSelectionError": "Erro ao selecionar instrumental para o job {job_id}: {error}",
"downloadUrlsError": "Erro ao obter URLs de download: {error}"
"downloadUrlsError": "Erro ao obter URLs de download: {error}",
"fileNoLongerAvailable": "O arquivo não está mais disponível"
},
"review": {
"jobNotFound": "Job não encontrado",
+2 -1
View File
@@ -47,7 +47,8 @@
"invalidInstrumentalSelection": "instrumental_selection invalid. Trebuie să fie unul dintre: {valid_selections}",
"instrumentalSelected": "Instrumental selectat. A început generarea videoclipului.",
"instrumentalSelectionError": "Eroare la selectarea instrumentalului pentru jobul {job_id}: {error}",
"downloadUrlsError": "Eroare la obținerea adreselor URL de descărcare: {error}"
"downloadUrlsError": "Eroare la obținerea adreselor URL de descărcare: {error}",
"fileNoLongerAvailable": "Fișierul nu mai este disponibil"
},
"review": {
"jobNotFound": "Jobul nu a fost găsit",
+2 -1
View File
@@ -47,7 +47,8 @@
"invalidInstrumentalSelection": "Недопустимый instrumental_selection. Должно быть одно из: {valid_selections}",
"instrumentalSelected": "Инструментал выбран. Началась генерация видео.",
"instrumentalSelectionError": "Ошибка при выборе инструментала для задачи {job_id}: {error}",
"downloadUrlsError": "Ошибка при получении URL-адресов для скачивания: {error}"
"downloadUrlsError": "Ошибка при получении URL-адресов для скачивания: {error}",
"fileNoLongerAvailable": "Файл больше недоступен"
},
"review": {
"jobNotFound": "Задача не найдена",
+2 -1
View File
@@ -47,7 +47,8 @@
"invalidInstrumentalSelection": "Neplatný výber inštrumentálu. Musí byť jeden z: {valid_selections}",
"instrumentalSelected": "Inštrumentál bol vybraný. Začalo sa generovanie videa.",
"instrumentalSelectionError": "Chyba pri výbere inštrumentálu pre úlohu {job_id}: {error}",
"downloadUrlsError": "Chyba pri získavaní adries URL na stiahnutie: {error}"
"downloadUrlsError": "Chyba pri získavaní adries URL na stiahnutie: {error}",
"fileNoLongerAvailable": "Súbor už nie je dostupný"
},
"review": {
"jobNotFound": "Úloha sa nenašla",
+2 -1
View File
@@ -47,7 +47,8 @@
"invalidInstrumentalSelection": "Ogiltigt instrumental_selection. Måste vara en av: {valid_selections}",
"instrumentalSelected": "Instrumental vald. Videogenereringen har startat.",
"instrumentalSelectionError": "Fel vid val av instrumental för jobb {job_id}: {error}",
"downloadUrlsError": "Fel vid hämtning av nedladdningslänkar: {error}"
"downloadUrlsError": "Fel vid hämtning av nedladdningslänkar: {error}",
"fileNoLongerAvailable": "Filen är inte längre tillgänglig"
},
"review": {
"jobNotFound": "Jobbet hittades inte",
+2 -1
View File
@@ -47,7 +47,8 @@
"invalidInstrumentalSelection": "instrumental_selection ไม่ถูกต้อง ต้องเป็นหนึ่งใน: {valid_selections}",
"instrumentalSelected": "เลือกดนตรีบรรเลงแล้ว กำลังเริ่มสร้างวิดีโอ",
"instrumentalSelectionError": "เกิดข้อผิดพลาดในการเลือกดนตรีบรรเลงสำหรับงาน {job_id}: {error}",
"downloadUrlsError": "เกิดข้อผิดพลาดในการรับ URL สำหรับดาวน์โหลด: {error}"
"downloadUrlsError": "เกิดข้อผิดพลาดในการรับ URL สำหรับดาวน์โหลด: {error}",
"fileNoLongerAvailable": "ไฟล์ไม่พร้อมใช้งานแล้ว"
},
"review": {
"jobNotFound": "ไม่พบงาน",
+2 -1
View File
@@ -47,7 +47,8 @@
"invalidInstrumentalSelection": "Mali ang instrumental_selection. Dapat isa sa: {valid_selections}",
"instrumentalSelected": "Napili na ang instrumental. Nagsimula na ang paggawa ng video.",
"instrumentalSelectionError": "Error sa pagpili ng instrumental para sa job {job_id}: {error}",
"downloadUrlsError": "Error sa pagkuha ng mga download URL: {error}"
"downloadUrlsError": "Error sa pagkuha ng mga download URL: {error}",
"fileNoLongerAvailable": "Hindi na available ang file"
},
"review": {
"jobNotFound": "Hindi nahanap ang job",
+2 -1
View File
@@ -47,7 +47,8 @@
"invalidInstrumentalSelection": "Geçersiz instrumental_selection. Şunlardan biri olmalıdır: {valid_selections}",
"instrumentalSelected": "Enstrümantal seçildi. Video oluşturma başladı.",
"instrumentalSelectionError": "{job_id} işi için enstrümantal seçme hatası: {error}",
"downloadUrlsError": "İndirme URL'lerini alma hatası: {error}"
"downloadUrlsError": "İndirme URL'lerini alma hatası: {error}",
"fileNoLongerAvailable": "Dosya artık mevcut değil"
},
"review": {
"jobNotFound": "İş bulunamadı",
+2 -1
View File
@@ -47,7 +47,8 @@
"invalidInstrumentalSelection": "Недійсний instrumental_selection. Має бути одним із: {valid_selections}",
"instrumentalSelected": "Інструментал вибрано. Розпочато генерацію відео.",
"instrumentalSelectionError": "Помилка вибору інструменталу для завдання {job_id}: {error}",
"downloadUrlsError": "Помилка отримання URL-адрес для завантаження: {error}"
"downloadUrlsError": "Помилка отримання URL-адрес для завантаження: {error}",
"fileNoLongerAvailable": "Файл більше недоступний"
},
"review": {
"jobNotFound": "Завдання не знайдено",
+2 -1
View File
@@ -47,7 +47,8 @@
"invalidInstrumentalSelection": "instrumental_selection không hợp lệ. Phải là một trong: {valid_selections}",
"instrumentalSelected": "Đã chọn nhạc nền. Đã bắt đầu tạo video.",
"instrumentalSelectionError": "Lỗi khi chọn nhạc nền cho công việc {job_id}: {error}",
"downloadUrlsError": "Lỗi khi lấy URL tải xuống: {error}"
"downloadUrlsError": "Lỗi khi lấy URL tải xuống: {error}",
"fileNoLongerAvailable": "Tệp không còn khả dụng"
},
"review": {
"jobNotFound": "Không tìm thấy công việc",
+2 -1
View File
@@ -47,7 +47,8 @@
"invalidInstrumentalSelection": "无效的 instrumental_selection。必须是以下之一:{valid_selections}",
"instrumentalSelected": "已选择伴奏。已开始生成视频。",
"instrumentalSelectionError": "为任务 {job_id} 选择伴奏时出错:{error}",
"downloadUrlsError": "获取下载 URL 时出错:{error}"
"downloadUrlsError": "获取下载 URL 时出错:{error}",
"fileNoLongerAvailable": "文件已不可用"
},
"review": {
"jobNotFound": "未找到任务",
+33 -9
View File
@@ -24,6 +24,7 @@ from typing import Optional, Dict, Any
from backend.services.job_manager import JobManager
from backend.services.storage_service import StorageService
from backend.services.audio_search_service import DownloadError
from backend.services.job_health_service import validate_worker_can_run
from backend.config import get_settings
from backend.workers.worker_logging import create_job_logger, setup_job_logging, job_logging_context
@@ -213,9 +214,9 @@ async def process_audio_separation(job_id: str) -> bool:
# Download audio file from GCS or URL
with job_span("download-audio", job_id) as download_span:
job_log.info("Downloading audio file...")
# download_audio raises DownloadError with a specific reason
# on failure (no silent None → generic-error fallback).
audio_path = await download_audio(job_id, temp_dir, storage, job, job_manager_instance=job_manager)
if not audio_path:
raise Exception("Failed to download audio file")
job_log.info(f"Audio downloaded: {os.path.basename(audio_path)}")
download_span.set_attribute("audio_file", os.path.basename(audio_path))
download_span.set_attribute("source", "url" if job.url else "gcs")
@@ -363,6 +364,16 @@ async def process_audio_separation(job_id: str) -> bool:
logger.info(f"[job:{job_id}] WORKER_END worker=audio status=success duration={duration:.1f}s")
return True
except DownloadError as e:
duration = time.time() - start_time
logger.error(f"[job:{job_id}] WORKER_END worker=audio status=error duration={duration:.1f}s error={e}", exc_info=True)
job_manager.mark_job_failed(
job_id=job_id,
error_message=f"Audio download failed: {str(e)}",
error_details={"stage": "download_audio", "error": str(e)}
)
return False
except Exception as e:
duration = time.time() - start_time
logger.error(f"[job:{job_id}] WORKER_END worker=audio status=error duration={duration:.1f}s error={e}", exc_info=True)
@@ -396,7 +407,7 @@ async def download_audio(
storage: StorageService,
job,
job_manager_instance: JobManager = None
) -> Optional[str]:
) -> str:
"""
Fetch the job's audio file from GCS to a local temp directory.
@@ -414,9 +425,14 @@ async def download_audio(
storage: StorageService instance
job: Job object with URL or GCS path
job_manager_instance: Optional JobManager instance for updating job metadata
Returns:
Path to downloaded audio file, or None if failed
Path to the downloaded audio file.
Raises:
DownloadError: with a specific reason if the audio can't be obtained.
We fail loudly with the real cause rather than returning None and
surfacing a generic "Failed to download audio file" to the user.
"""
try:
from karaoke_gen.utils import sanitize_filename
@@ -464,14 +480,22 @@ async def download_audio(
"fetched via the flacfetch service before processing; refusing to "
"download locally."
)
return None
raise DownloadError(
"URL job reached the audio worker without a downloaded input file. "
"URLs must be fetched via the flacfetch service before processing; "
"we never download locally on Cloud Run."
)
logger.error(f"Job {job_id}: No input source found (no GCS path or file_urls)")
return None
raise DownloadError(
"No input audio source found for this job (no GCS path and no file_urls)."
)
except DownloadError:
raise
except Exception as e:
logger.error(f"Job {job_id}: Failed to download audio: {e}", exc_info=True)
return None
raise DownloadError(f"Failed to download audio from storage: {e}") from e
async def upload_separation_results(
+45 -17
View File
@@ -31,6 +31,7 @@ from pathlib import Path
from backend.models.job import JobStatus
from backend.services.job_manager import JobManager
from backend.services.storage_service import StorageService
from backend.services.audio_search_service import DownloadError
from backend.services.job_health_service import validate_worker_can_run
from backend.services.lyrics_cache_service import LyricsCacheService
from backend.workers.worker_logging import create_job_logger, setup_job_logging, job_logging_context
@@ -302,9 +303,9 @@ async def process_lyrics_transcription(job_id: str) -> bool:
# Download audio file from GCS (waits for audio worker if URL job)
with job_span("download-audio", job_id) as download_span:
job_log.info("Downloading audio file from GCS...")
# download_audio raises DownloadError with a specific reason
# on failure (no silent None → generic-error fallback).
audio_path = await download_audio(job_id, temp_dir, storage, job, job_manager)
if not audio_path:
raise Exception("Failed to download audio file")
job_log.info(f"Audio downloaded: {os.path.basename(audio_path)}")
download_span.set_attribute("audio_file", os.path.basename(audio_path))
@@ -552,6 +553,17 @@ async def process_lyrics_transcription(job_id: str) -> bool:
logger.info(f"[job:{job_id}] WORKER_END worker=lyrics status=success duration={duration:.1f}s")
return True
except DownloadError as e:
duration = time.time() - start_time
job_log.error(f"Audio download failed: {str(e)}", exc_info=True)
logger.error(f"[job:{job_id}] WORKER_END worker=lyrics status=error duration={duration:.1f}s error={e}")
job_manager.mark_job_failed(
job_id=job_id,
error_message=f"Audio download failed: {str(e)}",
error_details={"stage": "download_audio", "error": str(e)}
)
return False
except Exception as e:
duration = time.time() - start_time
job_log.error(f"Lyrics transcription failed: {str(e)}", exc_info=True)
@@ -587,13 +599,14 @@ async def download_audio(
job,
job_manager: JobManager,
max_wait_seconds: int = 300
) -> Optional[str]:
) -> str:
"""
Download audio file from GCS to local temp directory.
For URL jobs, the audio worker downloads from YouTube first and uploads to GCS.
We wait for the input_media_gcs_path to be set by the audio worker.
For URL jobs, the audio worker fetches the source via the flacfetch service
first and uploads it to GCS. We wait for the input_media_gcs_path to be set
by the audio worker.
Args:
job_id: Job ID
temp_dir: Temporary directory for download
@@ -601,9 +614,14 @@ async def download_audio(
job: Job object
job_manager: JobManager instance
max_wait_seconds: Maximum time to wait for audio worker to download
Returns:
Path to downloaded audio file, or None if failed
Path to the downloaded audio file.
Raises:
DownloadError: with a specific reason if the audio can't be obtained
(fail loudly with the real cause instead of returning None and
surfacing a generic "Failed to download audio file").
"""
import time
@@ -636,20 +654,30 @@ async def download_audio(
# Check if audio worker failed
if updated_job and updated_job.status == JobStatus.FAILED:
logger.error(f"Job {job_id}: Audio worker failed, cannot proceed with lyrics")
return None
raise DownloadError(
"Audio worker failed before lyrics could run; cannot "
"proceed without the downloaded/separated audio."
)
# Wait before next poll - use asyncio.sleep to not block event loop
await asyncio.sleep(poll_interval)
logger.error(f"Job {job_id}: Timed out waiting for audio download (waited {max_wait_seconds}s)")
return None
raise DownloadError(
f"Timed out after {max_wait_seconds}s waiting for the audio worker "
"to download the input audio."
)
logger.error(f"Job {job_id}: No input_media_gcs_path found and no URL")
return None
raise DownloadError(
"No input audio available (no input_media_gcs_path and no URL)."
)
except DownloadError:
raise
except Exception as e:
logger.error(f"Job {job_id}: Failed to download audio: {e}", exc_info=True)
return None
raise DownloadError(f"Failed to download audio for lyrics: {e}") from e
async def upload_lyrics_results(
+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)
+65 -8
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
@@ -128,7 +128,10 @@ async def _encode_via_gce(
"base_name": base_name,
"instrumental_selection": instrumental_selection,
"existing_instrumental": existing_instrumental,
"ffmpeg_threads": 8, # c4-standard-8 has 8 vCPUs
# NOTE: intentionally no "ffmpeg_threads" — finalization ffmpeg commands in
# LocalEncodingService carry no -threads flag, so x264 uses its all-core auto
# default (measured ~66-78% of a 32-vCPU worker busy during the heavy libx264
# stages — not capped). See docs/archive/2026-08-16-finalization-cpu-efficiency-handoff.md.
}
job_log.info(f"Submitting encoding job to GCE worker")
@@ -150,12 +153,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 +372,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
@@ -494,6 +505,7 @@ async def redistribute_video(job_id: str) -> bool:
return False
temp_dir = tempfile.mkdtemp(prefix=f"karaoke_redist_{job_id}_")
orchestrator = None
try:
# Download existing finals from GCS by listing the finals folder
@@ -563,6 +575,10 @@ async def redistribute_video(job_id: str) -> bool:
gdrive_folder_id=dist.gdrive_folder_id,
enable_cdg=getattr(job, 'enable_cdg', False),
enable_txt=getattr(job, 'enable_txt', False),
# Redistributing an already-`complete` job: progress updates must not
# attempt status transitions (complete -> packaging is illegal and
# would abort the redistribution).
redistribute_mode=True,
)
orchestrator = VideoWorkerOrchestrator(
@@ -593,6 +609,24 @@ async def redistribute_video(job_id: str) -> bool:
await orchestrator._run_distribution()
await orchestrator._run_notifications()
# Verify the redistribution actually produced the archive before reporting
# success. The orchestrator swallows brand-code and Dropbox failures as
# non-fatal warnings, so an apparent "success" can hide a missing archive.
# Reporting success in that case would let the caller (public->private
# visibility change) delete the still-live public outputs against a
# non-existent private archive — the exact data-loss bug this path fixes.
if config.brand_prefix and not orchestrator.result.brand_code:
raise RuntimeError(
"Redistribution produced no brand code — archive identity is missing"
)
if config.dropbox_path:
dropbox_failed = any(
"Dropbox upload failed" in w
for w in (orchestrator.result.distribution_warnings or [])
)
if dropbox_failed:
raise RuntimeError("Redistribution failed to upload the Dropbox archive")
# Update job state_data with new distribution results
state_update = dict(job.state_data or {})
state_update['brand_code'] = orchestrator.result.brand_code
@@ -612,6 +646,27 @@ async def redistribute_video(job_id: str) -> bool:
except Exception as e:
logger.error(f"[job:{job_id}] WORKER_END worker=video-redistribute status=error error={e}")
# A brand code may have been allocated during _run_organization before the
# failure. It was never persisted to the job, so return it to the pool to
# avoid leaking a number (and, for a public->private change, so the caller's
# rollback leaves no orphaned NOMADNP code).
allocated = getattr(getattr(orchestrator, "result", None), "brand_code", None)
if allocated:
try:
from backend.services.brand_code_service import (
BrandCodeService,
get_brand_code_service,
)
prefix, number = BrandCodeService.parse_brand_code(allocated)
get_brand_code_service().recycle_brand_code(prefix, number)
logger.info(
f"[job:{job_id}] Recycled brand code {allocated} after failed redistribution"
)
except Exception as recycle_err:
logger.warning(
f"[job:{job_id}] Failed to recycle brand code {allocated} "
f"after failed redistribution: {recycle_err}"
)
return False
finally:
@@ -1635,6 +1690,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:
+54 -12
View File
@@ -105,6 +105,14 @@ class OrchestratorConfig:
dry_run: bool = False
non_interactive: bool = True
# Redistribution mode: when True, this orchestrator run is redistributing the
# finals of an already-`complete` job (e.g. a public->private visibility change)
# rather than driving a fresh job through its lifecycle. In this mode
# _update_progress must NOT attempt job status transitions — the job is (and
# stays) `complete`, and `complete -> packaging`/`encoding` are illegal
# transitions that would otherwise abort the redistribution.
redistribute_mode: bool = False
@dataclass
class OrchestratorResult:
@@ -126,6 +134,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
@@ -230,14 +242,28 @@ class VideoWorkerOrchestrator:
return self._discord_service
def _update_progress(self, status: JobStatus, progress: int, message: str):
"""Update job progress if job_manager is available."""
if self.job_manager:
self.job_manager.transition_to_state(
job_id=self.config.job_id,
new_status=status,
progress=progress,
message=message
"""Update job progress if job_manager is available.
In redistribute_mode the job is already `complete` and must stay that way,
so we update only the progress percentage/message and skip the (illegal)
status transition. Outside redistribute_mode this drives the normal
lifecycle transition with validation.
"""
if not self.job_manager:
return
if self.config.redistribute_mode:
# Progress-only update; do not transition status (job stays `complete`).
self.job_manager.update_job(
self.config.job_id,
{"progress": progress},
)
return
self.job_manager.transition_to_state(
job_id=self.config.job_id,
new_status=status,
progress=progress,
message=message
)
async def run(self) -> OrchestratorResult:
"""
@@ -487,11 +513,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 +563,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 +609,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)
+110 -2
View File
@@ -14,6 +14,7 @@
| BigQuery (monthly) | S3 `bigquery/musicbrainz/` | Load Parquet files | 30 days |
| BigQuery (Spotify) | S3 `bigquery/spotify/` | Load from Glacier Deep Archive | N/A (static) |
| GCS job files | S3 `gcs/job-files/` | Sync to new bucket | 24h |
| Git repos (code) | S3 `git-repos/{owner}/{repo}.bundle` (+ `manifest.json`) | `git clone <bundle>` then push to a new remote | 24h |
| Secret Manager | S3 `secrets/YYYY-MM-DD.bin` (sealed-box encrypted) | Decrypt with private key from KeepassXC | 24h |
| AWS credentials (function) | GCP Secret Manager `aws-backup-credentials` | Read directly | On-change |
| AWS credentials (offline) | KeepassXC — "Nomad Karaoke — DR backup AWS access" | Manual lookup | On-change |
@@ -24,6 +25,7 @@
- [ ] KeepassXC contains "Nomad Karaoke — DR backup AWS access" (access key, secret key, region, S3 bucket name)
- [ ] KeepassXC contains "Nomad Karaoke — DR backup decryption key" (Curve25519 private key, 64 hex chars)
- [ ] GitHub repo `nomadkaraoke/karaoke-gen` has the secrets `AWS_BACKUP_READONLY_ACCESS_KEY_ID`, `AWS_BACKUP_READONLY_SECRET_ACCESS_KEY`, `DR_MONITOR_DISCORD_WEBHOOK` configured (powers the freshness monitor)
- [ ] GCP Secret Manager `github-backup-token` holds a valid GitHub PAT (`repo` + `read:org`) so the nightly job can bundle every repo — without it the git-repo backup silently skips (see § "Git repo backup setup")
- [ ] You can decrypt yesterday's secrets backup locally (run the drill in § "Quarterly restore drill")
- [ ] Your KeepassXC database itself is backed up off-machine (cloud sync, second device, or printed paper recovery)
@@ -301,6 +303,112 @@ Some external services lock to redirect URIs or treat the old GCP project ID as
- Discord webhook URLs (re-issue if old GCP exposure could have leaked them)
- Cloudflare API tokens (rotate)
## Scenario 3: Loss of GitHub access (account ban / repo takedown)
If the GitHub account is suspended (e.g. an automated copyright false-positive)
or repos are taken down, **the code and its full history are still in S3**. The
nightly backup bundles every repo under `github.com/nomadkaraoke` and
`github.com/beveradb` into a single `git bundle` per repo — a self-contained
file you can clone from directly, no GitHub required. GCP is unaffected, so
production keeps running; this is purely about recovering the source of truth to
a new home.
### What's backed up
- `s3://nomadkaraoke-backup/git-repos/{owner}/{repo}.bundle` — one bundle per
repo, containing **all branches and tags** (entire reachable history).
- `s3://nomadkaraoke-backup/git-repos/manifest.json` — inventory of every repo
at backup time: visibility, default branch, description, size, fork/archived
flags, and per-repo backup status. Use it to know exactly what existed and to
recreate repo settings on the new host.
Forks are excluded by default (recoverable from upstream). Repos are only as
fresh as the last nightly run (24h RPO).
### Restore
```bash
# 1. Set AWS creds (see § "Setting AWS creds locally") and pull the bundles.
aws s3 sync s3://nomadkaraoke-backup/git-repos/ /tmp/git-repos/
# 2. Review the inventory — what existed, and did every repo back up cleanly?
jq '{total, bundled, errors, skipped, repos: [.repos[] | {full_name, status, default_branch, private}]}' \
/tmp/git-repos/manifest.json
# 3. Reconstruct the repo from any bundle. Use --mirror so EVERY branch and tag
# is restored as a real ref — a plain `git clone` keeps non-default branches
# only as remote-tracking refs, and `git push --all` would then omit them.
cd /tmp/git-repos/nomadkaraoke
git clone --mirror karaoke-gen.bundle karaoke-gen.git
cd karaoke-gen.git
git show-ref # every branch + tag is present as a real ref
# 4. Point it at a new remote and push everything (--mirror pushes all refs).
# New home options: a fresh GitHub org/account, GitLab, Codeberg, or a
# self-hosted Gitea. Create the empty repo there first, then:
git remote set-url origin <NEW_REMOTE_URL> # bare mirror already has 'origin'
git push --mirror origin
# (For a normal working clone afterwards: `git clone <NEW_REMOTE_URL>`.)
```
To restore *all* repos in one pass:
```bash
cd /tmp/git-repos
for owner in */; do
for bundle in "$owner"*.bundle; do
name=$(basename "$bundle" .bundle)
# --mirror preserves all branches/tags; `git clone` creates leading dirs.
git clone --mirror "$bundle" "restored/${owner}${name}.git"
# then: cd in, `git remote set-url origin <NEW_URL>`, `git push --mirror origin`
done
done
```
**Verify a bundle without cloning:** `git bundle verify /tmp/git-repos/nomadkaraoke/karaoke-gen.bundle`.
### After restore — repoint tooling
The DR runbook, CI, `poetry`/`pip` VCS deps, and cross-repo scripts reference
`github.com/nomadkaraoke/...` URLs. Once repos live at a new host, update:
- Git remotes in every local clone / worktree
- CI/CD config that clones sibling repos (e.g. `flacfetch` in `karaoke-gen`)
- Any `poetry`/`pip` dependency pinned to a GitHub URL
- Webhooks / deploy keys / Actions secrets on the new host
- `GIT_BACKUP_OWNERS` + the `github-backup-token` PAT so the nightly backup keeps
bundling from the new location
## Git repo backup setup
One-time setup so the nightly job can bundle private repos:
1. Create a GitHub PAT owned by **beveradb** (a member of the `nomadkaraoke` org):
- **Classic PAT:** scopes `repo` (full, to read private repos) + `read:org`
(to enumerate org repos). Simplest.
- **Fine-grained PAT:** resource owner = beveradb *and* a second token for the
nomadkaraoke org (fine-grained tokens are single-owner); grant
`Contents: Read-only` + `Metadata: Read-only`. Classic is easier here.
2. Store it in Secret Manager (value added manually — Pulumi only creates the
empty secret resource):
```bash
printf %s '<PAT>' | gcloud secrets versions add github-backup-token \
--data-file=- --project=nomadkaraoke
```
Also keep a copy in KeepassXC as "Nomad Karaoke — DR GitHub backup PAT".
3. The owners backed up are set by the `GIT_BACKUP_OWNERS` env var on the
`backup-to-aws` function (default `nomadkaraoke,beveradb`), wired in
`infrastructure/modules/backup.py`.
4. Trigger a run and confirm bundles appear:
```bash
curl -X POST -H "Authorization: Bearer $(gcloud auth print-identity-token)" \
https://us-central1-nomadkaraoke.cloudfunctions.net/backup-to-aws
aws s3 ls s3://nomadkaraoke-backup/git-repos/ --recursive | head
```
If the PAT is missing/expired the git-repo step logs a warning and skips; the
freshness monitor then flags `git-repos/` as stale within ~36h.
## Decrypting the secrets backup
```bash
@@ -341,13 +449,13 @@ export AWS_DEFAULT_REGION=us-east-1
## Backup freshness monitor
A GitHub Actions cron (`.github/workflows/dr-backup-freshness.yml`) runs daily at 14:00 UTC and checks that the most recent objects in `s3://nomadkaraoke-backup/firestore/`, `gcs/job-files/`, `secrets/`, and `bigquery/daily-refresh/` are no older than their per-prefix limit. Stale or missing backups → Discord alert + workflow failure.
A GitHub Actions cron (`.github/workflows/dr-backup-freshness.yml`) runs daily at 14:00 UTC and checks that the most recent objects in `s3://nomadkaraoke-backup/firestore/`, `gcs/job-files/`, `secrets/`, `bigquery/daily-refresh/`, and `git-repos/` are no older than their per-prefix limit. Stale or missing backups → Discord alert + workflow failure.
Per-prefix limits reflect each prefix's **S3 (off-site)** cadence, which is not the same as its GCS-staging cadence:
| Prefix | S3 upload cadence | Monitor limit |
|--------|-------------------|---------------|
| `gcs/job-files/`, `secrets/` | nightly | 36h |
| `gcs/job-files/`, `secrets/`, `git-repos/` | nightly | 36h |
| `firestore/`, `bigquery/daily-refresh/` | weekly (Sundays) | 192h (≈8 days) |
Firestore exports to GCS staging nightly (24h local restore point) but only ships to S3 weekly to cut cross-cloud egress (see `backup_to_aws/main.py` → `firestore_to_s3_today`). The monitor only sees the S3 copy, so its Firestore limit must allow a full week — using the 36h nightly figure caused a false "DR backup is stale" alert every Tue–Sat (fixed 2026-06-18).
+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)
+1
View File
@@ -274,3 +274,4 @@ The cloud function does metadata-only checks via the GDrive API (fast, cheap, ca
- **2026-02-28**: Added SendGrid email (primary), kept Pushbullet (fallback). Added post-job trigger from backend. Added `scripts/check_public_share.py` for manual invocation. Motivated by NOMAD-1271 duplicate brand code incident where daily-only checks left a duplicate undetected for ~24 hours.
- **2026-03-02**: NOMAD-1276 incident fix. Post-job trigger now uses 5-minute Cloud Tasks delay instead of immediate invocation, preventing false "all clear" when E2E test files are still in GDrive during cleanup. Also fixed cross-folder gap detection (uses global max across all folders) and added 28 unit tests for the Cloud Function.
- **2026-03-06**: NOMAD-1295 gap. Stale GCE encoding cache (#499) caused job `f4a552bf` to produce bad output on first run (allocated NOMAD-1295, only CDG uploaded). Admin re-triggered the job, which allocated a new brand code (NOMAD-1297) without recycling 1295. Fix: recycled 1295 back to the pool. Updated docs to clarify that new gaps must always be investigated and fixed, never added to KNOWN_GAPS.
- **2026-08-18**: NOMAD-1537 gap. A **public→private visibility change** on job `25d076e5` (`Alma Nocturna – Mejor Cállate`) deleted the public GDrive/YouTube/Dropbox outputs and recycled 1537, then the private redistribution crashed (`redistribute_video` drove an illegal `complete → packaging` transition), so the change failed *after* the public files were already gone — a delete-first, no-rollback flow. The daily validator caught the hole; it self-closed when an unrelated public job reused the recycled 1537. **Going-private is a legitimate cause of a transient gap** (the number is recycled and refilled by the next public track) — the alert is expected and desired, not suppressed. Fixes (v0.196.1): `redistribute_video` runs in `redistribute_mode` (no status transition, stays `complete`); `change_to_private` is now **distribute-then-delete** (public outputs removed only after the private archive succeeds; on failure the job stays fully public); failed redistributions recycle any allocated `NOMADNP` code. Validator intentionally left unchanged.
+243 -2
View File
@@ -6,6 +6,187 @@ Key insights for future AI agents working on this codebase.
---
## Don't Invent Silent Fallbacks — Ask or Fail Loud (Jun 2026)
When the desired behaviour for an edge case is unclear, **do not** invent a quiet
fallback that lets the system keep going while doing the wrong thing. Either ask
the human, or fail loudly with a clear, specific error. Silent fallbacks hide
bugs: the system "works" while producing wrong output, and the real failure
surfaces much later (or never).
**Motivating incident (2026-06-08):** a Facebook-URL job failed with a generic
"Failed to download audio file". A non-YouTube path had silently fallen back to
running yt-dlp *inside the Cloud Run container* (flacfetch was supposed to be the
sole downloader), which then died in a broken `convert_to_wav`. The download had
actually succeeded — the fallback was both unintended and broken. The fix
**deleted** the fallback rather than patching it.
A full audit of the codebase's fallback paths followed — see
`docs/archive/2026-06-09-fallback-audit-plan.md` for the catalogue and the
per-item decisions.
**Rules of thumb:**
- A function that can't produce its result should **raise a specific exception**,
not `return None` and let a caller surface a generic message. (See
`download_audio()` in `backend/workers/audio_worker.py` / `lyrics_worker.py`:
each failure mode now raises `DownloadError` with the real reason.)
- "If X isn't configured, silently do Y instead" is the most dangerous shape —
especially around download, payment, job-state, and worker-triggering. Prefer
failing closed and visibly. (See `YouTubeDownloadService.download` — no
flacfetch → raises, no local yt-dlp.)
- Don't trust a comment that *says* a path is a safe fallback — verify what the
user actually observes when it triggers.
- Comments/docstrings must not lie about fail-open vs fail-closed. The credit
evaluation service is **fail-closed** (`pending_review` on error); its
docstrings used to claim fail-open, which would have tempted a future
maintainer to "fix" the code into a free-credit-abuse hole.
- A safe-but-silent fallback (e.g. empty `ADMIN_TOKENS` → everything 403s) should
still log at ERROR so the error monitor alerts — a quiet warning reads as an
auth bug, not a config error.
Good loud-failure models already in the tree to copy:
`lyrics_transcriber/output/video.py` (raises on a missing background image) and
`backend/services/visibility_change_service.py` (checks the trigger result,
restores state, and raises rather than silently dropping a worker trigger).
---
## 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 +319,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.
@@ -258,7 +441,7 @@ When two sequential human review steps can be combined into one, do it. We origi
3. **`compute.instances.start` returns `503 SERVICE_UNAVAILABLE` for transient backend stress, not just capacity.** Initial fix only classified `ZONE_RESOURCE_POOL_EXHAUSTED` as transient/recoverable; `503` got the generic `EncodingWorkerStartError` and never triggered multi-zone fallback. Either treat the `EncodingWorkerStartError` parent class as fallback-worthy (what we did, PR #750) or expand the capacity error code list.
4. **GCE `c4d-highcpu-32` capacity in `us-central1-f` is unreliable enough to be useless as a fallback.** Provisioning failed there at create time on multiple attempts (the very thing the fallback is meant to mitigate). `-a` and `-b` are stable. (PR #749)
4. **GCE `c4d-highcpu-32` capacity in `us-central1-f` is unreliable enough to be useless as a fallback.** Provisioning failed there at create time on multiple attempts (the very thing the fallback is meant to mitigate). `-a` and `-b` were stable *at the time*. (PR #749) — **Superseded 2026-08-12:** see "Machine-family diversification" below; `-a`/`-b` are NOT immune — the whole `c4d-highcpu-32` family stocked out region-wide (a/b/c at once).
5. **`google-auth ≥ 2.40` uses mTLS-over-HTTPS for the GCE metadata server when `/run/google-mds-mtls/` certs exist on the VM.** Newer GCE images ship those certs; the mTLS handshake then fails with `SSL CERTIFICATE_VERIFY_FAILED` on freshly-provisioned VMs. The worker can't refresh its SA token, all GCS reads/writes break. Fix: set `GCE_METADATA_MTLS_MODE=none` in the systemd EnvironmentFile to force HTTP-on-port-80 metadata access. (PR #750)
@@ -266,8 +449,31 @@ When two sequential human review steps can be combined into one, do it. We origi
7. **`_request_with_retry` captured the URL once before the retry loop.** When the warmup-fallback updated the active URL override (e.g., switching from a dead primary to a live fallback), the retry loop kept hitting the original (dead) URL for all 8 attempts. Fix: thread the relative `path` through and re-resolve `_get_worker_url() + path` on retries after warmup has fired. (PR #752)
### Machine-family diversification (August 2026)
> **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).
**Root lesson:** zone diversity is not enough — a stockout is per **(machine family × region)**, and it can take out *every* zone of a family in a region at once. The fallback fleet must diversify **machine family**, not just zone.
**Fix (Option B):** added `n2-highcpu-32` capacity fallbacks (`encoding-worker-fallback-n2c`/`-n2f` in `us-central1-c`/`-f`) — an independent, much deeper capacity pool. Runtime needed **no change** (`ensure_any_running` already iterates arbitrary `{vm,zone,ip}` candidates; `start_vm(zone=...)` is zone-generic); it's purely `infrastructure/config.py::EncodingWorkerConfig.FALLBACKS` (now carries per-VM `machine_type` + `disk_type`) + `encoding_worker_vm.py` + a new `encoding-worker-fallback-vms` secret version. Gotchas:
- **n2 does not support `hyperdisk-balanced`** → its fallbacks use `pd-balanced` boot disks (per-VM `disk_type`).
- **Keep the existing `-a`/`-b` entries byte-identical** (including the IP `description` string!) — changing even the Address description forces the Address to replace, which cascades to *replacing the c4d VM* (needs the very capacity that's out). Always `pulumi preview` and confirm the diff is purely additive (`+N to create`, no `+-replace` on existing encoding-worker VMs) before `pulumi up`.
- **Preview-timeout is a separate, still-open fragility:** a synchronous preval that outlives the ~100 s edge timeout gives users an opaque 524. Fast-follow options: make preview async/polling (like render), fail fast to local encode when all VM starts stock out, or raise the edge read-timeout for that route.
**Architecture summary (post-fixes):**
- 4 GCE encoding workers: 2 primaries in `us-central1-c` (blue-green) + 2 capacity fallbacks in `us-central1-a` and `us-central1-b`. All idle by default; started on demand.
- 6 GCE encoding workers: 2 primaries in `us-central1-c` (blue-green, `c4d-highcpu-32`) + 2 `c4d` capacity fallbacks in `us-central1-a`/`-b` + 2 `n2-highcpu-32` fallbacks in `us-central1-c`/`-f`. All idle by default; started on demand.
- `EncodingWorkerCandidate` list iterated in `ensure_any_running` — primary first, fallbacks in declared order. Capacity errors fall through to next candidate; non-capacity start errors also fall through (broadened in PR #750).
- New `RENDER_PENDING_CAPACITY` job state for transient infra failures — different from `FAILED` (which is for unrecoverable bugs).
- Cloud Scheduler fires `/api/internal/retry-pending-render-jobs` every 5 min; 24h hard timeout per job.
@@ -819,6 +1025,41 @@ All status transitions after workers complete fail silently because they're inva
- `test_youtube_url_calls_start_job_processing_after_download` - verifies proper sequence
- `TestInvalidStateTransitionError`, `TestValidateStateTransitionRaisesBehavior`, `TestStartJobProcessing` in `test_job_manager.py`
### Made-For-You Order Emails Must Be Isolated From Audio Acquisition (Aug 2026)
**Problem**: Job 17dc6f48 (made_for_you order) failed on a YouTube "confirm you're
not a bot" download error, and the admin never received the "New Made-For-You Order
Received!" email. The error-fallback then crashed with
`'EmailService' object has no attribute 'send_email'`, so even the failure alert was lost.
**Root cause**: In `_handle_made_for_you_order`, both the customer order-confirmation
and the admin notification were sent *after* the fallible audio-acquisition step
(YouTube download / audio search). When acquisition raised, execution jumped straight
to the outer `except`, skipping BOTH emails. Separately, the fallback called
`email_service.send_email(...)` — a method that only existed on the *provider*
(`self.provider.send_email`), never on `EmailService` itself.
**Fix**:
1. Send the customer order-confirmation email **up-front**, right after job creation and
*before* audio acquisition — the order is paid/confirmed regardless of whether the
download or search succeeds. Wrapped so an email error is logged, not fatal.
2. Wrap the admin notification so an email hiccup on a successful order can't fake a
`[FAILED]` alert.
3. Route the outer failure handler through `_send_mfy_failure_alert()` (never raises,
HTML-escapes user input, tolerates `job_id=None`): success → normal admin
notification; acquisition failure → `[FAILED]` admin alert while the customer is
still confirmed.
4. Add a thin `EmailService.send_email()` passthrough to the provider so ad-hoc/plain
emails (like the failure alert) work.
**Why tests didn't catch it**: `email_service` was a `MagicMock` in the handler tests,
so `mock.send_email(...)` auto-created the attribute and never surfaced the real
`AttributeError`. **Pattern**: for critical fallbacks, add at least one test that
exercises the real `EmailService` (only mocking `.provider`), and assert that a failure
in a *later* step (audio) does not suppress *earlier* side effects (the confirmation
email). Idempotency note: mark the Stripe session processed *before* sending the
confirmation so a webhook retry can't double-send.
### Use data-testid for E2E
Prefer `data-testid` over label/text selectors. They're immune to label changes and won't break when similar fields are added.
+4
View File
@@ -55,6 +55,10 @@
## Recent Changes
- **Admin UI/UX Overhaul** (2026-08-22): Made the admin pages usable on mobile and fixed the long-standing overflow problems on the job detail page (v0.197.0). Long status timelines (retried/edited jobs) now collapse to the last 6 stages behind a "+N earlier (M failed)" expander; the Source field no longer bleeds across the info grid (CSS grid `min-w-0`); the Audio Source Details modal got wrap-safe stacked rows plus an "Open in YouTube/Spotify" link built from provider + source ID; Configuration fields are click-to-edit with always-visible pencils. The jobs list search box jumps straight to a job when given a job ID, and the status filter is URL-synced (`/admin/jobs?status=failed`), which the dashboard's now-clickable stat cards and status-breakdown rows link into. Also fixed a real crash: the "Trigger Now" button in the reset-result dialog referenced a deleted handler. Users list/detail, breadcrumbs, and the admin header are all responsive down to phone widths. 4 new e2e tests.
- **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).
+85 -10
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,18 +94,67 @@ 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"
```
---
## Render fails: `No module named '<pkg>'` (e.g. tenacity) on encoding worker
**Symptoms:** A render fails with `OutputGenerator not available: No module named 'tenacity'. The karaoke-gen wheel must be installed. Check that ensure_latest_wheel() succeeded.` (or another missing package). Retries hit the same VM and fail identically.
**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
# Identify the running worker
gcloud compute instances list --project=nomadkaraoke --filter="name~encoding AND status=RUNNING"
# Repair: install the latest versioned wheel WITH deps, then verify
gcloud compute ssh <worker-name> --zone=<zone> --project=nomadkaraoke --tunnel-through-iap --command='
V=$(gsutil ls "gs://karaoke-gen-storage-nomadkaraoke/wheels/karaoke_gen-*.whl" | grep -v current | sort -V | tail -1)
WHEEL="/tmp/$(basename "$V")" # keep the PEP 427 filename so pip accepts it
gsutil cp "$V" "$WHEEL"
sudo /opt/encoding-worker/venv/bin/python -m pip install --upgrade "$WHEEL"
/opt/encoding-worker/venv/bin/python -c "import tenacity; from karaoke_gen.lyrics_transcriber.output.generator import OutputGenerator; from karaoke_gen.lyrics_transcriber.correction.operations import CorrectionOperations; from backend.services.local_encoding_service import LocalEncodingService; print(\"OK\")"
'
```
**Re-render a job that already failed past review:** a failed job is terminal, and admin `/jobs/{id}/reset` has no `review_complete` target. Reset to `awaiting_review`, then re-submit the review (reuses the existing GCS corrections):
```bash
ADMIN_TOKEN=$(gcloud secrets versions access latest --secret=admin-tokens --project=nomadkaraoke | cut -d',' -f1)
curl -s -X POST "https://api.nomadkaraoke.com/api/admin/jobs/<id>/reset" \
-H "X-Admin-Token: $ADMIN_TOKEN" -H "Content-Type: application/json" \
-d '{"target_state": "awaiting_review"}'
# instrumental_selection is "clean" or "with_backing" (read prior value from Firestore state_data before reset)
curl -s -X POST "https://api.nomadkaraoke.com/api/review/<id>/complete?review_token=<token>" \
-H "Content-Type: application/json" -d '{"instrumental_selection": "with_backing"}'
```
Do **not** reset to `instrumental_selected` — that triggers the final video worker, which needs the (missing) lyrics video and fails "prerequisites not met"; and triggering render-video from `instrumental_selected` gets superseded (invalid `instrumental_selected → rendering_video`).
---
## GDrive validator reports sequence gap
**Symptoms:** Email from "Nomad Karaoke GDrive Validator" reporting `SEQUENCE GAPS: MP4: missing XXXX`.
@@ -233,7 +286,11 @@ gcloud compute instances describe encoding-worker-a \
**Symptoms:** Job status is `render_pending_capacity` (introduced 2026-05-05). User-facing message says *"Encoding capacity is temporarily unavailable. Your job will retry automatically — no action needed."* (As of v0.192.3 a mid-render stall can also land here — see "orphaned render" above.)
**Background — what this state means:** GCE returned `ZONE_RESOURCE_POOL_EXHAUSTED` or transient `503 SERVICE_UNAVAILABLE` from `compute.instances.start` on every encoding-worker VM (primary in `us-central1-c`, plus capacity fallbacks in `-a` and `-b`). The render worker parks the job in `RENDER_PENDING_CAPACITY` instead of failing it; Cloud Scheduler retries it every 5 min via `/api/internal/retry-pending-render-jobs`. Hard timeout is 24 hours (then transitions to `failed` with a clear permanent-failure message).
**Background — what this state means:** GCE returned `ZONE_RESOURCE_POOL_EXHAUSTED` or transient `503 SERVICE_UNAVAILABLE` from `compute.instances.start` on every encoding-worker VM. The render worker parks the job in `RENDER_PENDING_CAPACITY` instead of failing it; Cloud Scheduler retries it every 5 min via `/api/internal/retry-pending-render-jobs`. Hard timeout is 24 hours (then transitions to `failed` with a clear permanent-failure message).
The fallback fleet is diversified 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.
**Check how many retries have run:**
```bash
@@ -252,13 +309,31 @@ curl -X POST https://api.nomadkaraoke.com/api/internal/retry-pending-render-jobs
-H "X-Admin-Token: $ADMIN_TOKEN"
```
**Verify GCE has any capacity right now:**
**Verify GCE has any capacity right now** (the real error reason is in the Compute op, not the app's "503"):
```bash
# If this returns ZONE_RESOURCE_POOL_EXHAUSTED across all 4 zones, just wait
for ZONE in us-central1-a us-central1-b us-central1-c us-central1-f; do
gcloud compute instances describe "encoding-worker-fallback-${ZONE##*-}" \
--zone=$ZONE --project=nomadkaraoke --format='value(status)' 2>/dev/null \
&& echo " ↑ in $ZONE"
# See the actual stockout reason (ZONE_RESOURCE_POOL_EXHAUSTED / stockout) + vmType
gcloud logging read 'protoPayload.methodName:"instances.start" AND "ZONE_RESOURCE_POOL_EXHAUSTED"' \
--project=nomadkaraoke --freshness=30m --limit=5 \
--format='value(timestamp, protoPayload.resourceName)'
# Try starting a fallback in each 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" \
"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)"
else
echo "$VM: FAILED — $(echo "$OUT" | tr '\n' ' ')"
fi
done
```
@@ -0,0 +1,237 @@
# Fallback Logic Audit — karaoke-gen (2026-06-09)
**Driver prompt:** `docs/archive/2026-06-08-fallback-logic-audit-prompt.md`
**Motivating incident:** 2026-06-08 Facebook-URL job → generic "Failed to download
audio file". A non-YouTube path silently fell back to running yt-dlp *inside the
Cloud Run container*, which died in a broken `convert_to_wav`. flacfetch was
supposed to be the sole downloader. The fix **deleted** the fallback rather than
patching it. See `docs/archive/2026-06-08-flacfetch-sole-downloader-plan.md` and
memory `project_flacfetch_sole_downloader`.
**Goal of this audit:** make every silent fallback an *explicit, intentional*
decision — fail loudly with a clear error, OR keep + log/alert, OR something
else. Do **not** change behaviour without Andrew's answer. Some fallbacks are
load-bearing graceful degradation and should stay.
**Classification:**
- **A** = legitimate graceful degradation (intended, fails safe + visible). Keep.
- **B** = silent fallback masking a bug/misconfig (like the yt-dlp case). Delete or fail-fast.
- **C** = ambiguous — needs Andrew's intent.
**Method:** 5 parallel read-only triage agents over (1) audio/lyrics acquisition,
(2) job-state & worker triggering, (3) payment/credits/referral/auth, (4)
karaoke_gen core render, (5) backend routes/services/config. Findings below are
verified against actual behaviour, not comments.
> **DECISION fields capture Andrew's answers verbatim** (interview held 2026-06-09).
---
## THEME 1 — Source downgrade: flacfetch → YouTube-only (the motivating class)
These reconstruct the exact "silently use a worse source" pattern that caused the
incident. flacfetch is supposed to be the sole/lossless downloader.
| # | file:line | Class | What happens when it triggers |
|---|-----------|-------|-------------------------------|
| 1.1 | `backend/services/audio_search_service.py:224-230` | **B** | Remote flacfetch search error → silently re-runs **local** flacfetch (YouTube-only on Cloud Run). Transient remote outage silently downgrades a RED/OPS lossless job to a YouTube rip; user sees only a `logger.warning`. |
| 1.2 | `karaoke_gen/audio_fetcher.py:405-433` | **B** | If `TorrentDownloader` import fails / Transmission down / tracker `*_API_URL` unset → RED/OPS skipped, only `YoutubeProvider` registered. The concrete mechanism behind 1.1. |
| 1.3 | `karaoke_gen/audio_fetcher.py:1818-1823` | **C** | If exactly one of `FLACFETCH_API_URL` / `FLACFETCH_API_KEY` is set → logs "falling back to local mode". A typo'd secret silently disables the remote service. |
| 1.4 | `karaoke_gen/audio_fetcher.py:558-577` | **C** | `select_best` returns result[0] on any ranking failure → may silently auto-pick a lower-quality source. |
**DECISION (Theme 1):** Andrew — **"Fail loudly, no YouTube fallback."** flacfetch
is the sole/lossless downloader; if it can't serve (remote error, RED/OPS
unavailable, half-configured), fail the job with a clear error rather than
silently ripping YouTube. Applies to 1.1–1.4.
---
## THEME 2 — Silent worker-trigger drops → jobs stall forever
A recurring pattern: a downstream worker is triggered fire-and-forget and the
boolean/return is discarded. If the enqueue fails, the job sits in an intermediate
state with **no error and nothing to recover it**. The user is often told "success".
| # | file:line | Class | What happens when it triggers |
|---|-----------|-------|-------------------------------|
| 2.1 | `backend/services/job_manager.py:1126-1137` | **B** | `_trigger_screens_worker` catches `RuntimeError` (no event loop) and just logs `# TODO: use message queue`. Called from `mark_lyrics_complete` in the **lyrics_worker Cloud Run Job** (sync). If it no-ops, `lyrics_complete=True` is written but screens worker never fires → job stalls before AWAITING_REVIEW; `recover_stuck_jobs` doesn't cover this. *(Verify: does a loop exist in that Job?)* |
| 2.2 | `backend/api/routes/review.py:504` | **B** | After REVIEW_COMPLETE, `asyncio.create_task(trigger_render_video_worker)` result discarded; endpoint returns `{"status":"success"}`. Failed enqueue → stuck at REVIEW_COMPLETE, no error, no auto-recovery. |
| 2.3 | `backend/workers/render_video_worker.py:281,546` | **B** | `await trigger_video_worker(job_id)` bool ignored. Failed trigger → job stuck at INSTRUMENTAL_SELECTED with render done but final encode never started. |
| 2.4 | `backend/api/routes/internal.py:725-728` | **C** | Retry scheduler resets parked job to REVIEW_COMPLETE then triggers; on raise the comment assumes it'll be re-picked as RENDER_PENDING_CAPACITY, but the next tick queries `status==RENDER_PENDING_CAPACITY` and won't see it. Escapes both retry query and 24h timeout sweep → stuck indefinitely. |
| 2.5 | `backend/services/encoding_service.py:1018-1020` | **B** | `get_encoding_service()` does `try: set_worker_manager(manager) except Exception: pass`. Any client-init failure → service silently runs with **no worker manager**, falls back to static URL, loses multi-zone capacity failover, no signal. |
| 2.6 | `audio_download_worker.py:291-294`, `job_manager.py:1078-1081`, `jobs.py:70-71`, `review.py:2208-2209` | **B** | `asyncio.gather(trigger_audio, trigger_lyrics)` results discarded across these sites. One failed enqueue → that pipeline branch silently never starts while the other proceeds; job hangs. |
**Model to emulate:** `backend/services/visibility_change_service.py:194-205` does it
right — checks `triggered`, logs error, restores state, raises.
**DECISION (Theme 2):** Andrew — **"Fail loud / re-park & retry."** Check every
trigger result; on failure mark the job failed or re-queue (the
`visibility_change_service` pattern) so a job can never silently stall. Applies
to 2.1–2.6. _(Still verify reachability of 2.1's no-event-loop path during impl,
but the directional call is fail-loud/retry.)_
---
## THEME 3 — Lyrics/transcription silently degraded or missing
| # | file:line | Class | What happens when it triggers |
|---|-----------|-------|-------------------------------|
| 3.1 | `karaoke_gen/lyrics_transcriber/core/controller.py:487-491` | **B** | If every transcriber returns empty (no exception, e.g. AudioShake 200 with no words), code logs a warning and proceeds; `process()` skips output but job is still reported "completed successfully". → karaoke video with **no synced lyrics**, no error. |
| 3.2 | `karaoke_gen/lyrics_processor.py:372-373` + `core/config.py:16` | **B/C** | `enable_local_whisper=True` hardcoded as priority-3 fallback. On a host with `whisper_timestamped` installed, AudioShake failure silently yields much lower-quality Whisper timing with no signal. (No-op on Cloud Run where pkg absent — env-dependent.) |
| 3.3 | `core/controller.py:396-398` | **C** | Failure loading existing corrections JSON is swallowed → silently re-transcribes from scratch, discarding prior **human review** work. |
| 3.4 | `core/controller.py:442-454` | **C** | Per-provider reference-lyric fetch errors (Genius/Spotify/LRCLIB/Musixmatch) swallowed; all-fail → "No lyrics found", correction runs transcription-only (lower accuracy). Masks systemic outages (e.g. expired Spotify cookie). |
**DECISION (Theme 3):** Andrew — **"Fail the job loudly."** No transcription
results = fail with a clear error; lyrics are the core deliverable and a
lyric-less "success" must never ship. Treat 3.1 as a hard fail. _(Apply the same
fail-loud principle to 3.2–3.4 during impl — silent low-quality Whisper and
silently discarding human-review corrections both violate the principle; flag if
any needs a different call.)_
---
## THEME 4 — Wrong font / asset / color on a paid deliverable
Silent substitution of a missing branded asset → a wrong-looking video/CDG the
customer paid for. Note the karaoke-render path at
`lyrics_transcriber/output/video.py:43-44` already **raises** on a missing
background — a good loud-failure model the others diverge from.
| # | file:line | Class | What happens when it triggers |
|---|-----------|-------|-------------------------------|
| 4.1 | `lyrics_transcriber/output/video.py:417-423` | **B** | Final karaoke MP4: if theme font file missing, `:fontsdir` is silently dropped → libass resolves via system fontconfig → whole song in a substitute font, no log above debug. |
| 4.2 | `video_generator.py:120-132,153,174,191` | **B** | Title/end screens: missing font → `ImageFont.load_default()` (~10px bitmap). 4K title/end card renders artist/title in a near-invisible default font. |
| 4.3 | `video_generator.py:368-377` | **B/C** | Title/end screen: missing `background_image` → silently uses flat `background_color` (karaoke path raises instead — inconsistent). |
| 4.4 | `lyrics_transcriber/output/cdg.py:294-306` | **B/C** | CDG: unresolved theme font → bundled `arial.ttf` (warning only). Hardware disc renders all lyrics in Arial. |
| 4.5 | `karaoke_finalise.py:1132-1159` | **B/C** | Duet job: missing/malformed `duet_corrections_json` → renders CDG via LRC path = **solo colors**, loses singer-color distinction (warning only). |
| 4.6 | `lyrics_transcriber/output/cdg.py:551-561` | **B/C** | Duet CDG: lost/length-mismatched line→singer map → defaults every line to singer 1 "to keep the file valid". Silently wrong color attribution. |
| 4.7 | `lyrics_transcriber/output/ass/config.py:115-117,149-151` | **B/C** | Malformed theme color → hardcoded default blue/black. A typo'd theme color renders lyrics in the wrong brand color. |
| 4.8 | `lyrics_transcriber/output/ass/lyrics_line.py:39-45` | **B/C** | Text-measurement font → `load_default()` (different metrics) while libass renders a different font → line-wrap decisions desync from the actual video. Pairs with 4.1. |
**A (keep, verified intended + logged):** GPU→CPU encode fallback
(`karaoke_finalise.py:1803-1881`, visually equivalent libx264, warned);
`style_loader.py:164-192` documented default duet palette;
`subtitles.py:100-107` audio-duration estimate (logged).
**DECISION (Theme 4):** Andrew — **"Fail loudly on missing branded asset."** Match
`video.py:43-44` which already raises. A paid deliverable shouldn't silently
substitute fonts/backgrounds/colors — fail with a clear error so it's caught
before delivery. Applies to 4.1–4.8. _(Keep the confirmed-A items: GPU→CPU
encode, documented duet palette, audio-duration estimate.)_
---
## THEME 5 — Pricing undercharge / ceiling bypass
| # | file:line | Class | What happens when it triggers |
|---|-----------|-------|-------------------------------|
| 5.1 | `backend/api/routes/jobs.py:128-134` + `services/pricing.py:13-22` | **B** | Client-supplied `duration_seconds`; if `None`, `duration_to_credits(None)=1` and `is_blocked(None)=False`. Omitting duration → any-length job for 1 credit **and** skips the 60-min hard ceiling. `acknowledged_credits` guard only fires if client *sends* a mismatch. |
| 5.2 | `backend/api/routes/jobs.py:2446-2466` (`create_job_from_search`) | **B** | Guided/search flow never passes `credits=` → always `JobCreate.credits=1` regardless of length. Inconsistent with URL path; long-input undercharge. |
| 5.3 | `backend/api/routes/users.py:97` | **B** | Referral discount: `except Exception: discount_percent = 10` on Firestore read failure. A 20% link charged at 10% on a transient error. |
**DECISION (Theme 5):** Andrew — **"Keep defaults but always enforce ceiling +
alert."** Keep the 1-credit default, but the 60-min hard ceiling must always be
enforced (never silently bypassed when duration is omitted), and any
undercharge / discount-guess must raise a Discord alert so it's visible.
_Impl note:_ when duration is unknown we still alert + apply the ceiling rather
than reject; charge-by-duration consistency between URL and search flows to be
handled under this (alert if they diverge). Applies to 5.1–5.3.
---
## THEME 6 — Lost paid orders / "Unknown" customer data
| # | file:line | Class | What happens when it triggers |
|---|-----------|-------|-------------------------------|
| 6.1 | `backend/api/routes/users.py:1105-1135` (`_handle_made_for_you_order`) | **B** | Broad `except Exception` swallows fulfilment failure *after Stripe charged*; emails admin "[FAILED]" but does **not** re-raise → webhook returns 200 (no Stripe retry). If the email also fails (line 1134 logs only), a paid $50 order silently vanishes. |
| 6.2 | `backend/api/routes/users.py:858-859` | **B** | Made-for-you order: `metadata.get("artist","Unknown Artist")`/`("title","Unknown Title")` → a paid video titled "Unknown Artist - Unknown Title" instead of rejecting the order. |
**DECISION (Theme 6):** Andrew — **"Re-raise + durable failed-order record."** On
made-for-you fulfilment failure, re-raise so Stripe retries AND/OR write a
durable `needs_manual_fulfilment` record (don't rely on an email an admin might
miss); reject orders missing artist/title rather than shipping "Unknown Artist -
Unknown Title". Applies to 6.1–6.2.
---
## THEME 7 — Env-var / config defaults masking prod misconfiguration
A single unset/rotated env var silently produces wrong behaviour with only a
warning. Env vars are set in Cloud Run today, but the defaults are landmines.
| # | file:line | Class | What happens when it triggers |
|---|-----------|-------|-------------------------------|
| 7.1 | `backend/services/dropbox_service.py:34` | **B** | `GOOGLE_CLOUD_PROJECT` default `"karaoke-gen"` (real project is `nomadkaraoke`). If unset → secret lookup targets a non-existent project; bare `except` swallows → Dropbox distribution silently disabled. |
| 7.2 | `backend/config.py:19-21` | **B** | GCS bucket defaults `karaoke-gen-storage[/-temp/-outputs]` ≠ real `karaoke-gen-storage-nomadkaraoke`. If `GCS_BUCKET_NAME` unset → reads/writes a non-existent bucket, runtime 500s deep in processing instead of boot failure. |
| 7.3 | `backend/services/worker_service.py:160-166` | **B** | If `CLOUD_RUN_SERVICE_URL` unset → worker base URL = `http://localhost:{PORT}` with no env guard. Workers invoked against localhost → jobs created but silently never run. |
| 7.4 | `backend/middleware/tenant.py:30-31,102-105` | **B (security)** | `IS_PRODUCTION` from `ENV/ENVIRONMENT=="production"`, but app default is `"development"`. If prod doesn't explicitly set it → `?tenant=<id>` query override active → **tenant spoofing** (impersonate white-label portal). *(Verify prod sets ENVIRONMENT=production.)* |
| 7.5 | `backend/services/email_service.py:230-245` | **B** | No `POSTMARK_SERVER_TOKEN` → silent `ConsoleEmailProvider`; all sends "succeed". In prod with token unset/rotated, magic-link/completion/receipt emails silently vanish → users can't log in or get downloads. |
**DECISION (Theme 7):** Andrew — **"Fail-fast at startup in prod."** When
`ENVIRONMENT=production`, require these vars and refuse to boot (or go
health-check red) if missing; make the tenant-detection gate production-safe by
default (disable `?tenant=` override unless explicitly development). No silent
wrong-resource defaults. Applies to 7.1–7.5. _Impl note:_ first confirm prod
actually sets `ENVIRONMENT=production` (Pulumi `cloud_run.py`) — the security
gate 7.4 depends on it.
---
## THEME 8 — Lower-risk cleanups (docs lie, opaque errors, auth layers)
| # | file:line | Class | What happens when it triggers |
|---|-----------|-------|-------------------------------|
| 8.1 | `backend/config.py:77-78` & `credit_evaluation_service.py` module/`grant_welcome_credits` docstrings | **C/doc** | Docstrings say "Fail-open: credits granted on error" but code is **fail-CLOSED** (`pending_review`, no grant) — the *safe* behaviour. The lie risks a future maintainer "fixing code to match docs" and re-introducing free-credit abuse. Fix the docs, confirm policy. |
| 8.2 | `youtube_download_service.py:11,37-38`; `lyrics_worker.py:566` | **doc** | Stale docstrings still describe the deleted yt-dlp fallback ("falls back to local yt_dlp"). Misleading post-incident. |
| 8.3 | `backend/workers/audio_worker.py:467-473`, `lyrics_worker.py:611-623` → `audio_worker.py:217-218` | **C** | Distinct download failure causes all collapse to `return None` → generic user-facing "Failed to download audio file" (the opaque message from the incident). Surface specific reasons to the user? |
| 8.4 | `backend/api/routes/users.py:734-762` (`create_checkout`) | **C** | Unauthenticated; email + referral-discount taken from request body. Anyone can compute a discount against an arbitrary email. Direct money risk low (webhook keys off session metadata). Intended pre-login flow? |
| 8.5 | `backend/services/auth_service.py:107-111` | **C** | OIDC verified with `audience=None` (audience check skipped); mitigated by strict `token_email == scheduler SA`. Acceptable or tighten to URL allowlist? |
| 8.6 | `backend/services/auth_service.py:81-90` | **C** | Empty `ADMIN_TOKENS` → warning only; all admin endpoints 403 (fails closed = safe, but looks like an auth bug not a config bug). Louder signal in prod? |
| 8.7 | `backend/services/email_validation_service.py:226` | **C** | Missing Firestore blocklist doc → `DEFAULT_DISPOSABLE_DOMAINS` (the Firestore `.get` itself is unwrapped, so hard failures propagate — good). Acceptable degradation? |
**DECISION (Theme 8):** Andrew — **"Fix docs + specific errors + admin-token
signal."** Correct the lying/stale docstrings (8.1 fail-open→fail-closed, 8.2
yt-dlp), surface specific download-failure reasons to the user instead of the
generic "Failed to download audio file" (8.3), and add a loud prod signal when
`ADMIN_TOKENS` is empty (8.6). Leave 8.4 (unauth checkout), 8.5 (OIDC
audience=None), 8.7 (blocklist default) as acceptable fail-safe.
---
## A — Legitimate graceful degradation confirmed (no change; listed for the record)
- `audio_transcoding_service.py:113-130,171-175` — review-audio transcode fail → serve original FLAC (logged).
- `backend/workers/audio_worker.py:207-211` — audio separation not configured → **raises** (good model).
- `youtube_download_service.py:118-126` — flacfetch unconfigured → **raises** (the post-incident fix).
- `audio_download_worker.py:341-342` — unsupported source → raises `DownloadError` (post-fix state of the incident).
- `video_worker.py:182-185` — `_encode_via_gce` re-raises on GCE failure (no silent local fallback).
- `local_encoding_service.py:241-264` — GPU→CPU encode, warned. Visible perf degradation.
- `stripe_service.py` (multiple) — unconfigured/invalid → fail closed + visible.
- `user_service.py:1003-1017` — `add_credits` idempotent via `PROCESSED_STRIPE_SESSIONS`.
- `job_manager.py:146-164` — credit-deduction failure deletes job + raises `InsufficientCreditsError`.
- `referral_service.py:283-305` — `record_earning` returns None only for invalid/expired referral; wrapped so it never blocks the buyer's credits.
- `catalog_proxy_service.py:71,103` — autocomplete `[]` on karaoke-decide outage (cosmetic).
- `credential_manager` distribution checks — distinct NOT_CONFIGURED/INVALID/ERROR/VALID, blocking 400 on create-from-url.
- `file_upload.py:1827-1833` (create-from-url) — re-raises, calls `fail_job`, 500 with real detail.
---
## Execution roadmap (Phase 4) — one PR per theme, with tests
Ordered safest/clearest → most delicate. Each PR updates `docs/LESSONS-LEARNED.md`
with the principle ("don't invent silent fallbacks — ask or fail loud") + the
notable example(s) it fixes.
| PR | Theme | Decision in one line | Risk |
|----|-------|----------------------|------|
| 1 | **T8** docs/errors | Fix lying fail-open docstrings + stale yt-dlp docstrings; surface specific download-failure reasons; loud prod signal on empty ADMIN_TOKENS | Low |
| 2 | **T1** sourcing | flacfetch sole downloader → fail loud (no silent YouTube downgrade) across 1.1–1.4 | Low/Med |
| 3 | **T4** render assets | Missing branded font/bg/duet-color → raise (match video.py:43-44) across 4.1–4.8 | Med |
| 4 | **T7** env config | Prod fail-fast on missing required vars; tenant gate production-safe by default | Med (verify Pulumi env first) |
| 5 | **T3** lyrics | Empty transcription = fail loud; same principle to whisper/corrections/reference | Med |
| 6 | **T2** worker triggers | Check every trigger result → fail/re-park; never silently stall (2.1–2.6) | High (job state machine) |
| 7 | **T5** pricing | Keep 1-credit default but always enforce 60-min ceiling + alert on undercharge/discount-guess | High (money) |
| 8 | **T6** paid orders | Re-raise + durable needs_manual_fulfilment record; reject missing artist/title | High (money/webhook) |
**Status:** Phases 1–3 complete (discover + triage + interview; all 8 decisions
captured above). Phase 4 (execute) — pending sequencing go-ahead from Andrew.
Loaded 100 of 231 files, more files were not shown because too many files have changed in this diff. Show more